diff --git a/environments/.gitignore b/environments/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..3bbe7b6f921890134bd22373cfdd89e91d5e788f
--- /dev/null
+++ b/environments/.gitignore
@@ -0,0 +1,3 @@
+__pycache__/
+*.pyc
+*.pyo
diff --git a/environments/LICENSE b/environments/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..9cd205d2a58c0326a490e1151baef4a6e87b2d6d
--- /dev/null
+++ b/environments/LICENSE
@@ -0,0 +1,30 @@
+GameDojo Non-Commercial Research License 1.0
+
+Copyright (c) 2026 the GameDojo authors
+
+The GameDojo authors grant permission to use, reproduce, modify, and share
+original GameDojo environment code and the accompanying configuration,
+documentation, and training and evaluation code in this directory solely for
+non-commercial scientific research, including reproduction of research results.
+
+Non-commercial scientific research is work whose primary purpose is scientific
+inquiry and whose use of these materials is neither primarily directed toward
+commercial advantage nor intended for monetary compensation. Commercial use
+requires separate written permission from the applicable rights holders.
+
+Copies and substantial portions of the covered materials, including modified
+copies, must retain this copyright notice and license. Modified copies must
+identify their changes and may be shared only under these terms.
+
+All copyrights, trademarks, and other intellectual property rights in the
+original games, including their titles, characters, artwork, and audio, remain
+exclusively with their respective original game companies and rights holders.
+GameDojo has no affiliation, endorsement, or sponsorship from those parties.
+This license grants no rights in third-party material. Separately licensed
+components remain subject to their own terms. See THIRD_PARTY_NOTICES.md.
+
+THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+PURPOSE, AND NON-INFRINGEMENT. TO THE EXTENT PERMITTED BY LAW, THE AUTHORS ARE
+NOT LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY ARISING FROM THE MATERIALS
+OR THEIR USE.
diff --git a/environments/README.md b/environments/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..519544f8450764d7e01f9a6c8eb452245cd07894
--- /dev/null
+++ b/environments/README.md
@@ -0,0 +1,43 @@
+# GameDojo environments
+
+GameDojo contains 120 boss encounters across 20 games. The environment package provides browser play, Gymnasium interfaces, scripted reference controllers, and a model evaluation harness.
+
+## Setup
+
+From this directory, install Python 3.12 dependencies and a Chromium browser for RGB observations. Install Node.js and put `node` on `PATH` to use the symbolic back end for the shared web games. Minecraft RGB observations require a working OpenGL context through ModernGL.
+
+```sh
+python -m pip install -r requirements-games.txt
+python -m playwright install chromium
+```
+
+## Play in a browser
+
+Serve the game launcher at `http://127.0.0.1:8766/`.
+
+```sh
+python -m http.server 8766 --bind 127.0.0.1 --directory games/web
+```
+
+Start the Minecraft play server in another terminal. Its page is available directly at `http://127.0.0.1:8765/`.
+
+```sh
+python games/prototype/bossbench/play_server.py
+```
+
+## Train and evaluate
+
+Set `PYTHONPATH=games/prototype` when importing `bossbench`. The `BENCH_CASES` registry in `bossbench.scope` lists the official encounters. Use `bossbench.make_policy_env` for 200 ms keyboard and mouse actions, `bossbench.make_compact_env` for discrete semantic actions, and `bossbench.make_training_env` for the step-damage reward wrapper.
+
+```sh
+python check_games.py --game terraria_remake --out terraria-check.json
+python run_model.py --case doom/cyberdemon --tier normal --policy noop --max-steps 1
+```
+
+`run_model.py` accepts `--format lumine` for CUA or `--format semantic` for semantic actions, and `--time paused` or `--time realtime`. For model evaluation, use `--policy chat` and set `--base-url` and `--model` to your OpenAI-compatible endpoint and model. Run `python run_model.py --help` for the available options.
+
+## Copyright and license
+
+All copyrights, trademarks, and other intellectual property rights in the original games, including their titles, characters, artwork, and audio, remain exclusively with their respective original game companies and rights holders.
+
+Original GameDojo materials in this directory are available for non-commercial scientific research under the [GameDojo Non-Commercial Research License](LICENSE). See the [third-party notices](THIRD_PARTY_NOTICES.md) and the [project copyright and use statement](https://gamedojo-benchmark.github.io/).
diff --git a/environments/THIRD_PARTY_NOTICES.md b/environments/THIRD_PARTY_NOTICES.md
new file mode 100644
index 0000000000000000000000000000000000000000..992e2941524a68ec8d56896acbabb670f0b8700d
--- /dev/null
+++ b/environments/THIRD_PARTY_NOTICES.md
@@ -0,0 +1,8 @@
+# Third-party notices
+
+- Three.js r160 is bundled as `games/web/games/_boss3d/vendor/three.min.js`. Copyright © 2010–2023 Three.js authors. The [MIT license](games/web/games/_boss3d/vendor/LICENSE) applies to that component.
+- All copyrights, trademarks, and other intellectual property rights in the original games, including their titles, characters, artwork, and audio, remain exclusively with their respective original game companies and rights holders. The GameDojo license grants rights in original GameDojo material only.
+- Quake II’s deterministic trigonometry in `q2core.js` adapts [fdlibm](https://www.netlib.org/fdlibm/). Copyright © 1993 Sun Microsystems, Inc. See the [fdlibm permission notice](games/web/games/quake2_remake/LICENSE.fdlibm).
+- The Battle City environment includes stage layouts and spawn order transcribed from the reference game via an [annotated disassembly](https://github.com/cyneprepou4uk/NES-Games-Disassembly/blob/6c145873e0f344ac4f132f451ac2dc7ea95cea6b/Battle%20City/bank_FF.asm) and the [vgrichina/battlecity reference implementation](https://github.com/vgrichina/battlecity). The Mega Man environment includes weapon and boss tables transcribed via an [annotated disassembly](https://github.com/plasticsmoke/megaman1-disassembly-ca65/tree/2771fb3). The GameDojo license does not grant rights in the original games or their data.
+- The Kirby encounters reference the [Kirby's Dream Land disassembly](https://github.com/ElectroDeoxys/kirbydreamland/tree/dba74416a66e4641204073276c0330f07b30cf12) and WiKirby. The source-game graphics and audio are excluded from the package.
+- Upstream references for Need for Speed: Most Wanted, Hexen II, Quake II, and Tomb Raider are recorded in their game manifests.
diff --git a/environments/check_games.py b/environments/check_games.py
new file mode 100644
index 0000000000000000000000000000000000000000..0a0a3046f57c367acf7135c9e418edbefd8c103b
--- /dev/null
+++ b/environments/check_games.py
@@ -0,0 +1,44 @@
+"""Run from the delivered package in a clean Python environment. No model calls."""
+import argparse, hashlib, json, os, sys, time, traceback
+from pathlib import Path
+
+parser = argparse.ArgumentParser()
+parser.add_argument('--game', required=True)
+parser.add_argument('--out', required=True)
+args = parser.parse_args()
+ROOT = Path(__file__).resolve().parent
+sys.path.insert(0, str(ROOT / 'games/prototype'))
+import bossbench
+from bossbench.scope import BENCH_CASES
+from bossbench_llm import lumine, prompting
+cases = sorted(k for k,v in BENCH_CASES.items() if v['game']==args.game)
+report = {'game':args.game,'python':sys.version,'checks':[], 'started':time.time(), 'test':'reset + RGB + one valid 200ms action; not a win/performance evaluation'}
+for case in cases:
+ for tier in ('easy','normal','hard'):
+ env = None
+ start = time.time()
+ try:
+ env = bossbench.make_policy_env(case)
+ obs, info = env.reset(seed=1, options={'tier':tier})
+ assert obs.shape == (480,854,3), obs.shape
+ assert str(obs.dtype) == 'uint8', obs.dtype
+ kind = prompting.mouse_kind(args.game)
+ action = lumine.from_packet(bossbench.NOOP, mouse_kind=kind)
+ parsed = lumine.parse('\n\n\n\n'+action, mouse_kind=kind)
+ assert parsed.ok, parsed
+ nxt, reward, terminated, truncated, step_info = env.step(parsed.packet)
+ assert nxt.shape == (480,854,3)
+ assert prompting.system_prompt(args.game, case, 'lumine', 'en')
+ report['checks'].append({'case':case,'tier':tier,'passed':True,'rgb_sha256':hashlib.sha256(obs.tobytes()).hexdigest(),'reward':float(reward),'seconds':time.time()-start})
+ except Exception:
+ report['checks'].append({'case':case,'tier':tier,'passed':False,'error':traceback.format_exc(),'seconds':time.time()-start})
+ finally:
+ if env is not None:
+ try: env.close()
+ except Exception: pass
+ Path(args.out).write_text(json.dumps(report,indent=2),encoding='utf-8')
+report['passed'] = len(report['checks']) == 18 and all(c['passed'] for c in report['checks'])
+report['finished'] = time.time()
+Path(args.out).write_text(json.dumps(report,indent=2),encoding='utf-8')
+print(json.dumps({'game':args.game,'passed':report['passed'],'checks':len(report['checks'])}), flush=True)
+sys.exit(0 if report['passed'] else 1)
diff --git a/environments/games/prototype/bossbench/__init__.py b/environments/games/prototype/bossbench/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..147d193bf0321f29c46b6909a1c225f88731ac8c
--- /dev/null
+++ b/environments/games/prototype/bossbench/__init__.py
@@ -0,0 +1,127 @@
+"""BossBench: every case behind one Gymnasium interface (unified.py), whatever engine runs it.
+
+ import bossbench
+ bossbench.ENVS # {"2d/needle_warden": "web", "3d/minecraft_wither": "py", ...}
+ env = bossbench.make("2d/needle_warden", obs_mode="symbolic", time_mode="virtual_rt", latency=0.3)
+ obs, info = env.reset(seed=0, options={"difficulty": 0.5})
+ obs, r, term, trunc, info = env.step("<|action_start|> 0 0 0 ; D ; D ; D,Space ; D ; J ; J <|action_end|>")
+ env.verifier() # {reward in [-1,1], win, outcome, boss_damage, ...}
+ gymnasium.make("BossBench/2d-needle_warden-v0") # same env through the gymnasium registry
+
+Engines: "web" = web/engine + one folder per game under web/games/ (JavaScript, 60 Hz; HK-style 2D cases),
+"py" = this package (Minecraft). WEB_GAME maps each web case id to its game folder.
+Those engines run at 60 Hz. Independent backends declare their own native clocks.
+
+The retired Python tank demo and its aliases are no longer registered.
+"""
+import os
+import re
+
+from . import mc4d
+from .core import FPS, RES, Arena, Body, Boss, BossBenchEnv, Case, Knobs
+from .keymouse import NOOP, format_packet, parse_packet
+from .unified import PyCaseEnv, UnifiedEnv
+
+PY_CASES = {f"3d/minecraft_{m}": (mc4d.make, {"mob": m}) for m in mc4d.MOBS}
+
+
+def _web_cases():
+ """{case id: game folder} for every BB.CASES['...'] = registration under web/games//, found without
+ starting Node. Folders starting with "_" (the template) or without an index.html, and tests/ shots/, are skipped."""
+ games = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "web", "games")
+ out = {}
+ for game in sorted(os.listdir(games)) if os.path.isdir(games) else []:
+ if game.startswith(("_", ".")) or not os.path.isfile(os.path.join(games, game, "index.html")):
+ continue
+ for d, sub, files in os.walk(os.path.join(games, game)):
+ sub[:] = [s for s in sub if s not in ("tests", "shots")]
+ for f in files:
+ if f.endswith(".js"):
+ src = open(os.path.join(d, f), encoding="utf-8").read()
+ for i in re.findall(r"BB\.CASES\['([^']+)'\]\s*=", src):
+ if out.setdefault(i, game) != game:
+ raise RuntimeError(f"web case {i!r} registered by two games: {out[i]}, {game}")
+ return out
+
+
+WEB_GAME = _web_cases()
+WEB_CASES = sorted(WEB_GAME)
+ENVS = {**{i: "web" for i in WEB_CASES}, **{i: "py" for i in PY_CASES}}
+ENGINE_BACKENDS = {}
+
+
+def register_backend(case_id, factory):
+ """Explicitly register an independent GameBackend factory; this does not enroll it in training.
+
+ Call in the integration module on each process, including spawned workers.
+ Each factory call must create an independent backend and own its resources.
+ """
+ if not isinstance(case_id, str) or not re.fullmatch(r'[a-z0-9_]+/[a-z0-9_]+', case_id):
+ raise ValueError('case_id must be namespace/name using lowercase letters, digits or underscores')
+ if case_id in ENVS:
+ raise ValueError(f'case already registered: {case_id}')
+ if case_id in ('2d/tank_battle', 'tank_battle_1v1'):
+ raise ValueError('retired case cannot be registered again')
+ if not callable(factory):
+ raise TypeError('backend factory must be callable')
+ import gymnasium as gym
+ gym.register(gym_id(case_id), entry_point=make, kwargs={'name': case_id})
+ ENGINE_BACKENDS[case_id] = factory
+ ENVS[case_id] = 'native'
+
+
+def make(name, **kw):
+ """Unified env for any id in ENVS; kw: obs_mode, time_mode, latency, difficulty, reward_mode, action_mode,
+ (web) transport, (py) case_kw for the case constructor (e.g. {"camera": "first"})."""
+ if name in ENGINE_BACKENDS:
+ from .engine_env import EngineEnv
+ backend_options = dict(kw.pop('backend_options', {}) or {})
+ backend = ENGINE_BACKENDS[name](**backend_options)
+ return EngineEnv(name, backend, **kw)
+ if name in PY_CASES:
+ factory, fixed = PY_CASES[name]
+ extra = dict(kw.pop("case_kw", {}) or {})
+ if any(key in extra and extra[key] != value for key, value in fixed.items()):
+ raise ValueError(f"case_kw cannot override the registered case identity: {fixed}")
+ case_kw = {**extra, **fixed}
+ return PyCaseEnv(name, lambda **k: factory(**case_kw, **k), **kw)
+ if name in WEB_CASES:
+ from .webenv import WebCaseEnv
+ return WebCaseEnv(name, **kw)
+ raise KeyError(f"unknown case {name!r}; known: {sorted(ENVS)}")
+
+
+def gym_id(name):
+ return "BossBench/" + name.replace("/", "-") + "-v0"
+
+
+from .policy_env import PolicyEnv, make_policy_env, policy_gym_id
+
+
+try: # gymnasium.make("BossBench/2d-needle_warden-v0")
+ import gymnasium as gym
+ for _n in ENVS:
+ gym.register(gym_id(_n), entry_point=make, kwargs={"name": _n})
+ from .scope import FORMAL_CASES, PUBLIC_WEB_CASES
+ for _n in (*FORMAL_CASES, *PUBLIC_WEB_CASES):
+ gym.register(policy_gym_id(_n), entry_point=make_policy_env, kwargs={"case_id": _n})
+except Exception:
+ pass
+
+from .native_games import NATIVE_CASES, backend_factory
+for _n in NATIVE_CASES:
+ register_backend(_n, backend_factory(_n))
+ gym.register(policy_gym_id(_n), entry_point=make_policy_env, kwargs={'case_id': _n})
+
+# 2026-11-10: compact discrete action spaces (bossbench/compact-actions@1, compact.py). Registered for every public
+# case whose game ships web/games//compact_actions.json; the raw key/mouse contract above is unchanged.
+from . import compact
+from .compact import make_compact_env, compact_gym_id
+from .step_reward import StepDamageReward, make_training_env
+try:
+ from .scope import POLICY_CASES as _PC
+ for _n, _v in _PC.items():
+ if compact.declaration_path(_v['game']).is_file():
+ gym.register(compact_gym_id(_n), entry_point=make_compact_env, kwargs={'case_id': _n})
+except Exception:
+ pass
diff --git a/environments/games/prototype/bossbench/compact.py b/environments/games/prototype/bossbench/compact.py
new file mode 100644
index 0000000000000000000000000000000000000000..8086e601af03a2e1003d92b93a95977912594361
--- /dev/null
+++ b/environments/games/prototype/bossbench/compact.py
@@ -0,0 +1,315 @@
+"""Compact discrete action spaces for the public BossBench env: bossbench/compact-actions@1.
+
+Most games use fewer than 1,000 action combinations. Terraria has a separate action space.
+A game declares a few independent heads (move, turn, attack, ...), each a short list of options. One action
+picks one option per head and is held for one 200 ms packet, which is the ViZDoom frame-skip analogue. The
+action count is the product of the head sizes and must be below 1000.
+
+Nothing underneath changes. An action is translated into an ordinary key/mouse packet before env.step, so the
+simulation, the recordings, the verifier and the raw packet contract (bossbench/policy-gym@2) are all untouched.
+
+Declaration: web/games//compact_actions.json
+
+ {"schema": "bossbench/compact-actions@1", "game": "doom_remake", "version": "doom-compact@1",
+ "heads": [
+ {"name": "move", "zh": "movement", "options": [
+ {"label": "none"}, {"label": "forward", "zh": "forward", "keys": ["W", "Shift"]}, ...]},
+ {"name": "turn", "zh": "turn", "options": [
+ {"label": "none"}, {"label": "left_10", "zh": "turn left 10 degrees", "dx": -60}, ...]}]}
+
+Option fields: label (required, [a-z0-9_]+, unique within its head); zh; note; and at most one of
+ keys: [...] held in all six sub-steps
+ tap: [...] held in the first sub-step only, so the key is pressed afresh every packet
+ subs: [[...] x 6] an explicit per-sub-step pattern (motion inputs, combos)
+plus optional relative mouse counts dx, dy, dz for the packet.
+
+Rules:
+- Option 0 of every head is neutral (no keys, no mouse), so action [0, 0, ...] is the no-op packet.
+- Heads never share a key or a mouse axis.
+- Every combination must be a legal packet (at most 4 keys per sub-step).
+"""
+from __future__ import annotations
+
+from collections.abc import Mapping
+import itertools
+import json
+import math
+from pathlib import Path
+import re
+
+import gymnasium as gym
+import numpy as np
+
+from . import keymouse as km
+
+SCHEMA = 'bossbench/compact-actions@1'
+CONTRACT = 'bossbench/policy-compact@1'
+MAX_ACTIONS = 1000
+EXEMPT_GAMES = frozenset({'terraria_remake'})
+ROOT = Path(__file__).resolve().parents[2]
+_FOLDER = {'minecraft': 'minecraft_remake'}
+_LABEL = re.compile(r'[a-z0-9_]+\Z')
+_HEAD = re.compile(r'[a-z][a-z0-9_]*\Z')
+_AXES = ('dx', 'dy', 'dz')
+_LIMIT = (1000, 1000, 5)
+_FIELDS = {'label', 'zh', 'note', 'keys', 'tap', 'subs', 'dx', 'dy', 'dz'}
+INVALID = 'invalid compact action' # executed as a malformed packet: no-op, counted in format_errors
+
+
+def declaration_path(game):
+ return ROOT / 'web' / 'games' / _FOLDER.get(game, game) / 'compact_actions.json'
+
+
+def _keyset(value, where):
+ if not isinstance(value, list) or any(not isinstance(k, str) for k in value):
+ raise ValueError(f'{where}: keys must be a list of key names')
+ if len(set(value)) != len(value):
+ raise ValueError(f'{where}: duplicate key')
+ bad = [k for k in value if k not in km.KEYS]
+ if bad:
+ raise ValueError(f'{where}: unknown key(s) {bad}; allowed {list(km.KEYS)}')
+ if len(value) > km.MAX_KEYS:
+ raise ValueError(f'{where}: more than {km.MAX_KEYS} keys in one sub-step')
+ return frozenset(value)
+
+
+class CompactSpec:
+ """A validated compact action declaration. Indices are per head; flat indices are mixed-radix, first head
+ most significant, so flat 0 is the no-op."""
+
+ def __init__(self, data, where='declaration'):
+ if not isinstance(data, dict) or data.get('schema') != SCHEMA:
+ raise ValueError(f'{where}: schema must be {SCHEMA!r}')
+ self.where, self.game, self.version = where, data.get('game'), data.get('version')
+ if not isinstance(self.game, str) or not isinstance(self.version, str) or not self.version:
+ raise ValueError(f'{where}: game and version must be non-empty strings')
+ heads = data.get('heads')
+ if not isinstance(heads, list) or not heads:
+ raise ValueError(f'{where}: heads must be a non-empty list')
+ self.raw, self.heads, keys_owner, axes_owner = data, [], {}, {}
+ for h in heads:
+ name = h.get('name') if isinstance(h, dict) else None
+ if not isinstance(name, str) or not _HEAD.match(name) or any(x['name'] == name for x in self.heads):
+ raise ValueError(f'{where}: head names must match [a-z][a-z0-9_]* and be unique: {name!r}')
+ opts = h.get('options')
+ if not isinstance(opts, list) or len(opts) < 2:
+ raise ValueError(f'{where}: head {name!r} needs at least two options')
+ parsed, labels = [], set()
+ for i, o in enumerate(opts):
+ at = f'{where}: {name}[{i}]'
+ if not isinstance(o, dict) or set(o) - _FIELDS:
+ raise ValueError(f'{at}: unknown fields {sorted(set(o) - _FIELDS) if isinstance(o, dict) else o}')
+ label = o.get('label')
+ if not isinstance(label, str) or not _LABEL.match(label) or label in labels:
+ raise ValueError(f'{at}: label must match [a-z0-9_]+ and be unique in the head: {label!r}')
+ labels.add(label)
+ kinds = [k for k in ('keys', 'tap', 'subs') if k in o]
+ if len(kinds) > 1:
+ raise ValueError(f'{at}: use only one of keys / tap / subs')
+ subs = [frozenset()] * km.SUBSTEPS
+ if 'keys' in o:
+ subs = [_keyset(o['keys'], at)] * km.SUBSTEPS
+ elif 'tap' in o:
+ subs = [_keyset(o['tap'], at)] + [frozenset()] * (km.SUBSTEPS - 1)
+ elif 'subs' in o:
+ if not isinstance(o['subs'], list) or len(o['subs']) != km.SUBSTEPS:
+ raise ValueError(f'{at}: subs must list {km.SUBSTEPS} sub-steps')
+ subs = [_keyset(s, f'{at} sub {j + 1}') for j, s in enumerate(o['subs'])]
+ mouse = []
+ for axis, limit in zip(_AXES, _LIMIT):
+ v = o.get(axis, 0)
+ if isinstance(v, bool) or not isinstance(v, int) or abs(v) > limit:
+ raise ValueError(f'{at}: {axis} must be an integer within +-{limit}')
+ mouse.append(v)
+ if i == 0 and (any(subs) or any(mouse)):
+ raise ValueError(f'{at}: option 0 must be neutral (no keys, no mouse)')
+ parsed.append({'label': label, 'zh': o.get('zh'), 'subs': tuple(subs), 'mouse': tuple(mouse)})
+ uni = frozenset().union(*(frozenset().union(*p['subs']) for p in parsed))
+ axes = frozenset(a for p in parsed for a, v in zip(range(3), p['mouse']) if v)
+ for k in uni:
+ if k in keys_owner:
+ raise ValueError(f'{where}: key {k} is used by heads {keys_owner[k]!r} and {name!r}')
+ keys_owner[k] = name
+ for a in axes:
+ if a in axes_owner:
+ raise ValueError(f'{where}: mouse {_AXES[a]} is used by heads {axes_owner[a]!r} and {name!r}')
+ axes_owner[a] = name
+ self.heads.append({'name': name, 'zh': h.get('zh'), 'options': parsed, 'keys': uni, 'axes': axes})
+ self.nvec = [len(h['options']) for h in self.heads]
+ self.size = math.prod(self.nvec)
+ if self.size >= MAX_ACTIONS and self.game not in EXEMPT_GAMES:
+ raise ValueError(f'{where}: {self.size} actions ({" x ".join(map(str, self.nvec))}), must be below {MAX_ACTIONS}')
+ bad = None
+ for idx in itertools.islice(itertools.product(*(range(n) for n in self.nvec)), 200000):
+ if km.parse_packet(self.compose(idx)) is None:
+ bad = idx
+ break
+ if bad is not None:
+ raise ValueError(f'{where}: action {self.named(bad)} is not a legal packet (more than 4 keys in a sub-step?)')
+
+ # ---- conversions
+ def compose(self, idx):
+ subs, mouse = [set() for _ in range(km.SUBSTEPS)], [0, 0, 0]
+ for head, i in zip(self.heads, idx):
+ option = head['options'][i]
+ for j in range(km.SUBSTEPS):
+ subs[j] |= option['subs'][j]
+ for a in range(3):
+ mouse[a] += option['mouse'][a]
+ return km.format_packet([sorted(s, key=km.KEYS.index) for s in subs], mouse)
+
+ def unflat(self, i):
+ if not 0 <= i < self.size:
+ raise ValueError(f'flat action {i} outside [0, {self.size})')
+ out = []
+ for n in reversed(self.nvec):
+ i, r = divmod(i, n)
+ out.append(r)
+ return tuple(reversed(out))
+
+ def flat(self, idx):
+ i = 0
+ for n, v in zip(self.nvec, idx):
+ i = i * n + v
+ return i
+
+ def named(self, idx):
+ return {h['name']: h['options'][i]['label'] for h, i in zip(self.heads, idx)}
+
+ def parse(self, action):
+ """Action -> per-head indices. Accepts None (no-op), a flat int, a sequence of per-head ints, a mapping
+ {head: label or index} (missing heads = option 0), or text "move=forward; turn=left_10" (same rule)."""
+ if action is None:
+ return (0,) * len(self.heads)
+ if isinstance(action, (bool, np.bool_)):
+ raise ValueError('a boolean is not an action')
+ if isinstance(action, (int, np.integer)):
+ return self.unflat(int(action))
+ if isinstance(action, str):
+ text = action.strip()
+ for mark in ('<|compact_start|>', '<|compact_end|>'):
+ text = text.replace(mark, '')
+ pairs = {}
+ for part in re.split(r'[;,\n]', text):
+ part = part.strip()
+ if not part:
+ continue
+ if '=' not in part and ':' not in part:
+ raise ValueError(f'expected head=label, got {part!r}')
+ head, _, label = part.replace(':', '=', 1).partition('=')
+ head, label = head.strip(), label.strip()
+ if head in pairs:
+ raise ValueError(f'head {head!r} given twice')
+ pairs[head] = label
+ return self.parse(pairs)
+ if isinstance(action, Mapping):
+ names = [h['name'] for h in self.heads]
+ unknown = set(action) - set(names)
+ if unknown:
+ raise ValueError(f'unknown head(s) {sorted(unknown)}; heads are {names}')
+ out = []
+ for h in self.heads:
+ v = action.get(h['name'], 0)
+ if isinstance(v, str):
+ labels = [o['label'] for o in h['options']]
+ if v not in labels:
+ raise ValueError(f'head {h["name"]!r} has no option {v!r}; options are {labels}')
+ out.append(labels.index(v))
+ elif isinstance(v, (int, np.integer)) and not isinstance(v, (bool, np.bool_)) and 0 <= v < len(h['options']):
+ out.append(int(v))
+ else:
+ raise ValueError(f'head {h["name"]!r}: bad value {v!r}')
+ return tuple(out)
+ arr = np.asarray(action)
+ if arr.ndim != 1 or arr.shape[0] != len(self.heads) or arr.dtype.kind not in 'iu':
+ raise ValueError(f'expected {len(self.heads)} integer head indices')
+ if any(not 0 <= int(v) < n for v, n in zip(arr, self.nvec)):
+ raise ValueError(f'head index out of range for {self.nvec}')
+ return tuple(int(v) for v in arr)
+
+ def project(self, packet):
+ """Nearest compact action to a packet (packet text or parse_packet() dict), head by head.
+
+ Key heads: Hamming distance over the 6 sub-steps x the head's own keys.
+ Mouse: |difference| / 100 per axis the head owns. Ties go to the lowest index, so neutral wins a tie and
+ option order matters: list the richer of two equally close options first (cuphead v3 lost jumps this way)."""
+ p = km.parse_packet(packet) if isinstance(packet, str) else packet
+ if p is None:
+ return (0,) * len(self.heads)
+ out = []
+ for h in self.heads:
+ best, best_d = 0, None
+ for i, o in enumerate(h['options']):
+ d = sum(len((p['subs'][j] & h['keys']) ^ o['subs'][j]) for j in range(km.SUBSTEPS))
+ d += sum(abs(p['mouse'][a] - o['mouse'][a]) / 100 for a in h['axes'])
+ if best_d is None or d < best_d - 1e-12:
+ best, best_d = i, d
+ out.append(best)
+ return tuple(out)
+
+ def table(self):
+ """What an agent's manual shows: every head and option with its meaning."""
+ heads = []
+ for h, raw in zip(self.heads, self.raw['heads']):
+ heads.append({'name': h['name'], 'zh': h['zh'], 'options': [
+ {'index': i, **{k: v for k, v in o.items() if k in ('label', 'zh', 'note', 'keys', 'tap', 'subs', 'dx', 'dy', 'dz')}}
+ for i, o in enumerate(raw['options'])]})
+ return {'schema': SCHEMA, 'contract': CONTRACT, 'game': self.game, 'version': self.version,
+ 'size': self.size, 'nvec': list(self.nvec), 'decision_seconds': km.PACKET_SECONDS,
+ 'text_form': 'head=label; head=label (missing heads = option 0)', 'heads': heads}
+
+
+def load(game=None, path=None):
+ p = Path(path) if path else declaration_path(game)
+ if not p.is_file():
+ raise FileNotFoundError(f'no compact action declaration for {game!r}: {p}')
+ spec = CompactSpec(json.loads(p.read_text(encoding='utf-8')), where=str(p))
+ if game and spec.game != game:
+ raise ValueError(f'{p}: declares game {spec.game!r}, expected {game!r}')
+ return spec
+
+
+class CompactActionEnv(gym.Wrapper):
+ """The public policy env with a small MultiDiscrete action space; each action becomes one ordinary packet."""
+
+ def __init__(self, env, spec):
+ super().__init__(env)
+ self.compact_spec = spec # not `spec`: gym.Wrapper.spec is the registry EnvSpec (read-only)
+ self.action_space = gym.spaces.MultiDiscrete(spec.nvec)
+ self.metadata = {**env.metadata, 'action_contract': CONTRACT, 'compact_version': spec.version,
+ 'compact_size': spec.size}
+
+ def manual(self):
+ manual = self.env.manual()
+ manual['compact_actions'] = self.compact_spec.table()
+ return manual
+
+ def reset(self, *, seed=None, options=None):
+ obs, info = self.env.reset(seed=seed, options=options)
+ if 'manual' in info:
+ info = {**info, 'manual': self.manual()}
+ return obs, info
+
+ def step(self, action, latency=None):
+ try:
+ idx = self.compact_spec.parse(action)
+ packet = self.compact_spec.compose(idx)
+ except (ValueError, TypeError, OverflowError):
+ idx, packet = None, INVALID
+ obs, reward, terminated, truncated, info = self.env.step(packet, latency=latency)
+ info = {**info, 'compact_action': None if idx is None else self.compact_spec.named(idx)}
+ return obs, reward, terminated, truncated, info
+
+
+def make_compact_env(case_id, decl_path=None, **kwargs):
+ """make_policy_env(case_id) with the game's compact action space (MultiDiscrete, fewer than 1000 actions)."""
+ from .policy_env import make_policy_env
+ from .scope import POLICY_CASES
+ if case_id not in POLICY_CASES:
+ raise ValueError(f'case is not registered for the public policy interface: {case_id!r}')
+ spec = load(POLICY_CASES[case_id]['game'], decl_path)
+ return CompactActionEnv(make_policy_env(case_id, **kwargs), spec)
+
+
+def compact_gym_id(case_id):
+ return 'BossBenchCompact/' + case_id.replace('/', '-') + '-v0'
diff --git a/environments/games/prototype/bossbench/core.py b/environments/games/prototype/bossbench/core.py
new file mode 100644
index 0000000000000000000000000000000000000000..a7d19933524b5ef728c63fd2ff1abdc7084ab52b
--- /dev/null
+++ b/environments/games/prototype/bossbench/core.py
@@ -0,0 +1,252 @@
+"""BossBench core.
+
+A Case is the composition Arena (environment) + Body (embodiment) + Boss.
+Every component declares a difficulty TABLE; one scalar d in [0, 1] sets all knobs.
+BossBenchEnv wraps a Case as a Gymnasium env with three time modes.
+"""
+from __future__ import annotations
+
+import math
+from collections.abc import Mapping
+from numbers import Integral, Real
+import os
+import time
+
+import gymnasium as gym
+import numpy as np
+
+# fixed simulation tick: 60 Hz = 2 ticks per 33 ms sub-step of the 200 ms packet, as the web engine
+# (proposal 4.4). Rules are written per second (or per vanilla 20 Hz Minecraft tick, converted in mc4d), so the
+# game plays the same at any rate >= 30; BOSSBENCH_FPS overrides it for equivalence checks only.
+FPS = int(os.environ.get("BOSSBENCH_FPS", 60))
+RES = (854, 480) # every case and every renderer outputs 480p, 16:9 (W, H)
+
+
+class Knobs:
+ """d in [0,1] -> named parameters. A row is (easy, hard) or (easy, normal, hard)."""
+
+ def __init__(self, table: dict, d: float):
+ self._names = list(table)
+ d = float(np.clip(d, 0.0, 1.0))
+ for name, row in table.items():
+ setattr(self, name, float(np.interp(d, np.linspace(0, 1, len(row)), row)))
+
+ def as_dict(self) -> dict:
+ return {n: round(getattr(self, n), 4) for n in self._names}
+
+
+class Component:
+ TABLE: dict = {}
+
+ def reset(self, case: "Case") -> None:
+ self.k = Knobs(self.TABLE, case.d)
+
+ def update(self, case: "Case") -> None:
+ pass
+
+
+class Arena(Component):
+ """Static geometry + transient entities (projectiles, hazards)."""
+
+
+class Body(Component):
+ """The agent's embodiment: action space, kinematics, health."""
+ action_space: gym.Space
+ max_hp = 1.0
+
+ def noop(self):
+ raise NotImplementedError
+
+ def parse(self, text: str):
+ """'up+fire' -> action; lets LLM agents act with words."""
+ raise NotImplementedError
+
+ def apply(self, case: "Case", action) -> None:
+ raise NotImplementedError
+
+ # key/mouse packets (keymouse.py): what each key means is up to the body (proposal 4.3)
+ manual: tuple = ()
+
+ def keys(self, case: "Case", held: frozenset, pressed: frozenset, mouse: tuple):
+ """Keys held this tick (+ those newly pressed, + this tick's share of the mouse motion) -> native action."""
+ raise NotImplementedError
+
+
+class Boss(Component):
+ """Opponent: a state machine over MOVES (Boss-Spec DSL subset)."""
+ MOVES: dict = {}
+ SKILLS: tuple = ()
+ max_hp = 1.0
+
+
+class Case:
+ """Arena + Body + Boss, stepped at FPS. Subclasses add observe/state/render."""
+ name = "case"
+ max_seconds = 120.0
+ obs_dim = 0
+
+ def __init__(self, arena: Arena, body: Body, boss: Boss):
+ self.arena, self.body, self.boss = arena, body, boss
+ self.observation_space = gym.spaces.Box(-np.inf, np.inf, (self.obs_dim,), np.float32)
+
+ def reset(self, seed: int, d: float) -> None:
+ self.rng = np.random.default_rng(seed)
+ self.d, self.t, self.events = float(d), 0, []
+ for c in (self.arena, self.body, self.boss):
+ c.reset(self)
+
+ def tick(self, action) -> None:
+ self.body.apply(self, action)
+ self.boss.update(self)
+ self.arena.update(self)
+ self.interact()
+ self.t += 1
+
+ def interact(self) -> None:
+ """Case-specific body/boss contact rules."""
+
+ def outcome(self):
+ if self.boss.hp <= 0:
+ return "win"
+ if self.body.hp <= 0:
+ return "loss"
+ return None
+
+ def describe(self) -> dict:
+ """Difficulty knobs + boss spec: what an LLM generator/verifier sees."""
+ return {"case": self.name, "d": self.d,
+ "knobs": {type(c).__name__: c.k.as_dict() for c in (self.arena, self.body, self.boss)},
+ "moves": self.boss.MOVES, "skills_tested": self.boss.SKILLS}
+
+ def observe(self) -> np.ndarray:
+ raise NotImplementedError
+
+ def state(self) -> dict:
+ raise NotImplementedError
+
+ def render(self) -> np.ndarray:
+ raise NotImplementedError
+
+
+class BossBenchEnv(gym.Env):
+ """Gymnasium wrapper.
+
+ time_mode:
+ paused - the world waits for the agent (turn-based upper bound)
+ virtual - before each action the world runs ceil(latency*FPS) no-op ticks
+ (set env.latency per step to the agent's measured think time)
+ realtime - same, but the lag is measured on the wall clock between steps
+ reward: terminal win=+1, loss/timeout=-1+boss_damage_fraction (+ optional dense shaping)
+ """
+ metadata = {"render_modes": ["rgb_array"], "render_fps": FPS}
+
+ def __init__(self, case: Case, difficulty=0.5, time_mode="paused", latency=0.0,
+ frame_skip=1, reward_mode="sparse", render_mode=None, max_seconds=None):
+ assert time_mode in ("paused", "virtual", "realtime")
+ self.case, self.difficulty, self.time_mode, self.latency = case, difficulty, time_mode, latency
+ self.frame_skip, self.reward_mode, self.render_mode = frame_skip, reward_mode, render_mode
+ seconds = case.max_seconds if max_seconds is None else max_seconds
+ if (isinstance(seconds, (bool, np.bool_)) or not isinstance(seconds, Real) or
+ not math.isfinite(seconds) or not math.isfinite(seconds * FPS) or seconds < 1 / FPS):
+ raise ValueError("max_seconds must be finite and allow at least one simulation tick")
+ self.max_ticks = int(seconds * FPS)
+ self.action_space = case.body.action_space
+ self.observation_space = case.observation_space
+ self.renderer = None # None -> case.render(); or a callable(env) -> frame (e.g. skin.GodotRenderer)
+ self.episode = 0
+ self._closed = False
+ self._has_reset, self._done = False, True
+
+ # -- gym API ---------------------------------------------------------
+ def reset(self, *, seed=None, options=None):
+ self._ensure_open()
+ if options is not None and not isinstance(options, Mapping):
+ raise ValueError("reset options must be a mapping")
+ d = (options or {}).get("difficulty", self.difficulty)
+ if isinstance(d, (bool, np.bool_)) or not isinstance(d, Real) or not math.isfinite(d) or not 0 <= d <= 1:
+ raise ValueError("difficulty must be a finite number in [0, 1]")
+ if seed is not None:
+ if isinstance(seed, (bool, np.bool_)) or not isinstance(seed, Integral) or seed < 0:
+ raise ValueError("seed must be a nonnegative integer or None")
+ seed = int(seed)
+ super().reset(seed=seed)
+ self.case.reset(int(self.np_random.integers(2**31 - 1)), d)
+ self._has_reset, self._done = True, False
+ self.episode += 1
+ self._prev = self._progress()
+ self._lag_ticks = 0
+ self._t_return = time.perf_counter()
+ return self.case.observe(), self._info()
+
+ def step(self, action):
+ self._ensure_reset()
+ if self._done:
+ raise RuntimeError("episode is over; call reset()")
+ c = self.case
+ if isinstance(action, str):
+ action = c.body.parse(action)
+ c.events.clear()
+ self._lag_ticks = self._lag()
+ for a in [c.body.noop()] * self._lag_ticks + [action] * self.frame_skip:
+ c.tick(a)
+ if c.outcome() or c.t >= self.max_ticks:
+ break
+ terminated = c.outcome() is not None
+ truncated = not terminated and c.t >= self.max_ticks
+ prog, reward = self._progress(), 0.0
+ if self.reward_mode == "dense":
+ reward += (prog[0] - self._prev[0]) - (prog[1] - self._prev[1])
+ self._prev = prog
+ if terminated or truncated:
+ reward += self.verifier()["reward"]
+ self._done = True
+ obs, info = c.observe(), self._info()
+ self._t_return = time.perf_counter()
+ return obs, float(reward), terminated, truncated, info
+
+ def render(self):
+ self._ensure_reset()
+ img = self.renderer(self) if self.renderer else self.case.render()
+ assert img.shape == (RES[1], RES[0], 3), f"render must be 480p {RES}, got {img.shape}"
+ return img
+
+ def close(self):
+ if not self._closed:
+ try:
+ close = getattr(self.case, "close", None)
+ if close is not None:
+ close()
+ finally:
+ self._closed = True
+
+ def _ensure_open(self):
+ if self._closed:
+ raise RuntimeError("environment is closed; create a new environment")
+
+ def _ensure_reset(self):
+ self._ensure_open()
+ if not self._has_reset:
+ raise RuntimeError("environment has not been reset; call reset()")
+
+ # -- BossBench extras ----------------------------------------------------
+ def verifier(self) -> dict:
+ self._ensure_reset()
+ boss_frac, _ = self._progress()
+ win = self.case.outcome() == "win"
+ return {"reward": 1.0 if win else -1.0 + boss_frac, "win": win,
+ "boss_damage": round(boss_frac, 4), "seconds": self.case.t / FPS, "d": self.case.d}
+
+ def _progress(self):
+ b, p = self.case.boss, self.case.body
+ return (1 - max(b.hp, 0) / b.max_hp, 1 - max(p.hp, 0) / p.max_hp)
+
+ def _lag(self) -> int:
+ if self.time_mode == "virtual":
+ return math.ceil(self.latency * FPS - 1e-9)
+ if self.time_mode == "realtime":
+ return int((time.perf_counter() - self._t_return) * FPS)
+ return 0
+
+ def _info(self) -> dict:
+ return {"t": self.case.t / FPS, "state": self.case.state(), "events": list(self.case.events),
+ "lag_ticks": self._lag_ticks, "difficulty": self.case.d}
diff --git a/environments/games/prototype/bossbench/engine_contract.py b/environments/games/prototype/bossbench/engine_contract.py
new file mode 100644
index 0000000000000000000000000000000000000000..316f134d1b6728964bda7544b1c6456cce571922
--- /dev/null
+++ b/environments/games/prototype/bossbench/engine_contract.py
@@ -0,0 +1,130 @@
+"""External engine boundary. No Arena/Body/Boss/Case or renderer library required."""
+from __future__ import annotations
+
+from dataclasses import dataclass
+import math
+from typing import Protocol
+
+import numpy as np
+
+API_VERSION = 'bossbench/engine@1'
+
+
+@dataclass(frozen=True)
+class EngineSpec:
+ engine_id: str
+ dimension: str
+ native_hz: int
+ max_seconds: float
+ renderer: str
+ render_kind: str # raster | perspective
+ rule_version: str = '1'
+ resolution: tuple[int, int] = (854, 480)
+
+ def __post_init__(self):
+ if self.dimension not in ('2d', '3d') or self.render_kind not in ('raster', 'perspective'):
+ raise ValueError('invalid engine dimension or render_kind')
+ if isinstance(self.native_hz, bool) or not isinstance(self.native_hz, int) or not 5 <= self.native_hz <= 1000:
+ raise ValueError('native_hz must be an integer in [5, 1000]')
+ if not math.isfinite(self.max_seconds) or self.max_seconds <= 0:
+ raise ValueError('max_seconds must be positive and finite')
+ if not self.engine_id or not self.renderer or not self.rule_version:
+ raise ValueError('engine identity, renderer and rules must be declared')
+ if len(self.resolution) != 2 or any(type(v) is not int or v <= 0 for v in self.resolution):
+ raise ValueError('resolution must contain positive integer width/height')
+
+
+@dataclass(frozen=True)
+class RenderStatus:
+ renderer: str
+ kind: str
+ ready: bool
+ error: str | None = None
+
+
+@dataclass(frozen=True)
+class InputPacket:
+ """200ms of input; six equally spaced held-key samples and total relative mouse delta."""
+ mouse: tuple[float, float, float]
+ holds: tuple[frozenset[str], ...]
+
+ @classmethod
+ def noop(cls):
+ return cls((0, 0, 0), (frozenset(),) * 6)
+
+
+@dataclass(frozen=True)
+class TickInput:
+ held: frozenset[str]
+ pressed: frozenset[str]
+ mouse: tuple[float, float, float]
+
+
+class NativeClock:
+ """Optional integer scheduler: sample holds at each native tick, without clock drift.
+
+ The right endpoint belongs to the preceding input interval. Thus 35Hz uses
+ 7 ticks per packet while 24Hz alternates 4/5, executing exactly 24 per second.
+ Engines with their own native input queue may implement this boundary themselves.
+ """
+ def __init__(self, hz):
+ self.hz = hz
+ self.reset()
+
+ def reset(self):
+ self.packets = 0
+ self.ticks = 0
+ self.held = frozenset()
+
+ def schedule(self, packet: InputPacket):
+ end = (self.packets + 1) * self.hz // 5
+ count = end - self.ticks
+ result = []
+ for tick in range(self.ticks + 1, end + 1):
+ sub = (tick * 30 + self.hz - 1) // self.hz - 1 - self.packets * 6
+ held = packet.holds[max(0, min(5, sub))]
+ pressed = held - self.held
+ mouse = tuple(v / count for v in packet.mouse)
+ result.append(TickInput(held, pressed, mouse))
+ self.held = held
+ self.packets += 1
+ self.ticks = end
+ return result
+
+
+@dataclass
+class EngineSnapshot:
+ """Normalized diagnostics, owned by the trusted adapter; never a model observation.
+
+ ticks is absolute native time, frames is the number executed by this call.
+ Multipart bosses report aggregate remaining progress as hp/max_hp here.
+ state must include all replay-relevant game state/RNG/input state.
+ """
+ ticks: int
+ frames: int
+ outcome: str | None
+ player_hp: float
+ player_max_hp: float
+ boss_hp: float
+ boss_max_hp: float
+ state: dict
+ events: tuple = ()
+
+
+class GameBackend(Protocol):
+ """A game may be an in-process engine, subprocess, RPC client or browser client.
+
+ validate_options must be pure. reset must establish a fresh independent
+ episode. advance executes one packet and stops on the exact terminal tick.
+ render is read-only and returns a perspective RGB for a 3D game. close must
+ release resources and be idempotent. The adapter owns process isolation.
+ """
+ spec: EngineSpec
+
+ def validate_options(self, options: dict) -> None: ...
+ def reset(self, seed: int, difficulty: float, options: dict) -> EngineSnapshot: ...
+ def advance(self, packet: InputPacket) -> EngineSnapshot: ...
+ def render(self) -> np.ndarray: ...
+ def render_status(self) -> RenderStatus: ...
+ def manual(self) -> dict: ...
+ def close(self) -> None: ...
diff --git a/environments/games/prototype/bossbench/engine_env.py b/environments/games/prototype/bossbench/engine_env.py
new file mode 100644
index 0000000000000000000000000000000000000000..d6d531d9726ef26d32a44aa787f070188dc5b84c
--- /dev/null
+++ b/environments/games/prototype/bossbench/engine_env.py
@@ -0,0 +1,119 @@
+"""Gym adapter for independent game backends (engine_contract.GameBackend)."""
+from __future__ import annotations
+
+from dataclasses import asdict
+import copy
+import json
+import math
+
+from . import keymouse as km
+from .engine_contract import EngineSnapshot, InputPacket
+from .unified import UnifiedEnv
+
+
+class EngineEnv(UnifiedEnv):
+ """No access to a game world, Body, Boss or a specific rendering library."""
+ def __init__(self, case_id, backend, **kwargs):
+ self.backend = backend
+ try:
+ super().__init__(case_id, **kwargs)
+ if self.action_mode != 'keymouse':
+ raise ValueError('independent engine adapter accepts keymouse; native actions stay inside the backend')
+ self.fps = self.engine_spec.native_hz
+ self.max_seconds = self.engine_spec.max_seconds
+ self.max_ticks = math.ceil(self.max_seconds * self.fps)
+ self.observation_space = self._obs_space()
+ except BaseException:
+ backend.close()
+ raise
+
+ @property
+ def engine_spec(self):
+ return self.backend.spec
+
+ def render_status(self):
+ return self.backend.render_status()
+
+ def _declared_tiers(self):
+ declared = getattr(self.backend, 'declared_tiers', None)
+ return declared() if callable(declared) else None
+
+ def _difficulty_band(self, d):
+ band = getattr(self.backend, 'difficulty_band', None)
+ return band(d) if callable(band) else None
+
+ def _validate_options(self, options):
+ super()._validate_options(options)
+ self.backend.validate_options(copy.deepcopy(options))
+
+ def _snapshot(self, value, *, previous=None, reset=False):
+ if not isinstance(value, EngineSnapshot):
+ raise TypeError('backend must return EngineSnapshot')
+ if type(value.ticks) is not int or type(value.frames) is not int or min(value.ticks, value.frames) < 0:
+ raise ValueError('backend ticks/frames must be nonnegative integers')
+ if reset and (value.ticks != 0 or value.frames != 0 or value.outcome is not None):
+ raise ValueError('reset must return a fresh live episode at tick zero')
+ if previous is not None:
+ expected = round(previous['t'] * self.fps) + value.frames
+ if value.ticks != expected or value.frames > math.ceil(self.fps * km.PACKET_SECONDS):
+ raise ValueError('backend native time does not match the executed packet')
+ if not value.frames and value.outcome is None:
+ raise ValueError('live packet did not advance simulation')
+ if value.outcome not in (None, 'win', 'loss', 'timeout'):
+ raise ValueError('unknown backend outcome')
+ if value.ticks >= self.max_ticks and value.outcome is None:
+ raise ValueError('backend exceeded its declared episode deadline')
+ for hp, maximum in ((value.player_hp,value.player_max_hp),(value.boss_hp,value.boss_max_hp)):
+ if not math.isfinite(hp) or not math.isfinite(maximum) or maximum <= 0 or not 0 <= hp <= maximum:
+ raise ValueError('invalid normalized backend health/progress')
+ if not isinstance(value.state, dict):
+ raise ValueError('backend diagnostics state must be a JSON object')
+ result = asdict(value)
+ json.dumps(result, allow_nan=False)
+ result.pop('ticks')
+ result['t'] = value.ticks / self.fps
+ return copy.deepcopy(result)
+
+ def _engine_reset(self, seed, d, options=None):
+ return self._snapshot(self.backend.reset(seed, d, copy.deepcopy(options or {})), reset=True)
+
+ def _engine_packet(self, packet, lag, ok):
+ try:
+ return self._advance_packets(packet, lag, ok)
+ except BaseException:
+ # A failed backend may have advanced privately; never expose the stale snapshot as live.
+ self.snap, self.done = None, True
+ raise
+
+ def _advance_packets(self, packet, lag, ok):
+ parsed = km.parse_packet(packet) if ok else None
+ action = (InputPacket(tuple(parsed['mouse']),tuple(frozenset(h) for h in parsed['subs']))
+ if parsed is not None else InputPacket.noop())
+ snapshot = self.snap
+ frames = lag_frames = 0
+ events = []
+ for _ in range(lag):
+ if snapshot['outcome']:
+ break
+ snapshot = self._snapshot(self.backend.advance(InputPacket.noop()),previous=snapshot)
+ frames += snapshot['frames']
+ lag_frames += snapshot['frames']
+ events.extend(snapshot['events'])
+ if not snapshot['outcome']:
+ snapshot = self._snapshot(self.backend.advance(action),previous=snapshot)
+ frames += snapshot['frames']
+ events.extend(snapshot['events'])
+ return {**snapshot,'frames':frames,'events':events,'lag_frames':lag_frames}
+
+ def _manual(self):
+ return copy.deepcopy(self.backend.manual())
+
+ def _render(self):
+ return self.backend.render()
+
+ def close(self):
+ if not self._closed:
+ try:
+ self.backend.close()
+ finally:
+ super().close()
diff --git a/environments/games/prototype/bossbench/keymouse.py b/environments/games/prototype/bossbench/keymouse.py
new file mode 100644
index 0000000000000000000000000000000000000000..da507c86ef1f41dbef3fd5f31b054ba70e0023a9
--- /dev/null
+++ b/environments/games/prototype/bossbench/keymouse.py
@@ -0,0 +1,211 @@
+"""The key/mouse action packet shared by every BossBench case (proposal 4.4), Python side.
+
+ <|action_start|> dx dy dz ; K1 ; K2 ; K3 ; K4 ; K5 ; K6 <|action_end|>
+
+One packet = 200 ms = 6 sub-steps of 33 ms; K_j = 0-4 keys held during sub-step j. The parser is a
+line-for-line port of web/engine/case.js BB.parsePacket, so a
+packet means the same thing whether the case runs in Python or in the browser engine.
+
+Both engines tick at 60 Hz (2 ticks per sub-step); `schedule` spreads a packet over any number of
+ticks per 200 ms all the same: a key counts as held in a tick if it is held during any
+sub-step overlapping that tick, and a press (released -> held between sub-steps) lands in the tick
+where that sub-step starts. At 60 Hz this is exactly the web engine's 2 ticks per sub-step.
+"""
+from __future__ import annotations
+
+from collections.abc import Mapping
+import re
+
+import gymnasium as gym
+import numpy as np
+
+KEYS = ("W", "A", "S", "D", "Space", "Shift", "J", "K", "L", "Q", "E", "R", "LMB", "RMB")
+_UP = {k.upper(): k for k in KEYS}
+SUBSTEPS = 6
+PACKET_SECONDS = 0.2
+MAX_KEYS = 4
+_PACKET = re.compile(r"\s*<\|action_start\|>([\s\S]*)<\|action_end\|>\s*")
+_INT = re.compile(r"-?[0-9]+")
+
+
+def parse_packet(text):
+ """-> {"mouse": (dx, dy, dz), "subs": [frozenset(keys)] * 6}, or None if the packet is malformed."""
+ m = _PACKET.fullmatch("" if text is None else str(text))
+ if not m:
+ return None
+ parts = m.group(1).split(";")
+ if len(parts) != 1 + SUBSTEPS:
+ return None
+ mouse = parts[0].split()
+ if len(mouse) != 3 or not all(_INT.fullmatch(v) for v in mouse):
+ return None
+ # Canonicalize leading zeros before int(): Python limits decimal input size,
+ # whereas JS rejects enormous values as out of range. Neither may crash.
+ normalized = []
+ for value in mouse:
+ digits = value.lstrip("-").lstrip("0") or "0"
+ if len(digits) > 4:
+ return None
+ normalized.append(("-" if value.startswith("-") else "") + digits)
+ dx, dy, dz = (int(v) for v in normalized)
+ if abs(dx) > 1000 or abs(dy) > 1000 or abs(dz) > 5:
+ return None
+ subs = []
+ for s in parts[1:]:
+ s, held = s.strip(), set()
+ if s:
+ ks = s.split(",")
+ if len(ks) > MAX_KEYS:
+ return None
+ for k in ks:
+ k = _UP.get(k.strip().upper())
+ if k is None or k in held:
+ return None
+ held.add(k)
+ subs.append(frozenset(held))
+ return {"mouse": (dx, dy, dz), "subs": subs}
+
+
+def format_packet(subs, mouse=(0, 0, 0)) -> str:
+ """subs: 6 iterables of key names. Does not validate: too many keys gives a packet the env rejects."""
+ return "<|action_start|> " + " ".join(str(int(v)) for v in mouse) + " ; " + \
+ " ; ".join(",".join(_UP.get(str(k).upper(), str(k)) for k in s) for s in subs) + " <|action_end|>"
+
+
+NOOP = format_packet([()] * SUBSTEPS)
+
+
+def to_packet(action) -> str:
+ """Anything an agent may hand to env.step -> packet text.
+
+ str the packet itself (LLM agents)
+ None NOOP
+ {"mouse": (dx,dy,dz), "keys": 6x14} KeyMouse space sample: 0/1 per sub-step and key, in KEYS order
+ {"mouse": ..., "keys": [["D"], ["D", "Space"], ...]} key names per sub-step
+ """
+ if action is None:
+ return NOOP
+ if isinstance(action, str):
+ return action
+ # Invalid structured output has the same semantics as invalid packet text:
+ # the env executes a no-op and counts it, without coercing fractions to ints.
+ if not isinstance(action, Mapping) or set(action) - {"mouse", "keys"}:
+ return "invalid structured action"
+ try:
+ mouse = np.asarray(action.get("mouse", (0, 0, 0)))
+ if (mouse.shape != (3,) or mouse.dtype.kind not in "iuf" or
+ not np.isfinite(mouse).all() or not (mouse == np.trunc(mouse)).all() or
+ not (np.abs(mouse) <= (1000, 1000, 5)).all()):
+ return "invalid structured action"
+ rows = action.get("keys", [()] * SUBSTEPS)
+ if isinstance(rows, (str, bytes)) or len(rows) != SUBSTEPS:
+ return "invalid structured action"
+ if any(isinstance(row, (str, bytes)) for row in rows):
+ return "invalid structured action"
+ try:
+ matrix = np.asarray(rows)
+ except ValueError: # ragged lists of key names
+ matrix = None
+ if matrix is not None and matrix.shape == (SUBSTEPS, len(KEYS)) and matrix.dtype.kind in "biuf":
+ if not ((matrix == 0) | (matrix == 1)).all():
+ return "invalid structured action"
+ rows = [[KEYS[i] for i in np.flatnonzero(row)] for row in matrix]
+ elif not all(all(isinstance(key, str) for key in row) for row in rows):
+ return "invalid structured action"
+ return format_packet(rows, mouse)
+ except (TypeError, ValueError, OverflowError):
+ return "invalid structured action"
+
+
+def schedule(packet, n_ticks, prev=frozenset()):
+ """Spread a parsed packet (None = no-op) over n_ticks engine ticks.
+
+ -> ([(held, pressed, (dx, dy, dz)) per tick], held during the last sub-step)
+ `prev` is the last sub-step of the previous packet, so a key held across packets is not re-pressed.
+ """
+ subs = packet["subs"] if packet else [frozenset()] * SUBSTEPS
+ mouse = np.asarray(packet["mouse"] if packet else (0, 0, 0), float) / n_ticks
+ held = [set() for _ in range(n_ticks)]
+ pressed = [set() for _ in range(n_ticks)]
+ last = prev
+ for j, s in enumerate(subs):
+ for k in range(n_ticks): # sub-step [j/6, (j+1)/6) overlaps tick [k/n, (k+1)/n)
+ if j * n_ticks < SUBSTEPS * (k + 1) and k * SUBSTEPS < (j + 1) * n_ticks:
+ held[k] |= s
+ pressed[j * n_ticks // SUBSTEPS] |= s - last
+ last = s
+ return [(frozenset(h), frozenset(p), tuple(mouse)) for h, p in zip(held, pressed)], last
+
+
+class KeyMouse(gym.spaces.Dict):
+ """Structured form of a packet for RL: mouse (dx, dy, dz) + a 6 x 14 hold matrix (sub-step x KEYS).
+
+ env.step also accepts the packet text directly. Samples respect the 0-4 keys per sub-step rule;
+ an action that breaks it is a malformed packet (executed as no-op, counted in format_errors)."""
+
+ def __init__(self, seed=None):
+ super().__init__({"mouse": gym.spaces.Box(np.array([-1000, -1000, -5]), np.array([1000, 1000, 5]),
+ dtype=np.int64),
+ "keys": gym.spaces.MultiBinary([SUBSTEPS, len(KEYS)])}, seed=seed)
+
+ def sample(self, mask=None, probability=None):
+ out = super().sample(mask, probability)
+ out["keys"] = _constrained_keys(out["keys"], self.np_random,
+ None if mask is None else mask["keys"],
+ None if probability is None else probability["keys"])
+ return out
+
+ def contains(self, x) -> bool:
+ return super().contains(x) and bool((np.asarray(x["keys"]).sum(1) <= MAX_KEYS).all())
+
+
+def _constrained_keys(sample, rng, mask=None, probability=None):
+ keys = np.asarray(sample).copy()
+ rows = keys.reshape(-1, len(KEYS))
+ if mask is None and probability is None:
+ rows.fill(0)
+ for row in rows:
+ row[rng.choice(len(KEYS), rng.integers(0, MAX_KEYS + 1), replace=False)] = 1
+ else:
+ forced = (mask == 1) if mask is not None else (probability == 1)
+ for row, fixed in zip(rows, np.asarray(forced).reshape(-1, len(KEYS))):
+ if fixed.sum() > MAX_KEYS:
+ raise ValueError("key mask/probability forces more than four keys in a substep")
+ candidates = np.flatnonzero(row & ~fixed)
+ keep = MAX_KEYS - int(fixed.sum())
+ if len(candidates) > keep:
+ row[rng.choice(candidates, len(candidates) - keep, replace=False)] = 0
+ return keys
+
+
+class BatchedKeyMouse(gym.spaces.Dict):
+ """Gym's vector action space preserving KeyMouse's per-substep constraint."""
+
+ def __init__(self, single, n):
+ from gymnasium.vector.utils import batch_space
+ base = batch_space(gym.spaces.Dict(dict(single.spaces)), n)
+ spaces = dict(base.spaces)
+ # Gym batches MultiBinary as Box, which loses mask/probability support.
+ # Keep binary semantics as well as the leading member dimension.
+ spaces["keys"] = gym.spaces.MultiBinary([n, SUBSTEPS, len(KEYS)])
+ super().__init__(spaces)
+
+ def sample(self, mask=None, probability=None):
+ out = super().sample(mask, probability)
+ out["keys"] = _constrained_keys(out["keys"], self.np_random,
+ None if mask is None else mask["keys"],
+ None if probability is None else probability["keys"])
+ return out
+
+ def contains(self, x):
+ return super().contains(x) and bool((np.asarray(x["keys"]).sum(-1) <= MAX_KEYS).all())
+
+
+# Default Dict batching drops subclass invariants. Register the real batch
+# space so SyncVectorEnv/AsyncVectorEnv samplers still emit legal actions.
+from gymnasium.vector.utils import batch_space
+
+
+@batch_space.register(KeyMouse)
+def _batch_keymouse(space, n=1):
+ return BatchedKeyMouse(space, n)
diff --git a/environments/games/prototype/bossbench/mc4d.py b/environments/games/prototype/bossbench/mc4d.py
new file mode 100644
index 0000000000000000000000000000000000000000..a97d80199e73baf420c7229d87d8785bff63a57c
--- /dev/null
+++ b/environments/games/prototype/bossbench/mc4d.py
@@ -0,0 +1,2346 @@
+"""3D Minecraft 1v1 v2: one voxel arena, seven boss cases, one shared rig.
+
+ 3d/minecraft_iron_golem ground melee: telegraphed slam that flings, knockback immune, walks around walls
+ 3d/minecraft_zombie fast light melee, relentless pressure (legacy case)
+ 3d/minecraft_ender_dragon aerial phases: circling, fireball strafes, perching with breath; healing end crystals
+ 3d/minecraft_wither hovering artillery: three heads of skulls, spawn blast, arrow-proof armor at half health
+ 3d/minecraft_warden blind juggernaut of the deep dark: crushing melee, darkness, a sonic boom for out-of-reach
+ targets that ignores armor and walls
+ 3d/minecraft_skeleton strafing archer: telegraphed bow draws, inaccurate arrows, line of sight behind ruins
+ 3d/minecraft_zombie_leader a leader zombie whose hits call reinforcements: a horde to manage at night
+
+Rules stay on the Java-edition numbers the prototype already used (attack cooldown multiplier,
+crit conditions, 10-tick hurt immunity, armor, mob melee reach, knockback, mob auto-jump, fall
+damage, friction/gravity). Those numbers are per vanilla tick (20 Hz): TABLE speeds are blocks/tick,
+cooldowns are ticks. The simulation runs at core.FPS (60 Hz) and converts at use (per_vt / ticks / decay /
+gain below), so a fight lasts the same seconds and covers the same blocks at any tick rate. Every knob is interpolated by the single scalar d, and every boss runs
+the same 4-state machine so the observation vector keeps one layout across mobs.
+
+Rendering is a skin: boxes come from bossbench.rig, which the simulation poses once per tick;
+textures, per-state poses, particles, renderer and HUD all live in bossbench.mcskin.
+
+Replay compatibility is tracked by the RULES identifier.
+"""
+from __future__ import annotations
+
+import math
+
+import gymnasium as gym
+import numpy as np
+
+from .core import FPS, RES, Arena, Body, Boss, BossBenchEnv, Case
+from . import mcskin
+from .rig import Rigged
+
+RULES = "minecraft-arena@7"
+# Public difficulty tiers: every TABLE row below is (easy, normal, hard), so a tier
+# reads exactly one knot of each row. The continuous d in [0, 1] still interpolates between them for fine control.
+TIERS = {"easy": 0.0, "normal": 0.5, "hard": 1.0}
+S = 34 # arena side in blocks
+MID = S / 2 # arena centre line (z of both spawns)
+AREA_K = (S - 2) ** 2 / 22 ** 2 # obstacle counts scale with floor area so density matches the 24 layout
+VT = 20 / FPS # one simulation tick in vanilla Minecraft ticks
+TURNS = np.radians([-30, -10, 0, 10, 30]) * VT # native turn action, per vanilla tick
+
+
+def per_vt(x):
+ """A per-vanilla-tick velocity, step or rate -> per simulation tick."""
+ return x * VT
+
+
+def ticks(n):
+ """A duration in vanilla ticks -> simulation ticks."""
+ return int(round(n / VT))
+
+
+def decay(f):
+ """A per-vanilla-tick multiplier (friction, drag) -> per simulation tick, same decay per second."""
+ return f ** VT
+
+
+def push(v, f):
+ """A one-off vanilla impulse (b/t) decaying under per-vanilla-tick friction f -> the per-sim-tick
+ impulse that carries the body the same distance."""
+ F = decay(f)
+ return v * f / (1 - f) * (1 - F) / F
+
+
+def gain(k):
+ """A per-vanilla-tick approach fraction (lerp toward a target) -> per simulation tick."""
+ return 1 - (1 - k) ** VT
+
+
+# Per simulation tick, chosen so that every third 60 Hz tick lands exactly on the vanilla 20 Hz trajectory:
+# ground friction keeps vanilla's terminal speed (= accel b/t) and time constant, air drag keeps the terminal
+# 0.02 / 0.09 b/t, gravity the terminal fall 3.92 b/t.
+GROUND_F, AIR_F, FALL_F = decay(0.546), decay(0.91), decay(0.98)
+AIR_A = 0.02 / 0.09 * (1 - AIR_F) * VT
+V_FALL = -0.08 * 0.98 / 0.02 # vanilla terminal fall speed (b/t)
+GRAVITY = -V_FALL * VT * (1 - FALL_F) / FALL_F
+
+
+def vy_sim(v):
+ """A vanilla vertical velocity set at a tick (jump, fling) -> the sim-tick value giving the same arc."""
+ return V_FALL * VT + (v - V_FALL) * (1 - FALL_F) / (1 - 0.98)
+
+
+def vy_vanilla(u):
+ """Inverse of vy_sim."""
+ return V_FALL + (u - V_FALL * VT) * (1 - 0.98) / (1 - FALL_F)
+
+
+JUMP = vy_sim(0.42)
+# sprint-jump boost: vanilla decays it once by ground friction (the take-off tick), then by air drag;
+# the sim value travels the same distance under one sim tick of ground friction, then air drag
+SPRINT_JUMP = 0.2 * 0.546 / (1 - 0.91) * (1 - AIR_F) / GROUND_F
+PLAYER_W, PLAYER_H, EYE = 0.6, 1.8, 1.62
+PLAYER_REACH = 3.0
+WALL_CAP = 8
+# SPEED_NOTE (minecraft-arena@5): a Java mob's ground speed scales with the *square* of (movement_speed attribute x its
+# goal's speed modifier): MoveControl sets the forward input to that value and LivingEntity.travel scales the input by the
+# same speed again; the player's input is 0.98 at attribute 0.1. Relative to the walking player (0.216 b/t here):
+# v = 0.216 x (attribute x modifier)^2 / 0.098. Zombie 0.23 -> 0.117 b/t (2.3 m/s, the commonly measured value),
+# skeleton 0.25 -> 0.138, warden 0.3 x its 1.2 fight modifier -> 0.286 (a sprinting player's 0.281: it cannot be
+# outrun). The new scenes use these (the leader zombie 0.117); the @4 bosses, the formal zombie included, keep their
+# tuned values.
+
+WEAPONS = ('sword', 'bow')
+BOW_RULES = {
+ 'version': 'bossbench/minecraft-bow@2',
+ 'draw_seconds': 1.0, 'minimum_power': 0.1,
+ 'maximum_speed_blocks_per_vanilla_tick': 3.0,
+ 'gravity_blocks_per_vanilla_tick_squared': 0.05,
+ 'drag_per_vanilla_tick': 0.99, 'base_damage_per_speed': 2.0,
+ 'maximum_life_seconds': 60.0, 'ammunition': 'unlimited',
+ 'aim_assist': False, 'arrow_radius_blocks': 0.025,
+}
+
+
+def _weapon(value):
+ if not isinstance(value, str) or value not in WEAPONS:
+ raise ValueError(f'weapon must be one of {WEAPONS}, got {value!r}')
+ return value
+
+
+def _camera(value):
+ if value not in ('first', 'third'):
+ raise ValueError("camera must be 'first' or 'third'")
+ return value
+
+
+def _segment_box(start, end, low, high):
+ """First intersection fraction of a swept arrow segment and an AABB."""
+ lower, upper = 0.0, 1.0
+ direction = end - start
+ for axis in range(3):
+ if abs(direction[axis]) < 1e-12:
+ if start[axis] < low[axis] or start[axis] > high[axis]:
+ return None
+ continue
+ a = (low[axis] - start[axis]) / direction[axis]
+ b = (high[axis] - start[axis]) / direction[axis]
+ lower, upper = max(lower, min(a, b)), min(upper, max(a, b))
+ if lower > upper:
+ return None
+ return lower
+
+
+class Entity:
+ def __init__(self, x, y, z, yaw, w, h):
+ self.pos, self.vel = np.array([x, y, z], float), np.zeros(3)
+ self.yaw, self.w, self.h, self.on_ground, self.fall_from = yaw, w, h, True, 0.0
+ self.pitch = 0.0 # bow aiming; positive pitch looks up
+
+ @property
+ def fwd(self):
+ return np.array([math.cos(self.yaw), 0.0, math.sin(self.yaw)])
+
+ @property
+ def right(self):
+ return np.array([-math.sin(self.yaw), 0.0, math.cos(self.yaw)])
+
+
+# ---------------------------------------------------------------- arena
+class VoxelArena(Arena):
+ """Layouts. 'field' is the ground fight (low cover, one climbable pillar); 'towers' adds tall columns so an aerial
+ boss can be broken off and its line of sight cut. minecraft-arena@5 adds three themed layouts that draw the field's
+ cover first (same random stream, so a seed gives the same base layout) and then their own pieces:
+ 'night' (no extra pieces: the field at night, for the leader zombie and its reinforcements), 'deep_dark'
+ (deepslate pillars 3-4 high: tempting perches that the warden answers with its sonic boom) and 'ruins'
+ (broken stone-brick walls 2-3 high that stop arrows both ways: cover for a bow duel)."""
+ TABLE = {"cover_clusters": (8, 5, 2), # 1-high blocks: jumpable, block a ground mob's path
+ "safe_pillars": (2, 1, 0), # 3-high pillars: the classic "pillar up" cheese
+ "towers": (2, 3, 4), # tall columns, towers layout only
+ "dark_pillars": (3, 3, 3), # deep_dark only (minecraft-arena@5)
+ "ruin_walls": (6, 6, 6)} # ruins only (minecraft-arena@5)
+
+ def __init__(self, style="field"):
+ self.style = style
+
+ def reset(self, case):
+ super().reset(case)
+ rng, H = case.rng, np.zeros((S, S), np.int8)
+ H[0, :] = H[-1, :] = H[:, 0] = H[:, -1] = WALL_CAP # arena wall
+ for _ in range(int(round(self.k.cover_clusters * AREA_K))):
+ x, z = rng.integers(3, S - 4, 2)
+ H[x:x + rng.integers(1, 3), z:z + rng.integers(1, 3)] = 1
+ for _ in range(int(round(self.k.safe_pillars * AREA_K))):
+ x, z = rng.integers(4, S - 4, 2)
+ H[x, z] = 3
+ H[x + 1, z] = max(H[x + 1, z], 1)
+ H[x + 1, z + 1] = max(H[x + 1, z + 1], 2)
+ if self.style == "towers":
+ for _ in range(int(round(self.k.towers * AREA_K))):
+ x, z = rng.integers(3, S - 5, 2)
+ H[x, z] = 4 + int(rng.integers(0, 3))
+ H[x, z + 1] = max(H[x, z + 1], 1)
+ H[x + 1, z] = max(H[x + 1, z], int(H[x, z]) - 1)
+ elif self.style == "deep_dark":
+ for _ in range(int(round(self.k.dark_pillars * AREA_K))):
+ x, z = (int(v) for v in rng.integers(5, S - 5, 2))
+ h = 3 + int(rng.integers(0, 2))
+ H[x:x + 2, z:z + 2] = h # 2x2 deepslate column
+ for i in range(1, h): # a staircase: the top can be reached
+ H[x - i, z] = max(H[x - i, z], h - i)
+ elif self.style == "ruins":
+ for _ in range(int(round(self.k.ruin_walls * AREA_K))):
+ x, z = (int(v) for v in rng.integers(4, S - 9, 2))
+ n, h = int(rng.integers(3, 7)), 2 + int(rng.integers(0, 2))
+ gap = int(rng.integers(1, n - 1)) # a breach somewhere along the wall
+ for i in range(n):
+ if i == gap:
+ continue
+ if rng.random() < 0.5:
+ H[x + i, z] = max(H[x + i, z], h)
+ else:
+ H[x, z + i] = max(H[x, z + i], h)
+ m = int(MID)
+ H[m - 8:m - 3, m - 2:m + 2] = H[m + 3:m + 8, m - 2:m + 2] = 0 # spawn pads
+ self.H = H
+
+ def ground(self, p, w):
+ h = w / 2 - 1e-6
+ x0, x1, z0, z1 = int(p[0] - h), int(p[0] + h), int(p[2] - h), int(p[2] + h)
+ if p[0] - h < 0 or p[2] - h < 0 or x1 >= S or z1 >= S:
+ return 99.0
+ return float(self.H[x0:x1 + 1, z0:z1 + 1].max())
+
+ def los(self, a, b, eye_h=1.5):
+ """Coarse line of sight: sampled columns between two entity centres."""
+ a, b = np.asarray(a, float), np.asarray(b, float)
+ n = min(int(np.hypot(*(b - a)[[0, 2]]) * 2) + 1, 32)
+ for u in np.linspace(0.06, 0.94, n):
+ p = a + (b - a) * u
+ ix, iz = int(p[0]), int(p[2])
+ if not (0 <= ix < S and 0 <= iz < S):
+ continue
+ if self.H[ix, iz] > p[1] + eye_h:
+ return False
+ return True
+
+
+def physics(case, e, wish, accel, step=0.6, vertical=True):
+ """Minecraft-style integration: ground friction 0.546, air drag 0.91, gravity (per vanilla tick, converted
+ to the simulation tick); per-axis collision. accel is the vanilla walk speed in b/t; e.vel is per sim tick."""
+ A = case.arena
+ if e.on_ground:
+ e.vel[[0, 2]] = e.vel[[0, 2]] * GROUND_F + wish[[0, 2]] * per_vt(accel) * (1 - GROUND_F)
+ else:
+ e.vel[[0, 2]] = e.vel[[0, 2]] * AIR_F + wish[[0, 2]] * AIR_A
+ blocked = False
+ for ax in (0, 2):
+ new = e.pos.copy()
+ new[ax] += e.vel[ax]
+ if A.ground(new, e.w) > e.pos[1] + step:
+ e.vel[ax], blocked = 0.0, True
+ else:
+ e.pos = new
+ landed_from = None
+ if not vertical:
+ return blocked, landed_from
+ e.pos[1] += e.vel[1]
+ e.vel[1] = (e.vel[1] - GRAVITY) * FALL_F
+ g = A.ground(e.pos, e.w)
+ if e.pos[1] <= g:
+ if not e.on_ground:
+ landed_from = e.fall_from - g
+ e.pos[1], e.vel[1], e.on_ground = g, 0.0, True
+ e.fall_from = g
+ else:
+ if e.on_ground:
+ e.fall_from = e.pos[1]
+ e.fall_from = max(e.fall_from, e.pos[1])
+ e.on_ground = False
+ return blocked, landed_from
+
+
+def armor_reduce(dmg, armor, tough):
+ return dmg * (1 - min(20.0, max(armor / 5, armor - 4 * dmg / (tough + 8))) / 25)
+
+
+# ---------------------------------------------------------------- ground navigation (minecraft-arena@4)
+# Pure functions of the arena heights, cached by their bytes: shared by every clone the scripted controller makes
+# and by the live case, so a lookahead never pays twice for the same field.
+_NAV_CACHE: dict = {}
+_STEPS = ((1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (1, -1), (-1, 1), (-1, -1))
+
+
+def _cached(key, make):
+ hit = _NAV_CACHE.get(key)
+ if hit is None:
+ if len(_NAV_CACHE) > 512:
+ _NAV_CACHE.clear()
+ hit = _NAV_CACHE[key] = make()
+ return hit
+
+
+def nav_free(H, r, step):
+ """Cells whose centre a mob of grid radius r (0: 0.6 wide, 1: 1.4 wide) can stand on: no column taller than
+ `step` (the auto-jump height) within r cells, and not the arena wall."""
+ def make():
+ wall = H > step
+ grown = wall.copy()
+ for dx in range(-r, r + 1):
+ for dz in range(-r, r + 1):
+ grown |= np.roll(np.roll(wall, dx, 0), dz, 1)
+ grown[[0, -1], :] = True
+ grown[:, [0, -1]] = True
+ return ~grown
+ return _cached(("free", H.tobytes(), r, step), make)
+
+
+def _steps(free, cell):
+ """8-connected moves from cell onto free cells, without cutting a wall corner."""
+ x, z = cell
+ for dx, dz in _STEPS:
+ a, b = x + dx, z + dz
+ if not (0 < a < S - 1 and 0 < b < S - 1) or not free[a, b]:
+ continue
+ if dx and dz and not (free[x + dx, z] and free[x, z + dz]):
+ continue
+ yield a, b
+
+
+def nav_field(H, r, step, goal):
+ """Breadth-first step counts from every free cell to the goal cell (10**6 where unreachable)."""
+ def make():
+ free = nav_free(H, r, step)
+ dist = np.full(free.shape, 10 ** 6, np.int32)
+ dist[goal] = 0
+ frontier, n = [goal], 0
+ while frontier:
+ n += 1
+ nxt = []
+ for cell in frontier:
+ for a, b in _steps(free, cell):
+ if dist[a, b] > n:
+ dist[a, b] = n
+ nxt.append((a, b))
+ frontier = nxt
+ return dist
+ return _cached(("field", H.tobytes(), r, step, goal), make)
+
+
+def _walkable(free, start, seg, own, goal):
+ """True when every cell the straight segment crosses (except the two end cells) is free."""
+ length = math.hypot(seg[0], seg[2])
+ k = int(length / 0.35) + 2
+ x0, z0, sx, sz = float(start[0]), float(start[2]), float(seg[0]) / (k - 1), float(seg[2]) / (k - 1)
+ for i in range(1, k - 1):
+ c = (min(max(int(x0 + sx * i), 0), S - 1), min(max(int(z0 + sz * i), 0), S - 1))
+ if c != own and c != goal and not free[c]:
+ return False
+ return True
+
+
+# ---------------------------------------------------------------- body
+# The player's loadout is part of a scene, identical on every tier (minecraft-arena@5): (sword attack damage, armor points,
+# armor toughness). Diamond against the end-game bosses (iron golem, ender dragon, wither, warden) and on the formal
+# zombie case (its @4 kit), iron against the overworld night mobs (leader zombie horde, skeleton archer): Java iron
+# sword 6, iron armor 15 / 0; diamond sword 7, 20 / 8.
+KITS = {"diamond": (7.0, 20.0, 8.0), "iron": (6.0, 15.0, 0.0)}
+SCENE_KIT = {"iron_golem": "diamond", "zombie": "diamond", "ender_dragon": "diamond", "wither": "diamond",
+ "warden": "diamond", "skeleton": "iron", "zombie_leader": "iron"}
+
+
+class Steve(Body, Rigged):
+ # One fixed loadout per scene on every tier (only the boss scales with the tier): the TABLE is the @4 diamond kit,
+ # replaced at reset by the scene's KITS entry (identical floats for the diamond scenes).
+ TABLE = {"sword_dmg": (7, 7, 7),
+ "armor": (20, 20, 20),
+ "toughness": (8, 8, 8)}
+ MOVES = ("none", "forward", "back", "left", "right")
+ action_space = gym.spaces.MultiDiscrete([5, 5, 2, 2, 2]) # move, turn, jump, attack, sprint
+ max_hp = 20.0
+ T_ATTACK = FPS / 1.6 # ticks to a full attack charge (sword attack speed 1.6 -> 12.5 vanilla ticks)
+ T_FIST = FPS / 4.0 # empty hand / bow in hand: attack speed 4 -> 5 vanilla ticks
+ CRIT_CHARGE = 0.9 # Java: f2 > 0.9, i.e. the 84.8 % damage multiplier
+ HOTBAR = ('sword', 'bow')
+
+ def __init__(self, weapon='sword'):
+ self.weapon = _weapon(weapon)
+ self.rig = None
+ self.ph = 0.0
+
+ def reset(self, case):
+ super().reset(case)
+ self.kit = SCENE_KIT.get(getattr(case, "mob_name", ""), "diamond")
+ self.k.sword_dmg, self.k.armor, self.k.toughness = KITS[self.kit]
+ self.e = Entity(MID - 5.5, 0.0, MID, 0.0, PLAYER_W, PLAYER_H)
+ self.hp, self.since_swing, self.iframes, self.sprinting = self.max_hp, 5 * FPS, 0, False
+ self.last_hurt, self.wither_t = 0.0, 0
+ self.ph, self.swing_t = 0.0, -5 * FPS
+ self.bow_draw_ticks, self.bow_drawing = 0, False
+ self.arrows_fired, self.arrows_hit, self.arrow_damage = 0, 0, 0.0
+ self.wheel, self.notches, self.switches, self.melee_damage = 0.0, 0, 0, 0.0
+ self._build_rig()
+
+ # -- rig ---------------------------------------------------------------
+ def _build_rig(self):
+ self.rig = mcskin.steve_rig()
+
+ def pose(self, case):
+ mcskin.pose_steve(self, case)
+
+ def noop(self):
+ return np.array([0, 2, 0, 0, 0])
+
+ MOUSE_DEG = 0.15 # camera yaw/pitch per mouse unit (dx = 200 in one packet turns 30 deg)
+ MANUAL = (
+ "W forward, S back, A strafe left, D strafe right (one direction at a time; W > S > A > D)",
+ "mouse dx turns right and dy looks down, 0.15 deg per unit (dx 200 = 30 deg); pitch is limited to +-89 deg; "
+ "there is no aim assist for any weapon (since rules minecraft-arena@2)",
+ "Space jump (while held, whenever on the ground); Shift sprint (only while holding W)",
+ "hotbar: slot 1 sword (diamond against the end-game bosses, iron against the night mobs), slot 2 bow; mouse "
+ "wheel dz switches slots (each notch one slot); "
+ "switching resets the attack cooldown and cancels a bow draw",
+ "sword in hand: LMB or J swings once per press, 3 blocks reach along the view ray; damage scales with the "
+ "attack-cooldown charge (1.6 swings/s); a falling hit with charge > 90 %, not sprinting, is a crit (x1.5); "
+ "a sprinting hit at > 90 % adds knockback",
+ "bow in hand: hold RMB to draw across packets, release to fire (1 s = full draw, critical arrow); drawing "
+ "slows movement and stops sprinting; arrows fall with gravity and stop on terrain; LMB/J punch for 1",
+ "every hit gives 10 vanilla ticks (0.5 s) of damage immunity; a stronger hit inside it deals only the difference",
+ )
+ SWORD_MANUAL = MANUAL # kept for older imports
+
+ @property
+ def manual(self):
+ return self.MANUAL
+
+ def keys(self, case, held, pressed, mouse):
+ self.e.yaw = (self.e.yaw + math.radians(mouse[0] * self.MOUSE_DEG)) % (2 * math.pi)
+ self.e.pitch = float(np.clip(self.e.pitch - math.radians(mouse[1] * self.MOUSE_DEG),
+ math.radians(-89), math.radians(89)))
+ if len(mouse) > 2 and mouse[2]:
+ # The packet's wheel motion is spread over its ticks; a notch lands on the first tick that starts it.
+ self.wheel += mouse[2]
+ a = self.wheel
+ target = math.ceil(a - 1e-6) if a > 1e-6 else (-math.ceil(-a - 1e-6) if a < -1e-6 else 0)
+ while self.notches != target:
+ step = 1 if target > self.notches else -1
+ self.notches += step
+ self.select(case, self.HOTBAR[(self.HOTBAR.index(self.weapon) + step) % len(self.HOTBAR)])
+ move = next((i for i, k in ((1, "W"), (2, "S"), (3, "A"), (4, "D")) if k in held), 0)
+ swing = bool(pressed & {"LMB", "J"})
+ if self.weapon == 'bow':
+ return np.array([move, 2, "Space" in held, 'RMB' in held, "Shift" in held, swing])
+ return np.array([move, 2, "Space" in held, swing, "Shift" in held, 0])
+
+ def select(self, case, weapon):
+ """Hotbar switch: Java resets the attack strength ticker whenever the held item changes."""
+ if weapon == self.weapon:
+ return
+ if self.bow_drawing:
+ case.events.append('bow_cancel')
+ self.weapon, self.since_swing = weapon, 0
+ self.bow_drawing, self.bow_draw_ticks = False, 0
+ self.switches += 1
+ case.events.append(('hotbar', weapon))
+
+ def parse(self, text):
+ w = set(text.lower().replace(",", "+").replace(" ", "+").split("+"))
+ move = next((i for i, m in enumerate(self.MOVES) if m in w), 0)
+ turn = 0 if "turn_left_big" in w else 1 if "turn_left" in w else 4 if "turn_right_big" in w else \
+ 3 if "turn_right" in w else 2
+ return np.array([move, turn, "jump" in w, "attack" in w, "sprint" in w])
+
+ @property
+ def attack_charge(self):
+ """Java attack strength scale f2 = clamp((t + 0.5) / T) for the item in hand."""
+ return min(1.0, (self.since_swing + 0.5) / (self.T_ATTACK if self.weapon == 'sword' else self.T_FIST))
+
+ @property
+ def charge(self):
+ if self.weapon == 'bow':
+ return self.bow_charge
+ return self.attack_charge
+
+ @property
+ def bow_charge(self):
+ return min(1.0, self.bow_draw_ticks / (FPS * BOW_RULES['draw_seconds']))
+
+ def apply(self, case, action):
+ move, turn, jump, attack, sprint = (int(a) for a in action[:5])
+ punch = len(action) > 5 and bool(action[5])
+ e = self.e
+ self.iframes, self.since_swing = max(self.iframes - 1, 0), self.since_swing + 1
+ e.yaw = (e.yaw + TURNS[turn]) % (2 * math.pi)
+ wish = {0: 0 * e.fwd, 1: e.fwd, 2: -e.fwd, 3: -e.right, 4: e.right}[move]
+ drawing = self.weapon == 'bow' and bool(attack)
+ self.sprinting = bool(sprint) and move == 1 and not drawing
+ if jump and e.on_ground:
+ e.vel[1] = JUMP
+ if self.sprinting:
+ e.vel += e.fwd * SPRINT_JUMP
+ speed = 0.281 if self.sprinting else 0.216
+ if drawing:
+ wish = wish * 0.2
+ _, fell = physics(case, e, wish, speed)
+ if fell and fell > 3:
+ case.hurt_player(fell - 3, armor=False)
+ case.events.append("fall_damage")
+ if self.wither_t > 0: # Wither II: 1 damage per 20 vanilla ticks, ignores armor
+ self.wither_t -= 1
+ if self.wither_t % ticks(20) == 0:
+ case.hurt_player(1.0, armor=False)
+ case.events.append("wither_effect")
+ if self.weapon == 'bow':
+ self._update_bow(case, bool(attack))
+ if punch:
+ self._swing(case)
+ elif attack:
+ self._swing(case)
+
+ def _update_bow(self, case, held):
+ if held:
+ if not self.bow_drawing:
+ case.events.append('bow_draw')
+ self.bow_drawing = True
+ self.bow_draw_ticks += 1
+ return
+ if not self.bow_drawing:
+ return
+ charge = self.bow_charge
+ power = min(1.0, (charge * charge + 2.0 * charge) / 3.0)
+ self.bow_drawing, self.bow_draw_ticks = False, 0
+ if power < BOW_RULES['minimum_power']:
+ case.events.append('bow_cancel')
+ return
+ e = self.e
+ direction = self.look()
+ speed = BOW_RULES['maximum_speed_blocks_per_vanilla_tick'] * power
+ self.arrows_fired += 1
+ case.arrows.append({'id': self.arrows_fired,
+ 'pos': e.pos + [0, EYE, 0] + direction * 0.1,
+ 'vel': direction * per_vt(speed), 'age': 0,
+ 'damage': float(math.ceil(speed * BOW_RULES['base_damage_per_speed'])),
+ 'critical': power >= 1.0})
+ case.events.append(('bow_release', self.arrows_fired, round(power, 4)))
+
+ def look(self):
+ e = self.e
+ return np.array([math.cos(e.yaw) * math.cos(e.pitch), math.sin(e.pitch),
+ math.sin(e.yaw) * math.cos(e.pitch)])
+
+ def ray_hit(self, case):
+ """Nearest target box along the view ray within the 3 block attack range: (distance, kind, payload) or
+ None. Terrain in front of the target blocks the swing."""
+ eye = self.e.pos + [0, EYE, 0]
+ ray = self.look()
+ best = None
+ for kind, lo, hi, payload in case._targets():
+ with np.errstate(divide="ignore", invalid="ignore"):
+ t1, t2 = (lo - eye) / ray, (hi - eye) / ray
+ tn, tf = np.nanmax(np.minimum(t1, t2)), np.nanmin(np.maximum(t1, t2))
+ if tn <= tf and tf >= 0 and tn <= PLAYER_REACH and (best is None or tn < best[0]):
+ best = (max(float(tn), 0.0), kind, payload)
+ if best is not None and best[0] > 0.05:
+ wall, _ = case._arrow_world_hit(eye, eye + ray * best[0])
+ if wall is not None and wall < 0.999:
+ return None
+ return best
+
+ def _swing(self, case):
+ """Ray vs the mob hitbox along the player's own yaw and pitch (no aim assist since minecraft-arena@2)."""
+ g, e = case.boss, self.e
+ charge, self.since_swing = self.attack_charge, 0
+ self.swing_t = case.t
+ target = self.ray_hit(case)
+ if target is None:
+ case.events.append("miss")
+ return
+ base = self.k.sword_dmg if self.weapon == 'sword' else 1.0
+ mult = 0.2 + min(charge, 1.0) ** 2 * 0.8
+ strong = charge > self.CRIT_CHARGE
+ living = target[1] in ("boss", "minion") and not hasattr(g, "hitboxes") # Java: crits need a LivingEntity
+ crit = strong and living and not e.on_ground and e.vel[1] < 0 and not self.sprinting
+ sprint_hit = strong and self.sprinting
+ dmg = base * mult * (1.5 if crit else 1.0)
+ self.melee_damage += case._damage(target[1], target[2], dmg, "crit" if crit else "normal",
+ bonus_knockback=0.5 if sprint_hit else 0.0)
+ if sprint_hit: # Java: the attacker stops sprinting, keeps 60 % speed
+ e.vel[[0, 2]] *= 0.6
+ self.sprinting = False
+ case.events.append("sprint_hit")
+
+
+# ---------------------------------------------------------------- mobs
+class Mob(Boss, Rigged):
+ """Shared machinery: hitboxes, knockback, hit flash, hit posing, rig bookkeeping."""
+ STATES = ("chase", "windup", "swing", "recover")
+ aim_h = 1.35 # where the player's aim assist points
+ half = (0.7, 0.7) # hitbox half extents in x/z
+ knockback = 1.0 # 0 = knockback immune (vanilla iron golem)
+ hover = False
+ armor = 0.0 # natural armor points (Java: zombie 2, wither 4)
+ hit_event = "boss_hit" # event name a landed hit records ("minion_hit" for zombie reinforcements, @5)
+ last_hurt = 0.0
+
+ def __init__(self):
+ self.rig = None
+ self.tint_t = 0
+
+ def reset(self, case):
+ super().reset(case)
+ self._steer_t, self._steer_dir = -9, np.zeros(3) # steer() memo: last vanilla-tick plan
+
+ # -- geometry ----------------------------------------------------------
+ def hit_lo(self):
+ return self.e.pos - [self.half[0], 0.0 if not self.hover else 0.75, self.half[1]]
+
+ def hit_hi(self):
+ return self.e.pos + [self.half[0], self.height if not self.hover else -0.75, self.half[1]]
+
+ def dist_to(self, case):
+ return case.body.e.pos - self.e.pos
+
+ ATTACK_INFLATE = math.sqrt(2.04) - 0.6 # Java 1.20.2+: attack box = collision box + 0.828 horizontally
+
+ def in_reach(self, case):
+ """Java 1.20.2+ mob melee: the collision box expanded horizontally by 0.828 must intersect the
+ target's box, with line of sight (no hits through walls). Replaces the pre-1.20.2 reach^2 test."""
+ p, r = case.body.e, self.ATTACK_INFLATE
+ lo = self.e.pos - [self.half[0] + r, 0.0, self.half[1] + r]
+ hi = self.e.pos + [self.half[0] + r, self.height, self.half[1] + r]
+ plo, phi = p.pos - [PLAYER_W / 2, 0.0, PLAYER_W / 2], p.pos + [PLAYER_W / 2, PLAYER_H, PLAYER_W / 2]
+ if not (np.all(lo <= phi) and np.all(plo <= hi)):
+ return False
+ return case.arena.los(self.e.pos + [0, 1.0, 0], p.pos + [0, 1.0, 0], eye_h=0.0)
+
+ def immune(self, case, kind):
+ """Hits this mob ignores outright (wither spawn charge, wither armor vs arrows)."""
+ return False
+
+ # -- ground pathing (minecraft-arena@4) ----------------------------------------------------------------
+ NAV_STEP = 1 # columns up to this height are walkable (auto-jump); taller ones are walls
+
+ def steer(self, case):
+ """Unit xz walking direction toward the player. Straight while the line to the player is walkable (Java
+ mobs walk at a visible target); around walls along the step field otherwise (Java mobs path-find; without it
+ a pillar between the two pinned the mob in place forever: a soft-lock, found 2026-11-02). Re-planned once
+ per vanilla tick, like Java's 20 Hz mob AI; the two sim ticks in between keep the last direction."""
+ if case.t % 3 and case.t - 2 <= getattr(self, "_steer_t", -9) <= case.t:
+ return self._steer_dir
+ self._steer_t, self._steer_dir = case.t, self._plan_steer(case)
+ return self._steer_dir
+
+ def _plan_steer(self, case):
+ e, p = self.e, case.body.e
+ to = p.pos - e.pos
+ to[1] = 0.0
+ n = math.hypot(to[0], to[2])
+ if n < 1e-6:
+ return to
+ H = case.arena.H
+ r = int(math.ceil(self.half[0] - 0.5 - 1e-9))
+ free = nav_free(H, r, self.NAV_STEP)
+ own = (int(e.pos[0]), int(e.pos[2]))
+ goal = (min(max(int(p.pos[0]), 1), S - 2), min(max(int(p.pos[2]), 1), S - 2))
+ if _walkable(free, e.pos, to, own, goal):
+ return to / n
+ dist = nav_field(H, r, self.NAV_STEP, goal)
+ cell, path = own, []
+ for _ in range(4): # follow the field downhill a few cells
+ here = dist[cell] if free[cell] else 10 ** 6
+ best = None
+ for a, b in _steps(free, cell):
+ if dist[a, b] < here and (best is None or dist[a, b] < dist[best]):
+ best = (a, b)
+ if best is None:
+ break
+ path.append(best)
+ cell = best
+ if dist[cell] == 0:
+ break
+ if not path:
+ return to / n # nowhere better: lean on the wall toward the target
+ aim = np.array([path[0][0] + 0.5, 0.0, path[0][1] + 0.5])
+ for c in reversed(path[1:]): # string-pull to the farthest cell in a straight line
+ target = np.array([c[0] + 0.5, 0.0, c[1] + 0.5])
+ seg = target - e.pos
+ seg[1] = 0.0
+ if _walkable(free, e.pos, seg, own, c):
+ aim = target
+ break
+ d = aim - e.pos
+ d[1] = 0.0
+ return d / (float(np.linalg.norm(d)) + 1e-9)
+
+ def on_hurt(self, case, amount, kind):
+ pass
+
+ def take_hit(self, case, dmg, kind="normal", bonus_knockback=0.0):
+ """Java LivingEntity.hurt: a hit starts 10 vanilla ticks of immunity; inside the window only a stronger
+ hit lands and deals the difference (no knockback, no new window). Armor applies to what lands."""
+ if self.immune(case, kind):
+ case.events.append(("boss_immune", kind))
+ return 0.0
+ fresh = self.iframes <= 0
+ if fresh:
+ amount, self.last_hurt = dmg, dmg
+ self.iframes = ticks(10)
+ self.tint_t = ticks(8)
+ elif dmg > self.last_hurt:
+ amount, self.last_hurt = dmg - self.last_hurt, dmg
+ else:
+ return 0.0
+ if self.armor:
+ amount = armor_reduce(amount, self.armor, 0.0)
+ amount = amount * (1.0 - float(getattr(self, "guard", 0.0)))
+ self.hp -= amount
+ if fresh and self.knockback > 0 and not self.hover:
+ d = self.e.pos - case.body.e.pos
+ n = float(np.linalg.norm(d[[0, 2]])) + 1e-6
+ self.e.vel[[0, 2]] += d[[0, 2]] / n * push(0.4 + bonus_knockback, 0.546) * self.knockback
+ case.events.append((self.hit_event, round(amount, 2), kind))
+ self.on_hurt(case, amount, kind)
+ return amount
+
+ def hurt_player(self, case, dmg, fling=0.0, iframes=True, share=1.0, armor=True, origin=None, lift=0.0):
+ """Damage the player; a fresh (non-immune) hit knocks the player away from origin (default: this mob).
+ Java knockback: horizontal velocity halved plus the push; on the ground vy = min(0.4, vy / 2 + 0.4);
+ lift adds the iron golem's extra +0.4 b/t launch."""
+ p = case.body.e
+ landed = case.hurt_player(dmg, armor=armor, iframes=iframes, share=share)
+ if not landed:
+ return False
+ if fling and landed == "fresh":
+ d = p.pos - (self.e.pos if origin is None else np.asarray(origin, float))
+ n = float(np.linalg.norm(d[[0, 2]])) + 1e-6
+ p.vel[[0, 2]] = p.vel[[0, 2]] / 2 + d[[0, 2]] / n * push(fling, 0.546 if self.hover else 0.91)
+ if not self.hover or lift:
+ p.vel[1] = vy_sim(min(0.4, vy_vanilla(p.vel[1]) / 2 + 0.4) + lift)
+ p.on_ground = False
+ return True
+
+ # -- rig ---------------------------------------------------------------
+ def rigs(self):
+ return [self.rig] if self.rig is not None else []
+
+ def extra(self, case):
+ """Transient hazard visuals owned by the simulation (skulls), drawn as world-axis boxes."""
+ return []
+
+ def fx(self, case):
+ """Particle visuals. Uses case.fxrng, never case.rng: rendering must not consume the
+ gameplay random stream."""
+ return []
+
+
+class IronGolem(Mob):
+ TABLE = { # (easy, normal, hard) = TIERS
+ "hp": (380, 1000, 2700), # TIER calibration for ~25 s / 1 min / 3 min (Java: 100 on every difficulty)
+ "speed": (0.11, 0.13, 0.15), # vanilla b/t chase, below the player's 0.216 walk (Java ~0.14)
+ "dmg_min": (4.75, 7.5, 11.25), # Java easy / normal / hard
+ "dmg_max": (11.75, 21.5, 32.25),
+ "cooldown": (30, 24, 20), # vanilla ticks between slams (Java 20)
+ "windup": (0.60, 0.45, 0.35), # EXT seconds of raised arms before the hit
+ "jitter": (0.0, 0.05, 0.10), # EXT tempo variance
+ }
+ MOVES = {"swing": {"atoms": ["melee_area", "grab/fling"], "telegraph": "both arms raised",
+ "damage": "U[dmg_min, dmg_max] then armor", "range": "reach^2=(2*1.4)^2+0.6",
+ "punish": "cooldown (vanilla ticks) after each swing; cannot reach targets >=2.75 above"}}
+ SKILLS = ("spacing", "attack_timing", "crit_jump", "kiting", "terrain_use", "reaction")
+ name = "iron_golem"
+ height, aim_h, reach, reach_up = 2.7, 1.35, 2.9, 2.75
+ half = (0.7, 0.7)
+ knockback = 0.0
+
+ def reset(self, case):
+ super().reset(case)
+ self.max_hp = self.hp = self.k.hp
+ self.e = Entity(MID + 5.5, 0.0, MID, math.pi, 1.4, self.height)
+ self.state, self.timer, self.cd, self.iframes = "chase", 0.0, 0, 0
+ self.ph, self.tint_t, self.arm = 0.0, 0, 0.0
+ self.rig = golem_rig()
+
+ @property
+ def enraged(self):
+ return False # the @1-@3 below-half-HP enrage is not Java; dropped in @4
+
+ def update(self, case):
+ k, e, p = self.k, self.e, case.body.e
+ self.iframes, self.cd = max(self.iframes - 1, 0), max(self.cd - 1, 0)
+ self.tint_t = max(self.tint_t - 1, 0)
+ self.timer -= 1 / FPS
+ to = p.pos - e.pos
+ wish = self.steer(case)
+ e.yaw = math.atan2(wish[2], wish[0]) if wish.any() else e.yaw
+ speed = k.speed
+ if self.state == "chase":
+ if self.cd == 0 and self.in_reach(case):
+ self.state = "windup"
+ self.timer = max(0.05, k.windup + case.rng.uniform(-k.jitter, k.jitter))
+ case.events.append("golem_windup")
+ elif self.state == "windup":
+ speed *= 0.3
+ if self.timer <= 0:
+ self.state, self.timer = "swing", 0.15
+ if self.in_reach(case):
+ if self.hurt_player(case, case.rng.uniform(k.dmg_min, k.dmg_max), fling=0.4, lift=0.4):
+ case.events.append(("golem_hit",))
+ else:
+ case.events.append("golem_whiff")
+ elif self.state == "swing":
+ speed = 0.0
+ if self.timer <= 0:
+ self.state, self.cd = "recover", ticks(k.cooldown)
+ elif self.state == "recover" and self.cd == 0:
+ self.state = "chase"
+ if np.hypot(to[0], to[2]) < 0.75:
+ wish = 0 * wish
+ blocked, _ = physics(case, e, wish, speed, step=0.0)
+ if blocked and e.on_ground:
+ e.vel[1] = JUMP # mobs auto-jump 1-block steps
+ self.ph = (self.ph + float(np.hypot(e.vel[0], e.vel[2])) * 0.75) % 1.0
+ self.pose(case)
+
+ def pose(self, case):
+ mcskin.pose_golem(self, case)
+
+
+
+class Zombie(Mob):
+ TABLE = {
+ "hp": (14, 20, 26),
+ "speed": (0.13, 0.19, 0.26),
+ "dmg_min": (2.5, 3.0, 4.5), # Java easy / normal / hard (fixed per difficulty)
+ "dmg_max": (2.5, 3.0, 4.5),
+ "cooldown": (30, 20, 14),
+ "windup": (0.45, 0.28, 0.10),
+ "jitter": (0.0, 0.12, 0.3),
+ "enrage_speed": (1.0, 1.0, 1.3), # EXT: below half hp
+ "flail": (0.0, 0.0, 0.0), # EXT follow-up swipe, disabled since minecraft-arena@2 (not in Java)
+ }
+ MOVES = {"swipe": {"atoms": ["melee_single"], "telegraph": "arm cocked back",
+ "damage": "Java 2.5 / 3 / 4.5 then armor", "range": "reach 2.4",
+ "punish": "short cooldown; takes knockback on every hit; natural armor 2"}}
+ SKILLS = ("spacing", "attack_timing", "kiting", "target_priority", "reaction")
+ name = "zombie"
+ height, aim_h, reach, reach_up = 1.95, 1.05, 2.4, 2.6
+ half = (0.3, 0.3)
+ knockback = 1.0
+ armor = 2.0
+
+ def reset(self, case):
+ super().reset(case)
+ self.max_hp = self.hp = self.k.hp
+ self.e = Entity(MID + 2.0, 0.0, MID, math.pi, 0.6, self.height)
+ self.state, self.timer, self.cd, self.iframes = "chase", 0.0, 0, 0
+ self.ph, self.tint_t, self.swipes = 0.0, 0, 0
+ self.rig = zombie_rig()
+
+ @property
+ def enraged(self):
+ return self.hp <= self.max_hp / 2
+
+ def update(self, case):
+ k, e, p = self.k, self.e, case.body.e
+ self.iframes, self.cd = max(self.iframes - 1, 0), max(self.cd - 1, 0)
+ self.tint_t = max(self.tint_t - 1, 0)
+ self.timer -= 1 / FPS
+ to = p.pos - e.pos
+ wish = self.steer(case)
+ e.yaw = math.atan2(wish[2], wish[0]) if wish.any() else e.yaw
+ speed = k.speed * (k.enrage_speed if self.enraged else 1.0)
+ if self.state == "chase":
+ if self.cd == 0 and self.in_reach(case):
+ self.state = "windup"
+ self.timer = max(0.05, k.windup + case.rng.uniform(-k.jitter, k.jitter))
+ case.events.append("zombie_windup")
+ elif self.state == "windup":
+ speed *= 0.35
+ if self.timer <= 0:
+ self.state, self.timer, self.swipes = "swing", 0.1, 0
+ if self.in_reach(case):
+ self.hurt_player(case, case.rng.uniform(k.dmg_min, k.dmg_max), fling=0.4)
+ self.swipes = 1 + int(case.rng.random() < k.flail * 0.5)
+ else:
+ case.events.append("zombie_whiff")
+ elif self.state == "swing":
+ speed = 0.0
+ if self.timer <= 0:
+ self.swipes -= 1
+ if self.swipes > 0 and self.in_reach(case):
+ self.hurt_player(case, case.rng.uniform(k.dmg_min, k.dmg_max) * 0.7, fling=0.4)
+ self.timer = 0.1
+ case.events.append("zombie_flail")
+ else:
+ self.state, self.cd = "recover", ticks(k.cooldown)
+ elif self.state == "recover" and self.cd == 0:
+ self.state = "chase"
+ if np.hypot(to[0], to[2]) < 0.45:
+ wish = 0 * wish
+ blocked, _ = physics(case, e, wish, speed, step=0.0)
+ if blocked and e.on_ground:
+ e.vel[1] = JUMP
+ self.ph = (self.ph + float(np.hypot(e.vel[0], e.vel[2])) * 1.1) % 1.0
+ self.pose(case)
+
+ def pose(self, case):
+ mcskin.pose_zombie(self, case)
+
+
+
+class ZombieLeader(Mob):
+ """Java Edition 1.21 *leader zombie* as a boss fight (minecraft.wiki/w/Zombie, read 2026-11-02; Java:
+ up to 5 % spawn on Normal / Hard, max health x2-5, reinforcement chance +50-75 %) on a night field. Every hit it takes
+ may call a reinforcement: a plain zombie (20 HP, armor 2, 0.23 speed attribute) spawned 7-12 blocks away, out of
+ the player's reach, that joins the chase at once; the leader's chance drops 5 % per summon, as in Java. The case is won
+ by killing the leader; reinforcements only add pressure (their hits on the player, their bodies blocking the way).
+
+ Its own case since minecraft-arena@6 (3d/minecraft_zombie_leader): @5 had put it under 3d/minecraft_zombie, a
+ FORMAL_CASES scene that keeps its @4 rules (class Zombie above).
+
+ Deliberate deviations (minecraft-arena@5): reinforcements are on every tier (Java: Hard only), with the chance and the
+ number alive scaled by tier, because a public tier must be the same fight paced differently; the spawn search is the
+ arena's free floor 7-12 blocks from the player instead of Java's 0 / +-7-40 blocks in darkness.
+ """
+ TABLE = { # (easy, normal, hard) = TIERS
+ "hp": (215, 520, 1650), # TIER calibration (Java leader: 40-100 = 2-5x a zombie's 20)
+ "speed": (0.105, 0.117, 0.135), # vanilla b/t chase; Java 0.117 (see SPEED_NOTE), slower than a walk
+ "dmg_min": (2.5, 3.0, 4.5), # Java easy / normal / hard (fixed per difficulty)
+ "dmg_max": (2.5, 3.0, 4.5),
+ "cooldown": (30, 20, 20), # vanilla ticks between swings (Java 20)
+ "windup": (0.45, 0.30, 0.20), # EXT seconds of raised arms before the hit
+ "jitter": (0.0, 0.10, 0.15), # EXT tempo variance
+ "reinforce": (0.55, 0.60, 0.70), # leader's chance to call a reinforcement when hurt (Java +50-75 %)
+ "minions": (2, 3, 4), # reinforcements alive at once (EXT cap)
+ "minion_hp": (20, 20, 20), # Java zombie
+ "minion_dmg": (2.5, 3.0, 4.5), # Java easy / normal / hard
+ }
+ MOVES = {"swipe": {"atoms": ["melee_single"], "telegraph": "arms raised high, a lunge",
+ "damage": "Java 2.5 / 3 / 4.5 then armor", "range": "attack box 0.83 around its body",
+ "punish": "20-tick cooldown; takes knockback on every hit; natural armor 2"},
+ "reinforcements": {"atoms": ["summon_adds"], "telegraph": "smoke where a helper climbs out of the ground",
+ "damage": "each reinforcement swipes like its caller",
+ "range": "spawns 7-12 blocks from you", "punish": "kill the caller: the adds stay, the fight ends"}}
+ SKILLS = ("spacing", "attack_timing", "kiting", "target_priority", "crowd_control", "reaction")
+ name = "zombie_leader"
+ height, aim_h, reach, reach_up = 1.95, 1.05, 2.4, 2.6
+ half = (0.3, 0.3)
+ knockback = 1.0
+ armor = 2.0
+
+ def reset(self, case):
+ super().reset(case)
+ self.max_hp = self.hp = self.k.hp
+ self.e = Entity(MID + 4.0, 0.0, MID, math.pi, 0.6, self.height)
+ self.state, self.timer, self.cd, self.iframes = "chase", 0.0, 0, 0
+ self.ph, self.tint_t, self.swipes = 0.0, 0, 0
+ self.chance = float(self.k.reinforce)
+ self.minions, self.summoned = [], 0
+ self.rig = zombie_rig(leader=True)
+
+ @property
+ def enraged(self):
+ return False # the @1-@4 below-half-HP speed-up is not Java; dropped in @5
+
+ def update(self, case):
+ self.melee(case, self.k.dmg_min, self.k.dmg_max)
+ self.minions = [z for z in self.minions if z.hp > 0] # the dead leave the fight (their puff is an event)
+ for z in self.minions:
+ z.update(case)
+ self.pose(case)
+
+ def melee(self, case, dmg_min, dmg_max):
+ """One tick of the zombie melee AI (shared by the leader and its reinforcements)."""
+ k, e, p = self.k, self.e, case.body.e
+ self.iframes, self.cd = max(self.iframes - 1, 0), max(self.cd - 1, 0)
+ self.tint_t = max(self.tint_t - 1, 0)
+ self.timer -= 1 / FPS
+ to = p.pos - e.pos
+ wish = self.steer(case)
+ e.yaw = math.atan2(wish[2], wish[0]) if wish.any() else e.yaw
+ speed = k.speed
+ if self.state == "chase":
+ if self.cd == 0 and self.in_reach(case):
+ self.state = "windup"
+ self.timer = max(0.05, k.windup + case.rng.uniform(-k.jitter, k.jitter))
+ case.events.append("zombie_windup")
+ elif self.state == "windup":
+ speed *= 0.35
+ if self.timer <= 0:
+ self.state, self.timer = "swing", 0.1
+ if self.in_reach(case):
+ self.hurt_player(case, case.rng.uniform(dmg_min, dmg_max), fling=0.4)
+ else:
+ case.events.append("zombie_whiff")
+ elif self.state == "swing":
+ speed = 0.0
+ if self.timer <= 0:
+ self.state, self.cd = "recover", ticks(k.cooldown)
+ elif self.state == "recover" and self.cd == 0:
+ self.state = "chase"
+ if np.hypot(to[0], to[2]) < 0.45:
+ wish = 0 * wish
+ blocked, _ = physics(case, e, wish, speed, step=0.0)
+ if blocked and e.on_ground:
+ e.vel[1] = JUMP
+ self.ph = (self.ph + float(np.hypot(e.vel[0], e.vel[2])) * 1.1) % 1.0
+
+ def on_hurt(self, case, amount, kind):
+ """Java hurt(): a hurt mob may call a reinforcement; each summon lowers its own chance by 5 %."""
+ alive = [z for z in self.minions if z.hp > 0]
+ if self.hp > 0 and len(alive) < int(round(self.k.minions)) and case.rng.random() < self.chance:
+ spot = self._reinforcement_spot(case)
+ if spot is not None:
+ self.chance = max(0.0, self.chance - 0.05)
+ self.summoned += 1
+ z = Reinforcement(self, spot, self.summoned)
+ z.reset(case)
+ self.minions = alive + [z]
+ case.events.append(("zombie_reinforce", self.summoned, [round(float(v), 2) for v in spot]))
+
+ def _reinforcement_spot(self, case):
+ """A free floor cell 7-12 blocks from the player (Java: 7-40 blocks away, never within 7 of a player)."""
+ H, p = case.arena.H, case.body.e.pos
+ for _ in range(24):
+ ang = case.rng.uniform(0.0, 2.0 * math.pi)
+ r = case.rng.uniform(7.0, 12.0)
+ x, z = p[0] + math.cos(ang) * r, p[2] + math.sin(ang) * r
+ if not (2.0 <= x <= S - 2.0 and 2.0 <= z <= S - 2.0):
+ continue
+ ix, iz = int(x), int(z)
+ if H[ix - 1:ix + 2, iz - 1:iz + 2].max() > 0:
+ continue
+ return np.array([ix + 0.5, 0.0, iz + 0.5])
+ return None
+
+ def rigs(self):
+ return [self.rig] + [z.rig for z in self.minions if z.rig is not None]
+
+ def pose(self, case):
+ mcskin.pose_zombie(self, case)
+
+ def pose_child(self, case, z):
+ """Posing of a reinforcement goes through its leader, so a lookahead clone can switch all posing off at once."""
+ mcskin.pose_zombie(z, case)
+
+
+class Reinforcement(ZombieLeader):
+ """A plain Java zombie called by the leader: 20 HP, armor 2, Java damage, the same melee AI. It climbs out of the
+ ground for 0.8 s (cannot move or attack), then joins the chase. It takes the player's hits through MobFight._targets
+ (kind "minion") and leaves the fight at 0 HP; it never calls reinforcements itself (Java's summoned zombie keeps a
+ 5 %-lower chance: two generations would flood a one-on-one arena)."""
+ hit_event = "minion_hit"
+ CLIMB = 16 # vanilla ticks climbing out of the ground
+
+ def __init__(self, leader, spot, n):
+ super().__init__()
+ self.leader, self.spot, self.n = leader, np.asarray(spot, float), int(n)
+
+ def reset(self, case):
+ Mob.reset(self, case)
+ self.k = self.leader.k
+ self.max_hp = self.hp = float(self.k.minion_hp)
+ to = case.body.e.pos - self.spot
+ self.e = Entity(self.spot[0], 0.0, self.spot[2], math.atan2(to[2], to[0]), 0.6, self.height)
+ self.state, self.timer, self.cd, self.iframes = "chase", 0.0, 0, 0
+ self.ph, self.tint_t, self.swipes, self.summoned, self.minions = 0.0, 0, 0, 0, []
+ self.born = case.t
+ self.rig = zombie_rig()
+
+ def update(self, case):
+ if self.hp <= 0:
+ return
+ if case.t - self.born < ticks(self.CLIMB):
+ self.iframes, self.tint_t = max(self.iframes - 1, 0), max(self.tint_t - 1, 0)
+ else:
+ self.melee(case, self.k.minion_dmg, self.k.minion_dmg)
+ self.leader.pose_child(case, self)
+
+ def on_hurt(self, case, amount, kind):
+ if self.hp <= 0:
+ case.events.append(("minion_killed", self.n, [round(float(v), 2) for v in self.e.pos]))
+
+
+
+class EnderDragon(Mob):
+ """Java Edition 1.21 ender dragon phases (minecraft.wiki/w/Ender_Dragon, read 2026-11-01), at arena scale.
+
+ holding circles the portal; every `decide` vanilla ticks it lands with chance 1 / (3 + crystals alive),
+ otherwise strafes the player with chance 1/2
+ strafe flies at the player; lined up with line of sight it charges a fireball for `windup` and fires
+ (also right after an end crystal is destroyed); the fireball leaves a dragon's breath cloud
+ landing descends onto the portal at the arena centre
+ scanning perched: turns to the player; a player within 20 blocks after 1.25 s -> roar (2 s) -> flaming
+ (3 s breath cloud under its head, Harming I); after 4 flames, or > 50 damage taken while perched, it
+ takes off; nobody within 20 blocks for 5 s -> charge
+ charge rushes the player's position, then returns to holding
+ Hits to the head deal full damage, body/wing hits damage / 4 + min(damage, 1); arrows bounce off a perched
+ dragon. The nearest end crystal heals 1 HP every 10 vanilla ticks; destroying the healing crystal deals 10.
+ Contact: the head deals ram_dmg, the wings wing_dmg and a shove, only while the dragon was not hurt within
+ the last 10 vanilla ticks. The model, arena and clouds are scaled down (34-block arena instead of the island).
+ """
+ TABLE = {
+ "hp": (150, 320, 1350), # TIER calibration for ~25 s / 1 min / 3 min (Java: 200 on every difficulty)
+ "speed": (0.40, 0.50, 0.60), # vanilla b/t cruise
+ "turn": (1.6, 2.2, 3.0), # rad/s
+ "ram_dmg": (6.0, 10.0, 15.0), # Java head contact easy / normal / hard
+ "wing_dmg": (3.5, 5.0, 7.5), # Java wing contact
+ "breath_dmg": (3.0, 3.0, 3.0), # Harming I per 20 vanilla ticks inside the perched breath
+ "cloud_dmg": (6.0, 6.0, 6.0), # Harming II per 20 vanilla ticks inside a fireball cloud
+ "cloud_s": (8.0, 10.0, 12.0), # APPROX fireball cloud life (Java 30 s, growing radius 3 -> 7)
+ "decide": (70, 50, 34), # vanilla ticks between holding-pattern decisions (path nodes)
+ "altitude": (9.0, 8.5, 8.0), # holding height above the floor
+ "windup": (0.55, 0.40, 0.25), # EXT fireball telegraph (Java fireball charge 5 ticks)
+ "bank": (24.0, 40.0, 58.0), # EXT roll into turns
+ "crystals": (2, 6, 8), # end crystals on the tallest towers (Java 10 on the island)
+ "crystal_blast": (43.5, 85.0, 127.5), # power-6 explosion peak damage (easy / normal / hard)
+ "land_base": (1.5, 3.0, 3.0), # landing chance per decision 1 / (land_base + crystals alive); Java 3
+ "fire_min": (12.0, 10.0, 8.0), # APPROX nearest fireball shot, blocks from mouth to chest
+ }
+ MOVES = {"fireball": {"atoms": ["projectile_linear", "area_cloud"], "telegraph": "lines up on you, mouth glows",
+ "damage": "cloud_dmg per second inside the purple cloud (magic: armor does not help)",
+ "range": "fired from up to 20 blocks with line of sight",
+ "punish": "after firing it returns to circling"},
+ "perch": {"atoms": ["phase_land", "cone_dot"], "telegraph": "lands on the portal, roars for 2 s",
+ "damage": "breath_dmg per second in the cloud under its head",
+ "range": "breath under the head, about 2 blocks around",
+ "punish": "arrows bounce off, but sword hits on the head deal full damage; > 50 damage makes it take off"},
+ "charge": {"atoms": ["charge_ram"], "telegraph": "after 5 s perched with nobody close it lifts and rushes",
+ "damage": "ram_dmg head contact, wing_dmg + shove from the wings",
+ "range": "body contact", "punish": "it flies past and climbs back to circling"},
+ "crystals": {"atoms": ["heal_source"], "telegraph": "a white beam from the nearest crystal",
+ "damage": "the crystal explodes when hit (power 6)",
+ "range": "on top of the towers", "punish": "breaking the healing crystal deals 10 to the flyer"}}
+ SKILLS = ("aim_tracking", "target_priority", "weapon_switch", "dodge_dive", "dps_windows", "reaction")
+ STATES = ("circle", "strafe", "perch", "charge")
+ COARSE = {"holding": "circle", "takeoff": "circle", "strafe": "strafe", "landing": "perch",
+ "scanning": "perch", "roar": "perch", "flaming": "perch", "charge": "charge"}
+ SITTING = ("scanning", "roar", "flaming")
+ name = "ender_dragon"
+ height = 1.6
+ hover = True
+ knockback = 0.0
+ half = (1.25, 1.25)
+ PERCH_Y = 1.7 # body centre above the portal floor while perched
+
+ @property
+ def aim_h(self):
+ return 0.0 # pos is already the body centre
+
+ def hit_lo(self):
+ return self.e.pos - [1.25, 0.6, 1.25]
+
+ def hit_hi(self):
+ return self.e.pos + [1.25, 0.6, 1.25]
+
+ def head_center(self):
+ drop = -0.95 if self.phase in self.SITTING else 0.25
+ return self.e.pos + self.e.fwd * 3.2 + [0.0, drop, 0.0]
+
+ def hitboxes(self):
+ h = self.head_center()
+ return [("head", h - [0.55, 0.45, 0.55], h + [0.55, 0.45, 0.55]),
+ ("body", self.hit_lo(), self.hit_hi())]
+
+ def in_reach(self, case):
+ return bool(np.linalg.norm(self.dist_to(case)) <= 3.4)
+
+ def reset(self, case):
+ super().reset(case)
+ self.max_hp = self.hp = self.k.hp
+ self.e = Entity(MID + 5.0, float(self.k.altitude), MID, math.pi, 2.6, self.height)
+ self.phase, self.state, self.timer, self.cd, self.iframes = "holding", "circle", 0.0, ticks(self.k.decide), 0
+ self.flap, self.bank, self.tint_t, self.hurt_t = 0.0, 0.0, 0, 0
+ self.phase_t, self.flames, self.sit_damage, self.orbit = 0, 0, 0.0, 1.0
+ self.fireballs, self.clouds, self.goal = [], [], None
+ self.heal_from, self.last_hurt = None, 0.0
+ self.crystals = self._place_crystals(case)
+ self.rig = dragon_rig()
+
+ def _place_crystals(self, case):
+ """End crystals on the tallest tower tops (deterministic from the seeded layout; no RNG)."""
+ H, tops = case.arena.H, []
+ for x in range(1, S - 1):
+ for z in range(1, S - 1):
+ h = int(H[x, z])
+ if h >= 4 and h >= H[x - 1:x + 2, z - 1:z + 2].max():
+ if all(abs(x - a) > 1 or abs(z - b) > 1 for a, b, _ in tops):
+ tops.append((x, z, h))
+ tops.sort(key=lambda t: (-t[2], t[0], t[1]))
+ return [{"id": i, "pos": np.array([x + 0.5, h + 1.0, z + 0.5]), "alive": True}
+ for i, (x, z, h) in enumerate(tops[:int(round(self.k.crystals))])]
+
+ @property
+ def crystals_alive(self):
+ return sum(c["alive"] for c in self.crystals)
+
+ @property
+ def enraged(self):
+ return self.crystals_alive == 0
+
+ def _go(self, case, phase, timer=0.0):
+ self.phase, self.state, self.timer, self.phase_t = phase, self.COARSE[phase], timer, 0
+ case.events.append(("dragon_phase", phase))
+
+ # -- damage --------------------------------------------------------------------------------------------
+ def take_hit(self, case, dmg, kind="normal", bonus_knockback=0.0, part="body"):
+ if kind.startswith("arrow") and self.phase in self.SITTING:
+ case.events.append("arrow_deflected")
+ return 0.0
+ if part != "head":
+ dmg = dmg / 4.0 + min(dmg, 1.0)
+ before = self.hp
+ amount = super().take_hit(case, dmg, kind if part == "head" else kind + "_body")
+ if amount > 0:
+ self.hurt_t = ticks(10)
+ if self.phase in self.SITTING:
+ self.sit_damage += before - self.hp
+ if self.sit_damage > 0.25 * self.max_hp:
+ self.sit_damage = 0.0
+ self._go(case, "takeoff", 2.0)
+ return amount
+
+ def crystal_destroyed(self, case, crystal):
+ crystal["alive"] = False
+ case.events.append(("crystal_destroyed", crystal["id"]))
+ p = case.body.e
+ r = float(np.linalg.norm(p.pos + [0, PLAYER_H / 2, 0] - crystal["pos"]))
+ impact = 1.0 - r / 12.0
+ if impact > 0:
+ exposure = 1.0 if case.arena.los(crystal["pos"], p.pos + [0, 1.0, 0], eye_h=0.0) else 0.25
+ dmg = self.k.crystal_blast * ((impact * impact + impact) / 2 * 84 + 1) / 85 * exposure
+ self.hurt_player(case, dmg, fling=0.5 * impact, origin=crystal["pos"])
+ if self.heal_from is crystal:
+ self.heal_from = None
+ super().take_hit(case, 10.0, "crystal")
+ self.hurt_t = ticks(10)
+ if self.phase == "holding":
+ self._go(case, "strafe", 6.0)
+
+ # -- flight ----------------------------------------------------------------------------------------------
+ def _fly(self, case, goal, speed, rate):
+ e = self.e
+ to = goal - e.pos
+ want = math.atan2(to[2], to[0])
+ d = (want - e.yaw + math.pi) % (2 * math.pi) - math.pi
+ turn = float(np.clip(d, -rate, rate))
+ e.yaw = (e.yaw + turn) % (2 * math.pi)
+ self.bank = float(np.clip(-math.degrees(turn * FPS) * 45 / 400, -self.k.bank, self.k.bank))
+ horiz = np.hypot(to[0], to[2])
+ step = e.fwd * min(speed, horiz + 0.02) if horiz > 0.05 else np.zeros(3)
+ e.vel[1] = float(np.clip(to[1] * gain(0.12), per_vt(-0.45), per_vt(0.45)))
+ new = e.pos + step
+ if case.arena.ground(new, 2.2) > new[1] - 0.6 and self.phase not in ("landing",) + self.SITTING:
+ e.vel[1] = per_vt(0.45) # climb over a tower instead of flying through it
+ new = e.pos.copy()
+ e.pos[[0, 2]] = new[[0, 2]]
+ e.pos[1] = float(np.clip(e.pos[1] + e.vel[1], 1.0, 16.0))
+ return float(np.linalg.norm(goal - e.pos)), abs(d)
+
+ def update(self, case):
+ k, e, p = self.k, self.e, case.body.e
+ self.iframes, self.tint_t = max(self.iframes - 1, 0), max(self.tint_t - 1, 0)
+ self.hurt_t = max(self.hurt_t - 1, 0)
+ self.cd = max(self.cd - 1, 0)
+ self.timer -= 1 / FPS
+ self.phase_t += 1
+ rate, speed = k.turn / FPS, per_vt(k.speed)
+ centre = np.array([MID, 0.0, MID])
+ self._heal(case)
+ self._projectiles(case)
+ if self.phase == "holding":
+ radial = e.pos - centre
+ radial[1] = 0.0
+ ang = math.atan2(radial[2], radial[0]) + 0.9 * self.orbit
+ goal = centre + [math.cos(ang) * 10.5, k.altitude, math.sin(ang) * 10.5]
+ self._fly(case, goal, speed, rate)
+ if self.cd == 0:
+ self.cd = ticks(k.decide)
+ # Java: nextInt(3 + crystals alive) == 0 lands; land_base is that 3 (BossBench easy perches sooner)
+ if case.rng.random() * (k.land_base + self.crystals_alive) < 1.0:
+ self._go(case, "landing", 8.0)
+ elif case.rng.random() < 0.5:
+ self._go(case, "strafe", 6.0)
+ elif self.phase == "strafe":
+ goal = p.pos + [0.0, 5.0, 0.0]
+ dist, err = self._fly(case, goal, speed, rate * 1.2)
+ flat = float(np.hypot(*(p.pos - e.pos)[[0, 2]]))
+ aim = math.atan2((p.pos - e.pos)[2], (p.pos - e.pos)[0])
+ facing = abs((aim - e.yaw + math.pi) % (2 * math.pi) - math.pi) < math.radians(15)
+ mouth = e.pos + e.fwd * 3.6
+ if facing and flat < 20.0 and case.arena.los(mouth, p.pos + [0, 1.0, 0], eye_h=0.0):
+ if self.goal is None:
+ self.goal = case.t + ticks(20 * k.windup)
+ case.events.append("dragon_lineup")
+ elif case.t >= self.goal:
+ if float(np.linalg.norm(p.pos + [0, 0.9, 0] - mouth)) >= k.fire_min:
+ self._fireball(case, mouth, p.pos + [0, 0.9, 0])
+ self.goal = None
+ self._go(case, "holding")
+ self.orbit = -self.orbit
+ else:
+ # Java's dragon breaks off a strafe within 10 blocks of its target, so its fireballs come
+ # from across the island. The scaled arena would let it fire point-blank (a cloud nobody can
+ # outrun: found 2026-11-02), so a too-close shot is called off and the lineup starts over.
+ self.goal = None
+ case.events.append("dragon_hold_fire")
+ if self.phase == "strafe" and (self.timer <= 0 or flat < 3.0):
+ self.goal = None
+ self._go(case, "holding")
+ elif self.phase == "landing":
+ perch = centre + [0.0, self.PERCH_Y, 0.0]
+ flat = float(np.hypot(*(perch - e.pos)[[0, 2]]))
+ goal = perch + [0.0, min(6.0, flat * 0.5), 0.0]
+ self._fly(case, goal, speed * (0.6 if flat < 6 else 1.0), rate * 1.5)
+ if flat < 0.6 and e.pos[1] - perch[1] < 0.4 or self.timer <= 0:
+ e.pos[:] = perch
+ e.vel[:] = 0.0
+ self.flames, self.sit_damage = 0, 0.0
+ self._go(case, "scanning")
+ elif self.phase in self.SITTING:
+ to = p.pos - e.pos
+ want = math.atan2(to[2], to[0])
+ d = (want - e.yaw + math.pi) % (2 * math.pi) - math.pi
+ e.yaw = (e.yaw + float(np.clip(d, -rate * 0.6, rate * 0.6))) % (2 * math.pi)
+ self.bank = 0.0
+ near = float(np.hypot(*(p.pos - centre)[[0, 2]])) <= 20.0
+ if self.phase == "scanning":
+ if near and self.phase_t >= ticks(25) and abs(d) < math.radians(20):
+ self._go(case, "roar")
+ case.events.append("dragon_roar")
+ elif self.phase_t >= ticks(100):
+ self.goal = p.pos.copy() + [0, 1.0, 0]
+ self._go(case, "charge", 4.0)
+ elif self.phase == "roar" and self.phase_t >= ticks(40):
+ self._go(case, "flaming")
+ c = self.head_center()
+ g = case.arena.ground(c, 0.6)
+ self.clouds.append({"pos": np.array([c[0], g, c[2]]) + self.e.fwd * 1.2, "r": 2.0, "dmg": k.breath_dmg,
+ "life": 3.0, "life0": 3.0, "kind": "breath", "next": {}})
+ elif self.phase == "flaming" and self.phase_t >= ticks(60):
+ self.flames += 1
+ if self.flames >= 4:
+ self._go(case, "takeoff", 2.5)
+ else:
+ self._go(case, "scanning")
+ elif self.phase == "takeoff":
+ out = e.pos - centre
+ out[1] = 0.0
+ out = out / (np.linalg.norm(out) + 1e-6) if np.linalg.norm(out) > 0.5 else e.fwd
+ goal = centre + out * 10.0 + [0, k.altitude, 0]
+ self._fly(case, goal, speed * 0.7, rate)
+ if self.timer <= 0:
+ self.cd = ticks(k.decide)
+ self._go(case, "holding")
+ elif self.phase == "charge":
+ dist, _ = self._fly(case, self.goal, speed * 1.8, rate * 2.0)
+ if dist < 1.5 or self.timer <= 0:
+ self.goal = None
+ self.cd = ticks(k.decide)
+ self._go(case, "holding")
+ self._contact(case)
+ self.flap = (self.flap + (per_vt(0.35) + speed) * 0.55 * (0.2 if self.phase in self.SITTING else 1.0)) % 1.0
+ self.pose(case)
+
+ def _heal(self, case):
+ alive = [c for c in self.crystals if c["alive"]]
+ if self.heal_from is not None and not self.heal_from["alive"]:
+ self.heal_from = None
+ if self.heal_from is None and alive and case.rng.random() < 1 - 0.9 ** VT:
+ self.heal_from = min(alive, key=lambda c: float(np.linalg.norm(c["pos"] - self.e.pos)))
+ if self.heal_from is not None and case.t % ticks(10) == 0 and self.hp < self.max_hp:
+ self.hp = min(self.max_hp, self.hp + 1.0)
+
+ def _contact(self, case):
+ """Java aiStep: head/neck hurt and wing shove, only while hurtTime == 0."""
+ if self.hurt_t > 0:
+ return
+ p = case.body.e
+ lo, hi = p.pos - [0.3, 0.0, 0.3], p.pos + [0.3, PLAYER_H, 0.3]
+ h = self.head_center()
+ if np.all(hi >= h - 1.55) and np.all(lo <= h + 1.55):
+ if self.hurt_player(case, self.k.ram_dmg, fling=0.6, origin=h):
+ case.events.append("dragon_ram")
+ return
+ if self.phase in self.SITTING:
+ return
+ b = self.e.pos
+ flat = float(np.hypot(*(p.pos - b)[[0, 2]]))
+ if flat < 3.2 and -2.5 < p.pos[1] + 0.9 - b[1] < 1.0:
+ if self.hurt_player(case, self.k.wing_dmg, fling=1.0, origin=b):
+ p.vel[1] = vy_sim(0.2 + 0.2)
+ p.on_ground = False
+ case.events.append("dragon_wing")
+
+ # -- fireballs and clouds --------------------------------------------------------------------------------
+ def _fireball(self, case, start, target):
+ direction = np.asarray(target, float) - start
+ direction /= float(np.linalg.norm(direction)) + 1e-9
+ self.fireballs.append({"pos": start.copy(), "vel": direction * per_vt(0.1), "dir": direction, "life": 8.0})
+ case.events.append("dragon_fireball")
+
+ def _projectiles(self, case):
+ p, keep = case.body.e, []
+ lo, hi = p.pos - [0.45, 0.15, 0.45], p.pos + [0.45, PLAYER_H + 0.15, 0.45]
+ F = decay(0.95)
+ for f in self.fireballs:
+ f["vel"] = f["vel"] * F + f["dir"] * per_vt(1.9) * (1 - F)
+ start, end = f["pos"], f["pos"] + f["vel"]
+ f["life"] -= 1 / FPS
+ hp_ = _segment_box(start, end, lo, hi)
+ hw, _ = case._arrow_world_hit(start, end)
+ if hp_ is not None or hw is not None or f["life"] <= 0:
+ u = min(x for x in (hp_, hw, 1.0) if x is not None)
+ at = start + (end - start) * u
+ g = case.arena.ground(at, 0.2)
+ self.clouds.append({"pos": np.array([at[0], g, at[2]]), "r": 3.0, "dmg": self.k.cloud_dmg,
+ "life": self.k.cloud_s, "life0": self.k.cloud_s, "kind": "fireball", "next": {}})
+ case.events.append("dragon_cloud")
+ continue
+ f["pos"] = end
+ keep.append(f)
+ self.fireballs = keep
+ alive = []
+ for c in self.clouds:
+ c["life"] -= 1 / FPS
+ if c["kind"] == "fireball":
+ c["r"] = 3.0 + 1.0 * (1 - c["life"] / c["life0"])
+ if c["life"] <= 0:
+ continue
+ inside = float(np.hypot(*(p.pos - c["pos"])[[0, 2]])) <= c["r"] and -0.5 < p.pos[1] - c["pos"][1] < 1.5
+ if inside and case.t >= c["next"].get("p", 0):
+ c["next"]["p"] = case.t + ticks(20)
+ if self.hurt_player(case, c["dmg"], armor=False):
+ case.events.append("dragon_breath")
+ alive.append(c)
+ self.clouds = alive
+
+ def extra(self, case):
+ return []
+
+ def pose(self, case):
+ mcskin.pose_dragon(self, case)
+
+ def fx(self, case):
+ return [] # breath and ender particles: mcskin.fx_ambient
+
+
+class Wither(Mob):
+ """Java Edition 1.21 wither (minecraft.wiki/w/Wither, read 2026-11-01).
+
+ spawn 220 vanilla ticks of invulnerable charging (health bar fills), then a power-7 blast at its body
+ hover above half health: keeps its feet 5 blocks over the target and flies to within 3 blocks
+ horizontally; the main head fires a wither skull every 40 vanilla ticks with line of sight, each
+ side head 40-59 ticks after its last shot; an idle side head (counter > 15, +3 per hit taken,
+ Normal/Hard) lobs a slow blue skull at a random spot
+ armored at or below half health: wither armor makes it immune to arrows and it comes down to the
+ target's height (melee range); the armor goes away if it regenerates above half
+ nolos no line of sight from the main head: it stops firing and closes in
+ Regenerates 1 HP every 20 vanilla ticks; a damaged wither breaks the blocks of a 3x4x3 box around itself
+ 20 ticks later (the arena wall is immune). There is no dash in Java (the dash is Bedrock-only).
+ Black skulls accelerate 0.1 b/t^2 with inertia 0.95 (terminal 1.9 b/t), blue skulls inertia 0.73
+ (terminal 0.27 b/t). A hit deals skull_dmg (armor applies) and Wither II; the power-1 explosion
+ deals up to blast_dmg within 2 blocks.
+ """
+ TABLE = {
+ "hp": (100, 250, 600), # TIER calibration for ~25 s / 1 min / 3 min (Java: 300 on every difficulty)
+ "regen": (0.5, 1.0, 1.0), # HP per 20 vanilla ticks (Java 1)
+ "altitude": (4.0, 5.0, 5.0), # phase 1: feet above the target's feet (Java 5)
+ "speed": (0.30, 0.43, 0.43), # vanilla b/t approach when > 3 blocks away (Java ~0.43 steady)
+ "skull_dmg": (5.0, 8.0, 12.0), # Java Easy / Normal / Hard
+ "blast_dmg": (3.5, 5.0, 7.5), # power-1 skull explosion at its centre (scaled with the skull)
+ "wither_s": (0.0, 10.0, 40.0), # Wither II seconds (Java Easy none, Normal 10, Hard 40)
+ "cd_main": (60, 40, 40), # vanilla ticks between main-head skulls (Java 40; easy slower)
+ "cd_side": (100, 40, 40), # side head pause after a shot, + 0-19 (Java 40-59; easy slower)
+ "blue_idle": (1e9, 15, 15), # side-head idle counter limit for blue skulls (Normal/Hard only)
+ "spawn_blast": (35.5, 69.0, 103.5), # power-7 spawn explosion peak damage (Java easy / normal / hard)
+ }
+ MOVES = {"shell": {"atoms": ["projectile_linear", "explosion_small", "dot_drain"],
+ "telegraph": "a head turns to the player; black shells fly fast, blue shells slowly",
+ "damage": "shell damage (armor) + black-heart drain; explosion up to blast damage within 2 blocks",
+ "range": "main head 40 ticks, side heads 40-59 ticks, line of sight needed",
+ "punish": "break line of sight with cover; it stops firing"},
+ "spawn": {"atoms": ["charge_invulnerable", "explosion_large"],
+ "telegraph": "11 s of flickering blue while its health bar fills",
+ "damage": "spawn_blast at the centre, falling to 0 at 14 blocks (armor applies)",
+ "range": "power 7 (14 blocks)", "punish": "run far away before the blast"},
+ "armor": {"atoms": ["phase_shield"], "telegraph": "a translucent armor shell at half health",
+ "damage": "-", "range": "arrows bounce off; it descends to melee height",
+ "punish": "switch to the sword (hotbar) and fight it on the ground"}}
+ SKILLS = ("projectile_dodge", "cover_use", "weapon_switch", "aim_tracking", "spacing", "reaction")
+ STATES = ("spawn", "hover", "armored", "nolos")
+ name = "wither"
+ height, reach, reach_up, aim_h = 3.5, 3.0, 3.0, 0.0
+ half = (0.45, 0.45)
+ hover = True
+ knockback = 0.0
+ armor = 4.0
+ FEET = 1.5 # pos is the chest: hitbox [pos - 1.5, pos + 2.0], 0.9 wide
+ SPAWN_TICKS = 220 # vanilla ticks
+
+ def reset(self, case):
+ super().reset(case)
+ self.max_hp = float(self.k.hp)
+ self.hp = self.max_hp / 3 # Java: the bar fills during the spawn charge
+ p = case.body.e
+ self.e = Entity(MID + 4.0, self.FEET + 0.0, MID, math.pi, 0.9, self.height)
+ self.state, self.timer, self.cd, self.iframes = "spawn", self.SPAWN_TICKS / 20, ticks(self.k.cd_main), 0
+ self.side_next, self.idle = [ticks(20), ticks(30)], [0, 0]
+ self.skulls, self.tint_t, self.tilt, self.guard = [], 0, 0.0, 0.0
+ self.blocks_t, self.shots, self.blue_shots, self.last_hurt = -1, 0, 0, 0.0
+ self.armored = False
+ self.rig = wither_rig()
+
+ @property
+ def enraged(self):
+ return self.armored
+
+ def hit_lo(self):
+ return self.e.pos - [self.half[0], self.FEET, self.half[1]]
+
+ def hit_hi(self):
+ return self.e.pos + [self.half[0], self.height - self.FEET, self.half[1]]
+
+ def in_reach(self, case):
+ return bool(np.linalg.norm(self.dist_to(case)) <= 3.6)
+
+ def immune(self, case, kind):
+ if self.state == "spawn":
+ return True
+ return self.armored and kind.startswith("arrow")
+
+ def on_hurt(self, case, amount, kind):
+ self.idle = [i + 3 for i in self.idle]
+ if self.blocks_t < 0:
+ self.blocks_t = ticks(20)
+
+ def head_pos(self, i):
+ side = (0.0, -0.85, 0.85)[i]
+ return self.e.pos + [0.0, 1.05 - (0.1 if i else 0.0), 0.0] + self.e.right * side
+
+ def update(self, case):
+ k, e, p = self.k, self.e, case.body.e
+ self.iframes, self.tint_t = max(self.iframes - 1, 0), max(self.tint_t - 1, 0)
+ self.cd = max(self.cd - 1, 0)
+ self.timer = max(self.timer - 1 / FPS, 0.0)
+ self._skulls(case)
+ flat = np.array([p.pos[0] - e.pos[0], 0.0, p.pos[2] - e.pos[2]])
+ dist = float(np.linalg.norm(flat))
+ e.yaw = math.atan2(flat[2], flat[0])
+ if self.state == "spawn":
+ self.hp = min(self.max_hp, self.hp + self.max_hp * 2 / 3 / ticks(self.SPAWN_TICKS))
+ e.vel[:] = 0.0
+ if self.timer <= 0:
+ self.hp = self.max_hp
+ self._explode(case, e.pos, 7.0, k.spawn_blast, fling=1.2, name="wither_spawn_blast")
+ self.state = "hover"
+ self.pose(case)
+ return
+ if case.t % ticks(20) == 0 and self.hp < self.max_hp:
+ self.hp = min(self.max_hp, self.hp + k.regen)
+ if self.blocks_t >= 0:
+ self.blocks_t -= 1
+ if self.blocks_t < 0:
+ self._break_blocks(case)
+ self.armored = self.hp <= self.max_hp / 2
+ main = self.head_pos(0)
+ target = p.pos + [0, PLAYER_H * 0.45, 0]
+ sees = case.arena.los(main, target, eye_h=0.0)
+ self.state = "armored" if self.armored else "hover"
+ if not sees:
+ self.state = "nolos"
+ # -- movement: Java WitherBoss.aiStep, per vanilla tick converted to the simulation tick ----------
+ feet, goal = e.pos[1] - self.FEET, p.pos[1] + (0.0 if self.armored else k.altitude)
+ if feet < goal:
+ e.vel[1] = max(e.vel[1], 0.0)
+ e.vel[1] += (per_vt(0.3) - e.vel[1]) * gain(0.6)
+ elif self.armored and feet > goal + 0.25:
+ e.vel[1] += (per_vt(-0.15) - e.vel[1]) * gain(0.4)
+ else:
+ e.vel[1] *= decay(0.546)
+ if dist > 3.0 or (not sees and dist > 1.0):
+ e.vel[[0, 2]] += (flat[[0, 2]] / (dist + 1e-6) * per_vt(k.speed) - e.vel[[0, 2]]) * gain(0.636)
+ else:
+ e.vel[[0, 2]] *= decay(0.91)
+ new = e.pos + e.vel
+ if case.arena.ground(new, e.w) <= new[1] - self.FEET + 0.05:
+ e.pos[[0, 2]] = new[[0, 2]]
+ else: # flying pathing: rise over the column instead of stalling at it
+ e.vel[[0, 2]] *= decay(0.5)
+ e.vel[1] = max(e.vel[1], per_vt(0.3))
+ new[1] = e.pos[1] + e.vel[1]
+ floor = case.arena.ground(e.pos, e.w) + self.FEET
+ e.pos[1] = float(np.clip(new[1], floor, 16.0))
+ # -- heads -------------------------------------------------------------------------------------------
+ if sees and self.cd == 0 and float(np.linalg.norm(target - main)) <= 20.0:
+ self._fire(case, 0, target, blue=bool(case.rng.random() < 0.001))
+ self.cd = ticks(k.cd_main)
+ for i in (0, 1):
+ if case.t < self.side_next[i]:
+ continue
+ self.side_next[i] = case.t + ticks(10 + int(case.rng.integers(0, 10)))
+ if k.blue_idle < 1e8:
+ count, self.idle[i] = self.idle[i], self.idle[i] + 1
+ if count > k.blue_idle:
+ spot = np.array([e.pos[0] + case.rng.normal(0, 6.0), 0.0, e.pos[2] + case.rng.normal(0, 6.0)])
+ self._fire(case, i + 1, spot, blue=True)
+ self.idle[i] = 0
+ head = self.head_pos(i + 1)
+ if case.arena.los(head, target, eye_h=0.0) and float(np.linalg.norm(target - head)) <= 30.0:
+ self._fire(case, i + 1, target)
+ self.side_next[i] = case.t + ticks(k.cd_side + int(case.rng.integers(0, 20)))
+ self.idle[i] = 0
+ self.pose(case)
+
+ # -- projectiles and explosions ---------------------------------------------------------------------
+ def _fire(self, case, head, target, blue=False):
+ start = self.head_pos(head)
+ aim = np.asarray(target, float) - start
+ direction = aim / (float(np.linalg.norm(aim)) + 1e-9)
+ self.shots += 1
+ self.skulls.append({"pos": start + direction * 0.4, "vel": direction * per_vt(0.1), "dir": direction,
+ "blue": bool(blue), "life": 12.0, "head": int(head), "n": self.shots})
+ self.blue_shots += int(blue)
+ case.events.append(("wither_fire", int(head), "blue" if blue else "black"))
+
+ def _explode(self, case, at, power, peak, fling=0.0, name="explosion"):
+ """Java explosion falloff (impact = 1 - r / 2 power) scaled so the centre deals `peak`; armor applies."""
+ p = case.body.e
+ r = float(np.linalg.norm(p.pos + [0, PLAYER_H / 2, 0] - at))
+ impact = 1.0 - r / (2.0 * power)
+ case.events.append((name, round(r, 2), [round(float(v), 2) for v in at]))
+ if impact <= 0:
+ return False
+ dmg = peak * ((impact * impact + impact) / 2 * 7 * 2 * power + 1) / (7 * 2 * power + 1)
+ return self.hurt_player(case, dmg, fling=fling * impact, origin=at)
+
+ def _skulls(self, case):
+ p, keep = case.body.e, []
+ lo, hi = p.pos - [PLAYER_W / 2 + 0.16, 0.16, PLAYER_W / 2 + 0.16], p.pos + [PLAYER_W / 2 + 0.16, PLAYER_H + 0.16, PLAYER_W / 2 + 0.16]
+ for s in self.skulls:
+ inertia = 0.73 if s["blue"] else 0.95
+ F = decay(inertia)
+ s["vel"] = s["vel"] * F + s["dir"] * per_vt(0.1 * inertia / (1 - inertia)) * (1 - F)
+ start, end = s["pos"], s["pos"] + s["vel"]
+ s["life"] -= 1 / FPS
+ hit_player = _segment_box(start, end, lo, hi)
+ hit_world, reason = case._arrow_world_hit(start, end)
+ if hit_player is not None and (hit_world is None or hit_player <= hit_world):
+ at = start + (end - start) * hit_player
+ if self.hurt_player(case, self.k.skull_dmg, fling=0.3, origin=at):
+ if self.k.wither_s > 0:
+ case.body.wither_t = max(case.body.wither_t, ticks(20 * self.k.wither_s))
+ case.events.append("skull_hit")
+ self._explode(case, at, 1.0, self.k.blast_dmg, name="skull_blast")
+ continue
+ if hit_world is not None:
+ at = start + (end - start) * hit_world
+ case.events.append(("skull_ground", reason))
+ self._explode(case, at, 1.0, self.k.blast_dmg, name="skull_blast")
+ continue
+ s["pos"] = end
+ if s["life"] <= 0 or end[1] > 30:
+ continue
+ keep.append(s)
+ self.skulls = keep
+
+ def _break_blocks(self, case):
+ """Java: 20 ticks after damage, blocks in x/z +-1, y floor(feet)..+3 around the wither break (not the wall)."""
+ H, e = case.arena.H, self.e
+ base = int(math.floor(e.pos[1] - self.FEET))
+ broke = 0
+ for x in range(int(e.pos[0]) - 1, int(e.pos[0]) + 2):
+ for z in range(int(e.pos[2]) - 1, int(e.pos[2]) + 2):
+ if not (1 <= x < S - 1 and 1 <= z < S - 1):
+ continue # the arena wall is wither-immune (bedrock-like)
+ if base < H[x, z] <= base + 4:
+ H[x, z] = max(base, 0)
+ broke += 1
+ if broke:
+ case.events.append(("wither_break", broke))
+
+ def extra(self, case):
+ return [{"pos": s["pos"], "size": (0.32, 0.32, 0.32), "color": (0.2, 0.18, 0.22), "blue": s["blue"]}
+ for s in self.skulls]
+
+ def fx(self, case):
+ return [] # skull smoke and aura: mcskin.fx_ambient
+
+ def pose(self, case):
+ mcskin.pose_wither(self, case)
+
+
+class Warden(Mob):
+ """Java Edition 1.21 warden (minecraft.wiki/w/Warden, read 2026-11-02), as a fight in the deep dark.
+
+ emerge it climbs out of the floor (Java ~6.7 s; arena 3 s), invulnerable except to /kill
+ roar 4.2 s roar before the chase (Java: when anger reaches 80; skipped when attacked from within 5 blocks)
+ chase melee: Java 16 / 30 / 45 per hit (armor applies), 36-tick cooldown, disables a raised shield; a warden
+ is never knocked back. It walks at a player's pace, so out-walking it is not an option, but it
+ pivots slowly after a missed swing (the 'opening').
+ boom sonic boom when it cannot reach its target (Java: a pillar perch or across a gap): 1.7 s charge, then a
+ hit that ignores armor, shields and walls (Java 6 / 10 / 15) with knockback; 1.3 s recovery; in Java it
+ needs 5 s since its last attack. Range 15 horizontal / 20 vertical.
+ darkness every 6 s, 13 s of Darkness within 20 blocks (Java; visual only here: the screen dims in pulses)
+ Java's anger and sniffing decide *who* it hunts; a one-on-one arena gives it the player from the start.
+
+ BossBench deviations (minecraft-arena@5): health per tier (Java 500 on every difficulty); the sonic boom also fires
+ when the player has merely stayed out of melee reach for boom_every seconds (Java: when the target is unreachable,
+ 5 s after its last attack), so kiting in the open is answered as Java answers a pillar perch. The tiers span Java
+ Easy to Java *Normal* damage: Java Hard's 45-damage smash leaves 29 after unenchanted diamond armor, more than a
+ full 20-HP bar, so a three-minute hard tier would be a single-mistake test (Java players fight wardens in enchanted
+ netherite, which this arena does not model). Hard keeps every other Java Hard trait: 36-tick cooldown, 4.2 s roar.
+ """
+ TABLE = { # (easy, normal, hard) = TIERS
+ "hp": (260, 820, 2100), # TIER calibration (Java 500 on every difficulty)
+ "speed": (0.22, 0.26, 0.286), # vanilla b/t chase; Java 0.286 = attribute 0.3 x 1.2 (SPEED_NOTE),
+ # a sprinting player's pace (walk 0.216, sprint 0.281)
+ "dmg": (16.0, 23.0, 30.0), # melee before armor: Java Easy 16, midway, Java Normal 30 (see below)
+ "cooldown": (44, 40, 36), # vanilla ticks between swings (Java 36)
+ "windup": (0.80, 0.65, 0.55), # EXT raised-arms telegraph: long enough to back out of its attack box
+ # from contact range (it out-walks a backpedalling player)
+ "boom_dmg": (6.0, 8.0, 10.0), # sonic boom, ignores armor: Java Easy 6, midway, Java Normal 10
+ "boom_every": (9.0, 7.0, 5.0), # seconds out of reach before a boom (Java: 5 s since the last attack)
+ "emerge_s": (3.0, 3.0, 3.0), # APPROX (Java ~6.7 s)
+ "roar_s": (2.0, 3.0, 4.2), # EXT on easy / normal (Java 4.2 s)
+ }
+ MOVES = {"smash": {"atoms": ["melee_single"], "telegraph": "arms raised, chest glowing",
+ "damage": "16 / 23 / 30 then armor (Java 16 / 30 / 45)", "range": "attack box 0.83 around its body",
+ "punish": "36-44 tick cooldown; it keeps walking, so back off between swings"},
+ "shockwave": {"atoms": ["ranged_hitscan"], "telegraph": "1.7 s charge: chest lights, rings gather",
+ "damage": "6 / 8 / 10 (Java 6 / 10 / 15), ignores armor and walls, knocks back",
+ "range": "15 blocks horizontally, 20 vertically",
+ "punish": "1.3 s recovery after the boom; the timer only runs while you stay out of reach"},
+ "vision_dim": {"atoms": ["vision_dot"], "telegraph": "a heartbeat pulse", "damage": "-",
+ "range": "20 blocks", "punish": "-"}}
+ SKILLS = ("spacing", "attack_timing", "reaction", "resource_management", "terrain_use")
+ STATES = ("emerge", "chase", "windup", "boom")
+ name = "warden"
+ height, aim_h = 2.9, 1.45
+ half = (0.45, 0.45)
+ knockback = 0.0
+
+ def reset(self, case):
+ super().reset(case)
+ self.max_hp = self.hp = self.k.hp
+ self.e = Entity(MID + 6.0, 0.0, MID, math.pi, 0.9, self.height)
+ self.state, self.timer, self.cd, self.iframes = "emerge", float(self.k.emerge_s), 0, 0
+ self.phase = "emerge"
+ self.ph, self.tint_t = 0.0, 0
+ self.out_of_reach = 0 # sim ticks the player has spent out of melee reach
+ self.boom_cd = 0
+ self.dark_t = 0
+ self.booms = 0
+ self.rig = warden_rig()
+
+ @property
+ def enraged(self):
+ return False
+
+ def in_reach(self, case):
+ """Java 1.20.2+ attack box, plus the warden's vertical reach of 2 blocks (22w16a lowered it from 3): a player
+ standing more than 2 blocks above its feet is out of reach even while it jumps against the block below - the
+ perch its sonic boom exists for. APPROX: measured feet to feet."""
+ if case.body.e.pos[1] - self.e.pos[1] > 2.0:
+ return False
+ return super().in_reach(case)
+
+ def immune(self, case, kind):
+ return self.phase == "emerge" # Java: only /kill hurts an emerging warden
+
+ def on_hurt(self, case, amount, kind):
+ if self.phase == "roar" and float(np.linalg.norm(case.body.e.pos - self.e.pos)) <= 5.0:
+ self._go(case, "chase") # Java: attacked from within 5 blocks, it skips the roar
+
+ def _go(self, case, phase, timer=0.0):
+ self.phase, self.timer = phase, timer
+ self.state = {"emerge": "emerge", "roar": "emerge", "chase": "chase", "windup": "windup",
+ "smash": "windup", "recover": "chase", "boom": "boom", "boom_recover": "boom"}[phase]
+ case.events.append(("warden_phase", phase))
+
+ def update(self, case):
+ k, e, p = self.k, self.e, case.body.e
+ self.iframes, self.cd = max(self.iframes - 1, 0), max(self.cd - 1, 0)
+ self.boom_cd = max(self.boom_cd - 1, 0)
+ self.tint_t = max(self.tint_t - 1, 0)
+ self.timer -= 1 / FPS
+ if case.t % ticks(120) == 0: # Java: Darkness to players within 20 blocks every 6 s
+ if float(np.linalg.norm(p.pos - e.pos)) <= 20.0:
+ self.dark_t = ticks(260)
+ case.events.append("warden_darkness")
+ self.dark_t = max(self.dark_t - 1, 0)
+ to = p.pos - e.pos
+ flat = float(math.hypot(to[0], to[2]))
+ wish, speed = np.zeros(3), 0.0
+ reach = self.in_reach(case)
+ if self.phase == "emerge":
+ if self.timer <= 0:
+ self._go(case, "roar", float(k.roar_s))
+ case.events.append("warden_roar")
+ elif self.phase == "roar":
+ e.yaw = math.atan2(to[2], to[0])
+ if self.timer <= 0:
+ self._go(case, "chase")
+ elif self.phase in ("chase", "recover"):
+ wish = self.steer(case)
+ e.yaw = math.atan2(wish[2], wish[0]) if wish.any() else e.yaw
+ speed = k.speed * (0.45 if self.phase == "recover" else 1.0)
+ self.out_of_reach = 0 if reach else self.out_of_reach + 1
+ if self.phase == "recover" and self.timer <= 0:
+ self.phase = "chase"
+ if self.cd == 0 and reach:
+ self._go(case, "windup", max(0.05, float(k.windup)))
+ case.events.append("warden_windup")
+ elif (self.boom_cd == 0 and self.out_of_reach >= ticks(20 * k.boom_every)
+ and flat <= 15.0 and abs(to[1]) <= 20.0):
+ self._go(case, "boom", 1.7)
+ case.events.append("warden_boom_charge")
+ elif self.phase == "windup":
+ e.yaw = math.atan2(to[2], to[0])
+ speed = k.speed * 0.2
+ wish = e.fwd
+ if self.timer <= 0:
+ if self.in_reach(case):
+ if self.hurt_player(case, k.dmg, fling=0.5):
+ case.events.append("warden_smash")
+ else:
+ case.events.append("warden_whiff")
+ self.cd = ticks(k.cooldown)
+ self.out_of_reach = 0
+ self._go(case, "recover", 0.6) # turns slowly after a swing: the opening
+ elif self.phase == "boom":
+ e.yaw = math.atan2(to[2], to[0])
+ if self.timer <= 0:
+ self.booms += 1
+ if flat <= 15.0 and abs(to[1]) <= 20.0:
+ # Java: lands at once if the target is still in range; ignores armor, shields and walls
+ if self.hurt_player(case, k.boom_dmg, fling=1.2, armor=False, lift=0.1):
+ case.events.append("warden_boom_hit")
+ else:
+ case.events.append("warden_boom_miss")
+ self.out_of_reach, self.boom_cd = 0, ticks(20 * 5)
+ self._go(case, "boom_recover", 1.3)
+ elif self.phase == "boom_recover":
+ if self.timer <= 0:
+ self._go(case, "chase")
+ if flat < 0.6:
+ wish = 0 * wish
+ blocked, _ = physics(case, e, wish, speed, step=0.0)
+ if blocked and e.on_ground:
+ e.vel[1] = JUMP
+ self.ph = (self.ph + float(math.hypot(e.vel[0], e.vel[2])) * 0.7) % 1.0
+ self.pose(case)
+
+ def pose(self, case):
+ mcskin.pose_warden(self, case)
+
+
+class Skeleton(Mob):
+ """Java Edition 1.21 skeleton (minecraft.wiki/w/Skeleton, read 2026-11-02) as a boss: an armoured archer in ruins.
+
+ It keeps its distance and circles: it backs off when the player comes within 4 blocks, strafes around at mid range
+ (switching direction now and then) and closes in when the player is 14+ blocks away. With line of sight within
+ 15 blocks it draws (visible: bow up, string back) and fires; Java fires every 3 s on Easy / Normal and every 2 s on
+ Hard, aims 0.2 blocks higher per block of range and has an arrow 'error' of 10 / 6 / 2 (the player's is 1).
+ Arrows are real projectiles (gravity, drag, stopped by terrain): side-stepping and cover work. Java arrow damage
+ 2-4 / 3-5 / 4-8. It has no melee while it holds its bow.
+
+ BossBench deviations (minecraft-arena@5): health per tier (Java 20); it wears armor (iron on easy / normal pieces,
+ Java's armor-spawn chances made certain) so that the fight lasts; its draw time is a telegraph knob.
+ """
+ TABLE = { # (easy, normal, hard) = TIERS
+ "hp": (200, 500, 1050), # TIER calibration (Java 20)
+ "speed": (0.12, 0.138, 0.16), # vanilla b/t; Java 0.138 = attribute 0.25 (SPEED_NOTE); strafes at half
+ "interval": (60, 60, 40), # vanilla ticks between shots (Java 3 s / 3 s / 2 s)
+ "draw": (1.0, 0.85, 0.7), # EXT seconds of visible draw before the release
+ "error": (10.0, 6.0, 2.0), # Java arrow inaccuracy (player 1)
+ "arrow_min": (2.0, 3.0, 4.0), # Java arrow damage range per difficulty
+ "arrow_max": (4.0, 5.0, 8.0),
+ "armor": (8.0, 12.0, 15.0), # worn iron pieces (Java armor-spawn chance made certain): helmet +
+ # chestplate / + leggings / full set
+ }
+ MOVES = {"arrow": {"atoms": ["projectile_arc"], "telegraph": "bow raised and drawn back for most of a second",
+ "damage": "Java 2-4 / 3-5 / 4-8 then armor", "range": "up to 15 blocks with line of sight",
+ "punish": "3 s (2 s on hard) between shots; arrows fly in an arc and stop on walls"},
+ "kite": {"atoms": ["retreat", "strafe"], "telegraph": "-", "damage": "-",
+ "range": "backs off inside 4 blocks, closes in beyond 14",
+ "punish": "corner it against the ruins or the arena wall"}}
+ SKILLS = ("projectile_dodge", "cover_use", "aim_tracking", "chase", "weapon_switch")
+ STATES = ("chase", "windup", "swing", "recover")
+ name = "skeleton"
+ height, aim_h = 1.99, 1.0
+ half = (0.3, 0.3)
+ knockback = 1.0
+
+ def reset(self, case):
+ super().reset(case)
+ self.max_hp = self.hp = self.k.hp
+ self.armor = float(self.k.armor)
+ self.e = Entity(MID + 8.0, 0.0, MID, math.pi, 0.6, self.height)
+ self.state, self.timer, self.cd, self.iframes = "chase", 0.0, ticks(40), 0
+ self.ph, self.tint_t = 0.0, 0
+ self.strafe_dir, self.strafe_t = 1.0, 0
+ self.draw_t, self.shots, self.arrows = 0.0, 0, []
+ self.rig = skeleton_rig()
+
+ @property
+ def enraged(self):
+ return False
+
+ def sees(self, case):
+ eye = self.e.pos + [0, 1.74, 0]
+ return case.arena.los(eye, case.body.e.pos + [0, 1.2, 0], eye_h=0.0)
+
+ def update(self, case):
+ k, e, p = self.k, self.e, case.body.e
+ self.iframes, self.cd = max(self.iframes - 1, 0), max(self.cd - 1, 0)
+ self.tint_t = max(self.tint_t - 1, 0)
+ self.timer -= 1 / FPS
+ self._arrows(case)
+ to = p.pos - e.pos
+ flat = float(math.hypot(to[0], to[2]))
+ e.yaw = math.atan2(to[2], to[0])
+ sees = self.sees(case)
+ # -- movement (Java RangedBowAttackGoal: approach beyond range, back off inside 4 blocks, strafe otherwise) --
+ self.strafe_t -= 1
+ if self.strafe_t <= 0:
+ self.strafe_t = ticks(20 + int(case.rng.integers(0, 40)))
+ if case.rng.random() < 0.3:
+ self.strafe_dir = -self.strafe_dir
+ if not sees or flat >= 14.0:
+ wish, speed = self.steer(case), k.speed
+ elif flat < 4.0:
+ wish = -e.fwd + e.right * self.strafe_dir * 0.5
+ speed = k.speed
+ else:
+ wish, speed = e.right * self.strafe_dir, k.speed * 0.5
+ n = float(math.hypot(wish[0], wish[2]))
+ wish = wish / n if n > 1e-9 else wish
+ # -- bow --
+ if self.state == "chase":
+ if self.cd == 0 and sees and flat <= 15.0:
+ self.state, self.timer = "windup", float(k.draw)
+ case.events.append("skeleton_draw")
+ elif self.state == "windup":
+ speed *= 0.5
+ if not sees or flat > 16.0: # lost sight: keeps the bow drawn, fires when it sees again (Java)
+ self.timer = max(self.timer, 1 / FPS)
+ elif self.timer <= 0:
+ self._shoot(case)
+ self.state, self.timer = "swing", 0.15
+ elif self.state == "swing":
+ if self.timer <= 0:
+ self.state, self.cd = "recover", ticks(k.interval - 20 * k.draw)
+ elif self.state == "recover" and self.cd == 0:
+ self.state = "chase"
+ blocked, _ = physics(case, e, wish, speed, step=0.0)
+ if blocked and e.on_ground:
+ e.vel[1] = JUMP
+ self.strafe_dir = -self.strafe_dir # cornered against cover: strafe the other way
+ self.ph = (self.ph + float(math.hypot(e.vel[0], e.vel[2])) * 1.1) % 1.0
+ self.pose(case)
+
+ def _shoot(self, case):
+ """Java AbstractSkeleton.performRangedAttack: aims at a third of the target's height, 0.2 blocks higher per block
+ of horizontal range, speed 1.6 b/t, inaccuracy 14 - 4 x difficulty (10 / 6 / 2): each axis of the unit
+ direction gets a triangular deviation of 0.0172275 x inaccuracy (Projectile.getMovementToShoot)."""
+ k, e, p = self.k, self.e, case.body.e
+ start = e.pos + [0, 1.6, 0] + e.fwd * 0.4
+ target = p.pos + [0, PLAYER_H / 3, 0]
+ d = target - start
+ horiz = float(math.hypot(d[0], d[2]))
+ d[1] += horiz * 0.2
+ n = float(np.linalg.norm(d)) + 1e-9
+ spread = 0.0172275 * k.error
+ direction = d / n + (case.rng.random(3) - case.rng.random(3)) * spread
+ direction /= float(np.linalg.norm(direction)) + 1e-9
+ self.shots += 1
+ self.arrows.append({"id": self.shots, "pos": start, "vel": direction * per_vt(1.6), "age": 0,
+ "damage": float(case.rng.uniform(k.arrow_min, k.arrow_max))})
+ case.events.append(("skeleton_shot", self.shots))
+
+ def _arrows(self, case):
+ p, keep = case.body.e, []
+ lo, hi = p.pos - [PLAYER_W / 2, 0.0, PLAYER_W / 2], p.pos + [PLAYER_W / 2, PLAYER_H, PLAYER_W / 2]
+ for a in self.arrows:
+ start, end = a["pos"], a["pos"] + a["vel"]
+ hit_p = _segment_box(start, end, lo, hi)
+ hit_w, _ = case._arrow_world_hit(start, end)
+ if hit_p is not None and (hit_w is None or hit_p <= hit_w):
+ if self.hurt_player(case, a["damage"], fling=0.3, origin=start):
+ case.events.append("skeleton_arrow_hit")
+ continue
+ if hit_w is not None or a["age"] > FPS * 6:
+ case.events.append("skeleton_arrow_blocked")
+ continue
+ a["pos"] = end
+ a["vel"] = a["vel"] * decay(0.99)
+ a["vel"][1] -= 0.05 * VT * VT
+ a["age"] += 1
+ keep.append(a)
+ self.arrows = keep
+
+ def pose(self, case):
+ mcskin.pose_skeleton(self, case)
+
+ def extra(self, case):
+ return [] # arrows are drawn by mcskin.arrow_rows (same look as the player's)
+
+
+# ---------------------------------------------------------------- rigs
+golem_rig, zombie_rig = mcskin.golem_rig, mcskin.zombie_rig
+dragon_rig, wither_rig = mcskin.dragon_rig, mcskin.wither_rig
+warden_rig, skeleton_rig = mcskin.warden_rig, mcskin.skeleton_rig
+
+
+# ---------------------------------------------------------------- case
+MOBS = {"iron_golem": IronGolem, "zombie": Zombie, "ender_dragon": EnderDragon, "wither": Wither,
+ "warden": Warden, "skeleton": Skeleton, "zombie_leader": ZombieLeader}
+
+
+class MobFight(Case):
+ """Arena + player + one mob. One class serves every boss; `mob` picks the boss."""
+ R = 3
+ obs_dim = 12 + 14 + (2 * R + 1) ** 2
+ # per-boss observation extras: wither 3 nearest skulls x 7, skeleton 3 nearest arrows x 7, leader zombie 3 nearest
+ # reinforcements x 4, warden boom charge / time out of reach / darkness (the last three since minecraft-arena@5;
+ # the formal zombie case has none, as in @4)
+ EXTRA_OBS = {"wither": 21, "skeleton": 21, "zombie_leader": 12, "warden": 3}
+
+ # The camera changes only the image. Third-person is available through the reset options.
+ def __init__(self, mob="iron_golem", style="field", width=RES[0], height=RES[1], camera="first",
+ max_seconds=120.0, weapon='sword'):
+ self.default_weapon, self.default_camera = _weapon(weapon), _camera(camera)
+ self.mob_name = mob
+ self.max_seconds = max_seconds
+ self.obs_dim = MobFight.obs_dim + self.EXTRA_OBS.get(mob, 0)
+ super().__init__(VoxelArena(style), Steve(weapon), MOBS[mob]())
+ self.name = f"minecraft_{mob}_1v1"
+ self.size, self.camera, self._gl = (width, height), camera, None
+ self.render_error = None
+
+ def reset(self, seed, d, options=None):
+ options = dict(options or {})
+ weapon = _weapon(options.get('weapon', self.default_weapon))
+ camera = _camera(options.get('camera', self.default_camera))
+ self.body.weapon, self.camera = weapon, camera
+ self.render_error = None
+ self.arrows = []
+ super().reset(seed, d)
+ self.fxrng = np.random.default_rng((int(seed) * 2654435761 + 0x9E3779B9) % (2 ** 32))
+ self.fx = []
+ if self.body.weapon == 'bow':
+ self.body.pose(self) # establish visible bow pose before frame zero
+
+ def hurt_player(self, dmg, armor=True, iframes=True, share=1.0):
+ """Java LivingEntity.hurt for the player. A hit starts 10 vanilla ticks of immunity; inside the window
+ only a stronger raw hit lands, dealing the difference (no knockback, no new window). Returns "fresh",
+ "partial" or False. share < 1: this tick's part of a per-vanilla-tick damage (armor sees the whole hit);
+ iframes=False: damage that neither starts nor respects the window (fall, Wither effect, breath)."""
+ b = self.body
+ landed = "fresh"
+ if iframes:
+ if b.iframes > 0:
+ if dmg <= b.last_hurt:
+ return False
+ dmg, b.last_hurt, landed = dmg - b.last_hurt, dmg, "partial"
+ else:
+ b.last_hurt, b.iframes = dmg, ticks(10)
+ if armor:
+ dmg = armor_reduce(dmg, b.k.armor, b.k.toughness)
+ dmg *= share
+ b.hp -= dmg
+ self.events.append(("player_hit", round(float(dmg), 2)))
+ return landed
+
+
+ def interact(self):
+ p = self.body.e
+ if self.boss.hover:
+ return
+ # bodies push the player out (the boss, and since minecraft-arena@5 any living reinforcement); a zombie horde
+ # can pin a player against cover this way
+ for mob in [self.boss] + [z for z in getattr(self.boss, "minions", ()) if z.hp > 0]:
+ g = mob.e
+ d = p.pos[[0, 2]] - g.pos[[0, 2]]
+ dist, need = float(np.linalg.norm(d)), (PLAYER_W + 2 * mob.half[0]) / 2
+ if dist < need and abs(p.pos[1] - g.pos[1]) < mob.height:
+ push = d / (dist + 1e-6) * (need - dist)
+ new = p.pos.copy()
+ new[[0, 2]] += push
+ if self.arena.ground(new, PLAYER_W) <= p.pos[1] + 0.6:
+ p.pos = new
+
+ def track(self):
+ """Advance visual-only state after the rules ran: pose the player, step particles. Draws
+ from case.fxrng only, never touches gameplay state."""
+ self.body.pose(self)
+ mcskin.step_fx(self)
+
+ def tick(self, action):
+ self._ev0 = len(self.events) # first event of this tick (fx juice reads only new ones)
+ self.body.apply(self, action)
+ self.boss.update(self)
+ if self.arrows:
+ self._update_arrows()
+ self.arena.update(self)
+ self.interact()
+ self.track()
+ self.t += 1
+
+ def _arrow_world_hit(self, start, end):
+ """Swept collision against actual voxel columns and the arena floor."""
+ radius = BOW_RULES['arrow_radius_blocks']
+ first, reason = None, None
+ for axis in (0, 2):
+ if start[axis] < 0 or start[axis] > S:
+ return 0.0, 'bounds'
+ if end[axis] < 0 or end[axis] > S:
+ boundary = 0.0 if end[axis] < 0 else float(S)
+ value = (boundary - start[axis]) / (end[axis] - start[axis])
+ if first is None or value < first:
+ first, reason = value, 'bounds'
+ low = np.floor(np.minimum(start, end)[[0, 2]] - radius).astype(int)
+ high = np.floor(np.maximum(start, end)[[0, 2]] + radius).astype(int)
+ for x in range(max(0, low[0]), min(S - 1, high[0]) + 1):
+ for z in range(max(0, low[1]), min(S - 1, high[1]) + 1):
+ height = float(self.arena.H[x, z])
+ hit = _segment_box(start, end,
+ np.array([x - radius, -radius, z - radius]),
+ np.array([x + 1 + radius, height + radius, z + 1 + radius]))
+ if hit is not None and (first is None or hit < first):
+ first, reason = hit, 'ground' if height == 0 else 'voxel'
+ return first, reason
+
+ def _targets(self):
+ """Damageable boxes for arrows and the sword ray: (kind, lo, hi, payload)."""
+ g, out = self.boss, []
+ if hasattr(g, "hitboxes"):
+ out += [("boss", lo, hi, part) for part, lo, hi in g.hitboxes()]
+ else:
+ out.append(("boss", g.hit_lo(), g.hit_hi(), "body"))
+ for c in getattr(g, "crystals", ()):
+ if c["alive"]:
+ out.append(("crystal", c["pos"] - [0.5, 0.0, 0.5], c["pos"] + [0.5, 1.6, 0.5], c))
+ for z in getattr(g, "minions", ()): # zombie reinforcements (minecraft-arena@5)
+ if z.hp > 0:
+ out.append(("minion", z.hit_lo(), z.hit_hi(), z))
+ return out
+
+ def _damage(self, kind, payload, dmg, how, bonus_knockback=0.0):
+ g = self.boss
+ if kind == "crystal":
+ g.crystal_destroyed(self, payload)
+ return 0.0
+ if kind == "minion": # a reinforcement's health is not the boss's health
+ payload.take_hit(self, dmg, how, bonus_knockback=bonus_knockback)
+ return 0.0
+ before = max(0.0, float(g.hp))
+ if hasattr(g, "hitboxes"):
+ g.take_hit(self, dmg, how, bonus_knockback=bonus_knockback, part=payload)
+ else:
+ g.take_hit(self, dmg, how, bonus_knockback=bonus_knockback)
+ return max(0.0, before - max(0.0, float(g.hp)))
+
+ def _update_arrows(self):
+ kept = []
+ radius = BOW_RULES['arrow_radius_blocks']
+ for arrow in self.arrows:
+ if arrow['age'] >= FPS * BOW_RULES['maximum_life_seconds']:
+ self.events.append(('arrow_expired', arrow['id']))
+ continue
+ start, end = arrow['pos'], arrow['pos'] + arrow['vel']
+ world_hit, reason = self._arrow_world_hit(start, end)
+ best = None
+ for kind, lo, hi, payload in self._targets():
+ u = _segment_box(start, end, lo - radius, hi + radius)
+ if u is not None and (best is None or u < best[0]):
+ best = (u, kind, payload)
+ if world_hit is not None and (best is None or world_hit <= best[0]):
+ self.events.append(('arrow_blocked', arrow['id'], reason))
+ continue
+ if best is not None:
+ _, kind, payload = best
+ damage = math.ceil(float(np.linalg.norm(arrow['vel'])) / VT
+ * BOW_RULES['base_damage_per_speed'])
+ if arrow['critical']:
+ damage += int(self.rng.integers(0, damage // 2 + 2))
+ actual = self._damage(kind, payload, damage, 'arrow_critical' if arrow['critical'] else 'arrow')
+ if actual > 0:
+ self.body.arrows_hit += 1
+ self.body.arrow_damage += actual
+ self.events.append(('arrow_hit', arrow['id'], round(actual, 4), kind))
+ continue
+ arrow['pos'] = end
+ arrow['vel'] *= decay(BOW_RULES['drag_per_vanilla_tick'])
+ arrow['vel'][1] -= BOW_RULES['gravity_blocks_per_vanilla_tick_squared'] * VT * VT
+ arrow['age'] += 1
+ kept.append(arrow)
+ self.arrows = kept
+
+
+ # -- observation -------------------------------------------------------
+ def _rel(self):
+ p, g = self.body.e, self.boss.e
+ d = g.pos - p.pos
+ bearing = math.atan2(d[2], d[0]) - p.yaw
+ return d, math.hypot(d[0], d[2]), math.atan2(math.sin(bearing), math.cos(bearing))
+
+ def observe(self):
+ b, g, p = self.body, self.boss, self.body.e
+ d, dist, bearing = self._rel()
+ H = np.pad(self.arena.H, self.R, constant_values=WALL_CAP).astype(np.float32)
+ ix, iz = int(p.pos[0]) + self.R, int(p.pos[2]) + self.R
+ local = (H[max(ix - self.R, 0):ix + self.R + 1, max(iz - self.R, 0):iz + self.R + 1] - p.pos[1]) / 4
+ mine = [p.pos[0] / S, p.pos[1] / 4, p.pos[2] / S, *p.vel / VT * 4, math.sin(p.yaw), math.cos(p.yaw),
+ b.hp / b.max_hp, b.charge, float(p.on_ground)]
+ states = type(g).STATES
+ hot = g.state in ("windup", "lineup", "charge")
+ boss = [*d / 8, dist / 8, math.sin(bearing), math.cos(bearing), g.hp / g.max_hp,
+ *np.eye(4)[states.index(g.state)], max(g.timer, 0) if hot else 0,
+ min(g.cd / FPS, 2.0), float(g.enraged), float(g.in_reach(self))]
+ extra = []
+ skulls = getattr(g, "skulls", None)
+ if skulls is not None: # three nearest skulls, in player-relative terms
+ order = sorted(skulls, key=lambda s: float(np.linalg.norm(s["pos"] - p.pos)))[:3]
+ for s in order:
+ rel = s["pos"] - p.pos
+ extra += [*rel / 8, *s["vel"] / VT / 2, float(s["life"])]
+ extra += [0.0] * (3 - len(order)) * 7
+ if isinstance(g, Skeleton): # three nearest skeleton arrows
+ order = sorted(g.arrows, key=lambda a: float(np.linalg.norm(a["pos"] - p.pos)))[:3]
+ for a in order:
+ rel = a["pos"] - p.pos
+ extra += [*rel / 8, *a["vel"] / VT / 2, a["age"] / FPS]
+ extra += [0.0] * (3 - len(order)) * 7
+ if isinstance(g, ZombieLeader): # three nearest live reinforcements
+ live = sorted((z for z in g.minions if z.hp > 0), key=lambda z: float(np.linalg.norm(z.e.pos - p.pos)))[:3]
+ for z in live:
+ extra += [*(z.e.pos - p.pos) / 8, z.hp / z.max_hp]
+ extra += [0.0] * (3 - len(live)) * 4
+ if isinstance(g, Warden):
+ extra += [max(g.timer, 0.0) if g.phase == "boom" else 0.0, min(g.out_of_reach / FPS, 10.0) / 10.0,
+ g.dark_t / ticks(260)]
+ return np.concatenate([mine, boss, extra, local.ravel()]).astype(np.float32)
+
+ def state(self):
+ b, g = self.body, self.boss
+ d, dist, bearing = self._rel()
+ mob = {"pos": g.e.pos.round(2).tolist(), "hp": round(g.hp, 2), "max_hp": round(g.max_hp, 1),
+ "state": g.state, "timer": round(max(g.timer, 0), 2), "cooldown_s": round(g.cd / FPS, 2),
+ "enraged": bool(g.enraged), "distance": round(dist, 2),
+ "distance3d": round(float(np.linalg.norm(d)), 2),
+ "bearing_deg": round(math.degrees(bearing), 1), "in_reach": g.in_reach(self),
+ "iframes": int(g.iframes), "yaw_deg": round(math.degrees(g.e.yaw), 1)}
+ if g.state == "windup":
+ mob["windup_left"] = round(max(g.timer, 0), 2)
+ if getattr(g, "skulls", None):
+ mob["skulls"] = [{"pos": s["pos"].round(2).tolist(), "vel": (s["vel"] * FPS).round(2).tolist(), # b/s
+ "blue": bool(s.get("blue", False))} for s in g.skulls]
+ if hasattr(g, "phase"):
+ mob["phase"] = g.phase
+ if hasattr(g, "armored"):
+ mob["armored"] = bool(g.armored)
+ if hasattr(g, "crystals"):
+ mob["crystals"] = [{"id": c["id"], "pos": c["pos"].round(2).tolist(), "alive": bool(c["alive"])}
+ for c in g.crystals]
+ mob["healing_from"] = None if g.heal_from is None else g.heal_from["id"]
+ mob["fireballs"] = [{"pos": f["pos"].round(2).tolist()} for f in g.fireballs]
+ mob["clouds"] = [{"pos": c["pos"].round(2).tolist(), "r": round(c["r"], 2), "kind": c["kind"],
+ "life": round(c["life"], 2)} for c in g.clouds]
+ if isinstance(g, ZombieLeader):
+ mob["minions"] = [{"n": z.n, "pos": z.e.pos.round(2).tolist(), "hp": round(z.hp, 2), "state": z.state}
+ for z in g.minions if z.hp > 0]
+ mob["reinforce_chance"] = round(g.chance, 4)
+ mob["summoned"] = g.summoned
+ if isinstance(g, Warden):
+ mob["darkness_s"] = round(g.dark_t / FPS, 2)
+ mob["out_of_reach_s"] = round(g.out_of_reach / FPS, 2)
+ mob["booms"] = g.booms
+ if isinstance(g, Skeleton):
+ mob["arrows"] = [{"id": a["id"], "pos": a["pos"].round(3).tolist(), "vel": (a["vel"] * FPS).round(3).tolist()}
+ for a in g.arrows]
+ mob["shots"] = g.shots
+ result = {"rules": RULES,
+ "player": {"pos": b.e.pos.round(2).tolist(), "yaw_deg": round(math.degrees(b.e.yaw), 1),
+ "pitch_deg": round(math.degrees(b.e.pitch), 4), "weapon": b.weapon,
+ "hp": round(b.hp, 2), "max_hp": b.max_hp, "attack_charge": round(b.attack_charge, 2),
+ "on_ground": b.e.on_ground, "sprinting": bool(b.sprinting),
+ "iframes": int(b.iframes), "wither_effect_s": round(b.wither_t / FPS, 2)},
+ "boss": mob,
+ "boss_kind": self.mob_name, "boss_skills": list(self.boss.SKILLS)}
+ result['player'].update(bow_charge=round(b.bow_charge, 6), bow_drawing=b.bow_drawing,
+ arrows_fired=b.arrows_fired, arrows_hit=b.arrows_hit,
+ arrow_damage=round(b.arrow_damage, 6), melee_damage=round(b.melee_damage, 6))
+ result['arrows'] = [{'id': arrow['id'], 'pos': arrow['pos'].round(4).tolist(),
+ 'vel': (arrow['vel'] * FPS).round(4).tolist(), 'age': arrow['age'],
+ 'damage': arrow['damage'], 'critical': arrow['critical']} for arrow in self.arrows]
+ result['weapon_rules'] = dict(BOW_RULES)
+ return result
+
+
+ # -- rendering ---------------------------------------------------------
+ def render(self, t=None):
+ try:
+ if self._gl is None:
+ self._gl = mcskin.VoxelRenderer(*self.size)
+ img = self._gl.draw(self, t)
+ self.render_error = None
+ except Exception as ex: # no GL context: top-down map, reason kept for debugging
+ self.render_error = repr(ex)
+ renderer, self._gl = self._gl, None
+ if renderer is not None:
+ try:
+ renderer.close()
+ except Exception as close_ex:
+ self.render_error += f"; cleanup: {close_ex!r}"
+ img = self._topdown()
+ return mcskin.hud(img, self)
+
+ def close(self):
+ """Release the lazy renderer; a later render can create a fresh context."""
+ renderer, self._gl = self._gl, None
+ if renderer is not None:
+ renderer.close()
+
+ def _topdown(self):
+ W, H = self.size
+ T = H // S
+ img = np.zeros((H, W, 3), np.uint8)
+ pal = np.array([[90, 150, 60], [150, 110, 60], [120, 120, 120], [100, 100, 110], [60, 60, 60],
+ [70, 70, 75], [80, 80, 85], [95, 95, 100], [110, 110, 115]], np.uint8)
+ ox = (W - S * T) // 2
+ world = img[:S * T, ox:ox + S * T]
+ world[:] = pal[np.clip(self.arena.H.T, 0, 8)].repeat(T, 0).repeat(T, 1)
+ for e, c in ((self.boss.e, (220, 215, 205)), (self.body.e, (40, 120, 230))):
+ x, z, r = int(e.pos[0] * T), int(e.pos[2] * T), int(e.w * T / 2)
+ world[max(z - r, 0):z + r, max(x - r, 0):x + r] = c
+ return img
+
+
+# ---------------------------------------------------------------- factories
+STYLES = {"iron_golem": "field", "zombie": "field", "ender_dragon": "towers", "wither": "towers",
+ "warden": "deep_dark", "skeleton": "ruins", "zombie_leader": "night"}
+SECONDS = {"iron_golem": 300.0, "zombie": 90.0, "ender_dragon": 300.0, "wither": 300.0, # hard tier ~3 min (@4)
+ "warden": 300.0, "skeleton": 300.0, "zombie_leader": 300.0}
+
+
+def make(mob="iron_golem", **kw) -> BossBenchEnv:
+ case_kw = {k: kw.pop(k) for k in ("style", "width", "height", "camera", "weapon") if k in kw}
+ case_kw.setdefault("style", STYLES.get(mob, "field"))
+ seconds = kw.pop("max_seconds", SECONDS.get(mob, 120.0))
+ return BossBenchEnv(MobFight(mob, max_seconds=seconds, **case_kw), max_seconds=seconds, **kw)
diff --git a/environments/games/prototype/bossbench/mc_scripted.py b/environments/games/prototype/bossbench/mc_scripted.py
new file mode 100644
index 0000000000000000000000000000000000000000..c7334ce6f49a941fb209951acf56eacda9f6907d
--- /dev/null
+++ b/environments/games/prototype/bossbench/mc_scripted.py
@@ -0,0 +1,1102 @@
+"""Standard trusted scripted controller for the Minecraft remake (bossbench.mc4d), overnight PROTOCOL section 3.
+
+ from bossbench import mc_scripted
+ packet = mc_scripted.scripted(case) # case: the live mc4d.MobFight -> one legal 200 ms packet (text)
+
+It reads privileged simulation state (it is a reference controller, never shown to a policy) and emits only legal
+packets (<= 4 keys per hold set, |dx|,|dy| <= 1000, |dz| <= 5). It never mutates the live case: every lookahead
+runs on a light clone (deep copy with its own RNG state and arena heights; renderer, rigs and particles are not
+copied and posing is disabled), so it is deterministic for a given (case, seed, options, packet history). Memory
+lives in a WeakKeyDictionary keyed by the case and is reset when the episode tick is 0.
+
+Strategy per packet: decide the weapon (hotbar wheel), an aim point and a few candidate packets (movement x
+attack timing x jump/draw/release), roll every candidate forward 2-4 packets on a clone (the later packets are a
+greedy continuation), and keep the best score = 10 x boss damage - taken_w x player damage + shaping, with a small
+bonus for progress made sooner (breaks the "release now" vs "release next packet" tie that held full bow draws).
+minecraft-arena@4 (2026-11-02, three tiers): the iron golem gets its own planner (attack-box gap, room to back off,
+4-packet lookahead pricing a slam like the hit it is); the dragon aims only at crystals it can see, leaves their
+blast radius, sidesteps a fireball line-up and walks into sword reach of a perched head; the wither looks 3 packets
+ahead when a skull closes in at melee range.
+"""
+from __future__ import annotations
+
+import copy
+import math
+import types
+import weakref
+
+import numpy as np
+
+from . import keymouse as km
+from . import mc4d
+
+TICKS = 12 # 60 Hz simulation ticks per 200 ms packet
+DEG = mc4d.Steve.MOUSE_DEG
+_MEM: "weakref.WeakKeyDictionary" = weakref.WeakKeyDictionary()
+MOVES = ("", "W", "S", "A", "D")
+# minecraft-arena@7 removed natural regeneration: a hit taken at 10 s still counts at 170 s. Price player damage at
+# least at this fraction of the rate the fight affords (boss health left per player health left); short fights
+# keep their own taken_w, long hard fights get more careful as health runs down. Measured on seeds 1-32 (hard wins,
+# floor off -> on): dragon 28 -> 31, golem 13 -> 14, skeleton 0 -> 8, zombie leader 20 -> 32, warden 30 -> 30, but
+# wither 25 -> 20 (careful play stretched its fights until the skulls wore the player down), so the wither keeps 0.
+HP_BUDGET = 0.05
+HP_BUDGET_BY_BOSS = {"wither": 0.0}
+
+
+# ------------------------------------------------------------------------------------------- simulation helpers
+def clone(case):
+ """Gameplay-only deep copy. Shares the read-only difficulty knobs, drops renderer/rigs/particles."""
+ memo = {id(case.fx): []}
+ minions = list(getattr(case.boss, "minions", ())) # zombie reinforcements (minecraft-arena@5)
+ for obj in (getattr(case, "_gl", None), case.body.rig, case.boss.rig, getattr(case, "fxrng", None),
+ *(z.rig for z in minions)):
+ if obj is not None:
+ memo[id(obj)] = None
+ for comp in (case.arena, case.body, case.boss):
+ memo[id(comp.k)] = comp.k
+ arena = copy.copy(case.arena)
+ arena.H = case.arena.H.copy()
+ memo[id(case.arena)] = arena
+ sim = copy.deepcopy(case, memo)
+ # Harness wrappers (e.g. bossbench.scripted.FrameCapture) patch bound methods onto the live instance; deepcopy
+ # keeps function objects as-is, so a copied wrapper would still drive the LIVE case. Restore class methods.
+ for obj in (sim, sim.body, sim.boss, sim.arena, *getattr(sim.boss, "minions", ())):
+ for key in [k for k, v in vars(obj).items() if isinstance(v, (types.FunctionType, types.MethodType))]:
+ del vars(obj)[key]
+ sim.track = lambda: None
+ sim.body.pose = lambda c: None
+ sim.boss.pose = lambda c: None
+ sim.boss.pose_child = lambda c, z: None
+ return sim
+
+
+def run_packet(sim, packet, last):
+ """Execute one parsed packet exactly as PyCaseEnv does (keymouse.schedule over 12 ticks)."""
+ sched, last = km.schedule(packet, TICKS, last)
+ for held, pressed, mouse in sched:
+ if sim.outcome():
+ break
+ sim.tick(sim.body.keys(sim, held, pressed, mouse))
+ return last
+
+
+def packet(subs, mouse=(0, 0, 0)):
+ subs = [frozenset(s) for s in subs]
+ assert len(subs) == 6 and all(len(s) <= km.MAX_KEYS for s in subs)
+ mouse = (int(np.clip(mouse[0], -1000, 1000)), int(np.clip(mouse[1], -1000, 1000)), int(np.clip(mouse[2], -5, 5)))
+ return {"mouse": mouse, "subs": subs}
+
+
+def text(p):
+ order = {k: i for i, k in enumerate(km.KEYS)}
+ return km.format_packet([sorted(s, key=order.get) for s in p["subs"]], p["mouse"])
+
+
+def wrap(a):
+ return (a + math.pi) % (2 * math.pi) - math.pi
+
+
+def aim_to(body, point, frac=1.0):
+ """Mouse (dx, dy) that turns the view onto point by the end of the packet (frac < 1: by that fraction)."""
+ e = body.e
+ d = np.asarray(point, float) - (e.pos + [0, mc4d.EYE, 0])
+ yaw = math.atan2(d[2], d[0])
+ pitch = math.atan2(d[1], math.hypot(d[0], d[2]))
+ dyaw, dpitch = wrap(yaw - e.yaw), pitch - e.pitch
+ return math.degrees(dyaw) / DEG / frac, -math.degrees(dpitch) / DEG / frac
+
+
+def view_error(body, point):
+ dx, dy = aim_to(body, point)
+ return math.hypot(dx, dy) * DEG # degrees
+
+
+def flat(v):
+ return np.array([v[0], 0.0, v[2]])
+
+
+def hdist(a, b):
+ return float(math.hypot(a[0] - b[0], a[2] - b[2]))
+
+
+# ------------------------------------------------------------------------------------------- memory
+def memory(case):
+ m = _MEM.get(case)
+ if m is None or (case.t == 0 and m.get("t", -1) != 0) or case.t < m.get("t", -1):
+ m = {"last": frozenset(), "t": case.t, "crit_wait": 0}
+ _MEM[case] = m
+ m["t"] = case.t
+ return m
+
+
+def scripted(case):
+ """One legal packet (text) for the live MobFight; deterministic, read-only."""
+ m = memory(case)
+ planner = PLANNERS[case.boss.name]
+ p = planner(case, m)
+ m["last"] = frozenset(p["subs"][-1])
+ return text(p)
+
+
+# ------------------------------------------------------------------------------------------- packet building
+def build(move="", jump=(), swing=None, rmb=None, sprint=False, mouse=(0, 0, 0), wheel=0, last=frozenset()):
+ """Six hold sets. move: '' or one of W/S/A/D (held all packet); jump: substeps holding Space;
+ swing: substep index of one LMB/J press (the key not held in the previous substep);
+ rmb: None (released), 'hold' (held all packet) or an int j (held for substeps < j, released from j)."""
+ subs = []
+ prev = set(last)
+ for j in range(6):
+ s = set()
+ if move:
+ s.add(move)
+ if j in jump:
+ s.add("Space")
+ if sprint and move == "W":
+ s.add("Shift")
+ if rmb == "hold" or (isinstance(rmb, int) and not isinstance(rmb, bool) and j < rmb):
+ s.add("RMB")
+ if swing is not None and j == swing:
+ s.add("J" if "LMB" in prev else "LMB")
+ subs.append(s)
+ prev = s
+ return packet(subs, (mouse[0], mouse[1], wheel))
+
+
+def weapon_wheel(case, want):
+ return 0 if case.body.weapon == want else 1
+
+
+def swing_slots(body):
+ """Sub-steps worth trying a full-charge swing at: the first charged one and every other one after it (the
+ in-between timings rarely differ; pruning them keeps the lookahead fast enough for the live demo)."""
+ ready = [j for j in range(6) if charge_at(body, 2 * j) > 0.9]
+ return ready[::2]
+
+
+def charge_at(body, ticks_ahead, weapon=None):
+ weapon = weapon or body.weapon
+ T = body.T_ATTACK if weapon == "sword" else body.T_FIST
+ return min(1.0, (body.since_swing + ticks_ahead + 0.5) / T)
+
+
+# ------------------------------------------------------------------------------------------- evaluation
+def evaluate(case, m, cand, cont, shape, horizon=2, taken_w=8.0):
+ """Roll cand then (horizon - 1) greedy continuation packets on a clone; return (score, sim).
+ taken_w prices player damage against boss damage (x10): long fights must not trade hits. Since minecraft-arena@7
+ (no natural regeneration) health is a budget for the whole fight, so the price never drops below HP_BUDGET of
+ the exchange rate the fight affords: 10 x boss health left / player health left (see HP_BUDGET)."""
+ b = case.body
+ budget = HP_BUDGET_BY_BOSS.get(case.boss.name, HP_BUDGET)
+ taken_w = max(taken_w, budget * 10.0 * max(float(case.boss.hp), 0.0) / max(float(b.hp), 1.0))
+ sim = clone(case)
+ boss0, hp0 = float(sim.boss.hp), float(sim.body.hp)
+ wither0 = sim.body.wither_t
+
+ def alive():
+ return sum(c["alive"] for c in getattr(sim.boss, "crystals", ()))
+ alive0 = alive()
+ last = run_packet(sim, cand, m["last"])
+ first = (float(sim.boss.hp), float(sim.body.hp))
+ # Progress made sooner is worth a little more. Without it a full bow draw held "for later" ties with a release
+ # now (the continuation releases anyway), the tie goes to holding, and the next packet repeats it: found
+ # 2026-11-02, an easy dragon with a crystal in plain sight and the bow held at full draw for 15 s.
+ sooner, hp_prev, alive_prev = 0.0, boss0, alive0
+ for k in range(horizon):
+ if k:
+ if sim.outcome():
+ break
+ last = run_packet(sim, cont(sim, last), last)
+ hp_now, alive_now = float(sim.boss.hp), alive()
+ sooner += (1 - k / horizon) * (1.0 * (hp_prev - hp_now) + 3.0 * (alive_prev - alive_now))
+ hp_prev, alive_prev = hp_now, alive_now
+ dealt = boss0 - float(sim.boss.hp)
+ taken = hp0 - float(sim.body.hp) + max(0, sim.body.wither_t - wither0) / mc4d.FPS * 0.7
+ crystals = alive0 - alive()
+ score = 10 * dealt - taken_w * taken + 25 * crystals + 4 * (boss0 - first[0]) - 4 * (hp0 - first[1]) + sooner
+ if sim.outcome() == "win":
+ score += 1000
+ elif sim.outcome() == "loss":
+ score -= 1000
+ return score + shape(sim), sim
+
+
+def best_of(case, m, cands, cont, shape, horizon=2, taken_w=8.0):
+ """cands: packets, or (packet, own continuation) pairs; the best first packet wins."""
+ best, best_score = None, -math.inf
+ for cand in cands:
+ own = cont
+ if isinstance(cand, tuple):
+ cand, own = cand
+ s, _ = evaluate(case, m, cand, own, shape, horizon, taken_w)
+ if s > best_score + 1e-9:
+ best, best_score = cand, s
+ return best
+
+
+def greedy_melee(target_fn, band=(2.4, 3.2)):
+ """Continuation: keep aiming, keep the distance band, swing when charged and on target."""
+ def cont(sim, last):
+ b = sim.body
+ point = target_fn(sim)
+ dx, dy = aim_to(b, point)
+ dist = hdist(b.e.pos, point)
+ move = "S" if dist < band[0] else ("W" if dist > band[1] else "")
+ swing = None
+ if b.weapon == "sword" and charge_at(b, 0) > 0.9 and b.ray_hit(sim) is not None:
+ swing = 0
+ return build(move, swing=swing, mouse=(dx, dy), last=last)
+ return cont
+
+
+# ------------------------------------------------------------------------------------------- terrain helpers
+def open_space(case, pos):
+ """Distance to the arena wall and number of tall columns nearby (a crude 'room to retreat' measure)."""
+ H = case.arena.H
+ x, z = pos[0], pos[2]
+ wall = min(x - 1, z - 1, mc4d.S - 1 - x, mc4d.S - 1 - z)
+ ix, iz = int(x), int(z)
+ near = H[max(ix - 1, 0):ix + 2, max(iz - 1, 0):iz + 2]
+ return wall, int((near > pos[1] + 1).sum())
+
+
+def safe_shape(case_sim, centre_weight=0.15):
+ wall, tall = open_space(case_sim, case_sim.body.e.pos)
+ return -centre_weight * max(0.0, 4.0 - wall) ** 2 - 0.4 * tall
+
+
+# ------------------------------------------------------------------------------------------- melee (golem, zombie)
+def mob_centre(sim):
+ g = sim.boss
+ return (g.hit_lo() + g.hit_hi()) / 2
+
+
+def plan_melee(case, m, band, threat_reach, threat=None, taken_w=8.0, horizon=2):
+ b, g = case.body, case.boss
+ wheel = weapon_wheel(case, "sword")
+ lead = g.e.pos + g.e.vel * TICKS * 0.5
+ point = (g.hit_lo() + g.hit_hi()) / 2 + (lead - g.e.pos)
+ dx, dy = aim_to(b, point)
+ dist = hdist(b.e.pos, g.e.pos)
+
+ def shape(sim):
+ d = hdist(sim.body.e.pos, sim.boss.e.pos)
+ s = -1.2 * abs(d - (band[0] + band[1]) / 2) + safe_shape(sim)
+ if sim.boss.state in ("windup", "swing") and d < threat_reach:
+ s -= 6.0
+ if threat is not None:
+ s += threat(sim)
+ s -= 0.02 * view_error(sim.body, mob_centre(sim))
+ return s
+
+ cont = greedy_melee(mob_centre, band)
+ cands = []
+ swings = [None]
+ if wheel == 0 and dist < 5.5:
+ swings += swing_slots(b)
+ for move in MOVES:
+ for jump in ((), (0, 1, 2)):
+ if jump and move not in ("", "W", "S"):
+ continue
+ for sw in swings:
+ if jump and sw is not None and not (not b.e.on_ground and b.e.vel[1] < 0):
+ continue
+ cands.append(build(move, jump=jump, swing=sw, mouse=(dx, dy), wheel=wheel, last=m["last"]))
+ # turn and sprint away (sprint 0.281 b/t outruns a mob that is faster than walking backwards)
+ away = math.atan2(b.e.pos[2] - g.e.pos[2], b.e.pos[0] - g.e.pos[0])
+ for off in (-0.6, 0.0, 0.6):
+ turn = math.degrees(wrap(away + off - b.e.yaw)) / DEG
+ cands.append(build("W", sprint=True, mouse=(turn, 0), wheel=wheel, last=m["last"]))
+ return best_of(case, m, cands, cont, shape, horizon=horizon, taken_w=taken_w)
+
+
+def golem_gap(sim):
+ """Blocks between the player's box and the golem's attack box (Chebyshev; negative = inside). The 1.20.2 attack
+ box is the collision box grown 0.828 horizontally, axis-aligned, so on a diagonal it reaches 2.6 blocks."""
+ g, p = sim.boss, sim.body.e
+ r = g.half[0] + g.ATTACK_INFLATE + mc4d.PLAYER_W / 2
+ return max(abs(p.pos[0] - g.e.pos[0]), abs(p.pos[2] - g.e.pos[2])) - r
+
+
+def box_reach(sim):
+ """Distance from the player's eye to the golem's hitbox; the sword ray reaches 3."""
+ g, b = sim.boss, sim.body
+ eye = b.e.pos + [0, mc4d.EYE, 0]
+ return float(np.linalg.norm(eye - np.clip(eye, g.hit_lo(), g.hit_hi())))
+
+
+def golem_danger(sim, soon=10):
+ g = sim.boss
+ return g.state == "windup" or (g.state in ("chase", "recover") and g.cd <= mc4d.ticks(soon))
+
+
+def golem_threat(sim):
+ """Slams beyond the rollout horizon: the golem winds up the moment the player is inside its attack box with the
+ cooldown done. Keep a margin while it can swing and never be airborne next to it then (no air control).
+ Priced near the cost of eating a slam (taken_w x a mid-range hit): a crit is never worth one."""
+ g, b = sim.boss, sim.body
+ gap = golem_gap(sim)
+ s = 0.0
+ if g.state == "windup":
+ s -= 70.0 * max(0.0, 0.45 - gap)
+ elif golem_danger(sim, 8):
+ s -= 35.0 * max(0.0, 0.55 - gap)
+ if not b.e.on_ground:
+ s -= 15.0 * max(0.0, 1.2 - gap)
+ return s
+
+
+def retreat_room(sim, direction=None, limit=8.0):
+ """Free floor (blocks) behind the player when backing straight away from the boss (or along direction):
+ the arena wall and any column the player would have to jump end it. Backing into a corner is how a
+ near-walking-speed golem pins a player."""
+ p = sim.body.e.pos
+ if direction is None:
+ direction = flat(p - sim.boss.e.pos)
+ n = float(np.linalg.norm(direction))
+ if n < 1e-6:
+ return limit
+ u, H = direction / n, sim.arena.H
+ step = 0.0
+ while step < limit:
+ q = p + u * (step + 0.5)
+ if not (1.3 <= q[0] <= mc4d.S - 1.3 and 1.3 <= q[2] <= mc4d.S - 1.3) or H[int(q[0]), int(q[2])] > p[1] + 0.5:
+ break
+ step += 0.5
+ return step
+
+
+def golem_cont(sim, last):
+ """Continuation that fights like a careful player: face the golem, step back out of its box while it can
+ swing (sideways when the wall is behind), close in when out of sword reach, swing on a full charge."""
+ b = sim.body
+ dx, dy = aim_to(b, mob_centre(sim))
+ gap, reach = golem_gap(sim), box_reach(sim)
+ back = "S"
+ if retreat_room(sim) < 1.5:
+ left, right = -b.e.right, b.e.right
+ back = "A" if retreat_room(sim, left) >= retreat_room(sim, right) else "D"
+ if golem_danger(sim) and gap < 0.7:
+ move = back
+ elif reach > 2.8:
+ move = "W"
+ elif gap < 0.35:
+ move = back
+ else:
+ move = ""
+ swing = 0 if b.weapon == "sword" and charge_at(b, 0) > 0.9 and b.ray_hit(sim) is not None else None
+ return build(move, swing=swing, mouse=(dx, dy), last=last)
+
+
+def plan_golem(case, m):
+ b, g = case.body, case.boss
+ wheel = weapon_wheel(case, "sword")
+ lead = g.e.pos + g.e.vel * TICKS * 0.5
+ dx, dy = aim_to(b, mob_centre(case) + (lead - g.e.pos))
+
+ def shape(sim):
+ gap, reach = golem_gap(sim), box_reach(sim)
+ s = -1.2 * max(0.0, reach - 2.7) - 1.2 * max(0.0, 0.6 - gap) + safe_shape(sim) + golem_threat(sim)
+ if gap < 2.0: # keep open floor behind: circle away from walls and corners
+ s += 1.5 * min(retreat_room(sim), 6.0)
+ return s - 0.02 * view_error(sim.body, mob_centre(sim))
+
+ swings = [None]
+ if wheel == 0 and box_reach(case) < 4.0:
+ swings += swing_slots(b)
+ cands = []
+ for move in MOVES:
+ for jump in ((), (0, 1, 2)):
+ if jump and move not in ("", "W", "S"):
+ continue
+ for sw in swings:
+ if jump and sw is not None and not (not b.e.on_ground and b.e.vel[1] < 0):
+ continue
+ cands.append(build(move, jump=jump, swing=sw, mouse=(dx, dy), wheel=wheel, last=m["last"]))
+ # turn and sprint away (0.281 b/t sprint vs the golem's 0.11-0.15 b/t chase); the continuation keeps running
+ # so the rollout prices the escape, not a turn back into the slam
+ away = math.atan2(b.e.pos[2] - g.e.pos[2], b.e.pos[0] - g.e.pos[0])
+ for off in (-0.6, 0.0, 0.6):
+ turn = math.degrees(wrap(away + off - b.e.yaw)) / DEG
+ run = lambda sim, last: build("W", sprint=True, last=last)
+ cands.append((build("W", sprint=True, mouse=(turn, 0), wheel=wheel, last=m["last"]), run))
+ return best_of(case, m, cands, golem_cont, shape, horizon=4, taken_w=24.0)
+
+
+def plan_zombie(case, m):
+ return plan_melee(case, m, band=(2.5, 3.1), threat_reach=2.5)
+
+
+def plan_zombie_leader(case, m):
+ """Leader zombie with reinforcements (minecraft-arena@5; its own case since @6): fight at the edge of the horde, hit the leader on full
+ charges and cut down a reinforcement that comes into the sword's reach first (an add swipes as hard as the leader
+ but dies in two crits; the leader's hits on the player are what lose the fight). Priced like the golem, per zombie."""
+ b, g = case.body, case.boss
+ wheel = weapon_wheel(case, "sword")
+ target = horde_target(case)
+ lead = target.e.pos + target.e.vel * TICKS * 0.5
+ dx, dy = aim_to(b, mob_centre_of(target) + (lead - target.e.pos))
+ adds0 = {z.n: max(z.hp, 0.0) for z in g.minions if z.hp > 0}
+
+ def shape(sim):
+ gap, reach = mob_gap(sim, sim.boss), mob_reach(sim, sim.boss)
+ s = -0.8 * max(0.0, reach - 2.7) - 1.0 * max(0.0, 0.5 - gap) + safe_shape(sim) + horde_threat(sim)
+ alive = {z.n: max(z.hp, 0.0) for z in sim.boss.minions if z.hp > 0}
+ s += 6.0 * sum(hp - alive.get(n, 0.0) for n, hp in adds0.items()) # thinning the horde
+ s += 40.0 * sum(1 for n in adds0 if n not in alive) # a dead add stops swinging for good
+ s += 1.0 * min(retreat_room(sim), 6.0) * min(horde_near(sim), 3) # keep open floor behind when crowded
+ t = horde_target(sim)
+ return s - 0.02 * view_error(sim.body, mob_centre_of(t))
+
+ swings = [None]
+ if wheel == 0 and any(mob_reach(case, z) < 3.6 for z in horde(case)):
+ swings += swing_slots(b)
+ cands = []
+ for move in MOVES:
+ for jump in ((), (0, 1, 2)):
+ if jump and move not in ("", "W", "S"):
+ continue
+ for sw in swings:
+ if jump and sw is not None and not (not b.e.on_ground and b.e.vel[1] < 0):
+ continue
+ cands.append(build(move, jump=jump, swing=sw, mouse=(dx, dy), wheel=wheel, last=m["last"]))
+ centre = np.mean([z.e.pos for z in horde(case)], axis=0)
+ away = math.atan2(b.e.pos[2] - centre[2], b.e.pos[0] - centre[0])
+ for off in (-0.9, 0.0, 0.9):
+ turn = math.degrees(wrap(away + off - b.e.yaw)) / DEG
+ run = lambda sim, last: build("W", sprint=True, last=last)
+ cands.append((build("W", sprint=True, mouse=(turn, 0), wheel=wheel, last=m["last"]), run))
+ return best_of(case, m, cands, horde_cont, shape, horizon=3, taken_w=14.0)
+
+
+def mob_centre_of(mob):
+ return (mob.hit_lo() + mob.hit_hi()) / 2
+
+
+def horde_target(sim):
+ """Whom to aim at: a reinforcement in sword reach that one full-charge hit kills (it would otherwise keep swinging
+ for 2.5-4.5 a time), else a reinforcement clearly closer than the leader, else the leader."""
+ g = sim.boss
+ one_hit = mc4d.armor_reduce(sim.body.k.sword_dmg * 1.5, g.armor, 0.0)
+ best, best_key = g, (2, mob_reach(sim, g))
+ for z in g.minions:
+ if z.hp <= 0:
+ continue
+ r = mob_reach(sim, z)
+ if r < 2.9 and z.hp <= one_hit:
+ key = (0, r)
+ elif r < 2.9 and r < mob_reach(sim, g) - 0.3:
+ key = (1, r)
+ else:
+ continue
+ if key < best_key:
+ best, best_key = z, key
+ return best
+
+
+# ------------------------------------------------------------------------------------------- shared melee helpers (@5)
+def mob_gap(sim, mob):
+ """Blocks between the player's box and this mob's 1.20.2 attack box (Chebyshev; negative = inside)."""
+ p = sim.body.e
+ r = mob.half[0] + mob.ATTACK_INFLATE + mc4d.PLAYER_W / 2
+ return max(abs(p.pos[0] - mob.e.pos[0]), abs(p.pos[2] - mob.e.pos[2])) - r
+
+
+def mob_reach(sim, mob):
+ """Distance from the player's eye to this mob's hitbox (the sword ray reaches 3)."""
+ eye = sim.body.e.pos + [0, mc4d.EYE, 0]
+ return float(np.linalg.norm(eye - np.clip(eye, mob.hit_lo(), mob.hit_hi())))
+
+
+def horde(sim):
+ return [sim.boss] + [z for z in getattr(sim.boss, "minions", ()) if z.hp > 0]
+
+
+def horde_near(sim, within=3.0):
+ return sum(mob_gap(sim, z) < within for z in horde(sim))
+
+
+def horde_threat(sim):
+ """Swings beyond the rollout horizon, for every zombie: inside an attack box while its cooldown runs out."""
+ s = 0.0
+ for z in horde(sim):
+ gap = mob_gap(sim, z)
+ if z.state == "windup":
+ s -= 16.0 * max(0.0, 0.45 - gap)
+ elif z.state in ("chase", "recover") and z.cd <= mc4d.ticks(6):
+ s -= 6.0 * max(0.0, 0.5 - gap)
+ return s
+
+
+def horde_cont(sim, last):
+ """Continuation: face the current target (an add in reach, else the leader), back away from whichever zombie is
+ about to swing, close in when the leader is out of sword reach, swing on a full charge."""
+ b, g = sim.body, sim.boss
+ target = horde_target(sim)
+ dx, dy = aim_to(b, mob_centre_of(target))
+ threat = min(horde(sim), key=lambda z: mob_gap(sim, z))
+ tgap = mob_gap(sim, threat)
+ back = "S"
+ if retreat_room(sim, flat(b.e.pos - threat.e.pos)) < 1.5:
+ back = "A" if retreat_room(sim, -b.e.right) >= retreat_room(sim, b.e.right) else "D"
+ hot = threat.state == "windup" or (threat.state in ("chase", "recover") and threat.cd <= mc4d.ticks(8))
+ if hot and tgap < 0.6:
+ move = back
+ elif mob_reach(sim, g) > 2.8:
+ move = "W"
+ else:
+ move = ""
+ swing = 0 if b.weapon == "sword" and charge_at(b, 0) > 0.9 and b.ray_hit(sim) is not None else None
+ return build(move, swing=swing, mouse=(dx, dy), last=last)
+
+
+# ------------------------------------------------------------------------------------------- warden (@5)
+def warden_threat(sim):
+ """The warden's smash lands on anything in its attack box when the windup ends; it out-walks a backpedalling
+ player, so the only escape is backing out *during* the windup, from the edge of its box. One smash costs 8-15 HP.
+ Price being deep inside the box while its cooldown runs out (no escape from there) and being airborne then."""
+ g, b = sim.boss, sim.body
+ gap = mob_gap(sim, g)
+ s = 0.0
+ if g.phase == "windup":
+ s -= 90.0 * max(0.0, 0.5 - gap)
+ elif g.phase in ("chase", "recover"):
+ soon = max(0.0, 1.0 - g.cd / mc4d.ticks(24)) # 0 with 24+ vanilla ticks of cooldown left, 1 at 0
+ s -= 60.0 * soon * max(0.0, 0.45 - gap - 0.55 * (1.0 - soon))
+ if not b.e.on_ground and soon > 0.5:
+ s -= 20.0 * max(0.0, 1.3 - gap)
+ return s
+
+
+def warden_cont(sim, last):
+ """Continuation: face the warden; while it winds up, backpedal (sideways at a wall); in its recovery and early
+ cooldown stay in sword reach; as the cooldown runs out, drift to the edge of its attack box; swing on full charge."""
+ b, g = sim.body, sim.boss
+ dx, dy = aim_to(b, mob_centre(sim))
+ gap, reach = mob_gap(sim, g), mob_reach(sim, g)
+ back = "S"
+ if retreat_room(sim) < 1.5:
+ back = "A" if retreat_room(sim, -b.e.right) >= retreat_room(sim, b.e.right) else "D"
+ if g.phase == "windup" and gap < 0.6:
+ move = back
+ elif g.phase in ("chase", "recover") and g.cd <= mc4d.ticks(12) and gap < 0.1:
+ move = back
+ elif reach > 2.8:
+ move = "W"
+ else:
+ move = ""
+ swing = 0 if b.weapon == "sword" and charge_at(b, 0) > 0.9 and b.ray_hit(sim) is not None else None
+ return build(move, swing=swing, mouse=(dx, dy), last=last)
+
+
+def plan_warden(case, m):
+ b, g = case.body, case.boss
+ wheel = weapon_wheel(case, "sword")
+ dx, dy = aim_to(b, mob_centre(case))
+
+ def shape(sim):
+ w = sim.boss
+ gap, reach = mob_gap(sim, w), mob_reach(sim, w)
+ s = -1.0 * max(0.0, reach - 2.7) + safe_shape(sim) + warden_threat(sim)
+ if gap < 2.0:
+ s += 1.5 * min(retreat_room(sim), 6.0)
+ s -= 0.3 * max(0.0, w.out_of_reach / mc4d.FPS - 2.0) # staying out of reach invites a sonic boom
+ return s - 0.02 * view_error(sim.body, mob_centre(sim))
+
+ swings = [None]
+ if wheel == 0 and mob_reach(case, g) < 4.0:
+ swings += swing_slots(b)
+ # No crit jumps once its cooldown is nearly over: a player in the air when the smash winds up cannot back out of
+ # the attack box (no air control), and the smash lands after the rollout horizon (found 2026-11-03, hard seed 2).
+ jump_ok = g.phase in ("recover", "boom_recover") or (g.phase == "chase" and g.cd > mc4d.ticks(24))
+ cands = []
+ for move in MOVES:
+ for jump in ((), (0, 1, 2)):
+ if jump and (move not in ("", "W", "S") or not jump_ok):
+ continue
+ for sw in swings:
+ if jump and sw is not None and not (not b.e.on_ground and b.e.vel[1] < 0):
+ continue
+ cands.append(build(move, jump=jump, swing=sw, mouse=(dx, dy), wheel=wheel, last=m["last"]))
+ away = math.atan2(b.e.pos[2] - g.e.pos[2], b.e.pos[0] - g.e.pos[0])
+ for off in (-0.6, 0.0, 0.6):
+ turn = math.degrees(wrap(away + off - b.e.yaw)) / DEG
+ run = lambda sim, last: build("W", sprint=True, last=last)
+ cands.append((build("W", sprint=True, mouse=(turn, 0), wheel=wheel, last=m["last"]), run))
+ return best_of(case, m, cands, warden_cont, shape, horizon=4, taken_w=24.0)
+
+
+# ------------------------------------------------------------------------------------------- skeleton (@5)
+def arrow_threat(sim):
+ """Boss arrows closing on the player beyond the rollout horizon."""
+ p = sim.body.e.pos + [0, 0.9, 0]
+ pen = 0.0
+ for a in getattr(sim.boss, "arrows", ()):
+ rel = p - a["pos"]
+ dist = float(np.linalg.norm(rel))
+ v = a["vel"]
+ speed = float(np.linalg.norm(v)) + 1e-9
+ if dist < 12 and float(rel @ v) / (dist * speed + 1e-9) > 0.6:
+ pen += max(0.0, 1.0 - float(np.linalg.norm(np.cross(rel, v / speed)))) * 2.0
+ return pen
+
+
+def skeleton_cont(sim, last):
+ """Continuation: when the draw is about to release, strafe across the line of fire (a Java skeleton does not lead
+ its target, so a side-step beats the arrow beyond ~2.5 blocks); otherwise close in (sprinting when far) and
+ swing on a full charge."""
+ b, g = sim.body, sim.boss
+ dx, dy = aim_to(b, mob_centre(sim))
+ if g.state == "windup" and g.timer < 0.45:
+ side = "A" if retreat_room(sim, -b.e.right) >= retreat_room(sim, b.e.right) else "D"
+ return build(side, mouse=(dx, dy), last=last)
+ reach = mob_reach(sim, g)
+ if reach > 6.0:
+ return build("W", sprint=True, mouse=(dx, dy), last=last)
+ move = "W" if reach > 2.6 else ""
+ swing = 0 if b.weapon == "sword" and charge_at(b, 0) > 0.9 and b.ray_hit(sim) is not None else None
+ return build(move, swing=swing, mouse=(dx, dy), last=last)
+
+
+def plan_skeleton(case, m):
+ b, g = case.body, case.boss
+ wheel = weapon_wheel(case, "sword")
+ lead = g.e.pos + g.e.vel * TICKS * 0.5
+ dx, dy = aim_to(b, mob_centre(case) + (lead - g.e.pos))
+
+ def shape(sim):
+ s_ = sim.boss
+ drawing = s_.state == "windup"
+ s = -(0.25 if drawing else 0.8) * max(0.0, mob_reach(sim, s_) - 2.6) - arrow_threat(sim) + safe_shape(sim)
+ return s - 0.02 * view_error(sim.body, mob_centre(sim))
+
+ swings = [None]
+ if wheel == 0 and mob_reach(case, g) < 4.0:
+ swings += swing_slots(b)
+ cands = []
+ for move in MOVES:
+ for jump in ((), (0, 1, 2)):
+ if jump and move not in ("", "W"):
+ continue
+ for sw in swings:
+ if jump and sw is not None and not (not b.e.on_ground and b.e.vel[1] < 0):
+ continue
+ cands.append(build(move, jump=jump, swing=sw, mouse=(dx, dy), wheel=wheel, last=m["last"]))
+ for jump in ((), (0, 1)): # sprint (and sprint-jump) straight at it
+ cands.append(build("W", jump=jump, sprint=True, mouse=(dx, dy), wheel=wheel, last=m["last"]))
+ if g.state == "windup": # sprint across the line of fire (5.6 b/s vs walking 4.3)
+ to = math.atan2(g.e.pos[2] - b.e.pos[2], g.e.pos[0] - b.e.pos[0])
+ for off in (-math.pi / 2, math.pi / 2):
+ turn = math.degrees(wrap(to + off - b.e.yaw)) / DEG
+ run = lambda sim, last: build("W", sprint=True, last=last)
+ cands.append((build("W", sprint=True, mouse=(turn, 0), wheel=wheel, last=m["last"]), run))
+ # An arrow costs more than a crit gains: Java Hard arrows (every 2 s, 4-8) out-damage natural regeneration ten to
+ # one, so trading hits loses any fight longer than a minute (found 2026-11-03: hard 1/3 at a weight of 10).
+ return best_of(case, m, cands, skeleton_cont, shape, horizon=3, taken_w=20.0)
+
+
+# ------------------------------------------------------------------------------------------- bow helpers
+def ballistic_pitch(dx_h, dy, power=1.0):
+ """Pitch (rad) that makes a bow arrow of this power pass (dx_h, dy) relative to the eye (vanilla physics)."""
+ speed = mc4d.BOW_RULES['maximum_speed_blocks_per_vanilla_tick'] * power
+ g, drag = mc4d.BOW_RULES['gravity_blocks_per_vanilla_tick_squared'], mc4d.BOW_RULES['drag_per_vanilla_tick']
+
+ def height_at(pitch):
+ vx, vy, x, y = speed * math.cos(pitch), speed * math.sin(pitch), 0.0, 0.0
+ for n in range(200):
+ if x + vx >= dx_h:
+ u = (dx_h - x) / max(vx, 1e-9)
+ return y + vy * u, n + u
+ x, y = x + vx, y + vy
+ vx, vy = vx * drag, vy * drag - g
+ return -1e9, 200
+
+ lo, hi = -1.45, 1.45
+ pitch = math.atan2(dy, max(dx_h, 1e-6))
+ for _ in range(18):
+ h, _ = height_at(pitch)
+ if h < dy:
+ lo = pitch
+ else:
+ hi = pitch
+ pitch = (lo + hi) / 2
+ return pitch, height_at(pitch)[1]
+
+
+def bow_aim(case, point_fn, sim_future=None):
+ """Mouse to aim a full-power arrow at a moving point. point_fn(sim) gives the aim point in a state;
+ sim_future: list of (tick offset, point) predictions used for the lead."""
+ b = case.body
+ eye = b.e.pos + [0, mc4d.EYE, 0]
+ point = point_fn(case)
+ flight = 0.0
+ for _ in range(3):
+ target = point
+ if sim_future:
+ k = min(len(sim_future) - 1, int(round(flight / mc4d.VT)) + TICKS)
+ target = sim_future[k]
+ d = target - eye
+ pitch, flight = ballistic_pitch(math.hypot(d[0], d[2]), d[1])
+ yaw = math.atan2(d[2], d[0])
+ return math.degrees(wrap(yaw - b.e.yaw)) / DEG, -math.degrees(pitch - b.e.pitch) / DEG, target
+
+
+def predict(case, m, point_fn, n_packets=3, move=""):
+ """Future aim points (per tick) if the player stands (or keeps `move`), from a clone rollout."""
+ sim = clone(case)
+ out = [point_fn(sim)]
+ last = m["last"]
+ for _ in range(n_packets):
+ held = build(move, rmb="hold" if sim.body.bow_drawing else None, last=last)
+ sched, last = km.schedule(held, TICKS, last)
+ for h, p, mo in sched:
+ if sim.outcome():
+ break
+ sim.tick(sim.body.keys(sim, h, p, mo))
+ out.append(point_fn(sim))
+ return out
+
+
+def bow_cands(case, m, point_fn, moves=MOVES, wheel=0, extra_shape=None, allow_release=True):
+ """Candidates while using the bow: keep drawing (with each movement) or release at substep j."""
+ b = case.body
+ future = predict(case, m, point_fn)
+ dx, dy, _ = bow_aim(case, point_fn, future)
+ cands = []
+ full_in = max(0, int(mc4d.FPS * mc4d.BOW_RULES['draw_seconds']) - b.bow_draw_ticks)
+ for move in moves:
+ cands.append(build(move, rmb="hold", mouse=(dx, dy), wheel=wheel, last=m["last"]))
+ if b.bow_drawing and allow_release:
+ for j in range(6):
+ if 2 * j >= full_in:
+ cands.append(build(move, rmb=j, mouse=(dx, dy), wheel=wheel, last=m["last"]))
+ return cands, (dx, dy)
+
+
+def bow_cont(point_fn):
+ def cont(sim, last):
+ b = sim.body
+ point = point_fn(sim)
+ eye = b.e.pos + [0, mc4d.EYE, 0]
+ d = point - eye
+ pitch, _ = ballistic_pitch(math.hypot(d[0], d[2]), d[1])
+ yaw = math.atan2(d[2], d[0])
+ dx, dy = math.degrees(wrap(yaw - b.e.yaw)) / DEG, -math.degrees(pitch - b.e.pitch) / DEG
+ full = b.bow_draw_ticks >= mc4d.FPS * mc4d.BOW_RULES['draw_seconds']
+ return build("", rmb=0 if full else "hold", mouse=(dx, dy), last=last)
+ return cont
+
+
+def arrow_score_horizon(case):
+ return 3 # arrows need ~1-3 packets to land
+
+
+# ------------------------------------------------------------------------------------------- wither
+def wither_body(sim):
+ g = sim.boss
+ return (g.hit_lo() + g.hit_hi()) / 2 + [0, 0.3, 0]
+
+
+def skull_threat(sim):
+ """Penalty for skulls closing on the player (predicts hits beyond the rollout horizon)."""
+ p = sim.body.e.pos + [0, 0.9, 0]
+ pen = 0.0
+ for s in sim.boss.skulls:
+ rel = p - s["pos"]
+ dist = float(np.linalg.norm(rel))
+ v = s["vel"]
+ speed = float(np.linalg.norm(v)) + 1e-9
+ closing = float(rel @ v) / (dist * speed + 1e-9)
+ if closing > 0.6 and dist < 8:
+ miss = float(np.linalg.norm(np.cross(rel, v / speed)))
+ pen += max(0.0, 1.2 - miss) * 3.0
+ return pen
+
+
+def plan_wither(case, m):
+ b, g = case.body, case.boss
+ if g.state == "spawn":
+ # run to the far side and face the wither; the power-7 blast reaches 14 blocks
+ wheel = weapon_wheel(case, "bow")
+ away = flat(b.e.pos - g.e.pos)
+ away /= np.linalg.norm(away) + 1e-9
+ goal = np.clip(g.e.pos + away * 20.0, 2.5, mc4d.S - 2.5)
+ dist_goal = hdist(b.e.pos, goal)
+ face = goal if dist_goal > 1.5 else g.e.pos + [0, 1.0, 0]
+ dx, dy = aim_to(b, face + [0, mc4d.EYE if dist_goal > 1.5 else 0, 0])
+ mv = "W" if dist_goal > 1.0 else ""
+
+ def shape(sim):
+ return -1.5 * max(0.0, 15.5 - hdist(sim.body.e.pos, sim.boss.e.pos)) + safe_shape(sim, 0.05)
+ cands = [build(mv, jump=j, sprint=True, mouse=(dx, dy), wheel=wheel, last=m["last"]) for j in ((), (0, 1))]
+ cands += [build(k, mouse=(dx, dy), wheel=wheel, last=m["last"]) for k in ("A", "D")]
+ return best_of(case, m, cands, lambda sim, last: build(mv, sprint=True, mouse=(0, 0), last=last), shape)
+
+ if g.armored:
+ # phase 2: sword on the ground, keep 2.2-2.8 blocks, dodge skulls
+ wheel = weapon_wheel(case, "sword")
+ point = wither_body(case) - [0, 0.6, 0]
+ dx, dy = aim_to(b, point)
+ dist = hdist(b.e.pos, g.e.pos)
+
+ def shape(sim):
+ d = hdist(sim.body.e.pos, sim.boss.e.pos)
+ return -1.0 * abs(d - 2.5) - skull_threat(sim) + safe_shape(sim) - 0.02 * view_error(sim.body, wither_body(sim))
+ swings = [None]
+ if wheel == 0 and dist < 4.5:
+ swings += swing_slots(b)
+ cands = []
+ for move in MOVES:
+ for jump in ((), (0, 1, 2)):
+ if jump and move not in ("", "W"):
+ continue
+ for sw in swings:
+ cands.append(build(move, jump=jump, swing=sw, mouse=(dx, dy), wheel=wheel, last=m["last"]))
+ # A skull fired from 2-3 blocks lands within a packet, before the 2-packet rollout can price a dodge, and on
+ # Java Hard each one carries 40 s of Wither II. When one is closing in, look 3 packets ahead and value
+ # health like the long fight it is (found 2026-11-02: hard-tier losses were all to skulls at melee range).
+ incoming = skull_threat(case) > 0.0
+ return best_of(case, m, cands, greedy_melee(lambda s: wither_body(s) - [0, 0.6, 0], (2.2, 2.8)), shape,
+ horizon=3 if incoming else 2, taken_w=16.0 if incoming else 8.0)
+
+ # phase 1: bow, keep 4-9 blocks horizontally, dodge skulls between draws
+ wheel = weapon_wheel(case, "bow")
+ if wheel:
+ dx, dy = aim_to(b, wither_body(case))
+ return build("S", mouse=(dx, dy), wheel=wheel, last=m["last"])
+
+ def shape(sim):
+ d = hdist(sim.body.e.pos, sim.boss.e.pos)
+ eye = sim.body.e.pos + [0, mc4d.EYE, 0]
+ sight = 0.0 if sim.arena.los(eye, wither_body(sim), eye_h=0.0) else -2.5
+ # a wither directly overhead fires straight down: keep 5-9 blocks of horizontal distance
+ return (-0.2 * max(0.0, d - 10) - 0.8 * max(0.0, 5.0 - d) - 0.25 * skull_threat(sim) + safe_shape(sim) + sight
+ + 0.05 * min(sim.body.bow_draw_ticks, 60))
+ cands, _ = bow_cands(case, m, wither_body, moves=("", "A", "D", "S", "W"))
+ look = aim_to(b, wither_body(case))
+ if not b.bow_drawing or b.bow_draw_ticks <= 15: # releasing a longer draw would waste it on a weak arrow
+ cands += [build(mv, mouse=look, last=m["last"]) for mv in ("A", "D", "S", "W")]
+ elif g.skulls: # a skull is coming: release now and sidestep at full speed
+ for mv in ("A", "D"):
+ keep = lambda sim, last, mv=mv: build(mv, mouse=aim_to(sim.body, wither_body(sim)), last=last)
+ cands.append((build(mv, mouse=look, last=m["last"]), keep))
+ return best_of(case, m, cands, bow_cont(wither_body), shape, horizon=3)
+
+
+# ------------------------------------------------------------------------------------------- ender dragon
+def dragon_head(sim):
+ return sim.boss.head_center()
+
+
+def head_reach(sim):
+ """Distance from the player's eye to the dragon's head box; the sword ray reaches 3."""
+ h = sim.boss.head_center()
+ eye = sim.body.e.pos + [0, mc4d.EYE, 0]
+ return float(np.linalg.norm(eye - np.clip(eye, h - [0.55, 0.45, 0.55], h + [0.55, 0.45, 0.55])))
+
+
+def perch_cont(sim, last):
+ """Continuation at a perched dragon: walk into sword reach of the head (never into its contact box), step out
+ of a breath cloud sideways, swing on a full charge."""
+ b, g = sim.body, sim.boss
+ h = g.head_center()
+ dx, dy = aim_to(b, h)
+ gap = max(abs(b.e.pos[0] - h[0]), abs(b.e.pos[2] - h[2])) - 1.85
+ inside = [c for c in g.clouds if hdist(b.e.pos, c["pos"]) < c["r"] + 0.3]
+ if inside:
+ c = inside[0]
+ side = float(np.dot(flat(b.e.pos - c["pos"]), b.e.right))
+ move = "D" if side >= 0 else "A"
+ elif gap < 0.3:
+ move = "S"
+ elif head_reach(sim) > 2.7:
+ move = "W"
+ else:
+ move = ""
+ swing = 0 if b.weapon == "sword" and charge_at(b, 0) > 0.9 and b.ray_hit(sim) is not None else None
+ return build(move, swing=swing, mouse=(dx, dy), last=last)
+
+
+def dragon_body(sim):
+ return sim.boss.e.pos.copy()
+
+
+def clear_shot(sim, point):
+ """True when the straight line from the player's eye to point crosses no terrain (a cheap proxy for the
+ ballistic arc, which only rises above it)."""
+ eye = sim.body.e.pos + [0, mc4d.EYE, 0]
+ wall, _ = sim._arrow_world_hit(eye, np.asarray(point, float))
+ return wall is None or wall >= 0.999
+
+
+BLAST_SAFE = 12.5 # power-6 crystal blast reaches 12 blocks (mc4d.crystal_destroyed)
+
+
+def crystal_dist(sim, c):
+ return float(np.linalg.norm(sim.body.e.pos + [0, 0.9, 0] - c["pos"]))
+
+
+def crystal_target(case):
+ """Only the crystal that is shot explodes. Prefer one in the clear and already outside its blast: the healing
+ crystal first (breaking it also hurts the dragon), then the one nearest 13 blocks away."""
+ g = case.boss
+ alive = [c for c in g.crystals if c["alive"]]
+ if not alive:
+ return None
+ p = case.body.e.pos
+
+ def key(c):
+ clear = clear_shot(case, c["pos"] + [0, 0.8, 0])
+ return (not clear, crystal_dist(case, c) < BLAST_SAFE, c is not g.heal_from, abs(hdist(p, c["pos"]) - 13.0),
+ c["id"])
+ return min(alive, key=key)
+
+
+def plan_dragon(case, m):
+ b, g = case.body, case.boss
+ sitting = g.phase in g.SITTING
+ clouds = g.clouds
+
+ def cloud_pen(sim):
+ p = sim.body.e.pos
+ pen = 0.0
+ for c in sim.boss.clouds:
+ d = hdist(p, c["pos"])
+ pen += max(0.0, c["r"] + 1.0 - d) * 2.0
+ for f in sim.boss.fireballs:
+ rel = p + [0, 0.9, 0] - f["pos"]
+ dist = float(np.linalg.norm(rel))
+ if dist < 12:
+ miss = float(np.linalg.norm(np.cross(rel, f["dir"])))
+ pen += max(0.0, 3.5 - miss) * 0.8
+ return pen
+
+ if sitting and g.phase != "landing":
+ # perched: sword on the head (full damage). The perched dragon keeps turning to face the player, so the
+ # head is always attacked from the front: inside sword reach, outside the head's contact box, and out of the
+ # breath cloud it drops in front of its head (the cloud stays where it fell; a sidestep leaves it).
+ wheel = weapon_wheel(case, "sword")
+ head = g.head_center()
+ dx, dy = aim_to(b, head)
+
+ def shape(sim):
+ h = sim.boss.head_center()
+ p = sim.body.e.pos
+ gap = max(abs(p[0] - h[0]), abs(p[2] - h[2])) - 1.85 # > 0: outside the contact box
+ return (-1.5 * max(0.0, head_reach(sim) - 2.6) - cloud_pen(sim) - 0.03 * view_error(sim.body, h)
+ - 12.0 * max(0.0, 0.25 - gap))
+ swings = [None]
+ if wheel == 0 and head_reach(case) < 3.6:
+ swings += swing_slots(b)
+ cands = []
+ for move in MOVES:
+ for jump in ((), (0, 1, 2)):
+ if jump and move not in ("", "W"):
+ continue
+ for sw in swings:
+ cands.append(build(move, jump=jump, swing=sw, mouse=(dx, dy), wheel=wheel, last=m["last"]))
+ return best_of(case, m, cands, perch_cont, shape, horizon=3)
+
+ danger = any(hdist(b.e.pos, c["pos"]) < c["r"] + 0.6 for c in clouds) or any(
+ _fireball_lands_near(case, f) for f in g.fireballs)
+ if danger:
+ return flee(case, m, cloud_pen)
+ if g.phase == "strafe" and g.goal is not None:
+ return lineup_dodge(case, m, cloud_pen)
+ wheel = weapon_wheel(case, "bow")
+ crystal = crystal_target(case)
+ if crystal is not None:
+ point_fn = lambda sim, cid=crystal["id"]: sim.boss.crystals[cid]["pos"] + [0, 0.8, 0]
+ want = 13.0
+ else:
+ point_fn = dragon_head
+ want = 9.0
+ if wheel:
+ dx, dy = aim_to(b, point_fn(case))
+ return build("", mouse=(dx, dy), wheel=wheel, last=m["last"])
+
+ def shape(sim):
+ s = -cloud_pen(sim) + safe_shape(sim)
+ if crystal is not None:
+ c = sim.boss.crystals[crystal["id"]]
+ s -= 0.3 * abs(hdist(sim.body.e.pos, c["pos"]) - want)
+ s -= 3.0 * max(0.0, BLAST_SAFE - crystal_dist(sim, c))
+ if not clear_shot(sim, point_fn(sim)): # a draw held at a hidden crystal is wasted time
+ s -= 3.0
+ else:
+ s -= 0.1 * abs(hdist(sim.body.e.pos, [mc4d.MID, 0, mc4d.MID]) - 6.0)
+ return s
+ too_close = crystal is not None and crystal_dist(case, crystal) < BLAST_SAFE
+ cands, _ = bow_cands(case, m, point_fn, allow_release=not too_close)
+ if too_close: # run out of the power-6 blast before shooting: 8 headings
+ cands = []
+ for k in range(8):
+ turn = math.degrees(wrap(2 * math.pi * k / 8 - b.e.yaw)) / DEG
+ run = lambda sim, last: build("W", sprint=True, last=last)
+ cands.append((build("W", sprint=True, mouse=(turn, 0), last=m["last"]), run))
+ return best_of(case, m, cands, None, shape, horizon=2)
+ return best_of(case, m, cands, bow_cont(point_fn), shape, horizon=3)
+
+
+def _fireball_lands_near(case, f, radius=3.6):
+ p = case.body.e.pos
+ rel = p + [0, 0.9, 0] - f["pos"]
+ along = float(rel @ f["dir"])
+ if along < 0 or along > 14:
+ return False
+ return float(np.linalg.norm(rel - f["dir"] * along)) < radius
+
+
+def flee(case, m, penalty):
+ """Sprint out of a hazard: 8 headings, continuation keeps running; bow draw is dropped."""
+ b = case.body
+ cands = []
+ for k in range(8):
+ yaw = 2 * math.pi * k / 8
+ dx = math.degrees(wrap(yaw - b.e.yaw)) / DEG
+ cands.append(build("W", jump=(0, 1) if k % 2 else (), sprint=True, mouse=(dx, 0), last=m["last"]))
+ return best_of(case, m, cands, lambda sim, last: build("W", sprint=True, last=last),
+ lambda sim: -2.0 * penalty(sim) + safe_shape(sim), horizon=3)
+
+
+def lineup_dodge(case, m, penalty):
+ """The dragon is lining up a fireball (mouth glow, HUD flash): the shot goes where the player stands when it
+ fires and its cloud is 3 blocks wide, so drop the draw and sprint across the dragon's line of approach."""
+ b, g = case.body, case.boss
+ p0 = b.e.pos.copy()
+ line = flat(p0 - g.e.pos)
+ line /= float(np.linalg.norm(line)) + 1e-9
+
+ def shape(sim):
+ moved = flat(sim.body.e.pos - p0)
+ across = abs(moved[0] * line[2] - moved[2] * line[0])
+ return 2.0 * min(across, 4.0) - 2.0 * penalty(sim) + safe_shape(sim)
+ cands = []
+ for k in range(8):
+ dx = math.degrees(wrap(2 * math.pi * k / 8 - b.e.yaw)) / DEG
+ cands.append(build("W", jump=(0, 1) if k % 2 else (), sprint=True, mouse=(dx, 0), last=m["last"]))
+ return best_of(case, m, cands, lambda sim, last: build("W", sprint=True, last=last), shape, horizon=3)
+
+
+PLANNERS = {"iron_golem": plan_golem, "zombie": plan_zombie, "ender_dragon": plan_dragon, "wither": plan_wither,
+ "warden": plan_warden, "skeleton": plan_skeleton, "zombie_leader": plan_zombie_leader}
+
+
+# ------------------------------------------------------------------------------------------- self-check
+def play(mob, seed=1, d=0.5, weapon="sword", max_packets=None, verbose=False):
+ """Run the controller on a bare MobFight (no renderer) to the terminal outcome; for quick tuning."""
+ case = mc4d.MobFight(mob, style=mc4d.STYLES[mob], weapon=weapon, max_seconds=mc4d.SECONDS[mob])
+ case.reset(seed, d)
+ last = frozenset()
+ limit = max_packets or int(mc4d.SECONDS[mob] * 5)
+ for i in range(limit):
+ p = km.parse_packet(scripted(case))
+ assert p is not None
+ case.events.clear()
+ last = run_packet(case, p, last)
+ if verbose and i % 25 == 0:
+ print(i, case.boss.state, round(case.boss.hp, 1), round(case.body.hp, 1), case.body.weapon)
+ if case.outcome():
+ break
+ return {"mob": mob, "seed": seed, "d": d, "weapon": weapon, "outcome": case.outcome() or "timeout",
+ "seconds": round(case.t / mc4d.FPS, 2), "boss_hp": round(float(case.boss.hp), 1),
+ "player_hp": round(float(case.body.hp), 1)}
diff --git a/environments/games/prototype/bossbench/mcskin.py b/environments/games/prototype/bossbench/mcskin.py
new file mode 100644
index 0000000000000000000000000000000000000000..4debe08dab0baba3afb5c74d5222ffa01fb76f98
--- /dev/null
+++ b/environments/games/prototype/bossbench/mcskin.py
@@ -0,0 +1,1885 @@
+"""Minecraft skin for mc4d: textures, rigs, per-state poses, particles, renderer and HUD.
+
+Everything here is drawing. Pose functions read simulation state and write only to the rig
+(keyframes and rig.mem); particle helpers draw from case.fxrng; nothing reads or advances
+case.rng, so drawing cannot change an episode’s simulation state.
+
+Borrowed from the 2D web client (web/games/hollowknight_remake/draw/wanderer.js + web/engine/renderer.js):
+ * one pose table per boss state, with anticipation / follow-through keyed to state entry
+ * a white hit flash that hands over to the red hurt tint
+ * telegraph glow (eyes, mouth) and an additive halo pass for emissive parts
+ * event-driven juice (sparks, dust, smoke) on its own random stream
+ * a static world baked once (terrain instances), only actors re-uploaded per frame
+"""
+from __future__ import annotations
+
+import math
+import os
+
+import numpy as np
+
+from .core import FPS
+from .rig import Bones, Rig, q_to_mat
+
+# Pose and particle constants below were tuned per vanilla Minecraft tick (20 Hz). The simulation ticks at
+# core.FPS; keyframes stay in simulation ticks, everything time-based is read through VT so animation,
+# fades and particle drift run at the same speed in seconds whatever the tick rate.
+VT = 20 / FPS
+
+
+def _every(case, n):
+ """True once every n vanilla ticks (spawn cadence independent of the tick rate)."""
+ return case.t % max(1, round(n / VT)) == 0
+
+
+def ticks_hit(mob):
+ """A mob's tint_t right after a fresh hit (mc4d sets ticks(8)): picks the minion hurt this very tick."""
+ return round(8 / VT)
+
+# ================================================================ textures
+# 16x16 RGBA tiles in one texture array. Faces are 8x8 Minecraft-style pixel art doubled, the
+# rest is procedural noise from a fixed generator (visual only, built once at import).
+_TR = np.random.default_rng(20261012)
+TILES: dict = {}
+_LAYERS: list = []
+
+
+def _c(*rgb):
+ return np.array(rgb, float)
+
+
+def _tile(name, img):
+ img = np.clip(np.asarray(img, float), 0, 1)
+ if img.shape[2] == 3:
+ img = np.concatenate([img, np.ones((16, 16, 1))], 2)
+ TILES[name] = len(_LAYERS)
+ _LAYERS.append((img * 255).astype(np.uint8))
+
+
+def _noise(base, amt=0.08):
+ return np.broadcast_to(base, (16, 16, 3)) * (1 + _TR.normal(0, amt, (16, 16, 1)))
+
+
+def _art(rows, pal, amt=0.05):
+ """Rows of palette chars -> 16x16 rgba ('_' transparent); art narrower than 16 is scaled up."""
+ h, w = len(rows), len(rows[0])
+ img = np.zeros((h, w, 4))
+ for y, row in enumerate(rows):
+ for x, ch in enumerate(row):
+ if ch != "_":
+ img[y, x, :3], img[y, x, 3] = pal[ch], 1
+ img = img.repeat(16 // h, 0).repeat(16 // w, 1)
+ img[..., :3] *= 1 + _TR.normal(0, amt, (16, 16, 1))
+ return img
+
+
+def _rgba(rgb, a):
+ return np.concatenate([rgb, a[..., None]], 2)
+
+
+def _bricks(base, mortar, h=4, w=8, amt=0.07):
+ img = _noise(base, amt).copy()
+ for y in range(16):
+ off = (w // 2) * ((y // h) % 2)
+ for x in range(16):
+ if y % h == h - 1 or (x + off) % w == w - 1:
+ img[y, x] = mortar * (1 + _TR.normal(0, 0.05))
+ return img
+
+
+def _cells(base, edge, n=9, amt=0.09):
+ """Cobblestone: wrapped Voronoi cells, one shade per cell, dark borders."""
+ pts = _TR.uniform(0, 16, (n, 2))
+ yy, xx = np.mgrid[0:16, 0:16] + 0.5
+ d = np.stack([np.hypot(np.minimum(abs(xx - px), 16 - abs(xx - px)),
+ np.minimum(abs(yy - py), 16 - abs(yy - py))) for px, py in pts])
+ near = np.argmin(d, 0)
+ ds = np.sort(d, 0)
+ shade = (1 + _TR.normal(0, 0.13, n))[near]
+ img = _noise(base, amt) * shade[..., None]
+ img[(ds[1] - ds[0]) < 1.1] = edge
+ return img
+
+
+def _specks(img, color, k=10):
+ img = img.copy()
+ for _ in range(k):
+ x, y = _TR.integers(0, 16, 2)
+ img[y, x] = color
+ return img
+
+
+def _cracks(n):
+ a = np.zeros((16, 16, 4))
+ for _ in range(n):
+ x, y = (int(v) for v in _TR.integers(1, 15, 2))
+ for _ in range(int(_TR.integers(4, 9))):
+ a[y, x] = (0.28, 0.26, 0.25, 1.0)
+ x = int(np.clip(x + _TR.integers(-1, 2), 0, 15))
+ y = int(np.clip(y + _TR.choice([-1, 1]), 0, 15))
+ return a
+
+
+def TEX_FLIP(layer):
+ """A built tile mirrored left-right, back as float rgba."""
+ return layer[:, ::-1].astype(float) / 255
+
+
+def _build_tiles():
+ yy, xx = np.mgrid[0:16, 0:16] + 0.5
+ r = np.hypot(xx - 8, yy - 8) / 8
+ # -- terrain ----------------------------------------------------------
+ grass, dirt = _c(0.45, 0.68, 0.3), _c(0.55, 0.39, 0.26)
+ _tile("grass_top", _specks(_noise(grass, 0.11), grass * 0.78, 20))
+ side = _specks(_noise(dirt, 0.1), dirt * 0.7, 14)
+ for x in range(16):
+ dd = 3 + int(_TR.integers(0, 3))
+ side[:dd, x] = grass * (0.9 + _TR.normal(0, 0.07, (dd, 1)))
+ _tile("grass_side", side)
+ _tile("dirt", _specks(_noise(dirt, 0.1), dirt * 0.7, 18))
+ _tile("stone", _specks(_noise(_c(0.52, 0.52, 0.52), 0.07), _c(0.41, 0.41, 0.42), 22))
+ _tile("cobble", _cells(_c(0.53, 0.53, 0.53), _c(0.3, 0.3, 0.31)))
+ _tile("stone_brick", _bricks(_c(0.5, 0.5, 0.5), _c(0.33, 0.33, 0.34), 8, 16))
+ moss = _cells(_c(0.5, 0.5, 0.5), _c(0.3, 0.3, 0.31))
+ mask = _TR.random((16, 16)) < 0.32
+ moss[mask] = _noise(_c(0.33, 0.46, 0.22), 0.12)[mask]
+ _tile("mossy_cobble", moss)
+ es = _c(0.87, 0.88, 0.64)
+ _tile("end_stone", _specks(_noise(es, 0.06), es * 0.84, 28))
+ _tile("end_brick", _bricks(es, es * 0.72, 4, 8, 0.05))
+ obs = _noise(_c(0.08, 0.06, 0.12), 0.22).copy()
+ for _ in range(7):
+ x, y = _TR.integers(0, 15, 2)
+ obs[y, x:x + 2] = _c(0.26, 0.13, 0.36)
+ _tile("obsidian", obs)
+ _tile("bedrock", _cells(_c(0.34, 0.34, 0.34), _c(0.12, 0.12, 0.12), 14, 0.2))
+ # -- misc -------------------------------------------------------------
+ _tile("shadow", _rgba(np.zeros((16, 16, 3)), np.clip(1 - r, 0, 1) ** 1.2 * 0.85))
+ sw = (np.sin((xx + yy) * 0.8) * 0.5 + 0.5) * (np.sin((xx - yy) * 0.45 + 1) * 0.5 + 0.5)
+ _tile("shell", _rgba(np.stack([sw * 0.5 + 0.35, sw * 0.5 + 0.55, np.ones_like(sw)], 2), 0.3 + 0.7 * sw))
+ _tile("white", np.ones((16, 16, 3)))
+ _tile("glow", _rgba(np.ones((16, 16, 3)), np.clip(1 - r, 0, 1) ** 1.6))
+ _tile("puff", _rgba(np.ones((16, 16, 3)) * (0.85 + 0.15 * (1 - r))[..., None],
+ (np.clip(1.15 - r, 0, 1) > 0.25 + 0.2 * _TR.random((16, 16))).astype(float)))
+ for i in (1, 2, 3):
+ _tile(f"crack{i}", _cracks(3 * i))
+ # -- iron golem -------------------------------------------------------
+ iron, idark = _c(0.87, 0.85, 0.81), _c(0.63, 0.61, 0.58)
+ vine, vdark = _c(0.32, 0.52, 0.2), _c(0.2, 0.36, 0.13)
+
+ def iron_t(rivets=True, vine_col=None):
+ t = _specks(_noise(iron, 0.05), idark, 16)
+ if rivets:
+ for x, y in ((2, 2), (13, 2), (2, 13), (13, 13)):
+ t[y, x], t[y - 1, x] = idark * 0.85, iron * 1.08
+ if vine_col is not None:
+ x = vine_col
+ for y in range(16):
+ x = int(np.clip(x + _TR.integers(-1, 2), 0, 14))
+ t[y, x:x + 2] = (vine if _TR.random() < 0.7 else vdark) * (1 + _TR.normal(0, 0.1))
+ if _TR.random() < 0.4:
+ t[y, int(np.clip(x + _TR.choice([-1, 2]), 0, 15))] = vine * 1.2
+ return t
+ _tile("iron", iron_t())
+ _tile("iron_plain", iron_t(False))
+ _tile("iron_vine", iron_t(True, 5))
+ _tile("iron_chest", iron_t(True, 11))
+ P = {".": iron, ":": idark, "#": _c(0.46, 0.44, 0.42), "r": _c(0.8, 0.12, 0.1), "k": _c(0.2, 0.19, 0.19),
+ "m": _c(0.52, 0.5, 0.47)}
+ _tile("golem_face", _art(["..:.....", "........", "########", ".kr..rk.", "........",
+ "........", "..mmmm..", ".:....:."], P, 0.04))
+ _tile("golem_hand", _noise(idark, 0.06))
+ # -- zombie / steve ---------------------------------------------------
+ Z = {"g": _c(0.36, 0.6, 0.32), "d": _c(0.24, 0.43, 0.22), "k": _c(0.05, 0.06, 0.05),
+ "n": _c(0.27, 0.45, 0.25), "m": _c(0.16, 0.26, 0.15)}
+ _tile("zombie_face", _art(["dgdddgdd", "gdgggdgg", "gggggggg", "gggggggg", "gkkggkkg",
+ "gggnnggg", "ggmmmmgg", "gggggggg"], Z, 0.05))
+ _tile("zombie_head", _art(["dgdddgdd", "gdgggdgg", "gggdgggg", "gggggggg", "ggggggdg",
+ "gdgggggg", "gggggdgg", "gggggggg"], Z, 0.06))
+ _tile("zombie_skin", _noise(Z["g"], 0.07))
+ teal, tdark = _c(0.0, 0.62, 0.62), _c(0.0, 0.46, 0.48)
+ T = {"t": teal, "u": tdark, "g": Z["g"], "b": _c(0.27, 0.25, 0.62), "v": _c(0.2, 0.18, 0.48),
+ "s": _c(0.36, 0.36, 0.4)}
+ _tile("zombie_shirt", _art(["tttttttt", "tttutttt", "tttttttt", "tutttttt", "tttttutt",
+ "tttttttt", "ttttttut", "uutuuttu"], T, 0.06))
+ _tile("zombie_arm", _art(["tttt", "tuuu", "gggg", "gggg", "gggg", "gggg", "gggg", "gggg"], T, 0.06))
+ _tile("zombie_leg", _art(["bbbb", "bbvb", "bbbb", "bvbb", "bbbb", "bbbb", "vbbv", "ssss"], T, 0.06))
+ skin, hair = _c(0.78, 0.58, 0.44), _c(0.3, 0.2, 0.12)
+ S_ = {"h": hair, "s": skin, "w": _c(0.95, 0.95, 0.95), "b": _c(0.3, 0.25, 0.62), "n": _c(0.62, 0.42, 0.3),
+ "m": _c(0.45, 0.27, 0.17), "t": teal, "u": tdark, "p": _c(0.25, 0.23, 0.6), "q": _c(0.2, 0.18, 0.5),
+ "o": _c(0.42, 0.42, 0.44)}
+ _tile("steve_face", _art(["hhhhhhhh", "hhhhhhhh", "hssssssh", "ssssssss", "swbssbws",
+ "sssnnsss", "ssmmmmss", "ssssssss"], S_, 0.03))
+ _tile("steve_side", _art(["hhhhhhhh", "hhhhhhhh", "hhhhhhss", "hhhhssss", "hhhsssss",
+ "hhssssss", "hsssssss", "ssssssss"], S_, 0.04))
+ _tile("steve_hair", _noise(hair, 0.08))
+ _tile("steve_shirt", _art(["tttttttt", "tttttttt", "ttuttutt", "tttttttt", "tttttttt",
+ "tttttttt", "tttttttt", "uuuuuuuu"], S_, 0.04))
+ _tile("steve_arm", _art(["tttt", "tttt", "uuuu", "ssss", "ssss", "ssss", "ssss", "ssss"], S_, 0.04))
+ _tile("steve_leg", _art(["pppp", "pppp", "pqpp", "pppp", "pppp", "ppqp", "oooo", "oooo"], S_, 0.04))
+ _tile("steve_skin", _noise(skin, 0.04))
+ B = {"_": None, "w": _c(0.62, 0.9, 0.95), "l": _c(0.85, 1.0, 1.0), "d": _c(0.2, 0.55, 0.6),
+ "h": _c(0.42, 0.29, 0.16), "k": _c(0.25, 0.17, 0.1)}
+ _tile("sword", _art(["____________lw__", "___________lwd__", "__________lwd___", "_________lwd____",
+ "________lwd_____", "_______lwd______", "______lwd_______", "__d__lwd________",
+ "___dlwd_________", "____dd__________", "___hkd__________", "__hk_dd_________",
+ "_hk_____________", "kh______________", "k_______________", "________________"],
+ {k: v for k, v in B.items() if v is not None}, 0.02))
+ _tile("sword_m", TEX_FLIP(_LAYERS[TILES["sword"]]))
+ _tile("eye_pair", _art(["_ww__ww_"], {"w": _c(1, 1, 1)}, 0.0))
+ # -- ender dragon -----------------------------------------------------
+ sc, sc2 = _c(0.14, 0.13, 0.16), _c(0.22, 0.21, 0.25)
+ scale = _noise(sc, 0.12).copy()
+ for y in range(16):
+ for x in range(16):
+ o = (x + 2 * ((y // 4) % 2)) % 4
+ if y % 4 == 3 and o != 0:
+ scale[y, x] = sc * 0.55
+ elif y % 4 == 0:
+ scale[y, x] = sc2
+ _tile("dragon_scale", scale)
+ _tile("dragon_belly", _bricks(_c(0.25, 0.23, 0.27), _c(0.14, 0.13, 0.16), 4, 16, 0.08))
+ D = {"s": sc, "d": sc * 0.5, "k": _c(0.02, 0.02, 0.03), "l": sc2, "t": _c(0.66, 0.64, 0.58)}
+ _tile("dragon_snout", _art(["llllllll", "skksskks", "ssssssss", "sdssssds", "ssssssss",
+ "tststtst", "ssssssss", "dddddddd"], D, 0.08))
+ _tile("dragon_jaw", _art(["tstststs", "ssssssss", "ssssssss", "sdssssds", "ssssssss",
+ "ssssssss", "ssssssss", "dddddddd"], D, 0.08))
+ _tile("dragon_spike", _noise(_c(0.3, 0.29, 0.33), 0.1))
+ mem, rib = _c(0.2, 0.17, 0.24), _c(0.36, 0.33, 0.39)
+ m = _noise(mem, 0.12).copy()
+ a = np.ones((16, 16))
+ for x in range(16):
+ k = min(abs(x - 1), abs(x - 8), abs(x - 15))
+ if k == 0:
+ m[:, x] = rib * (1 + _TR.normal(0, 0.06, (16, 1)))
+ else: # scalloped trailing edge between ribs
+ cut = int(k * 1.1 + 0.5)
+ a[16 - cut:, x] = 0
+ m[0:2] = rib
+ _tile("wing_membrane", _rgba(m, a))
+ _tile("wing_bone", _noise(rib * 0.9, 0.06))
+ # -- wither -----------------------------------------------------------
+ ch, cd = _c(0.21, 0.21, 0.22), _c(0.12, 0.12, 0.13)
+ W = {"c": ch, "d": cd, "k": _c(0.02, 0.02, 0.02), "w": _c(0.4, 0.39, 0.38), "l": _c(0.28, 0.28, 0.29)}
+ _tile("wither_face", _art(["cccccccc", "cdcclcdc", "cccccccc", "ckkcckkc", "ckkcckkc",
+ "ccckkccc", "ckwkwkwc", "cdccccdc"], W, 0.06))
+ _tile("wither_skull", _art(["cccccccc", "cdcclccc", "ccccccdc", "clcccccc", "ccccdccc",
+ "cccccccl", "cdcccccc", "cccccccc"], W, 0.07))
+ _tile("wither_bone", _bricks(_c(0.25, 0.25, 0.26), cd, 4, 16, 0.08))
+ _tile("wither_eye", _art(["kkkk", "krrk", "krrk", "kkkk"], {"k": _c(0.02, 0.02, 0.02), "r": _c(1.0, 1.0, 1.0)}, 0.0))
+ # -- minecraft-arena@5: night field, deep dark, ruins; warden, skeleton, leader zombie ---------------
+ _build_tiles_arena5(yy, xx, r)
+
+
+def _build_tiles_arena5(yy, xx, r):
+ """Original 16x16 pixel art for the scenes added in minecraft-arena@5 (appended after the @4 layers, so every
+ earlier layer keeps its index and its random draws)."""
+ # -- terrain ----------------------------------------------------------
+ ngrass, ndirt = _c(0.26, 0.42, 0.24), _c(0.36, 0.27, 0.2)
+ _tile("night_grass", _specks(_noise(ngrass, 0.1), ngrass * 0.75, 20))
+ side = _specks(_noise(ndirt, 0.1), ndirt * 0.7, 14)
+ for x in range(16):
+ dd = 3 + int(_TR.integers(0, 3))
+ side[:dd, x] = ngrass * (0.9 + _TR.normal(0, 0.07, (dd, 1)))
+ _tile("night_grass_side", side)
+ _tile("night_dirt", _specks(_noise(ndirt, 0.1), ndirt * 0.7, 18))
+ ds, dsd = _c(0.21, 0.21, 0.24), _c(0.14, 0.14, 0.17)
+ deep = _noise(ds, 0.08).copy()
+ for y in range(16): # deepslate: horizontal strata
+ if y % 4 == 3:
+ deep[y] = dsd * (1 + _TR.normal(0, 0.06, (16, 1)))
+ _tile("deepslate", deep)
+ _tile("deepslate_tiles", _bricks(ds * 1.05, dsd * 0.8, 8, 8, 0.07))
+ sk, skd = _c(0.04, 0.12, 0.16), _c(0.02, 0.06, 0.09)
+ sculk = _noise(sk, 0.18).copy()
+ for _ in range(9): # glowing veins
+ x, y = (int(v) for v in _TR.integers(0, 16, 2))
+ for _ in range(int(_TR.integers(3, 7))):
+ sculk[y, x] = _c(0.05, 0.45, 0.5) * (1 + _TR.normal(0, 0.1))
+ x = int(np.clip(x + _TR.integers(-1, 2), 0, 15))
+ y = int(np.clip(y + _TR.integers(-1, 2), 0, 15))
+ _tile("sculk", sculk)
+ _tile("sculk_dark", _specks(_noise(skd, 0.2), _c(0.03, 0.25, 0.3), 12))
+ sb, sbm = _c(0.47, 0.47, 0.46), _c(0.3, 0.3, 0.31)
+ cracked = _bricks(sb, sbm, 8, 16)
+ for _ in range(3):
+ x, y = (int(v) for v in _TR.integers(1, 15, 2))
+ for _ in range(int(_TR.integers(3, 6))):
+ cracked[y, x] = sbm * 0.8
+ x = int(np.clip(x + _TR.choice([-1, 1]), 0, 15))
+ y = int(np.clip(y + _TR.integers(0, 2), 0, 15))
+ _tile("cracked_brick", cracked)
+ mossy = _bricks(sb, sbm, 8, 16).copy()
+ mask = _TR.random((16, 16)) < 0.28
+ mossy[mask] = _noise(_c(0.3, 0.43, 0.2), 0.12)[mask]
+ _tile("mossy_brick", mossy)
+ gravel = _cells(_c(0.5, 0.47, 0.45), _c(0.36, 0.34, 0.33), 18, 0.12)
+ _tile("gravel", gravel)
+ # -- warden -----------------------------------------------------------
+ # brighter than the deep-dark floor on purpose: a benchmark boss must stay readable in its own arena
+ wb, wd, wt = _c(0.13, 0.33, 0.40), _c(0.07, 0.19, 0.24), _c(0.45, 0.88, 0.9)
+ W = {"b": wb, "d": wd, "t": wt, "k": _c(0.01, 0.03, 0.05), "c": _c(0.75, 1.0, 1.0), "m": _c(0.2, 0.45, 0.5)}
+ _tile("warden_face", _art(["dbbbbbbd", "bbmbbmbb", "bbbbbbbb", "bkkbbkkb", "bbbbbbbb",
+ "bktttkbb", "bbktkbbb", "dbbbbbbd"], W, 0.06))
+ _tile("warden_skin", _specks(_noise(wb, 0.1), wd, 18))
+ chest = _specks(_noise(wb, 0.1), wd, 10).copy()
+ for y in range(4, 12):
+ for x in range(4, 12):
+ q = abs(x - 7.5) + abs(y - 7.5)
+ if q < 3.2:
+ chest[y, x] = wt * (1.15 - q * 0.12) # the glowing soul core in the ribcage
+ elif q < 4.2:
+ chest[y, x] = _c(0.02, 0.06, 0.08)
+ _tile("warden_chest", chest)
+ _tile("warden_rib", _art(["bdbdbdbd", "dddddddd", "bdbdbdbd", "dddddddd", "bdbdbdbd",
+ "dddddddd", "bdbdbdbd", "dddddddd"], W, 0.08))
+ _tile("warden_horn", _art(["cccc", "ctct", "cccc", "tctc"], W, 0.04))
+ # -- skeleton ---------------------------------------------------------
+ bone, bdark = _c(0.78, 0.77, 0.72), _c(0.55, 0.54, 0.5)
+ K = {"w": bone, "d": bdark, "k": _c(0.08, 0.08, 0.08), "g": _c(0.38, 0.37, 0.35)}
+ _tile("skeleton_face", _art(["wwwwwwww", "wdwwwwdw", "wwwwwwww", "wkkwwkkw", "wwwgwwww",
+ "wwwkkwww", "wkwkwkww", "wwwwwwww"], K, 0.05))
+ _tile("skeleton_head", _art(["wwwwwwww", "wdwwwwww", "wwwwwdww", "wwwwwwww", "wwdwwwww",
+ "wwwwwwdw", "wwwwwwww", "wdwwwwww"], K, 0.06))
+ _tile("skeleton_rib", _art(["wwwwwwww", "kwkkkkwk", "wwwwwwww", "kwkkkkwk", "wwwwwwww",
+ "kkkwwkkk", "kkkwwkkk", "kkkwwkkk"], K, 0.05))
+ _tile("skeleton_bone", _art(["wwww", "wdww", "wwww", "wwdw", "wwww", "wwww", "wdww", "wwww"], K, 0.05))
+ ir, ird = _c(0.78, 0.78, 0.78), _c(0.56, 0.56, 0.58)
+ _tile("iron_armor", _specks(_noise(ir, 0.05), ird, 14))
+ # -- leader zombie: a darker, torn variant (the reinforcements keep the plain zombie skin) -----
+ Z = {"g": _c(0.3, 0.52, 0.28), "d": _c(0.2, 0.36, 0.18), "k": _c(0.05, 0.06, 0.05),
+ "n": _c(0.24, 0.4, 0.22), "m": _c(0.45, 0.08, 0.06), "r": _c(0.85, 0.15, 0.1)}
+ _tile("zombie_leader_face", _art(["dgdddgdd", "gdgggdgg", "gggggggg", "gddggddg", "grkggkrg",
+ "gggnnggg", "gmmmmmmg", "gggggggg"], Z, 0.05))
+
+
+_build_tiles()
+TEX = np.stack(_LAYERS) # (n, 16, 16, 4) uint8
+
+
+# ================================================================ rig building
+# A part: size, a face spec (tile names for +x front, sides, top, bottom), the pivot inside its
+# bone frame, flags. "glow" parts are emissive and get the additive halo; "alpha" parts are
+# blended after the opaque pass.
+def part(size, front, side=None, top=None, bottom=None, pivot=(0, 0, 0), color=(1, 1, 1), glow=0.0,
+ alpha=False, crack=False, back=None):
+ side = side or front
+ top = top or side
+ return {"size": tuple(size), "color": tuple(color), "pivot": tuple(pivot),
+ "tiles": (front, side, top, bottom or top, back or side), "glow": glow, "alpha": alpha,
+ "crack": crack}
+
+
+BOW_PARTS = ("bow_grip", "bow_upper_inner", "bow_upper_outer", "bow_lower_inner",
+ "bow_lower_outer", "bow_string_upper", "bow_string_lower",
+ "bow_nocked_arrow", "bow_nocked_tip")
+
+
+def steve_rig():
+ sp, sk = "steve_shirt", "steve_skin"
+ parts = {
+ "head": part((0.5, 0.5, 0.5), "steve_face", "steve_side", "steve_hair", sk, (0, 0.25, 0), back="steve_hair"),
+ "torso": part((0.25, 0.75, 0.5), sp, sp, sp, sp),
+ "arm_r": part((0.25, 0.75, 0.25), "steve_arm", "steve_arm", "steve_shirt", sk, (0, -0.31, 0)),
+ "arm_l": part((0.25, 0.75, 0.25), "steve_arm", "steve_arm", "steve_shirt", sk, (0, -0.31, 0)),
+ "sword": part((0.03, 0.95, 0.95), "sword", "sword", "sword", "sword", (0, 0.21, 0.33), back="sword_m"),
+ "leg_r": part((0.25, 0.75, 0.25), "steve_leg", "steve_leg", "steve_leg", "steve_leg", (0, -0.375, 0)),
+ "leg_l": part((0.25, 0.75, 0.25), "steve_leg", "steve_leg", "steve_leg", "steve_leg", (0, -0.375, 0)),
+ }
+ # Actual articulated limbs and string, rather than a weapon icon. These
+ # parts are hidden for the original sword loadout and use existing tiles.
+ for name in BOW_PARTS:
+ string = "string" in name
+ arrow = "nocked" in name
+ color = (0.90, 0.88, 0.78) if string else (0.42, 0.26, 0.10)
+ if name == "bow_nocked_tip":
+ color = (0.65, 0.65, 0.62)
+ width = 0.015 if string else 0.028 if arrow else 0.055
+ parts[name] = part((0.1, width, width), "white", color=color)
+ rig = Rig(parts)
+ rig.hide.update(BOW_PARTS)
+ return rig
+
+
+def golem_rig():
+ """Vanilla proportions in pixels/16: legs 6x16x5, waist 9x5x6, chest 18x12x11, head 8x10x8, arms 4x30x6."""
+ I, V = "iron", "iron_vine"
+ return Rig({
+ "leg_l": part((0.31, 1.0, 0.375), I, I, I, "iron_plain", (0, -0.5, 0), crack=True),
+ "leg_r": part((0.31, 1.0, 0.375), V, V, I, "iron_plain", (0, -0.5, 0), crack=True),
+ "waist": part((0.375, 0.31, 0.56), "iron_plain", I, I, I, (0, 0.155, 0), crack=True),
+ "chest": part((0.69, 0.75, 1.125), "iron_chest", I, I, I, (0, 0.375, 0), crack=True),
+ "head": part((0.5, 0.62, 0.5), "golem_face", "iron_plain", "iron_plain", pivot=(0.08, 0.31, 0), crack=True),
+ "nose": part((0.125, 0.25, 0.125), "iron_plain", pivot=(0.06, 0, 0)),
+ "eyes": part((0.02, 0.078, 0.5), "eye_pair", color=(1.0, 0.25, 0.15), glow=1.0),
+ "arm_l": part((0.375, 1.875, 0.25), I, I, I, "golem_hand", (0, -0.88, 0), crack=True),
+ "arm_r": part((0.375, 1.875, 0.25), V, V, I, "golem_hand", (0, -0.88, 0), crack=True),
+ "flower": part((0.04, 0.22, 0.22), "white", color=(0.9, 0.2, 0.22), pivot=(0.04, 0, 0)),
+ })
+
+
+def zombie_rig(leader=False):
+ face = "zombie_leader_face" if leader else "zombie_face"
+ return Rig({
+ "head": part((0.5, 0.5, 0.5), face, "zombie_head", "zombie_head", pivot=(0, 0.25, 0)),
+ "torso": part((0.25, 0.75, 0.5), "zombie_shirt", "zombie_shirt", "zombie_shirt", "zombie_leg"),
+ "arm_l": part((0.25, 0.75, 0.25), "zombie_arm", "zombie_arm", "zombie_shirt", "zombie_skin", (0, -0.31, 0)),
+ "arm_r": part((0.25, 0.75, 0.25), "zombie_arm", "zombie_arm", "zombie_shirt", "zombie_skin", (0, -0.31, 0)),
+ "leg_l": part((0.25, 0.75, 0.25), "zombie_leg", pivot=(0, -0.375, 0)),
+ "leg_r": part((0.25, 0.75, 0.25), "zombie_leg", pivot=(0, -0.375, 0)),
+ })
+
+
+def warden_rig():
+ """Vanilla proportions (pixels/16): body 18x21x11, head 16x16x10, arms 8x28x8, legs 6x13x6; 2.9 tall; two
+ 'tendril' horns that flare with the heartbeat, and the glowing soul core in the chest."""
+ S, R = "warden_skin", "warden_rib"
+ return Rig({
+ "leg_l": part((0.375, 0.81, 0.375), S, pivot=(0, -0.405, 0)),
+ "leg_r": part((0.375, 0.81, 0.375), S, pivot=(0, -0.405, 0)),
+ "body": part((0.69, 1.31, 1.125), "warden_chest", R, S, S, (0, 0.655, 0), back=R),
+ "core": part((0.04, 0.5, 0.5), "white", color=(0.5, 1.0, 1.0), glow=0.6, pivot=(0.36, 0.75, 0)),
+ "head": part((0.625, 1.0, 1.0), "warden_face", S, S, S, (0.06, 0.5, 0)),
+ "horn_l": part((0.08, 0.6, 0.55), "warden_horn", color=(0.7, 1.0, 1.0), glow=0.3, pivot=(0, 0.28, 0)),
+ "horn_r": part((0.08, 0.6, 0.55), "warden_horn", color=(0.7, 1.0, 1.0), glow=0.3, pivot=(0, 0.28, 0)),
+ "arm_l": part((0.5, 1.75, 0.5), S, pivot=(0, -0.82, 0)),
+ "arm_r": part((0.5, 1.75, 0.5), S, pivot=(0, -0.82, 0)),
+ })
+
+
+def skeleton_rig():
+ """Vanilla proportions: head 8x8x8, body 8x12x4, thin 2-pixel limbs; a bow in the left hand and an iron
+ chestplate/helmet (the BossBench boss wears armour)."""
+ B, H = "skeleton_bone", "skeleton_head"
+ parts = {
+ "head": part((0.5, 0.5, 0.5), "skeleton_face", H, H, pivot=(0, 0.25, 0)),
+ "helmet": part((0.56, 0.2, 0.56), "iron_armor", pivot=(0, 0.42, 0)),
+ "torso": part((0.25, 0.75, 0.5), "skeleton_rib", "skeleton_rib", B, B),
+ "chestplate": part((0.3, 0.5, 0.56), "iron_armor", pivot=(0, 0.12, 0)),
+ "arm_l": part((0.125, 0.75, 0.125), B, pivot=(0, -0.31, 0)),
+ "arm_r": part((0.125, 0.75, 0.125), B, pivot=(0, -0.31, 0)),
+ "leg_l": part((0.125, 0.75, 0.125), B, pivot=(0, -0.375, 0)),
+ "leg_r": part((0.125, 0.75, 0.125), B, pivot=(0, -0.375, 0)),
+ }
+ for name in BOW_PARTS:
+ string = "string" in name
+ arrow = "nocked" in name
+ color = (0.90, 0.88, 0.78) if string else (0.42, 0.26, 0.10)
+ if name == "bow_nocked_tip":
+ color = (0.65, 0.65, 0.62)
+ width = 0.015 if string else 0.028 if arrow else 0.055
+ parts[name] = part((0.1, width, width), "white", color=color)
+ return Rig(parts)
+
+
+NECK, TAIL = 5, 8
+
+
+def dragon_rig():
+ s, b, sp = "dragon_scale", "dragon_belly", "dragon_spike"
+ parts = {
+ "body": part((2.4, 1.15, 1.25), s, s, s, b),
+ "head": part((0.8, 0.6, 0.75), s, s, s, b, (0.2, 0.05, 0)),
+ "snout": part((0.62, 0.3, 0.5), "dragon_snout", s, s, b, (0.31, 0, 0)),
+ "jaw": part((0.66, 0.16, 0.46), "dragon_jaw", s, b, b, (0.33, -0.08, 0)),
+ "horn_l": part((0.36, 0.14, 0.1), sp, pivot=(-0.16, 0, 0)),
+ "horn_r": part((0.36, 0.14, 0.1), sp, pivot=(-0.16, 0, 0)),
+ "nostril": part((0.08, 0.08, 0.36), sp),
+ "eye_l": part((0.04, 0.08, 0.18), "white", color=(0.85, 0.35, 1.0), glow=1.0),
+ "eye_r": part((0.04, 0.08, 0.18), "white", color=(0.85, 0.35, 1.0), glow=1.0),
+ "mouth": part((0.4, 0.06, 0.34), "white", color=(0.95, 0.45, 1.0), glow=0.0),
+ }
+ for i in range(NECK):
+ parts[f"neck{i}"] = part((0.42, 0.42, 0.42), s, s, s, b, (0.21, 0, 0))
+ parts[f"nspike{i}"] = part((0.1, 0.18, 0.06), sp, pivot=(0.21, 0.3, 0))
+ for i in range(TAIL):
+ k = 1.0 - 0.06 * i
+ parts[f"tail{i}"] = part((0.5, 0.42 * k, 0.42 * k), s, s, s, b, (-0.25, 0, 0))
+ parts[f"tspike{i}"] = part((0.12, 0.2 * k, 0.06), sp, pivot=(-0.25, 0.21 * k + 0.08, 0))
+ for i in range(3):
+ parts[f"bspike{i}"] = part((0.16, 0.32, 0.08), sp, pivot=(0, 0.72, 0))
+ for side, sg in (("l", -1), ("r", 1)):
+ parts[f"wing_{side}"] = part((0.18, 0.18, 2.0), "wing_bone", pivot=(0, 0, sg * 1.0))
+ parts[f"memb_{side}"] = part((1.9, 0.03, 2.0), "wing_membrane", "wing_bone", "wing_membrane",
+ pivot=(-0.95, 0, sg * 1.0), alpha=True)
+ parts[f"wtip_{side}"] = part((0.12, 0.12, 2.0), "wing_bone", pivot=(0, 0, sg * 1.0))
+ parts[f"mtip_{side}"] = part((1.6, 0.03, 2.0), "wing_membrane", "wing_bone", "wing_membrane",
+ pivot=(-0.8, 0, sg * 1.0), alpha=True)
+ for seg in ("thigh", "shin", "fore", "foreshin"):
+ big = seg in ("thigh", "shin")
+ parts[f"{seg}_{side}"] = part((0.3, 0.6 if big else 0.42, 0.3) if big else (0.22, 0.42, 0.22),
+ s, pivot=(0, -0.3 if big else -0.21, 0))
+ return Rig(parts)
+
+
+def wither_rig():
+ bn, sk = "wither_bone", "wither_skull"
+ p = {
+ "shoulders": part((0.38, 0.38, 2.0), bn, bn, bn, bn),
+ "spine": part((0.2, 1.0, 0.2), bn, pivot=(0, -0.5, 0)),
+ "tail": part((0.24, 0.78, 0.24), bn, pivot=(0, -0.39, 0)),
+ "head_m": part((0.5, 0.5, 0.5), "wither_face", sk, sk, pivot=(0, 0.25, 0)),
+ "head_l": part((0.38, 0.38, 0.38), "wither_face", sk, sk, pivot=(0, 0.19, 0)),
+ "head_r": part((0.38, 0.38, 0.38), "wither_face", sk, sk, pivot=(0, 0.19, 0)),
+ "eyes_m": part((0.02, 0.07, 0.3), "wither_eye", color=(1.0, 0.85, 0.75), pivot=(0.26, 0.28, 0), glow=0.4),
+ "eyes_l": part((0.02, 0.055, 0.23), "wither_eye", color=(1.0, 0.85, 0.75), pivot=(0.2, 0.21, 0), glow=0.4),
+ "eyes_r": part((0.02, 0.055, 0.23), "wither_eye", color=(1.0, 0.85, 0.75), pivot=(0.2, 0.21, 0), glow=0.4),
+ }
+ for i in range(3):
+ p[f"rib{i}"] = part((0.18, 0.13, 0.9 - 0.08 * i), bn, pivot=(0.08, 0, 0))
+ p["armor"] = part((0.9, 1.4, 1.1), "shell", alpha=True, color=(0.6, 0.8, 1.0), pivot=(0, -0.35, 0))
+ return Rig(p)
+
+
+# ================================================================ pose helpers
+def _ease(u):
+ u = min(max(u, 0.0), 1.0)
+ return u * u * (3 - 2 * u)
+
+
+def _out_back(u, s=1.7):
+ u = min(max(u, 0.0), 1.0) - 1
+ return 1 + u * u * ((s + 1) * u + s)
+
+
+def _entered(rig, state, t):
+ """Vanilla ticks since the current state began (pose memory; the sim keeps no such counter)."""
+ m = rig.mem
+ if m.get("state") != state:
+ m["state"], m["since"] = state, t
+ return (t - m["since"]) * VT
+
+
+def _smooth(rig, key, target, k):
+ """Approach target by fraction k per vanilla tick."""
+ v = rig.mem.get(key, target)
+ v += (target - v) * (1 - (1 - k) ** VT)
+ rig.mem[key] = v
+ return v
+
+
+def _hit_overlay(rig, tint_t, flash_from=7):
+ """White flash for the first two hurt ticks, then fading red (render.js hit flash). tint_t: sim ticks."""
+ tint_t *= VT
+ if tint_t >= flash_from:
+ rig.overlay = (1.0, 1.0, 1.0, 0.5)
+ elif tint_t > 0:
+ rig.overlay = (1.0, 0.1, 0.05, 0.45 * tint_t / flash_from + 0.1)
+ else:
+ rig.overlay = (0.0, 0.0, 0.0, 0.0)
+ rig.tint = (1.0, 0.45, 0.45) if tint_t > 3 else (1.0, 1.0, 1.0)
+
+
+def _look(e, target_pos, limit=45.0):
+ """Yaw and pitch (deg) from entity facing toward a point, clamped like a mob's head."""
+ d = np.asarray(target_pos, float) - e.pos
+ yaw = math.degrees(math.atan2(d[2], d[0]) - e.yaw)
+ yaw = (yaw + 180) % 360 - 180
+ return float(np.clip(yaw, -limit, limit)), float(np.clip(math.degrees(math.atan2(d[1], math.hypot(d[0], d[2]))), -40, 40))
+
+
+# ================================================================ poses
+def pose_steve(body, case):
+ e, t, rig = body.e, case.t, body.rig
+ _hit_overlay(rig, max(body.iframes - 2 / VT, 0), 7)
+ speed = float(np.hypot(e.vel[0], e.vel[2])) / VT # vanilla b/t
+ if e.on_ground:
+ body.ph = (body.ph + speed * 0.55 * VT) % 1.0
+ amp = min(1.0, speed / 0.2) * (50.0 if body.sprinting else 38.0)
+ a = 2 * math.pi * body.ph
+ leg = math.sin(a) * amp if e.on_ground else 0.0
+ sw = (t - body.swing_t) * VT / 6.0
+ # three-beat swing: cock back, slash across, settle
+ if 0 <= sw <= 1:
+ if sw < 0.25:
+ u = _ease(sw / 0.25)
+ raise_, cross, twist = 150 * u + 20, -20 * u, -25 * u
+ else:
+ u = _out_back((sw - 0.25) / 0.75, 1.2)
+ raise_, cross, twist = 170 - 140 * u, -20 + 55 * u, -25 + 45 * u
+ else:
+ raise_, cross, twist = 0.0, 0.0, 0.0
+ bob = abs(math.sin(a)) * 0.05 * amp / 40
+ lean = 6.0 if body.sprinting else 0.0
+ b = Bones()
+ hip = 0.75 + bob
+ b.bone("hips", None, (0, hip, 0), yaw=twist * 0.3, boxes=())
+ b.bone("torso", "hips", (0, 0.375, 0), yaw=twist * 0.4, pitch=-lean)
+ hy, hp = _look(e, case.boss.e.pos + [0, case.boss.aim_h, 0], 35)
+ b.bone("head", "torso", (0, 0.375, 0), yaw=hy * 0.6 - twist * 0.5, pitch=hp * 0.6)
+ if getattr(body, "weapon", "sword") == "bow":
+ charge = float(body.bow_charge)
+ pitch = math.degrees(body.e.pitch)
+ rig.hide.add("sword")
+ rig.hide.difference_update(BOW_PARTS)
+ if not body.bow_drawing:
+ rig.hide.update(("bow_nocked_arrow", "bow_nocked_tip"))
+ # Left hand holds the grip; the right arm retracts as the actual draw
+ # counter rises. Aim pitch follows the simulation, without auto-aim.
+ b.bone("head", "torso", (0, 0.375, 0), pitch=pitch)
+ b.bone("arm_l", "torso", (0, 0.31, -0.37), pitch=88 + pitch, yaw=10, roll=4)
+ b.bone("arm_r", "torso", (0, 0.31, 0.37), pitch=82 + pitch - 35 * charge,
+ yaw=-30 - 15 * charge, roll=-4)
+ _pose_bow(b, rig, charge, pitch)
+ else:
+ rig.hide.update(BOW_PARTS)
+ rig.hide.discard("sword")
+ b.bone("arm_r", "torso", (0, 0.31, 0.37), yaw=cross, pitch=-leg * 0.7 + raise_, roll=-4 - cross * 0.2)
+ b.bone("sword", "arm_r", (0.02, -0.64, 0), yaw=-90, roll=-20, boxes=("sword",))
+ b.bone("arm_l", "torso", (0, 0.31, -0.37), pitch=leg * 0.7 + raise_ * 0.15, roll=4)
+ air = 0.0 if e.on_ground else 1.0
+ b.bone("leg_r", "hips", (0, 0, 0.125), pitch=leg - 18 * air)
+ b.bone("leg_l", "hips", (0, 0, -0.125), pitch=-leg + 22 * air)
+ rig.pose(t, b.spans, e.pos, e.yaw)
+
+
+def _pose_bow(bones, rig, charge, pitch):
+ """Six wooden/string segments with a nock that moves toward the player."""
+ bones.bone("bow_frame", None, (0.72, 1.35, -0.20), pitch=pitch, boxes=())
+ tip_x = -0.14 - 0.07 * charge
+ tip_y = 0.54 - 0.045 * charge
+ nock = (-0.14 - 0.40 * charge, 0.0, 0.0)
+ upper, lower = (tip_x, tip_y, 0.0), (tip_x, -tip_y, 0.0)
+ sections = {
+ "bow_grip": ((0.0, -0.10, 0.0), (0.0, 0.10, 0.0)),
+ "bow_upper_inner": ((0.0, 0.10, 0.0), (0.01, 0.29, 0.0)),
+ "bow_upper_outer": ((0.01, 0.29, 0.0), upper),
+ "bow_lower_inner": ((0.0, -0.10, 0.0), (0.01, -0.29, 0.0)),
+ "bow_lower_outer": ((0.01, -0.29, 0.0), lower),
+ "bow_string_upper": (upper, nock),
+ "bow_string_lower": (lower, nock),
+ "bow_nocked_arrow": (nock, (0.44, 0.0, 0.0)),
+ "bow_nocked_tip": ((0.44, 0.0, 0.0), (0.53, 0.0, 0.0)),
+ }
+ for name, (start, end) in sections.items():
+ delta = np.asarray(end) - start
+ length = float(np.linalg.norm(delta))
+ width = rig.parts[name]["size"][1]
+ rig.parts[name]["size"] = (length, width, width)
+ middle = tuple((np.asarray(start) + end) * 0.5)
+ bones.bone(name, "bow_frame", middle,
+ pitch=math.degrees(math.atan2(delta[1], delta[0])))
+
+
+def pose_golem(g, case):
+ e, t, rig = g.e, case.t, g.rig
+ _hit_overlay(rig, g.tint_t)
+ k = g.hp / g.max_hp
+ rig.variant = "" if k > 0.75 else "crack1" if k > 0.5 else "crack2" if k > 0.25 else "crack3"
+ since = _entered(rig, g.state, t)
+ speed = float(np.hypot(e.vel[0], e.vel[2])) / VT
+ amp = min(1.0, speed / 0.12) * 30.0
+ a = 2 * math.pi * g.ph
+ leg = math.sin(a) * amp
+ breathe = math.sin(t * VT * 0.12)
+ # arm pitch / body lean per state; windup builds slowly, swing snaps, recover lingers low
+ if g.state == "windup":
+ u = _ease(since / 6.0)
+ arms, lean, sq = 180 * u, -12 * u, 0.04 * u
+ spread = 10 * u
+ elif g.state == "swing":
+ u = _out_back(since / 2.0, 2.2)
+ arms, lean, sq = 180 - 205 * u, 14 * u, -0.02
+ spread = 10 - 10 * u
+ elif g.state == "recover":
+ u = _ease(since / 10.0)
+ arms, lean, sq = -25 * (1 - u), 14 * (1 - u), 0.0
+ spread = 0.0
+ else:
+ arms, lean, sq, spread = 0.0, 3.0 * min(1.0, speed / 0.1), 0.0, 0.0
+ arms = _smooth(rig, "arms", arms, 0.75)
+ lean = _smooth(rig, "lean", lean, 0.5)
+ hurt = 6.0 * g.tint_t * VT / 8.0
+ rig.glow = 1.0 if g.state == "windup" else 0.0
+ b = Bones()
+ hip = 1.0 - sq + abs(math.sin(a)) * 0.04 * amp / 30
+ b.bone("hips", None, (0, hip, 0), boxes=("waist",))
+ b.bone("chest", "hips", (0, 0.31, 0), pitch=-lean - hurt, roll=math.sin(a) * 2.5, yaw=math.sin(a) * 4)
+ hy, hp = _look(e, case.body.e.pos + [0, 1.5, 0], 40)
+ b.bone("head", "chest", (0.1, 0.66, 0), yaw=hy, pitch=hp * 0.5 + lean * 0.5 + breathe)
+ b.bone("nose", "head", (0.33, 0.2, 0))
+ b.bone("eyes", "head", (0.335, 0.35, 0))
+ sway = 0.0 if g.state != "chase" else math.sin(a) * amp * 0.9
+ b.bone("arm_l", "chest", (0.0, 0.62, -0.75), pitch=arms + sway + breathe * 2, roll=spread + 4)
+ b.bone("arm_r", "chest", (0.0, 0.62, 0.75), pitch=arms - sway + breathe * 2, roll=-spread - 4)
+ b.bone("flower", "chest", (0.345, 0.5, 0.3), boxes=("flower",))
+ b.bone("leg_l", None, (0, hip, -0.25), pitch=leg)
+ b.bone("leg_r", None, (0, hip, 0.25), pitch=-leg)
+ rig.pose(t, b.spans, e.pos, e.yaw)
+
+
+def pose_zombie(z, case):
+ e, t, rig = z.e, case.t, z.rig
+ _hit_overlay(rig, z.tint_t)
+ since = _entered(rig, z.state, t)
+ speed = float(np.hypot(e.vel[0], e.vel[2])) / VT
+ amp = min(1.0, speed / 0.14) * 40.0
+ a = 2 * math.pi * z.ph
+ leg = math.sin(a) * amp
+ vt = t * VT
+ shamble = math.sin(vt * 0.21) * 6
+ # a reinforcement climbs out of the ground for its first 0.8 s (minecraft-arena@5; it cannot act meanwhile)
+ born = getattr(z, "born", None)
+ sink = 0.0 if born is None else 1.9 * max(0.0, 1.0 - (t - born) * VT / 16.0)
+ if z.state == "windup":
+ u = _ease(since / 4.0)
+ ar, al, lean, tw = 90 + 60 * u, 90 - 30 * u, -10 * u, -25 * u
+ elif z.state == "swing":
+ u = _out_back(since / 2.0, 2.0)
+ ar, al, lean, tw = 150 - 110 * u, 60 + 50 * u, 16 * u, -25 + 50 * u
+ elif z.state == "recover":
+ u = _ease(since / 8.0)
+ ar, al, lean, tw = 40 + 50 * u, 110 - 20 * u, 16 * (1 - u), 25 * (1 - u)
+ else:
+ ar, al, lean, tw = 90 + shamble, 90 - shamble, 6.0, 0.0
+ ar, al = _smooth(rig, "ar", ar, 0.7), _smooth(rig, "al", al, 0.7)
+ hurt = 10.0 * z.tint_t * VT / 8.0
+ b = Bones()
+ b.bone("hips", None, (0, 0.75 + abs(math.sin(a)) * 0.04, 0), yaw=tw * 0.3, boxes=())
+ b.bone("torso", "hips", (0, 0.375, 0), pitch=-lean - hurt, yaw=tw * 0.5, roll=math.sin(a) * 3)
+ hy, hp = _look(e, case.body.e.pos + [0, 1.5, 0], 50)
+ b.bone("head", "torso", (0, 0.375, 0), yaw=hy - tw * 0.4, pitch=hp * 0.7 + math.sin(vt * 0.09) * 4,
+ roll=math.sin(vt * 0.07) * 6)
+ b.bone("arm_r", "torso", (0, 0.31, 0.37), pitch=ar, yaw=-tw * 0.3)
+ b.bone("arm_l", "torso", (0, 0.31, -0.37), pitch=al)
+ b.bone("leg_r", "hips", (0, 0, 0.125), pitch=leg)
+ b.bone("leg_l", "hips", (0, 0, -0.125), pitch=-leg)
+ rig.pose(t, b.spans, e.pos - [0, sink, 0], e.yaw)
+
+
+def pose_warden(w, case):
+ """Heavy stalk; arms raised overhead for the smash; chest core and horn tendrils flare for the sonic boom and pulse
+ with the heartbeat; climbs out of the floor while emerging, throws its head back to roar."""
+ e, t, rig = w.e, case.t, w.rig
+ _hit_overlay(rig, w.tint_t)
+ phase = w.phase
+ since = _entered(rig, phase, t)
+ vt = t * VT
+ speed = float(np.hypot(e.vel[0], e.vel[2])) / VT
+ amp = min(1.0, speed / 0.12) * 22.0
+ a = 2 * math.pi * w.ph
+ leg = math.sin(a) * amp
+ beat = 0.5 + 0.5 * math.sin(vt * (0.63 if phase in ("chase", "windup", "recover", "boom") else 0.16))
+ sink, arms, lean, head_p, horns, core = 0.0, 0.0, 4.0 * min(1.0, speed / 0.1), 0.0, 10.0 * beat, 0.25 + 0.35 * beat
+ if phase == "emerge":
+ u = min(1.0, since / (20.0 * float(w.k.emerge_s)))
+ sink = 2.9 * (1.0 - _ease(u))
+ arms, lean, head_p = 150 * (1 - u) + 30, -20 * (1 - u), -10
+ elif phase == "roar":
+ u = _ease(since / 10.0)
+ arms, lean, head_p, horns, core = -40 * u, -18 * u, 35 * u, 45 * u, 0.9
+ elif phase == "windup":
+ u = _ease(since / 6.0)
+ arms, lean, head_p, horns, core = 175 * u, -14 * u, 10 * u, 30 * u, 0.7
+ elif phase == "recover":
+ u = _ease(since / 8.0)
+ arms, lean, head_p = -30 * (1 - u), 18 * (1 - u), -12 * (1 - u)
+ elif phase == "boom":
+ u = _ease(since / 34.0) # 1.7 s charge
+ arms, lean, head_p, horns, core = -55 * u, 10 * u, -15 * u, 55 * u, 0.6 + 0.6 * u
+ elif phase == "boom_recover":
+ u = _ease(since / 26.0)
+ arms, lean, head_p, horns, core = -55 * (1 - u), 10 * (1 - u), 0.0, 20 * (1 - u), 0.6 * (1 - u) + 0.3
+ arms, lean = _smooth(rig, "arms", arms, 0.6), _smooth(rig, "lean", lean, 0.5)
+ rig.glow = 1.0 if phase in ("windup", "boom") else 0.0
+ rig.parts["core"]["glow"] = core
+ rig.parts["horn_l"]["glow"] = rig.parts["horn_r"]["glow"] = 0.2 + 0.6 * (horns / 55.0)
+ hurt = 6.0 * w.tint_t * VT / 8.0
+ b = Bones()
+ hip = 0.81 + abs(math.sin(a)) * 0.05 * amp / 22
+ b.bone("hips", None, (0, hip, 0), boxes=())
+ b.bone("body", "hips", (0, 0.0, 0), pitch=-lean - hurt, roll=math.sin(a) * 2.0)
+ b.bone("core", "body", (0, 0, 0))
+ hy, hp = _look(e, case.body.e.pos + [0, 1.5, 0], 35)
+ b.bone("head", "body", (0.05, 1.18, 0), yaw=hy, pitch=hp * 0.4 + head_p)
+ b.bone("horn_l", "head", (0.0, 0.85, -0.42), roll=20 + horns)
+ b.bone("horn_r", "head", (0.0, 0.85, 0.42), roll=-20 - horns)
+ sway = math.sin(a) * amp * 0.8 if phase == "chase" else 0.0
+ b.bone("arm_l", "body", (0.0, 1.12, -0.82), pitch=arms + sway, roll=6)
+ b.bone("arm_r", "body", (0.0, 1.12, 0.82), pitch=arms - sway, roll=-6)
+ b.bone("leg_l", None, (0, hip, -0.3), pitch=leg)
+ b.bone("leg_r", None, (0, hip, 0.3), pitch=-leg)
+ rig.pose(t, b.spans, e.pos - [0, sink, 0], e.yaw)
+
+
+def pose_skeleton(s, case):
+ """Strafing archer: the bow arm points at the player, the draw arm pulls the string back over the visible draw;
+ the nocked arrow shows only while drawing."""
+ e, t, rig = s.e, case.t, s.rig
+ _hit_overlay(rig, s.tint_t)
+ speed = float(np.hypot(e.vel[0], e.vel[2])) / VT
+ amp = min(1.0, speed / 0.12) * 32.0
+ a = 2 * math.pi * s.ph
+ leg = math.sin(a) * amp
+ drawing = s.state == "windup"
+ charge = 0.0
+ if drawing:
+ charge = float(np.clip(1.0 - max(s.timer, 0.0) / max(float(s.k.draw), 1e-6), 0.0, 1.0))
+ charge = _smooth(rig, "charge", charge, 0.5)
+ rig.hide.difference_update(BOW_PARTS)
+ if not drawing:
+ rig.hide.update(("bow_nocked_arrow", "bow_nocked_tip"))
+ rig.glow = 1.0 if drawing and charge > 0.6 else 0.0
+ d = case.body.e.pos + [0, 1.0, 0] - (e.pos + [0, 1.5, 0])
+ pitch = math.degrees(math.atan2(d[1], math.hypot(d[0], d[2])))
+ hurt = 8.0 * s.tint_t * VT / 8.0
+ b = Bones()
+ b.bone("hips", None, (0, 0.75 + abs(math.sin(a)) * 0.03, 0), boxes=())
+ b.bone("torso", "hips", (0, 0.375, 0), pitch=-hurt, boxes=("torso", "chestplate"))
+ b.bone("head", "torso", (0, 0.375, 0), pitch=pitch * 0.8, boxes=("head", "helmet"))
+ b.bone("arm_l", "torso", (0, 0.31, -0.3), pitch=88 + pitch, yaw=10, roll=4)
+ b.bone("arm_r", "torso", (0, 0.31, 0.3), pitch=82 + pitch - 35 * charge, yaw=-30 - 15 * charge, roll=-4)
+ _pose_bow(b, rig, charge, pitch)
+ b.bone("leg_r", "hips", (0, 0, 0.1), pitch=leg)
+ b.bone("leg_l", "hips", (0, 0, -0.1), pitch=-leg)
+ rig.pose(t, b.spans, e.pos, e.yaw)
+
+
+def pose_dragon(dg, case):
+ e, t, rig = dg.e, case.t, dg.rig
+ _hit_overlay(rig, dg.tint_t)
+ phase = getattr(dg, "phase", dg.state)
+ since = _entered(rig, phase, t)
+ vt = t * VT
+ sitting = phase in ("scanning", "roar", "flaming")
+ dive = phase == "charge"
+ breath = phase == "flaming"
+ a = 2 * math.pi * dg.flap
+ # wing beat: fast downstroke, slow upstroke; folded in a charge, half-open and resting when perched
+ beat = math.sin(a - 0.6 * math.sin(a))
+ if dive:
+ fold = _ease(since / 4.0)
+ shoulder, elbow, sweep = -10 - 5 * beat * (1 - fold), 60 * fold, 50 * fold
+ elif sitting:
+ shoulder, elbow, sweep = 18 + 6 * beat, 40.0, 25.0
+ elif phase in ("takeoff", "landing"):
+ shoulder, elbow, sweep = 40 * beat, -20 * beat + 10, 0.0
+ else:
+ shoulder, elbow, sweep = 32 * beat + 4, -26 * math.sin(a + 1.0) + 6, 6 * math.sin(a)
+ rear = 0.0
+ if phase == "roar":
+ rear = _ease(since / 6.0)
+ elif breath:
+ rear = 0.4
+ elif phase == "strafe" and getattr(dg, "goal", None) is not None:
+ rear = 0.5
+ rear = _smooth(rig, "rear", rear, 0.4)
+ mouth = 0.0
+ if phase == "roar":
+ mouth = 40 * _ease(since / 4.0)
+ elif breath:
+ mouth = 30.0
+ elif phase == "strafe" and getattr(dg, "goal", None) is not None:
+ mouth = 24.0
+ elif dive:
+ mouth = 22.0
+ mouth = _smooth(rig, "mouth", mouth, 0.5)
+ hot = phase in ("roar", "flaming") or (phase == "strafe" and getattr(dg, "goal", None) is not None)
+ rig.glow = 1.0 if hot else 0.0
+ rig.parts["mouth"]["glow"] = 1.2 if hot else 0.0
+ base_pitch = 30.0 if dive else float(np.clip(-e.vel[1] / VT * 30.0, -20.0, 25.0))
+ if sitting:
+ base_pitch = -6.0
+ base_pitch = _smooth(rig, "pitch", base_pitch, 0.3)
+ bank = _smooth(rig, "bank", dg.bank, 0.3)
+ bodybob = -0.12 * beat * (0.3 if sitting else 1.0)
+ b = Bones()
+ b.bone("body", None, (0, bodybob, 0), pitch=-rear * 8)
+ hy, hp = _look(e, case.body.e.pos + [0, 0.9, 0], 60)
+ b.bone("n0", "body", (1.15, 0.2, 0), boxes=())
+ prev = "n0"
+ for i in range(NECK):
+ u = i / (NECK - 1)
+ pitch = (14 - 30 * u) * (1 - rear) + (26 - 10 * i) * rear * 1.4 + math.sin(vt * 0.15 - i * 0.6) * 3
+ if dive:
+ pitch = -4.0
+ if sitting and not phase == "roar":
+ pitch = -14.0 + 4 * i * 0.5
+ b.bone(f"neck{i}", prev, (0.42 if i else 0.0, 0, 0), yaw=hy / NECK, pitch=pitch + hp / NECK * 0.8,
+ boxes=(f"neck{i}", f"nspike{i}"))
+ prev = f"neck{i}"
+ b.bone("head", prev, (0.42, 0, 0), pitch=-10 * rear + hp * 0.2 - (18 if breath else 0))
+ b.bone("snout", "head", (0.55, -0.08, 0), boxes=("snout", "nostril"))
+ b.bone("nost", "snout", (0.58, 0.14, 0), boxes=("nostril",))
+ b.bone("jaw", "head", (0.5, -0.2, 0), pitch=-mouth)
+ b.bone("mouth", "head", (0.82, -0.2, 0), pitch=-mouth * 0.5)
+ b.bone("horn_l", "head", (0.0, 0.32, -0.22), pitch=18, yaw=12)
+ b.bone("horn_r", "head", (0.0, 0.32, 0.22), pitch=18, yaw=-12)
+ b.bone("eye_l", "head", (0.62, 0.22, -0.3), yaw=-60)
+ b.bone("eye_r", "head", (0.62, 0.22, 0.3), yaw=60)
+ for i, x in enumerate((0.7, 0.0, -0.7)):
+ b.bone(f"bspike{i}", "body", (x, 0, 0), boxes=(f"bspike{i}",))
+ b.bone("t0", "body", (-1.2, 0.05, 0), boxes=())
+ prev = "t0"
+ for i in range(TAIL):
+ w = math.sin(vt * 0.18 - i * 0.7)
+ b.bone(f"tail{i}", prev, (-0.5 if i else 0.0, 0, 0), yaw=w * (6 + i) + (-bank * 0.08),
+ pitch=(-3 if dive else 4 + 3 * math.sin(a - i * 0.5)) - rear * 3 - (6 if sitting else 0),
+ boxes=(f"tail{i}", f"tspike{i}"))
+ prev = f"tail{i}"
+ for side, sg in (("l", -1), ("r", 1)):
+ b.bone(f"wing_{side}", "body", (0.55, 0.45, sg * 0.6), yaw=-sg * sweep, roll=sg * -shoulder,
+ boxes=(f"wing_{side}", f"memb_{side}"))
+ b.bone(f"wtip_{side}", f"wing_{side}", (0, 0, sg * 2.0), yaw=-sg * sweep * 0.6, roll=sg * -elbow,
+ boxes=(f"wtip_{side}", f"mtip_{side}"))
+ tuck = 85 if dive else (10 if sitting else 60)
+ b.bone(f"thigh_{side}", "body", (-0.7, -0.45, sg * 0.5), pitch=-tuck + 6 * math.sin(a))
+ b.bone(f"shin_{side}", f"thigh_{side}", (0, -0.56, 0), pitch=-50 if not sitting else 30)
+ b.bone(f"fore_{side}", "body", (0.75, -0.45, sg * 0.45), pitch=(-50 if not sitting else 5) + 6 * math.sin(a + 1))
+ b.bone(f"foreshin_{side}", f"fore_{side}", (0, -0.4, 0), pitch=-60 if not sitting else 20)
+ rig.pose(t, b.spans, e.pos, e.yaw, base=(base_pitch, bank))
+
+
+def pose_wither(w, case):
+ e, t, rig = w.e, case.t, w.rig
+ _hit_overlay(rig, w.tint_t)
+ since = _entered(rig, w.state, t)
+ vt = t * VT
+ spawn = w.state == "spawn"
+ # recoil per head: a head that just fired snaps back (rig memory only)
+ shots = rig.mem.setdefault("shots", {})
+ for s in w.skulls:
+ key = s.get("n", 0) # serial number: id() is reused by CPython and is not reproducible
+ if key not in shots:
+ shots[key] = (t, s.get("head", 0))
+ recent = {h: tt for tt, h in shots.values()}
+ if len(shots) > 64:
+ for k in sorted(shots)[:len(shots) - 64]:
+ del shots[k]
+ rec = {h: max(0.0, 1.0 - (t - recent.get(h, -10 * FPS)) * VT / 6.0) for h in (0, 1, 2)}
+ rig.glow = 0.35 + 0.65 * max(rec.values())
+ if spawn:
+ rig.glow = 0.6 + 0.4 * math.sin(vt * 0.9)
+ for nm in ("eyes_m", "eyes_l", "eyes_r"):
+ rig.parts[nm]["glow"] = rig.glow
+ armored = bool(getattr(w, "armored", w.hp <= w.max_hp / 2))
+ rig.hide = set() if armored else {"armor"}
+ rig.shell = 0.0
+ if spawn: # flickering blue charge shell while invulnerable
+ rig.shell = 0.25 + 0.25 * (math.sin(vt * 1.7) > 0)
+ rig.shell_color = (0.35, 0.55, 1.0)
+ elif armored:
+ rig.shell = 0.18 + 0.06 * math.sin(vt * 0.5)
+ rig.shell_color = (0.55, 0.7, 1.0)
+ bob = math.sin(vt * 0.1) * 0.1
+ sway = math.sin(vt * 0.05) * 6
+ lean = float(np.clip(np.hypot(e.vel[0], e.vel[2]) / VT * 30.0, 0.0, 12.0))
+ b = Bones()
+ shrink = 0.0 if not spawn else -0.15 * (1 - since / max(1.0, w.SPAWN_TICKS))
+ b.bone("spine", None, (0, 0.55 + bob + shrink, 0), pitch=-lean * 0.3, roll=math.sin(vt * 0.07) * 3)
+ b.bone("shoulders", "spine", (0, 0.05, 0), yaw=sway * 0.3)
+ for i in range(3):
+ b.bone(f"rib{i}", "spine", (0, -0.2 - 0.26 * i, 0), yaw=math.sin(vt * 0.1 + i) * 2)
+ b.bone("tail", "spine", (0, -1.0, 0), pitch=-20 - lean * 0.6 + math.sin(vt * 0.09) * 12,
+ roll=math.sin(vt * 0.06) * 10)
+ b.bone("armor", "spine", (0, 0.1, 0))
+ target = case.body.e.pos + [0, 1.0, 0]
+ for idx, (nm, z, y, ph) in enumerate((("m", 0.0, 0.2, 0.0), ("l", -0.85, 0.2, 1.7), ("r", 0.85, 0.2, 3.4))):
+ hy, hp = _look(e, target, 60)
+ scan = 0.0 if nm == "m" else math.sin(vt * 0.04 + ph) * 18 * (1.0 - rec[idx])
+ if spawn:
+ hy, hp, scan = 0.0, -25.0 + 10 * math.sin(vt * 0.2 + ph), 0.0
+ pitch = hp - 18 * rec[idx]
+ b.bone(f"head_{nm}", "shoulders", (0.02 - 0.08 * rec[idx], y, z), yaw=hy + scan, pitch=pitch,
+ roll=math.sin(vt * 0.05 + ph) * 4, boxes=(f"head_{nm}", f"eyes_{nm}"))
+ rig.pose(t, b.spans, e.pos, e.yaw, base=(-lean * 0.5, 0.0))
+
+
+# ================================================================ particles (case.fxrng only)
+def _p(pos, vel, life, size, color, tile="puff", grav=0.0, glow=0.0):
+ return {"pos": np.asarray(pos, float), "vel": np.asarray(vel, float), "life": float(life), "life0": float(life),
+ "size": float(size), "color": tuple(color), "tile": tile, "grav": grav, "glow": glow}
+
+
+def fx_events(case):
+ """Juice keyed to this tick's events, spawned from case.fxrng. Particle vel / grav are per vanilla tick."""
+ r, out = case.fxrng, []
+ g, p = case.boss, case.body
+ for ev in case.events[getattr(case, "_ev0", 0):]:
+ name = ev[0] if isinstance(ev, tuple) else ev
+ if name == "boss_hit":
+ c = g.e.pos + [0, 0.0 if g.hover else g.aim_h, 0]
+ n = 12 if (isinstance(ev, tuple) and ev[2] == "crit") else 6
+ for _ in range(n):
+ v = r.normal(0, 1, 3)
+ v = v / (np.linalg.norm(v) + 1e-6) * r.uniform(0.08, 0.22)
+ col = (1.0, 0.95, 0.6) if n > 6 else (0.95, 0.95, 0.95)
+ out.append(_p(c + r.normal(0, 0.25, 3), v + [0, 0.08, 0], 0.4, 0.09, col, "white", -0.012, 1.0))
+ elif name == "player_hit":
+ c = p.e.pos + [0, 1.0, 0]
+ for _ in range(6):
+ out.append(_p(c + r.normal(0, 0.2, 3), r.normal(0, 0.06, 3) + [0, 0.06, 0], 0.5, 0.1,
+ (0.75, 0.08, 0.06), "white", -0.01))
+ elif name in ("golem_hit", "golem_whiff", "dragon_ram", "wither_ram", "skull_ground", "skull_hit"):
+ if name.startswith("skull"):
+ c = p.e.pos + [0, 0.9, 0] if name == "skull_hit" else None
+ if c is None:
+ continue
+ for _ in range(10):
+ out.append(_p(c + r.normal(0, 0.3, 3), r.normal(0, 0.05, 3), 0.7, 0.35, (0.2, 0.2, 0.22)))
+ continue
+ c = g.e.pos + g.e.fwd * (1.4 if name.startswith("golem") else 0.0)
+ gy = case.arena.ground(c, 0.6)
+ for _ in range(10):
+ ang = r.uniform(0, 2 * math.pi)
+ v = np.array([math.cos(ang), 0, math.sin(ang)]) * r.uniform(0.05, 0.12)
+ out.append(_p([c[0], gy + 0.1, c[2]], v + [0, 0.03, 0], 0.6, r.uniform(0.2, 0.35), (0.55, 0.45, 0.35)))
+ elif name in ("skull_blast", "wither_spawn_blast", "crystal_destroyed"):
+ if name == "crystal_destroyed":
+ cid = ev[1] if isinstance(ev, tuple) else 0
+ c = next((x["pos"] for x in getattr(g, "crystals", ()) if x["id"] == cid), g.e.pos)
+ elif isinstance(ev, tuple) and len(ev) > 2:
+ c = np.asarray(ev[2], float)
+ else:
+ c = g.e.pos
+ big = name != "skull_blast"
+ for _ in range(26 if big else 8):
+ v = r.normal(0, 1, 3)
+ v = v / (np.linalg.norm(v) + 1e-6) * r.uniform(0.05, 0.3 if big else 0.12)
+ out.append(_p(np.asarray(c, float) + r.normal(0, 0.3, 3), v + [0, 0.04, 0], r.uniform(0.4, 0.9),
+ r.uniform(0.35, 0.9) if big else r.uniform(0.25, 0.45),
+ (0.95, 0.85, 0.7) if big else (0.55, 0.52, 0.5), "puff", -0.004, 0.5 if big else 0.2))
+ elif name == "fall_damage":
+ c = p.e.pos
+ for _ in range(6):
+ ang = r.uniform(0, 2 * math.pi)
+ out.append(_p(c + [0, 0.1, 0], [math.cos(ang) * 0.08, 0.02, math.sin(ang) * 0.08], 0.5, 0.2,
+ (0.55, 0.45, 0.35)))
+ elif name == "zombie_reinforce": # a zombie digs out of the ground (minecraft-arena@5)
+ c = np.asarray(ev[2], float) if isinstance(ev, tuple) else g.e.pos
+ for _ in range(16):
+ ang = r.uniform(0, 2 * math.pi)
+ out.append(_p(c + [math.cos(ang) * 0.4, 0.1, math.sin(ang) * 0.4],
+ [math.cos(ang) * 0.06, r.uniform(0.04, 0.1), math.sin(ang) * 0.06], 0.9,
+ r.uniform(0.2, 0.4), (0.33, 0.27, 0.2), "puff", -0.006))
+ elif name == "minion_killed" and isinstance(ev, tuple) and len(ev) > 2:
+ c = np.asarray(ev[2], float) + [0, 1.0, 0]
+ for _ in range(12):
+ v = r.normal(0, 1, 3)
+ v = v / (np.linalg.norm(v) + 1e-6) * r.uniform(0.04, 0.12)
+ out.append(_p(c + r.normal(0, 0.3, 3), v + [0, 0.04, 0], 0.7, r.uniform(0.25, 0.4),
+ (0.5, 0.5, 0.5), "puff", -0.004))
+ elif name == "minion_hit":
+ for z in getattr(g, "minions", ()):
+ if z.tint_t >= ticks_hit(z):
+ c = z.e.pos + [0, 1.0, 0]
+ for _ in range(5):
+ v = r.normal(0, 1, 3)
+ v = v / (np.linalg.norm(v) + 1e-6) * r.uniform(0.06, 0.16)
+ out.append(_p(c + r.normal(0, 0.2, 3), v + [0, 0.06, 0], 0.4, 0.09, (0.95, 0.95, 0.95),
+ "white", -0.012, 1.0))
+ elif name == "warden_boom_hit" or name == "warden_boom_miss": # the sonic boom: rings along the line
+ a_, b_ = g.e.pos + [0, 1.9, 0], p.e.pos + [0, 1.0, 0]
+ for i in range(12):
+ u = (i + 0.5) / 12
+ out.append(_p(a_ + (b_ - a_) * u, [0, 0, 0], 0.45 + 0.02 * i, 0.5 + 0.06 * i,
+ (0.55, 0.95, 1.0), "glow", 0.0, 1.0))
+ elif name == "warden_smash":
+ c = g.e.pos + g.e.fwd * 1.0
+ gy = case.arena.ground(c, 0.6)
+ for _ in range(12):
+ ang = r.uniform(0, 2 * math.pi)
+ v = np.array([math.cos(ang), 0, math.sin(ang)]) * r.uniform(0.06, 0.14)
+ out.append(_p([c[0], gy + 0.1, c[2]], v + [0, 0.04, 0], 0.6, r.uniform(0.25, 0.4), (0.1, 0.18, 0.2)))
+ elif name in ("skeleton_arrow_blocked",):
+ pass
+ return out
+
+
+def fx_ambient(case):
+ """Per-tick continuous effects: footstep dust, dragon breath, skull smoke, wither aura."""
+ r, out, g = case.fxrng, [], case.boss
+ for ent, w in ((case.body.e, 0.3), (g.e, getattr(g.e, "w", 1.0) * 0.4)):
+ if g.hover and ent is g.e:
+ continue
+ if ent.on_ground and np.hypot(ent.vel[0], ent.vel[2]) > 0.12 * VT and _every(case, 3):
+ out.append(_p(ent.pos + r.normal(0, w, 3) * [1, 0, 1] + [0, 0.05, 0], [0, 0.02, 0], 0.5,
+ r.uniform(0.1, 0.18), (0.62, 0.55, 0.45)))
+ name = g.name
+ if name == "ender_dragon":
+ head = _dragon_mouth(g)
+ phase = getattr(g, "phase", "")
+ for c in getattr(g, "clouds", ()): # dragon's breath clouds: low purple haze
+ if _every(case, 1):
+ for _ in range(2 if c["kind"] == "breath" else 3):
+ ang, rad = r.uniform(0, 2 * math.pi), c["r"] * math.sqrt(r.uniform(0, 1))
+ pos = c["pos"] + [math.cos(ang) * rad, r.uniform(0.05, 0.6), math.sin(ang) * rad]
+ out.append(_p(pos, [0, 0.015, 0], r.uniform(0.5, 0.9), r.uniform(0.25, 0.45),
+ (0.72, 0.28, 0.9), "puff", 0.0, 0.6))
+ if phase == "flaming" and _every(case, 1):
+ for _ in range(4):
+ down = np.array([0.0, -1.0, 0.0]) + g.e.fwd * 0.5
+ out.append(_p(head + r.normal(0, 0.15, 3), down * 0.18 + r.normal(0, 0.04, 3), r.uniform(0.4, 0.7),
+ r.uniform(0.3, 0.55), (0.82, 0.32, 0.98), "puff", 0.0, 0.8))
+ elif (phase == "roar" or (phase == "strafe" and getattr(g, "goal", None) is not None)) and _every(case, 1):
+ out.append(_p(head + r.normal(0, 0.1, 3), r.normal(0, 0.02, 3), 0.4, 0.18, (0.95, 0.5, 1.0), "glow", 0, 1))
+ for f in getattr(g, "fireballs", ()):
+ if _every(case, 1):
+ out.append(_p(f["pos"] + r.normal(0, 0.1, 3), r.normal(0, 0.01, 3), 0.5, r.uniform(0.2, 0.35),
+ (0.75, 0.3, 0.95), "puff", 0.0, 0.9))
+ for c in getattr(g, "crystals", ()): # crystal sparkle
+ if c["alive"] and _every(case, 6):
+ out.append(_p(c["pos"] + [0, 0.8, 0] + r.normal(0, 0.35, 3), [0, 0.02, 0], 0.8, 0.07,
+ (1.0, 0.75, 0.95), "white", 0.0, 1.0))
+ if _every(case, 4): # ender particles drifting off the body
+ out.append(_p(g.e.pos + r.normal(0, 1.0, 3), r.normal(0, 0.01, 3), 1.2, 0.07, (0.7, 0.3, 0.9),
+ "white", 0.0, 1.0))
+ elif name == "wither":
+ for s in g.skulls if _every(case, 1) else ():
+ col = (0.35, 0.5, 0.85) if s.get("blue") else (0.18, 0.17, 0.2)
+ out.append(_p(s["pos"] + r.normal(0, 0.06, 3), r.normal(0, 0.01, 3), 0.45, r.uniform(0.14, 0.24), col))
+ if _every(case, 2):
+ out.append(_p(g.e.pos + r.normal(0, 0.5, 3) + [0, 0.3, 0], [0, 0.02, 0], 0.9, r.uniform(0.15, 0.25),
+ (0.15, 0.14, 0.16)))
+ if g.state == "spawn" and _every(case, 1):
+ for _ in range(2):
+ v = r.normal(0, 1, 3)
+ v /= np.linalg.norm(v) + 1e-6
+ out.append(_p(g.e.pos + v * 1.8 + [0, 0.4, 0], -v * 0.09, 0.35, 0.1, (0.5, 0.7, 1.0), "white", 0, 1))
+ elif name == "iron_golem" and g.state == "windup" and _every(case, 2):
+ out.append(_p(g.e.pos + r.normal(0, 0.4, 3) * [1, 0, 1] + [0, 0.05, 0], [0, 0.01, 0], 0.5, 0.2,
+ (0.6, 0.55, 0.45)))
+ elif name == "warden":
+ if g.phase == "boom" and _every(case, 1): # charge: cyan motes drawn into the chest
+ for _ in range(2):
+ v = r.normal(0, 1, 3)
+ v /= np.linalg.norm(v) + 1e-6
+ core = g.e.pos + [0, 1.6, 0] + g.e.fwd * 0.4
+ out.append(_p(core + v * 1.6, -v * 0.1, 0.35, 0.12, (0.5, 1.0, 1.0), "white", 0.0, 1.0))
+ if g.phase == "emerge" and _every(case, 1): # earth breaking where it climbs out
+ ang = r.uniform(0, 2 * math.pi)
+ out.append(_p(g.e.pos + [math.cos(ang) * 0.8, 0.1, math.sin(ang) * 0.8],
+ [math.cos(ang) * 0.05, r.uniform(0.05, 0.12), math.sin(ang) * 0.05], 0.8, r.uniform(0.2, 0.35),
+ (0.06, 0.12, 0.14), "puff", -0.01))
+ if _every(case, 5): # sculk spores drifting up
+ out.append(_p(g.e.pos + r.normal(0, 4.0, 3) * [1, 0, 1] + [0, 0.2, 0], [0, 0.015, 0], 2.0, 0.06,
+ (0.3, 0.85, 0.9), "white", 0.0, 1.0))
+ elif name == "skeleton" and g.state == "windup" and _every(case, 3):
+ out.append(_p(g.e.pos + [0, 1.6, 0] + g.e.fwd * 0.5, [0, 0.01, 0], 0.3, 0.08, (1.0, 0.9, 0.6), "glow", 0, 1))
+ return out
+
+
+def _dragon_mouth(g):
+ rig = g.rig
+ if rig.kf.get("mouth"):
+ return rig.kf["mouth"][-1][1].copy()
+ return g.e.pos + g.e.fwd * 3.2
+
+
+def step_fx(case):
+ """Advance particles. Called once per tick by MobFight.track; visual-only state."""
+ case.fx += fx_events(case) + fx_ambient(case)
+ keep = []
+ for p in case.fx:
+ p["pos"] = p["pos"] + p["vel"] * VT
+ p["vel"] = p["vel"] * 0.94 ** VT + [0, p.get("grav", 0.0) * VT, 0]
+ p["life"] -= 1 / FPS
+ if p["life"] > 0:
+ keep.append(p)
+ case.fx = keep[-260:]
+
+
+# ================================================================ renderer
+VS = """#version 330
+in vec3 in_pos; in vec3 in_norm;
+in vec3 i_center; in vec3 i_size; in vec4 i_q; in vec4 i_color; in vec4 i_tiles; in vec4 i_tiles2;
+in vec4 i_over; in vec2 i_fx;
+uniform mat4 mvp; uniform vec3 eye;
+out vec3 v_norm; out vec3 v_lnorm; out vec2 v_uv; out float v_dist; flat out float v_layer;
+out vec4 v_color; out vec4 v_over; out vec2 v_fx; out vec3 v_world;
+vec3 rot(vec4 q, vec3 v) { vec3 t = 2.0 * cross(q.xyz, v); return v + q.w * t + cross(q.xyz, t); }
+void main() {
+ vec3 lp = in_pos * i_size;
+ vec3 p = rot(i_q, lp) + i_center;
+ v_norm = rot(i_q, in_norm); v_lnorm = in_norm;
+ vec3 a = abs(in_norm);
+ // texel density: one tile per box face, but tiled per metre on big terrain faces (i_fx.y > 0)
+ vec2 uv; float layer;
+ if (a.y > 0.5) { uv = vec2(in_pos.x, in_pos.z); layer = in_norm.y > 0.0 ? i_tiles.z : i_tiles.w;
+ if (i_fx.y > 0.0) uv = vec2(lp.x, lp.z); }
+ else if (a.x > 0.5) { uv = vec2(in_pos.z * sign(in_norm.x), -in_pos.y); layer = in_norm.x > 0.0 ? i_tiles.x : i_tiles2.x;
+ if (i_fx.y > 0.0) uv = vec2(lp.z * sign(in_norm.x), -lp.y); }
+ else { uv = vec2(-in_pos.x * sign(in_norm.z), -in_pos.y); layer = i_tiles.y;
+ if (i_fx.y > 0.0) uv = vec2(-lp.x * sign(in_norm.z), -lp.y); }
+ v_uv = (i_fx.y > 0.0) ? uv : uv + 0.5;
+ v_layer = layer; v_color = i_color; v_over = i_over; v_fx = i_fx; v_world = p;
+ v_dist = length(p - eye);
+ gl_Position = mvp * vec4(p, 1.0);
+}"""
+FS = """#version 330
+in vec3 v_norm; in vec3 v_lnorm; in vec2 v_uv; in float v_dist; flat in float v_layer;
+in vec4 v_color; in vec4 v_over; in vec2 v_fx; in vec3 v_world;
+uniform sampler2DArray tex; uniform float crack; uniform vec3 fog_col; uniform vec2 fog_rng;
+uniform float alpha_pass; uniform vec3 sun;
+out vec4 f;
+void main() {
+ vec4 c = texture(tex, vec3(fract(v_uv), v_layer));
+ if (alpha_pass < 0.5 && c.a < 0.5) discard;
+ if (alpha_pass > 0.5 && c.a < 0.02) discard;
+ vec3 n = normalize(v_norm);
+ // Minecraft face shading (top 1.0, z faces 0.8, x faces 0.6, bottom 0.5) blended with a sun term
+ float mc = n.y > 0.5 ? 1.0 : (n.y < -0.5 ? 0.5 : mix(0.6, 0.8, abs(n.z)));
+ float l = mix(mc, 0.5 + 0.5 * max(dot(n, sun), 0.0), 0.35) * (0.92 + 0.08 * n.y);
+ vec3 col = c.rgb * v_color.rgb * l;
+ col = mix(col, c.rgb * v_color.rgb * 1.25, v_fx.x); // emissive
+ col = mix(col, v_over.rgb, v_over.a); // hurt flash
+ float fog = clamp((v_dist - fog_rng.x) / (fog_rng.y - fog_rng.x), 0.0, 1.0);
+ col = mix(col, fog_col, fog * (1.0 - 0.6 * v_fx.x));
+ f = vec4(col, c.a * v_color.a);
+}"""
+SKY_VS = """#version 330
+in vec2 in_pos; out vec2 v; void main() { v = in_pos; gl_Position = vec4(in_pos, 0.999, 1.0); }"""
+SKY_FS = """#version 330
+in vec2 v; uniform vec3 top; uniform vec3 bot; uniform mat3 inv_rot; uniform vec2 tanf;
+uniform float stars; out vec4 f;
+float h(vec3 p) { return fract(sin(dot(p, vec3(12.9898, 78.233, 37.719))) * 43758.5453); }
+void main() {
+ vec3 d = normalize(inv_rot * vec3(v.x * tanf.x, v.y * tanf.y, -1.0));
+ float k = clamp(d.y * 1.6 + 0.15, 0.0, 1.0);
+ vec3 col = mix(bot, top, sqrt(k));
+ if (stars > 0.0) { vec3 q = floor(d * 160.0); if (h(q) > 0.996 && d.y > -0.05) col += vec3(0.8) * stars; }
+ f = vec4(col, 1.0);
+}"""
+
+SUN = np.array([0.45, 0.85, 0.3]) / np.linalg.norm([0.45, 0.85, 0.3])
+THEMES = { # sky top, sky bottom / fog
+ "field": ((0.44, 0.62, 0.98), (0.73, 0.84, 1.0)),
+ "towers": ((0.04, 0.02, 0.07), (0.16, 0.1, 0.2)),
+ "wither": ((0.16, 0.15, 0.2), (0.38, 0.35, 0.4)),
+ "night": ((0.02, 0.03, 0.09), (0.13, 0.16, 0.27)), # minecraft-arena@5
+ "deep_dark": ((0.01, 0.02, 0.04), (0.09, 0.13, 0.17)),
+ "ruins": ((0.55, 0.52, 0.66), (0.86, 0.72, 0.6)), # dusk
+}
+FOG = {"field": (28.0, 76.0), "towers": (22.0, 62.0), "night": (20.0, 56.0), "deep_dark": (18.0, 52.0),
+ "ruins": (24.0, 68.0)}
+STARS = {"towers": 1.0, "night": 1.0}
+# third-person camera height above the player's feet, per arena style (default 2.6): the overworld night mobs are as tall
+# as Steve, so from 2.6 a zombie or skeleton straight ahead hides behind the player's own body, bow draw included.
+CAM_UP = {"night": 3.5, "ruins": 3.5}
+
+
+def _cube():
+ v = []
+ for ax in range(3):
+ for sgn in (-1, 1):
+ n = np.zeros(3)
+ n[ax] = sgn
+ u, w = np.eye(3)[(ax + 1) % 3], np.eye(3)[(ax + 2) % 3]
+ if sgn < 0:
+ u, w = w, u
+ q = [n * 0.5 + (a * u + b * w) * 0.5 for a, b in ((-1, -1), (1, -1), (1, 1), (-1, 1))]
+ for i in (0, 1, 2, 0, 2, 3):
+ v.append([*q[i], *n])
+ return np.array(v, "f4")
+
+
+def perspective(fovy, aspect, near, far):
+ f = 1 / math.tan(math.radians(fovy) / 2)
+ return np.array([[f / aspect, 0, 0, 0], [0, f, 0, 0],
+ [0, 0, (far + near) / (near - far), 2 * far * near / (near - far)], [0, 0, -1, 0]])
+
+
+def look_at(eye, target, up=(0, 1, 0)):
+ f = target - eye
+ f = f / (float(np.linalg.norm(f)) + 1e-9)
+ r = np.cross(f, up)
+ r = r / (float(np.linalg.norm(r)) + 1e-9)
+ u = np.cross(r, f)
+ m = np.eye(4)
+ m[0, :3], m[1, :3], m[2, :3] = r, u, -f
+ m[:3, 3] = -m[:3, :3] @ eye
+ return m
+
+
+QI = (0.0, 0.0, 0.0, 1.0)
+NOFX = (0.0, 0.0, 0.0, 0.0)
+ROW = 3 + 3 + 4 + 4 + 4 + 4 + 4 + 2 # floats per instance
+
+
+def _tid(n):
+ return float(TILES[n])
+
+
+def _row(c, size, q, color, tiles, over=NOFX, glow=0.0, world_uv=0.0):
+ f, s, tp, bt, bk = tiles
+ return [*c, *size, *q, *color, _tid(f), _tid(s), _tid(tp), _tid(bt), _tid(bk), 0.0, 0.0, 0.0,
+ *over, glow, world_uv]
+
+
+def part_rows(rig, t, crack_layer=None, excluded=()):
+ """Instances for one rig at fractional tick t. Pivot-aware: box centre = o + R(q) @ pivot."""
+ opaque, alpha, glows, cracks = [], [], [], []
+ shell = rig.shell
+ for name, (o, q) in rig.sample(t).items():
+ if name in rig.hide or name in excluded:
+ continue
+ p = rig.parts[name]
+ piv = p.get("pivot") or (0, 0, 0)
+ c = o + q_to_mat(q) @ np.asarray(piv, float) if any(piv) else o
+ tiles = p.get("tiles") or ("white",) * 5
+ col = (*p["color"], 1.0)
+ g = float(p.get("glow", 0.0))
+ g = g * max(rig.glow, 0.35) if g else 0.0
+ row = _row(c, p["size"], q, col, tiles, rig.overlay, min(g, 1.0))
+ (alpha if p.get("alpha") else opaque).append(row)
+ if g > 0.5:
+ s = min(0.7, sum(p["size"]) / 3 * (1.4 + 0.8 * rig.glow))
+ glows.append(_row(c, (s, s, s), QI, (*p["color"], 0.55 * g), ("glow",) * 5, glow=1.0))
+ if crack_layer and p.get("crack"):
+ sz = tuple(v + 0.004 for v in p["size"])
+ cracks.append(_row(c, sz, q, (1, 1, 1, 1), (crack_layer,) * 5, rig.overlay))
+ if shell > 0 and name not in ("armor",) and not p.get("alpha"):
+ sz = tuple(v + 0.18 for v in p["size"])
+ alpha.append(_row(c, sz, q, (*rig.shell_color, shell), ("shell",) * 5, glow=0.6))
+ return opaque + cracks, alpha, glows
+
+
+def arrow_rows(arrows):
+ """Draw simulated arrow positions and velocity directions; no state/RNG changes."""
+ rows = []
+ for arrow in arrows:
+ velocity = np.asarray(arrow["vel"], dtype=float)
+ speed = float(np.linalg.norm(velocity))
+ if speed < 1e-12:
+ continue
+ direction = velocity / speed
+ # Quaternion rotating the box's +x shaft onto its actual velocity.
+ if direction[0] < -1 + 1e-10:
+ rotation = np.array((0.0, 1.0, 0.0, 0.0))
+ else:
+ rotation = np.array((0.0, -direction[2], direction[1], 1 + direction[0]))
+ rotation /= np.linalg.norm(rotation)
+ tip = np.asarray(arrow["pos"], dtype=float)
+ rows.append(_row(tip - direction * 0.34, (0.68, 0.025, 0.025), rotation,
+ (0.48, 0.31, 0.14, 1), ("white",) * 5))
+ rows.append(_row(tip, (0.11, 0.08, 0.08), rotation,
+ (0.68, 0.68, 0.65, 1), ("white",) * 5))
+ tail = tip - direction * 0.61
+ for size in ((0.13, 0.11, 0.015), (0.13, 0.015, 0.11)):
+ rows.append(_row(tail, size, rotation, (0.90, 0.87, 0.78, 1), ("white",) * 5))
+ return rows
+
+
+def _terrain_rows(H, style):
+ """Column tops and exposed side runs, baked once per arena. Faces tile the texture per metre."""
+ S = H.shape[0]
+ rows = []
+ end = style == "towers"
+ # minecraft-arena@5 themes: (wall, tall column, mid column, low block, floor) as (top, side, bottom) tiles
+ themed = {
+ "night": (("stone_brick",) * 3, ("cobble",) * 3, ("mossy_cobble", "mossy_cobble", "cobble"),
+ ("night_grass", "night_grass_side", "night_dirt"), ("night_grass", "night_grass_side", "night_dirt")),
+ "deep_dark": (("deepslate_tiles",) * 3, ("sculk", "deepslate", "deepslate"), ("sculk", "deepslate", "deepslate"),
+ ("sculk_dark", "deepslate", "deepslate"), ("sculk_dark", "deepslate", "deepslate")),
+ "ruins": (("stone_brick",) * 3, ("cracked_brick",) * 3, ("mossy_brick", "cracked_brick", "cracked_brick"),
+ ("gravel",) * 3, ("grass_top", "grass_side", "dirt")),
+ }.get(style)
+ for (x, z), h in np.ndenumerate(H):
+ h = int(h)
+ if themed is not None:
+ top, side, bot = themed[0 if h >= 8 else 1 if h >= 4 else 2 if h >= 2 else 3 if h == 1 else 4]
+ elif h >= 8: # arena wall
+ top, side, bot = ("end_brick", "end_brick", "end_brick") if end else ("stone_brick",) * 3
+ elif h >= 4:
+ top, side, bot = ("obsidian",) * 3 if end else ("cobble", "cobble", "cobble")
+ elif h >= 2:
+ top, side, bot = ("end_stone",) * 3 if end else ("mossy_cobble", "mossy_cobble", "cobble")
+ elif h == 1:
+ top, side, bot = ("end_stone",) * 3 if end else ("grass_top", "grass_side", "dirt")
+ else:
+ top, side, bot = ("end_stone",) * 3 if end else ("grass_top", "grass_side", "dirt")
+ if h == 0:
+ rows.append(_row((x + 0.5, -0.5, z + 0.5), (1, 1, 1), QI, (1, 1, 1, 1),
+ (side, side, top, bot, side), world_uv=1.0))
+ continue
+ # a grass-topped single block keeps its grass_side band on the top metre only
+ if side in ("grass_side", "night_grass_side"):
+ rows.append(_row((x + 0.5, h - 0.5, z + 0.5), (1, 1, 1), QI, (1, 1, 1, 1),
+ (side, side, top, bot, side), world_uv=1.0))
+ if h > 1:
+ rows.append(_row((x + 0.5, (h - 1) / 2, z + 0.5), (1, h - 1, 1), QI, (1, 1, 1, 1),
+ (bot,) * 5, world_uv=1.0))
+ else:
+ rows.append(_row((x + 0.5, h / 2, z + 0.5), (1, h, 1), QI, (1, 1, 1, 1),
+ (side, side, top, bot, side), world_uv=1.0))
+ return rows
+
+
+class VoxelRenderer:
+ """Headless MSAA renderer: sky gradient, textured instanced boxes (opaque, then alpha, then an
+ additive glow pass), blob shadows, distance fog. A frame is a pure function of the case state
+ and the fractional tick t."""
+
+ def __init__(self, w, h, samples=8):
+ samples = int(os.environ.get("BB_MSAA", samples))
+ import moderngl
+ self.mgl = moderngl
+ self.w, self.h = w, h
+ self.ctx, self._resources, self._closed = None, [], False
+ self.terrain, self.terrain_key = None, None
+ self.cam, self.cam_override = None, None
+ backend = os.environ.get("BOSSBENCH_GL_BACKEND")
+ try:
+ ctx = self.ctx = moderngl.create_standalone_context(**({"backend": backend} if backend else {}))
+ self.prog = self._own(ctx.program(vertex_shader=VS, fragment_shader=FS))
+ self.sky = self._own(ctx.program(vertex_shader=SKY_VS, fragment_shader=SKY_FS))
+ self.vbo = self._own(ctx.buffer(_cube().tobytes()))
+ quad = np.array([-1, -1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1], "f4")
+ self.sky_vbo = self._own(ctx.buffer(quad.tobytes()))
+ self.sky_vao = self._own(ctx.vertex_array(self.sky, [(self.sky_vbo, "2f", "in_pos")]))
+ self.tex = self._own(ctx.texture_array((16, 16, len(TEX)), 4, TEX.tobytes()))
+ self.tex.filter = (moderngl.NEAREST, moderngl.NEAREST)
+ samples = min(samples, ctx.max_samples)
+ mscolor = self._own(ctx.renderbuffer((w, h), 4, samples=samples))
+ msdepth = self._own(ctx.depth_renderbuffer((w, h), samples=samples))
+ self.msfbo = self._own(ctx.framebuffer(color_attachments=[mscolor], depth_attachment=msdepth))
+ color = self._own(ctx.renderbuffer((w, h), 4))
+ depth = self._own(ctx.depth_renderbuffer((w, h)))
+ self.fbo = self._own(ctx.framebuffer(color_attachments=[color], depth_attachment=depth))
+ self.ibo = self._own(ctx.buffer(reserve=ROW * 4 * 4096, dynamic=True))
+ self.vao = self._own(ctx.vertex_array(self.prog, [
+ (self.vbo, "3f 3f", "in_pos", "in_norm"),
+ (self.ibo, "3f 3f 4f 4f 4f 4f 4f 2f/i", "i_center", "i_size", "i_q", "i_color", "i_tiles",
+ "i_tiles2", "i_over", "i_fx")]))
+ except BaseException:
+ try:
+ self.close()
+ except Exception:
+ pass # preserve the initialization failure after best-effort cleanup
+ raise
+
+ def _own(self, resource):
+ self._resources.append(resource)
+ return resource
+
+ def close(self):
+ """Release every owned GL object, including a partially initialized renderer."""
+ if self._closed:
+ return
+ self._closed = True
+ resources, self._resources = self._resources, []
+ errors = []
+ if self.ctx is not None:
+ try:
+ with self.ctx:
+ for resource in reversed(resources):
+ try:
+ resource.release()
+ except Exception as ex:
+ errors.append(ex)
+ except Exception as ex:
+ errors.append(ex)
+ finally:
+ try:
+ self.ctx.release()
+ except Exception as ex:
+ errors.append(ex)
+ self.terrain, self.terrain_key, self.cam = None, None, None
+ if errors:
+ raise RuntimeError("OpenGL renderer cleanup failed") from errors[0]
+
+ def _upload(self, rows):
+ data = np.asarray(rows, "f4")
+ if data.nbytes > self.ibo.size:
+ self.ibo.orphan(data.nbytes * 2)
+ self.ibo.write(data.tobytes())
+ return len(data)
+
+ def _draw_each(self, rows):
+ """Blended passes: one instance per draw call, in list order. With 8x MSAA the local GPU (RTX 5070 Ti) blended
+ the overlapping translucent instances of a single instanced draw in a varying order, so repeated renders of
+ one state differed by +-1 in a few pixels (the renderer_contract purity flake of 2026-11-01: 10 of 300
+ identical renders; 0 of 300 drawn one per call, 0 without MSAA). Costs < 1 ms for the ~20-30 blended rows."""
+ for row in rows:
+ self._upload((row,))
+ self.vao.render(instances=1)
+
+ def draw(self, c, t=None):
+ if self._closed:
+ raise RuntimeError("OpenGL renderer is closed")
+ # An RL group can own multiple standalone contexts in the same thread.
+ with self.ctx:
+ return self._draw(c, t)
+
+ def _draw(self, c, t=None):
+ mgl, ctx = self.mgl, self.ctx
+ t = float(c.t if t is None else t)
+ A, p, g = c.arena, c.body.e, c.boss.e
+ theme = THEMES["wither" if c.boss.name == "wither" else A.style]
+ terrain_key = (A.style, A.H.shape, A.H.dtype.str, A.H.tobytes())
+ if self.terrain_key != terrain_key or self.terrain is None:
+ self.terrain, self.terrain_key = _terrain_rows(A.H, A.style), terrain_key
+ # Billboards must use this frame's camera, independent of draw history.
+ eye, target = self._camera(c, p, g, t)
+ opaque, alpha, glow = list(self.terrain), [], []
+ for rig in [c.body.rig] + c.boss.rigs():
+ excluded = ()
+ if rig is c.body.rig and c.camera == "first":
+ # The eye lies inside the player head; keep arms/weapon, expose the world.
+ excluded = ("head", "torso", "leg_r", "leg_l")
+ o, a, gl = part_rows(rig, t, rig.variant or None, excluded=excluded)
+ opaque += o
+ alpha += a
+ glow += gl
+ opaque += arrow_rows(getattr(c, "arrows", ()))
+ opaque += arrow_rows(getattr(c.boss, "arrows", ())) # skeleton arrows (minecraft-arena@5)
+ for cr in getattr(c.boss, "crystals", ()): # end crystals: spinning cube in a glass cage
+ if not cr["alive"]:
+ continue
+ spin = (t * VT * 0.12 + cr["id"]) % (2 * math.pi)
+ centre = cr["pos"] + [0, 0.8 + 0.18 * math.sin(t * VT * 0.1 + cr["id"]), 0]
+ q1 = (math.sin(spin / 2) * 0.38, math.sin(spin / 2) * 0.6, math.sin(spin / 2) * 0.7, math.cos(spin / 2))
+ n = math.sqrt(sum(v * v for v in q1))
+ q1 = tuple(v / n for v in q1)
+ opaque.append(_row(centre, (0.42, 0.42, 0.42), q1, (0.95, 0.45, 0.85, 1), ("white",) * 5, glow=0.9))
+ alpha.append(_row(centre, (0.85, 0.85, 0.85), (q1[1], q1[0], q1[3], q1[2]), (0.85, 0.85, 1.0, 0.35),
+ ("shell",) * 5, glow=0.4))
+ opaque.append(_row(cr["pos"] + [0, 0.12, 0], (0.9, 0.24, 0.9), QI, (1, 1, 1, 1), ("bedrock",) * 5))
+ glow.append(_row(centre, (1.4, 1.4, 1.4), QI, (1.0, 0.5, 0.9, 0.45), ("glow",) * 5, glow=1.0))
+ if getattr(c.boss, "heal_from", None) is cr: # healing beam to the dragon
+ a_, b_ = centre, c.boss.e.pos
+ d = b_ - a_
+ L = float(np.linalg.norm(d))
+ dirn = d / (L + 1e-9)
+ if dirn[0] < -1 + 1e-9:
+ qb = (0.0, 1.0, 0.0, 0.0)
+ else:
+ qb = np.array((0.0, -dirn[2], dirn[1], 1 + dirn[0]))
+ qb = tuple(qb / np.linalg.norm(qb))
+ glow.append(_row((a_ + b_) / 2, (L, 0.12, 0.12), qb, (1.0, 0.9, 1.0, 0.8), ("white",) * 5, glow=1.0))
+ for fb in getattr(c.boss, "fireballs", ()): # dragon fireball
+ opaque.append(_row(fb["pos"], (0.5, 0.5, 0.5), QI, (0.6, 0.2, 0.75, 1), ("white",) * 5, glow=1.0))
+ glow.append(_row(fb["pos"], (1.2, 1.2, 1.2), QI, (0.8, 0.35, 1.0, 0.6), ("glow",) * 5, glow=1.0))
+ for cl in getattr(c.boss, "clouds", ()): # dragon's breath area cloud (flat disc)
+ k = min(1.0, cl["life"] / 0.6)
+ alpha.append(_row(cl["pos"] + [0, 0.05, 0], (cl["r"] * 2, 0.04, cl["r"] * 2), QI,
+ (0.7, 0.25, 0.85, 0.35 * k), ("shadow",) * 5))
+ for q in c.boss.extra(c): # wither skulls: textured, spinning
+ spin = (t * VT * 0.35 + float(q["pos"][0])) % (2 * math.pi)
+ qq = (0.0, math.sin(spin / 2), 0.0, math.cos(spin / 2))
+ blue = q.get("blue", False)
+ opaque.append(_row(q["pos"], q.get("size", (0.42, 0.42, 0.42)), qq, (0.55, 0.75, 1.0, 1) if blue else (1, 1, 1, 1),
+ ("wither_face", "wither_skull", "wither_skull", "wither_skull", "wither_skull")))
+ glow.append(_row(q["pos"], (1.0, 1.0, 1.0), QI, (0.3, 0.25, 0.35, 0.5), ("glow",) * 5, glow=1.0))
+ for q in c.fx:
+ life = q["life"] / q.get("life0", q["life"] or 1)
+ s = q["size"] * (0.5 + 0.5 * life) if q.get("tile") != "puff" else q["size"] * (1.4 - 0.6 * life)
+ tile = q.get("tile", "puff")
+ col = (*q["color"], min(1.0, life * 1.6))
+ r = _row(q["pos"], (s, s, s), self._billboard(), col, (tile,) * 5, glow=float(q.get("glow", 0)))
+ (glow if tile == "glow" else alpha).append(r)
+ shadows = [(p, 0.45), (g, max(0.7, g.w * 0.75))]
+ shadows += [(z.e, 0.45) for z in getattr(c.boss, "minions", ()) if z.hp > 0]
+ for e, rad in shadows:
+ gy = A.ground(e.pos, rad)
+ hgt = e.pos[1] - gy
+ if hgt < 12:
+ k = max(0.25, 1 - hgt / 12)
+ alpha.append(_row((e.pos[0], gy + 0.015, e.pos[2]), (rad * 2.2 * (1.3 - 0.3 * k), 0.01, rad * 2.2 * (1.3 - 0.3 * k)),
+ QI, (1, 1, 1, k), ("shadow",) * 5))
+ V = look_at(eye, target)
+ fov = 70.0
+ mvp = perspective(fov, self.w / self.h, 0.05, 120) @ V
+ self.msfbo.use()
+ ctx.clear(*theme[1], 1.0)
+ ctx.disable(mgl.DEPTH_TEST)
+ tf = math.tan(math.radians(fov) / 2)
+ self.sky["top"].value, self.sky["bot"].value = theme
+ self.sky["inv_rot"].write(np.ascontiguousarray(V[:3, :3]).astype("f4").tobytes())
+ self.sky["tanf"].value = (tf * self.w / self.h, tf)
+ self.sky["stars"].value = STARS.get(A.style, 0.0)
+ self.sky_vao.render()
+ ctx.enable(mgl.DEPTH_TEST)
+ pr = self.prog
+ pr["mvp"].write(mvp.T.astype("f4").tobytes())
+ pr["eye"].value = tuple(float(v) for v in eye)
+ pr["fog_col"].value = theme[1]
+ pr["fog_rng"].value = FOG.get(A.style, (22.0, 62.0))
+ pr["sun"].value = tuple(SUN)
+ self.tex.use(0)
+ pr["tex"].value = 0
+ pr["alpha_pass"].value = 0.0
+ ctx.disable(mgl.BLEND)
+ self.vao.render(instances=self._upload(opaque))
+ if alpha:
+ ctx.enable(mgl.BLEND)
+ ctx.blend_func = mgl.SRC_ALPHA, mgl.ONE_MINUS_SRC_ALPHA
+ pr["alpha_pass"].value = 1.0
+ ctx.depth_mask = False
+ # far-to-near so translucent shadows/smoke/membranes overlap sensibly
+ alpha.sort(key=lambda r: -float(np.sum((np.array(r[:3]) - eye) ** 2)))
+ self._draw_each(alpha)
+ ctx.depth_mask = True
+ if glow:
+ ctx.enable(mgl.BLEND)
+ ctx.blend_func = mgl.SRC_ALPHA, mgl.ONE
+ pr["alpha_pass"].value = 1.0
+ ctx.depth_mask = False
+ self._draw_each(glow)
+ ctx.depth_mask = True
+ ctx.disable(mgl.BLEND)
+ ctx.copy_framebuffer(self.fbo, self.msfbo)
+ img = np.frombuffer(self.fbo.read(components=3), np.uint8).reshape(self.h, self.w, 3)[::-1]
+ return np.ascontiguousarray(img)
+
+ def _billboard(self):
+ """Camera-facing quaternion (yaw only) so particle quads read as sprites."""
+ if self.cam is None:
+ return QI
+ f = self.cam[1] - self.cam[0]
+ yaw = math.atan2(f[2], f[0])
+ a = -yaw / 2
+ return (0.0, math.sin(a), 0.0, math.cos(a))
+
+ def _camera(self, c, p, g, t):
+ if self.cam_override is not None: # debug / turntable views
+ self.cam = self.cam_override
+ return self.cam
+ A = c.arena
+ rig = c.body.rig
+ kf = rig.kf.get("torso")
+ base = p.pos.copy()
+ if kf and len(kf) >= 2: # interpolated player position
+ o = rig.sample(t)["torso"][0]
+ base = np.array([o[0], p.pos[1], o[2]])
+ pitch = c.body.e.pitch # real view pitch for every weapon (arena@2)
+ aim = p.fwd * math.cos(pitch) + np.array([0.0, math.sin(pitch), 0.0])
+ if c.camera == "first":
+ eye = base + [0, 1.62, 0]
+ self.cam = (eye, eye + aim * 3)
+ return self.cam
+ lift = float(np.clip(g.pos[1] - p.pos[1], 0.0, 11.0)) * 0.30
+ back, up = 4.4, CAM_UP.get(A.style, 2.6) + lift
+ pivot = base + [0, 1.6, 0]
+
+ def clear(want):
+ # raymarch from the pivot toward the wanted eye; stop short of the first solid column
+ d = want - pivot
+ L = float(np.linalg.norm(d))
+ s = 0.0
+ while s < L:
+ q = pivot + d * (s / L)
+ ix, iz = int(math.floor(q[0])), int(math.floor(q[2]))
+ if not (0 <= ix < A.H.shape[0] and 0 <= iz < A.H.shape[1]) or A.H[ix, iz] > q[1] - 0.25:
+ return d, L, max(0.0, s - 0.35)
+ s += 0.1
+ return d, L, L
+
+ # a pillar or wall right behind the player: crane up over it before pulling in
+ best = None
+ for extra in (0.0, 1.5, 3.0, 4.5):
+ d, L, ok = clear(base + [0, up + extra, 0] - p.fwd * back)
+ if best is None or ok > best[2] + 0.5:
+ best = (d, L, ok)
+ if ok >= L * 0.85:
+ break
+ d, L, ok = best
+ eye = pivot + d * (ok / L) if ok >= 0.9 else pivot + p.fwd * 0.2 # boxed in: over the shoulder
+ # look along the player's own aim, far enough that a boss overhead stays in frame
+ target = base + [0, 1.62, 0] + aim * (2.2 + 3.0 * max(0.0, math.sin(pitch)))
+ self.cam = (eye, target)
+ return eye, target
+
+
+# ================================================================ HUD
+_FONTS = {}
+
+
+def _font(size, bold=False):
+ key = (size, bold)
+ if key not in _FONTS:
+ from PIL import ImageFont
+ for path in (("C:/Windows/Fonts/consolab.ttf" if bold else "C:/Windows/Fonts/consola.ttf"),
+ "DejaVuSansMono-Bold.ttf" if bold else "DejaVuSansMono.ttf"):
+ try:
+ _FONTS[key] = ImageFont.truetype(path, size)
+ break
+ except OSError:
+ continue
+ else:
+ _FONTS[key] = ImageFont.load_default()
+ return _FONTS[key]
+
+
+STATE_HUD = {"windup": "WIND UP", "lineup": "TELEGRAPH", "charge": "CHARGE", "swing": "SWING",
+ "strike": "STRIKE", "dash": "DASH", "recover": "RECOVER", "chase": "CHASE",
+ "circle": "CIRCLING", "climb": "CLIMBING", "hover": "HOVERING", "spawn": "SPAWNING - INVULNERABLE",
+ "armored": "SHELL UP - ARROWS BOUNCE", "nolos": "NO LINE OF SIGHT", "strafe": "STRAFING",
+ "perch": "PERCHED"}
+PHASE_HUD = {"holding": "CIRCLING", "strafe": "STRAFING", "landing": "LANDING", "scanning": "PERCHED - SCANNING",
+ "roar": "PERCHED - ROAR", "flaming": "PERCHED - BREATH", "takeoff": "TAKING OFF", "charge": "CHARGING YOU"}
+# the warden's phases (minecraft-arena@5); its 'roar' must not read as the dragon's perched roar
+WARDEN_HUD = {"emerge": "EMERGING - INVULNERABLE", "roar": "ROARING", "chase": "HUNTING", "windup": "SMASH - BACK OFF",
+ "recover": "RECOVERING - OPENING", "boom": "SHOCKWAVE CHARGING", "boom_recover": "RECOVERING - OPENING"}
+TITLES = {"iron_golem": "Hurling Brute", "zombie": "Green Brawler", "ender_dragon": "Violet Breath Flyer",
+ "wither": "Three-Headed Hover Gun", "warden": "Blind Shockwave Beast", "skeleton": "Strafing Bowman",
+ "zombie_leader": "Horde Caller"}
+BAR = {"iron_golem": (230, 225, 215), "zombie": (90, 170, 80), "ender_dragon": (200, 60, 220), "wither": (60, 60, 70),
+ "warden": (40, 160, 170), "skeleton": (215, 212, 200), "zombie_leader": (90, 170, 80)}
+
+
+def _darkness(out, c, h, w):
+ """Java Darkness: the world dims in slow pulses while the effect lasts (warden, minecraft-arena@5). Drawn over the
+ rendered frame, under the HUD, so health and timers stay readable."""
+ g = c.boss
+ left = getattr(g, "dark_t", 0)
+ if left <= 0:
+ return out
+ pulse = 0.5 + 0.5 * math.sin(c.t * VT * 0.21)
+ fade = min(1.0, left / max(1.0, 40 / VT))
+ yy, xx = np.mgrid[0:h, 0:w]
+ r = np.hypot((xx - w / 2) / (w / 2), (yy - h / 2) / (h / 2))
+ # strong at the edges, light in the middle: the warden (who is usually in front of the player) stays readable
+ k = (0.25 + 0.35 * pulse) * fade * np.clip(r * 0.9, 0.08, 1.0)[..., None]
+ return out * (1 - k)
+
+
+def hud(img, c):
+ """Minecraft-flavoured HUD: boss bar with name on top, hearts + attack indicator at the bottom,
+ telegraph banner and a red vignette pulse on damage."""
+ from PIL import Image, ImageDraw
+ h, w = img.shape[:2]
+ u = h / 480.0
+ b, g = c.body, c.boss
+ out = img.astype(np.float32)
+ out = _darkness(out, c, h, w)
+ hurt = b.iframes * VT # vanilla ticks of hurt immunity left
+ if hurt > 6: # hurt vignette
+ yy, xx = np.mgrid[0:h, 0:w]
+ r = np.hypot((xx - w / 2) / (w / 2), (yy - h / 2) / (h / 2))
+ k = np.clip(r - 0.55, 0, 1)[..., None] * 0.9 * (hurt - 6) / 4
+ out = out * (1 - k) + np.array([170, 0, 0]) * k
+ phase = getattr(g, "phase", None)
+ hot = g.state in ("windup", "lineup", "spawn") or phase in ("roar", "charge", "boom") or (
+ phase == "strafe" and getattr(g, "goal", None) is not None)
+ if hot and int(c.t * VT // 2) % 2 == 0:
+ out[:int(3 * u)] = out[:int(3 * u)] * 0.4 + np.array([255, 200, 40]) * 0.6
+ im = Image.fromarray(out.clip(0, 255).astype(np.uint8))
+ d = ImageDraw.Draw(im)
+ # boss bar
+ bw, bh, by = int(w * 0.46), max(3, int(7 * u)), int(26 * u)
+ bx = (w - bw) // 2
+ flag = {"wither": " [SHELL UP]", "ender_dragon": " [NO CRYSTALS]"}.get(g.name, " [ENRAGED]")
+ title = TITLES.get(g.name, g.name) + (flag if g.enraged else "")
+ f = _font(max(10, int(16 * u)), True)
+ tw = d.textlength(title, font=f)
+ d.text(((w - tw) / 2 + 1, by - int(20 * u) + 1), title, font=f, fill=(40, 40, 40))
+ d.text(((w - tw) / 2, by - int(20 * u)), title, font=f, fill=(255, 255, 255))
+ d.rectangle([bx - 1, by - 1, bx + bw + 1, by + bh + 1], fill=(20, 20, 20))
+ frac = max(g.hp, 0) / g.max_hp
+ col = (255, 70, 60) if g.enraged else BAR.get(g.name, (200, 60, 200))
+ d.rectangle([bx, by, bx + int(bw * frac), by + bh], fill=col)
+ for i in range(1, 20): # notches
+ x = bx + bw * i // 20
+ d.line([x, by + bh // 2, x, by + bh], fill=(0, 0, 0))
+ # numeric boss health: the tiers differ in maximum health (2026-11-02), which the bar alone does not show
+ f4 = _font(max(9, int(12 * u)), True)
+ hp_txt = f"{max(g.hp, 0):.0f} / {g.max_hp:.0f}"
+ d.text((bx + bw + int(8 * u) + 1, by - int(4 * u) + 1), hp_txt, font=f4, fill=(0, 0, 0))
+ d.text((bx + bw + int(8 * u), by - int(4 * u)), hp_txt, font=f4, fill=(235, 235, 235))
+ # state tag
+ if g.name == "warden":
+ tag = WARDEN_HUD.get(phase, phase.upper())
+ else:
+ tag = PHASE_HUD.get(phase, None) if phase else None
+ tag = tag or STATE_HUD.get(g.state, g.state.upper())
+ if hasattr(g, "crystals"):
+ tag += f" CRYSTALS {sum(x['alive'] for x in g.crystals)}"
+ if g.name == "zombie_leader":
+ tag += f" REINFORCEMENTS {sum(z.hp > 0 for z in g.minions)}"
+ if g.name == "skeleton" and g.state == "windup":
+ tag = "DRAWING - TAKE COVER"
+ f2 = _font(max(9, int(13 * u)), True)
+ tc = (255, 210, 60) if hot else (255, 120, 90) if g.state in ("swing", "strike", "dash", "armored") else (210, 210, 210)
+ tw = d.textlength(tag, font=f2)
+ d.text(((w - tw) / 2 + 1, by + bh + int(5 * u) + 1), tag, font=f2, fill=(0, 0, 0))
+ d.text(((w - tw) / 2, by + bh + int(5 * u)), tag, font=f2, fill=tc)
+ # fight clock + native simulation rate, top right
+ f5 = _font(max(9, int(12 * u)), True)
+ clock = f"{c.t / FPS:6.1f} s {FPS}Hz"
+ cw5 = d.textlength(clock, font=f5)
+ d.rectangle([w - cw5 - int(14 * u), int(6 * u), w - int(6 * u), int(24 * u)], fill=(16, 16, 20))
+ d.text((w - cw5 - int(10 * u), int(8 * u)), clock, font=f5, fill=(235, 235, 235))
+ # hearts (pixel art; black while the Wither effect drains, white outline blink while hurt-immune)
+ px = max(1, int(round(u)))
+ hw = 9 * px + px
+ hx, hy = int(w / 2 - 10 * hw / 2), h - int(44 * u)
+ heart = (".XXX.XXX.", "XXXXXXXXX", "XXXXXXXXX", "XXXXXXXXX", ".XXXXXXX.", "..XXXXX..", "...XXX...", "....X....")
+ withered = getattr(b, "wither_t", 0) > 0
+ blink = b.iframes > 0 and int(c.t * VT / 3) % 2 == 0
+ fill = (40, 34, 34) if withered else (214, 28, 28)
+ shine = (120, 110, 110) if withered else (255, 150, 150)
+ edge = (250, 250, 250) if blink else (24, 8, 8)
+ empty = (60, 18, 18)
+ pts = {"edge": [], "fill": [], "shine": [], "empty": []}
+ for i in range(10):
+ ox = hx + i * hw
+ full = b.hp - 2 * i
+ for y, row in enumerate(heart):
+ for x, ch in enumerate(row):
+ if ch != "X":
+ continue
+ for ex, ey in ((-1, 0), (1, 0), (0, -1), (0, 1)):
+ pts["edge"].append((ox + (x + ex) * px, hy + (y + ey) * px))
+ for y, row in enumerate(heart):
+ for x, ch in enumerate(row):
+ if ch != "X":
+ continue
+ lit = full >= 2 or (full >= 1 and x <= 4)
+ key = ("shine" if (x, y) in ((2, 1), (1, 2)) else "fill") if lit else "empty"
+ pts[key].append((ox + x * px, hy + y * px))
+ for key, col in (("edge", edge), ("empty", empty), ("fill", fill), ("shine", shine)):
+ for (x0, y0) in pts[key]:
+ d.rectangle([x0, y0, x0 + px - 1, y0 + px - 1], fill=col)
+ # armor points above the hearts (2 points per icon, grey chestplates)
+ armor = float(b.k.armor)
+ ay = hy - int(11 * u)
+ for i in range(10):
+ ox = hx + i * hw
+ level = armor - 2 * i
+ if level <= 0:
+ continue
+ col = (205, 210, 215)
+ d.rectangle([ox + px, ay, ox + 8 * px, ay + 6 * px], fill=(40, 40, 44))
+ right = ox + (8 if level >= 2 else 4) * px
+ d.rectangle([ox + 2 * px, ay + px, right - px, ay + 5 * px], fill=col)
+ # attack charge (crosshair indicator)
+ cw = int(16 * u)
+ cx, cy = w // 2, h // 2
+ d.line([cx - 5, cy, cx + 5, cy], fill=(240, 240, 240))
+ d.line([cx, cy - 5, cx, cy + 5], fill=(240, 240, 240))
+ is_bow = getattr(b, "weapon", "sword") == "bow"
+ if b.charge < 1.0 or is_bow:
+ d.rectangle([cx - cw // 2, cy + int(10 * u), cx + cw // 2, cy + int(12 * u)], fill=(60, 60, 60))
+ d.rectangle([cx - cw // 2, cy + int(10 * u), cx - cw // 2 + int(cw * b.charge), cy + int(12 * u)],
+ fill=(235, 185, 70) if is_bow else (230, 230, 230))
+ if is_bow:
+ draw_status = f"BOW {round(b.bow_charge * 100):d}%" if b.bow_drawing else "BOW / HOLD RMB"
+ f3 = _font(max(9, int(11 * u)))
+ tw = d.textlength(draw_status, font=f3)
+ d.text(((w - tw) / 2, h - int(66 * u)), draw_status, font=f3, fill=(255, 218, 128))
+ if b.bow_drawing:
+ d.text((int(10 * u), h - int(26 * u)), "Release RMB to fire", font=f3, fill=(255, 218, 128))
+ # hotbar: slot 1 sword, slot 2 bow, frame on the held slot (mouse wheel switches)
+ slot = int(20 * u)
+ sx, sy = int(w / 2 - 4.5 * slot), h - int(26 * u)
+ for i in range(9):
+ d.rectangle([sx + i * slot, sy, sx + (i + 1) * slot - 1, sy + slot - 1], outline=(30, 30, 30),
+ fill=(118, 118, 118) if i < 2 else (96, 96, 96))
+ held = 1 if is_bow else 0
+ d.rectangle([sx + held * slot - 1, sy - 1, sx + (held + 1) * slot, sy + slot], outline=(255, 255, 255),
+ width=max(1, int(round(1.5 * u))))
+ bx = sx + slot
+ d.line([(bx + 5, sy + 3), (bx + slot - 5, sy + slot // 2), (bx + 5, sy + slot - 4)],
+ fill=(205, 146, 65), width=max(1, int(2 * u)))
+ d.line([(bx + 5, sy + 3), (bx + 4, sy + slot // 2), (bx + 5, sy + slot - 4)], fill=(235, 230, 205), width=1)
+ d.line([sx + 4, sy + slot - 5, sx + slot - 5, sy + 4], fill=(120, 225, 235), width=max(1, int(2 * u)))
+ d.line([sx + 4, sy + slot - 5, sx + 8, sy + slot - 9], fill=(110, 75, 40), width=max(1, int(2 * u)))
+ if is_bow and getattr(c, "arrows", None):
+ f3 = _font(max(9, int(12 * u)))
+ d.text((int(10 * u), int(27 * u) if getattr(g, "skulls", None) else int(10 * u)),
+ f"arrows in flight: {len(c.arrows)}", font=f3, fill=(245, 220, 170))
+ if getattr(g, "skulls", None):
+ f3 = _font(max(9, int(12 * u)))
+ d.text((int(10 * u), int(10 * u)), f"shells in flight: {len(g.skulls)}", font=f3, fill=(220, 200, 255))
+ return np.asarray(im)
diff --git a/environments/games/prototype/bossbench/native_games.py b/environments/games/prototype/bossbench/native_games.py
new file mode 100644
index 0000000000000000000000000000000000000000..21c3e700770ae0e6512205dae0d37cb1aed2227c
--- /dev/null
+++ b/environments/games/prototype/bossbench/native_games.py
@@ -0,0 +1,249 @@
+"""Optional browser-backed integrations; no dependency on a game's internal world classes.
+
+The protocol also permits other implementations (native executable, RPC, Python).
+Only this integration knows JavaScript and Canvas. All instances have isolated pages.
+"""
+from __future__ import annotations
+
+import base64
+import io
+import json
+import os
+from pathlib import Path
+
+import numpy as np
+from PIL import Image
+
+from .engine_contract import EngineSpec, EngineSnapshot, RenderStatus
+
+WEB = Path(__file__).resolve().parents[2] / 'web'
+
+
+def _discover_native_games():
+ """Every web/games//manifest.json with engine "independent" is a native game.
+
+ New games register themselves by adding their own manifest; no shared file has to change.
+ """
+ games = []
+ for manifest in sorted((WEB / 'games').glob('*/manifest.json')):
+ if manifest.parent.name.startswith(('_', '.')):
+ continue
+ try:
+ data = json.loads(manifest.read_text(encoding='utf8'))
+ except (OSError, ValueError):
+ continue
+ if data.get('engine') == 'independent':
+ games.append(manifest.parent.name)
+ return tuple(games)
+
+
+NATIVE_GAMES = _discover_native_games()
+
+
+def _load_manifests():
+ """Each independent game declares itself in web/games//manifest.json (bossbench/game-manifest@1).
+
+ The JS module's own declaration (hz, version, renderer) is checked against it when a backend starts,
+ so a game folder can bump its rule version or add script files without editing this module.
+ """
+ cases = {}
+ for game in NATIVE_GAMES:
+ manifest = json.loads((WEB / 'games' / game / 'manifest.json').read_text(encoding='utf8'))
+ if manifest.get('schema') != 'bossbench/game-manifest@1' or manifest.get('game') != game:
+ raise RuntimeError(f'{game}: invalid manifest.json')
+ for case_id in manifest['cases']:
+ if case_id in cases:
+ raise RuntimeError(f'native case declared twice: {case_id}')
+ cases[case_id] = {'game': game, 'dimension': manifest['dimension'], 'hz': manifest['native_hz'],
+ 'module': manifest['module'], 'renderer': manifest['renderer'],
+ 'seconds': manifest['max_seconds'], 'version': manifest['rules'],
+ 'scripts': tuple(manifest['scripts'])}
+ return cases
+
+
+NATIVE_CASES = _load_manifests()
+
+
+def source_paths(case_id):
+ spec = NATIVE_CASES[case_id]
+ return [Path(__file__), *(WEB / 'games' / path for path in spec['scripts'])]
+
+
+class JavaScriptBackend:
+ def __init__(self, case_id):
+ from .webenv import BrowserTransport
+ self.case_id = case_id
+ entry = NATIVE_CASES[case_id]
+ self.spec = EngineSpec(entry['game'], entry['dimension'], entry['hz'], entry['seconds'],
+ entry['renderer'], 'perspective' if entry['dimension'] == '3d' else 'raster',
+ rule_version=entry['version'])
+ self.page = None
+ self._pid = os.getpid()
+ self._ready = False
+ self._error = None
+ self._reset = False
+ try:
+ self.page = BrowserTransport._launch().new_page(viewport={'width': 854, 'height': 480})
+ self.page.set_content('')
+ for script in source_paths(case_id)[1:]:
+ self.page.add_script_tag(path=str(script))
+ self.page.evaluate('name => { window.backendModule=window[name]; window.backendCanvas=document.querySelector("canvas"); }', entry['module'])
+ declaration = self.page.evaluate('() => [backendModule.hz,backendModule.version,backendModule.renderer]')
+ if declaration != [self.spec.native_hz, self.spec.rule_version, self.spec.renderer]:
+ raise RuntimeError('Python/JavaScript engine declaration mismatch')
+ from .tiers import validate_declared
+ self._tiers = validate_declared(self.page.evaluate('() => backendModule.tiers || null'),
+ where=f'{entry["module"]}.tiers')
+ # A game that declares validateOptions opts in to game-specific reset options (loadouts etc.);
+ # one that does not keeps refusing anything beyond the harness's own keys.
+ self._accepts_options = bool(self.page.evaluate(
+ '() => typeof backendModule.validateOptions === "function"'))
+ self._has_band = bool(self.page.evaluate(
+ '() => typeof backendModule.difficultyBand === "function"'))
+ except BaseException:
+ self.close()
+ raise
+
+ def _open(self):
+ if self.page is None:
+ raise RuntimeError('backend is closed')
+ if self._pid != os.getpid():
+ raise RuntimeError('backend belongs to another process; use spawned workers')
+
+ # Reset options the shared harness itself understands. Anything else is a *game* option: it is forwarded
+ # only when the game declares a validator (Module.validateOptions) and is rejected by that validator's own
+ # rules, so a typo still fails loudly instead of being silently ignored. 2026-11-03, requested by
+ # isaac_remake (item loadouts); games without a validator keep the old behaviour of refusing extras.
+ HARNESS_OPTIONS = frozenset({'difficulty', 'latency', 'engine_seed', 'resolved_from_tier'})
+
+ def game_options(self, options):
+ """Split reset options into the harness's own and the game's, validating the latter in the game."""
+ extra = {k: v for k, v in (options or {}).items() if k not in self.HARNESS_OPTIONS}
+ if not extra:
+ return None
+ if not self._accepts_options:
+ raise ValueError(f'unsupported {self.spec.engine_id} reset options: {sorted(extra)}')
+ try:
+ self.page.evaluate('a => backendModule.validateOptions(a)', extra)
+ except Exception as error: # the game's own message is the useful one
+ raise ValueError(f'{self.spec.engine_id} rejected reset options {sorted(extra)}: '
+ f'{str(error).splitlines()[0][:160]}') from None
+ return extra
+
+ def validate_options(self, options):
+ self.game_options(options)
+
+ def _snapshot(self, expression, argument=None):
+ # JSON canonicalization matches the Node validation path, including -0.
+ result = json.loads(self.page.evaluate(f'a => JSON.stringify({expression})', argument))
+ result['events'] = tuple(result['events'])
+ return EngineSnapshot(**result)
+
+ def reset(self, seed, difficulty, options):
+ self._open()
+ extra = self.game_options(options)
+ self.page.evaluate('a => { window.backendSession=new NativeBench.Session(backendModule,a.id,a.seed,a.d,a.options);'
+ ' backendSession.recording=false; }',
+ {'id': self.case_id, 'seed': seed, 'd': difficulty, 'options': extra})
+ self._reset = True
+ self._ready, self._error = False, None
+ return self._snapshot('backendSession.snapshot()')
+
+ def advance(self, packet):
+ self._open()
+ if not self._reset:
+ raise RuntimeError('reset before advancing')
+ return self._snapshot('backendSession.packet(a)',
+ {'holds': [sorted(h) for h in packet.holds], 'mouse': list(packet.mouse)})
+
+ def render(self):
+ self._open()
+ if not self._reset:
+ raise RuntimeError('reset before rendering')
+ try:
+ result = self.page.evaluate('''() => {
+ const context=backendCanvas.getContext("2d");
+ backendModule.draw(backendSession.game,context);
+ return {png:backendCanvas.toDataURL("image/png").split(",")[1],
+ status:backendModule.renderStatus ? backendModule.renderStatus(context) : null};
+ }''')
+ status = result['status']
+ if status is not None and (not status.get('ready') or status.get('error')
+ or status.get('kind') != self.spec.render_kind
+ or status.get('renderer') != self.spec.renderer):
+ raise RuntimeError(f"game renderer not ready: {status}")
+ png = result['png']
+ with Image.open(io.BytesIO(base64.b64decode(png))) as image:
+ rgb = np.asarray(image.convert('RGB'), dtype=np.uint8).copy()
+ if rgb.shape != (480, 854, 3):
+ raise RuntimeError('renderer returned an incorrect resolution')
+ self._ready, self._error = True, None
+ return rgb
+ except Exception as error:
+ self._ready, self._error = False, str(error)
+ raise
+
+ def render_status(self):
+ return RenderStatus(self.spec.renderer, self.spec.render_kind, self._ready, self._error)
+
+ def declared_tiers(self):
+ """The module's own Module.tiers = {easy, normal, hard} -> difficulty, validated at startup."""
+ return getattr(self, '_tiers', None)
+
+ def difficulty_band(self, d):
+ """Module.difficultyBand(d) -> the game's own name for the segment d falls in, or None.
+
+ Optional. Pure function of d, so it exposes nothing the public info does not already carry, and so
+ it is cached per difficulty — _info() runs every step, and querying the page each time wasted a
+ measurable share of a step (measured by the Cuphead session on the web route, 2026-11-03).
+ """
+ if not getattr(self, '_has_band', False):
+ return None
+ key = float(d)
+ cache = getattr(self, '_band_cache', None)
+ if cache is None:
+ cache = self._band_cache = {}
+ if key not in cache:
+ from .unified import _clean_band
+ cache[key] = _clean_band(
+ self.page.evaluate('d => backendModule.difficultyBand(d) ?? null', key),
+ f'{self.case_id}.difficultyBand')
+ return cache[key]
+
+ def scripted(self):
+ """Trusted reference controller (Module.scripted, else Module.oracle) for the current state.
+
+ Returns {holds: 6 key arrays, mouse: [dx, dy, dz]}; it must not change the simulation.
+ """
+ self._open()
+ if not self._reset:
+ raise RuntimeError('reset before asking the scripted controller')
+ return self.page.evaluate('''() => {
+ const M=backendModule, f=M.scripted||M.oracle;
+ if(typeof f!=='function') throw Error(M.id+': no scripted controller (Module.scripted)');
+ const before=NativeBench.hash(backendSession.state());
+ const out=f.call(M, backendSession.game);
+ if(NativeBench.hash(backendSession.state())!==before) throw Error('scripted controller changed the simulation');
+ return {holds:out.holds.map(h=>[...h]), mouse:[...(out.mouse||[0,0,0])]};
+ }''')
+
+ def manual(self):
+ self._open()
+ return self.page.evaluate('''() => ({controls:Array.isArray(backendModule.controls)
+ ? backendModule.controls : Object.entries(backendModule.controls).map(([key,value])=>key+": "+value)})''')
+
+ def close(self):
+ page, self.page = self.page, None
+ self._ready = False
+ if page is not None and self._pid == os.getpid() and not page.is_closed():
+ try:
+ page.evaluate('''() => {
+ if(window.backendModule && backendModule.closeRenderer && window.backendCanvas)
+ backendModule.closeRenderer(backendCanvas.getContext("2d"));
+ }''')
+ finally:
+ page.close()
+
+
+def backend_factory(case_id):
+ return lambda: JavaScriptBackend(case_id)
diff --git a/environments/games/prototype/bossbench/play_server.py b/environments/games/prototype/bossbench/play_server.py
new file mode 100644
index 0000000000000000000000000000000000000000..2d6d81696ba420543e14af430a84c3324d5f90bd
--- /dev/null
+++ b/environments/games/prototype/bossbench/play_server.py
@@ -0,0 +1,404 @@
+"""Human play server for the Minecraft remake: the real mc4d simulation + ModernGL renderer behind a browser page.
+
+ python games/prototype/bossbench/play_server.py # http://127.0.0.1:8765/
+ python games/prototype/bossbench/play_server.py --port 8770 --open
+
+Standard library only (http.server on 127.0.0.1). Each browser tab owns one session = one public-interface style
+environment (bossbench.make(case, obs_mode="symbolic") -> PyCaseEnv -> mc4d.MobFight), so a human packet is decoded
+by exactly the same keymouse.schedule + Steve.keys path as bossbench.make_policy_env. The page streams its own input
+as legal `bossbench/policy-replay@1` packets: one packet = 200 ms = 6 hold sets of <= 4 keys + mouse dx dy dz.
+
+ GET / -> web/games/minecraft_remake/index.html (and its static files)
+ GET /api/meta -> rules, tiers, cases, options, controls, protocol
+ POST /api/new {case, seed, tier | difficulty, weapon, camera} -> {sid, state}
+ POST /api/step {sid, packets:[text,...]} -> {state, outcome, ...} (<= 5 packets)
+ POST /api/scripted {sid, n} -> runs the standard scripted controller n packets
+ GET /api/frame?sid=..&t=.. -> image/jpeg of the current state from the real renderer (+HUD)
+ GET /api/replay?sid=.. -> the session's packets as bossbench/policy-replay@1
+ POST /api/import {replay} -> new session, re-simulated packet by packet, checked against rules/outcome/hash
+
+The world never advances on its own: the browser sends a packet every 200 ms (pause = stop sending), so the
+simulation stays a pure function of (case, seed, options, packets) and every play can be exported and re-verified.
+"""
+from __future__ import annotations
+
+import argparse
+import io
+import json
+import os
+import pathlib
+import secrets
+import sys
+import threading
+import time
+import traceback
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from urllib.parse import parse_qs, urlparse
+
+ROOT = pathlib.Path(__file__).resolve().parents[2]
+if str(ROOT / "prototype") not in sys.path:
+ sys.path.insert(0, str(ROOT / "prototype"))
+
+import numpy as np # noqa: E402
+
+import bossbench # noqa: E402
+from bossbench import keymouse as km, mc4d, mc_scripted, tiers # noqa: E402
+
+PAGE = ROOT / "web" / "games" / "minecraft_remake"
+CASES = tuple(f"3d/minecraft_{m}" for m in mc4d.MOBS)
+# 2026-11-10 (user: "remove the Green Brawler"): the scene list the page offers is the benchmark's six. The retired green zombie
+# stays playable by id (old replays, the frozen formal case); it is just not offered in the dropdown.
+from bossbench.scope import BENCH_RETIRED # noqa: E402
+LISTED = tuple(c for c in CASES if c not in BENCH_RETIRED)
+NAMES = {"3d/minecraft_iron_golem": "Hurling Brute", "3d/minecraft_zombie": "Green Brawler",
+ "3d/minecraft_ender_dragon": "Violet Breath Flyer", "3d/minecraft_wither": "Three-Headed Hover Gun",
+ "3d/minecraft_warden": "Blind Shockwave Beast", "3d/minecraft_skeleton": "Strafing Bowman",
+ "3d/minecraft_zombie_leader": "Horde Caller"}
+TIER_LABELS = {"easy": "Easy", "normal": "Normal", "hard": "Hard"} # as the shared page shells
+REPLAY_FORMAT = "bossbench/policy-replay@1"
+MAX_SESSIONS = 6
+TYPES = {".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".css": "text/css; charset=utf-8",
+ ".json": "application/json; charset=utf-8", ".png": "image/png", ".jpg": "image/jpeg", ".svg": "image/svg+xml",
+ ".md": "text/plain; charset=utf-8", ".mp4": "video/mp4"}
+
+
+class Session:
+ """One live episode. All access is serialized by the session lock (GL contexts are not thread-safe)."""
+
+ def __init__(self, case_id, seed, difficulty, options, tier=None):
+ self.lock = threading.RLock()
+ self.case_id = case_id
+ self.env = bossbench.make(case_id, obs_mode="symbolic")
+ self.used = time.time()
+ self.reset(seed, difficulty, options, tier)
+
+ def reset(self, seed, difficulty, options, tier=None):
+ # A public tier is resolved by the env from mc4d.TIERS (bossbench.tiers), exactly as make_policy_env does;
+ # the session then pins the concrete difficulty plus resolved_from_tier, like a harness replay.
+ opts = {"tier": tier} if tier is not None else {"difficulty": float(difficulty)}
+ opts["engine_seed"] = int(seed)
+ opts.update({k: v for k, v in options.items() if k in ("weapon", "camera")})
+ self.seed = int(seed)
+ _, info = self.env.reset(seed=int(seed), options=dict(opts))
+ if tier is not None:
+ opts.pop("tier")
+ opts["difficulty"], opts["resolved_from_tier"] = float(info["difficulty"]), tier
+ self.options = opts
+ self.packets, self.outcome, self.scripted_packets = [], None, 0
+
+ @property
+ def case(self):
+ return self.env.unwrapped.case
+
+ def step(self, packet, shots=None, every=2):
+ """Run one packet; with shots=[] also render a frame every `every` ticks (30 fps at 60 Hz) into it.
+ Rendering only reads the state (renderer contract), so frames never change the simulation."""
+ if self.outcome is not None:
+ return False
+ if km.parse_packet(packet) is None:
+ raise ValueError("illegal packet: " + repr(packet)[:200])
+ case = self.case
+ if shots is not None:
+ tick, inner = type(case).tick, self.env.unwrapped.inner
+
+ def wrapped(action, _case=case):
+ tick(_case, action)
+ if _case.t % every == 0 or _case.outcome():
+ shots.append(self.jpeg(inner.render()))
+ case.tick = wrapped
+ try:
+ _, _, terminated, truncated, info = self.env.step(packet)
+ finally:
+ case.__dict__.pop("tick", None)
+ self.packets.append(packet)
+ if terminated or truncated:
+ self.outcome = info["outcome"]
+ return True
+
+ @staticmethod
+ def jpeg(image, quality=74, data_url=True):
+ from PIL import Image
+ import base64
+ buffer = io.BytesIO()
+ Image.fromarray(image).save(buffer, "JPEG", quality=quality)
+ raw = buffer.getvalue()
+ return "data:image/jpeg;base64," + base64.b64encode(raw).decode("ascii") if data_url else raw
+
+ def frame(self, quality=78):
+ return self.jpeg(self.env.unwrapped.inner.render(), quality, data_url=False)
+
+ def summary(self):
+ c, raw = self.case, self.env.unwrapped
+ b, g = c.body, c.boss
+ boss = {"name": NAMES.get(self.case_id, g.name), "kind": g.name, "hp": round(max(float(g.hp), 0.0), 2),
+ "max_hp": float(g.max_hp), "state": g.state, "phase": getattr(g, "phase", g.state),
+ "armored": bool(getattr(g, "armored", False)),
+ "crystals": sum(x["alive"] for x in getattr(g, "crystals", ())) if hasattr(g, "crystals") else None,
+ "minions": sum(z.hp > 0 for z in getattr(g, "minions", ())) if hasattr(g, "minions") else None,
+ "darkness_s": round(getattr(g, "dark_t", 0) / mc4d.FPS, 1) if hasattr(g, "dark_t") else None}
+ player = {"hp": round(max(float(b.hp), 0.0), 2), "max_hp": float(b.max_hp), "weapon": b.weapon,
+ "kit": getattr(b, "kit", "diamond"),
+ "attack_charge": round(float(b.attack_charge), 3), "bow_charge": round(float(b.bow_charge), 3),
+ "bow_drawing": bool(b.bow_drawing), "arrows_fired": b.arrows_fired, "arrows_hit": b.arrows_hit,
+ "wither_effect_s": round(b.wither_t / mc4d.FPS, 2), "yaw_deg": round(float(np.degrees(b.e.yaw)), 1),
+ "pitch_deg": round(float(np.degrees(b.e.pitch)), 1)}
+ return {"case": self.case_id, "seed": self.seed, "options": self.options, "rules": mc4d.RULES,
+ "t": round(c.t / mc4d.FPS, 3), "ticks": int(c.t), "packets": len(self.packets),
+ "max_seconds": raw.max_seconds, "outcome": self.outcome, "player": player, "boss": boss,
+ "last_swing_t": round(b.swing_t / mc4d.FPS, 3),
+ "scripted_packets": self.scripted_packets, "camera": c.camera}
+
+ def replay(self):
+ raw = self.env.unwrapped
+ ver = raw.verifier()
+ return {"format": REPLAY_FORMAT, "case_id": self.case_id, "game": "minecraft", "contract": "bossbench/policy-gym@2",
+ "rules": mc4d.RULES, "native_hz": raw.fps, "gym_seed": self.seed, "engine_seed": int(raw.engine_seed),
+ "options": self.options,
+ "controller": "human (play page)" if self.scripted_packets == 0 else
+ f"mixed: {self.scripted_packets} of {len(self.packets)} packets from the scripted controller",
+ "packets": list(self.packets), "steps": len(self.packets), "ticks": int(self.case.t),
+ "seconds": round(self.case.t / raw.fps, 4), "outcome": ver["outcome"],
+ "terminated": ver["outcome"] in ("win", "loss"), "truncated": ver["outcome"] == "timeout",
+ "verifier": ver, "final_hash": raw.state_hash()}
+
+ def close(self):
+ try:
+ self.env.close()
+ except Exception:
+ pass
+
+
+SESSIONS: dict = {}
+SLOCK = threading.Lock()
+# WGL/GLX contexts are bound to the thread that made them current; http.server answers every request on a new
+# thread. All simulation + rendering therefore runs on this one worker thread (requests are serialized).
+from concurrent.futures import ThreadPoolExecutor # noqa: E402
+GL = ThreadPoolExecutor(max_workers=1, thread_name_prefix="bossbench-gl")
+
+
+def _session(sid):
+ with SLOCK:
+ s = SESSIONS.get(sid)
+ if s is None:
+ raise KeyError("unknown or expired session; press Start again")
+ s.used = time.time()
+ return s
+
+
+def _new_session(body):
+ case_id = body.get("case", LISTED[0])
+ if case_id not in CASES:
+ raise ValueError(f"unknown case {case_id!r}")
+ seed = int(body.get("seed", 1))
+ if not 0 <= seed < 2 ** 32:
+ raise ValueError("seed must be in [0, 2**32)")
+ tier = body.get("tier")
+ if tier is not None and "difficulty" in body:
+ raise ValueError("pass either tier or difficulty, not both")
+ if tier is not None and tier not in tiers.TIER_NAMES:
+ raise ValueError(f"tier must be one of {tiers.TIER_NAMES}")
+ difficulty = float(body.get("difficulty", 0.5))
+ if not 0.0 <= difficulty <= 1.0:
+ raise ValueError("difficulty must be in [0, 1]")
+ options = {k: body[k] for k in ("weapon", "camera") if k in body}
+ sid = secrets.token_hex(8)
+ s = Session(case_id, seed, difficulty, options, tier=tier)
+ if tier is None and body.get("resolved_from_tier") in tiers.TIER_NAMES: # an imported tier recording
+ s.options["resolved_from_tier"] = body["resolved_from_tier"]
+ with SLOCK:
+ SESSIONS[sid] = s
+ while len(SESSIONS) > MAX_SESSIONS: # drop the least recently used session
+ old = min(SESSIONS, key=lambda k: SESSIONS[k].used)
+ SESSIONS.pop(old).close()
+ return sid, s
+
+
+def meta():
+ body = mc4d.Steve()
+ declared = tiers.validate_declared(getattr(mc4d, "TIERS", None), "mc4d") or dict(tiers.DEFAULT_TIERS)
+ return {"rules": mc4d.RULES, "native_hz": mc4d.FPS, "packet_seconds": km.PACKET_SECONDS, "substeps": km.SUBSTEPS,
+ "keys": list(km.KEYS), "max_keys": km.MAX_KEYS, "protocol": bossbench.unified.PROTOCOL,
+ "cases": [{"id": c, "name": NAMES[c], "max_seconds": mc4d.SECONDS[c.split("_", 1)[1]]} for c in LISTED],
+ "tiers": [{"name": t, "label": TIER_LABELS[t], "difficulty": declared[t],
+ "target_seconds": list(tiers.TARGET_SECONDS[t])} for t in tiers.TIER_NAMES],
+ "default_tier": "normal",
+ "weapons": list(mc4d.WEAPONS), "cameras": ["first", "third"], "controls": list(body.MANUAL),
+ "replay_format": REPLAY_FORMAT}
+
+
+class Handler(BaseHTTPRequestHandler):
+ server_version = "BossBenchMinecraft/1"
+
+ def log_message(self, fmt, *args): # quiet: one line per error only
+ if args and str(args[1]).startswith(("4", "5")):
+ sys.stderr.write("%s %s\n" % (self.address_string(), fmt % args))
+
+ def _send(self, code, payload, ctype="application/json; charset=utf-8", extra=None):
+ data = payload if isinstance(payload, bytes) else json.dumps(payload, ensure_ascii=False).encode("utf-8")
+ self.send_response(code)
+ self.send_header("Content-Type", ctype)
+ self.send_header("Content-Length", str(len(data)))
+ self.send_header("Cache-Control", "no-store")
+ self.send_header("Access-Control-Allow-Origin", "*") # the lobby / file:// page talks to 127.0.0.1
+ for k, v in (extra or {}).items():
+ self.send_header(k, v)
+ self.end_headers()
+ self.wfile.write(data)
+
+ def _json(self):
+ n = int(self.headers.get("Content-Length") or 0)
+ if n > 16_000_000:
+ raise ValueError("request too large")
+ return json.loads(self.rfile.read(n) or b"{}")
+
+ def do_OPTIONS(self):
+ self.send_response(204)
+ self.send_header("Access-Control-Allow-Origin", "*")
+ self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
+ self.send_header("Access-Control-Allow-Headers", "Content-Type")
+ self.end_headers()
+
+ def do_GET(self):
+ return GL.submit(self._get).result()
+
+ def do_POST(self):
+ return GL.submit(self._post).result()
+
+ def _get(self):
+ url = urlparse(self.path)
+ q = parse_qs(url.query)
+ try:
+ if url.path == "/api/meta":
+ return self._send(200, meta())
+ if url.path == "/api/frame":
+ s = _session(q.get("sid", [""])[0])
+ with s.lock:
+ data = s.frame(int(q.get("q", ["78"])[0]))
+ return self._send(200, data, "image/jpeg")
+ if url.path == "/api/state":
+ s = _session(q.get("sid", [""])[0])
+ with s.lock:
+ return self._send(200, s.summary())
+ if url.path == "/api/replay":
+ s = _session(q.get("sid", [""])[0])
+ with s.lock:
+ return self._send(200, s.replay())
+ return self._static(url.path)
+ except KeyError as ex:
+ return self._send(404, {"error": str(ex).strip("'")})
+ except Exception as ex:
+ traceback.print_exc()
+ return self._send(500, {"error": repr(ex)})
+
+ def _static(self, path):
+ rel = path.lstrip("/") or "index.html"
+ if rel.endswith("/"):
+ rel += "index.html"
+ target = (PAGE / rel).resolve()
+ if not str(target).startswith(str(PAGE.resolve())) or not target.is_file():
+ return self._send(404, {"error": "not found: " + path})
+ return self._send(200, target.read_bytes(), TYPES.get(target.suffix.lower(), "application/octet-stream"))
+
+ def _post(self):
+ url = urlparse(self.path)
+ try:
+ body = self._json()
+ if url.path == "/api/new":
+ sid, s = _new_session(body)
+ with s.lock:
+ return self._send(200, {"sid": sid, "state": s.summary()})
+ if url.path == "/api/step":
+ s = _session(body.get("sid", ""))
+ packets = body.get("packets") or []
+ if len(packets) > 5:
+ raise ValueError("at most 5 packets per request (1 s of play)")
+ with s.lock:
+ shots = [] if body.get("frames") else None
+ for p in packets:
+ s.step(p, shots)
+ return self._send(200, {"state": s.summary(), "frames": shots or []})
+ if url.path == "/api/scripted":
+ s = _session(body.get("sid", ""))
+ n = max(1, min(int(body.get("n", 1)), 5))
+ with s.lock:
+ shots = [] if body.get("frames") else None
+ for _ in range(n):
+ if s.outcome is not None:
+ break
+ s.step(mc_scripted.scripted(s.case), shots)
+ s.scripted_packets += 1
+ return self._send(200, {"state": s.summary(), "frames": shots or []})
+ if url.path == "/api/import":
+ data = body.get("replay") or {}
+ problems = []
+ if data.get("format") != REPLAY_FORMAT:
+ problems.append("not a bossbench/policy-replay@1 file")
+ if data.get("rules") != mc4d.RULES:
+ problems.append(f"rules mismatch: recording {data.get('rules')!r}, engine {mc4d.RULES!r}")
+ if data.get("case_id") not in CASES:
+ problems.append(f"unknown case {data.get('case_id')!r}")
+ if problems:
+ return self._send(400, {"error": "; ".join(problems)})
+ opts = dict(data.get("options") or {})
+ sid, s = _new_session({"case": data["case_id"], "seed": opts.get("engine_seed", data.get("engine_seed", 1)),
+ "difficulty": opts.get("difficulty", 0.5),
+ **{k: opts[k] for k in ("weapon", "camera", "resolved_from_tier") if k in opts}})
+ return self._send(200, {"sid": sid, "packets": len(data.get("packets") or []),
+ "expect": {"outcome": data.get("outcome"), "final_hash": data.get("final_hash"),
+ "ticks": data.get("ticks")}, "state": s.summary()})
+ if url.path == "/api/still":
+ s = _session(body.get("sid", ""))
+ with s.lock:
+ return self._send(200, {"state": s.summary(), "frame": s.jpeg(s.env.unwrapped.inner.render())})
+ if url.path == "/api/verify":
+ s = _session(body.get("sid", ""))
+ with s.lock:
+ raw = s.env.unwrapped
+ return self._send(200, {"final_hash": raw.state_hash(), "ticks": int(s.case.t),
+ "outcome": raw.verifier()["outcome"]})
+ if url.path == "/api/close":
+ with SLOCK:
+ s = SESSIONS.pop(body.get("sid", ""), None)
+ if s is not None:
+ with s.lock:
+ s.close()
+ return self._send(200, {"closed": s is not None})
+ return self._send(404, {"error": "unknown endpoint"})
+ except KeyError as ex:
+ return self._send(404, {"error": str(ex).strip("'")})
+ except ValueError as ex:
+ return self._send(400, {"error": str(ex)})
+ except Exception as ex:
+ traceback.print_exc()
+ return self._send(500, {"error": repr(ex)})
+
+
+def main(argv=None):
+ parser = argparse.ArgumentParser(description="BossBench Minecraft human play server (127.0.0.1 only)")
+ parser.add_argument("--port", type=int, default=int(os.environ.get("BOSSBENCH_MC_PORT", 8765)))
+ parser.add_argument("--open", action="store_true", help="open the page in the default browser")
+ args = parser.parse_args(argv)
+ server = ThreadingHTTPServer(("127.0.0.1", args.port), Handler)
+ server.daemon_threads = True
+ url = f"http://127.0.0.1:{args.port}/"
+ print(f"Minecraft remake ({mc4d.RULES}) play server: {url}", flush=True)
+ if args.open:
+ import webbrowser
+ webbrowser.open(url)
+ try:
+ server.serve_forever()
+ except KeyboardInterrupt:
+ pass
+ finally:
+ server.server_close()
+ def shutdown():
+ with SLOCK:
+ for s in SESSIONS.values():
+ s.close()
+ SESSIONS.clear()
+ GL.submit(shutdown).result()
+ GL.shutdown()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/environments/games/prototype/bossbench/policy_env.py b/environments/games/prototype/bossbench/policy_env.py
new file mode 100644
index 0000000000000000000000000000000000000000..54a9fc199905f6f7ea477071623a821ce44096bd
--- /dev/null
+++ b/environments/games/prototype/bossbench/policy_env.py
@@ -0,0 +1,151 @@
+"""Public Gymnasium contract shared by visual models and RL, for 2D and 3D.
+
+The underlying simulations and privileged diagnostics remain accessible through
+``unwrapped`` for trusted collectors. This wrapper is an input boundary, not a
+security sandbox; policies receive ``rl.rollout.Context``, never the env object.
+"""
+from __future__ import annotations
+
+import copy
+
+import gymnasium as gym
+import numpy as np
+
+from . import keymouse as km
+from .core import RES
+from .scope import POLICY_CASES
+
+CONTRACT_VERSION = "bossbench/policy-gym@2"
+PUBLIC_INFO_KEYS = frozenset({
+ "case_id", "contract", "t", "steps", "frames", "lag_packets", "format_ok",
+ "format_errors", "difficulty", "engine_seed", "outcome", "terminated",
+ "truncated", "timing", "renderer",
+ # 2026-11-03: the game's own name for the segment `difficulty` falls in, when it declares one.
+ # Present only for such games, and safe to expose because it is a pure function of `difficulty`,
+ # which this info already carries — a label on a number the policy can already see, not live state.
+ # It exists so a d* sweep can explain the steps it measures at mode boundaries instead of
+ # re-deriving them from each game's source.
+ "difficulty_band",
+})
+_RAW_PUBLIC_KEYS = ("t", "steps", "frames", "lag_packets", "format_ok", "format_errors",
+ "difficulty", "engine_seed", "outcome")
+_RAW_OPTIONAL_KEYS = ("difficulty_band",)
+
+
+class PolicyEnv(gym.Wrapper):
+ """RGB + legal key/mouse packets + sparse reward + public-only info.
+
+ One step holds six key sets over 200 ms, using the declared native engine clock.
+ Text and structured actions share the same parser and rejection semantics.
+ Actual perspective 3D is mandatory: a fallback image raises an error.
+ """
+
+ def __init__(self, env):
+ raw = env.unwrapped
+ if raw.case_id not in POLICY_CASES:
+ raise ValueError(f"case is not registered for the public policy interface: {raw.case_id!r}")
+ if (raw.obs_mode, raw.action_mode, raw.reward_mode) != ("rgb", "keymouse", "sparse"):
+ raise ValueError("public policy env requires rgb/keymouse/sparse")
+ spec = raw.engine_spec
+ if raw.fps != spec.native_hz:
+ raise ValueError(f"engine clock must match declared {spec.native_hz} Hz; remove runtime FPS overrides")
+ if spec.dimension != POLICY_CASES[raw.case_id]['dimension']:
+ raise ValueError('engine dimension differs from the registered case')
+ if tuple(spec.resolution) != RES:
+ raise ValueError("public policy contract requires a renderer size of 854 x 480")
+ if spec.dimension == '3d' and spec.render_kind != 'perspective':
+ raise ValueError('3D policy observations require perspective rendering')
+ super().__init__(env)
+ self.metadata = {**env.metadata, "contract": CONTRACT_VERSION, "simulation_fps": raw.fps}
+ self._closed = False
+ self._elapsed_frames = 0
+
+ def _open(self):
+ if self._closed:
+ raise RuntimeError("environment is closed; create a new environment")
+
+ def _frame(self, image):
+ if not isinstance(image, np.ndarray) or image.shape != (RES[1], RES[0], 3) or image.dtype != np.uint8:
+ raise RuntimeError("policy observation must be RGB uint8 (480, 854, 3)")
+ if POLICY_CASES[self.unwrapped.case_id]["dimension"] == "3d":
+ status = self.unwrapped.render_status()
+ if (not status.ready or status.kind != 'perspective' or status.error is not None
+ or status.renderer != self.unwrapped.engine_spec.renderer):
+ raise RuntimeError(f"{self.unwrapped.case_id}: real 3D renderer unavailable: {status.error or 'no perspective renderer'}")
+ # Neither reused engine buffers nor policy mutation may change history.
+ return image.copy()
+
+ def _info(self, info, terminated=False, truncated=False):
+ raw = self.unwrapped
+ frames, lag = int(info["frames"]), int(info["lag_packets"])
+ lag_frames = int(raw.snap.get('lag_frames', min(frames, lag * round(raw.fps * km.PACKET_SECONDS))))
+ out = {k: copy.deepcopy(info[k]) for k in _RAW_PUBLIC_KEYS}
+ out.update({k: copy.deepcopy(info[k]) for k in _RAW_OPTIONAL_KEYS if k in info})
+ out.update(case_id=raw.case_id, contract=CONTRACT_VERSION,
+ terminated=bool(terminated), truncated=bool(truncated),
+ renderer=raw.engine_spec.renderer,
+ timing={"fps": raw.fps, "tick_seconds": 1 / raw.fps,
+ "packet_seconds": km.PACKET_SECONDS, "substeps": km.SUBSTEPS,
+ "ticks_per_substep": raw.fps * km.PACKET_SECONDS / km.SUBSTEPS,
+ "simulation_seconds": frames / raw.fps,
+ "elapsed_seconds": self._elapsed_frames / raw.fps,
+ "lag_frames": lag_frames, "action_frames": frames - lag_frames})
+ if "manual" in info:
+ out["manual"] = self.manual()
+ return out
+
+ def manual(self):
+ self._open()
+ manual = self.unwrapped.manual()
+ return {"protocol": str(manual["protocol"]), "controls": copy.deepcopy(manual["controls"])}
+
+ def reset(self, *, seed=None, options=None):
+ self._open()
+ obs, info = self.env.reset(seed=seed, options=options)
+ self._elapsed_frames = 0
+ return self._frame(obs), self._info(info)
+
+ def step(self, action, latency=None):
+ self._open()
+ obs, reward, terminated, truncated, info = self.env.step(action, latency=latency)
+ self._elapsed_frames += int(info["frames"])
+ return self._frame(obs), reward, terminated, truncated, self._info(info, terminated, truncated)
+
+ def render(self):
+ self._open()
+ return self._frame(self.env.render())
+
+ def close(self):
+ if not self._closed:
+ try:
+ self.env.close()
+ finally:
+ self._closed = True
+
+
+def make_policy_env(case_id, **kwargs):
+ """Create the same public Gym env for model evaluation and RL collection.
+
+ Pass engine-specific experiment conditions in reset(options=...), e.g.
+ Minecraft weapon/camera or Terraria dawn_in_seconds; engine_seed imports a
+ recording seed exactly. Raw symbolic/native/dense ablations use make().
+ """
+ if case_id not in POLICY_CASES:
+ raise ValueError(f"case is not registered for the public policy interface: {case_id!r}; known: {sorted(POLICY_CASES)}")
+ for key, value in (("obs_mode", "rgb"), ("action_mode", "keymouse"), ("reward_mode", "sparse")):
+ if key in kwargs and kwargs[key] != value:
+ raise ValueError(f"public policy contract requires {key}={value!r}")
+ kwargs[key] = value
+ kwargs.setdefault("time_mode", "paused")
+ kwargs.setdefault("render_mode", "rgb_array")
+ from . import make
+ env = make(case_id, **kwargs)
+ try:
+ return PolicyEnv(env)
+ except Exception:
+ env.close()
+ raise
+
+
+def policy_gym_id(case_id):
+ return "BossBenchPolicy/" + case_id.replace("/", "-") + "-v0"
diff --git a/environments/games/prototype/bossbench/progress_reward.py b/environments/games/prototype/bossbench/progress_reward.py
new file mode 100644
index 0000000000000000000000000000000000000000..b881d594b55d6823226b3ad97e2e81e5834950a8
--- /dev/null
+++ b/environments/games/prototype/bossbench/progress_reward.py
@@ -0,0 +1,102 @@
+"""Versioned high-water progress reward; trusted scoring only, never policy input."""
+from __future__ import annotations
+
+import math
+import gymnasium as gym
+
+REWARD_CONTRACT = 'bossbench/step-progress-highwater@1'
+
+
+def unit(value):
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
+ raise RuntimeError('progress must be numeric')
+ value = float(value)
+ if not math.isfinite(value) or not 0 <= value <= 1:
+ raise RuntimeError('progress must be finite and in [0,1]')
+ return value
+
+
+class HighWaterProgress:
+ def __init__(self, initial):
+ self.initial = self.peak = self.final = unit(initial)
+ self.steps = 0
+
+ def step(self, current):
+ current = unit(current)
+ peak = max(self.peak, current)
+ reward = peak - self.peak
+ self.peak, self.final = peak, current
+ self.steps += 1
+ return reward
+
+ def diagnostics(self):
+ return dict(contract=REWARD_CONTRACT, initial_progress=self.initial,
+ peak_progress=self.peak, final_progress=self.final,
+ episode_return=self.peak - self.initial, steps=self.steps)
+
+
+def objective_progress(snapshot, case_id):
+ """Read scoring fields while preserving the original game's HP and outcome."""
+ from .step_reward import objective_progress as hp_progress
+ if case_id == 'cuphead/root_pack':
+ boss = snapshot['state']['boss']
+ score = boss['reward_objective']
+ if score['version'] != 'root-pack-fixed-phase@1':
+ raise RuntimeError('Root Pack fixed phase scoring unavailable')
+ return unit(score['progress'])
+ if case_id == 'nfsmw/speedtrap':
+ game = snapshot['state']['game']
+ score, target = game['you'], game['reward_target_score']
+ if game['reward_target_version'] != 'speedtrap-reachable-profile@1':
+ raise RuntimeError('Speedtrap calibration unavailable')
+ if not math.isfinite(score) or score < 0 or not math.isfinite(target) or target <= 0:
+ raise RuntimeError('Invalid speedtrap score/target')
+ return unit(min(1.0, score / target))
+ return unit(hp_progress(snapshot))
+
+
+class StepProgressReward(gym.Wrapper):
+ """Reward new peaks at env.step boundaries, including each step's lag window.
+
+ No reward rescaling by batch, terminal bonus, time/death/format penalty, or
+ repeated credit after healing. Imported initial progress is not rewarded.
+ """
+ def __init__(self, env, case_id):
+ super().__init__(env)
+ self.case_id = case_id
+ self.metadata = dict(env.metadata, reward_contract=REWARD_CONTRACT)
+ self.scorer = None
+ self._closed, self._done = False, True
+
+ def reset(self, *, seed=None, options=None):
+ if self._closed:
+ raise RuntimeError('environment is closed')
+ obs, info = self.env.reset(seed=seed, options=options)
+ self._done = True
+ self.scorer = HighWaterProgress(objective_progress(self.unwrapped.snap, self.case_id))
+ self._done = False
+ return obs, dict(info, reward_contract=REWARD_CONTRACT)
+
+ def step(self, action, latency=None):
+ if self._closed or self._done or self.scorer is None:
+ raise RuntimeError('reset required before step')
+ try:
+ obs, _, terminated, truncated, info = self.env.step(action, latency=latency)
+ reward = self.scorer.step(objective_progress(self.unwrapped.snap, self.case_id))
+ except BaseException:
+ self._done = True
+ raise
+ self._done = bool(terminated or truncated)
+ return obs, reward, terminated, truncated, dict(info, reward_contract=REWARD_CONTRACT)
+
+ def reward_diagnostics(self):
+ if self.scorer is None:
+ raise RuntimeError('reset required')
+ return dict(self.scorer.diagnostics(), done=self._done)
+
+ def close(self):
+ if not self._closed:
+ try:
+ self.env.close()
+ finally:
+ self._closed = self._done = True
diff --git a/environments/games/prototype/bossbench/rig.py b/environments/games/prototype/bossbench/rig.py
new file mode 100644
index 0000000000000000000000000000000000000000..5e4978d77433052621e7b942bc5bf77268fa9b86
--- /dev/null
+++ b/environments/games/prototype/bossbench/rig.py
@@ -0,0 +1,235 @@
+"""Rig: the single animation channel that every renderer reads.
+
+A rig is a set of named boxes ("parts") attached to an entity's report frame. Once per tick the
+simulation poses it: each part gets a world origin and a rotation, built from a local offset in
+the entity's own frame (x = forward, y = up, z = right) plus three angles in degrees
+(yaw about up, pitch about right = limb raise, roll about forward = wing flap).
+
+ rig.pose(case.t, {"arm_l": (0, 2.05, -0.95, 0, 166), ...}, e.pos, e.yaw)
+
+Renderers interpolate between ticks instead of animating on their own clock::
+
+ origin(t) = origin[k] + (origin[k+1] - origin[k]) * u u = (t - tick_k) / (tick_k1 - tick_k)
+
+so a pose is an exact function of the simulation tick, not of the renderer's frame timer, and
+drawing two ticks or twenty between two keyframes gives the same picture at the same fractional
+time. Rotations travel as quaternions, which removes every Euler-order ambiguity between three.js,
+Godot and the numpy box renderer.
+
+Nothing here feeds back into the rules: a rig only ever describes what the simulation already did
+(architecture rule 1).
+"""
+from __future__ import annotations
+
+import math
+
+import numpy as np
+
+_PI = np.pi
+
+
+def q_y(deg: float) -> np.ndarray:
+ a = np.radians(deg) * 0.5
+ return np.array([0.0, np.sin(a), 0.0, np.cos(a)])
+
+
+def q_z(deg: float) -> np.ndarray:
+ a = np.radians(deg) * 0.5
+ return np.array([0.0, 0.0, np.sin(a), np.cos(a)])
+
+
+def q_x(deg: float) -> np.ndarray:
+ a = np.radians(deg) * 0.5
+ return np.array([np.sin(a), 0.0, 0.0, np.cos(a)])
+
+
+def q_mul(a: np.ndarray, b: np.ndarray) -> np.ndarray:
+ x1, y1, z1, w1 = a
+ x2, y2, z2, w2 = b
+ return np.array([w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2,
+ w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2,
+ w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2,
+ w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2])
+
+
+def q_norm(q: np.ndarray) -> np.ndarray:
+ n = np.linalg.norm(q)
+ return q / n if n > 1e-12 else np.array([0.0, 0.0, 0.0, 1.0])
+
+
+def q_slerp(a: np.ndarray, b: np.ndarray, u: float) -> np.ndarray:
+ """Shortest-arc slerp; u is clamped by the caller."""
+ d = float(np.dot(a, b))
+ if d < 0.0:
+ b, d = -b, -d
+ if d > 0.9995:
+ return q_norm(a + (b - a) * u)
+ th = np.arccos(np.clip(d, -1.0, 1.0))
+ s = np.sin(th)
+ return q_norm(np.sin((1 - u) * th) / s * a + np.sin(u * th) / s * b)
+
+
+def q_to_mat(q: np.ndarray) -> np.ndarray:
+ x, y, z, w = q
+ return np.array([[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)],
+ [2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)],
+ [2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)]])
+
+
+# -- tuple quaternions: Bones runs every tick inside the simulation step, so it stays off numpy --
+def _qm(a, b):
+ x1, y1, z1, w1 = a
+ x2, y2, z2, w2 = b
+ return (w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2, w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2,
+ w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2, w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2)
+
+
+def _qe(yaw, pitch, roll):
+ """q_y(-yaw) * q_z(pitch) * q_x(roll): yaw turns +x toward +z (right), pitch raises +x, roll
+ lowers +z. Same order the entity frame uses, so a chain of these composes like a skeleton."""
+ a, b, c = math.radians(-yaw) * 0.5, math.radians(pitch) * 0.5, math.radians(roll) * 0.5
+ q = (0.0, math.sin(a), 0.0, math.cos(a))
+ if b:
+ q = _qm(q, (0.0, 0.0, math.sin(b), math.cos(b)))
+ if c:
+ q = _qm(q, (math.sin(c), 0.0, 0.0, math.cos(c)))
+ return q
+
+
+def _qv(q, v):
+ x, y, z, w = q
+ tx, ty, tz = 2 * (y * v[2] - z * v[1]), 2 * (z * v[0] - x * v[2]), 2 * (x * v[1] - y * v[0])
+ return (v[0] + w * tx + y * tz - z * ty, v[1] + w * ty + z * tx - x * tz, v[2] + w * tz + x * ty - y * tx)
+
+
+class Bones:
+ """Forward kinematics in the entity frame, feeding Rig.pose.
+
+ b = Bones()
+ b.bone("body", None, (0, 1.0, 0), pitch=lean)
+ b.bone("arm_r", "body", (0, 0.62, 0.69), pitch=raise_, boxes=("arm_r", "vine_r"))
+ rig.pose(t, b.spans, e.pos, e.yaw)
+
+ A bone's offset and angles are relative to its parent; every box listed in `boxes` takes the
+ bone's frame (the box's own "pivot" then places it inside that frame).
+ """
+
+ def __init__(self):
+ self.f, self.spans = {}, {}
+
+ def bone(self, name, parent=None, at=(0.0, 0.0, 0.0), yaw=0.0, pitch=0.0, roll=0.0, boxes=None):
+ p, q = self.f[parent] if parent else ((0.0, 0.0, 0.0), (0.0, 0.0, 0.0, 1.0))
+ o = _qv(q, at)
+ pos = (p[0] + o[0], p[1] + o[1], p[2] + o[2])
+ ql = _qm(q, _qe(yaw, pitch, roll))
+ self.f[name] = (pos, ql)
+ for b in (boxes if boxes is not None else (name,)):
+ self.spans[b] = (pos[0], pos[1], pos[2], ql)
+ return pos
+
+ def point(self, name, v):
+ """A point given in bone `name`'s frame, in the entity frame."""
+ p, q = self.f[name]
+ o = _qv(q, v)
+ return (p[0] + o[0], p[1] + o[1], p[2] + o[2])
+
+
+class Rig:
+ """Boxes for one entity. Parts are declared once; only their pose changes per tick.
+
+ parts: name -> {"size": (sx, sy, sz), "color": (r, g, b), "pivot": (px, py, pz) or None,
+ "fwd": bool} pivot is the box centre inside the part frame (default the
+ origin); fwd=False means the box keeps world-aligned axes and only follows the
+ entity's position (legs of a diagonally-standing golem, for instance).
+ """
+
+ def __init__(self, parts: dict, tint=(1.0, 1.0, 1.0)):
+ self.parts = parts
+ self.tint = tuple(float(c) for c in tint)
+ self.kf: dict[str, list] = {}
+ self.hide: set = set() # parts not drawn this tick (e.g. wither armour above half hp)
+ self.variant = "" # texture variant suffix (golem cracks, wither eye glow)
+ self.overlay = (0.0, 0.0, 0.0, 0.0) # rgb + amount mixed over the lit colour (hurt red)
+ self.glow = 0.0 # boost for emissive texels (eyes flaring on a telegraph)
+ self.shell = 0.0 # alpha of a translucent shell around every part (wither guard)
+ self.shell_color = (0.55, 0.7, 1.0)
+ self.mem: dict = {} # pose-only memory (smoothed angles, state entry ticks)
+
+ # -- posing ----------------------------------------------------------
+ def reset(self) -> None:
+ self.kf = {n: [] for n in self.parts}
+
+ def pose(self, tick: int, spans: dict, root, yaw: float, base=(0.0, 0.0), h_floor: float = 0.0,
+ trim: int = 64) -> None:
+ """spans: name -> (lx, ly, lz[, yaw_deg, pitch_deg, roll_deg]) in the entity frame, or
+ (lx, ly, lz, q) with q a local quaternion (what Bones produces).
+
+ base = (pitch_deg, roll_deg) tilts the whole rig about the entity's right/forward axes,
+ which is how the dragon banks into a turn or the wither leans into a strafe.
+ """
+ Ry = q_y(-np.degrees(yaw))
+ QB = q_mul(Ry, q_mul(q_z(base[0]), q_x(base[1])))
+ M = q_to_mat(QB)
+ qb = tuple(QB)
+ root = np.asarray(root, float) + np.array([0.0, h_floor, 0.0])
+ for name, span in spans.items():
+ p = self.parts[name]
+ if len(span) == 4 and isinstance(span[3], tuple): # (lx, ly, lz, local quaternion)
+ lx, ly, lz, ql = span
+ origin = root + M @ np.array([lx, ly, lz])
+ q = np.array(_qm(qb, ql))
+ else:
+ lx, ly, lz, lyaw, pitch, roll = (tuple(span) + (0.0, 0.0, 0.0))[:6]
+ origin = root + M @ np.array([lx, ly, lz])
+ if p.get("fwd", True): # part frame follows the entity's facing
+ q = np.array(_qm(qb, _qe(lyaw, pitch, roll)))
+ else: # box keeps world axes, only its origin moves
+ q = np.array(_qe(lyaw, pitch, roll))
+ kf = self.kf.setdefault(name, [])
+ kf.append((int(tick), origin, q))
+ if len(kf) > trim:
+ del kf[:len(kf) - trim]
+
+ # -- reading ---------------------------------------------------------
+ def sample(self, t: float) -> dict:
+ """Pose at fractional tick t, interpolated between the two surrounding keyframes."""
+ out = {}
+ for name, kfs in self.kf.items():
+ if not kfs:
+ continue
+ if t <= kfs[0][0]:
+ _, o, q = kfs[0]
+ out[name] = (o, q)
+ continue
+ if t >= kfs[-1][0]:
+ _, o, q = kfs[-1]
+ out[name] = (o, q)
+ continue
+ i = 1
+ while i < len(kfs) and kfs[i][0] <= t:
+ i += 1
+ t0, o0, q0 = kfs[i - 1]
+ t1, o1, q1 = kfs[i]
+ u = 0.0 if t1 == t0 else (t - t0) / (t1 - t0)
+ out[name] = (o0 + (o1 - o0) * u, q_slerp(q0, q1, u))
+ return out
+
+
+class Rigged:
+ """Mixin: an entity that owns one or more rigs and reports their current state."""
+
+ def rigs(self) -> list:
+ return []
+
+ def rig_state(self, t) -> list:
+ out = []
+ for r in self.rigs():
+ out.append({"parts": r.parts, "pose": {n: [list(o), list(q)] for n, (o, q) in r.sample(t).items()},
+ "tint": list(getattr(r, "tint", (1.0, 1.0, 1.0)))})
+ return out
+
+
+def walk_cycle(phase: float, amp: float = 26.0, roll: float = 0.0) -> tuple:
+ """Two-leg walk: returns (left_pitch, right_pitch) in degrees for a phase in [0, 1)."""
+ a = 2 * _PI * phase
+ return (float(np.sin(a) * amp), float(np.sin(a + _PI) * amp))
diff --git a/environments/games/prototype/bossbench/scope.py b/environments/games/prototype/bossbench/scope.py
new file mode 100644
index 0000000000000000000000000000000000000000..505b223ecfe0cc7749b708dd3a224ba21dd20ac0
--- /dev/null
+++ b/environments/games/prototype/bossbench/scope.py
@@ -0,0 +1,81 @@
+"""Formal BossBench scope, separate from the backwards-compatible registry.
+
+Never discover training/evaluation scope by blindly iterating bossbench.ENVS. This manifest is
+explicit so a newly added game cannot silently enter an existing experiment.
+"""
+from __future__ import annotations
+
+from types import MappingProxyType
+
+
+FORMAL_GAMES = MappingProxyType({
+ "hollowknight_remake": "2d",
+ "kirby_remake": "2d",
+ "terraria_remake": "2d",
+ "minecraft": "3d",
+})
+
+FORMAL_CASES = MappingProxyType({
+ **{f"2d/{boss}": {"game": "hollowknight_remake", "dimension": "2d", "engine": "web"} for boss in (
+ "needle_warden", "iron_bulwark", "hollow_vessel", "sickle_sisters", "pale_vessel")},
+ **{f"kirby/{boss}": {"game": "kirby_remake", "dimension": "2d", "engine": "web"} for boss in (
+ "whispy_woods", "kracko", "king_dedede")},
+ **{f"terraria/{boss}": {"game": "terraria_remake", "dimension": "2d", "engine": "web"} for boss in (
+ "king_slime", "eye_of_cthulhu", "skeletron", "eater_of_worlds")},
+ **{f"3d/minecraft_{boss}": {"game": "minecraft", "dimension": "3d", "engine": "py"} for boss in (
+ "iron_golem", "zombie", "ender_dragon", "wither")},
+})
+
+RETIRED_CASES = ("2d/tank_battle", "tank_battle_1v1")
+# Public cases are discovered from registrations. Frozen evaluation cases are listed above.
+from . import WEB_GAME
+PUBLIC_WEB_CASES = MappingProxyType({
+ case_id: {"game": game, "dimension": "2d", "engine": "web"}
+ for case_id, game in WEB_GAME.items() if case_id not in FORMAL_CASES
+})
+# Python-route scenes (mc4d.MOBS) are discovered the same way, so Minecraft can add bosses without editing
+# this file. Their ids are "3d/_"; the game name is read from the id rather than assumed, so a
+# second Python game would be routed correctly instead of silently labelled Minecraft.
+from . import PY_CASES
+PUBLIC_PY_CASES = MappingProxyType({
+ case_id: {"game": case_id.split("/", 1)[1].split("_", 1)[0], "dimension": "3d", "engine": "py"}
+ for case_id in PY_CASES if case_id not in FORMAL_CASES
+})
+from .native_games import NATIVE_CASES
+POLICY_CASES = MappingProxyType({**FORMAL_CASES, **PUBLIC_WEB_CASES, **PUBLIC_PY_CASES, **{
+ key: {'game': value['game'], 'dimension': value['dimension'], 'engine': 'native'}
+ for key, value in NATIVE_CASES.items()
+}})
+# Retired cases retain their IDs for replay compatibility and are omitted from the benchmark registry.
+BENCH_RETIRED = frozenset({
+ "3d/minecraft_zombie", # Minecraft had 7; its tier calibration is the separate 3d/minecraft_zombie_leader
+})
+BENCH_SCENES_PER_GAME = 6
+BENCH_CASES = MappingProxyType({k: v for k, v in POLICY_CASES.items() if k not in BENCH_RETIRED})
+# Every game, including Minecraft (Python), with its dimension; used by the media/scripted harness.
+GAMES = MappingProxyType({spec["game"]: spec["dimension"] for spec in POLICY_CASES.values()})
+FIRST_CASE = "kirby/whispy_woods"
+COLD_START_CASE = "2d/needle_warden"
+SCOPE_VERSION = "bossbench/formal-scope@1"
+
+
+def case_ids(*, dimension: str | None = None, game: str | None = None) -> tuple[str, ...]:
+ """Return stable, sorted formal IDs, optionally restricted by game or dimension."""
+ if dimension is not None and dimension not in ("2d", "3d"):
+ raise ValueError("dimension must be '2d' or '3d'")
+ if game is not None and game not in FORMAL_GAMES:
+ raise ValueError(f"unknown formal game: {game!r}")
+ return tuple(sorted(i for i, spec in FORMAL_CASES.items()
+ if (dimension is None or spec["dimension"] == dimension)
+ and (game is None or spec["game"] == game)))
+
+
+def validate_registry() -> None:
+ """Reject missing/misrouted formal cases without changing the legacy registry."""
+ from . import ENVS, WEB_GAME
+
+ for case_id, spec in {**FORMAL_CASES, **PUBLIC_WEB_CASES, **PUBLIC_PY_CASES}.items():
+ if ENVS.get(case_id) != spec["engine"]:
+ raise RuntimeError(f"formal case {case_id!r} has missing or incorrect engine registration")
+ if spec["engine"] == "web" and WEB_GAME.get(case_id) != spec["game"]:
+ raise RuntimeError(f"formal case {case_id!r} has incorrect game registration")
diff --git a/environments/games/prototype/bossbench/scripted.py b/environments/games/prototype/bossbench/scripted.py
new file mode 100644
index 0000000000000000000000000000000000000000..d60d408e399e92c2025f48b0a02896cd6bd49e31
--- /dev/null
+++ b/environments/games/prototype/bossbench/scripted.py
@@ -0,0 +1,355 @@
+"""Standard trusted scripted controller + frame capture for every BossBench case (all 12 games).
+
+One API over the three engine routes, used by web/tools/bench_media.py and any trusted collector:
+
+ env = bossbench.make_policy_env(case_id) # public RGB interface (or bossbench.make(...) symbolic)
+ ctrl = scripted.controller(env) # reads env.unwrapped; never handed to a policy
+ obs, info = env.reset(seed=1, options={"difficulty": 0.5, "engine_seed": 1})
+ cap = scripted.FrameCapture(env) # optional: frames of this same run at native-tick cadence
+ while True:
+ obs, reward, terminated, truncated, info = env.step(ctrl())
+ frames = cap.drain() # [(tick, jpeg bytes), ...] produced during that step
+ if terminated or truncated: break
+
+Game hooks (one per engine route):
+ * BB.Case web games BB.GAME.scripted(case) -> packet (bridge cmd "scripted", web/engine/case.js scriptedPacket)
+ * independent JS Module.scripted(game) -> {holds, mouse} (fallback Module.oracle)
+ * Minecraft (Python) bossbench.mc_scripted.scripted(case) -> packet text
+Every controller must be deterministic and must not change the simulation; both are checked here or in JS.
+
+HAZARD for any Python-route controller that plans on a deep copy of the live case (found 2026-11-01 in
+mc_scripted): FrameCapture below installs an *instance-level* `case.tick` wrapper, and `copy.deepcopy` copies
+instance attributes — so a naive clone carries that wrapper with it and the controller's lookahead then drives
+the real episode while still reporting a legal packet. Strip bound functions from the clone's own __dict__
+before simulating it, e.g.
+
+ clone = copy.deepcopy(case)
+ for name, value in list(vars(clone).items()):
+ if callable(value) and not isinstance(value, type):
+ del vars(clone)[name] # drop instance-level patches; class methods are unaffected
+
+The state-hash check around each controller call catches this only if the lookahead happens to change the
+hash before the call returns, so do not rely on it as the guard.
+"""
+from __future__ import annotations
+
+import base64
+import hashlib
+import io
+import json
+from pathlib import Path
+
+import numpy as np
+
+from . import keymouse as km
+
+ROOT = Path(__file__).resolve().parents[2]
+WEB = ROOT / 'web'
+REPLAY_FORMAT = 'bossbench/policy-replay@1'
+
+
+def route(env):
+ """'web' (BB.Case), 'native' (independent JS backend) or 'py' (Minecraft) for a make()/make_policy_env() env."""
+ raw = env.unwrapped
+ from .webenv import WebCaseEnv
+ from .engine_env import EngineEnv
+ from .unified import PyCaseEnv
+ if isinstance(raw, WebCaseEnv):
+ return 'web'
+ if isinstance(raw, EngineEnv):
+ if not hasattr(raw.backend, 'page'):
+ raise TypeError(f'{raw.case_id}: backend has no scripted controller hook')
+ return 'native'
+ if isinstance(raw, PyCaseEnv):
+ return 'py'
+ raise TypeError(f'unsupported env type {type(raw).__name__}')
+
+
+def _page(env):
+ raw = env.unwrapped
+ kind = route(env)
+ if kind == 'web':
+ if raw.transport != 'browser':
+ return None
+ return raw.t.page
+ if kind == 'native':
+ return raw.backend.page
+ return None
+
+
+def controller(env):
+ """Callable returning the next legal packet text for the env's current (live) state."""
+ raw = env.unwrapped
+ kind = route(env)
+ if kind == 'web':
+ def ask():
+ return raw._call({'cmd': 'scripted'})['packet']
+ elif kind == 'native':
+ def ask():
+ out = raw.backend.scripted()
+ return km.format_packet([tuple(h) for h in out['holds']], tuple(int(round(v)) for v in out['mouse']))
+ else:
+ from . import mc_scripted
+
+ def ask():
+ before = raw.state_hash() if raw.snap is not None else None
+ packet = mc_scripted.scripted(raw.case)
+ if before is not None and raw.state_hash() != before:
+ raise RuntimeError('scripted controller changed the simulation')
+ return packet if isinstance(packet, str) else km.to_packet(packet)
+
+ def next_packet():
+ packet = ask()
+ if km.parse_packet(packet) is None:
+ raise RuntimeError(f'{raw.case_id}: scripted controller returned an illegal packet: {packet!r}')
+ return packet
+ return next_packet
+
+
+def rules(env):
+ """Rule/version string the engine declares for this case (None if the game has none)."""
+ raw = env.unwrapped
+ kind = route(env)
+ if kind == 'web':
+ return raw._call({'cmd': 'meta'}).get('rules')
+ if kind == 'native':
+ return raw.engine_spec.rule_version
+ from . import mc4d
+ return getattr(mc4d, 'RULES', None)
+
+
+def state_hash(env):
+ """Engine-native final-state hash (BB.hashState / NativeBench.hash / sha1 of the Python state)."""
+ raw = env.unwrapped
+ kind = route(env)
+ if kind == 'web':
+ return raw._call({'cmd': 'hash'})['hash']
+ if kind == 'native':
+ return raw.backend.page.evaluate('() => NativeBench.hash(backendSession.state())')
+ return raw.state_hash()
+
+
+def game_of(env):
+ raw = env.unwrapped
+ from .scope import POLICY_CASES
+ return POLICY_CASES[raw.case_id]['game']
+
+
+def source_files(env):
+ """Files that define this case's rules and pictures (fingerprinted in media provenance)."""
+ raw = env.unwrapped
+ kind = route(env)
+ if kind == 'web':
+ from .webenv import game_scripts
+ files = [Path(p) for p in game_scripts(raw.game)]
+ files += [WEB / 'games' / raw.game / 'index.html', WEB / 'engine' / 'bridge.js']
+ elif kind == 'native':
+ from .native_games import source_paths
+ files = source_paths(raw.case_id)
+ else:
+ pkg = Path(__file__).resolve().parent
+ files = [pkg / name for name in ('mc4d.py', 'mcskin.py', 'rig.py', 'core.py', 'unified.py', 'mc_scripted.py')]
+ out = {}
+ for path in files:
+ if path.is_file():
+ out[path.resolve().relative_to(ROOT).as_posix()] = hashlib.sha256(path.read_bytes()).hexdigest()
+ return out
+
+
+_WEB_CAPTURE = r'''a => {
+ const env = BB.bridgeEnv(), c = env.case;
+ if (!BB.Renderer) throw Error('capture needs the browser renderer');
+ const canvas = document.createElement('canvas');
+ const cap = window.__bbCapture = {R: new BB.Renderer(canvas), every: a.every, quality: a.quality, frames: [], ticks: [], case: c};
+ cap.grab = () => {
+ const before = BB.hashState(c);
+ cap.R.draw(c, c.t / BB.FPS, '');
+ if (BB.hashState(c) !== before) throw Error('renderer changed the simulation');
+ cap.frames.push(cap.R.canvas.toDataURL('image/jpeg', cap.quality).split(',')[1]); cap.ticks.push(c.t);
+ };
+ if (!c.__bbCaptureWrapped) {
+ const tick = c.tick;
+ c.tick = function (keys, mouse) {
+ const t0 = this.t; tick.call(this, keys, mouse);
+ const k = window.__bbCapture;
+ if (k && k.case === this && this.t !== t0 && (this.t % k.every === 0 || this.result)) k.grab();
+ };
+ c.__bbCaptureWrapped = true;
+ }
+ cap.grab();
+ return {w: cap.R.canvas.width, h: cap.R.canvas.height, hz: BB.FPS};
+}'''
+
+_NATIVE_CAPTURE = r'''a => {
+ const s = backendSession, M = backendModule;
+ const canvas = document.createElement('canvas'); canvas.width = 854; canvas.height = 480;
+ const ctx = canvas.getContext('2d');
+ const cap = window.__bbCapture = {every: a.every, quality: a.quality, frames: [], ticks: [], session: s, ctx, canvas};
+ cap.grab = () => {
+ const before = NativeBench.hash(s.state());
+ M.draw(s.game, ctx);
+ if (NativeBench.hash(s.state()) !== before) throw Error('renderer changed the simulation');
+ cap.frames.push(canvas.toDataURL('image/jpeg', cap.quality).split(',')[1]); cap.ticks.push(s.game.t);
+ };
+ const tick = s.tick.bind(s);
+ s.tick = function (keys, mouse) {
+ const ok = tick(keys, mouse), k = window.__bbCapture;
+ if (ok && k && k.session === s && (s.game.t % k.every === 0 || s.game.outcome)) k.grab();
+ return ok;
+ };
+ cap.grab();
+ return {w: 854, h: 480, hz: M.hz};
+}'''
+
+_DRAIN = '''() => { const k = window.__bbCapture; if (!k) return {frames: [], ticks: []};
+ const out = {frames: k.frames, ticks: k.ticks}; k.frames = []; k.ticks = []; return out; }'''
+
+_CLOSE_NATIVE = '''() => { const k = window.__bbCapture; if (k && k.ctx && backendModule.closeRenderer) backendModule.closeRenderer(k.ctx);
+ window.__bbCapture = null; }'''
+
+
+class FrameCapture:
+ """Frames of the live episode every `every` native ticks (default: 30 fps at 60 Hz, every tick below 40 Hz).
+
+ Install right after reset; frames come from a private renderer/canvas reading the same simulation, so the
+ policy observation, gameplay RNG and physics are untouched. The terminal tick is always captured.
+ """
+
+ def __init__(self, env, every=None, quality=0.92):
+ self.env, self.kind, self.raw = env, route(env), env.unwrapped
+ fps = int(self.raw.fps)
+ self.every = int(every or (2 if fps >= 40 else 1))
+ self.fps = fps / self.every
+ self.quality = float(quality)
+ self._py_frames = []
+ if self.kind in ('web', 'native'):
+ page = _page(env)
+ if page is None:
+ raise RuntimeError('frame capture needs the browser transport (obs_mode="rgb")')
+ self.page = page
+ script = _WEB_CAPTURE if self.kind == 'web' else _NATIVE_CAPTURE
+ self.size = page.evaluate(script, {'every': self.every, 'quality': self.quality})
+ else:
+ case, inner, frames, every = self.raw.case, self.raw.inner, self._py_frames, self.every
+ tick = type(case).tick
+
+ def wrapped(action, _case=case):
+ t0 = _case.t
+ tick(_case, action)
+ if _case.t != t0 and (_case.t % every == 0 or _case.outcome()):
+ frames.append((_case.t, inner.render()))
+ case.tick = wrapped
+ self._unwrap = lambda: case.__dict__.pop('tick', None)
+ frames.append((case.t, inner.render()))
+ self.size = {'w': case.size[0], 'h': case.size[1], 'hz': fps}
+
+ def drain(self):
+ """-> [(tick, jpeg bytes)] captured since the last drain."""
+ if self.kind in ('web', 'native'):
+ got = self.page.evaluate(_DRAIN)
+ return [(t, base64.b64decode(f)) for t, f in zip(got['ticks'], got['frames'])]
+ from PIL import Image
+ out = []
+ for t, rgb in self._py_frames:
+ buffer = io.BytesIO()
+ Image.fromarray(np.ascontiguousarray(rgb)).save(buffer, 'JPEG', quality=int(self.quality * 100))
+ out.append((t, buffer.getvalue()))
+ self._py_frames.clear()
+ return out
+
+ def close(self):
+ try:
+ if self.kind == 'native':
+ self.page.evaluate(_CLOSE_NATIVE)
+ elif self.kind == 'web':
+ self.page.evaluate('() => { window.__bbCapture = null; }')
+ else:
+ self._unwrap()
+ except Exception:
+ pass
+
+
+def play(env, *, seed=1, options=None, max_steps=None, on_step=None, capture=None):
+ """Run the scripted controller to the terminal outcome on an existing env; returns a policy-replay dict.
+
+ options are forwarded to reset (difficulty, engine-specific keys); engine_seed defaults to seed so the replay
+ and the human play page share the same world. on_step(index, packet, info, frames) is called after each step.
+ """
+ options = dict(options or {})
+ if 'tier' not in options:
+ options.setdefault('difficulty', 0.5)
+ options.setdefault('engine_seed', int(seed))
+ obs, info = env.reset(seed=int(seed), options=options)
+ # A replay must pin what was actually played. A `tier` is resolved by the game's declaration at reset
+ # time; store the concrete difficulty it produced (plus the tier name as provenance), so the recording
+ # still reproduces exactly if that game later recalibrates its tiers.
+ if 'tier' in options:
+ tier = options.pop('tier')
+ options['difficulty'] = float(info['difficulty'])
+ options['resolved_from_tier'] = tier
+ cap = FrameCapture(env, **capture) if capture is not None else None
+ if cap is not None and on_step is not None:
+ on_step(-1, None, info, cap.drain())
+ ctrl = controller(env)
+ raw = env.unwrapped
+ packets, terminated, truncated = [], False, False
+ limit = max_steps or int(raw.max_seconds / km.PACKET_SECONDS) + 2
+ try:
+ for index in range(limit):
+ packet = ctrl()
+ obs, reward, terminated, truncated, info = env.step(packet)
+ packets.append(packet)
+ if on_step is not None:
+ on_step(index, packet, info, cap.drain() if cap is not None else [])
+ if terminated or truncated:
+ break
+ finally:
+ if cap is not None:
+ cap.close()
+ verifier = raw.verifier()
+ ticks = int(round(raw.snap['t'] * raw.fps))
+ return {
+ 'format': REPLAY_FORMAT, 'case_id': raw.case_id, 'game': game_of(env), 'contract': 'bossbench/policy-gym@2',
+ 'rules': rules(env), 'native_hz': raw.fps, 'gym_seed': int(seed), 'engine_seed': int(raw.engine_seed),
+ 'options': options, 'controller': 'scripted (standard trusted reference controller; privileged state; not a model)',
+ 'packets': packets, 'steps': len(packets), 'ticks': ticks, 'seconds': round(ticks / raw.fps, 4),
+ 'outcome': verifier['outcome'], 'terminated': bool(terminated), 'truncated': bool(truncated),
+ 'verifier': verifier, 'final_hash': state_hash(env), 'source_sha256': source_files(env),
+ }
+
+
+def replay(env, data):
+ """Re-run a policy-replay through env; returns (outcome, final_hash, ticks, problems)."""
+ problems = []
+ raw = env.unwrapped
+ if data.get('format') != REPLAY_FORMAT:
+ problems.append('not a bossbench/policy-replay@1 file')
+ if data.get('case_id') != raw.case_id:
+ problems.append(f"case mismatch: {data.get('case_id')} vs {raw.case_id}")
+ current = rules(env)
+ if data.get('rules') != current:
+ problems.append(f"rules mismatch: recording {data.get('rules')!r}, engine {current!r}")
+ env.reset(seed=int(data['gym_seed']), options=dict(data['options']))
+ done = False
+ for index, packet in enumerate(data['packets']):
+ if done:
+ problems.append(f'packet {index} after terminal outcome')
+ break
+ _, _, terminated, truncated, _ = env.step(packet)
+ done = terminated or truncated
+ if not done:
+ problems.append('recording ended before a terminal outcome')
+ outcome = raw.verifier()['outcome']
+ final = state_hash(env)
+ ticks = int(round(raw.snap['t'] * raw.fps))
+ if outcome != data.get('outcome'):
+ problems.append(f"outcome mismatch: {outcome} vs {data.get('outcome')}")
+ if final != data.get('final_hash'):
+ problems.append(f"final hash mismatch: {final} vs {data.get('final_hash')}")
+ if ticks != data.get('ticks'):
+ problems.append(f"tick mismatch: {ticks} vs {data.get('ticks')}")
+ return outcome, final, ticks, problems
+
+
+def dumps(data):
+ return json.dumps(data, ensure_ascii=False, indent=1) + '\n'
diff --git a/environments/games/prototype/bossbench/step_reward.py b/environments/games/prototype/bossbench/step_reward.py
new file mode 100644
index 0000000000000000000000000000000000000000..24aecbb6ad69aa209e9c706738fc28ff5ce5b1b5
--- /dev/null
+++ b/environments/games/prototype/bossbench/step_reward.py
@@ -0,0 +1,105 @@
+"""Damage/progress-only rewards per Gym step, shared by every registered game.
+
+The engine's aggregate objective HP/progress is trusted scoring data. It is never
+added to the image observation or the model prompt.
+"""
+from __future__ import annotations
+
+import math
+import gymnasium as gym
+
+REWARD_CONTRACT = 'bossbench/step-damage@1'
+
+
+def objective_progress(snapshot):
+ """Use the existing aggregate objective, including all phases/required parts."""
+ if not isinstance(snapshot, dict):
+ raise RuntimeError('reward requires a valid current engine snapshot')
+ hp, maximum = float(snapshot['boss_hp']), float(snapshot['boss_max_hp'])
+ if not math.isfinite(hp) or not math.isfinite(maximum) or maximum <= 0 or not 0 <= hp <= maximum:
+ raise RuntimeError('invalid aggregate objective HP/progress')
+ return 1.0 - hp / maximum
+
+
+class StepDamageReward(gym.Wrapper):
+ """Replace sparse/dense return with the signed increment of objective progress.
+
+ A hit gives positive reward; a heal or objective regression gives negative
+ reward. No clipping, player-health penalty, step cost or terminal bonus is
+ added. Delay windows belong to the same step. Across a complete episode,
+ sum(reward) = final progress - reset progress.
+ """
+ def __init__(self, env):
+ super().__init__(env)
+ self.metadata = dict(env.metadata, reward_contract=REWARD_CONTRACT)
+ self._reward_previous = None
+ self._reward_total = 0.0
+ self._reward_steps = 0
+ self._reward_closed = False
+ self._reward_done = True
+
+ def reset(self, *, seed=None, options=None):
+ if self._reward_closed:
+ raise RuntimeError('environment is closed')
+ obs, info = self.env.reset(seed=seed, options=options)
+ self._reward_previous = objective_progress(self.unwrapped.snap)
+ self._reward_total = 0.0
+ self._reward_steps = 0
+ self._reward_done = False
+ return obs, dict(info, reward_contract=REWARD_CONTRACT)
+
+ def step(self, action, latency=None):
+ if self._reward_closed or self._reward_done or self._reward_previous is None:
+ raise RuntimeError('reset required before step')
+ try:
+ obs, _, terminated, truncated, info = self.env.step(action, latency=latency)
+ current = objective_progress(self.unwrapped.snap)
+ except BaseException:
+ self._reward_done = True
+ raise
+ reward = current - self._reward_previous
+ self._reward_previous = current
+ self._reward_total += reward
+ self._reward_steps += 1
+ self._reward_done = bool(terminated or truncated)
+ return obs, float(reward), terminated, truncated, dict(info, reward_contract=REWARD_CONTRACT)
+
+ def reward_diagnostics(self):
+ """Collector-only summary, not part of the visual observation."""
+ return dict(contract=REWARD_CONTRACT, episode_return=self._reward_total,
+ steps=self._reward_steps, done=self._reward_done)
+
+ def close(self):
+ if not self._reward_closed:
+ try:
+ self.env.close()
+ finally:
+ self._reward_closed = self._reward_done = True
+
+
+def make_training_env(case_id, *, action_format='keymouse', **kwargs):
+ """Public RGB environment; new calls default to versioned high-water progress.
+
+ action_format='compact' selects the game's declared MultiDiscrete interface.
+ All reset options, engine clocks, terminal flags and replay rules are kept.
+ The raw engine remains sparse internally; this wrapper replaces that scalar.
+ Explicit 'boss_damage' or 'bossbench/step-damage@1' retains legacy signed
+ delta behavior. New releases use 'bossbench/step-progress-highwater@1'.
+ """
+ from .progress_reward import StepProgressReward, REWARD_CONTRACT as HIGHWATER
+ mode = kwargs.pop('reward_mode', HIGHWATER)
+ if mode not in ('boss_damage', REWARD_CONTRACT, HIGHWATER):
+ raise ValueError('unknown versioned training reward')
+ if action_format == 'keymouse':
+ from .policy_env import make_policy_env
+ env = make_policy_env(case_id, **kwargs)
+ elif action_format == 'compact':
+ from .compact import make_compact_env
+ env = make_compact_env(case_id, **kwargs)
+ else:
+ raise ValueError('action_format must be keymouse or compact')
+ try:
+ return StepDamageReward(env) if mode in ('boss_damage', REWARD_CONTRACT) else StepProgressReward(env, case_id)
+ except BaseException:
+ env.close()
+ raise
diff --git a/environments/games/prototype/bossbench/tiers.py b/environments/games/prototype/bossbench/tiers.py
new file mode 100644
index 0000000000000000000000000000000000000000..800a6042c91ad5fb06a69a2195c9a7a91ecca7d1
--- /dev/null
+++ b/environments/games/prototype/bossbench/tiers.py
@@ -0,0 +1,97 @@
+"""Three public difficulty tiers shared by every BossBench game.
+
+The standard interface takes one of three named tiers. Use continuous difficulty for finer control.
+
+ env.reset(seed=1, options={"tier": "easy"}) # public: one of three tiers
+ env.reset(seed=1, options={"difficulty": 0.37}) # still allowed: direct continuous control
+
+Each game declares its own tier -> difficulty mapping next to its rule version, so the simulation, the play
+page and this public interface all read one source of truth:
+
+ BB.Case games BB.GAME.tiers = {easy: 0.15, normal: 0.5, hard: 0.85} (game.js)
+ native JS games Module.tiers = {easy: ..., normal: ..., hard: ...} (game.js)
+ Minecraft mc4d.TIERS = {"easy": ..., "normal": ..., "hard": ...}
+
+A game that declares nothing uses DEFAULT_TIERS. Passing both `tier` and `difficulty` is rejected, so a
+recording can never be ambiguous about which one produced it.
+
+"""
+from __future__ import annotations
+
+import math
+from numbers import Real
+from types import MappingProxyType
+
+TIER_NAMES = ("easy", "normal", "hard")
+
+DEFAULT_TIERS = MappingProxyType({"easy": 0.2, "normal": 0.5, "hard": 0.8})
+TIERS = DEFAULT_TIERS # backwards-compatible name
+
+# Reference-controller completion windows in seconds.
+TARGET_SECONDS = MappingProxyType({
+ "easy": (20.0, 30.0),
+ "normal": (45.0, 90.0),
+ "hard": (150.0, 240.0),
+})
+
+
+def validate_declared(declared, where="game"):
+ """Return a clean {tier: difficulty} from a game's declaration, or raise with a precise reason.
+
+ A declaration must name exactly easy/normal/hard, each a finite number in [0, 1], strictly increasing
+ from easy to hard. A broken declaration fails when the env is created, inside the game that wrote it.
+ """
+ if declared is None:
+ return None
+ if not isinstance(declared, dict):
+ raise ValueError(f"{where}: tiers must be an object with keys {TIER_NAMES}")
+ if set(declared) != set(TIER_NAMES):
+ raise ValueError(f"{where}: tiers must declare exactly {TIER_NAMES}, got {sorted(declared)}")
+ clean = {}
+ for name in TIER_NAMES:
+ value = declared[name]
+ if isinstance(value, bool) or not isinstance(value, Real) or not math.isfinite(value) or not 0 <= value <= 1:
+ raise ValueError(f"{where}: tier {name!r} must be a finite number in [0, 1], got {value!r}")
+ clean[name] = float(value)
+ if not clean["easy"] < clean["normal"] < clean["hard"]:
+ raise ValueError(f"{where}: tiers must increase strictly easy < normal < hard, got {clean}")
+ return clean
+
+
+def difficulty_for(tier, declared=None):
+ """Continuous difficulty for a public tier, using the game's own declaration when it has one."""
+ if tier not in TIER_NAMES:
+ raise ValueError(f"tier must be one of {TIER_NAMES}, got {tier!r}")
+ table = declared if declared else DEFAULT_TIERS
+ return float(table[tier])
+
+
+def resolve_options(options, declared=None):
+ """Replace a public `tier` with the concrete `difficulty` the engines already understand.
+
+ Returns a new dict; the original is not modified. `tier` and `difficulty` are mutually exclusive so a
+ replay's options always say exactly one thing about how hard the fight was.
+ """
+ if not options or "tier" not in options:
+ return dict(options or {})
+ resolved = dict(options)
+ tier = resolved.pop("tier")
+ if "difficulty" in resolved:
+ raise ValueError("pass either tier or difficulty, not both: a recording must be unambiguous")
+ resolved["difficulty"] = difficulty_for(tier, declared)
+ resolved["resolved_from_tier"] = tier # provenance: which tier the caller asked for
+ return resolved
+
+
+def tier_of(difficulty, declared=None, tolerance=1e-9):
+ """The tier that maps to this difficulty, or None when it is a custom continuous value."""
+ for tier in TIER_NAMES:
+ if abs(difficulty_for(tier, declared) - float(difficulty)) <= tolerance:
+ return tier
+ return None
+
+
+def within_target(tier, seconds):
+ """True when a scripted run's duration falls inside the reference-controller window for that tier."""
+ low, high = TARGET_SECONDS[tier]
+ return low <= float(seconds) <= high
diff --git a/environments/games/prototype/bossbench/unified.py b/environments/games/prototype/bossbench/unified.py
new file mode 100644
index 0000000000000000000000000000000000000000..ed8c63abbaf1b6f89ab28302dd262878cd9be162
--- /dev/null
+++ b/environments/games/prototype/bossbench/unified.py
@@ -0,0 +1,488 @@
+"""One Gymnasium interface for every BossBench case, whatever engine runs it (proposal 4.4).
+
+ import bossbench
+ env = bossbench.make("2d/needle_warden", # web engine (JS, 60 Hz)
+ obs_mode="symbolic", # "rgb" | "symbolic" | "vector"
+ time_mode="virtual_rt", # "paused" | "virtual_rt" | "wallclock_rt"
+ latency=0.3)
+ env = bossbench.make("3d/minecraft_wither") # Python engine (60 Hz) - same API
+ obs, info = env.reset(seed=0, options={"difficulty": 0.5})
+ obs, reward, terminated, truncated, info = env.step(
+ "<|action_start|> 120 0 0 ; W ; W ; W,Space ; W ; LMB ; LMB <|action_end|>")
+
+What is identical across cases (and is all an agent or trainer needs to know):
+ step one 200 ms key/mouse packet (keymouse.py): str, or a dict from env.action_space
+ action_space keymouse.KeyMouse() (mouse dx dy dz + 6 x 14 hold matrix); the key *meaning* is per
+ body and is spelled out in info["manual"]["controls"]
+ obs rgb: 480 x 854 x 3 uint8 | symbolic: the case's state dict | vector: float32 Box
+ time paused: the world waits; virtual_rt: ceil(latency / 0.2) no-op packets run first;
+ wallclock_rt: floor(wall time since the last return / 0.2) no-op packets run first
+ reward sparse: verifier reward at the end only; dense: + d(boss damage) - d(player damage)
+ info t, state, events, outcome, player_hp, player_max_hp, boss_hp, boss_max_hp, format_ok,
+ format_errors, steps, frames, lag_packets, difficulty, engine_seed
+ (+ manual at reset, verifier on the last step)
+ verifier() {reward in [-1, 1], win, outcome, boss_damage, seconds, d, player_hp}
+ end win / loss -> terminated; time cap -> truncated; stepping a finished episode raises
+
+info["state"] is always filled so oracles and loggers can read it; an rgb-only agent harness must not
+pass it to the agent (that is the perception-gap ablation's job, not the env's).
+
+action_mode="native" (Python engine only) keeps the body's own action space (e.g. MultiDiscrete for
+Steve) for RL ablations; one step is still one 200 ms packet with that action held throughout.
+"""
+from __future__ import annotations
+
+import hashlib
+import copy
+from collections.abc import Mapping
+import json
+import math
+from numbers import Integral, Real
+import time
+
+import gymnasium as gym
+import numpy as np
+
+from . import keymouse as km
+from .core import RES
+from .engine_contract import EngineSpec, RenderStatus
+
+OBS_MODES = ("rgb", "symbolic", "vector")
+TIME_MODES = ("paused", "virtual_rt", "wallclock_rt")
+PROTOCOL = ("one step = one 200 ms packet: <|action_start|> dx dy dz ; K1 ; K2 ; K3 ; K4 ; K5 ; K6 <|action_end|>; "
+ "K_j = 0-4 keys from W A S D Space Shift J K L Q E R LMB RMB held during the j-th 33 1/3 ms sub-step (2 ticks at 60 Hz), "
+ "comma separated; dx dy in [-1000, 1000] mouse motion, dz in [-5, 5] wheel; "
+ "a malformed packet runs as no-op and counts as a format error")
+
+
+class Json(gym.Space):
+ """Observation space of obs_mode='symbolic': a JSON-serialisable dict (the case's state())."""
+
+ def __init__(self, seed=None):
+ super().__init__(None, None, seed)
+
+ def contains(self, x) -> bool:
+ return isinstance(x, dict)
+
+ def sample(self, mask=None, probability=None):
+ return {}
+
+ def __repr__(self):
+ return "Json()"
+
+ def __eq__(self, other):
+ return isinstance(other, Json)
+
+
+def event_names(events):
+ return [e[0] if isinstance(e, (tuple, list)) else e for e in events]
+
+
+def _plain(o):
+ if isinstance(o, np.generic):
+ return o.item()
+ if isinstance(o, np.ndarray):
+ return o.tolist()
+ raise TypeError(type(o))
+
+
+def _finite_number(value, name, *, upper=None):
+ if isinstance(value, (bool, np.bool_)) or not isinstance(value, Real):
+ raise ValueError(f"{name} must be a finite number >= 0" + (f" and <= {upper}" if upper is not None else ""))
+ value = float(value)
+ if not math.isfinite(value) or value < 0 or (upper is not None and value > upper):
+ raise ValueError(f"{name} must be a finite number >= 0" + (f" and <= {upper}" if upper is not None else ""))
+ return value
+
+
+def _clean_band(value, where):
+ """Validate a game's difficulty_band declaration: a short plain name, or None for 'no segmentation'."""
+ if value is None:
+ return None
+ if not isinstance(value, str) or not value.strip() or len(value) > 40 or '\n' in value:
+ raise ValueError(f"{where}: difficulty_band must return a short non-empty string or None, "
+ f"got {value!r}")
+ return value.strip()
+
+
+def _reset_options(options):
+ if options is not None and not isinstance(options, Mapping):
+ raise ValueError("reset options must be a mapping")
+ return copy.deepcopy(dict(options or {}))
+
+
+class UnifiedEnv(gym.Env):
+ """Engine-independent half: action decoding, time modes, reward, info/verifier schema.
+
+ An engine adapter implements _engine_reset(seed, d, options) and _engine_packet(packet, lag, ok), both returning a
+ snapshot dict {state, events, outcome (None | win | loss | timeout), t, frames, player_hp, player_max_hp,
+ boss_hp, boss_max_hp}, plus _render / _vector / _manual, and sets fps and max_seconds.
+ """
+ metadata = {"render_modes": ["rgb_array"], "render_fps": round(1 / km.PACKET_SECONDS)}
+
+ def __init__(self, case_id, obs_mode="symbolic", action_mode="keymouse", time_mode="paused", latency=0.0,
+ difficulty=0.5, reward_mode="sparse", render_mode=None):
+ for name, value, choices in (("obs_mode", obs_mode, OBS_MODES), ("time_mode", time_mode, TIME_MODES),
+ ("action_mode", action_mode, ("keymouse", "native")),
+ ("reward_mode", reward_mode, ("sparse", "dense")),
+ ("render_mode", render_mode, (None, "rgb_array"))):
+ if value not in choices:
+ raise ValueError(f"{name} must be one of {choices}")
+ self.case_id, self.obs_mode, self.action_mode, self.time_mode = case_id, obs_mode, action_mode, time_mode
+ self.latency = self._default_latency = _finite_number(latency, "latency")
+ self.difficulty = _finite_number(difficulty, "difficulty", upper=1)
+ self.reward_mode = reward_mode
+ self.render_mode = render_mode
+ self.action_space = km.KeyMouse()
+ self.snap, self.done, self.d, self.engine_seed = None, True, self.difficulty, None
+ self._closed = False
+
+ def _obs_space(self, vector_space=None):
+ if self.obs_mode == "rgb":
+ return gym.spaces.Box(0, 255, (RES[1], RES[0], 3), np.uint8)
+ if self.obs_mode == "vector":
+ if vector_space is None:
+ raise ValueError(f"{self.case_id}: obs_mode='vector' is not available for this engine")
+ return vector_space
+ return Json()
+
+ @property
+ def engine_spec(self):
+ """Default for the existing web engine; independent backends override it."""
+ return EngineSpec('web-canvas', '2d', 60, self.max_seconds, 'canvas', 'raster')
+
+ def render_status(self):
+ return RenderStatus(self.engine_spec.renderer, self.engine_spec.render_kind, True)
+
+ # -- gym API -------------------------------------------------------------
+ def reset(self, *, seed=None, options=None):
+ """Reset using Gym's seed, or an explicit uint32 engine_seed for imported replays.
+
+ Ordinary seed handling is unchanged. options are forwarded to the web
+ game so its initial world settings match browser play.
+ """
+ self._ensure_open()
+ options = _reset_options(options)
+ # A public `tier` (easy/normal/hard) resolves to the continuous difficulty the engines understand,
+ # using the game's own declared mapping (see tiers.py), so the play page and this interface agree.
+ from .tiers import resolve_options
+ options = resolve_options(options, self._declared_tiers())
+ d = _finite_number(options.get("difficulty", self.difficulty), "difficulty", upper=1)
+ latency = _finite_number(options.get("latency", self._default_latency), "latency")
+ options["difficulty"] = d
+ if "latency" in options:
+ options["latency"] = latency
+ if seed is not None:
+ if isinstance(seed, (bool, np.bool_)) or not isinstance(seed, Integral) or seed < 0:
+ raise ValueError("seed must be a nonnegative integer or None")
+ seed = int(seed)
+ if "engine_seed" in options:
+ explicit_seed = options["engine_seed"]
+ if isinstance(explicit_seed, (bool, np.bool_)) or not isinstance(explicit_seed, Integral) or not 0 <= explicit_seed < 2 ** 32:
+ raise ValueError("engine_seed must be an integer in [0, 2**32)")
+ options["engine_seed"] = int(explicit_seed)
+ self._validate_options(options)
+ # Invalid reset conditions must not consume RNG or alter a live episode.
+ super().reset(seed=seed)
+ self.engine_seed = options.get("engine_seed", None)
+ if self.engine_seed is None:
+ self.engine_seed = int(self.np_random.integers(2 ** 31 - 1))
+ self.latency = latency
+ self.d, self.steps, self.format_errors, self.done = d, 0, 0, False
+ try:
+ self.snap = self._engine_reset(self.engine_seed, d, options)
+ except Exception:
+ self.snap, self.done = None, True
+ raise
+ self._prev = self._progress(self.snap)
+ info = self._info(True, 0)
+ info["manual"] = self.manual()
+ obs = self._observe()
+ self._t_return = time.perf_counter()
+ return obs, info
+
+ def step(self, action, latency=None):
+ """latency (s, virtual_rt only) overrides env.latency for this step: the agent's measured think time."""
+ self._ensure_reset()
+ if self.done:
+ raise RuntimeError("episode is over; call reset()")
+ latency = self.latency if latency is None else _finite_number(latency, "latency")
+ if self.time_mode == "virtual_rt":
+ # Bound work at the episode deadline, including huge but finite latency.
+ remaining = max(0, math.ceil(self.max_seconds / km.PACKET_SECONDS))
+ lag = remaining if latency >= self.max_seconds else math.ceil(latency / km.PACKET_SECONDS - 1e-9)
+ elif self.time_mode == "wallclock_rt":
+ lag = max(0, int((time.perf_counter() - self._t_return) / km.PACKET_SECONDS))
+ else:
+ lag = 0
+ if self.action_mode == "native":
+ packet, ok = action, True
+ else:
+ packet = km.to_packet(action)
+ ok = km.parse_packet(packet) is not None
+ if not ok:
+ self.format_errors += 1
+ self.snap = self._engine_packet(packet, lag, ok)
+ self.steps += 1
+ out = self.snap["outcome"]
+ terminated, truncated = out in ("win", "loss"), out == "timeout"
+ prog, reward = self._progress(self.snap), 0.0
+ if self.reward_mode == "dense":
+ reward += (prog[0] - self._prev[0]) - (prog[1] - self._prev[1])
+ self._prev = prog
+ info = self._info(ok, lag)
+ if terminated or truncated:
+ self.done = True
+ info["verifier"] = self.verifier()
+ reward += info["verifier"]["reward"]
+ obs = self._observe()
+ self._t_return = time.perf_counter()
+ return obs, float(reward), terminated, truncated, info
+
+ def render(self):
+ self._ensure_reset()
+ img = self._render()
+ if not isinstance(img, np.ndarray) or img.shape != (RES[1], RES[0], 3) or img.dtype != np.uint8:
+ raise RuntimeError(f"render must be RGB uint8 with shape {(RES[1], RES[0], 3)}")
+ return img
+
+ def verifier(self) -> dict:
+ self._ensure_reset()
+ s = self.snap
+ frac = 1 - max(s["boss_hp"], 0) / s["boss_max_hp"]
+ win = s["outcome"] == "win"
+ return {"reward": 1.0 if win else round(-1.0 + frac, 4), "win": win, "outcome": s["outcome"],
+ "boss_damage": round(frac, 4), "seconds": round(s["t"], 4), "d": self.d,
+ "player_hp": s["player_hp"]}
+
+ def manual(self) -> dict:
+ """Prompt context (proposal 4.4): packet protocol, this body's key meanings, this boss's skill table."""
+ self._ensure_open()
+ m = self._manual()
+ protocol = PROTOCOL
+ if getattr(self, 'fps', 60) != 60:
+ protocol = PROTOCOL.replace('(2 ticks at 60 Hz)',
+ f'(input sampled on native {self.fps} Hz ticks; actual executed time is reported)')
+ return {"protocol": protocol, "controls": list(m["controls"]), "skills": list(m.get("skills", []))}
+
+ def state_hash(self) -> str:
+ """sha1 of the symbolic state, for determinism checks across runs and transports."""
+ self._ensure_reset()
+ return hashlib.sha1(json.dumps(self.snap["state"], sort_keys=True, default=_plain).encode()).hexdigest()
+
+ def _ensure_open(self):
+ if self._closed:
+ raise RuntimeError("environment is closed; create a new environment")
+
+ def _ensure_reset(self):
+ self._ensure_open()
+ if self.snap is None:
+ raise RuntimeError("environment has not been reset; call reset()")
+
+ def _validate_options(self, options):
+ try:
+ json.dumps(options, allow_nan=False, default=_plain)
+ except (TypeError, ValueError) as ex:
+ raise ValueError("reset options must be finite JSON data") from ex
+
+ def close(self):
+ self._closed, self.done = True, True
+
+ # -- shared helpers ----------------------------------------------------------
+ def _progress(self, s):
+ return (1 - max(s["boss_hp"], 0) / s["boss_max_hp"], 1 - max(s["player_hp"], 0) / s["player_max_hp"])
+
+ def _info(self, ok, lag):
+ s = self.snap
+ info = {"t": round(s["t"], 4), "state": s["state"], "events": event_names(s["events"]),
+ "outcome": s["outcome"], "player_hp": s["player_hp"], "player_max_hp": s["player_max_hp"],
+ "boss_hp": s["boss_hp"], "boss_max_hp": s["boss_max_hp"], "format_ok": ok,
+ "format_errors": self.format_errors, "steps": self.steps, "frames": s["frames"],
+ "lag_packets": lag, "difficulty": self.d, "engine_seed": self.engine_seed}
+ band = self._difficulty_band(self.d)
+ if band is not None:
+ info["difficulty_band"] = band
+ return info
+
+ def _observe(self):
+ if self.obs_mode == "rgb":
+ return self.render()
+ if self.obs_mode == "vector":
+ return self._vector()
+ return self.snap["state"]
+
+ # -- engine adapter --------------------------------------------------------
+ def _declared_tiers(self):
+ """The game's own {easy, normal, hard} -> difficulty mapping, or None to use tiers.DEFAULT_TIERS."""
+ return None
+
+ def _difficulty_band(self, d):
+ """The game's own name for the segment `d` falls in, or None if it declares no segmentation.
+
+ 2026-11-03, requested by the Cuphead session. Several games map the continuous difficulty onto the
+ original's own modes (Cuphead Simple/Regular/Expert at 0.25 and 0.75, DOOM's skill levels, Terraria's
+ Classic/Expert gate at 0.75). Behaviour therefore steps at those boundaries: Cuphead measured the
+ scripted controller's median duration jumping +8%..+24% across d=0.25, and hits taken rising (Cagney
+ 0.13 -> 1.13) across d=0.75. Anyone sweeping d to find d* sees a discontinuous curve, and until now
+ had to re-derive the boundaries from the game's own source to know why.
+
+ This leaks nothing: the band is a pure function of `difficulty`, which the public info already
+ carries. It is a label on a number the policy can already see — not live state.
+ """
+ return None
+
+ def _engine_reset(self, seed, d, options=None):
+ raise NotImplementedError
+
+ def _engine_packet(self, packet, lag, ok):
+ raise NotImplementedError
+
+ def _render(self):
+ raise NotImplementedError
+
+ def _vector(self):
+ raise NotImplementedError
+
+ def _manual(self):
+ raise NotImplementedError
+
+
+class PyCaseEnv(UnifiedEnv):
+ """Adapter for the existing Python Case engine: the Case ticks at its own FPS (60 Hz -> 12 ticks per
+ packet, 2 per sub-step) and the body's keys() maps each tick's held keys onto its native action."""
+
+ def __init__(self, case_id, factory, case_kw=None, **kw):
+ super().__init__(case_id, **kw)
+ self.inner = factory(difficulty=self.difficulty, **(case_kw or {})) # BossBenchEnv: owns case + renderer
+ self.case = self.inner.case
+ self.fps = self.inner.metadata["render_fps"]
+ self.ticks = round(self.fps * km.PACKET_SECONDS)
+ self.max_ticks = self.inner.max_ticks
+ self.max_seconds = self.max_ticks / self.fps
+ if self.action_mode == "native":
+ self.action_space = self.case.body.action_space
+ self.observation_space = self._obs_space(self.case.observation_space)
+
+ @property
+ def engine_spec(self):
+ return EngineSpec('minecraft-python', '3d', 60, self.max_seconds, 'moderngl', 'perspective',
+ resolution=tuple(self.case.size))
+
+ def render_status(self):
+ error = getattr(self.case, 'render_error', None)
+ ready = getattr(self.case, '_gl', None) is not None and error is None
+ return RenderStatus('moderngl', 'perspective' if ready else 'raster', ready, error)
+
+ def _validate_options(self, options):
+ super()._validate_options(options)
+ # Minecraft loadout/camera are public experiment conditions, passed
+ # through the same Gym reset contract as the web games' options.
+ # Validate before UnifiedEnv changes the live episode or RNG state.
+ if self.case_id.startswith("3d/minecraft_"):
+ for key, choices in (("weapon", ("sword", "bow")),
+ ("camera", ("first", "third"))):
+ if key in options and options[key] not in choices:
+ raise ValueError(f"Minecraft {key} must be one of {choices}")
+
+ def reset(self, *, seed=None, options=None):
+ obs, info = super().reset(seed=seed, options=options)
+ return obs, self._visual_info(info)
+
+ def step(self, action, latency=None):
+ obs, reward, terminated, truncated, info = super().step(action, latency)
+ return obs, reward, terminated, truncated, self._visual_info(info)
+
+ def _visual_info(self, info):
+ # UnifiedEnv builds info before rendering. Inspect the renderer only
+ # after _observe returned so a fallback cannot masquerade as 3D RGB.
+ if self.case_id.startswith("3d/minecraft_"):
+ info = dict(info)
+ info.update(camera=self.case.camera,
+ weapon=getattr(self.case.body, "weapon", "sword"))
+ if self.obs_mode == "rgb":
+ error = getattr(self.case, "render_error", None)
+ renderer = getattr(self.case, "_gl", None)
+ info["render_error"] = error
+ info["renderer"] = "moderngl" if renderer is not None and error is None else "topdown"
+ if info["renderer"] == "moderngl":
+ info["render_backend"] = renderer.ctx.info.get("GL_RENDERER")
+ return info
+
+ def _snapshot(self, frames):
+ c = self.case
+ out = c.outcome() or ("timeout" if c.t >= self.max_ticks else None)
+ return {"state": c.state(), "events": list(c.events), "outcome": out, "t": c.t / self.fps,
+ "player_hp": round(max(float(c.body.hp), 0.0), 4), "player_max_hp": float(c.body.max_hp),
+ "boss_hp": round(max(float(c.boss.hp), 0.0), 4), "boss_max_hp": float(c.boss.max_hp), "frames": frames}
+
+ def _engine_reset(self, seed, d, options=None):
+ if self.case_id.startswith("3d/minecraft_"):
+ self.case.reset(seed, d, options=dict(options or {}))
+ else:
+ self.case.reset(seed, d)
+ self.inner._has_reset, self.inner._done = True, False
+ self._held = frozenset()
+ return self._snapshot(0)
+
+ def _tick_all(self, actions):
+ c, n = self.case, 0
+ for a in actions:
+ if c.outcome() or c.t >= self.max_ticks:
+ break
+ c.tick(a() if callable(a) else a) # keys() runs at tick time: it may read the current state
+ n += 1
+ return n
+
+ def _key_ticks(self, packet):
+ sched, self._held = km.schedule(packet, self.ticks, self._held)
+ body, c = self.case.body, self.case
+ return [lambda h=h, p=p, m=m: body.keys(c, h, p, m) for h, p, m in sched]
+
+ def _engine_packet(self, packet, lag, ok):
+ c, frames = self.case, 0
+ c.events.clear()
+ native = self.action_mode == "native"
+ for _ in range(lag): # the world did not wait
+ if c.outcome() or c.t >= self.max_ticks:
+ break
+ frames += self._tick_all([c.body.noop()] * self.ticks if native else self._key_ticks(None))
+ if c.outcome() or c.t >= self.max_ticks:
+ return self._snapshot(frames)
+ if native:
+ a = c.body.parse(packet) if isinstance(packet, str) else packet
+ frames += self._tick_all([a] * self.ticks)
+ else:
+ frames += self._tick_all(self._key_ticks(km.parse_packet(packet) if ok else None))
+ return self._snapshot(frames)
+
+ def _render(self):
+ return self.inner.render()
+
+ def _vector(self):
+ return self.case.observe()
+
+ def _manual(self):
+ skills = [{"move": n, "cue": m.get("cue") or m.get("telegraph"), "punish": m.get("punish"),
+ "damage": m.get("damage")} for n, m in self.case.boss.MOVES.items()]
+ return {"controls": self.case.body.manual, "skills": skills}
+
+ def _declared_tiers(self):
+ # The case's own module declares TIERS (e.g. mc4d.TIERS) next to its RULES constant.
+ import sys
+ from .tiers import validate_declared
+ module = sys.modules.get(type(self.case).__module__)
+ return validate_declared(getattr(module, "TIERS", None), where=self.case_id)
+
+ def _difficulty_band(self, d):
+ # Optional, same pattern as TIERS: the case's module may declare difficulty_band(d) -> str.
+ import sys
+ module = sys.modules.get(type(self.case).__module__)
+ fn = getattr(module, "difficulty_band", None)
+ return _clean_band(fn(d), self.case_id) if callable(fn) else None
+
+ def close(self):
+ if not self._closed:
+ try:
+ self.inner.close()
+ finally:
+ super().close()
diff --git a/environments/games/prototype/bossbench/webenv.py b/environments/games/prototype/bossbench/webenv.py
new file mode 100644
index 0000000000000000000000000000000000000000..53369d7934bd7d37d05563207d2ad55eb634723b
--- /dev/null
+++ b/environments/games/prototype/bossbench/webenv.py
@@ -0,0 +1,260 @@
+"""Gymnasium binding for the web engine (web/engine + web/games//, 60 Hz): the Hollow-Knight-style 2D cases.
+
+The simulation stays in JavaScript (one source of truth for the browser game, the Node tests and
+training). Each case belongs to one game folder (bossbench.WEB_GAME), whose index.html fixes the script order.
+This module drives it through web/engine/bridge.js over one of two transports:
+
+ node `node web/tools/gym_server.js `, JSON lines on stdin/stdout. symbolic only, fast, no browser.
+ browser a headless Chromium page (Playwright) with the game's scripts + renderer loaded; needed for obs_mode="rgb".
+ BB_CHANNEL=msedge|chrome picks an installed browser instead of Playwright's own build.
+
+transport="auto" picks browser for rgb and node otherwise. Both transports load the same game rules.
+"""
+from __future__ import annotations
+
+import atexit
+import base64
+import json
+import os
+import re
+import shutil
+import subprocess
+
+import numpy as np
+
+from .unified import UnifiedEnv, _finite_number, _plain
+
+WEB = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "web")
+NO_PAGE = ("engine/input.js", "engine/app.js") # browser-app UI: needs the game's DOM, not part of the env
+
+DEFAULT_GAME = "hollowknight_remake"
+
+
+def game_of(case_id):
+ from . import WEB_GAME
+ if case_id not in WEB_GAME:
+ raise KeyError(f"no web game registers {case_id!r}; known: {sorted(WEB_GAME)}")
+ return WEB_GAME[case_id]
+
+
+def game_scripts(game):
+ """Absolute paths of web/games//index.html's scripts in page order, minus the browser-app layer."""
+ gdir = os.path.join(WEB, "games", game)
+ with open(os.path.join(gdir, "index.html"), encoding="utf-8") as source:
+ html = source.read()
+ out = [os.path.normpath(os.path.join(gdir, s)) for s in re.findall(r'
+