Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(verse): add the hangar arena, deathmatch rules and day/arena switch (#1145)
Ruben Lütke214c91fde0f0
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 24f7b18210..a7d295a75c 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -309,7 +309,7 @@ jobs:uses: ./.github/actions/install-lockedwith:tools-only: "true"- with: typer platformdirs click httpx rich pyyaml pydantic loguru python-dotenv packaging+ with: typer platformdirs click httpx rich pyyaml pydantic loguru python-dotenv packaging jsonschema- name: Run every static gateenv:PRIVACY_PRIVATE_EMAILS: ${{ vars.PRIVACY_PRIVATE_EMAILS }}diff --git a/art/verse/decks/hangar/unreal_arena/__init__.py b/art/verse/decks/hangar/unreal_arena/__init__.pynew file mode 100644index 0000000000..a717ba112e--- /dev/null+++ b/art/verse/decks/hangar/unreal_arena/__init__.py@@ -0,0 +1,9 @@+"""The Unreal hangar arena (WP11) as code: layout, nav, flow and placements.++Pure Python (numpy and scipy, no bpy, no unreal). `layout` holds every box of+the hangar shell, the five arena zones and the armoury in plan metres;+`nav` turns the walk surfaces into a 2.5D grid graph; `flow` measures+sightlines, spawn distances and time to contact on it; `placements` writes+the `verse.placement/1` documents (art-pipeline 4). The spec the numbers+come from is docs/verse/unreal/arena.md.+"""diff --git a/art/verse/decks/hangar/unreal_arena/flow.py b/art/verse/decks/hangar/unreal_arena/flow.pynew file mode 100644index 0000000000..a5bc7901ee--- /dev/null+++ b/art/verse/decks/hangar/unreal_arena/flow.py@@ -0,0 +1,338 @@+"""Flow analysis of the arena (WP11.11): sightlines, spawn spacing, time to contact.++Sight runs eye to eye (1.65 m above the floor) against every box that blocks+sight; glass, grating, railings and the fence do not (destruction.md 2: intact+glass and grating let sight through). Two inputs feed time to contact:++* the walker model here (seeded, deterministic): two players roam the nav+ graph at bot speed, the second spawned by the 9.2 rule; contact is the first+ moment either sees the other;+* bot runs from the harness (WP10) when they exist: a JSON lines log with one+ `{"run": id, "t_contact_s": s}` object per contact (`contacts_from_log`).++The report is plain JSON (`report`), written by unreal_arena_build.py.+"""++from __future__ import annotations++import json+import math+from collections.abc import Iterable+from pathlib import Path++import numpy as np++from . import layout as L+from .nav import EYE_M, NavGraph++SIGHT_CAP_M = 40.0 # A11.5: longest unbroken sightline+TTC_RANGE_S = (6.0, 15.0) # A11.5: normal vs normal median time to contact+HIDER_CAP_S = 25.0 # A11.5 / BG12 with the hider model+BOT_SPEED_MPS = 4.8 # a normal-tier bot moving between cover (run, not sprint)+STEP_S = 0.25+PATH_SPACING_M = 20.0 # A11.2+++def sight_boxes(layout: L.Layout, pad: float = 2.0) -> np.ndarray:+ """(n, 6) array x0, z0, h0, x1, z1, h1 of the boxes that block sight near the arena."""+ ax0, ax1, az0, az1 = L.ARENA+ rows = [+ (b.x0, b.z0, b.h0, b.x1, b.z1, b.h1)+ for b in layout.boxes+ if b.sight+ and b.x1 > ax0 - pad+ and b.x0 < ax1 + pad+ and b.z1 > az0 - pad+ and b.z0 < az1 + pad+ and b.h1 > -1.0+ ]+ return np.array(rows, dtype=float)+++def clear(a: np.ndarray, b: np.ndarray, boxes: np.ndarray) -> np.ndarray:+ """Vectorised segment test: True where the segment a[i] -> b[i] hits no box."""+ a = np.atleast_2d(np.asarray(a, dtype=float))+ b = np.atleast_2d(np.asarray(b, dtype=float))+ out = np.ones(a.shape[0], dtype=bool)+ if boxes.size == 0:+ return out+ lo, hi = boxes[None, :, :3], boxes[None, :, 3:]+ eps = 1e-6+ step = max(1, 4_000_000 // (boxes.shape[0] * 3))+ for s in range(0, a.shape[0], step):+ sa = a[s : s + step, None, :]+ d = b[s : s + step, None, :] - sa+ par = np.abs(d) < 1e-12+ inv = 1.0 / np.where(par, 1.0, d)+ t1 = (lo - sa) * inv+ t2 = (hi - sa) * inv+ # Axis-parallel segments: inside the slab -> (-inf, inf), outside -> empty.+ inside = (sa > lo) & (sa < hi)+ tmin = np.where(par, np.where(inside, -np.inf, np.inf), np.minimum(t1, t2))+ tmax = np.where(par, np.where(inside, np.inf, -np.inf), np.maximum(t1, t2))+ enter = tmin.max(axis=2)+ leave = tmax.min(axis=2)+ hit = (enter <= leave) & (leave > eps) & (enter < 1.0 - eps)+ out[s : s + step] = ~hit.any(axis=1)+ return out+++def sample(nav: NavGraph, spacing_m: float = 2.0) -> np.ndarray:+ """Node indices on a coarser lattice (one per spacing x spacing cell and level)."""+ keys = {}+ for i in range(nav.count):+ key = (+ int(nav.xs[i] // spacing_m),+ int(nav.zs[i] // spacing_m),+ nav.level_of(float(nav.hs[i])),+ )+ keys.setdefault(key, i)+ return np.array(sorted(keys.values()))+++def sightlines(nav: NavGraph, layout: L.Layout, spacing_m: float = 2.0, chunk: int = 20000) -> dict:+ """Histogram of visible eye-to-eye distances over sampled node pairs."""+ idx = sample(nav, spacing_m)+ eyes = nav.eyes()[idx]+ boxes = sight_boxes(layout)+ ia, ib = np.triu_indices(len(idx), k=1)+ dist = np.linalg.norm(eyes[ia] - eyes[ib], axis=1)+ visible = np.zeros(len(ia), dtype=bool)+ for s in range(0, len(ia), chunk):+ e = slice(s, s + chunk)+ visible[e] = clear(eyes[ia[e]], eyes[ib[e]], boxes)+ vis_d = dist[visible]+ edges = list(range(0, 70, 5))+ hist, _ = np.histogram(vis_d, bins=edges)+ longest = float(vis_d.max()) if vis_d.size else 0.0+ worst = []+ order = np.argsort(-np.where(visible, dist, -1.0))[:10]+ for k in order:+ if not visible[k] or dist[k] <= SIGHT_CAP_M:+ break+ a, b = eyes[ia[k]], eyes[ib[k]]+ worst.append(+ {+ "from": [round(v, 1) for v in a],+ "to": [round(v, 1) for v in b],+ "m": round(float(dist[k]), 1),+ }+ )+ return {+ "samples": int(len(idx)),+ "pairs": int(len(ia)),+ "visible_pairs": int(visible.sum()),+ "bins_m": edges,+ "histogram": hist.tolist(),+ "longest_m": round(longest, 2),+ "over_cap": int((vis_d > SIGHT_CAP_M).sum()),+ "worst": worst,+ }+++def spawn_nodes(nav: NavGraph, layout: L.Layout) -> list[int]:+ return [nav.nearest(s.x, s.z, s.h) for s in layout.spawns]+++def spawn_spacing(nav: NavGraph, layout: L.Layout) -> dict:+ nodes = spawn_nodes(nav, layout)+ d = nav.distances_from(nodes)[:, nodes]+ names = [s.id for s in layout.spawns]+ pairs = []+ for i in range(len(nodes)):+ for j in range(i + 1, len(nodes)):+ pairs.append((float(d[i, j]), names[i], names[j]))+ pairs.sort()+ return {+ "count": len(nodes),+ "min_path_m": round(pairs[0][0], 2) if pairs else 0.0,+ "closest": [{"a": a, "b": b, "m": round(m, 2)} for m, a, b in pairs[:5]],+ }+++class _Walker:+ def __init__(self, nav: NavGraph, node: int, rng: np.random.Generator, goals: np.ndarray):+ self.nav, self.node, self.rng, self.goals = nav, node, rng, goals+ self.path: list[int] = []+ self.carry = 0.0++ def pos(self) -> np.ndarray:+ n = self.node+ return np.array([self.nav.xs[n], self.nav.zs[n], self.nav.hs[n] + EYE_M])++ def step(self, metres: float) -> None:+ budget = metres + self.carry+ while budget > 0:+ if not self.path:+ goal = int(self.rng.choice(self.goals))+ self.path = self.nav.path(self.node, goal)[1:]+ if not self.path:+ break+ nxt = self.path[0]+ seg = math.dist(+ (self.nav.xs[self.node], self.nav.zs[self.node], self.nav.hs[self.node]),+ (self.nav.xs[nxt], self.nav.zs[nxt], self.nav.hs[nxt]),+ )+ if seg > budget:+ break+ budget -= seg+ self.node = nxt+ self.path.pop(0)+ self.carry = budget+++def choose_spawn(+ nav: NavGraph, layout: L.Layout, boxes: np.ndarray, opponent: int, spawns: list[int]+) -> int:+ """The 9.2 rule on the grid: out of the opponent's sight if any is, then farthest by path."""+ eye = nav.eyes()[opponent]+ dist = nav.distances_from([opponent])[0]+ probes = []+ for n in spawns:+ base = np.array([nav.xs[n], nav.zs[n], nav.hs[n]])+ seen = clear(+ np.repeat(eye[None], 3, 0),+ base + np.array([[0, 0, 0.3], [0, 0, 1.0], [0, 0, 1.65]]),+ boxes,+ )+ probes.append(bool(seen.any()))+ pool = [n for n, seen in zip(spawns, probes, strict=True) if not seen] or list(spawns)+ return max(pool, key=lambda n: dist[n] if np.isfinite(dist[n]) else -1.0)+++def time_to_contact(+ nav: NavGraph, layout: L.Layout, runs: int = 120, seed: int = 11, cap_s: float = 90.0+) -> dict:+ boxes = sight_boxes(layout)+ spawns = spawn_nodes(nav, layout)+ goals = sample(nav, 3.0)+ rng = np.random.default_rng(seed)+ times = []+ for _ in range(runs):+ a_node = int(rng.choice(goals))+ b_node = choose_spawn(nav, layout, boxes, a_node, spawns)+ a, b = _Walker(nav, a_node, rng, goals), _Walker(nav, b_node, rng, goals)+ t = 0.0+ while t < cap_s:+ if clear(a.pos(), b.pos(), boxes)[0] and math.dist(a.pos(), b.pos()) <= 60.0:+ break+ a.step(BOT_SPEED_MPS * STEP_S)+ b.step(BOT_SPEED_MPS * STEP_S)+ t += STEP_S+ times.append(t)+ arr = np.array(times)+ return {+ "model": "walker",+ "runs": runs,+ "seed": seed,+ "speed_mps": BOT_SPEED_MPS,+ "median_s": round(float(np.median(arr)), 2),+ "p10_s": round(float(np.percentile(arr, 10)), 2),+ "p90_s": round(float(np.percentile(arr, 90)), 2),+ }+++class _Explorer(_Walker):+ """A seeker that clears the map: its next goal is the nearest sample it has not seen yet."""++ def __init__(self, nav: NavGraph, node: int, rng, samples: np.ndarray, boxes: np.ndarray):+ super().__init__(nav, node, rng, samples)+ self.samples = samples+ self.sample_eyes = nav.eyes()[samples]+ self.unseen = np.ones(len(samples), dtype=bool)+ self.boxes = boxes++ def look(self) -> None:+ todo = np.where(self.unseen)[0]+ if todo.size:+ eye = np.repeat(self.pos()[None], todo.size, 0)+ self.unseen[todo[clear(eye, self.sample_eyes[todo], self.boxes)]] = False++ def step(self, metres: float) -> None:+ if not self.path:+ todo = np.where(self.unseen)[0]+ if todo.size:+ d = np.linalg.norm(self.sample_eyes[todo] - self.pos(), axis=1)+ goal = int(self.samples[todo[int(np.argmin(d))]])+ self.path = self.nav.path(self.node, goal)[1:]+ if not self.path:+ self.unseen[todo[int(np.argmin(d))]] = False+ super().step(metres)+++def hider(+ nav: NavGraph, layout: L.Layout, runs: int = 60, seed: int = 12, cap_s: float = 120.0+) -> dict:+ """BG12 stand-in: the hider camps on one of the least-seen spots, the seeker clears the map."""+ boxes = sight_boxes(layout)+ idx = sample(nav, 3.0)+ eyes = nav.eyes()[idx]+ seen_count = np.zeros(len(idx), dtype=int)+ for i in range(len(idx)):+ seen_count[i] = int(clear(np.repeat(eyes[i][None], len(idx), 0), eyes, boxes).sum())+ hide_spots = idx[np.argsort(seen_count)[:8]]+ rng = np.random.default_rng(seed)+ spawns = spawn_nodes(nav, layout)+ times = []+ for r in range(runs):+ hide = int(hide_spots[r % len(hide_spots)])+ start = choose_spawn(nav, layout, boxes, hide, spawns)+ seeker = _Explorer(nav, start, rng, idx, boxes)+ target = nav.eyes()[hide]+ t = 0.0+ while t < cap_s and not clear(seeker.pos(), target, boxes)[0]:+ seeker.look()+ seeker.step(BOT_SPEED_MPS * STEP_S)+ t += STEP_S+ times.append(t)+ arr = np.array(times)+ return {+ "model": "explorer_vs_camper",+ "runs": runs,+ "hide_spots": [+ [round(float(nav.xs[n]), 2), round(float(nav.zs[n]), 2), round(float(nav.hs[n]), 2)]+ for n in hide_spots+ ],+ "median_s": round(float(np.median(arr)), 2),+ "p90_s": round(float(np.percentile(arr, 90)), 2),+ }+++def contacts_from_log(path: Path) -> list[float]:+ """Time-to-contact samples from a harness bot run log (JSON lines)."""+ out = []+ for line in path.read_text(encoding="utf-8").splitlines():+ line = line.strip()+ if line:+ out.append(float(json.loads(line)["t_contact_s"]))+ return out+++def summarize_contacts(samples: Iterable[float]) -> dict:+ arr = np.array(list(samples), dtype=float)+ if arr.size == 0:+ return {"runs": 0}+ return {"runs": int(arr.size), "median_s": round(float(np.median(arr)), 2)}+++def report(+ nav: NavGraph, layout: L.Layout, *, quick: bool = False, bot_log: Path | None = None+) -> dict:+ out = {+ "schema": "verse.arena_flow/1",+ "arena_m": list(L.ARENA),+ "nav": {+ "nodes": nav.count,+ "area_m2": round(nav.area_m2(), 1),+ "extent_m": [round(v, 2) for v in nav.extent()],+ "islands": nav.islands()[:5],+ "level_shares": {k: round(v, 3) for k, v in nav.level_shares().items()},+ },+ "spawns": spawn_spacing(nav, layout),+ "sightlines": sightlines(nav, layout, spacing_m=3.0 if quick else 2.0),+ "time_to_contact": time_to_contact(nav, layout, runs=30 if quick else 120),+ "hider": hider(nav, layout, runs=16 if quick else 60),+ }+ if bot_log is not None and bot_log.is_file():+ out["bot_runs"] = summarize_contacts(contacts_from_log(bot_log))+ return outdiff --git a/art/verse/decks/hangar/unreal_arena/layout.py b/art/verse/decks/hangar/unreal_arena/layout.pynew file mode 100644index 0000000000..7722edc638--- /dev/null+++ b/art/verse/decks/hangar/unreal_arena/layout.py@@ -0,0 +1,1087 @@+"""Hangar shell, arena zones and armoury of the Unreal hangar, as boxes.++Plan metres, the frame of `hangar_layout.py` and coordinates 3.1: `x` grows+east (0 = west hull wall, 100 = east), `z` grows toward the near wall (0 = the+hero wall, 62 = the near wall), `h` is height above the hall floor. Unreal+space is `(100 x, 100 z, 100 h)` cm (coordinates 2.1, three.js frame with+y = h), so a box converts by scaling only.++Everything the arena is made of is listed here once: the analysis (`nav`,+`flow`), the placement export (`placements`) and the spec+(docs/verse/unreal/arena.md) all read these tables. Change the arena here,+then rerun `python art/verse/decks/hangar/unreal_arena_build.py` and the+tests in tests/verse/test_verse_hangar_arena.py.+"""++from __future__ import annotations++from dataclasses import dataclass, field++DECK = "hangar"+OWNER = "WP11"++HALL = (0.0, 100.0, 0.0, 62.0)+CEILING_H = 21.0+FLOOR_T = 0.5++#: Walkable arena bounds (x0, x1, z0, z1): 50 x 40 m inside the hall (A11.1).+ARENA = (25.0, 75.0, 4.0, 44.0)+LEVELS = {"L0": 0.0, "L1": 3.0, "L2": 6.0}+#: Height bands that count as one level for the A11.1 share rule.+LEVEL_BANDS = (("L0", -1.0, 1.5), ("L1", 1.5, 4.5), ("L2", 4.5, 9.0))++#: Launch well opening (x0, x1, z0, z1); 26 m deep, the floor never breaks. Supersedes the+#: hangar_layout.py well (8..38, 8..20) for the Unreal hangar (arena.md 1).+WELL = (27.0, 37.0, 9.0, 19.0)+WELL_DEPTH = 26.0+#: Hero wall pier, x extent (it closes the north perimeter between its two runs).+PIER = (49.0, 51.0)++ZONES = ("shell", "arena_canyon", "arena_shuttle", "arena_booth", "arena_catwalks", "armoury")+ARENA_ZONES = ("arena_canyon", "arena_shuttle", "arena_booth", "arena_catwalks")++#: Destruction classes of destruction.md 3.2 -> (penetration material, max HP, repair s).+PIECE_CLASSES = {+ "wall_panel": ("sheet_metal", 200.0, 8.0),+ "cladding_wall": ("cladding_panel", 250.0, 8.0),+ "container_wall": ("container_wall", 300.0, 8.0),+ "glass": ("glass", 20.0, 4.0),+ "catwalk": ("catwalk_grating", 1.0, 10.0),+ "ceiling_panel": ("ceiling_panel", 60.0, 5.0),+}+#: Reference thickness in metres per penetration material (destruction.md 2, rule 9).+REF_THICKNESS_M = {+ "sheet_metal": 0.003,+ "container_wall": 0.004,+ "glass": 0.024,+ "cladding_panel": 0.04,+ "catwalk_grating": 0.03,+ "ceiling_panel": 0.025,+}+++#: Hangar haze and post settings of WP11.12 (art-pipeline 8.2 "Haze", 6.3 Lumen only):+#: exponential height fog plus volumetric fog with neutral grey scattering (albedo+#: saturation 0, never coloured fog), dense enough that the 21 m truss lights draw+#: visible cones. The placement schema has no volume kind, so this is data for the+#: level owner (arena.md 9); the values are what the visual lane tunes against.+HAZE = {+ "fog": "exponential_height",+ "fog_density": 0.035,+ "fog_height_falloff": 0.12,+ "fog_start_distance_m": 4.0,+ "fog_inscattering_rgb": (0.42, 0.42, 0.42),+ "volumetric": True,+ "volumetric_albedo_rgb": (0.85, 0.85, 0.85),+ "volumetric_extinction_scale": 1.0,+ "volumetric_view_distance_m": 60.0,+}+POST = {+ "gi": "lumen",+ "reflections": "lumen",+ "exposure": "manual",+ "exposure_compensation_ev": 0.0,+ "bloom_intensity": 0.35,+ "vignette": 0.25,+}+++@dataclass(frozen=True)+class Box:+ """An axis-aligned solid. `walk` marks a top surface people stand on."""++ id: str+ zone: str+ x0: float+ x1: float+ z0: float+ z1: float+ h0: float+ h1: float+ family: str # piece family; the placement piece is SM_<Family> / GC_<Family>+ sight: bool = True # blocks sight (glass, grating and railings do not)+ solid: bool = True # blocks pawns+ walk: bool = False+ material: str = "concrete"+ piece_class: str | None = None # destruction class, None = never breaks+ layer: str = "arena" # "base", "day" or "arena"++ @property+ def size(self) -> tuple[float, float, float]:+ return (self.x1 - self.x0, self.z1 - self.z0, self.h1 - self.h0)++ @property+ def centre(self) -> tuple[float, float, float]:+ return ((self.x0 + self.x1) / 2, (self.z0 + self.z1) / 2, (self.h0 + self.h1) / 2)+++@dataclass(frozen=True)+class Ramp:+ """A stair or ramp: a walk surface whose height runs linearly along one axis."""++ id: str+ zone: str+ x0: float+ x1: float+ z0: float+ z1: float+ h_start: float # height at the start edge (x0 for axis "x", z0 for axis "z")+ h_end: float+ axis: str # "x" or "z"+ family: str = "Stair"+ layer: str = "arena"++ def height_at(self, x: float, z: float) -> float:+ if self.axis == "x":+ t = (x - self.x0) / (self.x1 - self.x0)+ else:+ t = (z - self.z0) / (self.z1 - self.z0)+ t = min(1.0, max(0.0, t))+ return self.h_start + (self.h_end - self.h_start) * t+++@dataclass(frozen=True)+class Spawn:+ id: str+ zone: str+ x: float+ z: float+ h: float+ heading_deg: float # Unreal heading: 0 = +X (east), 90 = +Y (toward the near wall)+++@dataclass(frozen=True)+class Light:+ id: str+ zone: str+ x: float+ z: float+ h: float+ type: str # spot, rect, point+ kelvin: float+ intensity_lm: float+ attenuation_m: float+ cone_deg: float | None = None+ source_size_m: float | None = None+ pitch_deg: float = -90.0 # spots point down unless stated+++@dataclass(frozen=True)+class Station:+ id: str+ kind: str+ zone: str+ x: float+ z: float+ h: float+ heading_deg: float+ family: str+ size: tuple[float, float, float]+++@dataclass+class Layout:+ boxes: list[Box] = field(default_factory=list)+ ramps: list[Ramp] = field(default_factory=list)+ spawns: list[Spawn] = field(default_factory=list)+ lights: list[Light] = field(default_factory=list)+ stations: list[Station] = field(default_factory=list)++ def zone_boxes(self, zone: str) -> list[Box]:+ return [b for b in self.boxes if b.zone == zone]++ def zone_ramps(self, zone: str) -> list[Ramp]:+ return [r for r in self.ramps if r.zone == zone]+++def _split(a0: float, a1: float, step: float) -> list[tuple[float, float]]:+ """Cut [a0, a1] into pieces of about `step` (destructibles are per segment)."""+ n = max(1, round((a1 - a0) / step))+ width = (a1 - a0) / n+ return [(a0 + i * width, a0 + (i + 1) * width) for i in range(n)]+++# ---------------------------------------------------------------------------+# shell: hall floor, hull walls, ceiling, launch well, arena perimeter+# ---------------------------------------------------------------------------+++def _shell(out: Layout) -> None:+ z = "shell"+ wx0, wx1, wz0, wz1 = WELL+ hx0, hx1, hz0, hz1 = HALL+ floor = dict(zone=z, h0=-FLOOR_T, h1=0.0, family="HangarFloor", walk=True, layer="base")+ # The hall floor never breaks (A11.7): concrete, no destruction class.+ out.boxes += [+ Box("floor_north", x0=hx0, x1=hx1, z0=hz0, z1=wz0, **floor),+ Box("floor_south", x0=hx0, x1=hx1, z0=wz1, z1=hz1, **floor),+ Box("floor_west", x0=hx0, x1=wx0, z0=wz0, z1=wz1, **floor),+ Box("floor_east", x0=wx1, x1=hx1, z0=wz0, z1=wz1, **floor),+ ]+ wall = dict(zone=z, family="HullWall", layer="base")+ out.boxes += [+ Box("hero_wall", x0=hx0, x1=hx1, z0=hz0, z1=1.5, h0=0.0, h1=22.0, **wall),+ Box("near_wall", x0=hx0, x1=hx1, z0=61.6, z1=62.6, h0=0.0, h1=CEILING_H, **wall),+ Box("hull_west", x0=hx0, x1=2.5, z0=1.5, z1=61.6, h0=0.0, h1=CEILING_H, **wall),+ Box("hull_east", x0=97.5, x1=hx1, z0=1.5, z1=61.6, h0=0.0, h1=CEILING_H, **wall),+ Box(+ "ceiling",+ x0=hx0,+ x1=hx1,+ z0=hz0,+ z1=hz1,+ h0=CEILING_H,+ h1=CEILING_H + 1.0,+ zone=z,+ family="HangarCeiling",+ layer="base",+ ),+ ]+ pit = dict(zone=z, family="WellWall", layer="base", h0=-WELL_DEPTH, h1=0.0)+ out.boxes += [+ Box("well_wall_n", x0=wx0, x1=wx1, z0=wz0, z1=wz0 + 0.5, **pit),+ Box("well_wall_s", x0=wx0, x1=wx1, z0=wz1 - 0.5, z1=wz1, **pit),+ Box("well_wall_w", x0=wx0, x1=wx0 + 0.5, z0=wz0, z1=wz1, **pit),+ Box("well_wall_e", x0=wx1 - 0.5, x1=wx1, z0=wz0, z1=wz1, **pit),+ # Pit floor: not part of the arena nav (fall = death volume, WP02 world damage).+ Box(+ "well_floor",+ x0=wx0,+ x1=wx1,+ z0=wz0,+ z1=wz1,+ h0=-WELL_DEPTH - 0.5,+ h1=-WELL_DEPTH,+ zone=z,+ family="WellFloor",+ layer="base",+ ),+ ]+ # Structural columns of the roof truss, base layer: they also cut the long+ # diagonals of the open floor.+ for i, (cx, cz) in enumerate(((41.5, 10.5), (41.5, 26.5), (57.2, 21.5), (57.5, 9.0)), 1):+ out.boxes.append(+ Box(+ f"column_{i}",+ z,+ cx - 0.6,+ cx + 0.6,+ cz - 0.6,+ cz + 0.6,+ 0.0,+ CEILING_H,+ "TrussColumn",+ layer="base",+ )+ )+ # Hero wall pier: splits the north catwalk, so the 50 m run along the wall is two.+ out.boxes.append(Box("hero_pier", z, *PIER, 1.5, 7.0, 0.0, 12.0, "HeroPier", layer="base"))+ # Arena perimeter: blast barriers plus a see-through mesh fence, arena layer only.+ ax0, ax1, az0, az1 = ARENA+ barrier = dict(zone=z, family="BlastBarrier", h0=0.0, h1=4.5, layer="arena")+ fence = dict(zone=z, family="ArenaFence", h0=4.5, h1=10.0, sight=False, layer="arena")+ # North run along z = az0: closes the strip between the hero wall and the+ # arena; it stops at the hero pier, which closes the gap itself.+ px0, px1 = PIER+ for k, (a, b) in enumerate(((ax0 - 0.6, px0), (px1, ax1 + 0.6)), 1):+ out.boxes.append(Box(f"barrier_north_{k}", x0=a, x1=b, z0=az0 - 0.6, z1=az0, **barrier))+ out.boxes.append(Box(f"fence_north_{k}", x0=a, x1=b, z0=az0 - 0.6, z1=az0, **fence))+ for name, x0, x1, z0, z1 in (+ ("west", ax0 - 0.6, ax0, az0, az1),+ ("south", ax0 - 0.6, ax1 + 0.6, az1, az1 + 0.6),+ ("east", ax1, ax1 + 0.6, az0, az1),+ ):+ for k, (a, b) in enumerate(+ _split(z0, z1, 10.0) if name != "south" else _split(x0, x1, 10.0), 1+ ):+ if name == "south":+ out.boxes.append(Box(f"barrier_{name}_{k}", x0=a, x1=b, z0=z0, z1=z1, **barrier))+ out.boxes.append(Box(f"fence_{name}_{k}", x0=a, x1=b, z0=z0, z1=z1, **fence))+ else:+ out.boxes.append(Box(f"barrier_{name}_{k}", x0=x0, x1=x1, z0=a, z1=b, **barrier))+ out.boxes.append(Box(f"fence_{name}_{k}", x0=x0, x1=x1, z0=a, z1=b, **fence))+ # Railing around the well: blocks pawns, not sight.+ rail = dict(zone=z, family="Railing", h0=0.0, h1=1.1, sight=False, layer="arena")+ out.boxes += [+ Box("well_rail_n", x0=wx0, x1=wx1, z0=wz0 - 0.1, z1=wz0, **rail),+ Box("well_rail_s", x0=wx0, x1=wx1, z0=wz1, z1=wz1 + 0.1, **rail),+ Box("well_rail_w", x0=wx0 - 0.1, x1=wx0, z0=wz0, z1=wz1, **rail),+ Box("well_rail_e", x0=wx1, x1=wx1 + 0.1, z0=wz0, z1=wz1, **rail),+ ]+ # Work lights hang from the roof truss: hard, neutral-warm, shadowed (README Look).+ n = 0+ for lx in (12.0, 32.0, 50.0, 68.0, 88.0):+ for lz in (8.0, 24.0, 40.0, 54.0):+ n += 1+ out.lights.append(+ Light(+ f"work_{n:02d}",+ z,+ lx,+ lz,+ 18.5,+ "spot",+ 4300.0,+ 42000.0,+ 30.0,+ cone_deg=55.0,+ source_size_m=0.4,+ )+ )+++# ---------------------------------------------------------------------------+# arena_catwalks: upper level, ceiling panels, launch well crossing+# ---------------------------------------------------------------------------++CAT_T = 0.03 # grating deck thickness: the catwalk_grating reference (destruction 9)+++def _catwalk_run(+ out: Layout, name: str, x0: float, x1: float, z0: float, z1: float, along: str+) -> None:+ z = "arena_catwalks"+ h = LEVELS["L2"]+ a0, a1 = (x0, x1) if along == "x" else (z0, z1)+ for k, (a, b) in enumerate(_split(a0, a1, 4.0), 1):+ bx0, bx1, bz0, bz1 = (a, b, z0, z1) if along == "x" else (x0, x1, a, b)+ out.boxes.append(+ Box(+ f"{name}_{k:02d}",+ z,+ bx0,+ bx1,+ bz0,+ bz1,+ h - CAT_T,+ h,+ "CatwalkSegment",+ sight=False,+ walk=True,+ material="catwalk_grating",+ piece_class="catwalk",+ )+ )+++def _catwalks(out: Layout) -> None:+ z = "arena_catwalks"+ h = LEVELS["L2"]+ # North run along the hero wall, west leg, east leg over the canyon, well+ # crossing and its landing, and the south gantry over the open floor.+ _catwalk_run(out, "cat_north_w", 25.2, 49.0, 4.0, 6.4, "x")+ _catwalk_run(out, "cat_north_e", 51.0, 74.8, 4.0, 6.4, "x")+ _catwalk_run(out, "cat_west", 25.2, 27.4, 6.4, 32.0, "z")+ _catwalk_run(out, "cat_well", 27.4, 37.0, 13.0, 15.0, "x")+ _catwalk_run(out, "cat_landing", 37.0, 39.6, 13.0, 17.0, "x")+ # Railings on the open edges (pawns only).+ rail = dict(zone=z, family="Railing", sight=False)+ out.boxes += [+ Box("cat_north_rail_w", x0=27.4, x1=49.0, z0=6.3, z1=6.4, h0=h, h1=h + 1.1, **rail),+ Box("cat_north_rail_e", x0=63.0, x1=74.8, z0=6.3, z1=6.4, h0=h, h1=h + 1.1, **rail),+ Box("cat_west_rail", x0=27.3, x1=27.4, z0=6.4, z1=13.0, h0=h, h1=h + 1.1, **rail),+ Box("cat_west_rail_2", x0=27.3, x1=27.4, z0=15.0, z1=32.0, h0=h, h1=h + 1.1, **rail),+ ]+ # The south gantry is an enclosed gallery on a solid deck (booth upper room to the east stair):+ # sheet-metal walls that bolts hole and charges breach, so its sightlines are earned.+ out.boxes.append(+ Box(+ "gallery_deck",+ z,+ 38.0,+ 60.4,+ 36.0,+ 39.0,+ h - 0.2,+ h,+ "GalleryDeck",+ walk=True,+ material="armor_steel",+ )+ )+ sheet = REF_THICKNESS_M["sheet_metal"]+ for side, (x0, x1, z0) in (("n", (38.0, 57.8, 36.0)), ("s", (38.0, 60.4, 39.0 - sheet))):+ for k, (a, b) in enumerate(_split(x0, x1, 3.0), 1):+ out.boxes.append(+ Box(+ f"gallery_wall_{side}_{k}",+ z,+ a,+ b,+ z0,+ z0 + sheet,+ h,+ h + 2.4,+ "GalleryWallPanel",+ material="sheet_metal",+ piece_class="wall_panel",+ )+ )+ out.boxes.append(+ Box("gallery_wall_e", z, 60.4 - 0.2, 60.4, 36.0, 39.0, h, h + 2.4, "GalleryWall")+ )+ out.boxes.append(+ Box("gallery_roof", z, 38.0, 60.4, 36.0, 39.0, h + 2.4, h + 2.6, "GalleryRoof")+ )+ # A container hanging from the gantry crane over the shuttle: cuts the upper diagonals.+ out.boxes.append(+ Box(+ "hung_container",+ z,+ 44.0,+ 56.0,+ 22.0,+ 24.6,+ 6.5,+ 9.5,+ "HungContainer",+ material="armor_steel",+ )+ )+ # Ceiling panels over the north run: break and fall (ceiling_panel), block sight.+ panels = _split(25.2, 49.0, 1.8) + _split(51.0, 74.8, 1.8)+ for k, (a, b) in enumerate(panels, 1):+ out.boxes.append(+ Box(+ f"ceil_panel_{k:02d}",+ z,+ a,+ b,+ 4.0,+ 6.4,+ 9.0,+ 9.0 + 0.025,+ "CeilingPanel",+ material="ceiling_panel",+ piece_class="ceiling_panel",+ )+ )+ # Hanging blast screens below the truss: break the long upper-level diagonals.+ for k, (sx0, sx1, sz0, sz1) in enumerate(+ ((43.0, 49.0, 20.0, 20.3), (51.0, 57.0, 27.5, 27.8), (31.0, 31.3, 27.0, 33.0)), 1+ ):+ out.boxes.append(+ Box(+ f"screen_{k}",+ z,+ sx0,+ sx1,+ sz0,+ sz1,+ 4.2,+ 9.0,+ "HangingScreen",+ material="armor_steel",+ )+ )+ # Stairs between the levels.+ out.ramps += [+ Ramp("stair_cat_canyon", z, 60.6, 63.0, 6.4, 11.0, h, LEVELS["L1"], "z"),+ Ramp("stair_cat_shuttle", z, 39.6, 46.0, 15.0, 17.0, h, LEVELS["L1"], "x"),+ Ramp("stair_gantry", z, 57.8, 59.8, 28.0, 36.0, 0.0, h, "z"),+ ]+ out.lights += [+ Light("cat_north_a", z, 34.0, 5.0, 8.8, "rect", 4500.0, 2400.0, 9.0, source_size_m=1.2),+ Light("cat_north_b", z, 52.0, 5.0, 8.8, "rect", 4500.0, 2400.0, 9.0, source_size_m=1.2),+ Light("cat_gantry", z, 50.0, 37.5, h + 2.3, "rect", 4500.0, 1500.0, 6.0, source_size_m=0.8),+ ]+++# ---------------------------------------------------------------------------+# arena_booth: glazed lookout with breakable glass, mid level+# ---------------------------------------------------------------------------+++def _booth(out: Layout) -> None:+ z = "arena_booth"+ l1 = LEVELS["L1"]+ bx0, bx1, bz0, bz1 = 25.0, 38.0, 32.0, 44.0+ out.boxes.append(Box("plinth", z, bx0, bx1, bz0, bz1, 0.0, l1, "BoothPlinth", walk=True))+ glass_t = REF_THICKNESS_M["glass"]+ clad = REF_THICKNESS_M["cladding_panel"]+ up = 6.0 + 0.3 # upper room floor (L2)+ # Lower room (L1): cladding on the north and south faces, glass to the east.+ for side, zz in (("n", bz0), ("s", bz1 - clad)):+ for k, (a, b) in enumerate(_split(bx0, bx1, 3.0), 1):+ out.boxes.append(+ Box(+ f"wall_{side}_{k}",+ z,+ a,+ b,+ zz,+ zz + clad,+ l1,+ 6.0,+ "BoothCladding",+ material="cladding_panel",+ piece_class="cladding_wall",+ )+ )+ # East face: door from the bridge and the floor stair at z 32.2..35.5.+ out.boxes.append(Box("parapet_e", z, bx1 - 0.2, bx1, 35.5, 39.5, l1, l1 + 0.9, "BoothParapet"))+ out.boxes.append(Box("lintel_e", z, bx1 - 0.2, bx1, 35.5, 39.5, l1 + 2.7, 6.0, "BoothParapet"))+ out.boxes.append(Box("wall_e_s", z, bx1 - 0.2, bx1, 39.5, bz1, l1, 6.0, "BoothWallSolid"))+ for k, (a, b) in enumerate(_split(35.5, 39.5, 2.0), 1):+ out.boxes.append(+ Box(+ f"glass_e_{k}",+ z,+ bx1 - 0.1 - glass_t,+ bx1 - 0.1,+ a,+ b,+ l1 + 0.9,+ l1 + 2.7,+ "BoothGlass",+ sight=False,+ material="glass",+ piece_class="glass",+ )+ )+ out.boxes.append(Box("wall_w", z, bx0, bx0 + 0.2, bz0, bz1, l1, 6.0, "BoothWallSolid"))+ # Upper room (L2): from the west catwalk leg, the south gallery and an inner stair.+ out.boxes += [+ Box("upper_floor_a", z, 28.0, bx1, bz0, bz1, 6.0, up, "BoothFloor", walk=True),+ Box("upper_floor_b", z, bx0, 28.0, bz0, 35.5, 6.0, up, "BoothFloor", walk=True),+ Box("upper_wall_n", z, 27.6, bx1, bz0, bz0 + 0.2, up, up + 3.0, "BoothWallSolid"),+ Box("upper_wall_w", z, bx0, bx0 + 0.2, bz0 + 0.2, bz1, up, up + 3.0, "BoothWallSolid"),+ Box("upper_wall_e_n", z, bx1 - 0.2, bx1, bz0, 36.0, up, up + 3.0, "BoothWallSolid"),+ Box("upper_wall_e_s", z, bx1 - 0.2, bx1, 39.0, bz1, up, up + 3.0, "BoothWallSolid"),+ Box("upper_parapet_s", z, bx0, bx1, bz1 - 0.2, bz1, up, up + 0.9, "BoothParapet"),+ Box("upper_roof", z, bx0, bx1, bz0, bz1, up + 3.0, up + 3.3, "BoothRoof"),+ ]+ for k, (a, b) in enumerate(_split(bx0, bx1, 2.0), 1):+ out.boxes.append(+ Box(+ f"upper_glass_s_{k}",+ z,+ a,+ b,+ bz1 - 0.1 - glass_t,+ bz1 - 0.1,+ up + 0.9,+ up + 2.7,+ "BoothGlass",+ sight=False,+ material="glass",+ piece_class="glass",+ )+ )+ out.ramps.append(Ramp("stair_booth_inner", z, 26.2, 28.0, 35.5, 41.5, up, l1, "z"))+ # Consoles inside: half cover.+ out.boxes += [+ Box(+ "console_1",+ z,+ 30.0,+ 34.0,+ 35.0,+ 35.8,+ l1,+ l1 + 1.0,+ "BoothConsole",+ material="sheet_metal",+ ),+ Box(+ "console_2",+ z,+ 28.0,+ 29.0,+ 38.0,+ 40.5,+ l1,+ l1 + 1.0,+ "BoothConsole",+ material="sheet_metal",+ ),+ ]+ # Bridge to the shuttle roof (grating) and the floor stair.+ out.boxes.append(+ Box(+ "bridge_shuttle",+ z,+ bx1,+ 46.0,+ 31.5,+ 34.0,+ l1 - CAT_T,+ l1,+ "BridgeGrating",+ sight=False,+ walk=True,+ material="catwalk_grating",+ piece_class="catwalk",+ )+ )+ out.ramps.append(Ramp("stair_booth_floor", z, 38.0, 39.6, 34.0, 42.0, l1, 0.0, "z"))+ out.lights += [+ Light("booth_a", z, 30.0, 37.0, l1 + 2.9, "rect", 4500.0, 1800.0, 7.0, source_size_m=1.0),+ Light("booth_b", z, 35.0, 37.0, l1 + 2.9, "rect", 4500.0, 1800.0, 7.0, source_size_m=1.0),+ ]+++# ---------------------------------------------------------------------------+# arena_shuttle: walkable gunship as the mid building+# ---------------------------------------------------------------------------+++def _shuttle(out: Layout) -> None:+ z = "arena_shuttle"+ l1 = LEVELS["L1"]+ sx0, sx1, sz0, sz1 = 46.0, 54.0, 15.0, 33.0+ hatch = (23.0, 25.0)+ hull = dict(zone=z, family="GunshipHull", material="armor_steel")+ out.boxes += [+ Box("hull_w_fore", x0=sx0, x1=sx0 + 0.4, z0=sz0, z1=hatch[0], h0=0.0, h1=l1, **hull),+ Box("hull_w_aft", x0=sx0, x1=sx0 + 0.4, z0=hatch[1], z1=sz1, h0=0.0, h1=l1, **hull),+ Box("hull_e_fore", x0=sx1 - 0.4, x1=sx1, z0=sz0, z1=hatch[0], h0=0.0, h1=l1, **hull),+ Box("hull_e_aft", x0=sx1 - 0.4, x1=sx1, z0=hatch[1], z1=sz1, h0=0.0, h1=l1, **hull),+ Box("nose", x0=sx0, x1=sx1, z0=sz0, z1=sz0 + 0.4, h0=0.0, h1=l1, **hull),+ Box(+ "roof",+ zone=z,+ x0=sx0,+ x1=sx1,+ z0=sz0,+ z1=sz1,+ h0=l1 - 0.4,+ h1=l1,+ family="GunshipRoof",+ walk=True,+ material="armor_steel",+ ),+ # Dorsal turret: cover on the roof, cuts the upper diagonals.+ Box(+ "turret",+ zone=z,+ x0=48.8,+ x1=51.2,+ z0=21.0,+ z1=25.5,+ h0=l1,+ h1=l1 + 2.2,+ family="GunshipTurret",+ material="armor_steel",+ ),+ ]+ # Interior bulkhead with breakable service panels (sheet metal): a choice to open a lane.+ out.boxes += [+ Box(+ "bulkhead_w",+ z,+ sx0 + 0.4,+ 49.0,+ 27.8,+ 28.0,+ 0.0,+ l1 - 0.4,+ "GunshipBulkhead",+ material="armor_steel",+ ),+ Box(+ "bulkhead_e",+ z,+ 51.0,+ sx1 - 0.4,+ 27.8,+ 28.0,+ 0.0,+ l1 - 0.4,+ "GunshipBulkhead",+ material="armor_steel",+ ),+ Box(+ "service_panel",+ z,+ 49.0,+ 51.0,+ 27.85,+ 27.85 + REF_THICKNESS_M["sheet_metal"],+ 0.0,+ 2.2,+ "GunshipServicePanel",+ material="sheet_metal",+ piece_class="wall_panel",+ ),+ ]+ # Engine nacelles outside the tail and ground cover around the pad.+ out.boxes += [+ Box(+ "nacelle_w",+ z,+ 43.8,+ 46.0,+ 28.0,+ 33.0,+ 0.4,+ 2.4,+ "GunshipNacelle",+ material="armor_steel",+ ),+ Box(+ "nacelle_e",+ z,+ 54.0,+ 56.2,+ 28.0,+ 33.0,+ 0.4,+ 2.4,+ "GunshipNacelle",+ material="armor_steel",+ ),+ Box("fuel_cart", z, 42.0, 44.4, 39.6, 44.0, 0.0, 2.4, "FuelCart", material="sheet_metal"),+ Box("crate_n_1", z, 44.0, 46.0, 6.8, 8.8, 0.0, 2.4, "CargoCrate", material="sheet_metal"),+ Box(+ "crate_n_2", z, 51.5, 53.5, 9.0, 11.0, 0.0, 1.2, "CargoCrateLow", material="sheet_metal"+ ),+ Box("barrier_s", z, 47.0, 52.0, 40.5, 41.1, 0.0, 1.1, "LowBarrier"),+ Box("crate_s", z, 56.0, 58.0, 38.6, 40.6, 0.0, 2.2, "CargoCrate", material="sheet_metal"),+ Box("crate_w_1", z, 30.0, 32.0, 23.0, 25.0, 0.0, 2.4, "CargoCrate", material="sheet_metal"),+ Box("lowwall_w", z, 33.6, 36.0, 28.4, 29.0, 0.0, 1.1, "LowBarrier"),+ ]+ out.lights += [+ Light("cabin_a", z, 50.0, 19.0, l1 - 0.5, "rect", 4500.0, 1200.0, 6.0, source_size_m=0.8),+ Light("cabin_b", z, 50.0, 30.0, l1 - 0.5, "rect", 4500.0, 1200.0, 6.0, source_size_m=0.8),+ ]+++# ---------------------------------------------------------------------------+# arena_canyon: container rows with destructible walls and 3.6 m aisles+# ---------------------------------------------------------------------------++CONTAINER_W = 2.4+CONTAINER_H = 3.0+AISLE = 3.6+ROW_X0 = (60.6, 60.6 + CONTAINER_W + AISLE, 60.6 + 2 * (CONTAINER_W + AISLE))+#: Containers per row as (z0, z1, roof walkable). Gaps between them are the cross alleys.+ROWS = (+ ((11.0, 17.0, True), (17.0, 23.0, True), (25.0, 31.0, False), (31.0, 37.0, False)),+ (+ (5.5, 11.0, False),+ (13.0, 19.0, False),+ (19.0, 25.0, False),+ (27.0, 33.0, True),+ (33.0, 39.0, True),+ ),+ (+ (5.5, 11.0, False),+ (11.0, 17.0, False),+ (19.0, 25.0, False),+ (27.0, 33.0, False),+ (35.0, 41.0, False),+ ),+)+++def _canyon(out: Layout) -> None:+ z = "arena_canyon"+ wt = REF_THICKNESS_M["container_wall"]+ for r, (x0, row) in enumerate(zip(ROW_X0, ROWS, strict=True), 1):+ x1 = x0 + CONTAINER_W+ for c, (z0, z1, roof_walk) in enumerate(row, 1):+ cid = f"r{r}c{c}"+ # Long walls break (container_wall); the frame and roof do not.+ out.boxes += [+ Box(+ f"{cid}_wall_w",+ z,+ x0,+ x0 + wt,+ z0,+ z1,+ 0.0,+ CONTAINER_H - 0.2,+ "ContainerWall",+ material="container_wall",+ piece_class="container_wall",+ ),+ Box(+ f"{cid}_wall_e",+ z,+ x1 - wt,+ x1,+ z0,+ z1,+ 0.0,+ CONTAINER_H - 0.2,+ "ContainerWall",+ material="container_wall",+ piece_class="container_wall",+ ),+ Box(+ f"{cid}_roof",+ z,+ x0,+ x1,+ z0,+ z1,+ CONTAINER_H - 0.2,+ CONTAINER_H,+ "ContainerRoof",+ walk=roof_walk,+ material="armor_steel",+ ),+ ]+ # Every second container has its doors shut at the north end: a dead+ # end that a charge opens.+ if c % 2 == 0:+ out.boxes.append(+ Box(+ f"{cid}_doors",+ z,+ x0,+ x1,+ z0,+ z0 + wt,+ 0.0,+ CONTAINER_H - 0.2,+ "ContainerDoors",+ material="container_wall",+ piece_class="container_wall",+ )+ )+ l1 = LEVELS["L1"]+ out.boxes.append(+ Box(+ "bridge_shuttle",+ z,+ 54.0,+ ROW_X0[0],+ 15.0,+ 17.0,+ l1 - CAT_T,+ l1,+ "BridgeGrating",+ sight=False,+ walk=True,+ material="catwalk_grating",+ piece_class="catwalk",+ )+ )+ r2x0 = ROW_X0[1]+ out.ramps.append(Ramp("stair_r2", z, r2x0, r2x0 + CONTAINER_W, 39.0, 43.6, l1, 0.0, "z"))+ for k, cz in enumerate((9.0, 21.0, 33.0), 1):+ for a, ax in enumerate(+ (ROW_X0[0] + CONTAINER_W + AISLE / 2, ROW_X0[1] + CONTAINER_W + AISLE / 2), 1+ ):+ out.lights.append(+ Light(f"aisle_{k}{a}", z, ax, cz, 7.5, "spot", 4300.0, 5000.0, 10.0, cone_deg=60.0)+ )+++# ---------------------------------------------------------------------------+# armoury: loadout room in the front band, station placements for WP16/WP18+# ---------------------------------------------------------------------------++ARMOURY = (77.0, 97.5, 47.2, 61.6)+++def _armoury(out: Layout) -> None:+ z = "armoury"+ x0, x1, z0, z1 = ARMOURY+ h = 4.5+ wall = dict(zone=z, family="ArmouryWall", layer="base")+ out.boxes += [+ Box("wall_n_w", x0=x0, x1=85.0, z0=z0, z1=z0 + 0.3, h0=0.0, h1=h, **wall),+ Box("wall_n_e", x0=88.0, x1=x1, z0=z0, z1=z0 + 0.3, h0=0.0, h1=h, **wall),+ Box("lintel_n", x0=85.0, x1=88.0, z0=z0, z1=z0 + 0.3, h0=2.6, h1=h, **wall),+ Box("wall_w", x0=x0, x1=x0 + 0.3, z0=z0, z1=z1, h0=0.0, h1=h, **wall),+ Box(+ "ceiling",+ zone=z,+ x0=x0,+ x1=x1,+ z0=z0,+ z1=z1,+ h0=h,+ h1=h + 0.3,+ family="ArmouryCeiling",+ layer="base",+ ),+ Box(+ "rack_e",+ zone=z,+ x0=96.7,+ x1=97.5,+ z0=50.0,+ z1=58.0,+ h0=0.0,+ h1=2.4,+ family="ArmouryRack",+ material="sheet_metal",+ layer="base",+ ),+ Box(+ "bench",+ zone=z,+ x0=83.0,+ x1=91.0,+ z0=56.5,+ z1=57.3,+ h0=0.0,+ h1=0.5,+ family="ArmouryBench",+ material="sheet_metal",+ layer="base",+ ),+ ]+ out.stations += [+ # The duel entry (parity S-17, D-04): WP16 owns the station class, WP18 the panel it opens.+ Station("armoury", "armoury", z, 87.0, 51.5, 0.0, 90.0, "ArmouryConsole", (1.6, 0.8, 1.2)),+ # Loadout display beside the rack: WP18 armoury view on a station screen.+ Station(+ "armoury_loadout",+ "armoury",+ z,+ 96.4,+ 54.0,+ 0.0,+ 180.0,+ "ArmouryLoadoutBoard",+ (0.2, 3.0, 2.0),+ ),+ ]+ out.lights += [+ Light("armoury_a", z, 82.0, 54.0, h - 0.1, "rect", 4500.0, 3000.0, 8.0, source_size_m=1.2),+ Light("armoury_b", z, 92.0, 54.0, h - 0.1, "rect", 4500.0, 3000.0, 8.0, source_size_m=1.2),+ ]+++# ---------------------------------------------------------------------------+# spawns: AVerseSpawnPoint sockets, at least 8, every pair 20 m path apart (A11.2)+# ---------------------------------------------------------------------------++SPAWNS = (+ Spawn("sp_nw_floor", "arena_catwalks", 26.0, 5.0, 0.0, 45.0),+ Spawn("sp_north_mid", "arena_shuttle", 48.0, 8.0, 0.0, 90.0),+ Spawn("sp_ne_canyon", "arena_canyon", 70.8, 6.0, 0.0, 90.0),+ Spawn("sp_e_canyon", "arena_canyon", 71.0, 40.0, 0.0, 270.0),+ Spawn("sp_south_mid", "arena_shuttle", 48.5, 43.0, 0.0, 270.0),+ Spawn("sp_booth", "arena_booth", 31.5, 40.5, LEVELS["L1"], 0.0),+ Spawn("sp_cat_west", "arena_catwalks", 26.2, 18.0, LEVELS["L2"], 90.0),+ Spawn("sp_shuttle_roof", "arena_shuttle", 50.0, 30.5, LEVELS["L1"], 270.0),+ Spawn("sp_cat_gantry", "arena_catwalks", 57.5, 37.2, LEVELS["L2"], 180.0),+)+++# ---------------------------------------------------------------------------+# cover rhythm: blockers placed with the flow tool (unreal_arena.flow) so that+# no unbroken sightline exceeds 40 m (A11.5). Hanging screens cut the upper+# diagonals, cover walls and crates the floor lanes, truss columns both.+# ---------------------------------------------------------------------------++#: (kind, centre x, centre z, along) - "x" or "z" is the long axis of a screen or wall.+COVER = (+ ("screen", 45.0, 28.0, "z"),+ ("screen", 55.0, 10.0, "z"),+ ("screen", 63.0, 30.0, "z"),+ ("wall", 63.0, 40.0, "z"),+ ("screen", 37.0, 22.0, "z"),+ ("screen", 63.0, 36.0, "z"),+ ("screen", 47.0, 10.0, "z"),+ ("screen", 67.0, 8.0, "x"),+ ("screen", 39.0, 18.0, "x"),+ ("column", 41.0, 30.0, ""),+ ("column", 59.0, 24.0, ""),+ ("wall", 47.0, 11.4, "z"),+ ("column", 65.0, 40.0, ""),+ ("screen", 57.0, 14.0, "x"),+ ("column", 47.0, 14.0, ""),+ ("screen", 65.0, 20.0, "z"),+ ("column", 43.0, 22.0, ""),+ ("wall", 59.0, 6.0, "z"),+ ("wall", 45.0, 38.0, "x"),+ ("column", 45.0, 18.0, ""),+ ("crate", 39.0, 8.0, ""),+ ("wall", 59.0, 40.0, "z"),+ ("screen", 49.0, 10.0, "z"),+ ("column", 53.0, 40.0, ""),+ ("column", 41.0, 40.0, ""),+ ("screen_high", 60.0, 17.75, "x"),+ ("wall", 37.0, 24.0, "z"),+ ("wall", 52.0, 37.0, "z"),+ ("screen", 66.0, 24.0, "x"),+ ("screen", 40.0, 22.0, "z"),+ ("screen", 61.0, 37.0, "z"),+ ("column", 55.0, 19.0, ""),+ ("column", 37.0, 27.0, ""),+ ("screen_high", 50.0, 29.0, "x"),+ ("column", 53.0, 8.0, ""),+ ("column", 41.0, 13.0, ""),+ ("wall", 34.0, 30.0, "x"),+ ("wall", 47.0, 39.0, "x"),+ ("screen", 42.0, 35.0, "x"),+ ("screen", 37.0, 30.0, "x"),+)+COVER_SIZES = {+ "screen": (6.0, 0.3, 3.6, 9.0),+ "screen_high": (6.0, 0.3, 5.0, 9.0),+ "wall": (4.0, 0.4, 0.0, 3.4),+ "crate": (2.4, 2.4, 0.0, 2.6),+ "column": (1.2, 1.2, 0.0, CEILING_H),+}+++def _cover_zone(kind: str, x: float) -> str:+ if kind == "column":+ return "shell"+ if kind.startswith("screen"):+ return "arena_catwalks"+ if x >= ROW_X0[0] - 0.5:+ return "arena_canyon"+ if x < 40.0:+ return "arena_booth"+ return "arena_shuttle"+++def _cover(out: Layout) -> None:+ family = {+ "screen": "HangingScreen",+ "screen_high": "HangingScreen",+ "wall": "CoverWall",+ "crate": "CargoCrate",+ "column": "TrussColumn",+ }+ material = {+ "screen": "armor_steel",+ "screen_high": "armor_steel",+ "wall": "concrete",+ "crate": "sheet_metal",+ "column": "concrete",+ }+ for k, (kind, cx, cz, along) in enumerate(COVER, 1):+ long_, short, h0, h1 = COVER_SIZES[kind]+ wx, wz = (long_, short) if along != "z" else (short, long_)+ if kind in ("crate", "column"):+ wx = wz = long_+ zone = _cover_zone(kind, cx)+ out.boxes.append(+ Box(+ f"cover_{kind.split('_')[0]}_{k:02d}",+ zone,+ cx - wx / 2,+ cx + wx / 2,+ cz - wz / 2,+ cz + wz / 2,+ h0,+ h1,+ family[kind],+ material=material[kind],+ layer="base" if kind == "column" else "arena",+ )+ )+++def build() -> Layout:+ out = Layout()+ _shell(out)+ _catwalks(out)+ _booth(out)+ _shuttle(out)+ _canyon(out)+ _armoury(out)+ _cover(out)+ out.spawns = list(SPAWNS)+ return outdiff --git a/art/verse/decks/hangar/unreal_arena/nav.py b/art/verse/decks/hangar/unreal_arena/nav.pynew file mode 100644index 0000000000..c696d49267--- /dev/null+++ b/art/verse/decks/hangar/unreal_arena/nav.py@@ -0,0 +1,169 @@+"""A 2.5D grid nav graph of the arena walk surfaces (numpy and scipy only).++The Unreal navmesh is built from the real collision (destruction.md 6.1);+this grid is the design-time stand-in the layout is checked against: the+same body (0.3 m radius, 1.8 m tall, 0.5 m step), the same walk surfaces,+and a graph whose shortest paths approximate navmesh path lengths to within+a cell. A11.1 and A11.2 read it, and so does the flow tool.+"""++from __future__ import annotations++import math+from dataclasses import dataclass++import numpy as np+from scipy.sparse import csr_matrix+from scipy.sparse.csgraph import connected_components, dijkstra++from . import layout as L++CELL_M = 0.5+RADIUS_M = 0.3+HEIGHT_M = 1.8+STEP_M = 0.5+MERGE_M = 0.3 # two surfaces closer than this in one column are one floor+EYE_M = 1.65+++@dataclass+class NavGraph:+ xs: np.ndarray # node x (plan m)+ zs: np.ndarray # node z+ hs: np.ndarray # node floor height+ matrix: csr_matrix # symmetric, edge weight = 3D step length+ labels: np.ndarray # connected component per node+ cell: float++ @property+ def count(self) -> int:+ return int(self.xs.shape[0])++ def islands(self) -> list[int]:+ """Node count per connected component, largest first."""+ return sorted(np.bincount(self.labels).tolist(), reverse=True)++ def level_of(self, h: float) -> str:+ for name, lo, hi in L.LEVEL_BANDS:+ if lo <= h < hi:+ return name+ return "other"++ def level_shares(self) -> dict[str, float]:+ names = [self.level_of(float(h)) for h in self.hs]+ total = len(names)+ return {name: names.count(name) / total for name, _, _ in L.LEVEL_BANDS}++ def area_m2(self) -> float:+ return self.count * self.cell * self.cell++ def extent(self) -> tuple[float, float, float, float]:+ half = self.cell / 2+ return (+ float(self.xs.min()) - half,+ float(self.xs.max()) + half,+ float(self.zs.min()) - half,+ float(self.zs.max()) + half,+ )++ def nearest(self, x: float, z: float, h: float) -> int:+ d = (self.xs - x) ** 2 + (self.zs - z) ** 2 + (2.0 * (self.hs - h)) ** 2+ return int(np.argmin(d))++ def eyes(self) -> np.ndarray:+ return np.stack([self.xs, self.zs, self.hs + EYE_M], axis=1)++ def distances_from(self, sources: list[int]) -> np.ndarray:+ return dijkstra(self.matrix, directed=False, indices=sources)++ def path(self, source: int, target: int) -> list[int]:+ _, pred = dijkstra(self.matrix, directed=False, indices=source, return_predecessors=True)+ if pred[target] < 0 and target != source:+ return []+ out = [target]+ while out[-1] != source:+ out.append(int(pred[out[-1]]))+ return out[::-1]+++def _surfaces_at(x: float, z: float, walks: list, ramps: list) -> list[float]:+ heights = [b.h1 for b in walks if b.x0 <= x <= b.x1 and b.z0 <= z <= b.z1]+ heights += [r.height_at(x, z) for r in ramps if r.x0 <= x <= r.x1 and r.z0 <= z <= r.z1]+ heights.sort(reverse=True)+ merged: list[float] = []+ for h in heights:+ if not merged or merged[-1] - h > MERGE_M:+ merged.append(h)+ return merged+++def _blocked(x: float, z: float, h: float, solids: list, ramps: list) -> bool:+ lo, hi = h + 0.05, h + HEIGHT_M+ r = RADIUS_M+ for b in solids:+ if b.walk and b.h1 <= h + STEP_M:+ continue # a walk surface a body can step onto is floor, not a wall+ if b.x0 - r < x < b.x1 + r and b.z0 - r < z < b.z1 + r and b.h0 < hi and b.h1 > lo:+ return True+ for ramp in ramps:+ if ramp.x0 < x < ramp.x1 and ramp.z0 < z < ramp.z1:+ rh = ramp.height_at(x, z)+ if lo < rh < hi:+ return True+ return False+++def build(layout: L.Layout, cell: float = CELL_M, bounds=L.ARENA) -> NavGraph:+ """Nodes on every walk surface inside `bounds`, linked to their 8 neighbours."""+ x0, x1, z0, z1 = bounds+ walks = [b for b in layout.boxes if b.walk]+ solids = [b for b in layout.boxes if b.solid and not b.walk]+ # Walk boxes are solid for every surface but their own top.+ solids_all = solids + walks+ ramps = layout.ramps+ nx, nz = int(round((x1 - x0) / cell)), int(round((z1 - z0) / cell))+ columns: dict[tuple[int, int], list[tuple[float, int]]] = {}+ xs, zs, hs = [], [], []+ for ix in range(nx):+ x = x0 + (ix + 0.5) * cell+ for iz in range(nz):+ z = z0 + (iz + 0.5) * cell+ for h in _surfaces_at(x, z, walks, ramps):+ if _blocked(x, z, h, solids_all, ramps):+ continue+ columns.setdefault((ix, iz), []).append((h, len(xs)))+ xs.append(x)+ zs.append(z)+ hs.append(h)+ rows, cols, weights = [], [], []++ def link(a: tuple[int, int], b: tuple[int, int], horiz: float) -> None:+ for ha, na in columns.get(a, ()):+ for hb, nb in columns.get(b, ()):+ if abs(ha - hb) <= STEP_M:+ rows.append(na)+ cols.append(nb)+ weights.append(math.hypot(horiz, ha - hb))++ def has_floor(c: tuple[int, int], h: float) -> bool:+ return any(abs(hc - h) <= STEP_M for hc, _ in columns.get(c, ()))++ for (ix, iz), nodes in columns.items():+ link((ix, iz), (ix + 1, iz), cell)+ link((ix, iz), (ix, iz + 1), cell)+ for dx in (-1, 1):+ # A diagonal step needs both orthogonal cells free: no corner cutting.+ a, b, d = (ix + dx, iz), (ix, iz + 1), (ix + dx, iz + 1)+ for h, n in nodes:+ if not (has_floor(a, h) and has_floor(b, h)):+ continue+ for hd, nd in columns.get(d, ()):+ if abs(hd - h) <= STEP_M:+ rows.append(n)+ cols.append(nd)+ weights.append(math.hypot(cell * math.sqrt(2.0), hd - h))+ count = len(xs)+ matrix = csr_matrix((weights, (rows, cols)), shape=(count, count))+ matrix = matrix.maximum(matrix.T)+ _, labels = connected_components(matrix, directed=False)+ return NavGraph(np.array(xs), np.array(zs), np.array(hs), matrix.tocsr(), labels, cell)diff --git a/art/verse/decks/hangar/unreal_arena/placements.py b/art/verse/decks/hangar/unreal_arena/placements.pynew file mode 100644index 0000000000..aa7bce7558--- /dev/null+++ b/art/verse/decks/hangar/unreal_arena/placements.py@@ -0,0 +1,235 @@+"""`verse.placement/1` documents for the WP11 hangar zones (art-pipeline 4).++Graybox stage: every box of `layout` becomes one placement of its family's+graybox mesh, `SM_<Family>` (a 1 m cube, pivot at the bottom centre) scaled+to the box, or `GC_<Family>` with its proxies for the destructibles. The art+pass swaps the meshes behind the same ids, so actor files keep their names.+Spawns and lights are sockets; stations are placements with a `station`.+"""++from __future__ import annotations++import hashlib+import math+from pathlib import Path++from . import layout as L++PACKAGE = Path(__file__).resolve().parent+REPO = PACKAGE.parents[4]+BUILDER = "art/verse/decks/hangar/unreal_arena/layout.py"+GENERATOR = {"script": "unreal_arena_build.py", "version": "1", "blender": "0.0.0"}+DESTRUCTIBLE_CLASS = "/Script/VerseDestruction.VerseDestructible"+STATES = ["Intact", "Damaged", "Holed", "Breached", "Destroyed", "Repairing"]+PROXY_STATES = ["Intact", "Holed", "Breached", "Destroyed"]+LAYERS = {"base": "DL_Hangar_Base", "day": "DL_Hangar_Day", "arena": "DL_Hangar_Arena"}+FOLDERS = {+ "shell": "Shell",+ "arena_canyon": "ArenaCanyon",+ "arena_shuttle": "ArenaShuttle",+ "arena_booth": "ArenaBooth",+ "arena_catwalks": "ArenaCatwalks",+ "armoury": "Armoury",+}+++def cm(v: float) -> float:+ return round(v * 100.0, 3)+++def yaw_quat(heading_deg: float, pitch_deg: float = 0.0) -> list[float]:+ """Unreal [x, y, z, w] of FRotator(pitch, yaw, 0) (the engine's own formula)."""+ sp, cp = math.sin(math.radians(pitch_deg) / 2), math.cos(math.radians(pitch_deg) / 2)+ sy, cy = math.sin(math.radians(heading_deg) / 2), math.cos(math.radians(heading_deg) / 2)+ return [round(v, 7) + 0.0 for v in (sp * sy, -sp * cy, cp * sy, cp * cy)]+++def asset(zone: str, name: str) -> str:+ return f"/Game/Verse/Decks/Hangar/{FOLDERS[zone]}/{name}.{name}"+++def source_hash() -> str:+ h = hashlib.sha256()+ for name in sorted(p.name for p in PACKAGE.glob("*.py")):+ h.update(name.encode())+ h.update((PACKAGE / name).read_bytes().replace(b"\r\n", b"\n"))+ return h.hexdigest()+++def _box_placement(box: L.Box) -> dict:+ sx, sz, sh = box.size+ destructible = None+ collision = "Verse_Architecture"+ if box.piece_class is not None:+ piece = f"GC_{box.family}"+ material, health, repair = L.PIECE_CLASSES[box.piece_class]+ destructible = {+ "actor_class": DESTRUCTIBLE_CLASS,+ "penetration_material": material,+ "health": health,+ "states": STATES,+ "proxies": {s: asset(box.zone, f"SM_{box.family}_Proxy_{s}") for s in PROXY_STATES},+ "repair_s": repair,+ }+ collision = "Verse_Destructible"+ else:+ piece = f"SM_{box.family}"+ if not box.solid:+ collision = "Verse_NoCollision"+ elif not box.sight:+ collision = "Verse_Prop"+ nav = "walk" if box.walk else ("block" if box.solid else "none")+ return {+ "id": box.id,+ "piece": piece,+ "asset": asset(box.zone, piece),+ "location": [cm((box.x0 + box.x1) / 2), cm((box.z0 + box.z1) / 2), cm(box.h0)],+ "rotation": [0.0, 0.0, 0.0, 1.0],+ "scale": [round(sx, 6), round(sz, 6), round(sh, 6)],+ "room": None,+ "nav": nav,+ "mobility": "movable" if destructible else "static",+ "data_layer": LAYERS[box.layer],+ "collision": collision,+ "destructible": destructible,+ "station": None,+ "owner": L.OWNER,+ "tags": [f"Verse.Material.{box.material}"],+ }+++def _ramp_placement(ramp: L.Ramp) -> dict:+ sx, sz = ramp.x1 - ramp.x0, ramp.z1 - ramp.z0+ rise = abs(ramp.h_end - ramp.h_start)+ # The stair mesh rises along its local +X; turn it so it climbs the way the ramp does.+ if ramp.axis == "x":+ heading = 0.0 if ramp.h_end > ramp.h_start else 180.0+ length, width = sx, sz+ else:+ heading = 90.0 if ramp.h_end > ramp.h_start else 270.0+ length, width = sz, sx+ return {+ "id": ramp.id,+ "piece": f"SM_{ramp.family}",+ "asset": asset(ramp.zone, f"SM_{ramp.family}"),+ "location": [+ cm((ramp.x0 + ramp.x1) / 2),+ cm((ramp.z0 + ramp.z1) / 2),+ cm(min(ramp.h_start, ramp.h_end)),+ ],+ "rotation": yaw_quat(heading),+ "scale": [round(length, 6), round(width, 6), round(rise, 6)],+ "room": None,+ "nav": "walk",+ "mobility": "static",+ "data_layer": LAYERS[ramp.layer],+ "collision": "Verse_Architecture",+ "destructible": None,+ "station": None,+ "owner": L.OWNER,+ }+++def _station_placement(st: L.Station) -> dict:+ sx, sz, sh = st.size+ return {+ "id": st.id,+ "piece": f"SM_{st.family}",+ "asset": asset(st.zone, f"SM_{st.family}"),+ "location": [cm(st.x), cm(st.z), cm(st.h)],+ "rotation": yaw_quat(st.heading_deg),+ "scale": [sx, sz, sh],+ "room": "armoury" if st.zone == "armoury" else None,+ "nav": "block",+ "mobility": "static",+ "data_layer": "DL_Hangar_Base",+ "collision": "Verse_Prop",+ "destructible": None,+ "station": {"id": st.id, "kind": st.kind},+ "owner": L.OWNER,+ }+++def _light_socket(light: L.Light) -> dict:+ data = {+ "type": light.type,+ "kelvin": light.kelvin,+ "intensity_lm": light.intensity_lm,+ "attenuation_cm": cm(light.attenuation_m),+ "shadows": True,+ }+ if light.cone_deg is not None:+ data["cone_deg"] = light.cone_deg+ if light.source_size_m is not None:+ data["source_size_cm"] = cm(light.source_size_m)+ return {+ "id": f"light__{light.id}",+ "kind": "light",+ "location": [cm(light.x), cm(light.z), cm(light.h)],+ "rotation": yaw_quat(0.0, light.pitch_deg),+ "room": None,+ "station": None,+ "light": data,+ }+++def _spawn_socket(spawn: L.Spawn) -> dict:+ return {+ "id": f"spawn__{spawn.id}",+ "kind": "spawn",+ "location": [cm(spawn.x), cm(spawn.z), cm(spawn.h)],+ "rotation": yaw_quat(spawn.heading_deg),+ "room": None,+ "station": None,+ "spawn": {"team": "any", "duel": True},+ "props": {"probe_heights_m": "0.3,1.0,1.65", "spawn_id": spawn.id},+ }+++def _bounds(points: list[list[float]]) -> dict:+ lo = [min(p[i] for p in points) - 1.0 for i in range(3)]+ hi = [max(p[i] for p in points) + 1.0 for i in range(3)]+ return {"min": [round(v, 3) for v in lo], "max": [round(v, 3) for v in hi]}+++def documents(layout: L.Layout) -> dict[str, dict]:+ """zone -> verse.placement/1 document."""+ digest = source_hash()+ out = {}+ for zone in L.ZONES:+ placements = [_box_placement(b) for b in layout.zone_boxes(zone)]+ placements += [_ramp_placement(r) for r in layout.zone_ramps(zone)]+ placements += [_station_placement(s) for s in layout.stations if s.zone == zone]+ sockets = [_light_socket(li) for li in layout.lights if li.zone == zone]+ sockets += [_spawn_socket(s) for s in layout.spawns if s.zone == zone]+ rooms = []+ if zone == "armoury":+ x0, x1, z0, z1 = L.ARMOURY+ rooms.append(+ {+ "id": "armoury",+ "name": "Armoury",+ "polygon_cm": [+ [cm(x0), cm(z0)],+ [cm(x1), cm(z0)],+ [cm(x1), cm(z1)],+ [cm(x0), cm(z1)],+ ],+ "z_cm": 0.0,+ "main": False,+ }+ )+ points = [p["location"] for p in placements] + [s["location"] for s in sockets]+ out[zone] = {+ "schema": "verse.placement/1",+ "deck": L.DECK,+ "zone": zone,+ "bounds_cm": _bounds(points),+ "level": "/Game/Verse/Decks/Hangar/LV_Hangar",+ "source": {"builder": BUILDER, "sha256": digest},+ "generator": dict(GENERATOR),+ "placements": placements,+ "sockets": sockets,+ "rooms": rooms,+ }+ return outdiff --git a/art/verse/decks/hangar/unreal_arena_build.py b/art/verse/decks/hangar/unreal_arena_build.pynew file mode 100644index 0000000000..2fb6bbde01--- /dev/null+++ b/art/verse/decks/hangar/unreal_arena_build.py@@ -0,0 +1,160 @@+"""Build the WP11 hangar arena outputs from `unreal_arena/layout.py`.++ python art/verse/decks/hangar/unreal_arena_build.py # placements + flow report+ python art/verse/decks/hangar/unreal_arena_build.py --quick # coarser flow sampling+ python art/verse/decks/hangar/unreal_arena_build.py --bot-log runs.jsonl++Writes, all under the ignored proof folder+`unreal/Verse/Saved/Harness/proof/WP11/` (work-packages.md 0.4):++* `placements/hangar/<zone>.placement.json`: the six WP11 zones in canonical+ `verse.placement/1` form. They move to `unreal/Verse/Art/Placements/hangar/`+ in the same PR that imports their graybox meshes, because the static gate+ refuses placements whose assets have no import record (art-pipeline 14).+* `look.json`: haze and post settings of WP11.12 for the level owner.+* `flow.json`: the WP11.11 flow report (sightlines, spawn spacing, time to+ contact; `--bot-log` adds the harness bot runs).+* `plan_<level>.png`: top-down plan per level (needs matplotlib; skipped without).++Pure Python, no Blender and no Unreal, so it needs no machine lock.+"""++from __future__ import annotations++import argparse+import json+import sys+from pathlib import Path++HERE = Path(__file__).resolve().parent+REPO = HERE.parents[3]+sys.path.insert(0, str(HERE))+sys.path.insert(0, str(REPO / "art" / "verse"))++from lib import placement as placement_lib # noqa: E402+from unreal_arena import ( # noqa: E402+ flow,+ nav,+ placements, # noqa: E402+)+from unreal_arena import layout as L # noqa: E402++PROOF = REPO / "unreal" / "Verse" / "Saved" / "Harness" / "proof" / "WP11"+++def write_placements(lay: L.Layout, out_dir: Path) -> list[Path]:+ written = []+ for zone, doc in placements.documents(lay).items():+ path = out_dir / "hangar" / f"{zone}.placement.json"+ placement_lib.write(path, doc)+ errors = placement_lib.validate_file(path)+ if errors:+ raise SystemExit(f"{path}: " + "; ".join(errors))+ written.append(path)+ return written+++def plot_levels(lay: L.Layout, graph: nav.NavGraph, out_dir: Path) -> list[Path]:+ try:+ import matplotlib++ matplotlib.use("Agg")+ import matplotlib.pyplot as plt+ from matplotlib.patches import Rectangle+ except ImportError:+ return []+ colours = {+ "shell": "#5b5b5b",+ "arena_canyon": "#8a6a2f",+ "arena_shuttle": "#4f5a63",+ "arena_booth": "#6b4a3a",+ "arena_catwalks": "#7a7a50",+ "armoury": "#3d3d3d",+ }+ out = []+ for name, lo, hi in L.LEVEL_BANDS:+ fig, ax = plt.subplots(figsize=(10, 8.4), dpi=110)+ ax.set_facecolor("#141414")+ mask = [(lo <= h < hi) for h in graph.hs]+ xs = [x for x, m in zip(graph.xs, mask, strict=True) if m]+ zs = [z for z, m in zip(graph.zs, mask, strict=True) if m]+ ax.scatter(xs, zs, s=1.5, c="#c9a227", alpha=0.7, linewidths=0, zorder=3)+ for b in lay.boxes:+ if b.h1 <= lo or b.h0 >= hi + 2.0 or (b.walk and b.h1 <= lo + 1.5):+ continue+ if (+ b.x1 < L.ARENA[0] - 3+ or b.x0 > L.ARENA[1] + 3+ or b.z1 < L.ARENA[2] - 3+ or b.z0 > L.ARENA[3] + 3+ ):+ continue+ face = colours[b.zone] if b.sight else "none"+ edge = "#d0d0d0" if b.piece_class else "#9a9a9a"+ ax.add_patch(+ Rectangle(+ (b.x0, b.z0),+ b.x1 - b.x0,+ b.z1 - b.z0,+ facecolor=face,+ edgecolor=edge,+ linewidth=0.5,+ alpha=0.85,+ )+ )+ for s in lay.spawns:+ if lo <= s.h < hi:+ ax.plot(s.x, s.z, marker="o", color="#b3261e", markersize=6)+ ax.annotate(+ s.id,+ (s.x, s.z),+ color="#e0e0e0",+ fontsize=6,+ xytext=(3, 3),+ textcoords="offset points",+ )+ ax.set_xlim(L.ARENA[0] - 2, L.ARENA[1] + 2)+ ax.set_ylim(L.ARENA[3] + 2, L.ARENA[2] - 2) # plan z grows toward the near wall: down+ ax.set_aspect("equal")+ ax.set_title(+ f"Hangar arena graybox, level {name} (h {lo:g}..{hi:g} m): nav dots, boxes, spawns",+ color="#e0e0e0",+ fontsize=9,+ )+ ax.tick_params(colors="#9a9a9a", labelsize=7)+ fig.patch.set_facecolor("#0c0c0c")+ path = out_dir / f"plan_{name}.png"+ fig.savefig(path, facecolor=fig.get_facecolor())+ plt.close(fig)+ out.append(path)+ return out+++def main(argv: list[str] | None = None) -> int:+ ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])+ ap.add_argument("--quick", action="store_true", help="coarser sampling for a fast check")+ ap.add_argument("--bot-log", type=Path, help="harness time-to-contact log (JSON lines)")+ ap.add_argument("--out", type=Path, default=PROOF)+ args = ap.parse_args(argv)++ lay = L.build()+ graph = nav.build(lay)+ args.out.mkdir(parents=True, exist_ok=True)+ files = write_placements(lay, args.out / "placements")+ report = flow.report(graph, lay, quick=args.quick, bot_log=args.bot_log)+ (args.out / "flow.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")+ look = {"schema": "verse.hangar-look/1", "owner": L.OWNER, "haze": L.HAZE, "post": L.POST}+ (args.out / "look.json").write_text(json.dumps(look, indent=2) + "\n", encoding="utf-8")+ plots = plot_levels(lay, graph, args.out)+ print(f"placements: {len(files)} zones -> {args.out / 'placements'}")+ print(+ f"flow: longest sightline {report['sightlines']['longest_m']} m, "+ f"spawn min path {report['spawns']['min_path_m']} m, "+ f"time to contact median {report['time_to_contact']['median_s']} s"+ )+ print(f"plans: {len(plots)}")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/art/verse/kit/calib.py b/art/verse/kit/calib.pynew file mode 100644index 0000000000..237aa65f5b--- /dev/null+++ b/art/verse/kit/calib.py@@ -0,0 +1,71 @@+"""Calibration assets of the `fbx-ue/1` export settings (art-pipeline 6.1).++`SM_Calib_Axes` is an asymmetric arrow: a 20 cm hub, a long arm toward +X,+a short arm toward +Y, a tall arm toward +Z, and one 45 degree chamfer on the+top edge of the +X tip. No rotation can map it onto itself or its mirror, so+its bounds alone tell whether units, axes and handedness came through right.++`SK_Calib_Rig` is a small armature (`Root` along +Y with roll 0, so its rest+rotation is identity in Unreal; `Calib_Arm` toward +X,+`Calib_Side` toward +Y, each with an end bone at its tip) skinned to a small+box per bone. The import check compares every bone's rest position with+`unreal/Verse/Art/space_vectors.json`.++The numbers below are the contract of the calibration: the vector file holds+the same values converted to Unreal space; change both together and rerun+`python scripts/unreal/import_art.py calib`.+"""++from __future__ import annotations++from lib import kit++MATERIAL = "M_Struct_Gunmetal"++HUB = 0.1 # half size of the hub cube, metres+ARM = 0.05 # half thickness of every arm+X_TIP = 1.0+Y_TIP = 0.5+Z_TIP = 0.8+CHAMFER = 0.05 # 45 degree cut on the top edge of the +X tip++#: Rig bones: (name, parent, head, tail) in Blender metres.+RIG_BONES = (+ ("Root", None, (0.0, 0.0, 0.0), (0.0, 0.2, 0.0)),+ ("Calib_Arm", "Root", (0.0, 0.0, 0.5), (0.4, 0.0, 0.5)),+ ("Calib_Side", "Root", (0.0, 0.0, 0.5), (0.0, 0.25, 0.5)),+ ("Calib_ArmEnd", "Calib_Arm", (0.4, 0.0, 0.5), (0.5, 0.0, 0.5)),+ ("Calib_SideEnd", "Calib_Side", (0.0, 0.25, 0.5), (0.0, 0.35, 0.5)),+)+++ "SM_Calib_Axes",+ dims=(X_TIP + HUB, Y_TIP + HUB, Z_TIP),+ nav="none",+)+def calib_axes() -> None:+ """Asymmetric axis arrow used to calibrate the Blender-to-Unreal export."""+ mb = kit.MeshBuilder()+ mb.box((-HUB, -HUB, 0.0), (HUB, HUB, 2 * HUB), MATERIAL)+ zc = HUB # arm centre height+ # +X arm with the chamfer on its top tip edge (profile in XZ, extruded along Y).+ mb.prism_y(+ [+ (HUB, zc - ARM),+ (X_TIP, zc - ARM),+ (X_TIP, zc + ARM - CHAMFER),+ (X_TIP - CHAMFER, zc + ARM),+ (HUB, zc + ARM),+ ],+ -ARM,+ ARM,+ MATERIAL,+ )+ mb.box((-ARM, HUB, zc - ARM), (ARM, Y_TIP, zc + ARM), MATERIAL)+ mb.box((-ARM, -ARM, 2 * HUB), (ARM, ARM, Z_TIP), MATERIAL)+ mb.build("SM_Calib_Axes_body", bevel_width=0.0)+++def build_rig_marker() -> None:+ """Source marker of `SK_Calib_Rig`: built by `lib.unreal_export.build_rig` from `RIG_BONES`."""diff --git a/art/verse/lib/placement.py b/art/verse/lib/placement.pynew file mode 100644index 0000000000..2ec2313042--- /dev/null+++ b/art/verse/lib/placement.py@@ -0,0 +1,299 @@+"""`verse.placement/1` documents: ids, canonical form and validation.++Pure Python (no bpy, no unreal), shared by the Blender export, the static+check `scripts/unreal/check_art_text.py` and pytest. The format is defined in+docs/verse/unreal/contracts/art-pipeline.md section 4; the JSON Schema is+`art/verse/schema/placement.schema.json`. This module adds the rules a schema+cannot express: unique ids, origins inside the zone box, unit quaternions,+room references, level and data-layer names that match the deck, and the+destructible and mobility rules of sections 4.2 and 5.+"""++from __future__ import annotations++import json+import math+import re+from collections.abc import Iterable, Mapping, Sequence+from pathlib import Path+from typing import Any++SCHEMA_ID = "verse.placement/1"+SCHEMA_PATH = Path(__file__).resolve().parents[1] / "schema" / "placement.schema.json"++ID_SNAP_CM = 15.0+ID_SNAP_DEG = 1.0+LOCATION_DIGITS = 3 # 0.001 cm+QUAT_DIGITS = 7+SCALE_DIGITS = 6+MAX_FILE_BYTES = 2 * 1024 * 1024 # art-pipeline 10.4+UNIT_QUAT_TOLERANCE = 1e-4++#: Destructible proxy states every destructible must provide (art-pipeline 5).+REQUIRED_PROXY_STATES = ("Intact", "Holed", "Breached", "Destroyed")+#: Data layers allowed outside `DL_<Deck>_Base` (VerseDecks day/arena switch).+HANGAR_LAYERS = ("DL_Hangar_Day", "DL_Hangar_Arena")++_ID_SAFE = re.compile(r"[^a-z0-9_]+")+++def deck_title(deck: str) -> str:+ """`engineering` -> `Engineering`; `ops_deck` -> `OpsDeck` (folder and level case)."""+ return "".join(part.capitalize() for part in deck.split("_"))+++def level_path(deck: str) -> str:+ title = deck_title(deck)+ return f"/Game/Verse/Decks/{title}/LV_{title}"+++def base_layer(deck: str) -> str:+ return f"DL_{deck_title(deck)}_Base"+++def asset_name_of(object_path: str) -> str:+ """`/Game/Verse/Kit/SM_Wall_480.SM_Wall_480` -> `SM_Wall_480`."""+ return object_path.rsplit("/", 1)[-1].split(".", 1)[0]+++def sanitize_id(raw: str) -> str:+ """Builder ids become placement ids: lower case, `[a-z0-9_]` only."""+ cleaned = _ID_SAFE.sub("_", raw.lower()).strip("_")+ if not cleaned:+ raise ValueError(f"id {raw!r} has no usable characters")+ return cleaned+++def _id_number(value: float) -> str:+ n = int(round(value))+ return f"m{-n}" if n < 0 else str(n)+++def auto_id(piece: str, location_cm: Sequence[float], yaw_deg: float) -> str:+ """`<piece lower>_<x>_<y>_<z>_<yaw>`, snapped to 15 cm and 1 degree.++ Negative numbers are written `m<n>` because ids allow `[a-z0-9_]` only.+ """+ snapped = [ID_SNAP_CM * round(float(v) / ID_SNAP_CM) for v in location_cm]+ yaw = (ID_SNAP_DEG * round(float(yaw_deg) / ID_SNAP_DEG)) % 360.0+ parts = [sanitize_id(piece), *(_id_number(v) for v in snapped), _id_number(yaw) or "0"]+ return "_".join(parts)+++def unique_ids(ids: Iterable[str]) -> list[str]:+ """Duplicates get `_2`, `_3`, ... in order of appearance."""+ seen: dict[str, int] = {}+ taken = set()+ out = []+ for raw in ids:+ count = seen.get(raw, 0) + 1+ seen[raw] = count+ candidate = raw if count == 1 else f"{raw}_{count}"+ while candidate in taken:+ count += 1+ seen[raw] = count+ candidate = f"{raw}_{count}"+ taken.add(candidate)+ out.append(candidate)+ return out+++def yaw_from_quat_xyzw(quat: Sequence[float]) -> float:+ """Yaw in degrees of an [x, y, z, w] quaternion (rotation about Z part)."""+ x, y, z, w = (float(v) for v in quat)+ return math.degrees(math.atan2(2.0 * (w * z + x * y), 1.0 - 2.0 * (y * y + z * z)))+++def _round_list(values: Sequence[float], digits: int) -> list[float]:+ out = []+ for value in values:+ rounded = round(float(value), digits)+ out.append(0.0 if rounded == 0 else rounded)+ return out+++def canonical(doc: Mapping[str, Any]) -> dict[str, Any]:+ """Return a copy with rounded numbers and arrays in stable order (by id)."""+ out = json.loads(json.dumps(doc))+ for item in out.get("placements", []):+ item["location"] = _round_list(item["location"], LOCATION_DIGITS)+ item["rotation"] = _round_list(item["rotation"], QUAT_DIGITS)+ item["scale"] = _round_list(item["scale"], SCALE_DIGITS)+ if "tags" in item:+ item["tags"] = sorted(item["tags"])+ for item in out.get("sockets", []):+ item["location"] = _round_list(item["location"], LOCATION_DIGITS)+ item["rotation"] = _round_list(item["rotation"], QUAT_DIGITS)+ for room in out.get("rooms", []):+ room["polygon_cm"] = [_round_list(p, LOCATION_DIGITS) for p in room["polygon_cm"]]+ bounds = out.get("bounds_cm")+ if isinstance(bounds, dict):+ for key in ("min", "max"):+ if key in bounds:+ bounds[key] = _round_list(bounds[key], LOCATION_DIGITS)+ for key in ("placements", "sockets", "rooms"):+ if isinstance(out.get(key), list):+ out[key].sort(key=lambda entry: str(entry.get("id", "")))+ return out+++def dumps(doc: Mapping[str, Any]) -> str:+ """Canonical text: sorted keys, 2-space indent, LF, trailing newline."""+ return json.dumps(canonical(doc), indent=2, sort_keys=True, ensure_ascii=True) + "\n"+++def write(path: Path, doc: Mapping[str, Any]) -> bool:+ """Write `doc` canonically; return True when the file changed."""+ text = dumps(doc)+ if path.is_file() and path.read_text(encoding="utf-8") == text:+ return False+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_bytes(text.encode("utf-8"))+ return True+++# --------------------------------------------------------------------------+# Validation+# --------------------------------------------------------------------------+++def _schema_validator():+ import jsonschema++ schema = json.loads(SCHEMA_PATH.read_text(encoding="utf-8"))+ jsonschema.Draft202012Validator.check_schema(schema)+ return jsonschema.Draft202012Validator(schema)+++def _path_of(error) -> str:+ parts = [str(p) for p in error.absolute_path]+ return "/".join(parts) or "<root>"+++def schema_errors(doc: Any) -> list[str]:+ validator = _schema_validator()+ return [+ f"{_path_of(e)}: {e.message}"+ for e in sorted(validator.iter_errors(doc), key=lambda e: list(e.absolute_path))+ ]+++def _inside(point: Sequence[float], lo: Sequence[float], hi: Sequence[float]) -> bool:+ return all(a - 1e-6 <= p <= b + 1e-6 for p, a, b in zip(point, lo, hi, strict=True))+++def _dupes(values: Sequence[str]) -> list[str]:+ return sorted({v for v in values if values.count(v) > 1})+++def _quat_norm_error(quat: Sequence[float]) -> float:+ return abs(math.sqrt(sum(float(v) * float(v) for v in quat)) - 1.0)+++def semantic_errors(+ doc: Mapping[str, Any],+ *,+ path: Path | None = None,+ known_assets: set[str] | None = None,+) -> list[str]:+ """Rules beyond the schema. Assumes `schema_errors(doc)` is empty."""+ errors: list[str] = []+ deck, zone = doc["deck"], doc["zone"]+ if path is not None:+ if path.name != f"{zone}.placement.json":+ errors.append(f"file name must be {zone}.placement.json")+ if path.parent.name != deck:+ errors.append(f"file must live in Placements/{deck}/")+ size = path.stat().st_size if path.is_file() else 0+ if size > MAX_FILE_BYTES:+ errors.append(f"file is {size} bytes, budget {MAX_FILE_BYTES} (art-pipeline 10.4)")+ if doc["level"] != level_path(deck):+ errors.append(f"level must be {level_path(deck)}")+ lo, hi = doc["bounds_cm"]["min"], doc["bounds_cm"]["max"]+ if not all(a < b for a, b in zip(lo, hi, strict=True)):+ errors.append("bounds_cm: min must be below max on every axis")++ rooms = [room["id"] for room in doc["rooms"]]+ errors += [f"rooms: duplicate id {rid!r}" for rid in _dupes(rooms)]+ room_set = set(rooms)+ allowed_layers = {base_layer(deck)}+ if deck == "hangar":+ allowed_layers.update(HANGAR_LAYERS)++ ids = [p["id"] for p in doc["placements"]]+ errors += [f"placements: duplicate id {i!r}" for i in _dupes(ids)]+ for item in doc["placements"]:+ where = f"placements/{item['id']}"+ if asset_name_of(item["asset"]) != item["piece"]:+ errors.append(f"{where}: asset {item['asset']} is not the piece {item['piece']}")+ object_name = item["asset"].rsplit(".", 1)[-1]+ if object_name != item["piece"]:+ errors.append(f"{where}: object path must end in .{item['piece']}")+ if known_assets is not None and item["asset"] not in known_assets:+ errors.append(f"{where}: unknown asset {item['asset']} (no import record)")+ if not _inside(item["location"], lo, hi):+ errors.append(f"{where}: origin {item['location']} outside bounds_cm")+ if _quat_norm_error(item["rotation"]) > UNIT_QUAT_TOLERANCE:+ errors.append(f"{where}: rotation is not a unit quaternion")+ if item["room"] is not None and item["room"] not in room_set:+ errors.append(f"{where}: room {item['room']!r} is not in rooms[]")+ if item["data_layer"] not in allowed_layers:+ layers = sorted(allowed_layers)+ errors.append(f"{where}: data_layer {item['data_layer']} not in {layers}")+ destructible = item["destructible"]+ if destructible is not None:+ if item["mobility"] != "movable":+ errors.append(f"{where}: a destructible must be movable")+ if item["collision"] != "Verse_Destructible":+ errors.append(f"{where}: a destructible uses collision Verse_Destructible")+ missing = [s for s in REQUIRED_PROXY_STATES if s not in destructible["proxies"]]+ if missing:+ errors.append(f"{where}: destructible proxies missing {missing}")+ states = set(destructible["states"])+ for state in REQUIRED_PROXY_STATES:+ if state not in states:+ errors.append(f"{where}: destructible states missing {state}")+ elif item["collision"] == "Verse_Destructible":+ errors.append(f"{where}: collision Verse_Destructible needs a destructible block")+ if item["piece"].startswith("GC_") and destructible is None:+ errors.append(f"{where}: a geometry collection placement must be destructible")++ socket_ids = [s["id"] for s in doc["sockets"]]+ errors += [f"sockets: duplicate id {i!r}" for i in _dupes(socket_ids)]+ for socket in doc["sockets"]:+ where = f"sockets/{socket['id']}"+ if not _inside(socket["location"], lo, hi):+ errors.append(f"{where}: location outside bounds_cm")+ if _quat_norm_error(socket["rotation"]) > UNIT_QUAT_TOLERANCE:+ errors.append(f"{where}: rotation is not a unit quaternion")+ if socket["room"] is not None and socket["room"] not in room_set:+ errors.append(f"{where}: room {socket['room']!r} is not in rooms[]")+ return errors+++def validate(+ doc: Any, *, path: Path | None = None, known_assets: set[str] | None = None+) -> list[str]:+ """All errors of one placement document (schema first, then semantics)."""+ errors = schema_errors(doc)+ if errors:+ return errors+ return semantic_errors(doc, path=path, known_assets=known_assets)+++def validate_file(path: Path, *, known_assets: set[str] | None = None) -> list[str]:+ raw = path.read_bytes()+ errors: list[str] = []+ if b"\r\n" in raw:+ errors.append("line endings must be LF")+ try:+ doc = json.loads(raw.decode("utf-8"))+ except (UnicodeDecodeError, json.JSONDecodeError) as error:+ return [f"not valid JSON: {error}"]+ errors += validate(doc, path=path, known_assets=known_assets)+ if not errors and raw.decode("utf-8") != dumps(doc):+ errors.append(+ "not in canonical form (sorted keys, 2-space indent, arrays by id);"+ " rewrite it with lib.placement.write"+ )+ return errorsdiff --git a/art/verse/lib/ue_space.py b/art/verse/lib/ue_space.pynew file mode 100644index 0000000000..c9f6f7ee46--- /dev/null+++ b/art/verse/lib/ue_space.py@@ -0,0 +1,115 @@+"""Blender (and three.js) space to Unreal space (contracts/art-pipeline.md 4.1).++Pure Python, no bpy: the exporter, the placement validator, pytest and the+editor-side calibration all import it. The twin C++ conversion lives in+VerseCore; both are checked against ``unreal/Verse/Art/space_vectors.json``.++Blender: Z up, X = bow, metres, right-handed.+Unreal: Z up, X forward, Y right, centimetres, left-handed.++The mapping is the mirror across the XZ plane plus metres to centimetres:+``(x, y, z) m -> (100 x, -100 y, 100 z) cm``. A rotation R becomes M R M with+M = diag(1, -1, 1), which for a quaternion (w, x, y, z) is (w, -x, y, -z);+Unreal stores quaternions as [x, y, z, w].+"""++from __future__ import annotations++import math+from collections.abc import Sequence++CM_PER_M = 100.0++Vec3 = Sequence[float]+++def location_to_ue(location_m: Vec3) -> list[float]:+ """Blender location in metres -> Unreal location in centimetres."""+ x, y, z = (float(v) for v in location_m)+ return [_clean(CM_PER_M * x), _clean(-CM_PER_M * y), _clean(CM_PER_M * z)]+++def location_from_ue(location_cm: Vec3) -> list[float]:+ x, y, z = (float(v) for v in location_cm)+ return [_clean(x / CM_PER_M), _clean(-y / CM_PER_M), _clean(z / CM_PER_M)]+++def direction_to_ue(direction: Vec3) -> list[float]:+ """Unit-free direction (normals, axes): mirrored, not scaled."""+ x, y, z = (float(v) for v in direction)+ return [_clean(x), _clean(-y), _clean(z)]+++def quat_to_ue(quat_wxyz: Sequence[float]) -> list[float]:+ """Blender quaternion (w, x, y, z) -> Unreal [x, y, z, w], normalised, w >= 0."""+ w, x, y, z = (float(v) for v in quat_wxyz)+ norm = math.sqrt(w * w + x * x + y * y + z * z)+ if norm == 0.0:+ raise ValueError("zero quaternion")+ w, x, y, z = w / norm, x / norm, y / norm, z / norm+ out = [-x, y, -z, w]+ if out[3] < 0.0: # q and -q are the same rotation; keep one canonical sign+ out = [-v for v in out]+ return [_clean(v) for v in out]+++def quat_from_ue(quat_xyzw: Sequence[float]) -> list[float]:+ x, y, z, w = (float(v) for v in quat_xyzw)+ return [_clean(w), _clean(-x), _clean(y), _clean(-z)]+++def yaw_to_ue(rot_z_deg: float) -> float:+ """Blender rotation about Z (counter-clockwise from above) -> Unreal yaw."""+ return _clean(-float(rot_z_deg))+++def scale_to_ue(scale: Vec3) -> list[float]:+ """Scale is unchanged by the mirror (it is applied in local space)."""+ return [float(v) for v in scale]+++def three_to_ue(location_m: Vec3) -> list[float]:+ """three.js (x, y, z) m, Y up -> Unreal cm (three.js z = -Blender y)."""+ x, y, z = (float(v) for v in location_m)+ return [_clean(CM_PER_M * x), _clean(CM_PER_M * z), _clean(CM_PER_M * y)]+++def yaw_quat_wxyz(rot_z_deg: float) -> list[float]:+ """Blender quaternion (w, x, y, z) of a rotation about +Z."""+ half = math.radians(float(rot_z_deg)) / 2.0+ return [math.cos(half), 0.0, 0.0, math.sin(half)]+++def rotate_vector_xyzw(quat_xyzw: Sequence[float], vector: Vec3) -> list[float]:+ """Rotate ``vector`` by an [x, y, z, w] quaternion (q v q*), as FQuat does."""+ qx, qy, qz, qw = (float(v) for v in quat_xyzw)+ vx, vy, vz = (float(v) for v in vector)+ # t = 2 * cross(q.xyz, v); v' = v + w t + cross(q.xyz, t)+ tx = 2.0 * (qy * vz - qz * vy)+ ty = 2.0 * (qz * vx - qx * vz)+ tz = 2.0 * (qx * vy - qy * vx)+ return [+ vx + qw * tx + (qy * tz - qz * ty),+ vy + qw * ty + (qz * tx - qx * tz),+ vz + qw * tz + (qx * ty - qy * tx),+ ]+++def rotate_vector_wxyz(quat_wxyz: Sequence[float], vector: Vec3) -> list[float]:+ w, x, y, z = quat_wxyz+ return rotate_vector_xyzw([x, y, z, w], vector)+++def bounds_to_ue(min_m: Vec3, max_m: Vec3) -> tuple[list[float], list[float]]:+ """Blender box (metres) -> Unreal box (cm) with min <= max on every axis."""+ a = location_to_ue(min_m)+ b = location_to_ue(max_m)+ pairs = list(zip(a, b, strict=True))+ return [min(p) for p in pairs], [max(p) for p in pairs]+++def _clean(value: float) -> float:+ """Drop the sign of zero and float noise below 1e-12 so JSON stays stable."""+ if abs(value) < 1e-12:+ return 0.0+ return valuediff --git a/art/verse/lib/unreal_export.py b/art/verse/lib/unreal_export.pynew file mode 100644index 0000000000..91856e430e--- /dev/null+++ b/art/verse/lib/unreal_export.py@@ -0,0 +1,533 @@+"""Export kit pieces and calibration assets to FBX for Unreal (art-pipeline 6.1).++Runs inside Blender (bpy). The host entry is `scripts/verse/export_unreal.py`,+which starts Blender through `scripts/verse/blender.py` under the machine-wide+lock; nothing else calls this module.++One FBX per asset, in piece space as authored. Every export uses the frozen+settings set `fbx-ue/1` (`FBX_UE_1`), proven by the calibration assets of+`kit/calib.py` and `python scripts/unreal/import_art.py calib`. Any change to+`FBX_UE_1` is a contract change (`fbx-ue/2`) and reruns the calibration.++Name rules (art-pipeline 3.1):++* `UCX_*` objects and the `Occluders` collection are Blender depth proxies and+ are never exported.+* Kit sockets (`SOCKET_<kind>_<id>`) are world sockets; they go to the+ placement JSON, never into a mesh.+* `UECOL_<Box|Sphere|Capsule|Convex>_<nn>` meshes become Unreal collision+ primitives `UBX_/USP_/UCP_/UCX_<SM_Name>_<nn>`.+* `UESOCKET_<name>` empties become mesh sockets `SOCKET_<name>`.++Any other object whose name starts with a reserved Unreal prefix fails the+export.+"""++from __future__ import annotations++import datetime+import hashlib+import json+import re+from collections.abc import Iterator+from contextlib import contextmanager+from dataclasses import dataclass, field+from pathlib import Path++import bmesh+import bpy+from mathutils import Matrix, Vector++from . import ue_space, unreal_materials++SETTINGS_ID = "fbx-ue/1"+GENERATOR_VERSION = "1"++#: The frozen `fbx-ue/1` settings of `bpy.ops.export_scene.fbx`.+FBX_UE_1: dict = {+ "use_selection": True,+ "use_visible": False,+ "use_active_collection": False,+ "global_scale": 1.0,+ "apply_unit_scale": True,+ "apply_scale_options": "FBX_SCALE_NONE",+ "use_space_transform": True,+ "bake_space_transform": False,+ "axis_forward": "-Z",+ "axis_up": "Y",+ "object_types": {"MESH", "EMPTY", "ARMATURE"},+ "use_mesh_modifiers": True,+ "use_mesh_modifiers_render": True,+ "mesh_smooth_type": "FACE",+ "use_subsurf": False,+ "use_mesh_edges": False,+ "use_tspace": True,+ "use_triangles": True,+ "use_custom_props": False,+ "add_leaf_bones": False,+ "primary_bone_axis": "Y",+ "secondary_bone_axis": "X",+ "use_armature_deform_only": True,+ "armature_nodetype": "NULL",+ "bake_anim": False,+ "path_mode": "STRIP",+ "embed_textures": False,+ "batch_mode": "OFF",+}++#: Names the Unreal importer reads as collision or sockets (art-pipeline 3.1).+RESERVED_PREFIXES = ("UCX_", "UBX_", "USP_", "UCP_", "SOCKET_")+_COLLISION_RE = re.compile(r"^UECOL_(?P<type>Box|Sphere|Capsule|Convex)_(?P<nn>\d{2})(?:[._].*)?$")+_MESH_SOCKET_RE = re.compile(r"^UESOCKET_(?P<name>[A-Za-z][A-Za-z0-9_]*?)(?:\.\d{3})?$")+_COLLISION_PREFIX = {"Box": "UBX_", "Sphere": "USP_", "Capsule": "UCP_", "Convex": "UCX_"}+MAX_PRIMITIVES = 16+MAX_HULL_VERTS = 32++REPO_ROOT = Path(__file__).resolve().parents[3]+CACHE_ROOT = REPO_ROOT / "art" / "verse" / ".cache" / "unreal"+++class ExportError(RuntimeError):+ """The asset cannot be exported under `fbx-ue/1`."""+++@dataclass+class ExportResult:+ name: str+ file: Path+ sha256: str+ triangles: int+ vertices: int+ bounds_cm: dict+ uv_sets: int+ material_slots: list[dict]+ collision_primitives: int+ sockets: list[str] = field(default_factory=list)+ bones: list[str] = field(default_factory=list)++ def as_dict(self) -> dict:+ return {+ "name": self.name,+ "file": self.file.relative_to(REPO_ROOT).as_posix(),+ "sha256": self.sha256,+ "triangles": self.triangles,+ "vertices": self.vertices,+ "bounds_cm": self.bounds_cm,+ "uv_sets": self.uv_sets,+ "material_slots": self.material_slots,+ "collision_primitives": self.collision_primitives,+ "sockets": self.sockets,+ "bones": self.bones,+ "settings_id": SETTINGS_ID,+ "blender": bpy.app.version_string.split(" ")[0],+ }+++def strip_suffix(name: str) -> str:+ return re.sub(r"\.\d{3}$", "", name)+++# --------------------------------------------------------------------------+# Collecting a piece+# --------------------------------------------------------------------------+++def _walk(+ collection: bpy.types.Collection, matrix: Matrix, depth: int = 0+) -> Iterator[tuple[bpy.types.Object, Matrix]]:+ """Yield (object, matrix in piece space), recursing into collection instances."""+ if depth > 16:+ raise ExportError(f"collection instances nested too deep in {collection.name}")+ for obj in collection.all_objects:+ world = matrix @ obj.matrix_world+ yield obj, world+ if obj.instance_type == "COLLECTION" and obj.instance_collection is not None:+ inst = obj.instance_collection+ offset = Matrix.Translation(-Vector(inst.instance_offset))+ yield from _walk(inst, world @ offset, depth + 1)+++def _is_ghost(obj: bpy.types.Object) -> bool:+ return bool(obj.get("ceiling_ghost"))+++def _in_occluders(obj: bpy.types.Object) -> bool:+ return any(strip_suffix(col.name) == "Occluders" for col in obj.users_collection)+++def _evaluated_mesh(obj: bpy.types.Object, depsgraph, matrix: Matrix) -> bpy.types.Mesh:+ """Mesh with modifiers applied, transformed into piece space."""+ evaluated = obj.evaluated_get(depsgraph)+ mesh = bpy.data.meshes.new_from_object(+ evaluated, preserve_all_data_layers=True, depsgraph=depsgraph+ )+ mesh.transform(matrix)+ if matrix.determinant() < 0:+ mesh.flip_normals()+ return mesh+++@dataclass+class _Parts:+ meshes: list[tuple[bpy.types.Mesh, str]] = field(default_factory=list) # (mesh, source)+ collision: list[tuple[bpy.types.Mesh, str, str]] = field(default_factory=list)+ sockets: list[tuple[str, Matrix]] = field(default_factory=list)+++def collect(collection: bpy.types.Collection, root_name: str = "") -> _Parts:+ """Split a piece collection into render meshes, collision and mesh sockets."""+ parts = _Parts()+ # Masters live in the excluded KIT_MASTERS tree; link the piece into the+ # scene for a moment so its modifiers are evaluated.+ scene_root = bpy.context.scene.collection+ linked = collection.name not in scene_root.children+ if linked:+ scene_root.children.link(collection)+ try:+ bpy.context.view_layer.update()+ depsgraph = bpy.context.evaluated_depsgraph_get()+ for obj, matrix in _walk(collection, Matrix.Identity(4)):+ name = strip_suffix(obj.name)+ if _is_ghost(obj) or _in_occluders(obj) or name.startswith("UCX_"):+ continue+ collision = _COLLISION_RE.match(obj.name)+ if collision:+ if obj.type != "MESH":+ raise ExportError(f"{obj.name}: collision primitives must be meshes")+ parts.collision.append(+ (_evaluated_mesh(obj, depsgraph, matrix), collision["type"], collision["nn"])+ )+ continue+ socket = _MESH_SOCKET_RE.match(obj.name)+ if socket:+ parts.sockets.append((socket["name"], matrix.copy()))+ continue+ if name.startswith("SOCKET_") or name.startswith("ROOM_"):+ continue # world sockets and rooms belong to the placement JSON+ if name.startswith(RESERVED_PREFIXES):+ raise ExportError(f"{obj.name}: reserved Unreal prefix (art-pipeline 3.1)")+ if obj.type != "MESH":+ continue+ parts.meshes.append((_evaluated_mesh(obj, depsgraph, matrix), obj.name))+ finally:+ if linked:+ scene_root.children.unlink(collection)+ if not parts.meshes:+ raise ExportError(f"{collection.name}: nothing to export")+ return parts+++# --------------------------------------------------------------------------+# Building the export objects+# --------------------------------------------------------------------------+++def _join(meshes: list[bpy.types.Mesh], name: str) -> bpy.types.Mesh:+ """Join meshes into one, with one material slot per distinct material name."""+ slots: list[bpy.types.Material] = []+ slot_names: list[str] = []+ bm = bmesh.new()+ for mesh in meshes:+ remap = []+ for material in mesh.materials:+ key = strip_suffix(material.name) if material else "M_Default"+ if key not in slot_names:+ slot_names.append(key)+ slots.append(material)+ remap.append(slot_names.index(key))+ for poly in mesh.polygons:+ poly.material_index = remap[poly.material_index] if remap else 0+ bm.from_mesh(mesh)+ out = bpy.data.meshes.new(name)+ bm.to_mesh(out)+ bm.free()+ for material in slots:+ out.materials.append(material)+ return out+++def box_project_uv(mesh: bpy.types.Mesh) -> None:+ """UV0 in real metres, projected along each face's dominant axis (art-pipeline 6.1)."""+ layer = mesh.uv_layers.new(name="UVMap")+ for poly in mesh.polygons:+ n = poly.normal+ axis = max(range(3), key=lambda i: abs(n[i]))+ for li in poly.loop_indices:+ co = mesh.vertices[mesh.loops[li].vertex_index].co+ if axis == 0:+ u, v = (co.y if n.x >= 0 else -co.y), co.z+ elif axis == 1:+ u, v = (-co.x if n.y >= 0 else co.x), co.z+ else:+ u, v = co.x, (co.y if n.z >= 0 else -co.y)+ layer.data[li].uv = (u, v)+++def check_hygiene(mesh: bpy.types.Mesh, name: str) -> None:+ """Fail on zero-area faces; the rest of the hygiene list is the builder's job."""+ degenerate = sum(1 for poly in mesh.polygons if poly.area < 1e-10)+ if degenerate:+ raise ExportError(f"{name}: {degenerate} zero-area faces")+++def triangle_count(mesh: bpy.types.Mesh) -> int:+ return sum(len(poly.vertices) - 2 for poly in mesh.polygons)+++def bounds_cm(mesh: bpy.types.Mesh) -> dict:+ xs = [v.co.x for v in mesh.vertices]+ ys = [v.co.y for v in mesh.vertices]+ zs = [v.co.z for v in mesh.vertices]+ lo, hi = ue_space.bounds_to_ue((min(xs), min(ys), min(zs)), (max(xs), max(ys), max(zs)))+ return {"min": [round(v, 3) for v in lo], "max": [round(v, 3) for v in hi]}+++EXPORT_COLLECTION = "VERSE_UE_EXPORT"+++def _export_scene() -> bpy.types.Collection:+ """An emptied collection in the current scene that holds one asset's export objects.++ Exporting from the current scene avoids overriding the context scene,+ which crashes Blender 5.0 in background mode.+ """+ scene = bpy.context.scene+ scene.unit_settings.system = "METRIC"+ scene.unit_settings.scale_length = 1.0+ col = bpy.data.collections.get(EXPORT_COLLECTION)+ if col is None:+ col = bpy.data.collections.new(EXPORT_COLLECTION)+ scene.collection.children.link(col)+ for obj in list(col.objects):+ bpy.data.objects.remove(obj, do_unlink=True)+ return col+++#: Export data in centimetres with a scene unit scale of 0.01. With metres the+#: FBX armature node carries a scale of 100 that the importer bakes into the+#: first bone (found by the SK_Calib_Rig calibration); in centimetres every+#: node keeps scale 1. Part of `fbx-ue/1`.+CM = 100.0+++def _to_centimetres(objects: list[bpy.types.Object]) -> None:+ """Scale the export copies' data (never object scale) from metres to centimetres."""+ scale = Matrix.Scale(CM, 4)+ for obj in objects:+ if obj.type == "ARMATURE":+ with bpy.context.temp_override(active_object=obj, object=obj):+ bpy.ops.object.mode_set(mode="EDIT")+ for bone in obj.data.edit_bones:+ bone.head = bone.head * CM+ bone.tail = bone.tail * CM+ bpy.ops.object.mode_set(mode="OBJECT")+ elif obj.type == "MESH":+ obj.data.transform(scale)+ if obj.parent is None or obj.parent not in objects:+ obj.matrix_world.translation = obj.matrix_world.translation * CM+ elif obj.type == "EMPTY":+ obj.matrix_parent_inverse = Matrix.Identity(4)+ obj.matrix_basis.translation = obj.matrix_basis.translation * CM+++class _FixedClock(datetime.datetime):+ """`datetime.now()` pinned, so the FBX header time and the file hash are stable."""++ @classmethod+ def now(cls, tz=None): # noqa: ARG003 - same signature as datetime.now+ return cls(2000, 1, 1, 0, 0, 0)+++def _stable_hash(key) -> int:+ """Process-independent stand-in for `hash()` (string hashing is salted per run)."""+ return int.from_bytes(hashlib.sha256(repr(key).encode("utf-8")).digest()[:8], "little")+++@contextmanager+def _reproducible_fbx():+ """Pin the two run-dependent inputs of Blender's FBX writer: the header time+ and the object ids (derived from `hash()` of names). Same scene, same bytes,+ so `export.sha256` only changes when the art does (art-pipeline 10.2)."""+ from io_scene_fbx import export_fbx_bin, fbx_utils++ original = export_fbx_bin.datetime+ export_fbx_bin.datetime = type("datetime_module", (), {"datetime": _FixedClock})+ fbx_utils.hash = _stable_hash+ try:+ yield+ finally:+ export_fbx_bin.datetime = original+ del fbx_utils.hash+++def _write_fbx(col: bpy.types.Collection, objects: list[bpy.types.Object], path: Path) -> str:+ path.parent.mkdir(parents=True, exist_ok=True)+ view_layer = bpy.context.view_layer+ view_layer.update()+ _to_centimetres(objects)+ units = bpy.context.scene.unit_settings+ units.scale_length = 1.0 / CM+ for obj in view_layer.objects:+ obj.select_set(False)+ for obj in objects:+ obj.select_set(True)+ view_layer.objects.active = objects[0]+ try:+ override = bpy.context.temp_override(active_object=objects[0], object=objects[0])+ with override, _reproducible_fbx():+ result = bpy.ops.export_scene.fbx(filepath=str(path), **FBX_UE_1)+ finally:+ units.scale_length = 1.0+ if "FINISHED" not in result:+ raise ExportError(f"FBX export failed for {path.name}: {result}")+ check_fbx_names(path, {obj.name for obj in objects})+ return hashlib.sha256(path.read_bytes()).hexdigest()+++def check_fbx_names(path: Path, allowed: set[str]) -> None:+ """Fail when a reserved Unreal name reached the FBX by any other route."""+ data = path.read_bytes()+ for prefix in RESERVED_PREFIXES:+ for match in re.finditer(re.escape(prefix.encode()) + rb"[A-Za-z0-9_]+", data):+ found = match.group(0).decode("ascii", "replace")+ if found not in allowed:+ raise ExportError(f"{path.name}: reserved name {found} reached the FBX")+++def export_static_mesh(+ name: str, collection: bpy.types.Collection, out_dir: Path, *, root_name: str = ""+) -> ExportResult:+ """Export the objects of `collection` as static mesh `name` (one FBX)."""+ if not re.match(r"^SM_[A-Za-z0-9][A-Za-z0-9_]{0,60}$", name):+ raise ExportError(f"{name}: static mesh names are SM_<PascalCase> (art-pipeline 3)")+ parts = collect(collection, root_name)+ if len(parts.collision) > MAX_PRIMITIVES:+ count = len(parts.collision)+ raise ExportError(f"{name}: {count} collision primitives, cap {MAX_PRIMITIVES}")+ scene = _export_scene()+ mesh = _join([m for m, _ in parts.meshes], name)+ check_hygiene(mesh, name)+ if not mesh.uv_layers:+ box_project_uv(mesh)+ body = bpy.data.objects.new(name, mesh)+ scene.objects.link(body)+ objects = [body]+ for col_mesh, kind, nn in parts.collision:+ if kind == "Convex" and len(col_mesh.vertices) > MAX_HULL_VERTS:+ raise ExportError(f"{name}: convex hull {nn} has {len(col_mesh.vertices)} vertices")+ col_obj = bpy.data.objects.new(f"{_COLLISION_PREFIX[kind]}{name}_{nn}", col_mesh)+ scene.objects.link(col_obj)+ objects.append(col_obj)+ socket_names = []+ for socket_name, matrix in parts.sockets:+ empty = bpy.data.objects.new(f"SOCKET_{socket_name}", None)+ scene.objects.link(empty)+ empty.parent = body+ empty.matrix_world = matrix+ objects.append(empty)+ socket_names.append(f"SOCKET_{socket_name}")+ path = out_dir / f"{name}.fbx"+ box = bounds_cm(mesh) # metres -> cm before the export scales the copies+ digest = _write_fbx(scene, objects, path)+ slots = [+ {"slot": strip_suffix(m.name) if m else "M_Default", "mi": _mi_path(m)}+ for m in mesh.materials+ ]+ result = ExportResult(+ name=name,+ file=path,+ sha256=digest,+ triangles=triangle_count(mesh),+ vertices=len(mesh.vertices),+ bounds_cm=box,+ uv_sets=len(mesh.uv_layers),+ material_slots=slots,+ collision_primitives=len(parts.collision),+ sockets=sorted(socket_names),+ )+ for m, _ in parts.meshes:+ bpy.data.meshes.remove(m)+ return result+++def _mi_path(material) -> str:+ name = strip_suffix(material.name) if material else "M_Default"+ try:+ return unreal_materials.instance_path(name)+ except ValueError:+ return unreal_materials.instance_path("M_Default")+++# --------------------------------------------------------------------------+# Skeletal calibration rig+# --------------------------------------------------------------------------+++def build_rig(name: str, bones: tuple, out_dir: Path) -> ExportResult:+ """Build and export a skinned armature: one 10 cm box per bone, rigid weights.++ `bones` is a tuple of (name, parent, head, tail) in Blender metres.+ """+ scene = _export_scene()+ arm_data = bpy.data.armatures.new(f"{name}_Data")+ # The Unreal importer drops a root node named "Armature", so the first+ # bone of the skeleton is the rig's own `Root`.+ arm_obj = bpy.data.objects.new("Armature", arm_data)+ scene.objects.link(arm_obj)+ bpy.context.view_layer.update()+ bpy.context.view_layer.objects.active = arm_obj+ with bpy.context.temp_override(active_object=arm_obj, object=arm_obj):+ bpy.ops.object.mode_set(mode="EDIT")+ edit = arm_data.edit_bones+ for bone_name, parent, head, tail in bones:+ bone = edit.new(bone_name)+ bone.head = head+ bone.tail = tail+ bone.roll = 0.0+ bone.use_deform = True+ if parent:+ bone.parent = edit[parent]+ bpy.ops.object.mode_set(mode="OBJECT")++ bm = bmesh.new()+ groups: list[tuple[str, list[int]]] = []+ for bone_name, _parent, head, tail in bones:+ centre = (Vector(head) + Vector(tail)) * 0.5+ start = len(bm.verts)+ geom = bmesh.ops.create_cube(bm, size=0.1)+ bmesh.ops.translate(bm, verts=geom["verts"], vec=centre)+ groups.append((bone_name, list(range(start, start + len(geom["verts"])))))+ mesh = bpy.data.meshes.new(f"SK_{name[3:]}" if name.startswith("SK_") else name)+ bm.to_mesh(mesh)+ bm.free()+ box_project_uv(mesh)+ mesh.materials.append(bpy.data.materials.get("M_Calib") or bpy.data.materials.new("M_Calib"))+ body = bpy.data.objects.new(name, mesh)+ scene.objects.link(body)+ body.parent = arm_obj+ for bone_name, indices in groups:+ group = body.vertex_groups.new(name=bone_name)+ group.add(indices, 1.0, "REPLACE")+ modifier = body.modifiers.new("Armature", "ARMATURE")+ modifier.object = arm_obj+ path = out_dir / f"{name}.fbx"+ box = bounds_cm(mesh) # metres -> cm before the export scales the copies+ digest = _write_fbx(scene, [arm_obj, body], path)+ return ExportResult(+ name=name,+ file=path,+ sha256=digest,+ triangles=triangle_count(mesh),+ vertices=len(mesh.vertices),+ bounds_cm=box,+ uv_sets=len(mesh.uv_layers),+ material_slots=[],+ collision_primitives=0,+ bones=[b[0] for b in bones],+ )+++def write_result(path: Path, results: list[dict]) -> None:+ path.parent.mkdir(parents=True, exist_ok=True)+ payload = {"settings_id": SETTINGS_ID, "assets": results}+ path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")diff --git a/art/verse/lib/unreal_materials.py b/art/verse/lib/unreal_materials.pynew file mode 100644index 0000000000..6edcc46fea--- /dev/null+++ b/art/verse/lib/unreal_materials.py@@ -0,0 +1,62 @@+"""Blender material names to Unreal material instances (art-pipeline 7).++Pure Python. Each Blender `M_<Name>` of `lib/materials.py` maps to one+`MI_<Name>` in a group folder under `/Game/Verse/Materials/Instances/`; the+export writes that path into each mesh's material slot list, and the MI+recipe `unreal/Verse/Art/Materials/MI_<Name>.mi.json` (owned by the folder's+package, art-pipeline 9) describes the instance.+"""++from __future__ import annotations++import re++INSTANCES_ROOT = "/Game/Verse/Materials/Instances"++#: Blender name prefix (after `M_`) -> instance group folder. First match wins.+GROUPS: tuple[tuple[str, str], ...] = (+ ("Floor_", "Floors"),+ ("Deck_", "Markings"),+ ("Wall_", "Walls"),+ ("Ceiling_", "Walls"),+ ("Recess_", "Walls"),+ ("Section_", "Walls"),+ ("Struct_", "Metal"),+ ("Trim_", "Metal"),+ ("Rubber_", "Metal"),+ ("Hull_", "Hull"),+ ("Light_", "Lights"),+ ("Emit_", "Lights"),+ ("Indicator_", "Lights"),+ ("Console_", "Consoles"),+ ("Screen", "Screens"),+ ("Glass_", "Glass"),+ ("Weapon_", "Weapons"),+ ("Character_", "Characters"),+ ("Skin_", "Characters"),+)+DEFAULT_GROUP = "Props"++_BLENDER_NAME = re.compile(r"^M_(?P<name>[A-Za-z0-9][A-Za-z0-9_]*?)(?:\.\d{3})?$")+++def instance_name(blender_material: str) -> str:+ """`M_Wall_Charcoal` (or `M_Wall_Charcoal.001`) -> `MI_Wall_Charcoal`."""+ match = _BLENDER_NAME.match(blender_material)+ if not match:+ raise ValueError(f"not a Verse material name: {blender_material!r}")+ return f"MI_{match['name']}"+++def group_for(blender_material: str) -> str:+ name = instance_name(blender_material)[3:]+ for prefix, group in GROUPS:+ if name.startswith(prefix):+ return group+ return DEFAULT_GROUP+++def instance_path(blender_material: str) -> str:+ """Object path of the MI that replaces `blender_material`."""+ mi = instance_name(blender_material)+ return f"{INSTANCES_ROOT}/{group_for(blender_material)}/{mi}.{mi}"diff --git a/art/verse/schema/import.schema.json b/art/verse/schema/import.schema.jsonnew file mode 100644index 0000000000..7e23a68ccb--- /dev/null+++ b/art/verse/schema/import.schema.json@@ -0,0 +1,158 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "$id": "https://dodaios.dev/schema/verse.import-1.json",+ "title": "verse.import/1",+ "description": "Import record of one Unreal asset (docs/verse/unreal/contracts/art-pipeline.md 10.3). Written by scripts/verse/export_unreal.py, read by verse_pipeline and scripts/unreal/check_art_text.py.",+ "type": "object",+ "additionalProperties": false,+ "required": ["schema", "name", "asset_path", "kind", "source", "export", "lightmap", "license", "owner"],+ "properties": {+ "schema": { "const": "verse.import/1" },+ "name": { "type": "string", "pattern": "^[A-Z][A-Za-z]*_[A-Za-z0-9][A-Za-z0-9_]{0,60}$" },+ "asset_path": { "type": "string", "pattern": "^/Game/Verse/[A-Za-z0-9_/]+/([A-Za-z0-9_]+)\\.([A-Za-z0-9_]+)$", "maxLength": 180 },+ "kind": {+ "enum": [+ "static_mesh",+ "skeletal_mesh",+ "skeleton",+ "physics_asset",+ "animation",+ "texture",+ "geometry_collection",+ "proxy_mesh"+ ]+ },+ "source": {+ "type": "object",+ "additionalProperties": false,+ "required": ["builder", "function", "args"],+ "properties": {+ "builder": { "type": "string", "pattern": "^art/verse/[A-Za-z0-9_/.-]+\\.py$" },+ "function": { "type": "string", "minLength": 1 },+ "args": { "type": "object" }+ }+ },+ "export": {+ "type": "object",+ "additionalProperties": false,+ "required": ["format", "settings_id", "file", "sha256", "blender"],+ "properties": {+ "format": { "enum": ["fbx", "png"] },+ "settings_id": { "type": "string", "pattern": "^[a-z]+-ue/[0-9]+$" },+ "file": { "type": "string", "pattern": "^art/verse/\\.cache/unreal/[A-Za-z0-9_/.-]+\\.(fbx|png)$" },+ "sha256": { "type": "string", "pattern": "^[0-9a-f]{64}$" },+ "blender": { "type": "string", "pattern": "^[0-9]+\\.[0-9]+\\.[0-9]+$" }+ }+ },+ "mesh": {+ "type": "object",+ "additionalProperties": false,+ "required": ["triangles", "vertices", "bounds_cm", "uv_sets", "material_slots"],+ "properties": {+ "triangles": { "type": "integer", "minimum": 1 },+ "vertices": { "type": "integer", "minimum": 3 },+ "bounds_cm": {+ "type": "object",+ "additionalProperties": false,+ "required": ["min", "max"],+ "properties": {+ "min": { "$ref": "#/$defs/vec3" },+ "max": { "$ref": "#/$defs/vec3" }+ }+ },+ "uv_sets": { "type": "integer", "minimum": 0, "maximum": 1 },+ "material_slots": {+ "type": "array",+ "items": {+ "type": "object",+ "additionalProperties": false,+ "required": ["slot", "mi"],+ "properties": {+ "slot": { "type": "string", "pattern": "^[A-Za-z0-9_]+$" },+ "mi": { "type": "string", "pattern": "^/Game/Verse/Materials/[A-Za-z0-9_/]+/(MI_[A-Za-z0-9_]+)\\.(MI_[A-Za-z0-9_]+)$" }+ }+ }+ },+ "bones": { "type": "array", "items": { "type": "string", "pattern": "^[A-Za-z][A-Za-z0-9_]*$" } },+ "sockets": { "type": "array", "items": { "type": "string", "pattern": "^SOCKET_[A-Za-z0-9_]+$" } }+ }+ },+ "nanite": {+ "type": "object",+ "additionalProperties": false,+ "required": ["enabled"],+ "properties": {+ "enabled": { "type": "boolean" },+ "fallback_relative_error": { "type": "number", "minimum": 0 }+ }+ },+ "collision": {+ "type": "object",+ "additionalProperties": false,+ "required": ["profile", "source", "primitives"],+ "properties": {+ "profile": {+ "enum": [+ "Verse_Architecture",+ "Verse_Destructible",+ "Verse_Glass",+ "Verse_Prop",+ "Verse_PropSmall",+ "Verse_Debris",+ "Verse_ProxyOnly",+ "Verse_NoCollision"+ ]+ },+ "source": { "enum": ["authored", "auto_box", "proxy_states", "none"] },+ "primitives": { "type": "integer", "minimum": 0 }+ }+ },+ "lod": {+ "type": "object",+ "additionalProperties": false,+ "required": ["mode"],+ "properties": {+ "mode": { "enum": ["nanite", "auto", "single"] },+ "screen_sizes": { "type": "array", "items": { "type": "number", "exclusiveMinimum": 0, "maximum": 1 } }+ }+ },+ "lightmap": { "const": "none" },+ "texture": {+ "type": "object",+ "additionalProperties": false,+ "required": ["group", "max_size", "srgb", "compression", "flip_green"],+ "properties": {+ "group": { "enum": ["World", "WorldNormalMap", "Character", "CharacterNormalMap", "Weapon", "UI"] },+ "max_size": { "enum": [32, 64, 128, 256, 512, 1024, 2048, 4096] },+ "srgb": { "type": "boolean" },+ "compression": { "enum": ["Default", "Normalmap", "Masks", "BC7", "Grayscale", "HDR"] },+ "flip_green": { "type": "boolean" },+ "channels": { "type": "object", "additionalProperties": { "type": "string" } }+ }+ },+ "license": {+ "type": "object",+ "additionalProperties": false,+ "required": ["kind"],+ "properties": {+ "kind": { "enum": ["own", "ledger"] },+ "ledger_sha256": { "type": "array", "items": { "type": "string", "pattern": "^[0-9a-f]{64}$" } }+ }+ },+ "owner": { "type": "string", "pattern": "^WP[0-9]{2}$" },+ "budget_override": {+ "type": "object",+ "additionalProperties": false,+ "required": ["field", "value", "reason", "approved_by"],+ "properties": {+ "field": { "type": "string", "minLength": 1 },+ "value": { "type": ["number", "string"] },+ "reason": { "type": "string", "minLength": 10 },+ "approved_by": { "const": "integration" }+ }+ }+ },+ "$defs": {+ "vec3": { "type": "array", "minItems": 3, "maxItems": 3, "items": { "type": "number" } }+ }+}diff --git a/art/verse/schema/mi.schema.json b/art/verse/schema/mi.schema.jsonnew file mode 100644index 0000000000..f5ee7f3d03--- /dev/null+++ b/art/verse/schema/mi.schema.json@@ -0,0 +1,42 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "$id": "https://dodaios.dev/schema/verse.mi-1.json",+ "title": "verse.mi/1",+ "description": "Material instance recipe (docs/verse/unreal/contracts/art-pipeline.md 7). verse_pipeline.materials creates or updates the MI asset from it.",+ "type": "object",+ "additionalProperties": false,+ "required": ["schema", "name", "parent", "scalars", "vectors", "textures", "switches", "owner", "replaces"],+ "properties": {+ "schema": { "const": "verse.mi/1" },+ "name": { "type": "string", "pattern": "^MI_[A-Za-z0-9][A-Za-z0-9_]{0,60}$" },+ "parent": {+ "enum": [+ "/Game/Verse/Materials/Master/M_Verse_Surface.M_Verse_Surface",+ "/Game/Verse/Materials/Master/M_Verse_Floor.M_Verse_Floor",+ "/Game/Verse/Materials/Master/M_Verse_Emissive.M_Verse_Emissive",+ "/Game/Verse/Materials/Master/M_Verse_Glass.M_Verse_Glass",+ "/Game/Verse/Materials/Master/M_Verse_Screen.M_Verse_Screen",+ "/Game/Verse/Materials/Master/M_Verse_Character.M_Verse_Character",+ "/Game/Verse/Materials/Master/M_Verse_Weapon.M_Verse_Weapon",+ "/Game/Verse/Materials/Master/M_Verse_Decal.M_Verse_Decal"+ ]+ },+ "scalars": { "type": "object", "additionalProperties": { "type": "number" } },+ "vectors": {+ "type": "object",+ "additionalProperties": {+ "type": "array",+ "minItems": 4,+ "maxItems": 4,+ "items": { "type": "number", "minimum": 0 }+ }+ },+ "textures": {+ "type": "object",+ "additionalProperties": { "type": "string", "pattern": "^/Game/Verse/[A-Za-z0-9_/]+/(T_[A-Za-z0-9_]+)\\.(T_[A-Za-z0-9_]+)$" }+ },+ "switches": { "type": "object", "additionalProperties": { "type": "boolean" } },+ "owner": { "type": "string", "pattern": "^WP[0-9]{2}$" },+ "replaces": { "type": ["string", "null"], "pattern": "^M_[A-Za-z0-9_]+$" }+ }+}diff --git a/art/verse/schema/placement.schema.json b/art/verse/schema/placement.schema.jsonnew file mode 100644index 0000000000..449e0d25a4--- /dev/null+++ b/art/verse/schema/placement.schema.json@@ -0,0 +1,276 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "$id": "https://dodaios.dev/schema/verse.placement-1.json",+ "title": "verse.placement/1",+ "description": "Placements of one deck zone in Unreal space (docs/verse/unreal/contracts/art-pipeline.md section 4). Checked by scripts/unreal/check_art_text.py, which adds the rules a schema cannot express (unique ids, bounds, unit quaternions, rooms).",+ "type": "object",+ "additionalProperties": false,+ "required": [+ "schema",+ "deck",+ "zone",+ "bounds_cm",+ "level",+ "source",+ "generator",+ "placements",+ "sockets",+ "rooms"+ ],+ "properties": {+ "schema": { "const": "verse.placement/1" },+ "deck": { "$ref": "#/$defs/lowerId" },+ "zone": { "$ref": "#/$defs/lowerId" },+ "bounds_cm": {+ "type": "object",+ "additionalProperties": false,+ "required": ["min", "max"],+ "properties": {+ "min": { "$ref": "#/$defs/vec3" },+ "max": { "$ref": "#/$defs/vec3" }+ }+ },+ "level": {+ "type": "string",+ "pattern": "^/Game/Verse/Decks/[A-Z][A-Za-z0-9]*/LV_[A-Za-z0-9_]+$"+ },+ "source": {+ "type": "object",+ "additionalProperties": false,+ "required": ["builder", "sha256"],+ "properties": {+ "builder": { "type": "string", "pattern": "^art/verse/[A-Za-z0-9_/.-]+\\.py$" },+ "sha256": { "$ref": "#/$defs/sha256" }+ }+ },+ "generator": {+ "type": "object",+ "additionalProperties": false,+ "required": ["script", "version", "blender"],+ "properties": {+ "script": { "type": "string", "minLength": 1 },+ "version": { "type": "string", "pattern": "^[0-9]+$" },+ "blender": { "type": "string", "pattern": "^[0-9]+\\.[0-9]+\\.[0-9]+$" }+ }+ },+ "placements": { "type": "array", "items": { "$ref": "#/$defs/placement" } },+ "sockets": { "type": "array", "items": { "$ref": "#/$defs/socket" } },+ "rooms": { "type": "array", "items": { "$ref": "#/$defs/room" } }+ },+ "$defs": {+ "lowerId": { "type": "string", "pattern": "^[a-z][a-z0-9_]*$" },+ "sha256": { "type": "string", "pattern": "^[0-9a-f]{64}$" },+ "vec3": {+ "type": "array",+ "minItems": 3,+ "maxItems": 3,+ "items": { "type": "number" }+ },+ "quat": {+ "type": "array",+ "minItems": 4,+ "maxItems": 4,+ "items": { "type": "number", "minimum": -1, "maximum": 1 }+ },+ "assetName": { "type": "string", "pattern": "^(SM|GC)_[A-Za-z0-9][A-Za-z0-9_]{0,60}$" },+ "objectPath": {+ "type": "string",+ "pattern": "^/Game/Verse/[A-Za-z0-9_/]+/([A-Za-z0-9_]+)\\.([A-Za-z0-9_]+)$",+ "maxLength": 180+ },+ "roomRef": {+ "anyOf": [{ "type": "null" }, { "type": "string", "pattern": "^[A-Za-z0-9][A-Za-z0-9_-]*$" }]+ },+ "station": {+ "anyOf": [+ { "type": "null" },+ {+ "type": "object",+ "additionalProperties": false,+ "required": ["id", "kind"],+ "properties": {+ "id": { "type": "string", "minLength": 1 },+ "kind": { "type": "string", "minLength": 1 }+ }+ }+ ]+ },+ "collision": {+ "enum": [+ "Verse_Architecture",+ "Verse_Destructible",+ "Verse_Glass",+ "Verse_Prop",+ "Verse_PropSmall",+ "Verse_Debris",+ "Verse_ProxyOnly",+ "Verse_NoCollision"+ ]+ },+ "destructibleState": { "enum": ["Intact", "Damaged", "Holed", "Breached", "Destroyed", "Repairing"] },+ "destructible": {+ "anyOf": [+ { "type": "null" },+ {+ "type": "object",+ "additionalProperties": false,+ "required": ["actor_class", "penetration_material", "health", "states", "proxies", "repair_s"],+ "properties": {+ "actor_class": { "type": "string", "pattern": "^/Script/[A-Za-z0-9]+\\.[A-Za-z0-9_]+$|^/Game/Verse/[A-Za-z0-9_/]+\\.[A-Za-z0-9_]+_C$" },+ "penetration_material": { "type": "string", "pattern": "^[A-Za-z][A-Za-z0-9_]*$" },+ "health": { "type": "number", "exclusiveMinimum": 0 },+ "states": {+ "type": "array",+ "minItems": 1,+ "uniqueItems": true,+ "items": { "$ref": "#/$defs/destructibleState" }+ },+ "proxies": {+ "type": "object",+ "propertyNames": { "$ref": "#/$defs/destructibleState" },+ "additionalProperties": { "$ref": "#/$defs/objectPath" }+ },+ "repair_s": { "type": "number", "minimum": 0 }+ }+ }+ ]+ },+ "placement": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "id",+ "piece",+ "asset",+ "location",+ "rotation",+ "scale",+ "room",+ "nav",+ "mobility",+ "data_layer",+ "collision",+ "destructible",+ "station",+ "owner"+ ],+ "properties": {+ "id": { "type": "string", "pattern": "^[a-z0-9_]+$", "maxLength": 96 },+ "piece": { "$ref": "#/$defs/assetName" },+ "asset": { "$ref": "#/$defs/objectPath" },+ "location": { "$ref": "#/$defs/vec3" },+ "rotation": { "$ref": "#/$defs/quat" },+ "scale": {+ "type": "array",+ "minItems": 3,+ "maxItems": 3,+ "items": { "type": "number", "exclusiveMinimum": 0 }+ },+ "room": { "$ref": "#/$defs/roomRef" },+ "nav": { "enum": ["walk", "block", "none"] },+ "mobility": { "enum": ["static", "movable"] },+ "data_layer": { "type": "string", "pattern": "^DL_[A-Z][A-Za-z0-9]*_[A-Z][A-Za-z0-9]*$" },+ "collision": { "$ref": "#/$defs/collision" },+ "material_overrides": {+ "type": "object",+ "propertyNames": { "pattern": "^[A-Za-z0-9_]+$" },+ "additionalProperties": { "type": "string", "pattern": "^/Game/Verse/Materials/[A-Za-z0-9_/]+/(MI_[A-Za-z0-9_]+)\\.(MI_[A-Za-z0-9_]+)$" }+ },+ "destructible": { "$ref": "#/$defs/destructible" },+ "station": { "$ref": "#/$defs/station" },+ "owner": { "type": "string", "pattern": "^WP[0-9]{2}$" },+ "tags": {+ "type": "array",+ "uniqueItems": true,+ "items": { "type": "string", "pattern": "^Verse(\\.[A-Za-z0-9_]+)+$" }+ }+ }+ },+ "socket": {+ "type": "object",+ "additionalProperties": false,+ "required": ["id", "kind", "location", "rotation", "room", "station"],+ "properties": {+ "id": { "type": "string", "pattern": "^[A-Za-z0-9][A-Za-z0-9_-]*$", "maxLength": 120 },+ "kind": {+ "enum": ["screen", "seat", "stand", "bunk", "holo", "light", "door", "spawn", "lift", "station", "waypoint"]+ },+ "location": { "$ref": "#/$defs/vec3" },+ "rotation": { "$ref": "#/$defs/quat" },+ "room": { "$ref": "#/$defs/roomRef" },+ "station": { "$ref": "#/$defs/station" },+ "size_cm": {+ "type": "array",+ "minItems": 2,+ "maxItems": 2,+ "items": { "type": "number", "exclusiveMinimum": 0 }+ },+ "light": {+ "type": "object",+ "additionalProperties": false,+ "required": ["type", "kelvin", "intensity_lm", "attenuation_cm", "shadows"],+ "properties": {+ "type": { "enum": ["spot", "rect", "point"] },+ "kelvin": { "type": "number", "minimum": 1000, "maximum": 20000 },+ "intensity_lm": { "type": "number", "minimum": 0 },+ "attenuation_cm": { "type": "number", "exclusiveMinimum": 0 },+ "cone_deg": { "type": "number", "exclusiveMinimum": 0, "maximum": 180 },+ "source_size_cm": { "type": "number", "minimum": 0 },+ "shadows": { "const": true }+ }+ },+ "spawn": {+ "type": "object",+ "additionalProperties": false,+ "required": ["team", "duel"],+ "properties": {+ "team": { "enum": ["any", "a", "b"] },+ "duel": { "type": "boolean" }+ }+ },+ "props": {+ "type": "object",+ "additionalProperties": { "type": "string" }+ }+ },+ "allOf": [+ {+ "if": { "properties": { "kind": { "const": "screen" } } },+ "then": { "required": ["size_cm"] },+ "else": { "not": { "required": ["size_cm"] } }+ },+ {+ "if": { "properties": { "kind": { "const": "light" } } },+ "then": { "required": ["light"] },+ "else": { "not": { "required": ["light"] } }+ },+ {+ "if": { "properties": { "kind": { "const": "spawn" } } },+ "then": { "required": ["spawn"] },+ "else": { "not": { "required": ["spawn"] } }+ }+ ]+ },+ "room": {+ "type": "object",+ "additionalProperties": false,+ "required": ["id", "name", "polygon_cm", "z_cm", "main"],+ "properties": {+ "id": { "type": "string", "pattern": "^[A-Za-z0-9][A-Za-z0-9_-]*$" },+ "name": { "type": "string", "minLength": 1 },+ "polygon_cm": {+ "type": "array",+ "minItems": 3,+ "items": {+ "type": "array",+ "minItems": 2,+ "maxItems": 2,+ "items": { "type": "number" }+ }+ },+ "z_cm": { "type": "number" },+ "main": { "type": "boolean" }+ }+ }+ }+}diff --git a/docs/verse/unreal/arena.md b/docs/verse/unreal/arena.mdnew file mode 100644index 0000000000..b3c88cb20c--- /dev/null+++ b/docs/verse/unreal/arena.md@@ -0,0 +1,200 @@+# Hangar arena (WP11)++Deck 4 is a normal deck day to day and turns into a dense, three-level,+destructible 1v1 arena on demand (README, Arena and Mode). This file is the+layout spec of WP11.1 and the reference for the other WP11 sub-tasks. The+layout itself is code: `art/verse/decks/hangar/unreal_arena/layout.py` holds+every box, stair, spawn, light and station once; the numbers below come from+it and from the flow report its tool writes.++```text+python art/verse/decks/hangar/unreal_arena_build.py # placements, flow report, plans+python -m pytest tests/verse/test_verse_hangar_arena.py # A11.1, A11.2, A11.5, A11.7 (static)+```++## 1. Frame++Plan metres in the frame of `hangar_layout.py` and `coordinates.md` 3.1:+`x` east (0 = west hull wall, 100 = east), `z` toward the near wall (0 = the+hero wall, 62 = the near wall), `h` height above the hall floor. Unreal space+is `(100 x, 100 z, 100 h)` cm. The three.js numbers do not carry over (README,+"What carries over").++| Item | Value |+|---|---|+| Hall | 100 x 62 m, ceiling underside at 21 m, hull walls and hero wall solid concrete |+| Hall floor | concrete, `Verse_Architecture`, no `destructible` block: never breaks (A11.7) |+| Launch well | opening x 27..37, z 9..19, 26 m deep, railed; the pit is outside the nav. This supersedes the well of `hangar_layout.py` (x 8..38, z 8..20) and the worked example of coordinates 3.1 for the Unreal hangar: WP12 day zones and WP15 crew sockets must keep clear of x 27..37, z 9..19 and may use the old well area as floor |+| Arena | x 25..75, z 4..44: 50 x 40 m, walkable extent 49 x 39.5 m |+| Levels | L0 floor 0 m, L1 3.0 m, L2 6.0 to 6.3 m |+| Perimeter | blast barriers 4.5 m plus a see-through fence to 10 m on all four edges, arena layer only; the north run (z 3.4..4) stops at the hero pier (x 49..51), which closes the gap. Checked by `test_arena_is_sealed_from_the_hall`: nav built over the whole hall in arena mode, no node outside the arena reaches one inside |++## 2. Zones++| Zone | Owner | Data layer | Holds |+|---|---|---|---|+| `shell` | WP11 | `DL_Hangar_Base` (perimeter: `DL_Hangar_Arena`) | Floor slabs, hull and hero walls, ceiling, launch well, hero pier, truss columns, perimeter, work lights |+| `arena_canyon` | WP11 | `DL_Hangar_Arena` | Three container rows (x 60.6, 66.6, 72.6; 2.4 m wide, 3.0 m tall), 3.6 m aisles, staggered cross alleys, shut doors on every second container, bridge to the shuttle roof, south stair to the R2 roofs |+| `arena_shuttle` | WP11 | `DL_Hangar_Arena` | The walkable gunship (x 46..54, z 15..33): armoured hull, side hatches, open tail, inner bulkhead with a breakable service panel, roof deck at L1 with a turret; ground cover around the pad |+| `arena_booth` | WP11 | `DL_Hangar_Arena` | The glazed lookout (x 25..38, z 32..44): lower room at L1 with breakable glass to the east, upper room at L2, inner stair, floor stair, bridge to the shuttle |+| `arena_catwalks` | WP11 | `DL_Hangar_Arena` | North runs at L2 split by the hero pier, west leg, launch-well crossing and landing, enclosed south gallery on a solid deck, ceiling panels, hanging screens, the hung container, the stairs between levels |+| `armoury` | WP11 | `DL_Hangar_Base` | Loadout room x 77..97.5, z 47.2..61.6; the `armoury` station (WP16 class, WP18 panel) and the loadout board |+| `lift_lobby`, `day_stations` | WP12 | `DL_Hangar_Base`, `DL_Hangar_Day` | Not in this package |++Every placement carries `owner: "WP11"` and the tag+`Verse.Material.<penetration material>`. Pieces that never break use+`Verse_Architecture` (or `Verse_Prop` for pawn-only railings and fences);+breakable ones use `Verse_Destructible` with the class of+`/Script/VerseDestruction.VerseDestructible` (WP06).++## 3. Levels, lanes and cover rhythm++Nav shares (A11.1, at least 15 % each): L0 65.0 %, L1 18.4 %, L2 16.5 % of+1,949 m², one connected island.++| Link | From | To |+|---|---|---|+| Booth floor stair | L0 south corridor (z 42) | L1 booth door, bridge to the shuttle |+| Booth inner stair | L1 booth | L2 booth upper room |+| R2 stair | L0 south end of aisle 2 | L1 roofs of R2 containers 4-5 |+| Catwalk to canyon | L2 north run (east) | L1 roofs of R1 containers 1-2, bridge to the shuttle roof |+| Well crossing stair | L2 well landing | L1 shuttle roof |+| Gallery stair | L0 corridor x 58..60 | L2 south gallery, which leads into the booth upper room |+| West leg | L2 north run (west) | L2 booth upper room |++Lanes:++- **Canyon** (east): three 3.6 m aisles along z, cross alleys offset per row+ so no alley runs the whole width. Container walls are `container_wall`+ (300 HP, bullets hole, charges breach), so the canyon opens over a match;+ drones close it again after about 60 s (destruction 7).+- **Shuttle** (middle): the hull is armour and never breaks; the interior is+ a short close-range lane with two side hatches and an open tail. The+ bulkhead's service panel is the only breakable part, a choice to open a+ through-lane.+- **West floor**: the well with its railing (see-through, not walkable), the+ well crossing above it, crates and cover walls on the floor.+- **Upper ring**: north runs, west leg, booth upper room and the enclosed+ south gallery form an L2 loop. The north run is split by the hero pier, the+ gallery has sheet-metal walls (bolts hole them, charges breach them), so+ every long upper sightline has to be opened first.++Cover rhythm: the flow tool placed 40 blockers (`COVER` in `layout.py`):+18 hanging blast screens (bottom 3.6 m or 5.0 m, top 9 m) cut the upper+diagonals, 9 cover walls (3.4 m) and a crate the floor lanes, 12 truss+columns both.+After them no unbroken sightline in the arena exceeds 40 m (section 6).++## 4. Spawns++`AVerseSpawnPoint` actors from the `spawn` sockets (`team: any`,+`duel: true`, probe heights 0.3, 1.0, 1.65 m). Nine spawns, every pair at+least 22.6 m apart by path (A11.2 asks 20 m).++| Id | Plan (x, z, h) m | Heading |+|---|---|---|+| `sp_nw_floor` | 26.0, 5.0, 0 | 45 |+| `sp_north_mid` | 48.0, 8.0, 0 | 90 |+| `sp_ne_canyon` | 70.8, 6.0, 0 | 90 |+| `sp_e_canyon` | 71.0, 40.0, 0 | 270 |+| `sp_south_mid` | 48.5, 43.0, 0 | 270 |+| `sp_booth` | 31.5, 40.5, 3.0 | 0 |+| `sp_cat_west` | 26.2, 18.0, 6.0 | 90 |+| `sp_shuttle_roof` | 50.0, 30.5, 3.0 | 270 |+| `sp_cat_gantry` | 57.5, 37.2, 6.0 | 180 |++Selection and protection are `UVerseRuleset_Deathmatch` (combat-state 9.2,+9.3): out of the opponent's sight if any spawn is, then the farthest by path,+ties within 1 m by `VerseRng(match seed, death count)`; a spawn with a pawn,+Bulwark or armed breach charge within 3 m is skipped. Path length is the+navmesh path from the opponent's floor point (`APawn::GetNavAgentLocation`)+to the spawn floor, queried through reflection on+`UNavigationSystemV1::FindPathToLocationSynchronously` (VerseCombat has no+NavigationSystem module edge); no path falls back to the Euclidean distance.+The spawn list is sorted by `SpawnId`, then actor name, before the tie break,+so a seeded match picks the same spawns however World Partition loads them.++## 5. Destructibles++Every breakable piece is solid at its material's reference thickness+(destruction 9), checked by `test_destructibles_are_solid_at_their_reference_thickness`.++| Class | Material | Pieces | Where |+|---|---|---|---|+| Container wall | `container_wall`, 4 mm | 34 | Canyon long walls and shut doors |+| Ceiling panel | `ceiling_panel`, 25 mm | 26 | Over the north runs, at 9 m |+| Catwalk segment | `catwalk_grating`, 30 mm | 23 | North runs, west leg, well crossing, bridges (charges only) |+| Wall panel | `sheet_metal`, 3 mm | 15 | South gallery walls, shuttle service panel |+| Cladding wall | `cladding_panel`, 40 mm | 8 | Booth lower room north and south faces |+| Glass pane | `glass`, 24 mm | 8 | Booth lower room east face, upper room south face |++Arena on and arena off both run the full destruction reset (destruction 11);+the switch raises the event, VerseDestruction does the reset.++## 6. Flow (WP11.11)++`unreal_arena/flow.py` measures the layout on a 0.5 m 2.5D nav grid (body+radius 0.3 m, height 1.8 m, step 0.5 m). Sight runs eye to eye at 1.65 m;+glass, grating, railings and the fence let sight through, as in the game.++| Measure | Value | Gate |+|---|---|---|+| Longest unbroken sightline (2 m lattice, 262,450 pairs) | 38.8 m | A11.5: at most 40 m |+| Sightline histogram, 5 m bins from 0 | 4625, 9284, 9367, 5939, 3656, 1524, 780, 176, 0 | |+| Time to contact, walker model, 120 runs | median 6.25 s (p10 1.0 s, p90 14.8 s) | A11.5: 6-15 s for normal vs normal |+| Hider (explorer seeker vs camper on the 8 least-seen spots), 60 runs | median 17.25 s | BG12 with `hider`: at most 25 s |++The walker and explorer are design-time stand-ins: seeded, deterministic,+4.8 m/s, no hearing. A11.5 is final only with normal-tier bots from the+harness: `unreal_arena_build.py --bot-log <runs.jsonl>` adds the bot runs+(`{"run", "t_contact_s"}` per line) to the report.++## 7. Day and arena switch (WP11.8)++`UVerseHangarSwitchSubsystem` (VerseDecks, server): unloads one of+`DL_Hangar_Day` / `DL_Hangar_Arena`, activates the other, waits for+streaming, then raises `FVerseArenaSwitchEvent {bArenaOn, Deck: "hangar"}` on+the hub. The listeners do the rest: `AVerseGameMode` starts the match (arena+on) and the ruleset ends it with an `Unfinished` summary (arena off),+VerseDestruction resets, VerseCrew walks the crew out of the arena bounds+(`ArenaBoundsCm`). Entries: the armoury station and the Verse bar quick start+call `RequestArena`; the bridge's `lifecycle.show {reason: "quick_start_duel"}`+goes through `HandleLifecycleShow`. A switch over 2.0 s is logged (A11.4);+stuck layers finish after 10 s.++## 8. Rules (WP11.9, WP11.10)++`AVerseGameMode` is the forwarder of combat-state 10; deathmatch start values+are text in `unreal/Verse/Data/rules/deathmatch.json` (`verse.rules/1`:+respawn 3.0 s, protection 2.0 s, first to 10, no regeneration, armour 0).+The ruleset keeps per-set lines from the hub (fire, hit, gadget, fracture,+death) and raises one `FVerseSetSummary` per finished set and one+`Unfinished` summary when the arena closes or the Verse quits mid-set.++## 9. Lighting (WP11.12)++Hard work lights from the roof truss (20 spots at 18.5 m, 4300 K, 55°),+low aisle spots in the canyon (4300 K), rect lights in the booth, the+gunship cabin, the catwalk ceiling and the armoury (4500 K): all inside the+4300-6500 K of art-pipeline 8.2. All movable with shadows (art-pipeline 6.3:+Lumen only).++Haze and post are data in `layout.py` (`HAZE`, `POST`), written to+`look.json` by the build tool: exponential height fog (density 0.035,+falloff 0.12, start 4 m) plus volumetric fog with neutral grey scattering+(albedo saturation 0, art-pipeline 8.3), Lumen GI and reflections, manual+exposure. The placement schema has no volume kind, so the level owner puts+the fog actor and the post volume into `LV_Hangar` from these values (open,+below). Palette shares of art-pipeline 8.1 are measured on the rendered build.++## 10. Open items++| Item | Needs |+|---|---|+| Placement files into `unreal/Verse/Art/Placements/hangar/` and `sync_placements` into `LV_Hangar` | Graybox meshes `SM_<Family>` / `GC_<Family>` and their import records: the static gate refuses placements without records. The `deck` mode of `scripts/verse/export_unreal.py` is reserved and owned by the integration owner |+| Fog actor and post volume in `LV_Hangar` | The level owner, from `look.json` (no volume kind in `verse.placement/1`) |+| Screenshots, palette shares, perf JSON, 600 MB deck budget (A11.6), switch timing in the real level (A11.4) | The imported level and the visual lane (WP10.8) |+| A11.4 "0 pieces not Intact, 0 crew in the arena" | WP06 reset and WP15 crew listeners on `OnArenaSwitch` |+| A11.5 with bots, BG12 | WP08 decisions and WP10 Gauntlet runs |+| A11.7 1,000 breach charges on the floor | WP06 pieces and WP02 gadgets; the floor has no destructible block today |+| `lifecycle.show` wiring | WP17 calls `HandleLifecycleShow` from the bridge client |diff --git a/docs/verse/unreal/contracts/art-pipeline.md b/docs/verse/unreal/contracts/art-pipeline.mdindex e3c0bf230e..956970934e 100644--- a/docs/verse/unreal/contracts/art-pipeline.md+++ b/docs/verse/unreal/contracts/art-pipeline.md@@ -40,8 +40,9 @@ flowchart LR| Step | Command (planned) | Runs where | Lock ||---|---|---|---|| Export | `python scripts/verse/export_unreal.py {piece <SM_Name> \| deck <deck> [--zone <zone>] \| characters \| weapons \| textures}` | Blender via `scripts/verse/blender.py` | `scripts/unreal/with_lock.py` (the machine-wide `gpu-heavy.lock`, architecture 8.2) |-| Import | `python scripts/unreal/import_art.py {assets \| placements} [--deck D --zone Z] [--only NAME,...]` | `UnrealEditor-Cmd.exe unreal/Verse/Verse.uproject -run=pythonscript -script=verse_pipeline.cli -unattended -nosplash -nullrhi` | same lock |-| Validate | `python scripts/unreal/import_art.py validate` | same commandlet; also in `unreal-build` | same lock |+| Import | `python scripts/unreal/import_art.py {assets \| placements} [--deck D --zone Z] [--only NAME,...]` | `UnrealEditor-Cmd.exe unreal/Verse/Verse.uproject -ExecutePythonScript=<Content/Python/verse_pipeline/cli.py> -unattended -nosplash -nullrhi` (a headless editor, not the `pythonscript` commandlet: asset import tasks need the Slate application, which a commandlet does not create) | same lock |+| Validate | `python scripts/unreal/import_art.py validate` | same headless editor; also in `unreal-build` | same lock |+| Calibrate | `python scripts/unreal/import_art.py calib [--export]` | export, then the same headless editor (6.1) | same lock || Static check (no engine) | `python scripts/unreal/check_art_text.py` | `unreal-static` lane, GitHub-hosted, LFS not fetched | none |Parallel agents call only these scripts, never Blender or UnrealEditor@@ -226,7 +227,8 @@ exercised on FBX; one format means one calibration.|---|---|| Scope | One FBX per asset (one kit master, prop, character, weapon or clip set); piece space as authored (origin on the floor, centred, `kit/README.md`) || Export settings | One frozen settings set, id `fbx-ue/1`, in `art/verse/lib/unreal_export.py` (unit scale, axes, smoothing by face, tangent space, no leaf bones, no embedded textures, deform bones only). It is frozen when the calibration test passes |-| Calibration | `SM_Calib_Axes` (an asymmetric arrow: long +X, short +Y, tall +Z, one chamfer) and `SK_Calib_Rig`; a UE automation test checks bounds, facing and the first bone's rest transform against `space_vectors.json`. Any change to `fbx-ue/1` reruns it |+| Calibration | `SM_Calib_Axes` (an asymmetric arrow: long +X, short +Y, tall +Z, one chamfer) and `SK_Calib_Rig` (`art/verse/kit/calib.py`); `verse_pipeline.calib` imports both headless and checks bounds, the chamfer, tip normals, triangle winding against the engine cube, bone positions and the first bone's rest rotation and scale against `space_vectors.json`. Any change to `fbx-ue/1` reruns it |+| Calibrated facts (G0.7) | Data is exported in centimetres with a scene unit scale of 0.01 (in metres the armature node carries a scale of 100 into the first bone); the importer is the engine default (Interchange) with `convert_scene=True`, `force_front_x_axis=False`, `convert_scene_unit=False`; a rig's `Root` bone points along Blender +Y with roll 0, so its rest rotation is identity in Unreal. The export pins the FBX header time and object ids, so the same scene gives the same bytes and `export.sha256` changes only with the art || Mesh hygiene | Manifold where the piece is destructible, no zero-area faces, no doubled faces, normals out, bevels as real geometry (style bible §3 "bevel everything"), no single-sided planes in architecture || UV0 | Box-projected in real metres by the builder (1 UV unit = 1 m) when the piece has no authored UVs; authored UVs for characters, weapons, hero props || UV1 | Not exported (no lightmaps) |diff --git a/scripts/ci/run_gates.py b/scripts/ci/run_gates.pyindex 4eb94dafe5..92ab5271fd 100644--- a/scripts/ci/run_gates.py+++ b/scripts/ci/run_gates.py@@ -59,6 +59,7 @@ def _gates(base: str) -> list[Gate]:Gate("plugin-auth-contract", ((PY, ci + "check_plugin_auth_contract.py"),)),Gate("unreal-build-dag", ((PY, "scripts/unreal/check_build_dag.py"),)),Gate("unreal-forbidden-names", ((PY, "scripts/unreal/check_forbidden_names.py"),)),+ Gate("unreal-art-text", ((PY, "scripts/unreal/check_art_text.py"),)),Gate("reference-docs",(diff --git a/scripts/unreal/art_common.py b/scripts/unreal/art_common.pynew file mode 100644index 0000000000..0984bbb8f5--- /dev/null+++ b/scripts/unreal/art_common.py@@ -0,0 +1,115 @@+"""Shared paths, records and the machine-wide lock of the art pipeline entries.++Used by `scripts/verse/export_unreal.py`, `scripts/unreal/import_art.py` and+`scripts/unreal/check_art_text.py` (docs/verse/unreal/contracts/art-pipeline.md+sections 2 and 10). Pure Python; no Blender, no Unreal.+"""++from __future__ import annotations++import json+import os+import sys+import time+from collections.abc import Iterator+from contextlib import contextmanager+from pathlib import Path++REPO_ROOT = Path(__file__).resolve().parents[2]+ART_ROOT = REPO_ROOT / "art" / "verse"+CACHE_ROOT = ART_ROOT / ".cache" / "unreal"+PROJECT_DIR = REPO_ROOT / "unreal" / "Verse"+UPROJECT = PROJECT_DIR / "Verse.uproject"+ART_TEXT = PROJECT_DIR / "Art"+PLACEMENTS = ART_TEXT / "Placements"+IMPORT_RECORDS = ART_TEXT / "Import"+MI_RECIPES = ART_TEXT / "Materials"+SPACE_VECTORS = ART_TEXT / "space_vectors.json"+CONTENT_VERSE = PROJECT_DIR / "Content" / "Verse"+SCHEMA_DIR = ART_ROOT / "schema"++LOCK_DIR_ENV = "DODAIOS_LOCK_DIR"+HELD_ENV = "DODAIOS_GPU_LOCK_HELD"+DEFAULT_LOCK_DIR = Path("C:/demo/.locks")+++def lock_path() -> Path:+ """The machine-wide `gpu-heavy.lock` (orchestration.md 4, architecture 8.2)."""+ override = os.environ.get(LOCK_DIR_ENV, "").strip()+ if override:+ return Path(override) / "gpu-heavy.lock"+ if os.name == "nt":+ return DEFAULT_LOCK_DIR / "gpu-heavy.lock"+ return Path.home() / ".cache" / "dodaios" / "locks" / "gpu-heavy.lock"+++@contextmanager+def heavy_lock(label: str) -> Iterator[None]:+ """Hold the machine-wide lock; waiters queue, never fail.++ Uses `scripts/unreal/with_lock.py` (FIFO queue, holder file, 90 minute+ hold limit) when it is present, else the same OS file lock directly. A job+ started under the lock (`DODAIOS_GPU_LOCK_HELD`) does not queue again.+ """+ if os.environ.get(HELD_ENV):+ yield+ return+ try:+ if str(REPO_ROOT) not in sys.path:+ sys.path.insert(0, str(REPO_ROOT))+ from scripts.unreal import with_lock+ except ImportError:+ with_lock = None+ if with_lock is not None and hasattr(with_lock, "held"):+ with with_lock.held(label, sys.argv):+ yield+ return+ from filelock import FileLock, Timeout++ path = lock_path()+ path.parent.mkdir(parents=True, exist_ok=True)+ lock = FileLock(str(path))+ started = time.monotonic()+ announced = False+ while True:+ try:+ lock.acquire(timeout=10)+ break+ except Timeout:+ if not announced:+ print(f"[verse] {label}: waiting for {path}", flush=True)+ announced = True+ if announced:+ print(f"[verse] {label}: lock acquired after {time.monotonic() - started:.0f} s")+ os.environ[HELD_ENV] = label+ try:+ yield+ finally:+ os.environ.pop(HELD_ENV, None)+ lock.release()+++def load_lib(name: str):+ """Import a pure module of `art/verse/lib` (e.g. `placement`, `ue_space`)."""+ art = str(ART_ROOT)+ if art not in sys.path:+ sys.path.insert(0, art)+ module = __import__(f"lib.{name}", fromlist=[name])+ return module+++def dump_json(path: Path, payload: dict) -> bool:+ """Write sorted, 2-space, LF JSON; return True when the file changed."""+ text = json.dumps(payload, indent=2, sort_keys=True, ensure_ascii=True) + "\n"+ if path.is_file() and path.read_text(encoding="utf-8") == text:+ return False+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_bytes(text.encode("utf-8"))+ return True+++def rel(path: Path) -> str:+ try:+ return path.resolve().relative_to(REPO_ROOT).as_posix()+ except ValueError:+ return str(path)diff --git a/scripts/unreal/check_art_text.py b/scripts/unreal/check_art_text.pynew file mode 100644index 0000000000..db9d0c7285--- /dev/null+++ b/scripts/unreal/check_art_text.py@@ -0,0 +1,513 @@+#!/usr/bin/env python3+"""Static check of the Verse art text, no engine and no LFS content (art-pipeline 10.3, 14).++Runs in the `unreal-static` lane and in `scripts/ci/run_gates.py`. It fails on:++* placement JSON (`unreal/Verse/Art/Placements/<deck>/<zone>.placement.json`)+ that breaks the `verse.placement/1` schema or its rules (`lib/placement.py`),+ or names an asset without an import record;+* import records (`Art/Import/**/<Name>.import.json`) that break `verse.import/1`,+ have no asset, break the naming rules of section 3, exceed a cap of 6.2,+ 6.4 or 10.4, cite an unknown ledger row (section 11) or name the wrong owner+ for their content folder (section 9);+* MI recipes (`Art/Materials/MI_*.mi.json`) that break `verse.mi/1` or use a+ banned colour (section 8.3);+* a `.uasset` of an imported kind under `Content/Verse/` with no record, any+ asset name outside section 3, engine sample content (section 11), and+ banned folder names under `unreal/` and `art/verse/` (section 10.1);+* a `space_vectors.json` that disagrees with `art/verse/lib/ue_space.py`.++ python scripts/unreal/check_art_text.py # the repository+ python scripts/unreal/check_art_text.py --root D # another checkout (tests)+"""++from __future__ import annotations++import argparse+import colorsys+import json+import re+import subprocess+import sys+from collections.abc import Iterable+from pathlib import Path++REPO_ROOT = Path(__file__).resolve().parents[2]++# --------------------------------------------------------------------------+# Rules from the contract+# --------------------------------------------------------------------------++NAME_MAX = 64+OBJECT_PATH_MAX = 180++#: Section 3 prefixes of assets under /Game/Verse.+ASSET_PREFIXES = (+ "SM_", "GC_", "SK_", "SKEL_", "PHYS_", "IKRig_", "RTG_", "A_", "AM_", "BS_", "ABP_",+ "M_", "MF_", "MI_", "T_", "SW_", "MS_", "NS_", "DA_", "LV_", "DL_", "BP_",+) # fmt: skip+TEXTURE_SUFFIXES = ("_BC", "_N", "_ORM", "_E", "_M")+NAME_RE = re.compile(r"^[A-Za-z][A-Za-z0-9]*_[A-Za-z0-9][A-Za-z0-9_]*$")++#: Import record kind -> name rule.+KIND_NAMES = {+ "static_mesh": re.compile(r"^SM_[A-Za-z0-9_]+$"),+ "proxy_mesh": re.compile(+ r"^SM_[A-Za-z0-9]+(?:_[A-Za-z0-9]+)*_Proxy_(Intact|Holed|Breached|Destroyed)$"+ ),+ "skeletal_mesh": re.compile(r"^SK_[A-Za-z0-9_]+$"),+ "skeleton": re.compile(r"^SKEL_[A-Za-z0-9_]+$"),+ "physics_asset": re.compile(r"^PHYS_[A-Za-z0-9_]+$"),+ "animation": re.compile(r"^A_[A-Za-z0-9_]+$"),+ "texture": re.compile(rf"^T_[A-Za-z0-9_]+(?:{'|'.join(TEXTURE_SUFFIXES)})$"),+ "geometry_collection": re.compile(r"^GC_[A-Za-z0-9_]+$"),+}+#: Prefixes whose assets come from an import record (a .uasset needs one).+IMPORTED_PREFIXES = ("SM_", "SK_", "SKEL_", "PHYS_", "A_", "T_", "GC_")++#: Triangle caps of section 6.2, first matching rule wins: (path prefix, name test, cap).+TRIANGLE_CAPS: tuple[tuple[str, str, int], ...] = (+ ("/Game/Verse/Kit/Architecture/", "", 500_000),+ ("/Game/Verse/Weapons/", "SK_Weapon_", 60_000),+ ("/Game/Verse/Weapons/", "SM_Weapon_", 150_000),+ ("/Game/Verse/Characters/", "SK_", 80_000),+ ("", "GC_", 300_000),+ ("", "_Proxy_", 2_000),+ ("", "SM_", 200_000),+)+TEXTURE_MAX = 2048+TEXTURE_MAX_FIRST_PERSON = 4096+MAX_BONES = {"character": 200, "weapon": 24}++#: Content folder ownership of section 9, longest prefix first.+FOLDER_OWNERS: tuple[tuple[str, str], ...] = (+ ("/Game/Verse/Materials/Master/", "WP14"),+ ("/Game/Verse/Materials/Instances/Weapons/", "WP14"),+ ("/Game/Verse/Materials/Instances/Characters/", "WP13"),+ ("/Game/Verse/Materials/Instances/Screens/", "WP16"),+ ("/Game/Verse/Materials/Instances/", "WP12"),+ ("/Game/Verse/Kit/", "WP12"),+ ("/Game/Verse/Characters/", "WP13"),+ ("/Game/Verse/Animations/", "WP13"),+ ("/Game/Verse/Weapons/", "WP14"),+ ("/Game/Verse/VFX/Weapons/", "WP14"),+ ("/Game/Verse/PostProcess/", "WP14"),+ ("/Game/Verse/Combat/Abilities/", "WP02"),+ ("/Game/Verse/Combat/Finisher/", "WP04"),+ ("/Game/Verse/Movement/", "WP01"),+ ("/Game/Verse/Destruction/_Holes/", "WP03"),+ ("/Game/Verse/Destruction/", "WP06"),+ ("/Game/Verse/Gore/", "WP05"),+ ("/Game/Verse/Bot/Tiers/", "WP09"),+ ("/Game/Verse/Bot/", "WP08"),+ ("/Game/Verse/Crew/", "WP15"),+ ("/Game/Verse/Screens/", "WP16"),+ ("/Game/Verse/UI/Stations/", "WP16"),+ ("/Game/Verse/UI/ServiceRecord/", "WP21"),+ ("/Game/Verse/UI/", "WP18"),+ ("/Game/Verse/Audio/", "WP19"),+)+_TEST_FOLDER = re.compile(r"^/Game/Verse/Test/(WP\d{2})/")+#: G0 fixtures built in the editor by scripts/unreal/g0_content.py (G0.9 SK_Test_Human and its+#: skeleton and physics asset), not by the art pipeline: they carry no import record.+G0_GENERATED = "/Game/Verse/Test/G0/"++#: Folder names that may not appear under unreal/ or art/verse/ (section 10.1).+BANNED_FOLDERS = {+ "build", "models", "env", "logs", "dist", "secrets", "credentials", "traces",+ "blobs", "video", "videos", "film", "films", "renders", "evidence", "recordings",+ "screenshots",+} # fmt: skip+ALLOWED_FOLDERS = {"unreal/Verse/Build"}++#: Engine sample content (section 11, "Scan").+ENGINE_CONTENT = re.compile(+ r"/Game/StarterContent|/Game/Characters/Mannequins|SKM_Manny|SKM_Quinn|SK_Mannequin",+ re.IGNORECASE,+)++#: Banned hues for MI vector parameters (section 8.3): (label, lo, hi, min sat, emissive only).+HUE_BANS = (+ ("cyan", 160.0, 210.0, 0.35, False),+ ("violet/purple/magenta", 250.0, 330.0, 0.2, False),+ ("saturated green light", 90.0, 160.0, 0.5, True),+ ("info blue light", 210.0, 250.0, 0.4, True),+)+GOLD_SRGB = (0xC8, 0xA2, 0x4A)+GOLD_DELTA_E = 6.0+++# --------------------------------------------------------------------------+# Helpers+# --------------------------------------------------------------------------+++def _art_lib(root: Path):+ art = str(root / "art" / "verse")+ if art not in sys.path:+ sys.path.insert(0, art)+ from lib import placement, ue_space++ return placement, ue_space+++def _validator(schema_path: Path):+ import jsonschema++ schema = json.loads(schema_path.read_text(encoding="utf-8"))+ jsonschema.Draft202012Validator.check_schema(schema)+ return jsonschema.Draft202012Validator(schema)+++def _schema_errors(validator, doc) -> list[str]:+ out = []+ for error in sorted(validator.iter_errors(doc), key=lambda e: list(e.absolute_path)):+ where = "/".join(str(p) for p in error.absolute_path) or "<root>"+ out.append(f"{where}: {error.message}")+ return out+++def _load_json(path: Path) -> tuple[object | None, list[str]]:+ raw = path.read_bytes()+ errors = ["line endings must be LF"] if b"\r\n" in raw else []+ try:+ return json.loads(raw.decode("utf-8")), errors+ except (UnicodeDecodeError, json.JSONDecodeError) as error:+ return None, [*errors, f"not valid JSON: {error}"]+++def asset_name(object_path: str) -> str:+ return object_path.rsplit("/", 1)[-1].split(".", 1)[0]+++def folder_owner(object_path: str) -> str | None:+ test = _TEST_FOLDER.match(object_path)+ if test:+ return test.group(1)+ deck_zone = re.match(r"^/Game/Verse/Decks/[^/]+/(?!DataLayers/)([^/]+)/", object_path)+ if deck_zone:+ return None # zone folders: owner from work-packages.md section 3, checked by owner field+ for prefix, owner in FOLDER_OWNERS:+ if object_path.startswith(prefix):+ return owner+ return None+++def name_errors(name: str) -> list[str]:+ errors = []+ if len(name) > NAME_MAX:+ errors.append(f"{name}: longer than {NAME_MAX} characters")+ if not name.isascii() or not NAME_RE.match(name):+ errors.append(f"{name}: not ASCII PascalCase segments joined by _ (art-pipeline 3)")+ if not name.startswith(ASSET_PREFIXES):+ errors.append(f"{name}: prefix not in art-pipeline section 3")+ if name.startswith("T_") and not name.endswith(TEXTURE_SUFFIXES):+ errors.append(f"{name}: texture needs a suffix {'/'.join(TEXTURE_SUFFIXES)}")+ return errors+++def triangle_cap(record: dict) -> int | None:+ path, name = record["asset_path"], record["name"]+ for prefix, test, cap in TRIANGLE_CAPS:+ if path.startswith(prefix) and test in name:+ return cap+ return None+++def ledger_hashes(root: Path) -> set[str]:+ path = root / "art" / "verse" / "LICENSES.md"+ if not path.is_file():+ return set()+ return set(re.findall(r"\b[0-9a-f]{64}\b", path.read_text(encoding="utf-8")))+++def _srgb(linear: float) -> float:+ linear = max(0.0, linear)+ return 12.92 * linear if linear <= 0.0031308 else 1.055 * linear ** (1 / 2.4) - 0.055+++def _lab(rgb: Iterable[float]) -> tuple[float, float, float]:+ """sRGB (0..1) -> CIE Lab (D65)."""++ def lin(c: float) -> float:+ return c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4++ r, g, b = (lin(c) for c in rgb)+ x = (0.4124 * r + 0.3576 * g + 0.1805 * b) / 0.95047+ y = 0.2126 * r + 0.7152 * g + 0.0722 * b+ z = (0.0193 * r + 0.1192 * g + 0.9505 * b) / 1.08883++ def f(t: float) -> float:+ return t ** (1 / 3) if t > 0.008856 else 7.787 * t + 16 / 116++ fx, fy, fz = f(x), f(y), f(z)+ return 116 * fy - 16, 500 * (fx - fy), 200 * (fy - fz)+++def colour_bans(name: str, rgba_linear: list[float], *, gold_allowed: bool) -> list[str]:+ """Section 8.3 hue tests on one MI vector parameter (linear RGBA)."""+ r, g, b = (min(1.0, _srgb(c)) for c in rgba_linear[:3])+ hue, sat, _value = colorsys.rgb_to_hsv(r, g, b)+ hue *= 360.0+ emissive = "emissive" in name.lower() or "light" in name.lower()+ hits = []+ for label, lo, hi, min_sat, emissive_only in HUE_BANS:+ if emissive_only and not emissive:+ continue+ if lo <= hue <= hi and sat > min_sat:+ hits.append(f"{name}: banned colour ({label}, hue {hue:.0f}, sat {sat:.2f})")+ if not gold_allowed:+ gold = _lab(c / 255 for c in GOLD_SRGB)+ lab = _lab((r, g, b))+ if sum((p - q) ** 2 for p, q in zip(lab, gold, strict=True)) ** 0.5 <= GOLD_DELTA_E:+ hits.append(f"{name}: brand gold outside art/verse/gold_allowlist.txt")+ return hits+++# --------------------------------------------------------------------------+# Checks+# --------------------------------------------------------------------------+++class Checker:+ def __init__(self, root: Path):+ self.root = root+ self.project = root / "unreal" / "Verse"+ self.art = self.project / "Art"+ self.content = self.project / "Content" / "Verse"+ self.schemas = root / "art" / "verse" / "schema"+ self.errors: list[str] = []++ def fail(self, path: Path | str, message: str) -> None:+ where = path.relative_to(self.root).as_posix() if isinstance(path, Path) else path+ self.errors.append(f"{where}: {message}")++ # -- records ----------------------------------------------------------++ def records(self) -> dict[str, dict]:+ validator = _validator(self.schemas / "import.schema.json")+ ledger = ledger_hashes(self.root)+ out: dict[str, dict] = {}+ folder = self.art / "Import"+ for path in sorted(folder.rglob("*.json")) if folder.is_dir() else []:+ if not path.name.endswith(".import.json"):+ self.fail(path, "import records are named <Asset>.import.json")+ continue+ doc, errors = _load_json(path)+ errors += _schema_errors(validator, doc) if doc is not None else []+ if errors:+ for error in errors:+ self.fail(path, error)+ continue+ self._record_rules(path, doc, ledger)+ if doc["asset_path"] in out:+ self.fail(path, f"second record for {doc['asset_path']}")+ out[doc["asset_path"]] = {**doc, "_file": path}+ return out++ def _record_rules(self, path: Path, doc: dict, ledger: set[str]) -> None:+ name, object_path = doc["name"], doc["asset_path"]+ if path.name != f"{name}.import.json":+ self.fail(path, f"file must be named {name}.import.json")+ if asset_name(object_path) != name or not object_path.endswith(f".{name}"):+ self.fail(path, f"asset_path {object_path} is not the asset {name}")+ if len(object_path) >= OBJECT_PATH_MAX:+ self.fail(path, f"object path longer than {OBJECT_PATH_MAX - 1} characters")+ for error in name_errors(name):+ self.fail(path, error)+ if not KIND_NAMES[doc["kind"]].match(name):+ self.fail(path, f"kind {doc['kind']} does not fit the name {name}")+ expected_owner = folder_owner(object_path)+ if expected_owner and doc["owner"] != expected_owner:+ self.fail(path, f"owner {doc['owner']}, the content folder belongs to {expected_owner}")+ mesh = doc.get("mesh")+ cap = triangle_cap(doc)+ override = doc.get("budget_override") or {}+ if mesh and cap and mesh["triangles"] > cap and override.get("field") != "triangles":+ self.fail(path, f"{mesh['triangles']} triangles, cap {cap} (art-pipeline 6.2)")+ if mesh and "bones" in mesh:+ limit = MAX_BONES["weapon" if "/Weapons/" in object_path else "character"]+ if len(mesh["bones"]) > limit and override.get("field") != "bones":+ self.fail(path, f"{len(mesh['bones'])} bones, cap {limit} (art-pipeline 10.4)")+ if doc["kind"] in ("static_mesh", "skeletal_mesh", "proxy_mesh") and not mesh:+ self.fail(path, "mesh records need a mesh block")+ texture = doc.get("texture")+ if doc["kind"] == "texture" and not texture:+ self.fail(path, "texture records need a texture block")+ if texture:+ limit = TEXTURE_MAX_FIRST_PERSON if texture["group"] == "Weapon" else TEXTURE_MAX+ if texture["max_size"] > limit and override.get("field") != "max_size":+ self.fail(path, f"texture max_size {texture['max_size']} > {limit}")+ if name.endswith("_N") and not texture["flip_green"]:+ self.fail(path, "normal maps flip green on import (art-pipeline 6.4)")+ if name.endswith(("_N", "_ORM", "_M")) and texture["srgb"]:+ self.fail(path, "_N, _ORM and _M textures are linear (srgb false)")+ if name.endswith(("_BC", "_E")) and not texture["srgb"]:+ self.fail(path, "_BC and _E textures are sRGB")+ license_ = doc["license"]+ if license_["kind"] == "ledger":+ cited = license_.get("ledger_sha256") or []+ if not cited:+ self.fail(path, "licence kind ledger needs ledger_sha256 rows")+ for digest in cited:+ if digest not in ledger:+ self.fail(path, f"ledger row {digest[:12]}... not in art/verse/LICENSES.md")+ elif license_.get("ledger_sha256"):+ self.fail(path, "own work cites no ledger rows")+ if ENGINE_CONTENT.search(json.dumps(doc)):+ self.fail(path, "engine sample content is forbidden (art-pipeline 11)")++ # -- placements -------------------------------------------------------++ def placements(self, records: dict[str, dict]) -> None:+ placement, _ = _art_lib(self.root)+ folder = self.art / "Placements"+ for path in sorted(folder.rglob("*")) if folder.is_dir() else []:+ if path.is_dir():+ continue+ if not path.name.endswith(".placement.json"):+ self.fail(path, "only <zone>.placement.json files live under Placements/")+ continue+ for error in placement.validate_file(path, known_assets=set(records)):+ self.fail(path, error)+ text = path.read_text(encoding="utf-8", errors="replace")+ if ENGINE_CONTENT.search(text):+ self.fail(path, "engine sample content is forbidden (art-pipeline 11)")++ # -- material instances ---------------------------------------------++ def materials(self) -> None:+ validator = _validator(self.schemas / "mi.schema.json")+ allow = self.root / "art" / "verse" / "gold_allowlist.txt"+ gold_ok = set(allow.read_text(encoding="utf-8").split()) if allow.is_file() else set()+ folder = self.art / "Materials"+ for path in sorted(folder.rglob("*")) if folder.is_dir() else []:+ if path.is_dir():+ continue+ if not path.name.endswith(".mi.json"):+ self.fail(path, "only MI_<Name>.mi.json recipes live under Art/Materials/")+ continue+ doc, errors = _load_json(path)+ errors += _schema_errors(validator, doc) if doc is not None else []+ if errors:+ for error in errors:+ self.fail(path, error)+ continue+ if path.name != f"{doc['name']}.mi.json":+ self.fail(path, f"file must be named {doc['name']}.mi.json")+ for param, value in sorted(doc["vectors"].items()):+ for hit in colour_bans(param, value, gold_allowed=doc["name"] in gold_ok):+ self.fail(path, hit)++ # -- content tree ---------------------------------------------------++ def content_tree(self, records: dict[str, dict]) -> None:+ on_disk = set()+ if self.content.is_dir():+ for path in sorted(self.content.rglob("*")):+ if path.suffix not in (".uasset", ".umap"):+ continue+ rel = path.relative_to(self.content).with_suffix("")+ name = rel.name+ object_path = f"/Game/Verse/{rel.as_posix()}.{name}"+ on_disk.add(object_path)+ for error in name_errors(name):+ self.fail(path, error)+ generated = object_path.startswith(G0_GENERATED)+ imported = name.startswith(IMPORTED_PREFIXES) and not generated+ if path.suffix == ".uasset" and imported:+ if object_path not in records:+ self.fail(path, "no import record in unreal/Verse/Art/Import/")+ if ENGINE_CONTENT.search(object_path):+ self.fail(path, "engine sample content is forbidden (art-pipeline 11)")+ for object_path, record in sorted(records.items()):+ if object_path not in on_disk:+ self.fail(+ record["_file"],+ f"record has no asset (import it: python scripts/unreal/import_art.py"+ f" assets --only {record['name']})",+ )++ def folders(self) -> None:+ for rel in _tracked(self.root, ("unreal", "art/verse")):+ parts = rel.split("/")[:-1]+ for depth, part in enumerate(parts):+ prefix = "/".join(parts[: depth + 1])+ if part.lower() in BANNED_FOLDERS and prefix not in ALLOWED_FOLDERS:+ self.fail(rel, f"folder name {part!r} is banned (art-pipeline 10.1)")+ break+ if ENGINE_CONTENT.search(rel):+ self.fail(rel, "engine sample content is forbidden (art-pipeline 11)")++ def space_vectors(self) -> None:+ path = self.art / "space_vectors.json"+ if not path.is_file():+ self.fail(path.relative_to(self.root).as_posix(), "missing")+ return+ _, ue_space = _art_lib(self.root)+ doc, errors = _load_json(path)+ for error in errors:+ self.fail(path, error)+ if doc is None:+ return+ for case in doc.get("blender_to_unreal", []):+ b, u = case["blender"], case["unreal"]+ got = ue_space.location_to_ue(b["location_m"])+ if any(abs(p - q) > 1e-6 for p, q in zip(got, u["location_cm"], strict=True)):+ self.fail(path, f"{case['name']}: location {got} != {u['location_cm']}")+ quat = ue_space.quat_to_ue(b["quat_wxyz"])+ if any(abs(p - q) > 1e-9 for p, q in zip(quat, u["quat_xyzw"], strict=True)):+ self.fail(path, f"{case['name']}: rotation {quat} != {u['quat_xyzw']}")+ for case in doc.get("yaw", []):+ if abs(ue_space.yaw_to_ue(case["blender_rot_z_deg"]) - case["unreal_yaw_deg"]) > 1e-9:+ self.fail(path, f"yaw {case['blender_rot_z_deg']} disagrees")+ for case in doc.get("three_to_unreal", []):+ got = ue_space.three_to_ue(case["three_m"])+ if any(abs(p - q) > 1e-6 for p, q in zip(got, case["unreal_cm"], strict=True)):+ self.fail(path, f"three {case['three_m']} -> {got} != {case['unreal_cm']}")++ def run(self) -> list[str]:+ records = self.records()+ self.placements(records)+ self.materials()+ self.content_tree(records)+ self.folders()+ self.space_vectors()+ return self.errors+++def _tracked(root: Path, scopes: tuple[str, ...]) -> list[str]:+ try:+ out = subprocess.run(+ ["git", "-C", str(root), "ls-files", "--cached", "--others", "--exclude-standard",+ "--", *scopes],+ capture_output=True, text=True, check=True,+ ).stdout # fmt: skip+ return [line for line in out.splitlines() if line]+ except (OSError, subprocess.CalledProcessError):+ files = []+ for scope in scopes:+ base = root / scope+ if base.is_dir():+ files += [p.relative_to(root).as_posix() for p in base.rglob("*") if p.is_file()]+ return files+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(+ description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter+ )+ parser.add_argument("--root", type=Path, default=REPO_ROOT)+ options = parser.parse_args(argv)+ errors = Checker(options.root.resolve()).run()+ for error in errors:+ print(f"check_art_text: {error}", file=sys.stderr)+ if errors:+ print(f"check_art_text: {len(errors)} problem(s)", file=sys.stderr)+ return 1+ print("check_art_text: ok")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/unreal/import_art.py b/scripts/unreal/import_art.pynew file mode 100644index 0000000000..c578b27d55--- /dev/null+++ b/scripts/unreal/import_art.py@@ -0,0 +1,177 @@+"""Import Verse art into the Unreal project and check it (art-pipeline 2).++The only import entry for agents. It runs the editor headless (no window,+`-nullrhi`) with a Python script under the machine-wide `gpu-heavy.lock`:++ UnrealEditor-Cmd.exe <Verse.uproject>+ -ExecutePythonScript=<Content/Python/verse_pipeline/cli.py>+ -unattended -nosplash -nullrhi -nosound -stdout++The `pythonscript` commandlet cannot be used: asset import tasks need the+Slate application, which a commandlet does not create (assertion+`CurrentApplication.IsValid()`).++ python scripts/unreal/import_art.py assets [--only SM_A,SM_B] [--no-save]+ python scripts/unreal/import_art.py placements --deck hangar [--zone arena_canyon] [--dry-run]+ python scripts/unreal/import_art.py validate [--only ...]+ python scripts/unreal/import_art.py calib [--export] [--importer interchange|legacy]++`calib` is the `fbx-ue/1` calibration test: with `--export` it first runs+`scripts/verse/export_unreal.py calib`, then imports `SM_Calib_Axes` and+`SK_Calib_Rig` without saving and checks them against+`unreal/Verse/Art/space_vectors.json`. Exit 0 only when every check passed.+The report lands in `unreal/Verse/Saved/ArtPipeline/<command>-<stamp>.json`.+The editor modules must be built (`Build.bat VerseEditor Win64 Development`).+"""++from __future__ import annotations++import argparse+import json+import os+import subprocess+import sys+import time+from pathlib import Path++HERE = Path(__file__).resolve().parent+sys.path.insert(0, str(HERE))++import art_common # noqa: E402++ENGINE_ENV = "DODAIOS_UE_ROOT"+DEFAULT_ENGINE = Path("C:/Program Files/Epic Games/UE_5.7")+CLI = art_common.PROJECT_DIR / "Content" / "Python" / "verse_pipeline" / "cli.py"+REPORT_DIR = art_common.PROJECT_DIR / "Saved" / "ArtPipeline"+TIMEOUT_S = 1800+++def engine_root() -> Path:+ override = os.environ.get(ENGINE_ENV, "").strip()+ return Path(override) if override else DEFAULT_ENGINE+++def editor_cmd() -> Path:+ exe = "UnrealEditor-Cmd.exe" if os.name == "nt" else "UnrealEditor-Cmd"+ platform = "Win64" if os.name == "nt" else "Linux"+ return engine_root() / "Engine" / "Binaries" / platform / exe+++def command_line(log: Path) -> list[str]:+ return [+ str(editor_cmd()),+ str(art_common.UPROJECT),+ f"-ExecutePythonScript={CLI}",+ "-unattended",+ "-nosplash",+ "-nullrhi",+ "-nosound",+ "-NoP4",+ "-stdout",+ "-FullStdOutLogOutput",+ f"-abslog={log}",+ ]+++def run_pipeline(argv: list[str]) -> tuple[int, dict, Path]:+ """Run verse_pipeline.cli with `argv`; return (exit code, report, report path)."""+ REPORT_DIR.mkdir(parents=True, exist_ok=True)+ stamp = time.strftime("%Y%m%d-%H%M%S")+ report_path = REPORT_DIR / f"{argv[0]}-{stamp}.json"+ log = REPORT_DIR / f"{argv[0]}-{stamp}.log"+ report_path.unlink(missing_ok=True)+ env = dict(+ os.environ,+ VERSE_PIPELINE_ARGS=json.dumps(argv),+ VERSE_PIPELINE_RESULT=str(report_path),+ VERSE_PIPELINE_QUIT="1",+ )+ command = command_line(log)+ if not editor_cmd().is_file():+ raise FileNotFoundError(f"{editor_cmd()} not found; set {ENGINE_ENV}")+ with art_common.heavy_lock(f"import_art {argv[0]}"):+ print(f"[verse] {' '.join(command)}", flush=True)+ completed = subprocess.run(+ command,+ env=env,+ cwd=str(art_common.REPO_ROOT),+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ timeout=TIMEOUT_S,+ check=False,+ )+ if not report_path.is_file():+ text = log.read_text(encoding="utf-8", errors="replace") if log.is_file() else ""+ tail = text.splitlines()[-40:]+ report = {"ok": False, "error": "the commandlet wrote no report", "log_tail": tail}+ else:+ report = json.loads(report_path.read_text(encoding="utf-8"))+ report["exit_code"] = completed.returncode+ report["log"] = str(log)+ art_common.dump_json(report_path, report)+ return (0 if report.get("ok") else 1), report, report_path+++def _print_report(report: dict) -> None:+ if report.get("error"):+ print(f"[verse] error: {report['error']}", file=sys.stderr)+ for key in ("SM_Calib_Axes", "SK_Calib_Rig"):+ if key in report:+ for line in report[key].get("errors", []):+ print(f"[verse] {key}: {line}", file=sys.stderr)+ for line in report.get("errors", []):+ print(f"[verse] {line}", file=sys.stderr)+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(+ description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter+ )+ sub = parser.add_subparsers(dest="command", required=True)+ assets = sub.add_parser("assets", help="import changed assets from their records")+ assets.add_argument("--only", default="")+ assets.add_argument("--no-save", action="store_true")+ placements = sub.add_parser("placements", help="sync a deck's zones from placement JSON")+ placements.add_argument("--deck", required=True)+ placements.add_argument("--zone")+ placements.add_argument("--dry-run", action="store_true")+ validate = sub.add_parser("validate", help="check imported assets against their records")+ validate.add_argument("--only", default="")+ calib = sub.add_parser("calib", help="the fbx-ue/1 calibration test")+ calib.add_argument("--export", action="store_true", help="export the calibration assets first")+ calib.add_argument("--importer", choices=("interchange", "legacy"))+ options = parser.parse_args(argv)++ forwarded: list[str] = [options.command]+ if options.command in ("assets", "validate") and options.only:+ forwarded += ["--only", options.only]+ if options.command == "assets" and options.no_save:+ forwarded.append("--no-save")+ if options.command == "placements":+ forwarded += ["--deck", options.deck]+ if options.zone:+ forwarded += ["--zone", options.zone]+ if options.dry_run:+ forwarded.append("--dry-run")+ if options.command == "calib":+ if options.export:+ export = HERE.parent / "verse" / "export_unreal.py"+ code = subprocess.call([sys.executable, str(export), "calib"])+ if code != 0:+ return code+ if options.importer:+ forwarded += ["--importer", options.importer]++ try:+ code, report, path = run_pipeline(forwarded)+ except (FileNotFoundError, subprocess.TimeoutExpired) as error:+ print(f"[verse] {error}", file=sys.stderr)+ return 1+ _print_report(report)+ verdict = "PASS" if code == 0 else "FAIL"+ print(f"[verse] import_art {options.command}: {verdict} (report {art_common.rel(path)})")+ return code+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/verse/_export_unreal_entry.py b/scripts/verse/_export_unreal_entry.pynew file mode 100644index 0000000000..1c116e7433--- /dev/null+++ b/scripts/verse/_export_unreal_entry.py@@ -0,0 +1,100 @@+"""Blender side of scripts/verse/export_unreal.py (run by scripts/verse/blender.py).++argv: <mode> [options]; modes:+ piece <SM_Name> --out DIR --result FILE [--module M ...]+ calib --out DIR --result FILE++Writes FBX files into DIR and a JSON summary into FILE that the host turns+into import records. Exceptions propagate, so Blender exits with 1.+"""++from __future__ import annotations++import argparse+import importlib+import inspect+import sys+from pathlib import Path++import bpy+from lib import kit, unreal_export++#: Kit modules that register pieces when imported (kit/README.md).+DEFAULT_MODULES = (+ "kit.architecture",+ "kit.props.command",+ "kit.props.industrial",+ "kit.calib",+)+++def _load(modules: list[str]) -> None:+ for name in modules:+ module = importlib.import_module(name)+ loader = getattr(module, "load_all", None)+ if callable(loader):+ loader()+++def _reset() -> None:+ """Empty the factory scene (Blender runs with --factory-startup)."""+ for obj in list(bpy.data.objects):+ bpy.data.objects.remove(obj, do_unlink=True)+ bpy.context.scene.unit_settings.system = "METRIC"+ bpy.context.scene.unit_settings.scale_length = 1.0+++def main(argv: list[str]) -> None:+ parser = argparse.ArgumentParser(prog="_export_unreal_entry")+ sub = parser.add_subparsers(dest="mode", required=True)+ piece = sub.add_parser("piece")+ piece.add_argument("name")+ piece.add_argument("--module", action="append", default=[])+ calib = sub.add_parser("calib")+ for p in (piece, calib):+ p.add_argument("--out", type=Path, required=True)+ p.add_argument("--result", type=Path, required=True)+ options = parser.parse_args(argv)++ _reset()+ results = []+ if options.mode == "piece":+ _load(options.module or list(DEFAULT_MODULES))+ results.append(_export_piece(options.name, options.out))+ else:+ from kit import calib as calib_kit++ _load(["kit.calib"])+ results.append(_export_piece("SM_Calib_Axes", options.out))+ rig = unreal_export.build_rig("SK_Calib_Rig", calib_kit.RIG_BONES, options.out)+ entry = rig.as_dict()+ entry["source"] = _source_of(calib_kit.build_rig_marker, {})+ results.append(entry)+ unreal_export.write_result(options.result, results)+ for result in results:+ print(f"[verse] exported {result['name']}: {result['triangles']} tris")+++def _source_of(fn, args: dict) -> dict:+ path = Path(inspect.getsourcefile(fn)).resolve()+ return {+ "builder": path.relative_to(unreal_export.REPO_ROOT).as_posix(),+ "function": fn.__name__,+ "module": fn.__module__,+ "args": {k: v for k, v in args.items() if isinstance(v, (int, float, str, bool))},+ }+++def _export_piece(name: str, out: Path) -> dict:+ pdef = kit.registry().get(name)+ if pdef is None:+ raise KeyError(f"unknown kit piece {name!r}")+ master = kit.build_master(name)+ result = unreal_export.export_static_mesh(name, master, out, root_name=kit.MASTER_ROOT)+ entry = result.as_dict()+ entry["source"] = _source_of(pdef.builder, pdef.params)+ entry["nav"] = pdef.nav+ return entry+++main(sys.argv[1:])diff --git a/scripts/verse/export_unreal.py b/scripts/verse/export_unreal.pynew file mode 100644index 0000000000..5aa1280f0b--- /dev/null+++ b/scripts/verse/export_unreal.py@@ -0,0 +1,194 @@+"""Export Verse art from the Blender builders to FBX for Unreal (art-pipeline 2).++The only export entry for agents. It runs headless Blender through+`scripts/verse/blender.py` while holding the machine-wide `gpu-heavy.lock`,+writes FBX files into the ignored cache `art/verse/.cache/unreal/` and, for+assets that ship, the committed import records+`unreal/Verse/Art/Import/<Kind>/<Asset>.import.json` (art-pipeline 10.3).++ python scripts/verse/export_unreal.py piece SM_Wall_480+ python scripts/verse/export_unreal.py calib+ python scripts/verse/export_unreal.py {deck <deck> [--zone Z] | characters | weapons | textures}++`calib` exports the `fbx-ue/1` calibration assets (`kit/calib.py`) into the+cache only; `python scripts/unreal/import_art.py calib` imports and checks+them. `deck`, `characters`, `weapons` and `textures` are reserved for the+packages that own that art (WP11/WP12, WP13, WP14) and exit 2 until they+land.+"""++from __future__ import annotations++import argparse+import json+import sys+from pathlib import Path++HERE = Path(__file__).resolve().parent+sys.path.insert(0, str(HERE))+sys.path.insert(0, str(HERE.parent / "unreal"))++import art_common # noqa: E402+import blender # noqa: E402++ENTRY = HERE / "_export_unreal_entry.py"+GENERATOR = "export_unreal.py"++#: Reserved modes and the package that owns them (work-packages.md).+RESERVED = {+ "deck": "WP12 (agent decks, hangar day zones) and WP11 (arena zones)",+ "characters": "WP13",+ "weapons": "WP14",+ "textures": "the package that creates the texture set",+}++#: Kit module prefix -> (content folder under /Game/Verse/Kit, record folder).+KIT_GROUPS = (+ ("kit.architecture", "Architecture"),+ ("kit.props", "Props"),+)+KIT_OWNER = "WP12"+PROP_SMALL_CM = 30.0+PROP_NANITE_MIN_TRIS = 300+++def _run_blender(mode_args: list[str], label: str) -> dict:+ out_dir = art_common.CACHE_ROOT / ("calib" if mode_args[0] == "calib" else "kit")+ result = art_common.CACHE_ROOT / "results" / f"{label}.json"+ result.unlink(missing_ok=True)+ args = [*mode_args, "--out", str(out_dir), "--result", str(result)]+ with art_common.heavy_lock(f"export_unreal {label}"):+ blender.run(ENTRY, args, lock=False, device="cpu", timeout=1800)+ return json.loads(result.read_text(encoding="utf-8"))+++def kit_group(module: str) -> str:+ for prefix, group in KIT_GROUPS:+ if module == prefix or module.startswith(prefix + "."):+ return group+ raise ValueError(f"{module}: not a kit module with a content folder")+++def collision_profile(group: str, bounds: dict) -> str:+ if group == "Architecture":+ return "Verse_Architecture"+ size = [hi - lo for lo, hi in zip(bounds["min"], bounds["max"], strict=True)]+ return "Verse_PropSmall" if max(size) < PROP_SMALL_CM else "Verse_Prop"+++def build_record(asset: dict, previous: dict | None) -> dict:+ """The `verse.import/1` record of an exported kit piece.++ Fields a person or package tuned by hand (nanite error, collision+ profile, lod, licence, owner, budget override) survive a re-export.+ """+ source = asset["source"]+ group = kit_group(source["module"])+ name = asset["name"]+ record = {+ "schema": "verse.import/1",+ "name": name,+ "asset_path": f"/Game/Verse/Kit/{group}/{name}.{name}",+ "kind": "static_mesh",+ "source": {+ "builder": source["builder"],+ "function": source["function"],+ "args": source["args"],+ },+ "export": {+ "format": "fbx",+ "settings_id": asset["settings_id"],+ "file": asset["file"],+ "sha256": asset["sha256"],+ "blender": asset["blender"],+ },+ "mesh": {+ "triangles": asset["triangles"],+ "vertices": asset["vertices"],+ "bounds_cm": asset["bounds_cm"],+ "uv_sets": asset["uv_sets"],+ "material_slots": asset["material_slots"],+ },+ "nanite": {"enabled": group == "Architecture" or asset["triangles"] > PROP_NANITE_MIN_TRIS},+ "collision": {+ "profile": collision_profile(group, asset["bounds_cm"]),+ "source": "authored" if asset["collision_primitives"] else "auto_box",+ "primitives": asset["collision_primitives"],+ },+ "lod": {"mode": "nanite"},+ "lightmap": "none",+ "license": {"kind": "own"},+ "owner": KIT_OWNER,+ }+ if asset["sockets"]:+ record["mesh"]["sockets"] = asset["sockets"]+ if not record["nanite"]["enabled"]:+ record["lod"] = {"mode": "single"}+ if previous:+ for key in ("nanite", "collision", "lod", "license", "owner", "budget_override"):+ if key in previous:+ record[key] = previous[key]+ record["collision"]["primitives"] = asset["collision_primitives"]+ return record+++def record_path(record: dict) -> Path:+ group = record["asset_path"].split("/")[4]+ return art_common.IMPORT_RECORDS / "Kit" / group / f"{record['name']}.import.json"+++def export_piece(name: str) -> int:+ payload = _run_blender(["piece", name], name)+ for asset in payload["assets"]:+ record = build_record(asset, None)+ path = record_path(record)+ previous = json.loads(path.read_text(encoding="utf-8")) if path.is_file() else None+ record = build_record(asset, previous)+ changed = art_common.dump_json(path, record)+ state = "updated" if changed else "unchanged"+ print(f"[verse] {name}: record {art_common.rel(path)} {state}")+ return 0+++def export_calib() -> int:+ payload = _run_blender(["calib"], "calib")+ summary = art_common.CACHE_ROOT / "calib" / "calib.export.json"+ art_common.dump_json(summary, payload)+ for asset in payload["assets"]:+ print(f"[verse] {asset['name']}: {asset['file']} sha256 {asset['sha256'][:12]}")+ print(f"[verse] calibration export summary: {art_common.rel(summary)}")+ return 0+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(+ description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter+ )+ sub = parser.add_subparsers(dest="mode", required=True)+ piece = sub.add_parser("piece", help="export one kit master and write its import record")+ piece.add_argument("name")+ sub.add_parser("calib", help="export the fbx-ue/1 calibration assets into the cache")+ deck = sub.add_parser("deck", help="reserved (placement JSON of a deck zone)")+ deck.add_argument("deck")+ deck.add_argument("--zone")+ for mode in ("characters", "weapons", "textures"):+ sub.add_parser(mode, help="reserved")+ options = parser.parse_args(argv)+ try:+ if options.mode == "piece":+ return export_piece(options.name)+ if options.mode == "calib":+ return export_calib()+ except blender.BlenderError as error:+ print(error, file=sys.stderr)+ return 1+ print(+ f"export_unreal {options.mode}: not available yet; it lands with {RESERVED[options.mode]}"+ " (docs/verse/unreal/work-packages.md)",+ file=sys.stderr,+ )+ return 2+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tests/verse/test_unreal_art_pipeline.py b/tests/verse/test_unreal_art_pipeline.pynew file mode 100644index 0000000000..57e8d20602--- /dev/null+++ b/tests/verse/test_unreal_art_pipeline.py@@ -0,0 +1,659 @@+"""Art pipeline entry points of the Unreal Verse (G0.7, contracts/art-pipeline.md).++No Blender and no Unreal: the pure parts of the export, the placement format,+the static check and the editor-side `verse_pipeline` package. The engine+part of the `fbx-ue/1` calibration runs with `python scripts/unreal/import_art.py+calib --export` on a machine with Blender and the editor.+"""++from __future__ import annotations++import copy+import importlib.util+import json+import math+import random+import shutil+import sys+from pathlib import Path++import pytest++REPO_ROOT = Path(__file__).resolve().parents[2]+ART = REPO_ROOT / "art" / "verse"+PIPELINE = REPO_ROOT / "unreal" / "Verse" / "Content" / "Python"+VECTORS = REPO_ROOT / "unreal" / "Verse" / "Art" / "space_vectors.json"++for _path in (ART, PIPELINE):+ if str(_path) not in sys.path:+ sys.path.insert(0, str(_path))++from lib import placement, ue_space, unreal_materials # noqa: E402+from verse_pipeline import ( # noqa: E402+ calib,+ import_assets,+ records,+ sync_placements,+ validate_assets, # noqa: E402+)+++def _load(name: str, path: Path):+ spec = importlib.util.spec_from_file_location(name, path)+ module = importlib.util.module_from_spec(spec)+ sys.modules[name] = module+ spec.loader.exec_module(module)+ return module+++check_art_text = _load("check_art_text", REPO_ROOT / "scripts" / "unreal" / "check_art_text.py")+++def _close(a, b, tol=1e-9):+ return all(abs(p - q) <= tol for p, q in zip(a, b, strict=True))+++# --- Space (art-pipeline 4.1) -------------------------------------------------+++def test_location_is_mirrored_across_xz_and_scaled_to_centimetres():+ assert ue_space.location_to_ue((1.0, 2.0, 3.0)) == [100.0, -200.0, 300.0]+ assert ue_space.location_from_ue([100.0, -200.0, 300.0]) == [1.0, 2.0, 3.0]+ assert ue_space.three_to_ue((1.0, 2.0, 3.0)) == [100.0, 300.0, 200.0]+++def test_three_and_blender_paths_agree():+ # three.js (x, y, z) is Blender (x, -z, y).+ for x, y, z in [(1.0, 2.0, 3.0), (-4.5, 0.25, 7.0)]:+ assert _close(ue_space.three_to_ue((x, y, z)), ue_space.location_to_ue((x, -z, y)))+++def test_blender_yaw_90_turns_bow_to_port_which_is_unreal_minus_y():+ quat = ue_space.quat_to_ue(ue_space.yaw_quat_wxyz(90.0))+ assert _close(ue_space.rotate_vector_xyzw(quat, [1.0, 0.0, 0.0]), [0.0, -1.0, 0.0])+ assert ue_space.yaw_to_ue(90.0) == -90.0+++def test_quaternion_conversion_commutes_with_the_mirror():+ rng = random.Random(7) # noqa: S311 - deterministic test vectors+ for _ in range(500):+ q = [rng.uniform(-1, 1) for _ in range(4)]+ norm = math.sqrt(sum(c * c for c in q))+ q = [c / norm for c in q]+ v = [rng.uniform(-5, 5) for _ in range(3)]+ blender_rotated = ue_space.rotate_vector_wxyz(q, v)+ unreal_rotated = ue_space.rotate_vector_xyzw(+ ue_space.quat_to_ue(q), ue_space.direction_to_ue(v)+ )+ assert _close(ue_space.direction_to_ue(blender_rotated), unreal_rotated, 1e-9)+ assert ue_space.quat_to_ue(q)[3] >= 0.0+++def test_space_vectors_file_matches_the_python_conversion():+ checker = check_art_text.Checker(REPO_ROOT)+ checker.space_vectors()+ assert checker.errors == []+ doc = json.loads(VECTORS.read_text(encoding="utf-8"))+ assert doc["calibration"]["settings_id"] == "fbx-ue/1"+ assert doc["calibration"]["SM_Calib_Axes"]["bounds_cm"] == {+ "min": [-10.0, -50.0, 0.0],+ "max": [100.0, 10.0, 80.0],+ }+++def test_calibration_numbers_match_the_kit_builder_source():+ """kit/calib.py needs bpy; read its constants as text so the two cannot drift."""+ text = (ART / "kit" / "calib.py").read_text(encoding="utf-8")+ consts = {+ name: float(value)+ for name, value in (+ line.split("#")[0].replace(" ", "").split("=")+ for line in text.splitlines()+ if line[:1].isupper() and "=" in line and "(" not in line and '"' not in line+ )+ }+ spec = json.loads(VECTORS.read_text(encoding="utf-8"))["calibration"]["SM_Calib_Axes"]+ lo, hi = ue_space.bounds_to_ue(+ (-consts["HUB"], -consts["HUB"], 0.0), (consts["X_TIP"], consts["Y_TIP"], consts["Z_TIP"])+ )+ assert _close(lo, spec["bounds_cm"]["min"]) and _close(hi, spec["bounds_cm"]["max"])+ top_at_tip = (consts["HUB"] + consts["ARM"] - consts["CHAMFER"]) * 100.0+ assert math.isclose(top_at_tip, spec["x_tip"]["max_z_cm"])+++# --- Materials mapping (art-pipeline 7) ----------------------------------------+++def test_blender_materials_map_to_instances_in_owned_groups():+ assert unreal_materials.instance_name("M_Wall_Charcoal.001") == "MI_Wall_Charcoal"+ assert (+ unreal_materials.instance_path("M_Struct_Gunmetal")+ == "/Game/Verse/Materials/Instances/Metal/MI_Struct_Gunmetal.MI_Struct_Gunmetal"+ )+ assert unreal_materials.group_for("M_Crate_Paint") == "Props"+ with pytest.raises(ValueError):+ unreal_materials.instance_name("Material.001")+++# --- Placement JSON (art-pipeline 4) --------------------------------------------+++def _placement_doc() -> dict:+ return {+ "schema": "verse.placement/1",+ "deck": "hangar",+ "zone": "arena_canyon",+ "bounds_cm": {"min": [-5000.0, -3100.0, 0.0], "max": [5000.0, 3100.0, 2000.0]},+ "level": "/Game/Verse/Decks/Hangar/LV_Hangar",+ "source": {"builder": "art/verse/decks/hangar/zones/arena_canyon.py", "sha256": "a" * 64},+ "generator": {"script": "export_unreal.py", "version": "1", "blender": "5.0.1"},+ "placements": [+ {+ "id": "container_wall_a",+ "piece": "GC_ContainerWall_240",+ "asset": "/Game/Verse/Destruction/GC_ContainerWall_240.GC_ContainerWall_240",+ "location": [120.0, -240.0, 0.0],+ "rotation": [0.0, 0.0, -0.7071068, 0.7071068],+ "scale": [1.0, 1.0, 1.0],+ "room": "canyon",+ "nav": "block",+ "mobility": "movable",+ "data_layer": "DL_Hangar_Arena",+ "collision": "Verse_Destructible",+ "destructible": {+ "actor_class": "/Script/VerseDestruction.VerseContainerWall",+ "penetration_material": "ContainerSteel",+ "health": 600,+ "states": ["Intact", "Damaged", "Holed", "Breached", "Destroyed"],+ "proxies": {+ s: f"/Game/Verse/Destruction/SM_ContainerWall_240_Proxy_{s}"+ f".SM_ContainerWall_240_Proxy_{s}"+ for s in ("Intact", "Holed", "Breached", "Destroyed")+ },+ "repair_s": 30,+ },+ "station": None,+ "owner": "WP11",+ },+ {+ "id": "floor_a",+ "piece": "SM_Floor_480",+ "asset": "/Game/Verse/Kit/Architecture/SM_Floor_480.SM_Floor_480",+ "location": [0.0, 0.0, 0.0],+ "rotation": [0.0, 0.0, 0.0, 1.0],+ "scale": [1.0, 1.0, 1.0],+ "room": None,+ "nav": "walk",+ "mobility": "static",+ "data_layer": "DL_Hangar_Base",+ "collision": "Verse_Architecture",+ "destructible": None,+ "station": None,+ "owner": "WP11",+ "tags": ["Verse.Arena.Cover"],+ },+ ],+ "sockets": [+ {+ "id": "floor_a__spawn_1",+ "kind": "spawn",+ "location": [100.0, 100.0, 0.0],+ "rotation": [0.0, 0.0, 0.0, 1.0],+ "room": "canyon",+ "station": None,+ "spawn": {"team": "a", "duel": True},+ },+ {+ "id": "floor_a__screen_1",+ "kind": "screen",+ "location": [100.0, 100.0, 150.0],+ "rotation": [0.0, 0.0, 0.0, 1.0],+ "room": None,+ "station": {"id": "arm_1", "kind": "armoury"},+ "size_cm": [120.0, 70.0],+ },+ ],+ "rooms": [+ {+ "id": "canyon",+ "name": "Canyon",+ "polygon_cm": [[-1000, -1000], [1000, -1000], [1000, 1000]],+ "z_cm": 0,+ "main": True,+ }+ ],+ }+++def test_a_complete_placement_document_is_valid():+ assert placement.validate(_placement_doc()) == []+++ ("mutate", "needle"),+ [+ (lambda d: d["placements"][1].update(location=[9000.0, 0.0, 0.0]), "outside bounds_cm"),+ (lambda d: d["placements"][1].update(id="container_wall_a"), "duplicate id"),+ (lambda d: d["placements"][1].update(rotation=[0.0, 0.0, 0.5, 0.5]), "unit quaternion"),+ (lambda d: d["placements"][1].update(room="nowhere"), "not in rooms"),+ (lambda d: d["placements"][1].update(data_layer="DL_Bridge_Base"), "data_layer"),+ (lambda d: d["placements"][0].update(mobility="static"), "must be movable"),+ (lambda d: d["placements"][0]["destructible"]["proxies"].pop("Holed"), "proxies missing"),+ (lambda d: d["placements"][1].update(piece="SM_Floor_240"), "is not the piece"),+ (lambda d: d.update(level="/Game/Verse/Decks/Bridge/LV_Bridge"), "level must be"),+ (lambda d: d["placements"][1].update(owner="Team"), "owner"),+ (lambda d: d["sockets"][1].pop("size_cm"), "size_cm"),+ (lambda d: d["sockets"][0].update(size_cm=[1, 1]), "size_cm"),+ (lambda d: d["placements"][1].update(tags=["Game.Cover"]), "tags"),+ (lambda d: d["placements"][1].update(collision="BlockAll"), "collision"),+ (lambda d: d.update(schema="verse.placement/2"), "schema"),+ ],+)+def test_placement_rules_reject_broken_documents(mutate, needle):+ doc = copy.deepcopy(_placement_doc())+ mutate(doc)+ errors = placement.validate(doc)+ assert errors, f"expected an error about {needle}"+ assert any(needle in e for e in errors), errors+++def test_placement_assets_must_have_records_when_known_assets_are_given():+ errors = placement.validate(_placement_doc(), known_assets=set())+ assert any("no import record" in e for e in errors)+++def test_canonical_form_is_stable_sorted_and_lf(tmp_path):+ doc = _placement_doc()+ doc["placements"].reverse()+ doc["placements"][0]["location"] = [0.00000001, -0.0, 0.0]+ path = tmp_path / "hangar" / "arena_canyon.placement.json"+ assert placement.write(path, doc) is True+ assert placement.write(path, json.loads(path.read_text(encoding="utf-8"))) is False+ raw = path.read_bytes()+ assert b"\r\n" not in raw and raw.endswith(b"\n")+ written = json.loads(raw)+ assert [p["id"] for p in written["placements"]] == ["container_wall_a", "floor_a"]+ assert written["placements"][1]["location"] == [0.0, 0.0, 0.0]+ assert placement.validate_file(path) == []+++def test_validate_file_flags_non_canonical_text(tmp_path):+ path = tmp_path / "hangar" / "arena_canyon.placement.json"+ path.parent.mkdir()+ path.write_text(json.dumps(_placement_doc()), encoding="utf-8")+ assert any("canonical" in e for e in placement.validate_file(path))+++def test_auto_ids_snap_to_15_cm_and_one_degree_and_deduplicate():+ auto = placement.auto_id("SM_Wall_480", [107.0, -52.0, 0.0], -90.4)+ assert auto == "sm_wall_480_105_m45_0_270"+ assert placement.unique_ids(["a", "b", "a", "a"]) == ["a", "b", "a_2", "a_3"]+ assert placement.sanitize_id("Pit-P.1") == "pit_p_1"+++def test_level_and_layer_names_follow_the_deck():+ assert placement.level_path("engineering") == "/Game/Verse/Decks/Engineering/LV_Engineering"+ assert placement.base_layer("ops") == "DL_Ops_Base"+++# --- Static check (art-pipeline 10.3, 14) ---------------------------------------+++def _scratch_root(tmp_path: Path) -> Path:+ root = tmp_path / "repo"+ shutil.copytree(ART / "schema", root / "art" / "verse" / "schema")+ shutil.copy(ART / "LICENSES.md", root / "art" / "verse" / "LICENSES.md")+ (root / "art" / "verse" / "lib").mkdir(parents=True)+ art = root / "unreal" / "Verse" / "Art"+ art.mkdir(parents=True)+ shutil.copy(VECTORS, art / "space_vectors.json")+ return root+++def _record(name="SM_Wall_480", folder="/Game/Verse/Kit/Architecture") -> dict:+ return {+ "schema": "verse.import/1",+ "name": name,+ "asset_path": f"{folder}/{name}.{name}",+ "kind": "static_mesh",+ "source": {+ "builder": "art/verse/kit/architecture/walls.py",+ "function": "wall",+ "args": {},+ },+ "export": {+ "format": "fbx",+ "settings_id": "fbx-ue/1",+ "file": f"art/verse/.cache/unreal/kit/{name}.fbx",+ "sha256": "b" * 64,+ "blender": "5.0.1",+ },+ "mesh": {+ "triangles": 1200,+ "vertices": 900,+ "bounds_cm": {"min": [-240.0, -30.0, 0.0], "max": [240.0, 0.0, 450.0]},+ "uv_sets": 1,+ "material_slots": [+ {+ "slot": "M_Wall_Charcoal",+ "mi": "/Game/Verse/Materials/Instances/Walls/MI_Wall_Charcoal.MI_Wall_Charcoal",+ }+ ],+ },+ "nanite": {"enabled": True},+ "collision": {"profile": "Verse_Architecture", "source": "auto_box", "primitives": 0},+ "lod": {"mode": "nanite"},+ "lightmap": "none",+ "license": {"kind": "own"},+ "owner": "WP12",+ }+++def _write(path: Path, payload) -> Path:+ path.parent.mkdir(parents=True, exist_ok=True)+ text = payload if isinstance(payload, str) else json.dumps(payload, indent=2)+ path.write_bytes(text.encode("utf-8"))+ return path+++def _with_asset(root: Path, record: dict) -> None:+ folder = record["asset_path"].split(".")[0].replace("/Game/Verse/", "")+ _write(root / "unreal" / "Verse" / "Content" / "Verse" / f"{folder}.uasset", "pointer")+ group = record["asset_path"].split("/")[4]+ records_dir = root / "unreal" / "Verse" / "Art" / "Import" / "Kit" / group+ _write(records_dir / f"{record['name']}.import.json", record)+++def _errors(root: Path) -> list[str]:+ return check_art_text.Checker(root).run()+++def test_the_repository_art_text_is_clean():+ assert check_art_text.main([]) == 0+++def test_an_imported_asset_with_its_record_passes(tmp_path):+ root = _scratch_root(tmp_path)+ _with_asset(root, _record())+ assert _errors(root) == []+++def test_a_record_without_asset_and_an_asset_without_record_fail(tmp_path):+ root = _scratch_root(tmp_path)+ record = _record()+ _write(root / "unreal/Verse/Art/Import/Kit/Architecture/SM_Wall_480.import.json", record)+ _write(root / "unreal/Verse/Content/Verse/Kit/Architecture/SM_Lonely_120.uasset", "pointer")+ errors = _errors(root)+ assert any("record has no asset" in e for e in errors)+ assert any("SM_Lonely_120.uasset: no import record" in e for e in errors)+++ ("mutate", "needle"),+ [+ (lambda r: r.update(owner="WP14"), "belongs to WP12"),+ (lambda r: r["mesh"].update(triangles=600_000), "cap 500000"),+ (+ lambda r: r.update(license={"kind": "ledger", "ledger_sha256": ["c" * 64]}),+ "ledger row",+ ),+ (lambda r: r.update(lightmap="generated"), "lightmap"),+ (lambda r: r["export"].update(file="C:/tmp/x.fbx"), "export/file"),+ (lambda r: r.update(kind="skeletal_mesh"), "does not fit the name"),+ ],+)+def test_record_rules(tmp_path, mutate, needle):+ root = _scratch_root(tmp_path)+ record = _record()+ mutate(record)+ _with_asset(root, record)+ errors = _errors(root)+ assert any(needle in e for e in errors), errors+++def test_ledger_rows_that_exist_pass(tmp_path):+ root = _scratch_root(tmp_path)+ record = _record()+ row = "1da6ddb0f455d53636754b3b629942e6aec2f77fafaf6a53cee102ec107854c1"+ record["license"] = {"kind": "ledger", "ledger_sha256": [row]}+ _with_asset(root, record)+ assert _errors(root) == []+++def test_texture_records_follow_the_texture_rules(tmp_path):+ root = _scratch_root(tmp_path)+ record = _record("T_Hull_N", "/Game/Verse/Textures/Hull")+ record.update(kind="texture", owner="WP12")+ record["export"].update(format="png", file="art/verse/.cache/unreal/tex/T_Hull_N.png")+ del record["mesh"], record["nanite"], record["collision"], record["lod"]+ record["texture"] = {+ "group": "WorldNormalMap",+ "max_size": 4096,+ "srgb": True,+ "compression": "Normalmap",+ "flip_green": False,+ }+ _with_asset(root, record)+ errors = "\n".join(_errors(root))+ assert "max_size 4096 > 2048" in errors+ assert "flip green" in errors+ assert "linear" in errors+++def test_banned_names_folders_and_engine_content(tmp_path):+ root = _scratch_root(tmp_path)+ _write(root / "unreal/Verse/Content/Verse/Kit/Thing.uasset", "pointer")+ _write(root / "unreal/Verse/Content/Verse/Kit/SKM_Manny_Simple.uasset", "pointer")+ _write(root / "art/verse/Renders/a.txt", "x")+ _write(root / "unreal/Verse/Build/Windows/icon.txt", "allowed")+ errors = "\n".join(_errors(root))+ assert "Thing: prefix not in art-pipeline section 3" in errors+ assert "engine sample content" in errors+ assert "folder name 'Renders' is banned" in errors+ assert "Build" not in errors+++def test_material_recipes_reject_banned_colours(tmp_path):+ root = _scratch_root(tmp_path)+ recipe = {+ "schema": "verse.mi/1",+ "name": "MI_Light_Panel",+ "parent": "/Game/Verse/Materials/Master/M_Verse_Emissive.M_Verse_Emissive",+ "scalars": {"EmissiveNits": 40.0},+ "vectors": {+ "BaseTint": [0.02, 0.02, 0.022, 1.0],+ "EmissiveColor": [0.0, 0.6, 0.6, 1.0],+ },+ "textures": {},+ "switches": {"UseTriplanar": False},+ "owner": "WP12",+ "replaces": "M_Light_CeilingPanel",+ }+ path = _write(root / "unreal/Verse/Art/Materials/MI_Light_Panel.mi.json", recipe)+ errors = "\n".join(_errors(root))+ assert "EmissiveColor: banned colour (cyan" in errors+ recipe["vectors"]["EmissiveColor"] = [1.0, 0.36, 0.04, 1.0] # amber+ _write(path, recipe)+ assert _errors(root) == []+++def test_gold_is_banned_outside_the_allowlist():+ def linear(c):+ c /= 255+ return c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4++ rgba = [linear(0xC8), linear(0xA2), linear(0x4A), 1.0]+ assert check_art_text.colour_bans("BaseTint", rgba, gold_allowed=False)+ assert not check_art_text.colour_bans("BaseTint", rgba, gold_allowed=True)+++def test_placements_in_the_tree_are_checked_against_records(tmp_path):+ root = _scratch_root(tmp_path)+ doc = _placement_doc()+ doc["placements"] = [doc["placements"][1]]+ doc["sockets"] = []+ _write(+ root / "unreal/Verse/Art/Placements/hangar/arena_canyon.placement.json",+ placement.dumps(doc),+ )+ assert any("no import record" in e for e in _errors(root))+ _with_asset(root, _record("SM_Floor_480"))+ assert _errors(root) == []+++# --- verse_pipeline pure parts ------------------------------------------------+++def test_object_paths_split_into_folder_and_name():+ split = records.split_object_path("/Game/Verse/Kit/A/SM_X.SM_X")+ assert split == ("/Game/Verse/Kit/A", "SM_X")+ with pytest.raises(records.RecordError):+ records.split_object_path("/Game/Verse/Kit/A/SM_X.SM_Y")+++def test_import_plan_skips_unchanged_exports():+ rec = _record()+ other = _record("SM_Wall_240")+ tex = dict(_record("T_A_BC"), kind="texture")+ steps = import_assets.plan([rec, other, tex], {rec["asset_path"]: rec["export"]["sha256"]})+ assert [(r["name"], a) for r, a in steps] == [+ ("SM_Wall_480", "skip"),+ ("SM_Wall_240", "import"),+ ("T_A_BC", "unsupported"),+ ]+++def test_sync_plan_updates_in_place_creates_deletes_and_ignores_manual_actors():+ doc = _placement_doc()+ actors = [+ {"key": "a", "tags": ["verse.zone:arena_canyon", "verse.pid:floor_a"]},+ {"key": "b", "tags": ["verse.zone:arena_canyon", "verse.pid:gone"]},+ {"key": "c", "tags": ["verse.zone:arena_canyon", "verse.manual"]},+ {"key": "d", "tags": ["verse.zone:shell", "verse.pid:floor_a"]},+ {"key": "e", "tags": ["verse.zone:arena_canyon", "verse.pid:floor_a"]},+ ]+ steps = sync_placements.plan(doc, actors)+ assert [k for k, _ in steps["update"]] == ["a"]+ assert sorted(steps["delete"]) == ["b", "e"]+ assert steps["duplicates"] == ["e"]+ assert [p["id"] for p in steps["create"]] == ["container_wall_a"]+ assert sync_placements.actor_tags("z", "p") == ["verse.zone:z", "verse.pid:p"]+++def test_validate_assets_compares_records_with_asset_facts():+ rec = _record()+ assert validate_assets.compare(rec, {"exists": False})[0].endswith("does not exist")+ facts = {"exists": True, "nanite": True, "lightmap_uvs": False, "slots": ["M_Wall_Charcoal"]}+ assert validate_assets.compare(rec, facts) == []+ facts.update(nanite=False, lightmap_uvs=True, slots=["Other"])+ assert len(validate_assets.compare(rec, facts)) == 3+++def _cube():+ v = [[x, y, z] for x in (0, 1) for y in (0, 1) for z in (0, 1)]+ # Faces wound counter-clockwise seen from outside (right-handed convention).+ quads = [(0, 1, 3, 2), (4, 6, 7, 5), (0, 4, 5, 1), (2, 3, 7, 6), (0, 2, 6, 4), (1, 5, 7, 3)]+ tris = []+ for a, b, c, d in quads:+ tris += [a, b, c, a, c, d]+ centre = [0.5, 0.5, 0.5]+ normals = [[p[i] - centre[i] for i in range(3)] for p in v]+ return v, tris, normals+++def test_winding_sign_detects_inside_out_meshes():+ v, tris, normals = _cube()+ sign = calib.winding_sign(v, tris, normals)+ assert sign in (1, -1)+ flipped = [tris[i + k] for i in range(0, len(tris), 3) for k in (0, 2, 1)]+ assert calib.winding_sign(v, flipped, normals) == -sign+ mixed = flipped[:6] + tris[6:]+ assert calib.winding_sign(v, mixed, normals) == 0+++def test_calibration_checks_catch_wrong_units_mirror_and_chamfer():+ spec = calib.load_spec(VECTORS)+ axes = spec["SM_Calib_Axes"]+ tol = spec["tolerance_cm"]+ assert calib.check_bounds([-10, -50, 0], [100, 10, 80], axes["bounds_cm"], tol) == []+ assert calib.check_bounds([-0.1, -0.5, 0], [1, 0.1, 0.8], axes["bounds_cm"], tol) # metres+ assert calib.check_bounds([-10, -10, 0], [100, 50, 80], axes["bounds_cm"], tol) # no mirror+ good_tip = [[100.0, 0.0, 5.0], [100.0, 0.0, 10.0], [95.0, 0.0, 15.0]]+ assert calib.check_x_tip(good_tip, axes["x_tip"], tol) == []+ assert calib.check_x_tip([[100.0, 0.0, 15.0]], axes["x_tip"], tol) # flipped upside down+++def test_calibration_bone_check():+ spec = calib.load_spec(VECTORS)["SK_Calib_Rig"]+ pose = {+ "names": [b["name"] for b in spec["bones"]],+ "locations": {b["name"]: b["component_location_cm"] for b in spec["bones"]},+ "root_scale": [1.0, 1.0, 1.0],+ }+ assert calib.check_bones(pose, "Root", spec, 0.05) == []+ pose["root_rotation"] = [0.0, 0.0, 0.0, -1.0] # -q is the same rotation+ assert calib.check_bones(pose, "Root", spec, 0.05) == []+ pose["root_rotation"] = [0.7071068, 0.0, 0.0, -0.7071068] # Y-up bone axis leaked in+ pose["locations"]["Calib_SideEnd"] = [0.0, 25.0, 50.0] # not mirrored+ pose["root_scale"] = [100.0, 100.0, 100.0]+ pose["names"] = ["Armature", *pose["names"]]+ assert len(calib.check_bones(pose, "Root", spec, 0.05)) == 5+++# --- Export entry (host side) -------------------------------------------------+++export_unreal = _load("export_unreal", REPO_ROOT / "scripts" / "verse" / "export_unreal.py")+++def _exported(**overrides) -> dict:+ asset = {+ "name": "SM_Crate_60",+ "file": "art/verse/.cache/unreal/kit/SM_Crate_60.fbx",+ "sha256": "d" * 64,+ "triangles": 120,+ "vertices": 96,+ "bounds_cm": {"min": [-30.0, -20.0, 0.0], "max": [30.0, 20.0, 25.0]},+ "uv_sets": 1,+ "material_slots": [+ {"slot": "M_Crate_Paint", "mi": unreal_materials.instance_path("M_Crate_Paint")}+ ],+ "collision_primitives": 0,+ "sockets": [],+ "bones": [],+ "settings_id": "fbx-ue/1",+ "blender": "5.0.1",+ "source": {+ "builder": "art/verse/kit/props/fitout.py",+ "function": "crate",+ "module": "kit.props.fitout",+ "args": {"w": 0.6},+ },+ }+ asset.update(overrides)+ return asset+++def test_export_records_follow_the_kit_rules(tmp_path):+ record = export_unreal.build_record(_exported(), None)+ assert record["asset_path"] == "/Game/Verse/Kit/Props/SM_Crate_60.SM_Crate_60"+ assert record["collision"]["profile"] == "Verse_Prop"+ assert record["nanite"] == {"enabled": False} and record["lod"] == {"mode": "single"}+ big = export_unreal.build_record(_exported(triangles=5000), None)+ assert big["nanite"]["enabled"] is True+ tiny = _exported(bounds_cm={"min": [-5.0, -5.0, 0.0], "max": [5.0, 5.0, 10.0]})+ assert export_unreal.build_record(tiny, None)["collision"]["profile"] == "Verse_PropSmall"+ tuned = dict(record, nanite={"enabled": True, "fallback_relative_error": 0.2})+ kept = export_unreal.build_record(_exported(), tuned)["nanite"]+ assert kept["fallback_relative_error"] == 0.2+ # The record passes the static check's schema and rules.+ root = _scratch_root(tmp_path)+ folder = root / "unreal/Verse/Content/Verse/Kit/Props"+ _write(folder / "SM_Crate_60.uasset", "pointer")+ _write(root / "unreal/Verse/Art/Import/Kit/Props/SM_Crate_60.import.json", record)+ assert _errors(root) == []+++def test_reserved_export_modes_exit_2(capsys):+ assert export_unreal.main(["characters"]) == 2+ assert "WP13" in capsys.readouterr().errdiff --git a/tests/verse/test_verse_hangar_arena.py b/tests/verse/test_verse_hangar_arena.pynew file mode 100644index 0000000000..87799a6865--- /dev/null+++ b/tests/verse/test_verse_hangar_arena.py@@ -0,0 +1,240 @@+"""WP11 hangar arena: layout, spawns, flow and placements (work-packages.md WP11).++The geometry acceptance rows that need no engine run here on the design-time+model of `art/verse/decks/hangar/unreal_arena` (A11.1, A11.2, A11.5, the+structural half of A11.7); the Unreal automation tests `Verse.Combat.Deathmatch.*`+and `Verse.Decks.HangarSwitch.*` cover the rules and the switch.+"""++from __future__ import annotations++import json+import sys+from pathlib import Path++import numpy as np+import pytest++REPO = Path(__file__).resolve().parents[2]+sys.path.insert(0, str(REPO / "art" / "verse" / "decks" / "hangar"))+sys.path.insert(0, str(REPO / "art" / "verse"))++from lib import placement as placement_lib # noqa: E402+from unreal_arena import flow, nav, placements # noqa: E402+from unreal_arena import layout as L # noqa: E402++pytest.importorskip("jsonschema")++[email protected](scope="module")+def lay() -> L.Layout:+ return L.build()++[email protected](scope="module")+def graph(lay) -> nav.NavGraph:+ return nav.build(lay)++[email protected](scope="module")+def docs(lay) -> dict[str, dict]:+ return placements.documents(lay)+++# --- A11.1 arena geometry ---------------------------------------------------------+++def test_walkable_bounds_fit_50_by_40(graph):+ x0, x1, z0, z1 = graph.extent()+ assert x1 - x0 <= 50.0 + 1e-6+ assert z1 - z0 <= 40.0 + 1e-6+ ax0, ax1, az0, az1 = L.ARENA+ assert ax0 >= L.HALL[0] and ax1 <= L.HALL[1] and az0 >= L.HALL[2] and az1 <= L.HALL[3]+++def test_three_levels_each_at_least_15_percent(graph):+ shares = graph.level_shares()+ assert set(shares) == {"L0", "L1", "L2"}+ for name, share in shares.items():+ assert share >= 0.15, (name, share)+++def test_nav_is_one_island(graph):+ assert graph.islands() == [graph.count]+++def test_arena_is_sealed_from_the_hall(lay):+ """Built over the whole hall in arena mode, no walkable node outside the+ arena bounds may reach one inside (the perimeter is closed on all sides)."""+ hall = nav.build(lay, bounds=(2.5, 97.5, 1.5, 61.6))+ ax0, ax1, az0, az1 = L.ARENA+ inside = (hall.xs > ax0) & (hall.xs < ax1) & (hall.zs > az0) & (hall.zs < az1)+ assert inside.any() and (~inside).any()+ shared = set(hall.labels[inside].tolist()) & set(hall.labels[~inside].tolist())+ assert not shared, f"{int((~inside & np.isin(hall.labels, list(shared))).sum())} nodes leak"+++def test_ceiling_is_21_m_and_floor_is_whole(lay):+ ceiling = next(b for b in lay.boxes if b.id == "ceiling")+ assert ceiling.h0 == pytest.approx(21.0)+ floors = [b for b in lay.boxes if b.family == "HangarFloor"]+ area = sum((b.x1 - b.x0) * (b.z1 - b.z0) for b in floors)+ wx0, wx1, wz0, wz1 = L.WELL+ assert area == pytest.approx(100 * 62 - (wx1 - wx0) * (wz1 - wz0))+++# --- A11.2 spawns -------------------------------------------------------------------+++def test_at_least_eight_spawns_20_m_apart_by_path(lay, graph):+ assert len(lay.spawns) >= 8+ spacing = flow.spawn_spacing(graph, lay)+ assert spacing["min_path_m"] >= 20.0, spacing["closest"]+++def test_every_spawn_stands_on_the_nav(lay, graph):+ for s in lay.spawns:+ n = graph.nearest(s.x, s.z, s.h)+ assert abs(graph.xs[n] - s.x) <= 0.5 and abs(graph.zs[n] - s.z) <= 0.5, s.id+ assert abs(graph.hs[n] - s.h) <= 0.35, s.id+++# --- A11.5 flow (design-time model; the bot runs replace the walker in phase 2) ------+++def test_longest_unbroken_sightline_at_most_40_m(lay, graph):+ lines = flow.sightlines(graph, lay, spacing_m=1.5)+ assert lines["longest_m"] <= flow.SIGHT_CAP_M, lines["worst"]+++def test_walker_time_to_contact_median_in_range(lay, graph):+ ttc = flow.time_to_contact(graph, lay, runs=30)+ lo, hi = flow.TTC_RANGE_S+ assert lo <= ttc["median_s"] <= hi, ttc+++def test_sight_test_honours_glass_and_walls(lay):+ boxes = flow.sight_boxes(lay)+ # Across the canyon at eye height, through a container (walls block) ...+ a = np.array([[59.0, 14.0, 1.65]])+ b = np.array([[65.0, 14.0, 1.65]])+ assert not flow.clear(a, b, boxes)[0]+ # ... and through the booth's east glass (glass does not).+ a = np.array([[36.0, 37.5, 4.65]])+ b = np.array([[39.5, 37.5, 4.65]])+ assert flow.clear(a, b, boxes)[0]+++def test_bot_log_is_read(tmp_path):+ log = tmp_path / "runs.jsonl"+ log.write_text(+ '{"run": 1, "t_contact_s": 7.5}\n\n{"run": 2, "t_contact_s": 9.5}\n', encoding="utf-8"+ )+ assert flow.summarize_contacts(flow.contacts_from_log(log)) == {"runs": 2, "median_s": 8.5}+++# --- placements, destructibles, A11.7 floor ------------------------------------------+++def test_placement_documents_validate(docs, tmp_path):+ assert set(docs) == set(L.ZONES)+ for zone, doc in docs.items():+ path = tmp_path / "hangar" / f"{zone}.placement.json"+ placement_lib.write(path, doc)+ assert placement_lib.validate_file(path) == [], zone+ assert {p["owner"] for p in doc["placements"]} == {"WP11"}+++def test_arena_zones_live_in_the_arena_layer(docs):+ for zone in L.ARENA_ZONES:+ layers = {p["data_layer"] for p in docs[zone]["placements"]}+ assert layers <= {"DL_Hangar_Arena", "DL_Hangar_Base"}, zone+ assert "DL_Hangar_Arena" in layers, zone+ assert {p["data_layer"] for p in docs["armoury"]["placements"]} == {"DL_Hangar_Base"}+++def test_hall_floor_never_breaks(docs):+ floors = [p for p in docs["shell"]["placements"] if p["piece"] == "SM_HangarFloor"]+ assert len(floors) == 4+ for p in floors:+ assert p["destructible"] is None+ assert p["collision"] == "Verse_Architecture"+ assert p["nav"] == "walk"+ assert "Verse.Material.concrete" in p["tags"]+++def test_destructibles_are_solid_at_their_reference_thickness(lay):+ pieces = [b for b in lay.boxes if b.piece_class]+ assert {b.piece_class for b in pieces} == set(L.PIECE_CLASSES)+ for b in pieces:+ material = L.PIECE_CLASSES[b.piece_class][0]+ assert b.material == material, b.id+ ref = L.REF_THICKNESS_M[material]+ assert min(b.size) == pytest.approx(ref, rel=0.10), (b.id, b.size, ref)+++def test_canyon_aisles_are_3_6_m(lay):+ rows = sorted(L.ROW_X0)+ gaps = [rows[i + 1] - (rows[i] + L.CONTAINER_W) for i in range(len(rows) - 1)]+ assert gaps == pytest.approx([3.6] * len(gaps))+++def test_spawn_sockets_and_armoury_station(docs):+ spawns = [s for d in docs.values() for s in d["sockets"] if s["kind"] == "spawn"]+ assert len(spawns) >= 8+ assert all(s["spawn"] == {"team": "any", "duel": True} for s in spawns)+ stations = [p["station"] for p in docs["armoury"]["placements"] if p["station"]]+ assert {"id": "armoury", "kind": "armoury"} in stations+++def test_lights_are_warm_work_lights(docs):+ lights = [s["light"] for d in docs.values() for s in d["sockets"] if s["kind"] == "light"]+ assert lights+ # art-pipeline 8.2: hard work lights at 4300-6500 K.+ assert all(4300 <= li["kelvin"] <= 6500 for li in lights)+++def test_haze_is_neutral_volumetric_height_fog():+ # art-pipeline 8.2 "Haze" and 8.3 "Coloured fog" (saturation > 0.1 fails), 6.3 Lumen only.+ import colorsys++ assert L.HAZE["fog"] == "exponential_height" and L.HAZE["volumetric"] is True+ assert L.HAZE["fog_density"] > 0+ for key in ("fog_inscattering_rgb", "volumetric_albedo_rgb"):+ _, sat, _ = colorsys.rgb_to_hsv(*L.HAZE[key])+ assert sat <= 0.1, key+ assert L.POST["gi"] == "lumen" and L.POST["reflections"] == "lumen"+++def test_placements_are_deterministic(lay):+ a = placements.documents(lay)+ b = placements.documents(L.build())+ assert json.dumps(a, sort_keys=True) == json.dumps(b, sort_keys=True)+++# --- rules data -----------------------------------------------------------------------+++def test_deathmatch_rules_start_values():+ doc = json.loads(+ (REPO / "unreal" / "Verse" / "Data" / "rules" / "deathmatch.json").read_text("utf-8")+ )+ assert doc["schema"] == "verse.rules/1"+ assert doc["ruleset"] == "endless/1"+ assert doc["respawn_delay_s"] == 3.0+ assert doc["spawn_protection_max_s"] == 2.0+ assert doc["kills_per_set"] == 10+ assert doc["health_regen_per_s"] == 0.0+ assert doc["max_armor"] == 0.0+ known = {+ "schema",+ "ruleset",+ "respawn_delay_s",+ "spawn_protection_max_s",+ "kills_per_set",+ "health_regen_per_s",+ "max_armor",+ "loadout",+ "notes",+ }+ assert set(doc) <= knowndiff --git a/unreal/Verse/Art/space_vectors.json b/unreal/Verse/Art/space_vectors.jsonnew file mode 100644index 0000000000..b9f30489f2--- /dev/null+++ b/unreal/Verse/Art/space_vectors.json@@ -0,0 +1,503 @@+{+ "blender_to_unreal": [+ {+ "blender": {+ "location_m": [+ 0.0,+ 0.0,+ 0.0+ ],+ "quat_wxyz": [+ 1.0,+ 0.0,+ 0.0,+ 0.0+ ],+ "scale": [+ 1.0,+ 1.0,+ 1.0+ ]+ },+ "name": "origin__identity",+ "unreal": {+ "location_cm": [+ 0.0,+ 0.0,+ 0.0+ ],+ "quat_xyzw": [+ 0.0,+ 0.0,+ 0.0,+ 1.0+ ],+ "scale": [+ 1.0,+ 1.0,+ 1.0+ ]+ }+ },+ {+ "blender": {+ "location_m": [+ 1.0,+ 0.0,+ 0.0+ ],+ "quat_wxyz": [+ 0.707106781187,+ 0.0,+ 0.0,+ 0.707106781187+ ],+ "scale": [+ 1.0,+ 1.0,+ 1.0+ ]+ },+ "name": "bow_1m__yaw_90",+ "unreal": {+ "location_cm": [+ 100.0,+ 0.0,+ 0.0+ ],+ "quat_xyzw": [+ 0.0,+ 0.0,+ -0.707106781187,+ 0.707106781187+ ],+ "scale": [+ 1.0,+ 1.0,+ 1.0+ ]+ }+ },+ {+ "blender": {+ "location_m": [+ 0.0,+ 1.0,+ 0.0+ ],+ "quat_wxyz": [+ 0.965925826289,+ 0.0,+ 0.0,+ -0.258819045103+ ],+ "scale": [+ 1.0,+ 1.0,+ 1.0+ ]+ },+ "name": "port_1m__yaw_m30",+ "unreal": {+ "location_cm": [+ 0.0,+ -100.0,+ 0.0+ ],+ "quat_xyzw": [+ 0.0,+ 0.0,+ 0.258819045103,+ 0.965925826289+ ],+ "scale": [+ 1.0,+ 1.0,+ 1.0+ ]+ }+ },+ {+ "blender": {+ "location_m": [+ 0.0,+ 0.0,+ 1.0+ ],+ "quat_wxyz": [+ 0.923879532511,+ 0.0,+ 0.382683432365,+ 0.0+ ],+ "scale": [+ 1.0,+ 1.0,+ 1.0+ ]+ },+ "name": "up_1m__pitch_45_about_y",+ "unreal": {+ "location_cm": [+ 0.0,+ 0.0,+ 100.0+ ],+ "quat_xyzw": [+ 0.0,+ 0.382683432365,+ 0.0,+ 0.923879532511+ ],+ "scale": [+ 1.0,+ 1.0,+ 1.0+ ]+ }+ },+ {+ "blender": {+ "location_m": [+ 12.5,+ -3.25,+ 4.5+ ],+ "quat_wxyz": [+ 0.984807753012,+ 0.173648177667,+ 0.0,+ 0.0+ ],+ "scale": [+ 1.0,+ 1.0,+ 1.0+ ]+ },+ "name": "mixed__roll_20_about_x",+ "unreal": {+ "location_cm": [+ 1250.0,+ 325.0,+ 450.0+ ],+ "quat_xyzw": [+ -0.173648177667,+ 0.0,+ 0.0,+ 0.984807753012+ ],+ "scale": [+ 1.0,+ 1.0,+ 1.0+ ]+ }+ },+ {+ "blender": {+ "location_m": [+ -50.0,+ 31.0,+ 0.0+ ],+ "quat_wxyz": [+ 0.803856860617,+ 0.158973076705,+ 0.31794615341,+ 0.476919230115+ ],+ "scale": [+ 1.0,+ 1.0,+ 1.0+ ]+ },+ "name": "hangar_corner__oblique_73",+ "unreal": {+ "location_cm": [+ -5000.0,+ -3100.0,+ 0.0+ ],+ "quat_xyzw": [+ -0.158973076705,+ 0.31794615341,+ -0.476919230115,+ 0.803856860617+ ],+ "scale": [+ 1.0,+ 1.0,+ 1.0+ ]+ }+ },+ {+ "blender": {+ "location_m": [+ 2.0,+ 2.0,+ 0.0+ ],+ "quat_wxyz": [+ 1.0,+ 0.0,+ 0.0,+ 0.0+ ],+ "scale": [+ 2.0,+ 0.5,+ 1.0+ ]+ },+ "name": "scaled_box",+ "unreal": {+ "location_cm": [+ 200.0,+ -200.0,+ 0.0+ ],+ "quat_xyzw": [+ 0.0,+ 0.0,+ 0.0,+ 1.0+ ],+ "scale": [+ 2.0,+ 0.5,+ 1.0+ ]+ }+ }+ ],+ "calibration": {+ "SK_Calib_Rig": {+ "asset": "/Game/Verse/Test/Calib/SK_Calib_Rig.SK_Calib_Rig",+ "bones": [+ {+ "component_location_cm": [+ 0.0,+ 0.0,+ 0.0+ ],+ "name": "Root",+ "parent": null+ },+ {+ "component_location_cm": [+ 0.0,+ 0.0,+ 50.0+ ],+ "name": "Calib_Arm",+ "parent": "Root"+ },+ {+ "component_location_cm": [+ 0.0,+ 0.0,+ 50.0+ ],+ "name": "Calib_Side",+ "parent": "Root"+ },+ {+ "component_location_cm": [+ 40.0,+ 0.0,+ 50.0+ ],+ "name": "Calib_ArmEnd",+ "parent": "Calib_Arm"+ },+ {+ "component_location_cm": [+ 0.0,+ -25.0,+ 50.0+ ],+ "name": "Calib_SideEnd",+ "parent": "Calib_Side"+ }+ ],+ "first_bone": "Root",+ "root_rotation_xyzw": [+ 0.0,+ 0.0,+ 0.0,+ 1.0+ ],+ "root_scale": [+ 1.0,+ 1.0,+ 1.0+ ]+ },+ "SM_Calib_Axes": {+ "asset": "/Game/Verse/Test/Calib/SM_Calib_Axes.SM_Calib_Axes",+ "bounds_cm": {+ "max": [+ 100.0,+ 10.0,+ 80.0+ ],+ "min": [+ -10.0,+ -50.0,+ 0.0+ ]+ },+ "tip_normals": [+ {+ "axis": 0,+ "sign": 1,+ "tip": "x"+ },+ {+ "axis": 1,+ "sign": -1,+ "tip": "y"+ },+ {+ "axis": 2,+ "sign": 1,+ "tip": "z"+ }+ ],+ "x_tip": {+ "max_z_cm": 10.0,+ "x_cm": 100.0+ }+ },+ "settings_id": "fbx-ue/1",+ "tolerance_cm": 0.05+ },+ "directions": [+ {+ "blender": [+ 1.0,+ 0.0,+ 0.0+ ],+ "unreal": [+ 1.0,+ 0.0,+ 0.0+ ]+ },+ {+ "blender": [+ 0.0,+ 1.0,+ 0.0+ ],+ "unreal": [+ 0.0,+ -1.0,+ 0.0+ ]+ },+ {+ "blender": [+ 0.0,+ 0.0,+ 1.0+ ],+ "unreal": [+ 0.0,+ 0.0,+ 1.0+ ]+ }+ ],+ "note": "Golden vectors of docs/verse/unreal/contracts/art-pipeline.md 4.1. Read by the art/verse/lib/ue_space.py tests, the VerseCore twin and verse_pipeline.calib. Change only together with the contract.",+ "schema": "verse.space_vectors/1",+ "three_to_unreal": [+ {+ "three_m": [+ 0.0,+ 0.0,+ 0.0+ ],+ "unreal_cm": [+ 0.0,+ 0.0,+ 0.0+ ]+ },+ {+ "three_m": [+ 1.0,+ 0.0,+ 0.0+ ],+ "unreal_cm": [+ 100.0,+ 0.0,+ 0.0+ ]+ },+ {+ "three_m": [+ 0.0,+ 1.0,+ 0.0+ ],+ "unreal_cm": [+ 0.0,+ 0.0,+ 100.0+ ]+ },+ {+ "three_m": [+ 0.0,+ 0.0,+ 1.0+ ],+ "unreal_cm": [+ 0.0,+ 100.0,+ 0.0+ ]+ },+ {+ "three_m": [+ 3.5,+ 1.7,+ -12.0+ ],+ "unreal_cm": [+ 350.0,+ -1200.0,+ 170.0+ ]+ }+ ],+ "yaw": [+ {+ "blender_rot_z_deg": 0.0,+ "unreal_yaw_deg": 0.0+ },+ {+ "blender_rot_z_deg": 90.0,+ "unreal_yaw_deg": -90.0+ },+ {+ "blender_rot_z_deg": -90.0,+ "unreal_yaw_deg": 90.0+ },+ {+ "blender_rot_z_deg": 180.0,+ "unreal_yaw_deg": -180.0+ },+ {+ "blender_rot_z_deg": 45.0,+ "unreal_yaw_deg": -45.0+ }+ ]+}diff --git a/unreal/Verse/Content/Python/verse_pipeline/__init__.py b/unreal/Verse/Content/Python/verse_pipeline/__init__.pynew file mode 100644index 0000000000..ebd9ed5fca--- /dev/null+++ b/unreal/Verse/Content/Python/verse_pipeline/__init__.py@@ -0,0 +1,24 @@+"""Editor Python of the Verse art pipeline (docs/verse/unreal/contracts/art-pipeline.md).++Unreal puts `Content/Python` on `sys.path`; this package is never cooked.+The host entry is `scripts/unreal/import_art.py`, which runs+`UnrealEditor-Cmd -run=pythonscript -script=<cli.py>` under the machine-wide+lock. Modules that touch the engine import `unreal` lazily, so the pure parts+(records, plans, checks) are tested with pytest outside the editor.+"""++from __future__ import annotations++from pathlib import Path++PACKAGE_DIR = Path(__file__).resolve().parent+PROJECT_DIR = PACKAGE_DIR.parents[2]+REPO_ROOT = PROJECT_DIR.parents[1]+ART_TEXT = PROJECT_DIR / "Art"+IMPORT_RECORDS = ART_TEXT / "Import"+PLACEMENTS = ART_TEXT / "Placements"+MI_RECIPES = ART_TEXT / "Materials"+SPACE_VECTORS = ART_TEXT / "space_vectors.json"+CACHE_ROOT = REPO_ROOT / "art" / "verse" / ".cache" / "unreal"++SETTINGS_ID = "fbx-ue/1"diff --git a/unreal/Verse/Content/Python/verse_pipeline/calib.py b/unreal/Verse/Content/Python/verse_pipeline/calib.pynew file mode 100644index 0000000000..b3b358d85a--- /dev/null+++ b/unreal/Verse/Content/Python/verse_pipeline/calib.py@@ -0,0 +1,227 @@+"""`fbx-ue/1` calibration: import the calibration assets and check them (art-pipeline 6.1).++`SM_Calib_Axes` and `SK_Calib_Rig` come from `art/verse/kit/calib.py` through+`python scripts/verse/export_unreal.py calib`. This module imports both into+`/Game/Verse/Test/Calib/` without saving and compares them with the+`calibration` block of `unreal/Verse/Art/space_vectors.json`:++* static mesh bounds (units, axes and the mirror of art-pipeline 4.1),+* the chamfer at the +X tip (top and bottom not swapped),+* outward normals at the three tips,+* triangle winding against the engine's own cube (faces not inside out),+* skeleton bone names, first bone, component-space bone positions, and the+ root's rest rotation and scale (identity and 1: the armature node did not+ leave its axis conversion or unit scale in the first bone).++The pure comparison functions take plain lists so pytest covers them.+"""++from __future__ import annotations++import json+from collections.abc import Sequence+from pathlib import Path++from . import CACHE_ROOT, REPO_ROOT, SPACE_VECTORS++EXPORT_SUMMARY = CACHE_ROOT / "calib" / "calib.export.json"+ENGINE_CUBE = "/Engine/BasicShapes/Cube.Cube"++Vec = Sequence[float]+++# --------------------------------------------------------------------------+# Pure checks+# --------------------------------------------------------------------------+++def _sub(a: Vec, b: Vec) -> list[float]:+ return [a[0] - b[0], a[1] - b[1], a[2] - b[2]]+++def _cross(a: Vec, b: Vec) -> list[float]:+ return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]+++def _dot(a: Vec, b: Vec) -> float:+ return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]+++def check_bounds(lo: Vec, hi: Vec, expected: dict, tol: float) -> list[str]:+ errors = []+ for label, got, want in (("min", lo, expected["min"]), ("max", hi, expected["max"])):+ if any(abs(g - w) > tol for g, w in zip(got, want, strict=True)):+ errors.append(f"bounds {label} {list(got)} != {want}")+ return errors+++def check_x_tip(vertices: Sequence[Vec], spec: dict, tol: float) -> list[str]:+ tip = [v for v in vertices if abs(v[0] - spec["x_cm"]) <= tol]+ if not tip:+ return [f"no vertex at x = {spec['x_cm']} cm"]+ top = max(v[2] for v in tip)+ if top > spec["max_z_cm"] + tol:+ return [f"+X tip rises to z = {top:.3f} cm, chamfer expects <= {spec['max_z_cm']}"]+ return []+++def check_tip_normals(+ vertices: Sequence[Vec], normals: Sequence[Vec], bounds: dict, specs: Sequence[dict], tol: float+) -> list[str]:+ errors = []+ for spec in specs:+ axis, sign = spec["axis"], spec["sign"]+ edge = bounds["max"][axis] if sign > 0 else bounds["min"][axis]+ picked = [n for v, n in zip(vertices, normals, strict=True) if abs(v[axis] - edge) <= tol]+ if not picked:+ errors.append(f"no vertex at the {spec['tip']} tip")+ continue+ mean = sum(n[axis] for n in picked) / len(picked)+ if mean * sign <= 0:+ errors.append(f"{spec['tip']} tip normals point inward (mean {mean:.3f})")+ return errors+++def winding_sign(vertices: Sequence[Vec], triangles: Sequence[int], normals: Sequence[Vec]) -> int:+ """+1 when every triangle's cross(b - a, c - a) agrees with its vertex normals, -1 when+ every one disagrees, 0 when mixed (a mesh that is partly inside out)."""+ signs = set()+ for i in range(0, len(triangles) - 2, 3):+ a, b, c = triangles[i], triangles[i + 1], triangles[i + 2]+ geo = _cross(_sub(vertices[b], vertices[a]), _sub(vertices[c], vertices[a]))+ n = [normals[a][k] + normals[b][k] + normals[c][k] for k in range(3)]+ d = _dot(geo, n)+ if abs(d) > 1e-9:+ signs.add(1 if d > 0 else -1)+ return signs.pop() if len(signs) == 1 else 0+++def check_bones(pose: dict, first_bone: str, spec: dict, tol: float) -> list[str]:+ """`pose`: {"names": [...], "locations": {name: [x, y, z]}, "root_scale": [...]}"""+ errors = []+ want = [b["name"] for b in spec["bones"]]+ if sorted(pose["names"]) != sorted(want):+ errors.append(f"bones {pose['names']} != {want}")+ if not pose["names"] or pose["names"][0] != first_bone:+ errors.append(f"first bone is {pose['names'][:1]}, expected {first_bone}")+ for bone in spec["bones"]:+ got = pose["locations"].get(bone["name"])+ if got is None:+ continue+ if any(abs(g - w) > tol for g, w in zip(got, bone["component_location_cm"], strict=True)):+ errors.append(f"{bone['name']} at {got}, expected {bone['component_location_cm']}")+ rotation = pose.get("root_rotation")+ want_rotation = spec.get("root_rotation_xyzw")+ if rotation is not None and want_rotation is not None:+ same = abs(sum(a * b for a, b in zip(rotation, want_rotation, strict=True)))+ if same < 1.0 - 1e-6: # q and -q are one rotation+ errors.append(f"root rotation {rotation} != {want_rotation}")+ scale = pose.get("root_scale")+ want_scale = spec["root_scale"]+ if scale is not None and any(abs(s - w) > 1e-3 for s, w in zip(scale, want_scale, strict=True)):+ errors.append(f"root scale {scale} != {spec['root_scale']}")+ return errors+++def load_spec(path: Path = SPACE_VECTORS) -> dict:+ return json.loads(path.read_text(encoding="utf-8"))["calibration"]+++# --------------------------------------------------------------------------+# Editor side+# --------------------------------------------------------------------------+++def _mesh_section(mesh):+ import unreal++ section = unreal.ProceduralMeshLibrary.get_section_from_static_mesh(mesh, 0, 0)+ vertices, triangles, normals = section[0], section[1], section[2]+ to_list = lambda v: [float(v.x), float(v.y), float(v.z)] # noqa: E731+ return [to_list(v) for v in vertices], list(triangles), [to_list(n) for n in normals]+++def _static_report(asset, spec: dict, tol: float, reference_sign: int) -> dict:+ box = asset.get_bounding_box()+ lo = [float(box.min.x), float(box.min.y), float(box.min.z)]+ hi = [float(box.max.x), float(box.max.y), float(box.max.z)]+ vertices, triangles, normals = _mesh_section(asset)+ errors = check_bounds(lo, hi, spec["bounds_cm"], tol)+ errors += check_x_tip(vertices, spec["x_tip"], tol)+ errors += check_tip_normals(vertices, normals, spec["bounds_cm"], spec["tip_normals"], tol)+ sign = winding_sign(vertices, triangles, normals)+ if sign != reference_sign:+ errors.append(f"triangle winding {sign} differs from the engine cube ({reference_sign})")+ return {+ "bounds_cm": {"min": lo, "max": hi},+ "triangles": len(triangles) // 3,+ "winding": sign,+ "errors": errors,+ }+++def _skeletal_pose(mesh) -> dict:+ import unreal++ skeleton = mesh.get_editor_property("skeleton")+ ext = unreal.AnimPoseExtensions+ pose = ext.get_reference_pose(skeleton)+ names = [str(n) for n in ext.get_bone_names(pose)]+ locations = {}+ root_scale = None+ root_rotation = None+ for name in names:+ transform = ext.get_bone_pose(pose, name, unreal.AnimPoseSpaces.WORLD)+ t = transform.translation+ locations[name] = [float(t.x), float(t.y), float(t.z)]+ if root_scale is None:+ s = transform.scale3d+ root_scale = [float(s.x), float(s.y), float(s.z)]+ q = transform.rotation+ root_rotation = [float(q.x), float(q.y), float(q.z), float(q.w)]+ return {+ "names": names,+ "locations": locations,+ "root_scale": root_scale,+ "root_rotation": root_rotation,+ }+++def run(*, importer: str | None = None) -> dict:+ """Import both calibration assets (not saved) and return the report."""+ import unreal++ from . import import_meshes++ spec = load_spec()+ tol = float(spec["tolerance_cm"])+ summary = json.loads(EXPORT_SUMMARY.read_text(encoding="utf-8"))+ if summary.get("settings_id") != spec["settings_id"]:+ raise RuntimeError(f"export settings {summary.get('settings_id')} != {spec['settings_id']}")+ files = {a["name"]: REPO_ROOT / a["file"] for a in summary["assets"]}+ used = import_meshes.use_importer(importer)++ cube = unreal.load_asset(ENGINE_CUBE)+ reference_sign = winding_sign(*_mesh_section(cube))++ axes_spec = spec["SM_Calib_Axes"]+ options = import_meshes.static_mesh_options(nanite=False, auto_collision=False)+ axes = import_meshes.run_import(files["SM_Calib_Axes"], axes_spec["asset"], options, save=False)+ static = _static_report(axes, axes_spec, tol, reference_sign)++ rig_spec = spec["SK_Calib_Rig"]+ rig = import_meshes.run_import(+ files["SK_Calib_Rig"], rig_spec["asset"], import_meshes.skeletal_mesh_options(), save=False+ )+ pose = _skeletal_pose(rig)+ skeletal = {"pose": pose, "errors": check_bones(pose, rig_spec["first_bone"], rig_spec, tol)}++ ok = not static["errors"] and not skeletal["errors"]+ return {+ "settings_id": spec["settings_id"],+ "importer": used,+ "engine_cube_winding": reference_sign,+ "SM_Calib_Axes": static,+ "SK_Calib_Rig": skeletal,+ "ok": ok,+ }diff --git a/unreal/Verse/Content/Python/verse_pipeline/cli.py b/unreal/Verse/Content/Python/verse_pipeline/cli.pynew file mode 100644index 0000000000..162347ad52--- /dev/null+++ b/unreal/Verse/Content/Python/verse_pipeline/cli.py@@ -0,0 +1,94 @@+"""Editor entry of verse_pipeline, run by `scripts/unreal/import_art.py`.++ UnrealEditor-Cmd Verse.uproject -ExecutePythonScript=<this file>+ -unattended -nosplash -nullrhi++Arguments come in `VERSE_PIPELINE_ARGS` (a JSON list, so nothing is lost to+command-line quoting); the JSON report goes to `VERSE_PIPELINE_RESULT`. The+host reads the report, so a failure is never hidden by the editor's own exit+code. With `VERSE_PIPELINE_QUIT=1` the editor quits when the command is done.++Commands: `assets [--only A,B] [--no-save]`, `placements --deck D [--zone Z]+[--dry-run]`, `validate [--only A,B]`, `calib [--importer interchange|legacy]`.+"""++from __future__ import annotations++import argparse+import json+import os+import sys+import traceback+from pathlib import Path++ARGS_ENV = "VERSE_PIPELINE_ARGS"+RESULT_ENV = "VERSE_PIPELINE_RESULT"+++def _parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(prog="verse_pipeline.cli")+ sub = parser.add_subparsers(dest="command", required=True)+ assets = sub.add_parser("assets")+ assets.add_argument("--only", default="")+ assets.add_argument("--no-save", action="store_true")+ placements = sub.add_parser("placements")+ placements.add_argument("--deck", required=True)+ placements.add_argument("--zone")+ placements.add_argument("--dry-run", action="store_true")+ validate = sub.add_parser("validate")+ validate.add_argument("--only", default="")+ calib = sub.add_parser("calib")+ calib.add_argument("--importer", choices=("interchange", "legacy"))+ return parser+++def _only(value: str) -> list[str]:+ return [v.strip() for v in value.split(",") if v.strip()]+++def dispatch(argv: list[str]) -> dict:+ options = _parser().parse_args(argv)+ if options.command == "calib":+ from verse_pipeline import calib++ return calib.run(importer=options.importer)+ if options.command == "assets":+ from verse_pipeline import import_assets++ return import_assets.run(_only(options.only), save=not options.no_save)+ if options.command == "placements":+ from verse_pipeline import sync_placements++ return sync_placements.run(options.deck, options.zone, dry_run=options.dry_run)+ from verse_pipeline import validate_assets++ return validate_assets.run(_only(options.only))+++def main() -> None:+ raw = os.environ.get(ARGS_ENV, "")+ argv = json.loads(raw) if raw else sys.argv[1:]+ result_path = os.environ.get(RESULT_ENV, "")+ try:+ report = dispatch(argv)+ except BaseException as error: # the host must see every failure in the report+ report = {+ "ok": False,+ "error": f"{type(error).__name__}: {error}",+ "traceback": traceback.format_exc(),+ }+ print("[verse_pipeline] " + json.dumps({"ok": report.get("ok"), "command": argv[:1]}))+ if result_path:+ path = Path(result_path)+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(json.dumps(report, indent=2, sort_keys=True) + "\n", encoding="utf-8")+ if os.environ.get("VERSE_PIPELINE_QUIT") == "1":+ import unreal++ unreal.SystemLibrary.quit_editor()+ elif not report.get("ok"):+ raise RuntimeError(report.get("error") or "verse_pipeline reported failures")+++if __name__ == "__main__":+ main()diff --git a/unreal/Verse/Content/Python/verse_pipeline/geometry_collections.py b/unreal/Verse/Content/Python/verse_pipeline/geometry_collections.pynew file mode 100644index 0000000000..0ad4f1602c--- /dev/null+++ b/unreal/Verse/Content/Python/verse_pipeline/geometry_collections.py@@ -0,0 +1,15 @@+"""Geometry collections from `SM_<Piece>_Frac` exports (art-pipeline 13).++Reserved entry point of the frozen layout (art-pipeline 10.1). It lands with+WP06 (its first spike proves this route); until then `run()` fails loudly instead of doing nothing.+"""++from __future__ import annotations++OWNER_NOTE = (+ "verse_pipeline.geometry_collections lands with WP06 (its first spike proves this route)"+)+++def run(*_args, **_kwargs) -> dict:+ raise NotImplementedError(OWNER_NOTE)diff --git a/unreal/Verse/Content/Python/verse_pipeline/import_assets.py b/unreal/Verse/Content/Python/verse_pipeline/import_assets.pynew file mode 100644index 0000000000..292c44a02a--- /dev/null+++ b/unreal/Verse/Content/Python/verse_pipeline/import_assets.py@@ -0,0 +1,73 @@+"""`import_art.py assets`: import every (or the named) import record's export.++Reimports only what changed: an asset whose stored source hash equals the+record's `export.sha256` is skipped (art-pipeline 10.2, LFS quota). The hash+is kept in the asset's metadata tag `VerseExportSha256`.+"""++from __future__ import annotations++from verse_pipeline import import_meshes, records++SHA_TAG = "VerseExportSha256"+SUPPORTED = {"static_mesh", "proxy_mesh", "skeletal_mesh"}+++def plan(all_records: list[dict], stored: dict[str, str]) -> list[tuple[dict, str]]:+ """(record, action) with action `import`, `skip` or `unsupported`. Pure."""+ out = []+ for record in all_records:+ if record["kind"] not in SUPPORTED:+ out.append((record, "unsupported"))+ elif stored.get(record["asset_path"]) == record["export"]["sha256"]:+ out.append((record, "skip"))+ else:+ out.append((record, "import"))+ return out+++def _stored_hashes(all_records: list[dict]) -> dict[str, str]:+ import unreal++ lib = unreal.EditorAssetLibrary+ out = {}+ for record in all_records:+ path = record["asset_path"]+ if lib.does_asset_exist(path):+ asset = lib.load_asset(path)+ value = lib.get_metadata_tag(asset, SHA_TAG)+ if value:+ out[path] = str(value)+ return out+++def run(only: list[str], *, save: bool = True) -> dict:+ import unreal++ selected = records.select(records.load_all(), only)+ steps = plan(selected, _stored_hashes(selected))+ report = {"imported": [], "skipped": [], "errors": []}+ used = import_meshes.use_importer()+ for record, action in steps:+ name = record["name"]+ if action == "skip":+ report["skipped"].append(name)+ continue+ if action == "unsupported":+ report["errors"].append(f"{name}: kind {record['kind']} has no importer yet")+ continue+ try:+ fbx = records.export_file(record)+ if record["kind"] == "skeletal_mesh":+ asset = import_meshes.import_skeletal(record, fbx, save=False)+ else:+ asset = import_meshes.import_static(record, fbx, save=False)+ unreal.EditorAssetLibrary.set_metadata_tag(asset, SHA_TAG, record["export"]["sha256"])+ if save:+ unreal.EditorAssetLibrary.save_loaded_asset(asset, only_if_is_dirty=False)+ report["imported"].append(name)+ except Exception as error: # report every asset, then fail once+ report["errors"].append(f"{name}: {type(error).__name__}: {error}")+ report["importer"] = used+ report["ok"] = not report["errors"]+ return reportdiff --git a/unreal/Verse/Content/Python/verse_pipeline/import_meshes.py b/unreal/Verse/Content/Python/verse_pipeline/import_meshes.pynew file mode 100644index 0000000000..88ed9ccad9--- /dev/null+++ b/unreal/Verse/Content/Python/verse_pipeline/import_meshes.py@@ -0,0 +1,127 @@+"""Import static and skeletal meshes from FBX with the `fbx-ue/1` options (art-pipeline 6).++The import options are part of `fbx-ue/1`: they and the Blender export+settings (`art/verse/lib/unreal_export.py`) are proven together by+`verse_pipeline.calib`. Imports never create materials or textures (those+come from MI recipes and texture records) and never generate lightmap UVs.+"""++from __future__ import annotations++import os+from pathlib import Path++from .records import split_object_path++#: Which FBX importer runs: the engine default (Interchange) or the legacy+#: FbxFactory. Part of `fbx-ue/1`; calibrated by verse_pipeline.calib.+IMPORTER_ENV = "VERSE_FBX_IMPORTER"+DEFAULT_IMPORTER = "interchange"+_CVAR = "Interchange.FeatureFlags.Import.FBX"+++def _unreal():+ import unreal++ return unreal+++def use_importer(name: str | None = None) -> str:+ """Select the FBX importer for this process and return its name."""+ unreal = _unreal()+ name = (name or os.environ.get(IMPORTER_ENV) or DEFAULT_IMPORTER).lower()+ if name not in ("interchange", "legacy"):+ raise ValueError(f"{IMPORTER_ENV} must be interchange or legacy, got {name!r}")+ value = "1" if name == "interchange" else "0"+ unreal.SystemLibrary.execute_console_command(None, f"{_CVAR} {value}")+ return name+++def _base_options(skeletal: bool):+ unreal = _unreal()+ ui = unreal.FbxImportUI()+ ui.set_editor_property("import_mesh", True)+ ui.set_editor_property("import_materials", False)+ ui.set_editor_property("import_textures", False)+ ui.set_editor_property("import_animations", False)+ ui.set_editor_property("create_physics_asset", False)+ ui.set_editor_property("automated_import_should_detect_type", False)+ ui.set_editor_property("import_as_skeletal", skeletal)+ kinds = unreal.FBXImportType+ kind = kinds.FBXIT_SKELETAL_MESH if skeletal else kinds.FBXIT_STATIC_MESH+ ui.set_editor_property("mesh_type_to_import", kind)+ return ui+++def _common(data) -> None:+ unreal = _unreal()+ data.set_editor_property("convert_scene", True)+ data.set_editor_property("force_front_x_axis", False)+ data.set_editor_property("convert_scene_unit", False)+ data.set_editor_property("import_uniform_scale", 1.0)+ data.set_editor_property("import_translation", unreal.Vector(0.0, 0.0, 0.0))+ data.set_editor_property("import_rotation", unreal.Rotator(0.0, 0.0, 0.0))+++def static_mesh_options(*, nanite: bool, auto_collision: bool):+ unreal = _unreal()+ ui = _base_options(skeletal=False)+ data = ui.get_editor_property("static_mesh_import_data")+ _common(data)+ data.set_editor_property("combine_meshes", True)+ data.set_editor_property("generate_lightmap_u_vs", False)+ data.set_editor_property("auto_generate_collision", auto_collision)+ data.set_editor_property("remove_degenerates", True)+ data.set_editor_property("build_nanite", nanite)+ data.set_editor_property(+ "normal_import_method", unreal.FBXNormalImportMethod.FBXNIM_IMPORT_NORMALS+ )+ return ui+++def skeletal_mesh_options(skeleton=None):+ unreal = _unreal()+ ui = _base_options(skeletal=True)+ if skeleton is not None:+ ui.set_editor_property("skeleton", skeleton)+ data = ui.get_editor_property("skeletal_mesh_import_data")+ _common(data)+ data.set_editor_property("import_meshes_in_bone_hierarchy", True)+ data.set_editor_property("use_t0_as_ref_pose", False)+ data.set_editor_property(+ "normal_import_method", unreal.FBXNormalImportMethod.FBXNIM_IMPORT_NORMALS+ )+ return ui+++def run_import(fbx: Path, object_path: str, options, *, save: bool):+ """Import one FBX into `object_path` and return the loaded asset."""+ unreal = _unreal()+ folder, name = split_object_path(object_path)+ task = unreal.AssetImportTask()+ task.set_editor_property("filename", str(fbx))+ task.set_editor_property("destination_path", folder)+ task.set_editor_property("destination_name", name)+ task.set_editor_property("automated", True)+ task.set_editor_property("replace_existing", True)+ task.set_editor_property("replace_existing_settings", True)+ task.set_editor_property("save", save)+ task.set_editor_property("options", options)+ unreal.AssetToolsHelpers.get_asset_tools().import_asset_tasks([task])+ asset = unreal.load_asset(object_path)+ if asset is None:+ imported = list(task.get_editor_property("imported_object_paths") or [])+ raise RuntimeError(f"import of {fbx.name} produced no {object_path} (got {imported})")+ return asset+++def import_static(record: dict, fbx: Path, *, save: bool = True):+ nanite = bool(record.get("nanite", {}).get("enabled", False))+ collision = record.get("collision", {})+ auto_box = collision.get("source") == "auto_box"+ options = static_mesh_options(nanite=nanite, auto_collision=auto_box)+ return run_import(fbx, record["asset_path"], options, save=save)+++def import_skeletal(record: dict, fbx: Path, *, save: bool = True, skeleton=None):+ return run_import(fbx, record["asset_path"], skeletal_mesh_options(skeleton), save=save)diff --git a/unreal/Verse/Content/Python/verse_pipeline/import_skeletal.py b/unreal/Verse/Content/Python/verse_pipeline/import_skeletal.pynew file mode 100644index 0000000000..36c9e9e1e5--- /dev/null+++ b/unreal/Verse/Content/Python/verse_pipeline/import_skeletal.py@@ -0,0 +1,7 @@+"""Skeletal mesh import (art-pipeline 6, 12). The options live in import_meshes."""++from __future__ import annotations++from verse_pipeline.import_meshes import import_skeletal, skeletal_mesh_options++__all__ = ["import_skeletal", "skeletal_mesh_options"]diff --git a/unreal/Verse/Content/Python/verse_pipeline/import_textures.py b/unreal/Verse/Content/Python/verse_pipeline/import_textures.pynew file mode 100644index 0000000000..5c0cc56f83--- /dev/null+++ b/unreal/Verse/Content/Python/verse_pipeline/import_textures.py@@ -0,0 +1,16 @@+"""Texture import from `verse.import/1` texture records (art-pipeline 6.4).++Reserved entry point of the frozen layout (art-pipeline 10.1). It lands with+the first package that creates a texture set; until then `run()` fails+loudly instead of doing nothing.+"""++from __future__ import annotations++OWNER_NOTE = (+ "verse_pipeline.import_textures lands with the first package that creates a texture set"+)+++def run(*_args, **_kwargs) -> dict:+ raise NotImplementedError(OWNER_NOTE)diff --git a/unreal/Verse/Content/Python/verse_pipeline/materials.py b/unreal/Verse/Content/Python/verse_pipeline/materials.pynew file mode 100644index 0000000000..bd04ed9325--- /dev/null+++ b/unreal/Verse/Content/Python/verse_pipeline/materials.py@@ -0,0 +1,13 @@+"""Material instances from `verse.mi/1` recipes (art-pipeline 7).++Reserved entry point of the frozen layout (art-pipeline 10.1). It lands with+WP14, once the master materials exist; until then `run()` fails loudly instead of doing nothing.+"""++from __future__ import annotations++OWNER_NOTE = "verse_pipeline.materials lands with WP14, once the master materials exist"+++def run(*_args, **_kwargs) -> dict:+ raise NotImplementedError(OWNER_NOTE)diff --git a/unreal/Verse/Content/Python/verse_pipeline/records.py b/unreal/Verse/Content/Python/verse_pipeline/records.pynew file mode 100644index 0000000000..456bb5e8df--- /dev/null+++ b/unreal/Verse/Content/Python/verse_pipeline/records.py@@ -0,0 +1,65 @@+"""Import records (`verse.import/1`, art-pipeline 10.3): loading and paths. Pure Python."""++from __future__ import annotations++import json+from collections.abc import Iterable+from pathlib import Path++from . import IMPORT_RECORDS, REPO_ROOT++SCHEMA_ID = "verse.import/1"+++class RecordError(ValueError):+ """A record is missing, malformed or points at a missing export."""+++def split_object_path(object_path: str) -> tuple[str, str]:+ """`/Game/Verse/Kit/A/SM_X.SM_X` -> (`/Game/Verse/Kit/A`, `SM_X`)."""+ package, _, obj = object_path.rpartition(".")+ folder, _, name = package.rpartition("/")+ if not folder or not name or obj != name:+ raise RecordError(f"not an object path of the form /Game/.../Name.Name: {object_path!r}")+ return folder, name+++def load(path: Path) -> dict:+ try:+ record = json.loads(path.read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError) as error:+ raise RecordError(f"{path}: {error}") from error+ if record.get("schema") != SCHEMA_ID:+ raise RecordError(f"{path}: schema must be {SCHEMA_ID}")+ record["_path"] = str(path)+ return record+++def load_all(root: Path = IMPORT_RECORDS) -> list[dict]:+ if not root.is_dir():+ return []+ return [load(p) for p in sorted(root.rglob("*.import.json"))]+++def select(records: Iterable[dict], only: Iterable[str] | None) -> list[dict]:+ """Records whose name is in `only` (all when `only` is empty); unknown names fail."""+ records = list(records)+ wanted = [n for n in (only or []) if n]+ if not wanted:+ return records+ by_name = {r["name"]: r for r in records}+ missing = [n for n in wanted if n not in by_name]+ if missing:+ raise RecordError(f"no import record for {', '.join(missing)}")+ return [by_name[n] for n in wanted]+++def export_file(record: dict) -> Path:+ """The FBX or PNG the record was exported to (inside the ignored cache)."""+ path = REPO_ROOT / record["export"]["file"]+ if not path.is_file():+ raise RecordError(+ f"{record['name']}: export {record['export']['file']} is missing;"+ f" run python scripts/verse/export_unreal.py first"+ )+ return pathdiff --git a/unreal/Verse/Content/Python/verse_pipeline/sync_placements.py b/unreal/Verse/Content/Python/verse_pipeline/sync_placements.pynew file mode 100644index 0000000000..e9290c30e2--- /dev/null+++ b/unreal/Verse/Content/Python/verse_pipeline/sync_placements.py@@ -0,0 +1,136 @@+"""`import_art.py placements`: make a deck level match its placement JSON (art-pipeline 4.3).++1. An actor belongs to a placement by its tags `verse.zone:<zone>` and+ `verse.pid:<id>`; its label is `<zone>.<id>`.+2. Existing actors are updated in place, so their One File Per Actor files+ keep their names.+3. A placement that is gone deletes its actor; a new one creates an actor.+4. Only actors tagged with the zone are touched, and only their external+ actor packages are saved; the `.umap` is never saved.+5. Actors tagged `verse.manual` are ignored.++`plan()` is pure and tested with pytest; `run()` applies it in the editor.+"""++from __future__ import annotations++import json+from collections.abc import Iterable+from pathlib import Path++from verse_pipeline import PLACEMENTS++ZONE_TAG = "verse.zone:"+PID_TAG = "verse.pid:"+MANUAL_TAG = "verse.manual"+++def zone_files(deck: str, zone: str | None) -> list[Path]:+ folder = PLACEMENTS / deck+ if zone:+ path = folder / f"{zone}.placement.json"+ if not path.is_file():+ raise FileNotFoundError(f"no placement file {path}")+ return [path]+ return sorted(folder.glob("*.placement.json"))+++def actor_tags(zone: str, pid: str) -> list[str]:+ return [f"{ZONE_TAG}{zone}", f"{PID_TAG}{pid}"]+++def plan(doc: dict, actors: Iterable[dict]) -> dict:+ """Decide creates, updates and deletes for one zone. Pure.++ `actors`: [{"key": any, "tags": [...]}] of every actor in the level.+ Returns {"create": [placement], "update": [(key, placement)], "delete": [key],+ "duplicates": [key]}.+ """+ zone = doc["zone"]+ wanted = {p["id"]: p for p in doc["placements"]}+ seen: dict[str, object] = {}+ result: dict = {"create": [], "update": [], "delete": [], "duplicates": []}+ for actor in actors:+ tags = list(actor["tags"])+ if MANUAL_TAG in tags or f"{ZONE_TAG}{zone}" not in tags:+ continue+ pids = [t[len(PID_TAG) :] for t in tags if t.startswith(PID_TAG)]+ pid = pids[0] if len(pids) == 1 else None+ if pid is None or pid not in wanted:+ result["delete"].append(actor["key"])+ elif pid in seen:+ result["duplicates"].append(actor["key"])+ result["delete"].append(actor["key"])+ else:+ seen[pid] = actor["key"]+ result["update"].append((actor["key"], wanted[pid]))+ result["create"] = [p for pid, p in sorted(wanted.items()) if pid not in seen]+ return result+++# --------------------------------------------------------------------------+# Editor side+# --------------------------------------------------------------------------+++def _apply(actor, placement: dict, zone: str) -> None:+ import unreal++ x, y, z, w = placement["rotation"]+ transform = unreal.Transform(+ location=unreal.Vector(*placement["location"]),+ rotation=unreal.Quat(x, y, z, w).rotator(),+ scale=unreal.Vector(*placement["scale"]),+ )+ actor.set_actor_transform(transform, False, False)+ actor.set_actor_label(f"{zone}.{placement['id']}")+ keep = [t for t in actor.tags if not str(t).startswith(("verse.zone:", "verse.pid:"))]+ actor.tags = keep + [unreal.Name(t) for t in actor_tags(zone, placement["id"])]+ component = actor.static_mesh_component+ component.set_static_mesh(unreal.load_asset(placement["asset"]))+ mobility = unreal.ComponentMobility+ movable = placement["mobility"] == "movable"+ component.set_mobility(mobility.MOVABLE if movable else mobility.STATIC)+ component.set_collision_profile_name(placement["collision"])+ component.set_can_ever_affect_navigation(placement["nav"] != "none")+ for slot, mi in (placement.get("material_overrides") or {}).items():+ index = component.get_material_index(slot)+ if index >= 0:+ component.set_material(index, unreal.load_asset(mi))+++def run(deck: str, zone: str | None, *, dry_run: bool = False) -> dict:+ import unreal++ actors_sub = unreal.get_editor_subsystem(unreal.EditorActorSubsystem)+ level_sub = unreal.get_editor_subsystem(unreal.LevelEditorSubsystem)+ report: dict = {"zones": {}, "errors": []}+ for path in zone_files(deck, zone):+ doc = json.loads(path.read_text(encoding="utf-8"))+ if not level_sub.load_level(doc["level"]):+ report["errors"].append(f"cannot load {doc['level']}")+ continue+ level_actors = {a.get_path_name(): a for a in actors_sub.get_all_level_actors()}+ steps = plan(+ doc, [{"key": k, "tags": [str(t) for t in a.tags]} for k, a in level_actors.items()]+ )+ summary = {k: len(v) for k, v in steps.items()}+ report["zones"][doc["zone"]] = summary+ if dry_run:+ continue+ touched = []+ for key, placement in steps["update"]:+ _apply(level_actors[key], placement, doc["zone"])+ touched.append(level_actors[key])+ for placement in steps["create"]:+ actor = actors_sub.spawn_actor_from_class(unreal.StaticMeshActor, unreal.Vector())+ _apply(actor, placement, doc["zone"])+ touched.append(actor)+ packages = [a.get_package() for a in touched]+ for key in steps["delete"]:+ packages.append(level_actors[key].get_package())+ actors_sub.destroy_actor(level_actors[key])+ if packages:+ unreal.EditorLoadingAndSavingUtils.save_packages(packages, False)+ report["ok"] = not report["errors"]+ return reportdiff --git a/unreal/Verse/Content/Python/verse_pipeline/validate_assets.py b/unreal/Verse/Content/Python/verse_pipeline/validate_assets.pynew file mode 100644index 0000000000..f250be2771--- /dev/null+++ b/unreal/Verse/Content/Python/verse_pipeline/validate_assets.py@@ -0,0 +1,73 @@+"""`import_art.py validate`: imported assets match their import records (art-pipeline 14).++Checks per static mesh: the asset exists, Nanite matches `nanite.enabled`,+no lightmap UVs are generated, the collision primitive count matches+`collision.primitives` when the record says `authored`, and material slots+carry the slot names of the record. Further checks (palette bans on MI+vectors, texture settings, LOD screen sizes) join here as their assets land.+"""++from __future__ import annotations++from verse_pipeline import records+++def compare(record: dict, facts: dict) -> list[str]:+ """Differences between a record and the facts read from its asset. Pure."""+ name = record["name"]+ if not facts.get("exists"):+ return [f"{name}: asset {record['asset_path']} does not exist"]+ errors = []+ nanite = record.get("nanite")+ if nanite is not None and facts.get("nanite") is not None:+ if bool(facts["nanite"]) != bool(nanite["enabled"]):+ errors.append(f"{name}: nanite {facts['nanite']} != record {nanite['enabled']}")+ if facts.get("lightmap_uvs"):+ errors.append(f"{name}: lightmap UVs are generated (record says none)")+ collision = record.get("collision")+ if collision and collision["source"] == "authored" and "primitives" in facts:+ if facts["primitives"] != collision["primitives"]:+ got, want_count = facts["primitives"], collision["primitives"]+ errors.append(f"{name}: {got} collision primitives, record {want_count}")+ want = [s["slot"] for s in record.get("mesh", {}).get("material_slots", [])]+ if want and facts.get("slots") is not None and sorted(facts["slots"]) != sorted(want):+ errors.append(f"{name}: material slots {facts['slots']} != record {want}")+ return errors+++def _facts(record: dict) -> dict:+ import unreal++ lib = unreal.EditorAssetLibrary+ if not lib.does_asset_exist(record["asset_path"]):+ return {"exists": False}+ asset = lib.load_asset(record["asset_path"])+ facts: dict = {"exists": True}+ if isinstance(asset, unreal.StaticMesh):+ settings = asset.get_editor_property("nanite_settings")+ facts["nanite"] = bool(settings.get_editor_property("enabled"))+ build = unreal.StaticMeshEditorSubsystem+ subsystem = unreal.get_editor_subsystem(build)+ facts["primitives"] = int(subsystem.get_simple_collision_count(asset))+ source = asset.get_source_model(0) if hasattr(asset, "get_source_model") else None+ if source is not None:+ facts["lightmap_uvs"] = bool(+ source.get_editor_property("build_settings").get_editor_property(+ "generate_lightmap_u_vs"+ )+ )+ materials = asset.get_editor_property("static_materials")+ facts["slots"] = [str(m.get_editor_property("material_slot_name")) for m in materials]+ return facts+++def run(only: list[str]) -> dict:+ selected = records.select(records.load_all(), only)+ errors = []+ checked = []+ for record in selected:+ if record["kind"] not in ("static_mesh", "proxy_mesh"):+ continue+ errors += compare(record, _facts(record))+ checked.append(record["name"])+ return {"checked": checked, "errors": errors, "ok": not errors}diff --git a/unreal/Verse/Content/Python/verse_pipeline/validate_ownership.py b/unreal/Verse/Content/Python/verse_pipeline/validate_ownership.pynew file mode 100644index 0000000000..afba9ce19f--- /dev/null+++ b/unreal/Verse/Content/Python/verse_pipeline/validate_ownership.py@@ -0,0 +1,13 @@+"""Ownership of changed assets and external actors (art-pipeline 9).++Reserved entry point of the frozen layout (art-pipeline 10.1). It lands with+WP10 with the `unreal-build` lane; until then `run()` fails loudly instead of doing nothing.+"""++from __future__ import annotations++OWNER_NOTE = "verse_pipeline.validate_ownership lands with WP10 with the unreal-build lane"+++def run(*_args, **_kwargs) -> dict:+ raise NotImplementedError(OWNER_NOTE)diff --git a/unreal/Verse/Data/rules/deathmatch.json b/unreal/Verse/Data/rules/deathmatch.jsonnew file mode 100644index 0000000000..6ef5cf8e3c--- /dev/null+++ b/unreal/Verse/Data/rules/deathmatch.json@@ -0,0 +1,11 @@+{+ "schema": "verse.rules/1",+ "ruleset": "endless/1",+ "respawn_delay_s": 3.0,+ "spawn_protection_max_s": 2.0,+ "kills_per_set": 10,+ "health_regen_per_s": 0.0,+ "max_armor": 0.0,+ "loadout": {},+ "notes": "Endless 1v1 deathmatch, start values of contracts/combat-state.md 9.1-9.3 (tuning, owned by the balance harness). The loadout map takes EVerseLoadoutSlot names to weapon or gadget data asset paths once WP02 lands them; empty means the game mode's default loadout."+}diff --git a/unreal/Verse/Source/VerseCombat/Private/Rules/VerseGameMode.cpp b/unreal/Verse/Source/VerseCombat/Private/Rules/VerseGameMode.cppnew file mode 100644index 0000000000..3ce7e4850e--- /dev/null+++ b/unreal/Verse/Source/VerseCombat/Private/Rules/VerseGameMode.cpp@@ -0,0 +1,337 @@+#include "Rules/VerseGameMode.h"++#include "Damage/VerseCombatStateComponent.h"+#include "Engine/World.h"+#include "EngineUtils.h"+#include "Events/VerseEventHub.h"+#include "GameFramework/Controller.h"+#include "GameFramework/GameStateBase.h"+#include "GameFramework/Pawn.h"+#include "Misc/FileHelper.h"+#include "Rules/VersePlayerState.h"+#include "Rules/VerseRulesetConfig.h"+#include "Rules/VerseRuleset_Deathmatch.h"+#include "Rules/VerseSpawnPoint.h"+#include "UObject/UnrealType.h"+#include "VerseCollision.h"+#include "VerseLog.h"++namespace+{+ /**+ * Navmesh path length in cm, or -1 when there is no navigation system or no path.+ * VerseCombat has no NavigationSystem edge in the module DAG (architecture 2), so the static+ * UFUNCTION UNavigationSystemV1::FindPathToLocationSynchronously is called through+ * reflection and the returned UNavigationPath's PathPoints are summed (as VerseCrew does).+ */+ float NavPathLength(UWorld* World, const FVector& From, const FVector& To)+ {+ if (!World || !World->GetNavigationSystem())+ {+ return -1.f;+ }+ static TWeakObjectPtr<UClass> NavClass;+ static TWeakObjectPtr<UFunction> FindPath;+ if (!FindPath.IsValid())+ {+ NavClass = FindObject<UClass>(nullptr, TEXT("/Script/NavigationSystem.NavigationSystemV1"));+ FindPath = NavClass.IsValid() ? NavClass->FindFunctionByName(TEXT("FindPathToLocationSynchronously")) : nullptr;+ if (!FindPath.IsValid())+ {+ return -1.f;+ }+ }+ UFunction* Function = FindPath.Get();+ uint8* Params = static_cast<uint8*>(FMemory::Malloc(FMath::Max<int32>(Function->ParmsSize, 1), 16));+ FMemory::Memzero(Params, Function->ParmsSize);+ for (TFieldIterator<FProperty> It(Function); It && It->HasAnyPropertyFlags(CPF_Parm); ++It)+ {+ It->InitializeValue_InContainer(Params);+ }+ float Length = -1.f;+ FObjectProperty* WorldParam = CastField<FObjectProperty>(Function->FindPropertyByName(TEXT("WorldContextObject")));+ FStructProperty* StartParam = CastField<FStructProperty>(Function->FindPropertyByName(TEXT("PathStart")));+ FStructProperty* EndParam = CastField<FStructProperty>(Function->FindPropertyByName(TEXT("PathEnd")));+ FObjectProperty* ReturnParam = CastField<FObjectProperty>(Function->GetReturnProperty());+ if (WorldParam && StartParam && EndParam && ReturnParam)+ {+ WorldParam->SetObjectPropertyValue_InContainer(Params, World);+ *StartParam->ContainerPtrToValuePtr<FVector>(Params) = From;+ *EndParam->ContainerPtrToValuePtr<FVector>(Params) = To;+ NavClass->GetDefaultObject()->ProcessEvent(Function, Params);+ if (UObject* Path = ReturnParam->GetObjectPropertyValue_InContainer(Params))+ {+ if (FArrayProperty* Points = CastField<FArrayProperty>(Path->GetClass()->FindPropertyByName(TEXT("PathPoints"))))+ {+ FScriptArrayHelper Helper(Points, Points->ContainerPtrToValuePtr<void>(Path));+ if (Helper.Num() >= 2)+ {+ double Sum = 0.0;+ for (int32 I = 1; I < Helper.Num(); ++I)+ {+ Sum += FVector::Dist(*reinterpret_cast<const FVector*>(Helper.GetRawPtr(I - 1)),+ *reinterpret_cast<const FVector*>(Helper.GetRawPtr(I)));+ }+ Length = float(Sum);+ }+ }+ }+ }+ for (TFieldIterator<FProperty> It(Function); It && It->HasAnyPropertyFlags(CPF_Parm); ++It)+ {+ It->DestroyValue_InContainer(Params);+ }+ FMemory::Free(Params);+ return Length;+ }+}++AVerseGameMode::AVerseGameMode()+{+ PlayerStateClass = AVersePlayerState::StaticClass();+ PrimaryActorTick.bCanEverTick = false;+}++const UVerseRulesetConfig* AVerseGameMode::ResolveConfig()+{+ if (!RulesetConfig)+ {+ RulesetConfig = NewObject<UVerseRulesetConfig>(this, TEXT("RulesetConfig_Deathmatch"));+ RulesetConfig->RulesetClass = UVerseRuleset_Deathmatch::StaticClass();+ const FString Path = UVerseRulesetConfig::RulesFilePath(TEXT("deathmatch"));+ FString Text;+ FString Error;+ if (!FFileHelper::LoadFileToString(Text, *Path))+ {+ UE_LOG(LogVerseCombat, Warning, TEXT("Rules: %s not found, using the built-in start values"), *Path);+ }+ else if (!RulesetConfig->ApplyJson(Text, Error))+ {+ UE_LOG(LogVerseCombat, Error, TEXT("Rules: %s: %s; using the built-in start values"), *Path, *Error);+ RulesetConfig = NewObject<UVerseRulesetConfig>(this, TEXT("RulesetConfig_Defaults"));+ RulesetConfig->RulesetClass = UVerseRuleset_Deathmatch::StaticClass();+ }+ }+ return RulesetConfig;+}++void AVerseGameMode::CreateRuleset()+{+ const UVerseRulesetConfig* Config = ResolveConfig();+ TSubclassOf<UVerseRuleset> Class = Config && Config->RulesetClass ? Config->RulesetClass : TSubclassOf<UVerseRuleset>(UVerseRuleset_Deathmatch::StaticClass());+ Ruleset = NewObject<UVerseRuleset>(this, Class);+ Ruleset->SetHost(MakeDefaultHost());+ Ruleset->Init(this, Config);+}++void AVerseGameMode::InitGame(const FString& MapName, const FString& Options, FString& ErrorMessage)+{+ Super::InitGame(MapName, Options, ErrorMessage);+ CreateRuleset();+}++void AVerseGameMode::BeginPlay()+{+ Super::BeginPlay();+ if (!Ruleset)+ {+ CreateRuleset();+ }+ if (UVerseEventHub* Hub = UVerseEventHub::Get(this))+ {+ ArenaHandle = Hub->OnArenaSwitch.AddUObject(this, &AVerseGameMode::HandleArenaSwitch);+ DeathHandle = Hub->OnDeath.AddUObject(this, &AVerseGameMode::HandleDeath);+ }+}++void AVerseGameMode::EndPlay(const EEndPlayReason::Type EndPlayReason)+{+ // Verse quitting mid-set sends the running set as unfinished (9.1 Leaving).+ if (UVerseRuleset_Deathmatch* Deathmatch = Cast<UVerseRuleset_Deathmatch>(Ruleset))+ {+ Deathmatch->EndMatch();+ }+ if (UVerseEventHub* Hub = UVerseEventHub::Get(this))+ {+ Hub->OnArenaSwitch.Remove(ArenaHandle);+ Hub->OnDeath.Remove(DeathHandle);+ }+ Super::EndPlay(EndPlayReason);+}++void AVerseGameMode::HandleArenaSwitch(const FVerseArenaSwitchEvent& E)+{+ if (Ruleset && E.bArenaOn)+ {+ Ruleset->OnMatchStart();+ }+}++void AVerseGameMode::HandleDeath(const FVerseDeathEvent& E)+{+ if (Ruleset)+ {+ Ruleset->OnKill(E);+ }+}++AActor* AVerseGameMode::ChoosePlayerStart_Implementation(AController* Player)+{+ const UVerseRuleset_Deathmatch* Deathmatch = Cast<UVerseRuleset_Deathmatch>(Ruleset);+ if (Ruleset && Player && (!Deathmatch || Deathmatch->IsMatchRunning()))+ {+ if (AVerseSpawnPoint* Spawn = Ruleset->ChooseSpawn(Player->GetPlayerState<AVersePlayerState>()))+ {+ return Spawn;+ }+ }+ return Super::ChoosePlayerStart_Implementation(Player);+}++bool AVerseGameMode::CanDamage(const FVerseDamageContext& Ctx) const+{+ return Ruleset ? Ruleset->CanDamage(Ctx) : true;+}++float AVerseGameMode::ModifyDamage(const FVerseDamageContext& Ctx, float Damage) const+{+ return Ruleset ? Ruleset->ModifyDamage(Ctx, Damage) : Damage;+}++void AVerseGameMode::NotifyPlayerAction(AVersePlayerState* Player, EVersePlayerAction Action)+{+ if (Ruleset)+ {+ Ruleset->OnPlayerAction(Player, Action);+ }+}++void AVerseGameMode::GetLoadout(const AVersePlayerState* Player, TMap<EVerseLoadoutSlot, const UPrimaryDataAsset*>& Out) const+{+ Out.Reset();+ if (Ruleset)+ {+ Ruleset->GetLoadout(Player, Out);+ }+}++bool AVerseGameMode::ShouldResetDestruction(EVerseBoundary Boundary) const+{+ return Ruleset ? Ruleset->ShouldResetDestruction(Boundary) : false;+}++FVerseRulesHost AVerseGameMode::MakeDefaultHost()+{+ FVerseRulesHost Host;+ TWeakObjectPtr<AVerseGameMode> Self(this);+ Host.ServerTime = [Self]() { return Self.IsValid() && Self->GetWorld() ? Self->GetWorld()->GetTimeSeconds() : 0.f; };+ Host.Players = [Self]() {+ TArray<AVersePlayerState*> Out;+ const AGameStateBase* State = Self.IsValid() ? Self->GameState.Get() : nullptr;+ if (State)+ {+ for (APlayerState* P : State->PlayerArray)+ {+ if (AVersePlayerState* V = Cast<AVersePlayerState>(P))+ {+ Out.Add(V);+ }+ }+ }+ return Out;+ };+ Host.SpawnPoints = [Self]() {+ TArray<AVerseSpawnPoint*> Out;+ if (UWorld* World = Self.IsValid() ? Self->GetWorld() : nullptr)+ {+ for (TActorIterator<AVerseSpawnPoint> It(World); It; ++It)+ {+ Out.Add(*It);+ }+ }+ return Out;+ };+ Host.SpawnFloor = [](const AVerseSpawnPoint* S) { return S->GetFloorLocation(); };+ Host.EyePoint = [](const AVersePlayerState* P, FVector& OutEye) {+ const APawn* Pawn = P ? P->GetPawn() : nullptr;+ if (!Pawn)+ {+ return false;+ }+ FRotator Rotation;+ Pawn->GetActorEyesViewPoint(OutEye, Rotation);+ return true;+ };+ Host.LineClear = [Self](const FVector& A, const FVector& B) {+ UWorld* World = Self.IsValid() ? Self->GetWorld() : nullptr;+ if (!World)+ {+ return true;+ }+ // Pawns never hide a spawn: only world geometry and the current piece proxies do.+ FCollisionQueryParams Params(SCENE_QUERY_STAT(VerseSpawnSight), false);+ for (TActorIterator<APawn> It(World); It; ++It)+ {+ Params.AddIgnoredActor(*It);+ }+ return !World->LineTraceTestByChannel(A, B, VerseCollision::Bolt, Params);+ };+ Host.FloorPoint = [](const AVersePlayerState* P, FVector& OutFloor) {+ const APawn* Pawn = P ? P->GetPawn() : nullptr;+ if (!Pawn)+ {+ return false;+ }+ OutFloor = Pawn->GetNavAgentLocation();+ return true;+ };+ // Navmesh path length through reflection; "no path" (-1) falls back to Euclidean (9.2).+ Host.PathLength = [Self](const FVector& A, const FVector& B) {+ return NavPathLength(Self.IsValid() ? Self->GetWorld() : nullptr, A, B);+ };+ Host.PawnNear = [Self](const FVector& Floor, float RadiusCm, const AVersePlayerState* Ignore) {+ UWorld* World = Self.IsValid() ? Self->GetWorld() : nullptr;+ if (!World)+ {+ return false;+ }+ for (TActorIterator<APawn> It(World); It; ++It)+ {+ if (Ignore && It->GetPlayerState() == Ignore)+ {+ continue;+ }+ if (FVector::Dist2D(It->GetActorLocation(), Floor) <= RadiusCm && FMath::Abs(It->GetActorLocation().Z - Floor.Z) <= 300.0)+ {+ return true;+ }+ }+ return false;+ };+ Host.Respawn = [Self](AVersePlayerState* P, AVerseSpawnPoint* Spawn) {+ AController* Controller = P ? P->GetOwningController() : nullptr;+ if (!Self.IsValid() || !Controller)+ {+ return;+ }+ if (APawn* Old = Controller->GetPawn())+ {+ // The body stays for the kill cam and gore, then goes.+ Controller->UnPossess();+ Old->SetLifeSpan(10.f);+ }+ if (Spawn)+ {+ Self->RestartPlayerAtPlayerStart(Controller, Spawn);+ }+ else+ {+ Self->RestartPlayer(Controller);+ }+ };+ Host.CombatState = [](const AVersePlayerState* P) -> UVerseCombatStateComponent* {+ const APawn* Pawn = P ? P->GetPawn() : nullptr;+ return Pawn ? Pawn->FindComponentByClass<UVerseCombatStateComponent>() : nullptr;+ };+ return Host;+}diff --git a/unreal/Verse/Source/VerseCombat/Private/Rules/VersePlayerState.cpp b/unreal/Verse/Source/VerseCombat/Private/Rules/VersePlayerState.cppnew file mode 100644index 0000000000..d2f98222b5--- /dev/null+++ b/unreal/Verse/Source/VerseCombat/Private/Rules/VersePlayerState.cpp@@ -0,0 +1,37 @@+#include "Rules/VersePlayerState.h"++#include "Net/Core/PushModel/PushModel.h"+#include "Net/UnrealNetwork.h"++AVersePlayerState::AVersePlayerState()+{+ bReplicates = true;+}++void AVersePlayerState::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const+{+ Super::GetLifetimeReplicatedProps(OutLifetimeProps);++ FDoRepLifetimeParams Params;+ Params.bIsPushBased = true;+ DOREPLIFETIME_WITH_PARAMS_FAST(AVersePlayerState, Kills, Params);+ DOREPLIFETIME_WITH_PARAMS_FAST(AVersePlayerState, Deaths, Params);+ DOREPLIFETIME_WITH_PARAMS_FAST(AVersePlayerState, Headshots, Params);+ DOREPLIFETIME_WITH_PARAMS_FAST(AVersePlayerState, Finishers, Params);+ DOREPLIFETIME_WITH_PARAMS_FAST(AVersePlayerState, SetKills, Params);+ DOREPLIFETIME_WITH_PARAMS_FAST(AVersePlayerState, SetsWon, Params);+ DOREPLIFETIME_WITH_PARAMS_FAST(AVersePlayerState, RespawnAt, Params);+ DOREPLIFETIME_WITH_PARAMS_FAST(AVersePlayerState, BotTier, Params);+ DOREPLIFETIME_WITH_PARAMS_FAST(AVersePlayerState, BotEffectiveSkill, Params);+}++void AVersePlayerState::MarkScoreDirty()+{+ MARK_PROPERTY_DIRTY_FROM_NAME(AVersePlayerState, Kills, this);+ MARK_PROPERTY_DIRTY_FROM_NAME(AVersePlayerState, Deaths, this);+ MARK_PROPERTY_DIRTY_FROM_NAME(AVersePlayerState, Headshots, this);+ MARK_PROPERTY_DIRTY_FROM_NAME(AVersePlayerState, Finishers, this);+ MARK_PROPERTY_DIRTY_FROM_NAME(AVersePlayerState, SetKills, this);+ MARK_PROPERTY_DIRTY_FROM_NAME(AVersePlayerState, SetsWon, this);+ MARK_PROPERTY_DIRTY_FROM_NAME(AVersePlayerState, RespawnAt, this);+}diff --git a/unreal/Verse/Source/VerseCombat/Private/Rules/VerseRuleset.cpp b/unreal/Verse/Source/VerseCombat/Private/Rules/VerseRuleset.cppnew file mode 100644index 0000000000..a8bf97bafa--- /dev/null+++ b/unreal/Verse/Source/VerseCombat/Private/Rules/VerseRuleset.cpp@@ -0,0 +1,66 @@+#include "Rules/VerseRuleset.h"++#include "Engine/DataAsset.h"+#include "Engine/World.h"+#include "Rules/VersePlayerState.h"++void UVerseRuleset::Init(AVerseGameMode* InMode, const UVerseRulesetConfig* InConfig)+{+ Mode = InMode;+ Config = InConfig;+}++void UVerseRuleset::GetLoadout(const AVersePlayerState* P, TMap<EVerseLoadoutSlot, const UPrimaryDataAsset*>& Out) const+{+ Out.Reset();+ if (!Config)+ {+ return;+ }+ for (const TPair<EVerseLoadoutSlot, TSoftObjectPtr<UPrimaryDataAsset>>& Pair : Config->Loadout)+ {+ if (const UPrimaryDataAsset* Asset = Pair.Value.LoadSynchronous())+ {+ Out.Add(Pair.Key, Asset);+ }+ }+}++float UVerseRuleset::GetRespawnDelay(const AVersePlayerState* P) const+{+ return Config ? Config->RespawnDelay : 3.f;+}++float UVerseRuleset::GetSpawnProtection(const AVersePlayerState* P) const+{+ return Config ? Config->SpawnProtectionMax : 2.f;+}++float UVerseRuleset::Now() const+{+ if (Host.ServerTime)+ {+ return Host.ServerTime();+ }+ const UWorld* World = GetWorld();+ return World ? World->GetTimeSeconds() : 0.f;+}++TArray<AVersePlayerState*> UVerseRuleset::GetPlayers() const+{+ TArray<AVersePlayerState*> Out = Host.Players ? Host.Players() : TArray<AVersePlayerState*>();+ Out.RemoveAll([](const AVersePlayerState* P) { return P == nullptr; });+ return Out;+}++AVersePlayerState* UVerseRuleset::FindPlayer(int32 PlayerId) const+{+ for (AVersePlayerState* P : GetPlayers())+ {+ if (P->GetPlayerId() == PlayerId)+ {+ return P;+ }+ }+ return nullptr;+}diff --git a/unreal/Verse/Source/VerseCombat/Private/Rules/VerseRulesetConfig.cpp b/unreal/Verse/Source/VerseCombat/Private/Rules/VerseRulesetConfig.cppnew file mode 100644index 0000000000..ee26fe4cda--- /dev/null+++ b/unreal/Verse/Source/VerseCombat/Private/Rules/VerseRulesetConfig.cpp@@ -0,0 +1,273 @@+#include "Rules/VerseRulesetConfig.h"++#include "Misc/Paths.h"+#include "Rules/VerseRuleset_Deathmatch.h"++namespace+{+ const TCHAR* RulesSchema = TEXT("verse.rules/1");++ /**+ * The rules files are flat JSON: strings, numbers and one object of strings. VerseCombat+ * has no Json module edge in the module DAG, so this small reader covers exactly that.+ */+ struct FRulesValue+ {+ enum class EKind : uint8 { String, Number, Object, Other } Kind = EKind::Other;+ FString String;+ double Number = 0.0;+ TArray<TPair<FString, FString>> Object; // string values only+ };++ struct FRulesReader+ {+ const FString& Text;+ int32 Pos = 0;+ FString Error;++ explicit FRulesReader(const FString& InText) : Text(InText) {}++ void Skip()+ {+ while (Pos < Text.Len() && FChar::IsWhitespace(Text[Pos]))+ {+ ++Pos;+ }+ }++ bool Eat(TCHAR C)+ {+ Skip();+ if (Pos < Text.Len() && Text[Pos] == C)+ {+ ++Pos;+ return true;+ }+ return false;+ }++ bool ReadString(FString& Out)+ {+ if (!Eat(TEXT('"')))+ {+ Error = TEXT("string expected");+ return false;+ }+ Out.Reset();+ while (Pos < Text.Len() && Text[Pos] != TEXT('"'))+ {+ if (Text[Pos] == TEXT('\\') && Pos + 1 < Text.Len())+ {+ ++Pos;+ }+ Out.AppendChar(Text[Pos++]);+ }+ if (Pos >= Text.Len())+ {+ Error = TEXT("unterminated string");+ return false;+ }+ ++Pos;+ return true;+ }++ bool ReadValue(FRulesValue& Out, bool bAllowObject)+ {+ Skip();+ if (Pos >= Text.Len())+ {+ Error = TEXT("value expected");+ return false;+ }+ const TCHAR C = Text[Pos];+ if (C == TEXT('"'))+ {+ Out.Kind = FRulesValue::EKind::String;+ return ReadString(Out.String);+ }+ if (C == TEXT('{') && bAllowObject)+ {+ ++Pos;+ Out.Kind = FRulesValue::EKind::Object;+ if (Eat(TEXT('}')))+ {+ return true;+ }+ do+ {+ FString Key;+ FRulesValue Inner;+ if (!ReadString(Key) || !Eat(TEXT(':')) || !ReadValue(Inner, false))+ {+ Error = Error.IsEmpty() ? TEXT("bad object") : Error;+ return false;+ }+ if (Inner.Kind != FRulesValue::EKind::String)+ {+ Error = FString::Printf(TEXT("%s: a string"), *Key);+ return false;+ }+ Out.Object.Emplace(Key, Inner.String);+ } while (Eat(TEXT(',')));+ if (!Eat(TEXT('}')))+ {+ Error = TEXT("} expected");+ return false;+ }+ return true;+ }+ const int32 Start = Pos;+ while (Pos < Text.Len() && (FChar::IsDigit(Text[Pos]) || Text[Pos] == TEXT('-') || Text[Pos] == TEXT('+')+ || Text[Pos] == TEXT('.') || Text[Pos] == TEXT('e') || Text[Pos] == TEXT('E')))+ {+ ++Pos;+ }+ if (Pos == Start)+ {+ Error = TEXT("unsupported value (strings, numbers and one object of strings only)");+ return false;+ }+ Out.Kind = FRulesValue::EKind::Number;+ Out.Number = FCString::Atod(*Text.Mid(Start, Pos - Start));+ return true;+ }++ bool ReadRoot(TMap<FString, FRulesValue>& Out)+ {+ if (!Eat(TEXT('{')))+ {+ Error = TEXT("not valid JSON");+ return false;+ }+ if (!Eat(TEXT('}')))+ {+ do+ {+ FString Key;+ FRulesValue Value;+ if (!ReadString(Key) || !Eat(TEXT(':')) || !ReadValue(Value, true))+ {+ Error = Error.IsEmpty() ? TEXT("not valid JSON") : Error;+ return false;+ }+ Out.Add(Key, MoveTemp(Value));+ } while (Eat(TEXT(',')));+ if (!Eat(TEXT('}')))+ {+ Error = TEXT("not valid JSON");+ return false;+ }+ }+ Skip();+ if (Pos != Text.Len())+ {+ Error = TEXT("trailing text");+ return false;+ }+ return true;+ }+ };+}++FString UVerseRulesetConfig::RulesFilePath(const FString& Name)+{+ return FPaths::Combine(FPaths::ProjectDir(), TEXT("Data"), TEXT("rules"), Name + TEXT(".json"));+}++bool UVerseRulesetConfig::ApplyJson(const FString& Text, FString& OutError)+{+ TMap<FString, FRulesValue> Root;+ FRulesReader Reader(Text);+ if (!Reader.ReadRoot(Root))+ {+ OutError = Reader.Error;+ return false;+ }+ const FRulesValue* Schema = Root.Find(TEXT("schema"));+ if (!Schema || Schema->Kind != FRulesValue::EKind::String || Schema->String != RulesSchema)+ {+ OutError = FString::Printf(TEXT("schema must be %s"), RulesSchema);+ return false;+ }+ static const TSet<FString> Known = {+ TEXT("schema"), TEXT("ruleset"), TEXT("respawn_delay_s"), TEXT("spawn_protection_max_s"),+ TEXT("kills_per_set"), TEXT("health_regen_per_s"), TEXT("max_armor"), TEXT("loadout"), TEXT("notes")};+ for (const TPair<FString, FRulesValue>& Pair : Root)+ {+ if (!Known.Contains(Pair.Key))+ {+ OutError = FString::Printf(TEXT("unknown key %s"), *Pair.Key);+ return false;+ }+ }+ if (const FRulesValue* Ruleset = Root.Find(TEXT("ruleset")))+ {+ if (Ruleset->String != UVerseRuleset_Deathmatch::RulesetId.ToString())+ {+ OutError = FString::Printf(TEXT("unknown ruleset %s"), *Ruleset->String);+ return false;+ }+ RulesetClass = UVerseRuleset_Deathmatch::StaticClass();+ }+ auto Number = [&Root](const TCHAR* Key, double& Out) {+ const FRulesValue* V = Root.Find(Key);+ if (V && V->Kind == FRulesValue::EKind::Number)+ {+ Out = V->Number;+ return true;+ }+ return false;+ };+ double Value = 0.0;+ if (Number(TEXT("respawn_delay_s"), Value))+ {+ RespawnDelay = float(Value);+ }+ if (Number(TEXT("spawn_protection_max_s"), Value))+ {+ SpawnProtectionMax = float(Value);+ }+ if (Number(TEXT("kills_per_set"), Value))+ {+ KillsPerSet = FMath::RoundToInt(Value);+ }+ if (Number(TEXT("health_regen_per_s"), Value))+ {+ HealthRegenPerSec = float(Value);+ }+ if (Number(TEXT("max_armor"), Value))+ {+ MaxArmor = float(Value);+ }+ if (const FRulesValue* LoadoutValue = Root.Find(TEXT("loadout")))+ {+ if (LoadoutValue->Kind != FRulesValue::EKind::Object)+ {+ OutError = TEXT("loadout must be an object");+ return false;+ }+ const UEnum* SlotEnum = StaticEnum<EVerseLoadoutSlot>();+ Loadout.Reset();+ for (const TPair<FString, FString>& Pair : LoadoutValue->Object)+ {+ const int64 Slot = SlotEnum->GetValueByNameString(Pair.Key);+ if (Slot == INDEX_NONE)+ {+ OutError = FString::Printf(TEXT("loadout: unknown slot %s"), *Pair.Key);+ return false;+ }+ if (!Pair.Value.StartsWith(TEXT("/Game/Verse/")))+ {+ OutError = FString::Printf(TEXT("loadout.%s: an object path under /Game/Verse/"), *Pair.Key);+ return false;+ }+ Loadout.Add(EVerseLoadoutSlot(Slot), TSoftObjectPtr<UPrimaryDataAsset>(FSoftObjectPath(Pair.Value)));+ }+ }+ if (RespawnDelay <= 0.f || SpawnProtectionMax < 0.f || KillsPerSet < 1 || MaxArmor < 0.f)+ {+ OutError = TEXT("respawn_delay_s > 0, spawn_protection_max_s >= 0, kills_per_set >= 1, max_armor >= 0");+ return false;+ }+ return true;+}diff --git a/unreal/Verse/Source/VerseCombat/Private/Rules/VerseRuleset_Deathmatch.cpp b/unreal/Verse/Source/VerseCombat/Private/Rules/VerseRuleset_Deathmatch.cppnew file mode 100644index 0000000000..fa57e1f89e--- /dev/null+++ b/unreal/Verse/Source/VerseCombat/Private/Rules/VerseRuleset_Deathmatch.cpp@@ -0,0 +1,652 @@+#include "Rules/VerseRuleset_Deathmatch.h"++#include "Damage/VerseCombatStateComponent.h"+#include "Engine/World.h"+#include "Events/VerseEventHub.h"+#include "GameFramework/Pawn.h"+#include "Misc/Guid.h"+#include "Net/Core/PushModel/PushModel.h"+#include "Rules/VersePlayerState.h"+#include "Rules/VerseSpawnPoint.h"+#include "VerseLog.h"++const FName UVerseRuleset_Deathmatch::RulesetId(TEXT("endless/1"));++namespace+{+ const FName BulwarkId(TEXT("bulwark"));+ const FName BreachChargeId(TEXT("breach_charge"));+ constexpr float GadgetBlockRadiusCm = 300.f;+}++void UVerseRuleset_Deathmatch::Init(AVerseGameMode* InMode, const UVerseRulesetConfig* InConfig)+{+ Super::Init(InMode, InConfig);+ Subscribe();+}++void UVerseRuleset_Deathmatch::BeginDestroy()+{+ Unsubscribe();+ Super::BeginDestroy();+}++void UVerseRuleset_Deathmatch::Subscribe()+{+ Unsubscribe();+ UVerseEventHub* Hub = UVerseEventHub::Get(this);+ if (!Hub)+ {+ return;+ }+ BoundHub = Hub;+ Handles.Add(Hub->OnFire.AddUObject(this, &UVerseRuleset_Deathmatch::HandleFire));+ Handles.Add(Hub->OnHit.AddUObject(this, &UVerseRuleset_Deathmatch::HandleHit));+ Handles.Add(Hub->OnGadget.AddUObject(this, &UVerseRuleset_Deathmatch::HandleGadget));+ Handles.Add(Hub->OnFracture.AddUObject(this, &UVerseRuleset_Deathmatch::HandleFracture));+ Handles.Add(Hub->OnArenaSwitch.AddUObject(this, &UVerseRuleset_Deathmatch::HandleArenaSwitch));+}++void UVerseRuleset_Deathmatch::Unsubscribe()+{+ if (UVerseEventHub* Hub = BoundHub.Get())+ {+ Hub->OnFire.Remove(Handles.IsValidIndex(0) ? Handles[0] : FDelegateHandle());+ Hub->OnHit.Remove(Handles.IsValidIndex(1) ? Handles[1] : FDelegateHandle());+ Hub->OnGadget.Remove(Handles.IsValidIndex(2) ? Handles[2] : FDelegateHandle());+ Hub->OnFracture.Remove(Handles.IsValidIndex(3) ? Handles[3] : FDelegateHandle());+ Hub->OnArenaSwitch.Remove(Handles.IsValidIndex(4) ? Handles[4] : FDelegateHandle());+ }+ Handles.Reset();+ BoundHub.Reset();+}++UVerseRuleset_Deathmatch::FPlayerRecord& UVerseRuleset_Deathmatch::Record(const AVersePlayerState* P)+{+ const TWeakObjectPtr<const AVersePlayerState> Key(P);+ if (FPlayerRecord* Found = Records.Find(Key))+ {+ return *Found;+ }+ // A player first seen mid-set (a bot spawned by a later OnArenaSwitch listener) gets its+ // identity now, so the set summary never reports player 0.+ FPlayerRecord& Added = Records.Add(Key);+ if (P)+ {+ Added.Line.PlayerId = P->GetPlayerId();+ Added.Line.bIsBot = P->IsBotPlayer();+ }+ return Added;+}++const UVerseRuleset_Deathmatch::FPlayerRecord* UVerseRuleset_Deathmatch::FindRecord(const AVersePlayerState* P) const+{+ return Records.Find(TWeakObjectPtr<const AVersePlayerState>(P));+}++bool UVerseRuleset_Deathmatch::IsSpawnProtected(const AVersePlayerState* P) const+{+ const FPlayerRecord* R = FindRecord(P);+ return R && R->bAlive && R->bProtected;+}++bool UVerseRuleset_Deathmatch::IsAlive(const AVersePlayerState* P) const+{+ const FPlayerRecord* R = FindRecord(P);+ return R && R->bAlive;+}++// ---------------------------------------------------------------------------+// Match and sets+// ---------------------------------------------------------------------------++void UVerseRuleset_Deathmatch::OnMatchStart()+{+ if (bRunning)+ {+ EndMatch();+ }+ bRunning = true;+ SessionId = FGuid::NewGuid().ToString(EGuidFormats::DigitsWithHyphensLower);+ SetIndex = 0;+ DeathCount = 0;+ ActiveGadgets.Reset();+ Records.Reset();+ for (AVersePlayerState* P : GetPlayers())+ {+ P->Kills = P->Deaths = P->Headshots = P->Finishers = 0;+ P->SetKills = P->SetsWon = 0;+ P->RespawnAt = 0.f;+ P->MarkScoreDirty();+ Record(P);+ }+ StartSet();+ // Spawn both: the second spawn already sees the first player as its opponent.+ for (AVersePlayerState* P : GetPlayers())+ {+ SpawnPlayer(P);+ }+ UE_LOG(LogVerseCombat, Log, TEXT("Deathmatch: match %s started with %d players"), *SessionId, Records.Num());+}++void UVerseRuleset_Deathmatch::StartSet()+{+ ++SetIndex;+ SetStartTime = Now();+ SetStartUnix = Host.UnixNow ? Host.UnixNow() : double(FDateTime::UtcNow().ToUnixTimestamp());+ for (auto& Pair : Records)+ {+ const int32 Id = Pair.Value.Line.PlayerId;+ const bool bBot = Pair.Value.Line.bIsBot;+ Pair.Value.Line = FVerseSetLine();+ Pair.Value.Line.PlayerId = Id;+ Pair.Value.Line.bIsBot = bBot;+ Pair.Value.Streak = 0;+ }+ for (AVersePlayerState* P : GetPlayers())+ {+ FPlayerRecord& R = Record(P);+ R.Line.PlayerId = P->GetPlayerId();+ R.Line.bIsBot = P->IsBotPlayer();+ P->SetKills = 0;+ P->MarkScoreDirty();+ }+}++void UVerseRuleset_Deathmatch::EndMatch()+{+ if (!bRunning)+ {+ return;+ }+ FVerseSetSummary Summary;+ BuildSummary(Summary, nullptr);+ bRunning = false;+ if (UVerseEventHub* Hub = UVerseEventHub::Get(this))+ {+ Hub->OnSetEnded.Broadcast(Summary);+ }+ UE_LOG(LogVerseCombat, Log, TEXT("Deathmatch: match %s ended mid-set %d (unfinished)"), *SessionId, SetIndex);+}++bool UVerseRuleset_Deathmatch::IsSetOver(AVersePlayerState*& OutWinner) const+{+ const int32 Target = Config ? Config->KillsPerSet : 10;+ for (AVersePlayerState* P : GetPlayers())+ {+ if (P->SetKills >= Target)+ {+ OutWinner = P;+ return true;+ }+ }+ return false;+}++void UVerseRuleset_Deathmatch::FinishSet(AVersePlayerState* Winner)+{+ FVerseSetSummary Summary;+ BuildSummary(Summary, Winner);+ Winner->SetsWon += 1;+ Winner->MarkScoreDirty();+ if (UVerseEventHub* Hub = UVerseEventHub::Get(this))+ {+ Hub->OnSetEnded.Broadcast(Summary);+ }+ StartSet();+}++void UVerseRuleset_Deathmatch::BuildSetSummary(FVerseSetSummary& Out) const+{+ AVersePlayerState* Winner = nullptr;+ BuildSummary(Out, IsSetOver(Winner) ? Winner : nullptr);+}++void UVerseRuleset_Deathmatch::BuildSummary(FVerseSetSummary& Out, const AVersePlayerState* Winner) const+{+ Out = FVerseSetSummary();+ Out.SessionId = SessionId;+ Out.SetIndex = SetIndex;+ Out.MatchId = FString::Printf(TEXT("%s/%d"), *SessionId, SetIndex);+ Out.RulesetId = RulesetId;+ Out.StartedAtUnix = SetStartUnix;+ Out.EndedAtUnix = Host.UnixNow ? Host.UnixNow() : double(FDateTime::UtcNow().ToUnixTimestamp());+ Out.MatchTimeS = FMath::Max(0.f, Now() - SetStartTime);++ // The person is the first player without a bot tier; the opponent is the other one.+ const AVersePlayerState* Person = nullptr;+ const AVersePlayerState* Opponent = nullptr;+ for (const AVersePlayerState* P : GetPlayers())+ {+ if (!Person && !P->IsBotPlayer())+ {+ Person = P;+ }+ }+ for (const AVersePlayerState* P : GetPlayers())+ {+ if (P != Person && !Opponent)+ {+ Opponent = P;+ }+ }+ if (!Person)+ {+ Person = Opponent;+ Opponent = nullptr;+ for (const AVersePlayerState* P : GetPlayers())+ {+ if (P != Person && !Opponent)+ {+ Opponent = P;+ }+ }+ }+ if (const FPlayerRecord* R = Person ? FindRecord(Person) : nullptr)+ {+ Out.Person = R->Line;+ }+ if (const FPlayerRecord* R = Opponent ? FindRecord(Opponent) : nullptr)+ {+ Out.Opponent = R->Line;+ }+ Out.BotTier = Opponent ? Opponent->BotTier : NAME_None;+ if (!Winner)+ {+ Out.Outcome = EVerseSetOutcome::Unfinished;+ }+ else+ {+ Out.Outcome = Winner == Person ? EVerseSetOutcome::Won : EVerseSetOutcome::Lost;+ }+}++// ---------------------------------------------------------------------------+// Kills, respawn, protection+// ---------------------------------------------------------------------------++void UVerseRuleset_Deathmatch::OnKill(const FVerseDeathEvent& E)+{+ if (!bRunning)+ {+ return;+ }+ AVersePlayerState* Victim = FindPlayer(E.VictimId);+ if (!Victim)+ {+ return;+ }+ FPlayerRecord& VR = Record(Victim);+ if (!VR.bAlive)+ {+ return; // one death per life+ }+ ++DeathCount;+ VR.bAlive = false;+ VR.bProtected = false;+ VR.Streak = 0;+ VR.Line.Deaths += 1;+ VR.RespawnAt = E.ServerTime + GetRespawnDelay(Victim);+ Victim->Deaths += 1;+ Victim->RespawnAt = VR.RespawnAt;+ Victim->MarkScoreDirty();+ WriteProtection(Victim, false, 0.f);++ AVersePlayerState* Killer = E.KillerId != E.VictimId ? FindPlayer(E.KillerId) : nullptr;+ if (Killer)+ {+ FPlayerRecord& KR = Record(Killer);+ const bool bHead = E.LastZone == EVerseHitZone::Head;+ const bool bFinisher = E.Cause == EVerseDamageSource::Finisher;+ KR.Line.Kills += 1;+ KR.Line.Headshots += bHead ? 1 : 0;+ KR.Line.Finishers += bFinisher ? 1 : 0;+ KR.Line.MeleeKills += E.Cause == EVerseDamageSource::Melee ? 1 : 0;+ KR.Streak += 1;+ KR.Line.BestStreak = FMath::Max(KR.Line.BestStreak, KR.Streak);+ if (!E.WeaponId.IsNone())+ {+ FIntVector4& W = KR.Line.PerWeapon.FindOrAdd(E.WeaponId);+ W.X += 1;+ W.Y += bHead ? 1 : 0;+ }+ Killer->Kills += 1;+ Killer->SetKills += 1;+ Killer->Headshots += bHead ? 1 : 0;+ Killer->Finishers += bFinisher ? 1 : 0;+ Killer->MarkScoreDirty();+ }++ AVersePlayerState* Winner = nullptr;+ if (IsSetOver(Winner) && Winner)+ {+ FinishSet(Winner);+ }+}++void UVerseRuleset_Deathmatch::Advance(float ServerTime)+{+ if (!bRunning)+ {+ return;+ }+ for (AVersePlayerState* P : GetPlayers())+ {+ FPlayerRecord& R = Record(P);+ if (!R.bAlive && ServerTime >= R.RespawnAt)+ {+ SpawnPlayer(P);+ }+ else if (R.bAlive && R.bProtected && ServerTime >= R.ProtectedUntil)+ {+ EndProtection(P);+ }+ }+}++void UVerseRuleset_Deathmatch::SpawnPlayer(AVersePlayerState* P)+{+ AVerseSpawnPoint* Spawn = ChooseSpawn(P);+ if (Host.Respawn)+ {+ Host.Respawn(P, Spawn);+ }+ FPlayerRecord& R = Record(P);+ R.bAlive = true;+ R.bProtected = true;+ R.ProtectedUntil = Now() + GetSpawnProtection(P);+ WriteProtection(P, true, R.ProtectedUntil);+}++void UVerseRuleset_Deathmatch::EndProtection(AVersePlayerState* P)+{+ FPlayerRecord& R = Record(P);+ if (!R.bProtected)+ {+ return;+ }+ R.bProtected = false;+ WriteProtection(P, false, R.ProtectedUntil);+}++void UVerseRuleset_Deathmatch::WriteProtection(const AVersePlayerState* P, bool bOn, float Until) const+{+ UVerseCombatStateComponent* Combat = Host.CombatState ? Host.CombatState(P) : nullptr;+ if (!Combat)+ {+ return;+ }+ Combat->bSpawnProtected = bOn;+ Combat->SpawnProtectedUntil = Until;+ MARK_PROPERTY_DIRTY_FROM_NAME(UVerseCombatStateComponent, bSpawnProtected, Combat);+ MARK_PROPERTY_DIRTY_FROM_NAME(UVerseCombatStateComponent, SpawnProtectedUntil, Combat);+}++bool UVerseRuleset_Deathmatch::CanDamage(const FVerseDamageContext& Ctx) const+{+ const AVersePlayerState* Victim = Ctx.Victim ? Ctx.Victim->GetPlayerState<AVersePlayerState>() : nullptr;+ if (!Victim)+ {+ return true; // not a duel player (a test dummy, a drone): the ruleset has no say+ }+ return CanDamagePlayer(Victim, Ctx.Source);+}++bool UVerseRuleset_Deathmatch::CanDamagePlayer(const AVersePlayerState* Victim, EVerseDamageSource Source) const+{+ if (IsSpawnProtected(Victim))+ {+ return false;+ }+ if (const UVerseCombatStateComponent* Combat = Host.CombatState ? Host.CombatState(Victim) : nullptr)+ {+ if (Combat->Phase == EVerseCombatPhase::FinisherVictim && Source != EVerseDamageSource::Finisher)+ {+ return false;+ }+ }+ return true;+}++void UVerseRuleset_Deathmatch::OnPlayerAction(AVersePlayerState* P, EVersePlayerAction Action)+{+ if (!P)+ {+ return;+ }+ switch (Action)+ {+ case EVersePlayerAction::Fire:+ case EVersePlayerAction::Melee:+ case EVersePlayerAction::Gadget:+ EndProtection(P);+ break;+ default:+ break; // reload, ADS, movement and slot switches keep protection (9.3)+ }+}++// ---------------------------------------------------------------------------+// Spawn selection (9.2)+// ---------------------------------------------------------------------------++bool UVerseRuleset_Deathmatch::IsSpawnBlocked(const FVector& Floor, const AVersePlayerState* Respawning) const+{+ if (Host.PawnNear && Host.PawnNear(Floor, VerseSpawnSelection::BlockRadiusCm, Respawning))+ {+ return true;+ }+ for (const FVerseGadgetEvent& G : ActiveGadgets)+ {+ if (FVector::Dist(FVector(G.Location), Floor) <= GadgetBlockRadiusCm)+ {+ return true;+ }+ }+ return false;+}++AVerseSpawnPoint* UVerseRuleset_Deathmatch::ChooseSpawn(const AVersePlayerState* P)+{+ TArray<AVerseSpawnPoint*> Points = Host.SpawnPoints ? Host.SpawnPoints() : TArray<AVerseSpawnPoint*>();+ Points.RemoveAll([](const AVerseSpawnPoint* S) { return S == nullptr; });+ // Actor iteration order is not stable across World Partition loads; the seeded tie break+ // indexes into this list, so order it by SpawnId, then by actor name.+ Points.Sort([](const AVerseSpawnPoint& A, const AVerseSpawnPoint& B) {+ if (A.SpawnId != B.SpawnId)+ {+ return A.SpawnId.LexicalLess(B.SpawnId);+ }+ return A.GetFName().LexicalLess(B.GetFName());+ });+ if (Points.IsEmpty())+ {+ UE_LOG(LogVerseCombat, Warning, TEXT("Deathmatch: no AVerseSpawnPoint in the arena"));+ LastChoice = FVerseSpawnChoice();+ return nullptr;+ }+ TArray<FVerseSpawnCandidate> Candidates;+ for (const AVerseSpawnPoint* S : Points)+ {+ FVerseSpawnCandidate& C = Candidates.AddDefaulted_GetRef();+ C.Floor = Host.SpawnFloor ? Host.SpawnFloor(S) : S->GetFloorLocation();+ C.ProbeHeightsM = S->ProbeHeightsM;+ C.bBlocked = IsSpawnBlocked(C.Floor, P);+ }+ // 1v1: the opponent is the only other player; with more, the nearest living enemy would be used.+ TOptional<FVector> OpponentEye;+ TOptional<FVector> OpponentFloor;+ for (const AVersePlayerState* Other : GetPlayers())+ {+ FVector Eye;+ if (Other != P && IsAlive(Other) && Host.EyePoint && Host.EyePoint(Other, Eye))+ {+ OpponentEye = Eye;+ FVector Floor;+ if (Host.FloorPoint && Host.FloorPoint(Other, Floor))+ {+ OpponentFloor = Floor;+ }+ break;+ }+ }+ auto LineClear = [this](const FVector& A, const FVector& B) { return Host.LineClear ? Host.LineClear(A, B) : true; };+ auto PathLength = [this](const FVector& A, const FVector& B) { return Host.PathLength ? Host.PathLength(A, B) : -1.f; };+ LastChoice = VerseSpawnSelection::Choose(Candidates, OpponentEye, LineClear, PathLength, MatchSeed, DeathCount, OpponentFloor);+ return Points.IsValidIndex(LastChoice.Index) ? Points[LastChoice.Index] : nullptr;+}++// ---------------------------------------------------------------------------+// Statistics from the hub+// ---------------------------------------------------------------------------++void UVerseRuleset_Deathmatch::HandleFire(const FVerseFireEvent& E)+{+ if (!bRunning)+ {+ return;+ }+ if (AVersePlayerState* P = FindPlayer(E.ShooterId))+ {+ FPlayerRecord& R = Record(P);+ R.Line.ShotsFired += 1;+ if (!E.WeaponId.IsNone())+ {+ R.Line.PerWeapon.FindOrAdd(E.WeaponId).Z += 1;+ }+ // The first own shot ends protection on the tick it is fired (D4), even when the+ // weapon code reports it only through the hub.+ OnPlayerAction(P, EVersePlayerAction::Fire);+ }+}++void UVerseRuleset_Deathmatch::HandleHit(const FVerseHitEvent& E)+{+ if (!bRunning || E.bBlockedBySpawnProtection)+ {+ return;+ }+ if (AVersePlayerState* Shooter = FindPlayer(E.InstigatorId))+ {+ FPlayerRecord& R = Record(Shooter);+ if (E.Source == EVerseDamageSource::Bolt)+ {+ R.Line.ShotsHit += 1;+ if (!E.WeaponId.IsNone())+ {+ R.Line.PerWeapon.FindOrAdd(E.WeaponId).W += 1;+ }+ }+ R.Line.DamageDealt += FMath::RoundToInt(E.Damage);+ }+ if (AVersePlayerState* Victim = FindPlayer(E.VictimId))+ {+ Record(Victim).Line.DamageTaken += FMath::RoundToInt(E.Damage);+ }+}++void UVerseRuleset_Deathmatch::HandleGadget(const FVerseGadgetEvent& E)+{+ auto Remove = [this, &E](const FName Id) {+ // Destroyed, Expired and Detonate end the nearest active gadget of that owner and kind.+ int32 Best = INDEX_NONE;+ double BestD = TNumericLimits<double>::Max();+ for (int32 i = 0; i < ActiveGadgets.Num(); ++i)+ {+ const FVerseGadgetEvent& G = ActiveGadgets[i];+ const double D = FVector::DistSquared(FVector(G.Location), FVector(E.Location));+ if (G.GadgetId == Id && G.OwnerId == E.OwnerId && D < BestD)+ {+ Best = i;+ BestD = D;+ }+ }+ if (Best != INDEX_NONE)+ {+ ActiveGadgets.RemoveAt(Best);+ }+ };+ switch (E.Kind)+ {+ case EVerseGadgetEventKind::Deploy:+ // One active Bulwark per owner (2.3): a second deploy replaces the first.+ ActiveGadgets.RemoveAll([&E](const FVerseGadgetEvent& G) { return G.GadgetId == BulwarkId && G.OwnerId == E.OwnerId; });+ ActiveGadgets.Add(E);+ break;+ case EVerseGadgetEventKind::Plant:+ ActiveGadgets.Add(E);+ break;+ case EVerseGadgetEventKind::Destroyed:+ case EVerseGadgetEventKind::Expired:+ Remove(E.GadgetId.IsNone() ? BulwarkId : E.GadgetId);+ break;+ case EVerseGadgetEventKind::Detonate:+ Remove(E.GadgetId.IsNone() ? BreachChargeId : E.GadgetId);+ break;+ }+ if (!bRunning)+ {+ return;+ }+ if (AVersePlayerState* P = FindPlayer(E.OwnerId))+ {+ if (E.Kind == EVerseGadgetEventKind::Deploy && E.GadgetId == BulwarkId)+ {+ Record(P).Line.BulwarksPlaced += 1;+ }+ if (E.Kind == EVerseGadgetEventKind::Deploy || E.Kind == EVerseGadgetEventKind::Plant)+ {+ OnPlayerAction(P, EVersePlayerAction::Gadget);+ }+ }+}++void UVerseRuleset_Deathmatch::HandleFracture(const FVerseFractureEvent& E)+{+ if (!bRunning || E.Cause != EVerseFractureCause::Breach || E.ToState != EVersePieceState::Breached)+ {+ return;+ }+ // FVerseFractureEvent carries the instigator as the low byte of the player state id.+ for (AVersePlayerState* P : GetPlayers())+ {+ if (uint8(P->GetPlayerId() & 0xFF) == E.Instigator)+ {+ Record(P).Line.WallsBreached += 1;+ break;+ }+ }+}++void UVerseRuleset_Deathmatch::HandleArenaSwitch(const FVerseArenaSwitchEvent& E)+{+ // AVerseGameMode forwards "arena on" as OnMatchStart; closing the arena ends the match here.+ if (!E.bArenaOn)+ {+ EndMatch();+ }+}++// ---------------------------------------------------------------------------+// FTickableGameObject+// ---------------------------------------------------------------------------++void UVerseRuleset_Deathmatch::Tick(float DeltaTime)+{+ Advance(Now());+}++TStatId UVerseRuleset_Deathmatch::GetStatId() const+{+ RETURN_QUICK_DECLARE_CYCLE_STAT(UVerseRuleset_Deathmatch, STATGROUP_Tickables);+}++bool UVerseRuleset_Deathmatch::IsTickable() const+{+ return bAutoTick && bRunning && !IsTemplate() && !HasAnyFlags(RF_BeginDestroyed);+}++UWorld* UVerseRuleset_Deathmatch::GetTickableGameObjectWorld() const+{+ return GetWorld();+}diff --git a/unreal/Verse/Source/VerseCombat/Private/Rules/VerseSpawnPoint.cpp b/unreal/Verse/Source/VerseCombat/Private/Rules/VerseSpawnPoint.cppnew file mode 100644index 0000000000..71191cad22--- /dev/null+++ b/unreal/Verse/Source/VerseCombat/Private/Rules/VerseSpawnPoint.cpp@@ -0,0 +1,15 @@+#include "Rules/VerseSpawnPoint.h"++#include "Components/CapsuleComponent.h"++AVerseSpawnPoint::AVerseSpawnPoint(const FObjectInitializer& ObjectInitializer)+ : Super(ObjectInitializer)+{+}++FVector AVerseSpawnPoint::GetFloorLocation() const+{+ const UCapsuleComponent* Capsule = GetCapsuleComponent();+ const double Half = Capsule ? Capsule->GetScaledCapsuleHalfHeight() : 0.0;+ return GetActorLocation() - FVector(0.0, 0.0, Half);+}diff --git a/unreal/Verse/Source/VerseCombat/Private/Rules/VerseSpawnSelection.cpp b/unreal/Verse/Source/VerseCombat/Private/Rules/VerseSpawnSelection.cppnew file mode 100644index 0000000000..6f4bad8725--- /dev/null+++ b/unreal/Verse/Source/VerseCombat/Private/Rules/VerseSpawnSelection.cpp@@ -0,0 +1,93 @@+#include "Rules/VerseSpawnSelection.h"++#include "VerseRng.h"++FVerseSpawnChoice VerseSpawnSelection::Choose(+ const TArray<FVerseSpawnCandidate>& Candidates,+ const TOptional<FVector>& OpponentEye,+ TFunctionRef<bool(const FVector& From, const FVector& To)> LineClear,+ TFunctionRef<float(const FVector& From, const FVector& To)> PathLength,+ uint64 MatchSeed,+ uint64 DeathCount,+ const TOptional<FVector>& OpponentFloor)+{+ FVerseSpawnChoice Out;+ const int32 Count = Candidates.Num();+ Out.Visible.Init(false, Count);+ Out.Distances.Init(0.f, Count);+ if (Count == 0)+ {+ return Out;+ }++ TArray<int32> Open;+ for (int32 i = 0; i < Count; ++i)+ {+ if (!Candidates[i].bBlocked)+ {+ Open.Add(i);+ }+ }+ if (Open.IsEmpty())+ {+ for (int32 i = 0; i < Count; ++i)+ {+ Open.Add(i);+ }+ }++ if (OpponentEye.IsSet())+ {+ const FVector Eye = OpponentEye.GetValue();+ // Sight starts at the eye; path lengths start from the floor under it, where a navmesh+ // query can project (a query from the eye point finds no polygon on a catwalk).+ const FVector Feet = OpponentFloor.IsSet() ? OpponentFloor.GetValue() : Eye - FVector(0.0, 0.0, EyeHeightCm);+ for (const int32 i : Open)+ {+ const FVerseSpawnCandidate& C = Candidates[i];+ bool bSeen = false;+ for (const float HeightM : C.ProbeHeightsM)+ {+ if (LineClear(Eye, C.Floor + FVector(0.0, 0.0, HeightM * 100.0)))+ {+ bSeen = true;+ break;+ }+ }+ Out.Visible[i] = bSeen;+ const float Path = PathLength(Feet, C.Floor);+ Out.Distances[i] = Path >= 0.f ? Path : float(FVector::Dist(Feet, C.Floor));+ }+ }++ for (const int32 i : Open)+ {+ if (!Out.Visible[i])+ {+ Out.Pool.Add(i);+ }+ }+ if (Out.Pool.IsEmpty())+ {+ Out.Pool = Open;+ }++ float Best = -1.f;+ for (const int32 i : Out.Pool)+ {+ Best = FMath::Max(Best, Out.Distances[i]);+ }+ TArray<int32> Ties;+ for (const int32 i : Out.Pool)+ {+ if (Out.Distances[i] >= Best - TieCm)+ {+ Ties.Add(i);+ }+ }+ FVerseRng Rng(MatchSeed, DeathCount, EVerseRngSalt::Spawn);+ Out.Index = Ties[Rng.RangeInt(0, Ties.Num() - 1)];+ Out.bVisible = Out.Visible[Out.Index];+ Out.DistanceCm = Out.Distances[Out.Index];+ return Out;+}diff --git a/unreal/Verse/Source/VerseCombat/Private/Tests/Rules/VerseDeathmatchTest.cpp b/unreal/Verse/Source/VerseCombat/Private/Tests/Rules/VerseDeathmatchTest.cppnew file mode 100644index 0000000000..ee43485221--- /dev/null+++ b/unreal/Verse/Source/VerseCombat/Private/Tests/Rules/VerseDeathmatchTest.cpp@@ -0,0 +1,604 @@+#include "Misc/AutomationTest.h"++#if WITH_DEV_AUTOMATION_TESTS++#include "Events/VerseEventHub.h"+#include "Math/RandomStream.h"+#include "Misc/FileHelper.h"+#include "Rules/VersePlayerState.h"+#include "Rules/VerseRulesetConfig.h"+#include "Rules/VerseRuleset_Deathmatch.h"+#include "Rules/VerseSpawnPoint.h"+#include "Rules/VerseSpawnSelection.h"+#include "Tests/Rules/VerseRulesTestWorld.h"++// Verse.Combat.Deathmatch.*: the deathmatch invariants D1-D4 of contracts/combat-state.md 9.4+// and the per-set summaries (work-packages.md A11.3, A11.8). The world is scripted through+// FVerseRulesHost: no pawns, the hangar arena spawns (docs/verse/unreal/arena.md), a few+// occluder boxes for sight and a stand-in path metric.++namespace VerseDeathmatchTest+{+ constexpr float TickS = 1.f / 60.f;++ // Spawn floors of the hangar arena (arena.md, plan metres x 100).+ const FVector SpawnFloors[] = {+ {2600, 500, 0}, {4800, 800, 0}, {7080, 600, 0}, {7100, 4000, 0}, {4850, 4300, 0},+ {3150, 4050, 300}, {2620, 1800, 600}, {5000, 3050, 300}, {5750, 3720, 600},+ };++ // Shuttle hull, booth, the three container rows: enough to make sight matter.+ const FBox Occluders[] = {+ FBox(FVector(4600, 1500, 0), FVector(5400, 3300, 300)),+ FBox(FVector(2500, 3200, 0), FVector(3800, 4400, 930)),+ FBox(FVector(6060, 1100, 0), FVector(6300, 3700, 300)),+ FBox(FVector(6660, 500, 0), FVector(6900, 3900, 300)),+ FBox(FVector(7260, 500, 0), FVector(7500, 4100, 300)),+ };++ bool LineClear(const FVector& A, const FVector& B)+ {+ for (const FBox& Box : Occluders)+ {+ if (FMath::LineBoxIntersection(Box, A, B, B - A))+ {+ return false;+ }+ }+ return true;+ }++ // A path metric that differs from the Euclidean fallback: grid walking plus stairs.+ float PathLength(const FVector& A, const FVector& B)+ {+ return float(FMath::Abs(A.X - B.X) + FMath::Abs(A.Y - B.Y) + 2.0 * FMath::Abs(A.Z - B.Z));+ }++ bool Inside(const FVector& P)+ {+ for (const FBox& Box : Occluders)+ {+ if (Box.IsInsideOrOn(P))+ {+ return true;+ }+ }+ return false;+ }++ /** The scripted duel: two players, positions, a clock and a log of everything that happened. */+ struct FDuel+ {+ FVerseRulesTestWorld TestWorld;+ UVerseRuleset_Deathmatch* Rules = nullptr;+ UVerseRulesetConfig* Config = nullptr;+ AVersePlayerState* Person = nullptr;+ AVersePlayerState* Bot = nullptr;+ TArray<AVerseSpawnPoint*> Spawns;+ TArray<AVersePlayerState*> Players;+ TMap<const AVersePlayerState*, FVector> Feet;+ TMap<const AVersePlayerState*, float> LastRespawn;+ TArray<FVerseSetSummary> Summaries;+ float Time = 0.f;+ int32 Respawns = 0;+ TFunction<void(AVersePlayerState*, AVerseSpawnPoint*)> OnRespawn;++ FDuel()+ {+ UWorld* World = TestWorld.World;+ Person = TestWorld.Spawn<AVersePlayerState>();+ Person->SetPlayerId(1);+ Bot = TestWorld.Spawn<AVersePlayerState>();+ Bot->SetPlayerId(2);+ Bot->BotTier = TEXT("normal");+ Players = {Person, Bot};+ for (const FVector& Floor : SpawnFloors)+ {+ Spawns.Add(TestWorld.Spawn<AVerseSpawnPoint>(Floor));+ }+ Config = NewObject<UVerseRulesetConfig>(World);+ Rules = NewObject<UVerseRuleset_Deathmatch>(World);+ Rules->bAutoTick = false;++ FVerseRulesHost Host;+ Host.ServerTime = [this]() { return Time; };+ Host.UnixNow = [this]() { return 1.8e9 + Time; };+ Host.Players = [this]() { return Players; };+ Host.SpawnPoints = [this]() { return Spawns; };+ Host.SpawnFloor = [](const AVerseSpawnPoint* S) { return S->GetActorLocation(); };+ Host.EyePoint = [this](const AVersePlayerState* P, FVector& Out) {+ const FVector* F = Feet.Find(P);+ if (!F)+ {+ return false;+ }+ Out = *F + FVector(0, 0, 165);+ return true;+ };+ Host.LineClear = &LineClear;+ Host.PathLength = &PathLength;+ Host.PawnNear = [this](const FVector& Floor, float Radius, const AVersePlayerState* Ignore) {+ for (const TPair<const AVersePlayerState*, FVector>& Pair : Feet)+ {+ if (Pair.Key != Ignore && FVector::Dist(Pair.Value, Floor) <= Radius)+ {+ return true;+ }+ }+ return false;+ };+ Host.Respawn = [this](AVersePlayerState* P, AVerseSpawnPoint* S) {+ if (OnRespawn)+ {+ OnRespawn(P, S);+ }+ Feet.Add(P, S ? S->GetActorLocation() : FVector::ZeroVector);+ LastRespawn.Add(P, Time);+ ++Respawns;+ };+ Rules->SetHost(Host);+ Rules->Init(nullptr, Config);+ if (UVerseEventHub* Hub = UVerseEventHub::Get(World))+ {+ Hub->OnSetEnded.AddLambda([this](const FVerseSetSummary& S) { Summaries.Add(S); });+ }+ }++ UVerseEventHub* Hub() const { return UVerseEventHub::Get(TestWorld.World); }++ void Kill(AVersePlayerState* Victim, AVersePlayerState* Killer, EVerseDamageSource Cause = EVerseDamageSource::Bolt,+ EVerseHitZone Zone = EVerseHitZone::UpperTorso)+ {+ FVerseDeathEvent E;+ E.VictimId = Victim->GetPlayerId();+ E.KillerId = Killer ? Killer->GetPlayerId() : 0;+ E.Cause = Cause;+ E.LastZone = Zone;+ E.WeaponId = TEXT("graveline");+ E.ServerTime = Time;+ Feet.Remove(Victim);+ Rules->OnKill(E);+ }++ void Fire(AVersePlayerState* Shooter)+ {+ FVerseFireEvent E;+ E.ShooterId = Shooter->GetPlayerId();+ E.WeaponId = TEXT("graveline");+ E.ServerTime = Time;+ Hub()->OnFire.Broadcast(E);+ }++ void TickOnce()+ {+ Time += TickS;+ Rules->Advance(Time);+ }++ AVersePlayerState* Other(AVersePlayerState* P) const { return P == Person ? Bot : Person; }+ };+}++using namespace VerseDeathmatchTest;++IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseDeathmatchSpawnSelectionTest, "Verse.Combat.Deathmatch.SpawnSelection",+ EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::EngineFilter)++bool FVerseDeathmatchSpawnSelectionTest::RunTest(const FString& Parameters)+{+ auto Make = [](std::initializer_list<FVector> Floors) {+ TArray<FVerseSpawnCandidate> Out;+ for (const FVector& F : Floors)+ {+ FVerseSpawnCandidate& C = Out.AddDefaulted_GetRef();+ C.Floor = F;+ }+ return Out;+ };+ const FVector Eye(4000, 2000, 165);++ // Out of sight wins over a farther candidate in sight; the farthest hidden one wins.+ {+ TArray<FVerseSpawnCandidate> C = Make({{2600, 500, 0}, {7100, 4000, 0}, {6500, 2000, 0}, {9000, 2000, 0}});+ // Wall at x 8000 hides candidate 3 (and only it), wall around the shuttle hides 2.+ auto Clear = [](const FVector& A, const FVector& B) {+ const FBox Walls[] = {FBox(FVector(8000, 0, 0), FVector(8100, 6000, 900)), FBox(FVector(6000, 1500, 0), FVector(6200, 2500, 900))};+ for (const FBox& W : Walls)+ {+ if (FMath::LineBoxIntersection(W, A, B, B - A))+ {+ return false;+ }+ }+ return true;+ };+ auto Euclid = [](const FVector& A, const FVector& B) { return float(FVector::Dist(A, B)); };+ const FVerseSpawnChoice Choice = VerseSpawnSelection::Choose(C, Eye, Clear, Euclid, 7, 0);+ TestEqual(TEXT("farthest hidden spawn chosen"), Choice.Index, 3);+ TestFalse(TEXT("chosen spawn is hidden"), Choice.bVisible);+ TestEqual(TEXT("two hidden candidates in the pool"), Choice.Pool.Num(), 2);+ }+ // Everything visible: the farthest of all.+ {+ TArray<FVerseSpawnCandidate> C = Make({{2600, 500, 0}, {7100, 4000, 0}, {4100, 2100, 0}});+ auto Clear = [](const FVector&, const FVector&) { return true; };+ auto Euclid = [](const FVector& A, const FVector& B) { return float(FVector::Dist(A, B)); };+ const FVerseSpawnChoice Choice = VerseSpawnSelection::Choose(C, Eye, Clear, Euclid, 7, 0);+ TestEqual(TEXT("all visible: farthest"), Choice.Index, 1);+ TestTrue(TEXT("all visible: flagged"), Choice.bVisible);+ }+ // Blocked candidates are skipped unless every one is blocked.+ {+ TArray<FVerseSpawnCandidate> C = Make({{2600, 500, 0}, {7100, 4000, 0}});+ C[1].bBlocked = true;+ auto Clear = [](const FVector&, const FVector&) { return false; };+ auto Euclid = [](const FVector& A, const FVector& B) { return float(FVector::Dist(A, B)); };+ TestEqual(TEXT("blocked candidate skipped"), VerseSpawnSelection::Choose(C, Eye, Clear, Euclid, 7, 0).Index, 0);+ C[0].bBlocked = true;+ TestEqual(TEXT("all blocked: falls back to all"), VerseSpawnSelection::Choose(C, Eye, Clear, Euclid, 7, 0).Index, 1);+ }+ // No path: the Euclidean distance stands in (9.2).+ {+ TArray<FVerseSpawnCandidate> C = Make({{2600, 500, 0}, {4100, 2100, 0}});+ auto Clear = [](const FVector&, const FVector&) { return false; };+ auto NoPath = [](const FVector&, const FVector&) { return -1.f; };+ const FVerseSpawnChoice Choice = VerseSpawnSelection::Choose(C, Eye, Clear, NoPath, 7, 0);+ TestEqual(TEXT("no path: euclidean"), Choice.Index, 0);+ TestTrue(TEXT("no path: distance is euclidean"), FMath::IsNearlyEqual(Choice.DistanceCm, float(FVector::Dist(Eye - FVector(0, 0, VerseSpawnSelection::EyeHeightCm), C[0].Floor)), 0.5f));+ }+ // Ties within 1 m go to VerseRng(seed, deaths): deterministic, and both sides get picked.+ {+ TArray<FVerseSpawnCandidate> C = Make({{3000, 2000, 0}, {5000, 2000, 0}});+ const FVector Mid(4000, 2000, 165);+ auto Clear = [](const FVector&, const FVector&) { return false; };+ auto Euclid = [](const FVector& A, const FVector& B) { return float(FVector::Dist(A, B)); };+ TSet<int32> Seen;+ for (uint64 Deaths = 0; Deaths < 32; ++Deaths)+ {+ const int32 A = VerseSpawnSelection::Choose(C, Mid, Clear, Euclid, 99, Deaths).Index;+ const int32 B = VerseSpawnSelection::Choose(C, Mid, Clear, Euclid, 99, Deaths).Index;+ TestEqual(TEXT("tie break is deterministic"), A, B);+ Seen.Add(A);+ }+ TestEqual(TEXT("tie break uses both candidates"), Seen.Num(), 2);+ // No opponent (first spawn): every candidate ties.+ const FVerseSpawnChoice First = VerseSpawnSelection::Choose(C, TOptional<FVector>(), Clear, Euclid, 99, 0);+ TestTrue(TEXT("no opponent: a valid pick"), First.Index == 0 || First.Index == 1);+ }+ // Path length starts at the opponent's floor point, not the eye.+ {+ TArray<FVerseSpawnCandidate> C = Make({{2600, 500, 0}});+ auto Clear = [](const FVector&, const FVector&) { return false; };+ FVector From = FVector::ZeroVector;+ auto Record = [&From](const FVector& A, const FVector&) { From = A; return 1.f; };+ VerseSpawnSelection::Choose(C, Eye, Clear, Record, 7, 0);+ TestEqual(TEXT("path from eye minus eye height"), From, Eye - FVector(0, 0, VerseSpawnSelection::EyeHeightCm));+ const FVector Floor(4000, 2000, 600);+ VerseSpawnSelection::Choose(C, Eye, Clear, Record, 7, 0, Floor);+ TestEqual(TEXT("path from the given floor point"), From, Floor);+ }+ // The ruleset orders the spawn points itself: a shuffled list gives the same picks.+ {+ FDuel Duel;+ TArray<AVerseSpawnPoint*> Picks;+ for (uint64 Seed = 1; Seed <= 8; ++Seed)+ {+ Duel.Rules->MatchSeed = Seed;+ Picks.Add(Duel.Rules->ChooseSpawn(Duel.Person));+ }+ FRandomStream Shuffle(42);+ for (int32 i = Duel.Spawns.Num() - 1; i > 0; --i)+ {+ Duel.Spawns.Swap(i, Shuffle.RandRange(0, i));+ }+ for (uint64 Seed = 1; Seed <= 8; ++Seed)+ {+ Duel.Rules->MatchSeed = Seed;+ TestTrue(TEXT("shuffled spawn list: same pick"), Duel.Rules->ChooseSpawn(Duel.Person) == Picks[Seed - 1]);+ }+ TSet<AVerseSpawnPoint*> Distinct;+ for (AVerseSpawnPoint* Pick : Picks)+ {+ Distinct.Add(Pick);+ }+ TestTrue(TEXT("first spawns are seeded across points"), Distinct.Num() > 1);+ TestFalse(TEXT("deathmatch never resets destruction at a set"), Duel.Rules->ShouldResetDestruction(EVerseBoundary::Set));+ TestFalse(TEXT("deathmatch never resets destruction at a round"), Duel.Rules->ShouldResetDestruction(EVerseBoundary::Round));+ }+ return true;+}++IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseDeathmatchInvariantsTest, "Verse.Combat.Deathmatch.Invariants",+ EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::EngineFilter)++// D1-D4 over 200 seeded deaths (A11.3).+bool FVerseDeathmatchInvariantsTest::RunTest(const FString& Parameters)+{+ FDuel Duel;+ FRandomStream Rng(1111);+ int32 D1Fail = 0, D2Fail = 0, D3Fail = 0, D4Fail = 0, Checked = 0, HiddenAvailable = 0;+ TMap<const AVersePlayerState*, float> DiedAt;+ TMap<const AVersePlayerState*, float> FireAt; // planned first shot after a respawn, or 1e9++ Duel.OnRespawn = [&](AVersePlayerState* P, AVerseSpawnPoint* S) {+ if (const float* Died = DiedAt.Find(P))+ {+ const float Wait = Duel.Time - *Died;+ if (Wait < 3.f - KINDA_SMALL_NUMBER || Wait > 3.f + TickS + KINDA_SMALL_NUMBER)+ {+ ++D1Fail;+ }+ DiedAt.Remove(P);+ }+ // D2 and D3, recomputed from the scripted world, not read back from the rules.+ const FVector* OppFeet = Duel.Feet.Find(Duel.Other(P));+ if (OppFeet && S)+ {+ const FVector Eye = *OppFeet + FVector(0, 0, 165);+ auto Hidden = [&](const FVector& Floor) {+ for (const float H : {0.3f, 1.0f, 1.65f})+ {+ if (LineClear(Eye, Floor + FVector(0, 0, H * 100)))+ {+ return false;+ }+ }+ return true;+ };+ float BestHidden = -1.f;+ for (const AVerseSpawnPoint* C : Duel.Spawns)+ {+ const FVector F = C->GetActorLocation();+ if (FVector::Dist(F, *OppFeet) > VerseSpawnSelection::BlockRadiusCm && Hidden(F))+ {+ BestHidden = FMath::Max(BestHidden, PathLength(*OppFeet, F));+ }+ }+ ++Checked;+ if (BestHidden >= 0.f)+ {+ ++HiddenAvailable;+ if (!Hidden(S->GetActorLocation()))+ {+ ++D2Fail;+ }+ else if (PathLength(*OppFeet, S->GetActorLocation()) < BestHidden - VerseSpawnSelection::TieCm)+ {+ ++D3Fail;+ }+ }+ }+ FireAt.Add(P, Rng.FRand() < 0.6f ? Duel.Time + Rng.FRandRange(0.1f, 1.9f) : 1e9f);+ };++ Duel.Rules->OnMatchStart();+ int32 Deaths = 0;+ float NextDeath = 2.f;+ float NextWander = 1.f;+ while (Deaths < 200 && Duel.Time < 3600.f)+ {+ Duel.TickOnce();+ for (AVersePlayerState* P : {Duel.Person, Duel.Bot})+ {+ if (!Duel.Rules->IsAlive(P))+ {+ continue;+ }+ const float* Planned = FireAt.Find(P);+ const bool bProtected = Duel.Rules->IsSpawnProtected(P);+ const float SinceSpawn = Duel.Time - Duel.LastRespawn.FindRef(P);+ // D4: no damage while protected; reload and ADS keep it.+ if (bProtected)+ {+ D4Fail += Duel.Rules->CanDamagePlayer(P, EVerseDamageSource::Bolt) ? 1 : 0;+ Duel.Rules->OnPlayerAction(P, EVersePlayerAction::Reload);+ Duel.Rules->OnPlayerAction(P, EVersePlayerAction::Ads);+ D4Fail += Duel.Rules->IsSpawnProtected(P) ? 0 : 1;+ if (SinceSpawn > 2.f + TickS + KINDA_SMALL_NUMBER)+ {+ ++D4Fail; // protection outlived SpawnProtectionMax+ }+ }+ if (Planned && Duel.Time >= *Planned)+ {+ const bool bWasProtected = Duel.Rules->IsSpawnProtected(P);+ Duel.Fire(P);+ FireAt.Add(P, 1e9f);+ // The first own shot ends protection on that tick.+ if (bWasProtected && (Duel.Rules->IsSpawnProtected(P) || !Duel.Rules->CanDamagePlayer(P, EVerseDamageSource::Bolt)))+ {+ ++D4Fail;+ }+ }+ }+ if (Duel.Time >= NextWander)+ {+ NextWander += 1.f;+ for (AVersePlayerState* P : {Duel.Person, Duel.Bot})+ {+ if (Duel.Feet.Contains(P))+ {+ FVector Pos;+ do+ {+ Pos = FVector(Rng.FRandRange(2600, 7400), Rng.FRandRange(500, 4300), 0);+ } while (Inside(Pos + FVector(0, 0, 50)));+ Duel.Feet.Add(P, Pos);+ }+ }+ }+ if (Duel.Time >= NextDeath && Duel.Rules->IsAlive(Duel.Person) && Duel.Rules->IsAlive(Duel.Bot))+ {+ AVersePlayerState* Victim = Rng.FRand() < 0.5f ? Duel.Person : Duel.Bot;+ DiedAt.Add(Victim, Duel.Time);+ Duel.Kill(Victim, Duel.Other(Victim));+ ++Deaths;+ NextDeath = Duel.Time + Rng.FRandRange(0.5f, 4.f);+ }+ }+ // Let the last respawn happen.+ for (int32 i = 0; i < 240; ++i)+ {+ Duel.TickOnce();+ }++ TestEqual(TEXT("200 seeded deaths"), Deaths, 200);+ TestEqual(TEXT("D1: every respawn at 3.0 s within one tick"), D1Fail, 0);+ TestEqual(TEXT("D2: out of sight whenever a candidate is"), D2Fail, 0);+ TestEqual(TEXT("D3: farthest by path among the hidden"), D3Fail, 0);+ TestEqual(TEXT("D4: protected takes no damage, first shot ends it on that tick"), D4Fail, 0);+ TestTrue(TEXT("the sight rule was exercised"), HiddenAvailable > 100 && Checked >= 200);+ TestEqual(TEXT("2 first spawns + one per death"), Duel.Respawns, 202);+ return true;+}++IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseDeathmatchSetSummaryTest, "Verse.Combat.Deathmatch.SetSummary",+ EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::EngineFilter)++// 50 scripted sets: one FVerseSetSummary each with the kills of the server log; leaving+// mid-set raises exactly one Unfinished summary (A11.8).+bool FVerseDeathmatchSetSummaryTest::RunTest(const FString& Parameters)+{+ FDuel Duel;+ FRandomStream Rng(5050);+ Duel.Rules->OnMatchStart();+ struct FLog+ {+ int32 Person = 0, Bot = 0, PersonHead = 0, BotFinishers = 0;+ };+ TArray<FLog> Logs;+ Logs.AddDefaulted();+ int32 Kills = 0;+ while (Duel.Summaries.Num() < 50 && Kills < 2000)+ {+ // Both must be alive for a kill: wait out the respawn.+ while (!(Duel.Rules->IsAlive(Duel.Person) && Duel.Rules->IsAlive(Duel.Bot)))+ {+ Duel.TickOnce();+ }+ for (int32 i = 0; i < 30; ++i)+ {+ Duel.TickOnce();+ }+ const bool bPersonKills = Rng.FRand() < 0.45f;+ const bool bHead = Rng.FRand() < 0.3f;+ const bool bFinisher = !bHead && Rng.FRand() < 0.1f;+ FLog& L = Logs.Last();+ if (bPersonKills)+ {+ L.Person += 1;+ L.PersonHead += bHead ? 1 : 0;+ Duel.Kill(Duel.Bot, Duel.Person, EVerseDamageSource::Bolt, bHead ? EVerseHitZone::Head : EVerseHitZone::UpperTorso);+ }+ else+ {+ L.Bot += 1;+ L.BotFinishers += bFinisher ? 1 : 0;+ Duel.Kill(Duel.Person, Duel.Bot, bFinisher ? EVerseDamageSource::Finisher : EVerseDamageSource::Bolt);+ }+ ++Kills;+ if (Duel.Summaries.Num() == Logs.Num())+ {+ Logs.AddDefaulted();+ }+ }+ TestEqual(TEXT("50 finished sets"), Duel.Summaries.Num(), 50);+ TSet<FString> Ids;+ for (int32 i = 0; i < FMath::Min(50, Duel.Summaries.Num()); ++i)+ {+ const FVerseSetSummary& S = Duel.Summaries[i];+ const FLog& L = Logs[i];+ const bool bWon = L.Person == 10;+ TestEqual(FString::Printf(TEXT("set %d index"), i), S.SetIndex, i + 1);+ TestEqual(FString::Printf(TEXT("set %d person kills"), i), S.Person.Kills, L.Person);+ TestEqual(FString::Printf(TEXT("set %d opponent kills"), i), S.Opponent.Kills, L.Bot);+ TestEqual(FString::Printf(TEXT("set %d person deaths"), i), S.Person.Deaths, L.Bot);+ TestEqual(FString::Printf(TEXT("set %d headshots"), i), S.Person.Headshots, L.PersonHead);+ TestEqual(FString::Printf(TEXT("set %d finishers"), i), S.Opponent.Finishers, L.BotFinishers);+ TestTrue(FString::Printf(TEXT("set %d first to 10"), i), FMath::Max(L.Person, L.Bot) == 10);+ TestTrue(FString::Printf(TEXT("set %d outcome"), i), S.Outcome == (bWon ? EVerseSetOutcome::Won : EVerseSetOutcome::Lost));+ TestTrue(TEXT("ruleset id"), S.RulesetId == FName(TEXT("endless/1")));+ TestTrue(TEXT("bot tier"), S.BotTier == FName(TEXT("normal")));+ TestTrue(TEXT("person line is the person"), !S.Person.bIsBot && S.Opponent.bIsBot);+ TestTrue(TEXT("set time counted"), S.MatchTimeS > 0.f && S.EndedAtUnix >= S.StartedAtUnix);+ Ids.Add(S.MatchId);+ }+ TestEqual(TEXT("match ids unique"), Ids.Num(), Duel.Summaries.Num());++ // Leave mid-set: a couple of kills into set 51, then the arena closes.+ while (!(Duel.Rules->IsAlive(Duel.Person) && Duel.Rules->IsAlive(Duel.Bot)))+ {+ Duel.TickOnce();+ }+ Duel.Kill(Duel.Bot, Duel.Person);+ FVerseArenaSwitchEvent Off;+ Off.bArenaOn = false;+ Off.Deck = TEXT("hangar");+ Duel.Hub()->OnArenaSwitch.Broadcast(Off);+ Duel.Hub()->OnArenaSwitch.Broadcast(Off); // a second close changes nothing+ Duel.Rules->EndMatch();+ TestEqual(TEXT("exactly one unfinished summary"), Duel.Summaries.Num(), 51);+ if (Duel.Summaries.Num() == 51)+ {+ const FVerseSetSummary& U = Duel.Summaries.Last();+ TestTrue(TEXT("unfinished outcome"), U.Outcome == EVerseSetOutcome::Unfinished);+ TestEqual(TEXT("unfinished set index"), U.SetIndex, 51);+ TestEqual(TEXT("unfinished kills"), U.Person.Kills, 1);+ }+ TestFalse(TEXT("match stopped"), Duel.Rules->IsMatchRunning());+ return true;+}++IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseDeathmatchLateRecordTest, "Verse.Combat.Deathmatch.LateRecord",+ EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::EngineFilter)++// A bot first seen after OnMatchStart (spawned by a later arena-switch listener) is named in+// the first set summary with its id and as a bot, not as player 0.+bool FVerseDeathmatchLateRecordTest::RunTest(const FString& Parameters)+{+ FDuel Duel;+ Duel.Players = {Duel.Person};+ Duel.Rules->OnMatchStart();+ Duel.Players = {Duel.Person, Duel.Bot};+ Duel.Fire(Duel.Bot);+ Duel.Rules->EndMatch();+ if (!TestEqual(TEXT("one unfinished summary"), Duel.Summaries.Num(), 1))+ {+ return false;+ }+ const FVerseSetSummary& S = Duel.Summaries[0];+ TestEqual(TEXT("late opponent id"), S.Opponent.PlayerId, 2);+ TestTrue(TEXT("late opponent is a bot"), S.Opponent.bIsBot);+ TestEqual(TEXT("late opponent shot counted"), S.Opponent.ShotsFired, 1);+ return true;+}++IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseDeathmatchRulesJsonTest, "Verse.Combat.Deathmatch.RulesJson",+ EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::EngineFilter)++bool FVerseDeathmatchRulesJsonTest::RunTest(const FString& Parameters)+{+ FString Text;+ const FString Path = UVerseRulesetConfig::RulesFilePath(TEXT("deathmatch"));+ if (!TestTrue(TEXT("Data/rules/deathmatch.json exists"), FFileHelper::LoadFileToString(Text, *Path)))+ {+ return false;+ }+ UVerseRulesetConfig* Config = NewObject<UVerseRulesetConfig>();+ FString Error;+ TestTrue(FString::Printf(TEXT("parses (%s)"), *Error), Config->ApplyJson(Text, Error));+ TestEqual(TEXT("respawn 3.0 s"), Config->RespawnDelay, 3.f);+ TestEqual(TEXT("protection 2.0 s"), Config->SpawnProtectionMax, 2.f);+ TestEqual(TEXT("first to 10"), Config->KillsPerSet, 10);+ TestEqual(TEXT("no regeneration"), Config->HealthRegenPerSec, 0.f);+ TestEqual(TEXT("armor inert"), Config->MaxArmor, 0.f);+ TestTrue(TEXT("deathmatch class"), Config->RulesetClass == UVerseRuleset_Deathmatch::StaticClass());++ UVerseRulesetConfig* Bad = NewObject<UVerseRulesetConfig>();+ TestFalse(TEXT("unknown key refused"), Bad->ApplyJson(TEXT("{\"schema\":\"verse.rules/1\",\"respawn\":3}"), Error));+ TestFalse(TEXT("wrong schema refused"), Bad->ApplyJson(TEXT("{\"schema\":\"verse.rules/2\"}"), Error));+ TestFalse(TEXT("bad slot refused"), Bad->ApplyJson(TEXT("{\"schema\":\"verse.rules/1\",\"loadout\":{\"Sidearm\":\"/Game/Verse/X.X\"}}"), Error));+ return true;+}++#endif // WITH_DEV_AUTOMATION_TESTSdiff --git a/unreal/Verse/Source/VerseCombat/Private/Tests/Rules/VerseRulesTestWorld.h b/unreal/Verse/Source/VerseCombat/Private/Tests/Rules/VerseRulesTestWorld.hnew file mode 100644index 0000000000..6607da24bd--- /dev/null+++ b/unreal/Verse/Source/VerseCombat/Private/Tests/Rules/VerseRulesTestWorld.h@@ -0,0 +1,37 @@+#pragma once++#if WITH_DEV_AUTOMATION_TESTS++#include "CoreMinimal.h"+#include "Engine/Engine.h"+#include "Engine/World.h"++/** A bare game world for the rules tests: subsystems (the event hub) but no game mode. */+struct FVerseRulesTestWorld+{+ UWorld* World = nullptr;++ FVerseRulesTestWorld()+ {+ World = UWorld::CreateWorld(EWorldType::Game, false);+ FWorldContext& Context = GEngine->CreateNewWorldContext(EWorldType::Game);+ Context.SetCurrentWorld(World);+ World->InitializeActorsForPlay(FURL());+ }++ ~FVerseRulesTestWorld()+ {+ GEngine->DestroyWorldContext(World);+ World->DestroyWorld(false);+ }++ template <class T>+ T* Spawn(const FVector& Location = FVector::ZeroVector)+ {+ FActorSpawnParameters Params;+ Params.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn;+ return World->SpawnActor<T>(T::StaticClass(), Location, FRotator::ZeroRotator, Params);+ }+};++#endif // WITH_DEV_AUTOMATION_TESTSdiff --git a/unreal/Verse/Source/VerseCombat/Public/Rules/VerseGameMode.h b/unreal/Verse/Source/VerseCombat/Public/Rules/VerseGameMode.hnew file mode 100644index 0000000000..f9e0b688ab--- /dev/null+++ b/unreal/Verse/Source/VerseCombat/Public/Rules/VerseGameMode.h@@ -0,0 +1,61 @@+#pragma once++#include "Combat/VerseCombatTypes.h"+#include "CoreMinimal.h"+#include "GameFramework/GameModeBase.h"+#include "Rules/VerseRuleset.h"++#include "VerseGameMode.generated.h"++class AVersePlayerState;+class UVerseRulesetConfig;++/**+ * The thin game mode of combat-state.md 10: it owns one UVerseRuleset (from RulesetConfig, or+ * from unreal/Verse/Data/rules/deathmatch.json when none is set), fills the ruleset's world+ * functions, and forwards every rule question. It never decides a rule itself.+ *+ * Arena on (FVerseArenaSwitchEvent on the hub) is forwarded as OnMatchStart, every death as+ * OnKill; weapon, melee and gadget code report offensive actions with NotifyPlayerAction and+ * ask CanDamage / ModifyDamage before damage lands.+ */+UCLASS()+class VERSECOMBAT_API AVerseGameMode : public AGameModeBase+{+ GENERATED_BODY()++public:+ AVerseGameMode();++ UPROPERTY(EditDefaultsOnly, Category = "Verse|Rules")+ TObjectPtr<UVerseRulesetConfig> RulesetConfig;++ UPROPERTY(Transient)+ TObjectPtr<UVerseRuleset> Ruleset;++ virtual void InitGame(const FString& MapName, const FString& Options, FString& ErrorMessage) override;+ virtual void BeginPlay() override;+ virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override;+ virtual AActor* ChoosePlayerStart_Implementation(AController* Player) override;++ bool CanDamage(const FVerseDamageContext& Ctx) const;+ float ModifyDamage(const FVerseDamageContext& Ctx, float Damage) const;+ void NotifyPlayerAction(AVersePlayerState* Player, EVersePlayerAction Action);+ void GetLoadout(const AVersePlayerState* Player, TMap<EVerseLoadoutSlot, const UPrimaryDataAsset*>& Out) const;+ /** Forwards UVerseRuleset::ShouldResetDestruction; false without a ruleset. */+ bool ShouldResetDestruction(EVerseBoundary Boundary) const;++ /** The world functions a ruleset gets in a real match (path length: navmesh through reflection). */+ FVerseRulesHost MakeDefaultHost();++ /** The config the ruleset is built from; loads the rules JSON on first use. */+ const UVerseRulesetConfig* ResolveConfig();++private:+ void CreateRuleset();+ void HandleArenaSwitch(const FVerseArenaSwitchEvent& E);+ void HandleDeath(const FVerseDeathEvent& E);++ FDelegateHandle ArenaHandle;+ FDelegateHandle DeathHandle;+};diff --git a/unreal/Verse/Source/VerseCombat/Public/Rules/VersePlayerState.h b/unreal/Verse/Source/VerseCombat/Public/Rules/VersePlayerState.hnew file mode 100644index 0000000000..fea1fceb33--- /dev/null+++ b/unreal/Verse/Source/VerseCombat/Public/Rules/VersePlayerState.h@@ -0,0 +1,58 @@+#pragma once++#include "CoreMinimal.h"+#include "GameFramework/PlayerState.h"++#include "VersePlayerState.generated.h"++/**+ * Score, respawn time and bot identity of one duel player (contracts/combat-state.md 2.1, 11.2).+ * Replicated to all with the push model; written on the server only: the score and RespawnAt+ * by the ruleset (Rules/), BotTier and BotEffectiveSkill by VerseBot.+ */+UCLASS()+class VERSECOMBAT_API AVersePlayerState : public APlayerState+{+ GENERATED_BODY()++public:+ AVersePlayerState();++ virtual void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const override;++ UPROPERTY(Replicated, VisibleInstanceOnly, BlueprintReadOnly, Category = "Verse|Score")+ int32 Kills = 0;++ UPROPERTY(Replicated, VisibleInstanceOnly, BlueprintReadOnly, Category = "Verse|Score")+ int32 Deaths = 0;++ UPROPERTY(Replicated, VisibleInstanceOnly, BlueprintReadOnly, Category = "Verse|Score")+ int32 Headshots = 0;++ UPROPERTY(Replicated, VisibleInstanceOnly, BlueprintReadOnly, Category = "Verse|Score")+ int32 Finishers = 0;++ /** Kills in the running set (first to UVerseRulesetConfig::KillsPerSet). */+ UPROPERTY(Replicated, VisibleInstanceOnly, BlueprintReadOnly, Category = "Verse|Score")+ int32 SetKills = 0;++ UPROPERTY(Replicated, VisibleInstanceOnly, BlueprintReadOnly, Category = "Verse|Score")+ int32 SetsWon = 0;++ /** Server time of the next respawn; UI countdown and kill cam length. */+ UPROPERTY(Replicated, VisibleInstanceOnly, BlueprintReadOnly, Category = "Verse|Score")+ float RespawnAt = 0.f;++ /** normal, hard, elite or adaptive for the bot; None for a person. */+ UPROPERTY(Replicated, VisibleInstanceOnly, BlueprintReadOnly, Category = "Verse|Bot")+ FName BotTier;++ /** Adaptive skill s of the bot; -1 for a person. */+ UPROPERTY(Replicated, VisibleInstanceOnly, BlueprintReadOnly, Category = "Verse|Bot")+ float BotEffectiveSkill = -1.f;++ bool IsBotPlayer() const { return !BotTier.IsNone(); }++ /** Server: marks every score field dirty for the push model after the ruleset wrote them. */+ void MarkScoreDirty();+};diff --git a/unreal/Verse/Source/VerseCombat/Public/Rules/VerseRuleset.h b/unreal/Verse/Source/VerseCombat/Public/Rules/VerseRuleset.hnew file mode 100644index 0000000000..f770bfcd84--- /dev/null+++ b/unreal/Verse/Source/VerseCombat/Public/Rules/VerseRuleset.h@@ -0,0 +1,107 @@+#pragma once++#include "Combat/VerseCombatTypes.h"+#include "CoreMinimal.h"+#include "Rules/VerseRulesetConfig.h"+#include "UObject/Object.h"++#include "VerseRuleset.generated.h"++class AVerseGameMode;+class AVersePlayerState;+class AVerseSpawnPoint;+class UPrimaryDataAsset;+class UVerseCombatStateComponent;++/**+ * A boundary in a match at which a ruleset may want the destructible pieces reset+ * (destruction.md 11). Arena on, arena off and match end always reset fully and are not asked;+ * respawns never reset. VerseCombat asks UVerseRuleset::ShouldResetDestruction, VerseDestruction+ * executes the reset (WP06).+ */+UENUM()+enum class EVerseBoundary : uint8+{+ /** One round of a round-based mode. */+ Round,+ /** One set of an endless mode (deathmatch: first to KillsPerSet). */+ Set,+};++/**+ * Everything a ruleset needs from the world, as functions. AVerseGameMode fills it from the+ * real world (FillDefaultHost); tests fill it with a scripted world, so the rules run the same+ * code in both. Every function may be left empty; the ruleset then uses the documented fallback.+ */+struct VERSECOMBAT_API FVerseRulesHost+{+ /** Server time in seconds (the world's time, paused time excluded). */+ TFunction<float()> ServerTime;+ /** Wall clock for FVerseSetSummary::StartedAtUnix / EndedAtUnix. Fallback FDateTime::UtcNow. */+ TFunction<double()> UnixNow;+ /** The duel players. */+ TFunction<TArray<AVersePlayerState*>()> Players;+ /** The spawn points of the arena data layer. */+ TFunction<TArray<AVerseSpawnPoint*>()> SpawnPoints;+ /** Floor point under a spawn point, world cm. Fallback: the actor location. */+ TFunction<FVector(const AVerseSpawnPoint*)> SpawnFloor;+ /** Current eye point of a player's pawn; false when the player has no pawn. */+ TFunction<bool(const AVersePlayerState*, FVector&)> EyePoint;+ /** Is the segment clear on VerseBolt against the current piece proxies? Fallback: clear. */+ TFunction<bool(const FVector&, const FVector&)> LineClear;+ /** Floor point under a player's pawn (the navmesh agent location); false without a pawn. Fallback: eye minus 165 cm. */+ TFunction<bool(const AVersePlayerState*, FVector&)> FloorPoint;+ /** Navmesh path length in cm, floor point to floor point; negative when there is no path. Fallback: Euclidean. */+ TFunction<float(const FVector&, const FVector&)> PathLength;+ /** Is a pawn other than `Ignore`'s within the radius of `Floor`? */+ TFunction<bool(const FVector& Floor, float RadiusCm, const AVersePlayerState* Ignore)> PawnNear;+ /** Puts the player's new pawn on the spawn point. */+ TFunction<void(AVersePlayerState*, AVerseSpawnPoint*)> Respawn;+ /** The combat state component of the player's current pawn, or nullptr. */+ TFunction<UVerseCombatStateComponent*(const AVersePlayerState*)> CombatState;+};++/**+ * One game mode's rules (combat-state.md 10). AVerseGameMode is a thin forwarder that owns one+ * instance and asks it every rule question; a new mode is a subclass plus a config asset.+ */+UCLASS(Abstract)+class VERSECOMBAT_API UVerseRuleset : public UObject+{+ GENERATED_BODY()++public:+ virtual void Init(AVerseGameMode* InMode, const UVerseRulesetConfig* InConfig);+ virtual void OnMatchStart() PURE_VIRTUAL(UVerseRuleset::OnMatchStart, );+ virtual void GetLoadout(const AVersePlayerState* P, TMap<EVerseLoadoutSlot, const UPrimaryDataAsset*>& Out) const;+ virtual bool CanDamage(const FVerseDamageContext& Ctx) const { return true; }+ virtual float ModifyDamage(const FVerseDamageContext& Ctx, float Damage) const { return Damage; }+ virtual void OnPlayerAction(AVersePlayerState* P, EVersePlayerAction Action) {}+ virtual void OnKill(const FVerseDeathEvent& E) PURE_VIRTUAL(UVerseRuleset::OnKill, );+ virtual float GetRespawnDelay(const AVersePlayerState* P) const;+ virtual AVerseSpawnPoint* ChooseSpawn(const AVersePlayerState* P) PURE_VIRTUAL(UVerseRuleset::ChooseSpawn, return nullptr;);+ virtual float GetSpawnProtection(const AVersePlayerState* P) const;+ virtual bool IsSetOver(AVersePlayerState*& OutWinner) const { return false; }+ virtual void BuildSetSummary(FVerseSetSummary& Out) const {}+ /** Reset the destructible pieces at this boundary? (destruction.md 11) Endless modes: no. */+ virtual bool ShouldResetDestruction(EVerseBoundary Boundary) const { return false; }++ /** Replaces the world functions (tests, the harness). */+ void SetHost(const FVerseRulesHost& InHost) { Host = InHost; }+ const FVerseRulesHost& GetHost() const { return Host; }+ const UVerseRulesetConfig* GetConfig() const { return Config; }+ AVerseGameMode* GetMode() const { return Mode; }++protected:+ float Now() const;+ TArray<AVersePlayerState*> GetPlayers() const;+ AVersePlayerState* FindPlayer(int32 PlayerId) const;++ UPROPERTY(Transient)+ TObjectPtr<AVerseGameMode> Mode = nullptr;++ UPROPERTY(Transient)+ TObjectPtr<const UVerseRulesetConfig> Config = nullptr;++ FVerseRulesHost Host;+};diff --git a/unreal/Verse/Source/VerseCombat/Public/Rules/VerseRulesetConfig.h b/unreal/Verse/Source/VerseCombat/Public/Rules/VerseRulesetConfig.hnew file mode 100644index 0000000000..37bfc90d24--- /dev/null+++ b/unreal/Verse/Source/VerseCombat/Public/Rules/VerseRulesetConfig.h@@ -0,0 +1,83 @@+#pragma once++#include "Combat/VerseCombatTypes.h"+#include "CoreMinimal.h"+#include "Engine/DataAsset.h"++#include "VerseRulesetConfig.generated.h"++class AController;+class APawn;+class UVerseRuleset;++/** What a player did; offensive actions end spawn protection (combat-state.md 9.3, 10). */+UENUM()+enum class EVersePlayerAction : uint8+{+ Fire,+ Melee,+ Gadget,+ Reload,+ Ads,+ SwitchSlot+};++/** The question "may this damage land" (combat-state.md 10, CanDamage / ModifyDamage). */+USTRUCT()+struct VERSECOMBAT_API FVerseDamageContext+{+ GENERATED_BODY()++ UPROPERTY()+ TObjectPtr<AController> Instigator = nullptr;++ UPROPERTY()+ TObjectPtr<APawn> Victim = nullptr;++ UPROPERTY()+ EVerseDamageSource Source = EVerseDamageSource::Bolt;++ UPROPERTY()+ EVerseHitZone Zone = EVerseHitZone::None;+};++/**+ * One game mode's rules as data (combat-state.md 10, 11.2). Deathmatch reads its start values+ * from unreal/Verse/Data/rules/deathmatch.json (ApplyJson); the balance harness owns them.+ */+UCLASS(BlueprintType)+class VERSECOMBAT_API UVerseRulesetConfig : public UPrimaryDataAsset+{+ GENERATED_BODY()++public:+ UPROPERTY(EditDefaultsOnly, Category = "Verse|Rules")+ TSubclassOf<UVerseRuleset> RulesetClass;++ UPROPERTY(EditDefaultsOnly, Category = "Verse|Rules", meta = (Units = "s"))+ float RespawnDelay = 3.f;++ UPROPERTY(EditDefaultsOnly, Category = "Verse|Rules", meta = (Units = "s"))+ float SpawnProtectionMax = 2.f;++ UPROPERTY(EditDefaultsOnly, Category = "Verse|Rules")+ int32 KillsPerSet = 10;++ UPROPERTY(EditDefaultsOnly, Category = "Verse|Rules")+ float HealthRegenPerSec = 0.f;++ UPROPERTY(EditDefaultsOnly, Category = "Verse|Rules")+ float MaxArmor = 0.f;++ UPROPERTY(EditDefaultsOnly, Category = "Verse|Rules")+ TMap<EVerseLoadoutSlot, TSoftObjectPtr<UPrimaryDataAsset>> Loadout;++ /**+ * Reads the `verse.rules/1` text surface (unreal/Verse/Data/rules/<mode>.json) into this+ * config. Unknown keys are errors, so a renamed field never silently keeps its old value.+ */+ bool ApplyJson(const FString& Text, FString& OutError);++ /** Project path of a rules file: <project>/Data/rules/<Name>.json. */+ static FString RulesFilePath(const FString& Name);+};diff --git a/unreal/Verse/Source/VerseCombat/Public/Rules/VerseRuleset_Deathmatch.h b/unreal/Verse/Source/VerseCombat/Public/Rules/VerseRuleset_Deathmatch.hnew file mode 100644index 0000000000..30501a92b1--- /dev/null+++ b/unreal/Verse/Source/VerseCombat/Public/Rules/VerseRuleset_Deathmatch.h@@ -0,0 +1,111 @@+#pragma once++#include "Combat/VerseCombatTypes.h"+#include "CoreMinimal.h"+#include "Destruction/VerseDestructionTypes.h"+#include "Rules/VersePlayerState.h"+#include "Rules/VerseRuleset.h"+#include "Rules/VerseSpawnSelection.h"+#include "Tickable.h"++#include "VerseRuleset_Deathmatch.generated.h"++/**+ * Endless 1v1 deathmatch (combat-state.md 9.1-9.4): kill +1, sets of first to KillsPerSet with+ * one FVerseSetSummary per finished set and one Unfinished summary when the arena closes+ * mid-set, respawn after RespawnDelay at the 9.2 spawn, spawn protection that ends at+ * SpawnProtectionMax or on the first own offensive action. Server only.+ *+ * It listens on the event hub itself for what only feeds statistics (fire, hit, gadget,+ * fracture) and for the arena closing; AVerseGameMode forwards the rule questions.+ */+UCLASS()+class VERSECOMBAT_API UVerseRuleset_Deathmatch : public UVerseRuleset, public FTickableGameObject+{+ GENERATED_BODY()++public:+ /** FVerseSetSummary::RulesetId of this mode. */+ static const FName RulesetId;++ virtual void Init(AVerseGameMode* InMode, const UVerseRulesetConfig* InConfig) override;+ virtual void OnMatchStart() override;+ virtual bool CanDamage(const FVerseDamageContext& Ctx) const override;+ virtual void OnPlayerAction(AVersePlayerState* P, EVersePlayerAction Action) override;+ virtual void OnKill(const FVerseDeathEvent& E) override;+ virtual AVerseSpawnPoint* ChooseSpawn(const AVersePlayerState* P) override;+ virtual bool IsSetOver(AVersePlayerState*& OutWinner) const override;+ virtual void BuildSetSummary(FVerseSetSummary& Out) const override;+ /** Endless deathmatch never resets the world between sets (destruction.md 11). */+ virtual bool ShouldResetDestruction(EVerseBoundary Boundary) const override { return false; }+ virtual void BeginDestroy() override;++ /** Runs respawns and protection timeouts up to `ServerTime`. Ticked every frame unless bAutoTick is off. */+ void Advance(float ServerTime);++ /** The arena closed or the Verse quits: the running set is sent as Unfinished, the match stops. */+ void EndMatch();++ bool IsMatchRunning() const { return bRunning; }+ bool IsSpawnProtected(const AVersePlayerState* P) const;+ /** CanDamage for a known victim (the pawn-free form tests and the harness use). */+ bool CanDamagePlayer(const AVersePlayerState* Victim, EVerseDamageSource Source) const;+ bool IsAlive(const AVersePlayerState* P) const;+ int32 GetSetIndex() const { return SetIndex; }+ const FString& GetSessionId() const { return SessionId; }+ /** The last spawn decision, for logs and the D2/D3 tests. */+ const FVerseSpawnChoice& GetLastSpawnChoice() const { return LastChoice; }++ /** Tests and the harness step time themselves. */+ bool bAutoTick = true;+ /** Seed of the spawn tie-break stream (VerseRng salt Spawn). */+ uint64 MatchSeed = 0x5EED11;++ // FTickableGameObject+ virtual void Tick(float DeltaTime) override;+ virtual TStatId GetStatId() const override;+ virtual bool IsTickable() const override;+ virtual UWorld* GetTickableGameObjectWorld() const override;++private:+ struct FPlayerRecord+ {+ bool bAlive = false;+ bool bProtected = false;+ float ProtectedUntil = 0.f;+ float RespawnAt = 0.f;+ int32 Streak = 0;+ FVerseSetLine Line;+ };++ FPlayerRecord& Record(const AVersePlayerState* P);+ const FPlayerRecord* FindRecord(const AVersePlayerState* P) const;+ void SpawnPlayer(AVersePlayerState* P);+ void EndProtection(AVersePlayerState* P);+ void WriteProtection(const AVersePlayerState* P, bool bOn, float Until) const;+ void FinishSet(AVersePlayerState* Winner);+ void StartSet();+ void BuildSummary(FVerseSetSummary& Out, const AVersePlayerState* Winner) const;+ bool IsSpawnBlocked(const FVector& Floor, const AVersePlayerState* Respawning) const;+ void Subscribe();+ void Unsubscribe();++ void HandleFire(const FVerseFireEvent& E);+ void HandleHit(const FVerseHitEvent& E);+ void HandleGadget(const FVerseGadgetEvent& E);+ void HandleFracture(const FVerseFractureEvent& E);+ void HandleArenaSwitch(const FVerseArenaSwitchEvent& E);++ TMap<TWeakObjectPtr<const AVersePlayerState>, FPlayerRecord> Records;+ /** Bulwarks and armed breach charges by owner and kind: they block spawns within 3 m (2.3). */+ TArray<FVerseGadgetEvent> ActiveGadgets;+ FVerseSpawnChoice LastChoice;+ bool bRunning = false;+ FString SessionId;+ int32 SetIndex = 0;+ float SetStartTime = 0.f;+ double SetStartUnix = 0.0;+ uint64 DeathCount = 0;+ TWeakObjectPtr<class UVerseEventHub> BoundHub;+ TArray<FDelegateHandle> Handles;+};diff --git a/unreal/Verse/Source/VerseCombat/Public/Rules/VerseSpawnPoint.h b/unreal/Verse/Source/VerseCombat/Public/Rules/VerseSpawnPoint.hnew file mode 100644index 0000000000..6e25a39583--- /dev/null+++ b/unreal/Verse/Source/VerseCombat/Public/Rules/VerseSpawnPoint.h@@ -0,0 +1,30 @@+#pragma once++#include "CoreMinimal.h"+#include "GameFramework/PlayerStart.h"++#include "VerseSpawnPoint.generated.h"++/**+ * A duel spawn in the arena data layer (combat-state.md 9.2, 11.2). Placed from the `spawn`+ * sockets of the hangar arena placement files (docs/verse/unreal/arena.md). The probe points+ * are the heights above the floor the opponent's sight is tested against.+ */+UCLASS()+class VERSECOMBAT_API AVerseSpawnPoint : public APlayerStart+{+ GENERATED_BODY()++public:+ AVerseSpawnPoint(const FObjectInitializer& ObjectInitializer);++ UPROPERTY(EditInstanceOnly, Category = "Verse|Spawn")+ TArray<float> ProbeHeightsM = {0.3f, 1.0f, 1.65f};++ /** The socket id of the placement file, e.g. "sp_booth" (for logs and tests). */+ UPROPERTY(EditInstanceOnly, Category = "Verse|Spawn")+ FName SpawnId;++ /** Floor point under the capsule, world cm. */+ FVector GetFloorLocation() const;+};diff --git a/unreal/Verse/Source/VerseCombat/Public/Rules/VerseSpawnSelection.h b/unreal/Verse/Source/VerseCombat/Public/Rules/VerseSpawnSelection.hnew file mode 100644index 0000000000..1257f6313b--- /dev/null+++ b/unreal/Verse/Source/VerseCombat/Public/Rules/VerseSpawnSelection.h@@ -0,0 +1,57 @@+#pragma once++#include "CoreMinimal.h"+#include "Templates/Function.h"++/** One spawn candidate for VerseSpawnSelection::Choose. */+struct VERSECOMBAT_API FVerseSpawnCandidate+{+ /** Floor point, world cm. */+ FVector Floor = FVector::ZeroVector;+ /** Probe heights above the floor, metres (AVerseSpawnPoint::ProbeHeightsM). */+ TArray<float> ProbeHeightsM = {0.3f, 1.0f, 1.65f};+ /** A pawn, Bulwark or armed breach charge within BlockRadiusCm. */+ bool bBlocked = false;+};++/** What Choose found, for logs and the D2/D3 tests. */+struct VERSECOMBAT_API FVerseSpawnChoice+{+ int32 Index = INDEX_NONE;+ bool bVisible = false;+ float DistanceCm = 0.f;+ /** Every candidate's visibility and distance as Choose saw them (same order as the input). */+ TArray<bool> Visible;+ TArray<float> Distances;+ TArray<int32> Pool;+};++/**+ * Spawn selection of combat-state.md 9.2, as a pure function: no world, so the rule is tested+ * on its own and the ruleset only gathers the inputs.+ *+ * candidates = not blocked (all of them when every one is blocked)+ * visible(c) = a line from the opponent's eye to any probe point of c is clear+ * dist(c) = path length from the opponent's floor point to c (Euclidean when there is+ * no path); the floor point is OpponentFloor, or the eye minus EyeHeightCm+ * pool = the candidates out of sight, or all candidates when none is+ * pick = the largest dist in the pool; ties within 1 m broken by VerseRng(seed, deaths)+ *+ * Without an opponent (the first spawn of a match) every candidate ties and the seed picks.+ */+namespace VerseSpawnSelection+{+ inline constexpr float BlockRadiusCm = 300.f;+ inline constexpr float TieCm = 100.f;+ /** Eye height above the floor (combat-state.md 9.2) when no floor point is given. */+ inline constexpr float EyeHeightCm = 165.f;++ VERSECOMBAT_API FVerseSpawnChoice Choose(+ const TArray<FVerseSpawnCandidate>& Candidates,+ const TOptional<FVector>& OpponentEye,+ TFunctionRef<bool(const FVector& From, const FVector& To)> LineClear,+ TFunctionRef<float(const FVector& From, const FVector& To)> PathLength,+ uint64 MatchSeed,+ uint64 DeathCount,+ const TOptional<FVector>& OpponentFloor = TOptional<FVector>());+}diff --git a/unreal/Verse/Source/VerseDecks/Private/HangarSwitch/VerseHangarSwitchSubsystem.cpp b/unreal/Verse/Source/VerseDecks/Private/HangarSwitch/VerseHangarSwitchSubsystem.cppnew file mode 100644index 0000000000..fa85d066f0--- /dev/null+++ b/unreal/Verse/Source/VerseDecks/Private/HangarSwitch/VerseHangarSwitchSubsystem.cpp@@ -0,0 +1,223 @@+#include "HangarSwitch/VerseHangarSwitchSubsystem.h"++#include "Combat/VerseCombatTypes.h"+#include "Engine/World.h"+#include "Events/VerseEventHub.h"+#include "HAL/PlatformTime.h"+#include "VerseLog.h"+#include "WorldPartition/DataLayer/DataLayerAsset.h"+#include "WorldPartition/DataLayer/DataLayerInstance.h"+#include "WorldPartition/DataLayer/DataLayerManager.h"+#include "WorldPartition/WorldPartitionSubsystem.h"++const FName UVerseHangarSwitchSubsystem::HangarDeck(TEXT("hangar"));+const FName UVerseHangarSwitchSubsystem::QuickStartReason(TEXT("quick_start_duel"));++const TCHAR* FVerseHangarDataLayers::DayLayerPath = TEXT("/Game/Verse/Decks/Hangar/DataLayers/DL_Hangar_Day.DL_Hangar_Day");+const TCHAR* FVerseHangarDataLayers::ArenaLayerPath = TEXT("/Game/Verse/Decks/Hangar/DataLayers/DL_Hangar_Arena.DL_Hangar_Arena");++// ---------------------------------------------------------------------------+// Data layers+// ---------------------------------------------------------------------------++namespace+{+ struct FHangarLayerAssets+ {+ const UDataLayerAsset* Day = nullptr;+ const UDataLayerAsset* Arena = nullptr;+ bool IsValid() const { return Day && Arena; }+ };++ FHangarLayerAssets LoadLayerAssets()+ {+ FHangarLayerAssets Out;+ Out.Day = LoadObject<UDataLayerAsset>(nullptr, FVerseHangarDataLayers::DayLayerPath);+ Out.Arena = LoadObject<UDataLayerAsset>(nullptr, FVerseHangarDataLayers::ArenaLayerPath);+ return Out;+ }+}++bool FVerseHangarDataLayers::Request(bool bArena)+{+ UWorld* W = World.Get();+ UDataLayerManager* Manager = W ? UDataLayerManager::GetDataLayerManager(W) : nullptr;+ const FHangarLayerAssets Assets = LoadLayerAssets();+ if (!Manager || !Assets.IsValid())+ {+ return false;+ }+ // Unload the side that goes away first, so the two sets never stand in each other.+ const bool bA = Manager->SetDataLayerRuntimeState(bArena ? Assets.Day : Assets.Arena, EDataLayerRuntimeState::Unloaded);+ const bool bB = Manager->SetDataLayerRuntimeState(bArena ? Assets.Arena : Assets.Day, EDataLayerRuntimeState::Activated);+ return bA && bB;+}++bool FVerseHangarDataLayers::IsDone(bool bArena) const+{+ UWorld* W = World.Get();+ const UDataLayerManager* Manager = W ? UDataLayerManager::GetDataLayerManager(W) : nullptr;+ const FHangarLayerAssets Assets = LoadLayerAssets();+ if (!Manager || !Assets.IsValid())+ {+ return true;+ }+ const UDataLayerInstance* On = Manager->GetDataLayerInstanceFromAsset(bArena ? Assets.Arena : Assets.Day);+ const UDataLayerInstance* Off = Manager->GetDataLayerInstanceFromAsset(bArena ? Assets.Day : Assets.Arena);+ if (!On || !Off)+ {+ return true;+ }+ if (Manager->GetDataLayerInstanceEffectiveRuntimeState(On) != EDataLayerRuntimeState::Activated+ || Manager->GetDataLayerInstanceEffectiveRuntimeState(Off) != EDataLayerRuntimeState::Unloaded)+ {+ return false;+ }+ const UWorldPartitionSubsystem* Streaming = W->GetSubsystem<UWorldPartitionSubsystem>();+ return !Streaming || Streaming->IsStreamingCompleted();+}++// ---------------------------------------------------------------------------+// Subsystem+// ---------------------------------------------------------------------------++UVerseHangarSwitchSubsystem* UVerseHangarSwitchSubsystem::Get(const UObject* WorldContextObject)+{+ const UWorld* World = WorldContextObject ? WorldContextObject->GetWorld() : nullptr;+ return World ? World->GetSubsystem<UVerseHangarSwitchSubsystem>() : nullptr;+}++bool UVerseHangarSwitchSubsystem::ShouldCreateSubsystem(UObject* Outer) const+{+ const UWorld* World = Cast<UWorld>(Outer);+ return World && (World->WorldType == EWorldType::Game || World->WorldType == EWorldType::PIE);+}++void UVerseHangarSwitchSubsystem::Initialize(FSubsystemCollectionBase& Collection)+{+ Collection.InitializeDependency<UVerseEventHub>();+ Super::Initialize(Collection);+ if (!Layers)+ {+ Layers = MakeUnique<FVerseHangarDataLayers>(GetWorld());+ }+}++void UVerseHangarSwitchSubsystem::SetLayers(TUniquePtr<IVerseHangarLayers> InLayers)+{+ Layers = MoveTemp(InLayers);+}++FBox UVerseHangarSwitchSubsystem::ArenaBoundsCm()+{+ // docs/verse/unreal/arena.md: plan x 25..75 m, z 4..44 m, heights up to the fence.+ return FBox(FVector(2500.0, 400.0, -100.0), FVector(7500.0, 4400.0, 1000.0));+}++bool UVerseHangarSwitchSubsystem::HasAuthority() const+{+ const UWorld* World = GetWorld();+ return World && World->GetNetMode() != NM_Client;+}++double UVerseHangarSwitchSubsystem::NowSeconds() const+{+ return Clock ? Clock() : FPlatformTime::Seconds();+}++bool UVerseHangarSwitchSubsystem::HandleLifecycleShow(FName Reason)+{+ return Reason == QuickStartReason && RequestArena(true, Reason);+}++bool UVerseHangarSwitchSubsystem::RequestArena(bool bArena, FName Reason)+{+ if (!HasAuthority())+ {+ return false;+ }+ if (IsSwitching())+ {+ const bool bTarget = Mode == EVerseHangarMode::SwitchingToArena;+ if (bTarget == bArena)+ {+ Pending.Reset();+ return false;+ }+ Pending = bArena; // applied when the running switch is done+ return true;+ }+ if (IsArenaOn() == bArena)+ {+ return false;+ }+ Mode = bArena ? EVerseHangarMode::SwitchingToArena : EVerseHangarMode::SwitchingToDay;+ RequestedAt = NowSeconds();+ const bool bLayers = Layers && Layers->Request(bArena);+ if (!bLayers)+ {+ UE_LOG(LogVerseDecks, Warning, TEXT("Hangar switch: no hangar data layers in this world; switching without streaming"));+ Finish();+ return true;+ }+ UE_LOG(LogVerseDecks, Log, TEXT("Hangar switch: to %s (%s)"), bArena ? TEXT("arena") : TEXT("day"), *Reason.ToString());+ Step();+ return true;+}++void UVerseHangarSwitchSubsystem::Step()+{+ if (!IsSwitching())+ {+ return;+ }+ const bool bArena = Mode == EVerseHangarMode::SwitchingToArena;+ if (!Layers || Layers->IsDone(bArena))+ {+ Finish();+ return;+ }+ if (NowSeconds() - RequestedAt > SwitchTimeoutS)+ {+ UE_LOG(LogVerseDecks, Error, TEXT("Hangar switch: layers not done after %.1f s; finishing anyway"), SwitchTimeoutS);+ Finish();+ }+}++void UVerseHangarSwitchSubsystem::Finish()+{+ const bool bArena = Mode == EVerseHangarMode::SwitchingToArena;+ Mode = bArena ? EVerseHangarMode::Arena : EVerseHangarMode::Day;+ LastSwitchSeconds = float(NowSeconds() - RequestedAt);+ ++SwitchCount;+ if (LastSwitchSeconds > SwitchBudgetS)+ {+ UE_LOG(LogVerseDecks, Warning, TEXT("Hangar switch took %.2f s (budget %.1f s, A11.4)"), LastSwitchSeconds, SwitchBudgetS);+ }+ if (UVerseEventHub* Hub = UVerseEventHub::Get(this))+ {+ FVerseArenaSwitchEvent Event;+ Event.bArenaOn = bArena;+ Event.Deck = HangarDeck;+ const UWorld* World = GetWorld();+ Event.ServerTime = World ? World->GetTimeSeconds() : 0.f;+ Hub->OnArenaSwitch.Broadcast(Event);+ }+ if (Pending.IsSet())+ {+ const bool bNext = Pending.GetValue();+ Pending.Reset();+ RequestArena(bNext, NAME_None);+ }+}++void UVerseHangarSwitchSubsystem::Tick(float DeltaTime)+{+ Super::Tick(DeltaTime);+ Step();+}++TStatId UVerseHangarSwitchSubsystem::GetStatId() const+{+ RETURN_QUICK_DECLARE_CYCLE_STAT(UVerseHangarSwitchSubsystem, STATGROUP_Tickables);+}diff --git a/unreal/Verse/Source/VerseDecks/Private/Tests/HangarSwitch/VerseHangarSwitchTest.cpp b/unreal/Verse/Source/VerseDecks/Private/Tests/HangarSwitch/VerseHangarSwitchTest.cppnew file mode 100644index 0000000000..d167975512--- /dev/null+++ b/unreal/Verse/Source/VerseDecks/Private/Tests/HangarSwitch/VerseHangarSwitchTest.cpp@@ -0,0 +1,212 @@+#include "Misc/AutomationTest.h"++#if WITH_DEV_AUTOMATION_TESTS++#include "Combat/VerseCombatTypes.h"+#include "Engine/Engine.h"+#include "Engine/World.h"+#include "Events/VerseEventHub.h"+#include "HangarSwitch/VerseHangarSwitchSubsystem.h"++// Verse.Decks.HangarSwitch.*: the day/arena switch of work-packages.md WP11.8 (A11.4 timing on+// the switch side; the reset and crew halves are the listeners' tests). The data layers are a+// scripted fake so the state machine runs without LV_Hangar.++namespace VerseHangarSwitchTest+{+ /** Layers that finish `DoneAfterS` seconds after each request on the shared fake clock. */+ class FFakeHangarLayers : public IVerseHangarLayers+ {+ public:+ FFakeHangarLayers(const double* InClock, double InDoneAfterS, bool bInPresent = true)+ : Clock(InClock), DoneAfterS(InDoneAfterS), bPresent(bInPresent)+ {+ }++ virtual bool Request(bool bArena) override+ {+ ++Requests;+ Target = bArena;+ RequestedAt = *Clock;+ return bPresent;+ }++ virtual bool IsDone(bool bArena) const override+ {+ return bArena == Target && *Clock - RequestedAt >= DoneAfterS;+ }++ const double* Clock;+ double DoneAfterS;+ bool bPresent;+ bool Target = false;+ double RequestedAt = 0.0;+ int32 Requests = 0;+ };++ struct FSwitchWorld+ {+ UWorld* World = nullptr;+ UVerseHangarSwitchSubsystem* Switch = nullptr;+ FFakeHangarLayers* Layers = nullptr;+ double Clock = 0.0;+ TArray<FVerseArenaSwitchEvent> Events;++ explicit FSwitchWorld(double DoneAfterS, bool bLayersPresent = true)+ {+ World = UWorld::CreateWorld(EWorldType::Game, false);+ FWorldContext& Context = GEngine->CreateNewWorldContext(EWorldType::Game);+ Context.SetCurrentWorld(World);+ Switch = World->GetSubsystem<UVerseHangarSwitchSubsystem>();+ if (Switch)+ {+ TUniquePtr<FFakeHangarLayers> Fake = MakeUnique<FFakeHangarLayers>(&Clock, DoneAfterS, bLayersPresent);+ Layers = Fake.Get();+ Switch->SetLayers(MoveTemp(Fake));+ Switch->SetClock([this]() { return Clock; });+ }+ if (UVerseEventHub* Hub = UVerseEventHub::Get(World))+ {+ Hub->OnArenaSwitch.AddLambda([this](const FVerseArenaSwitchEvent& E) { Events.Add(E); });+ }+ }++ ~FSwitchWorld()+ {+ GEngine->DestroyWorldContext(World);+ World->DestroyWorld(false);+ }++ /** Advances the fake clock in 60 Hz frames until `Seconds` passed. */+ void Run(double Seconds)+ {+ const int32 Frames = FMath::CeilToInt(Seconds * 60.0);+ for (int32 i = 0; i < Frames; ++i)+ {+ Clock += 1.0 / 60.0;+ Switch->Step();+ }+ }+ };+}++using namespace VerseHangarSwitchTest;++IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseHangarSwitchToggleTest, "Verse.Decks.HangarSwitch.Toggle",+ EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::EngineFilter)++bool FVerseHangarSwitchToggleTest::RunTest(const FString& Parameters)+{+ FSwitchWorld W(0.0);+ if (!TestNotNull(TEXT("switch subsystem exists in a game world"), W.Switch))+ {+ return false;+ }+ TestTrue(TEXT("starts as the day deck"), W.Switch->GetMode() == EVerseHangarMode::Day);+ TestTrue(TEXT("arena on accepted"), W.Switch->RequestArena(true));+ TestTrue(TEXT("arena on"), W.Switch->IsArenaOn());+ TestEqual(TEXT("one event"), W.Events.Num(), 1);+ if (W.Events.Num() == 1)+ {+ TestTrue(TEXT("event says arena on"), W.Events[0].bArenaOn);+ TestTrue(TEXT("event names the hangar"), W.Events[0].Deck == FName(TEXT("hangar")));+ }+ TestFalse(TEXT("arena on again changes nothing"), W.Switch->RequestArena(true));+ TestEqual(TEXT("still one event"), W.Events.Num(), 1);+ TestTrue(TEXT("back to day accepted"), W.Switch->RequestArena(false));+ TestTrue(TEXT("day again"), W.Switch->GetMode() == EVerseHangarMode::Day);+ TestEqual(TEXT("two events"), W.Events.Num(), 2);+ TestTrue(TEXT("second event says arena off"), W.Events.Num() == 2 && !W.Events[1].bArenaOn);+ TestEqual(TEXT("layers asked twice"), W.Layers->Requests, 2);+ return true;+}++IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseHangarSwitchStreamingTest, "Verse.Decks.HangarSwitch.WaitsForStreaming",+ EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::EngineFilter)++// The event comes only once the layers are streamed, so the listeners never reset a half-loaded+// arena; a 1.2 s stream gives a switch time of 1.2 s, under the 2.0 s budget of A11.4.+bool FVerseHangarSwitchStreamingTest::RunTest(const FString& Parameters)+{+ FSwitchWorld W(1.2);+ if (!TestNotNull(TEXT("switch subsystem"), W.Switch))+ {+ return false;+ }+ W.Switch->RequestArena(true);+ TestTrue(TEXT("switching while streaming"), W.Switch->IsSwitching());+ W.Run(1.0);+ TestEqual(TEXT("no event before the layers are done"), W.Events.Num(), 0);+ W.Run(0.3);+ TestEqual(TEXT("event once done"), W.Events.Num(), 1);+ TestTrue(TEXT("arena on"), W.Switch->IsArenaOn());+ const float Took = W.Switch->GetLastSwitchSeconds();+ TestTrue(FString::Printf(TEXT("switch took %.3f s, within one frame of the stream"), Took), Took >= 1.2f && Took <= 1.2f + 1.f / 60.f + 1e-3f);+ TestTrue(TEXT("within the 2.0 s budget"), Took <= UVerseHangarSwitchSubsystem::SwitchBudgetS);++ W.Switch->RequestArena(false);+ W.Run(1.3);+ TestTrue(TEXT("day again"), W.Switch->GetMode() == EVerseHangarMode::Day);+ TestTrue(TEXT("back within budget"), W.Switch->GetLastSwitchSeconds() <= UVerseHangarSwitchSubsystem::SwitchBudgetS);++ // A request against a running switch is queued, not dropped.+ W.Switch->RequestArena(true);+ W.Run(0.5);+ TestTrue(TEXT("queued while switching"), W.Switch->RequestArena(false));+ W.Run(1.0);+ TestTrue(TEXT("arena reached first"), W.Events.Num() >= 3 && W.Events[2].bArenaOn);+ W.Run(1.5);+ TestTrue(TEXT("then day"), W.Switch->GetMode() == EVerseHangarMode::Day && W.Events.Num() == 4 && !W.Events[3].bArenaOn);++ // Stuck layers finish after the timeout instead of hanging the duel.+ AddExpectedMessage(TEXT("layers not done after"), EAutomationExpectedMessageFlags::Contains, 1);+ AddExpectedMessage(TEXT("Hangar switch took"), EAutomationExpectedMessageFlags::Contains, 1);+ FSwitchWorld Stuck(1e9);+ Stuck.Switch->RequestArena(true);+ Stuck.Run(UVerseHangarSwitchSubsystem::SwitchTimeoutS + 0.5);+ TestTrue(TEXT("stuck layers time out"), Stuck.Switch->IsArenaOn() && Stuck.Events.Num() == 1);+ return true;+}++IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseHangarSwitchQuickStartTest, "Verse.Decks.HangarSwitch.QuickStart",+ EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::EngineFilter)++// lifecycle.show {reason: "quick_start_duel"} goes straight to the arena (bridge-protocol.md 12,+// parity D-03); any other reason leaves the deck as it is.+bool FVerseHangarSwitchQuickStartTest::RunTest(const FString& Parameters)+{+ FSwitchWorld W(0.0);+ if (!TestNotNull(TEXT("switch subsystem"), W.Switch))+ {+ return false;+ }+ TestFalse(TEXT("verse_view keeps the day deck"), W.Switch->HandleLifecycleShow(TEXT("verse_view")));+ TestFalse(TEXT("station keeps the day deck"), W.Switch->HandleLifecycleShow(TEXT("station")));+ TestTrue(TEXT("still day"), W.Switch->GetMode() == EVerseHangarMode::Day);+ TestTrue(TEXT("quick start accepted"), W.Switch->HandleLifecycleShow(UVerseHangarSwitchSubsystem::QuickStartReason));+ TestTrue(TEXT("arena on"), W.Switch->IsArenaOn());+ TestFalse(TEXT("second quick start is a no-op"), W.Switch->HandleLifecycleShow(UVerseHangarSwitchSubsystem::QuickStartReason));+ TestEqual(TEXT("one event"), W.Events.Num(), 1);++ // A world without the hangar layers still switches (and says so in the log).+ FSwitchWorld Bare(0.0, false);+ TestTrue(TEXT("no layers: accepted"), Bare.Switch->RequestArena(true));+ TestTrue(TEXT("no layers: arena on at once"), Bare.Switch->IsArenaOn() && Bare.Events.Num() == 1);+ return true;+}++IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseHangarSwitchBoundsTest, "Verse.Decks.HangarSwitch.ArenaBounds",+ EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::EngineFilter)++bool FVerseHangarSwitchBoundsTest::RunTest(const FString& Parameters)+{+ const FBox Bounds = UVerseHangarSwitchSubsystem::ArenaBoundsCm();+ const FVector Size = Bounds.GetSize();+ TestTrue(TEXT("50 m wide"), FMath::IsNearlyEqual(Size.X, 5000.0));+ TestTrue(TEXT("40 m deep"), FMath::IsNearlyEqual(Size.Y, 4000.0));+ // Inside the 100 x 62 m hall (coordinates.md 3.1).+ TestTrue(TEXT("inside the hall"), Bounds.Min.X >= 0.0 && Bounds.Max.X <= 10000.0 && Bounds.Min.Y >= 0.0 && Bounds.Max.Y <= 6200.0);+ return true;+}++#endif // WITH_DEV_AUTOMATION_TESTSdiff --git a/unreal/Verse/Source/VerseDecks/Public/HangarSwitch/VerseHangarSwitchSubsystem.h b/unreal/Verse/Source/VerseDecks/Public/HangarSwitch/VerseHangarSwitchSubsystem.hnew file mode 100644index 0000000000..de3489312d--- /dev/null+++ b/unreal/Verse/Source/VerseDecks/Public/HangarSwitch/VerseHangarSwitchSubsystem.h@@ -0,0 +1,117 @@+#pragma once++#include "CoreMinimal.h"+#include "Subsystems/WorldSubsystem.h"++#include "VerseHangarSwitchSubsystem.generated.h"++/**+ * How the switch reaches the level: the data layers of LV_Hangar by default+ * (FVerseHangarDataLayers), a scripted fake in tests. Both layers move together.+ */+class VERSEDECKS_API IVerseHangarLayers+{+public:+ virtual ~IVerseHangarLayers() = default;+ /** Asks for arena (true) or day (false). Returns false when the layers are missing. */+ virtual bool Request(bool bArena) = 0;+ /** True once the requested side is loaded and activated and the other is unloaded. */+ virtual bool IsDone(bool bArena) const = 0;+};++/** The day/arena state of deck 4. */+UENUM()+enum class EVerseHangarMode : uint8+{+ Day,+ SwitchingToArena,+ Arena,+ SwitchingToDay+};++/**+ * The hangar day/arena switch (work-packages.md WP11.8, README Arena and Duel entry). Server+ * side: it flips the data layers DL_Hangar_Day and DL_Hangar_Arena, waits until streaming is+ * done, then raises FVerseArenaSwitchEvent on the hub. The listeners do the rest: the game+ * mode starts or ends the match, VerseDestruction runs its full reset and nav rebuild,+ * VerseCrew walks the crew out of the hall (VerseDecks never includes Crew or Destruction).+ *+ * Entries: the armoury duel panel and the in-Verse quick start call RequestArena; the bridge's+ * lifecycle.show {reason: "quick_start_duel"} goes through HandleLifecycleShow.+ */+UCLASS()+class VERSEDECKS_API UVerseHangarSwitchSubsystem : public UTickableWorldSubsystem+{+ GENERATED_BODY()++public:+ /** Deck id in FVerseArenaSwitchEvent::Deck. */+ static const FName HangarDeck;+ /** lifecycle.show reason that goes straight to the arena (bridge-protocol.md 12). */+ static const FName QuickStartReason;+ /** A switch is slower than this only on a broken level (A11.4: at most 2.0 s each way). */+ static constexpr float SwitchBudgetS = 2.0f;+ /** After this long the switch completes anyway and logs an error (layers stuck). */+ static constexpr float SwitchTimeoutS = 10.0f;++ static UVerseHangarSwitchSubsystem* Get(const UObject* WorldContextObject);++ /** Server: switches to the arena (true) or back to the day deck. False when nothing changes. */+ bool RequestArena(bool bArena, FName Reason = NAME_None);++ /** Server: the bridge's lifecycle.show reason; quick_start_duel turns the arena on. */+ bool HandleLifecycleShow(FName Reason);++ EVerseHangarMode GetMode() const { return Mode; }+ bool IsArenaOn() const { return Mode == EVerseHangarMode::Arena; }+ bool IsSwitching() const { return Mode == EVerseHangarMode::SwitchingToArena || Mode == EVerseHangarMode::SwitchingToDay; }+ /** Seconds the last finished switch took, request to event. */+ float GetLastSwitchSeconds() const { return LastSwitchSeconds; }+ /** Number of FVerseArenaSwitchEvent this subsystem raised. */+ int32 GetSwitchCount() const { return SwitchCount; }++ /** Replaces the data-layer access (tests). Takes ownership. */+ void SetLayers(TUniquePtr<IVerseHangarLayers> InLayers);+ /** Replaces the clock (tests); seconds. */+ void SetClock(TFunction<double()> InClock) { Clock = MoveTemp(InClock); }+ /** Runs the state machine once (Tick calls it; tests call it directly). */+ void Step();++ /** The walkable arena bounds in world cm (arena.md): crew, stations and tests use them. */+ static FBox ArenaBoundsCm();++ // UTickableWorldSubsystem+ virtual bool ShouldCreateSubsystem(UObject* Outer) const override;+ virtual void Initialize(FSubsystemCollectionBase& Collection) override;+ virtual void Tick(float DeltaTime) override;+ virtual TStatId GetStatId() const override;++private:+ bool HasAuthority() const;+ double NowSeconds() const;+ void Finish();++ TUniquePtr<IVerseHangarLayers> Layers;+ TFunction<double()> Clock;+ EVerseHangarMode Mode = EVerseHangarMode::Day;+ double RequestedAt = 0.0;+ float LastSwitchSeconds = 0.f;+ int32 SwitchCount = 0;+ /** A request that came in while a switch was running; applied when it finishes. */+ TOptional<bool> Pending;+};++/** IVerseHangarLayers over the LV_Hangar data layers (UDataLayerManager). */+class VERSEDECKS_API FVerseHangarDataLayers : public IVerseHangarLayers+{+public:+ static const TCHAR* DayLayerPath;+ static const TCHAR* ArenaLayerPath;++ explicit FVerseHangarDataLayers(UWorld* InWorld) : World(InWorld) {}+ virtual bool Request(bool bArena) override;+ virtual bool IsDone(bool bArena) const override;++private:+ TWeakObjectPtr<UWorld> World;+};