File size: 12,350 Bytes
a54e6a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
"""Real-time combat loop: brains pick agent-designed moves from the live state, actors evaluate one frame at a time,
hits trigger reactions, bodies push apart, a causal follow camera frames the fight, and every frame renders straight
to condition frames (the model input) and readable frames.

Brain spec (JSON-able, written by the agent per character):
  {"moves": {name: {"range": [min_cm, max_cm], "angle": deg, "cooldown": frames, "weight": w}},
   "locomotion": {"speed": cm/frame, "turn": rad/frame, "keep": [min_cm, max_cm], "circle": cm/frame},
   "aggression": chance per idle frame to attack when a move is eligible, "min_idle": frames between moves,
   "reaction": move played when hit,
   player bot only: "dodge": {"default": move, "<joint prefix>": move}, "dodge_chance", "reaction_frames", "punish"}
Distances are between body centres.
"""
import json, time
from pathlib import Path
import numpy as np
from .effector import MoveRun, flat, axes, mirror, wrap, TORSO
from .geometry import Camera, UP
from .render import Renderer, VideoWriter, ReadableWriter, readable_rgb8


def relation(actor, other):
    d = flat(other.center() - actor.center())
    return wrap(np.arctan2(d[1], d[0]) - actor.yaw), float(np.linalg.norm(d))


def _seg_dist(p, a, b):
    ab = b - a; s = np.clip(((p - a) * ab).sum(-1) / np.maximum((ab * ab).sum(-1), 1e-9), 0, 1)
    return np.linalg.norm(a + ab * s[..., None] - p, axis=-1)


def body_radius(sk):
    return 0.13 * sk.height if sk.family == "humanoid" else 0.24 * sk.meta.get("shoulder_height", sk.height)


class Brain:
    """Utility brain: when idle, maybe start an eligible move (range, facing, cooldown) chosen by weight; otherwise turn
    toward the opponent and manage distance (approach / back off / circle)."""

    def __init__(self, spec, moves, rng):
        self.spec, self.moves, self.rng = spec, moves, rng
        self.cool = {m: 0 for m in spec["moves"]}; self.idle = 0

    def eligible(self, actor, other, t):
        ang, dist = relation(actor, other)
        return [(n, c.get("weight", 1.0)) for n, c in self.spec["moves"].items()
                if t >= self.cool[n] and c["range"][0] <= dist <= c["range"][1] and abs(np.degrees(ang)) <= c.get("angle", 45)]

    def start(self, actor, other, t, world, name, spec=None, label=None):
        actor.start(spec or self.moves[name], other, t)
        if name in self.cool:
            self.cool[name] = t + self.spec["moves"][name].get("cooldown", 60)
        self.idle = 0
        world.log.append((t, actor.name, label or name))

    def attack(self, actor, other, t, world, force=False):
        if self.idle < self.spec.get("min_idle", 12):
            return False
        choices = self.eligible(actor, other, t)
        if choices and (force or self.rng.random() < self.spec.get("aggression", 0.2)):
            names, w = zip(*choices)
            self.start(actor, other, t, world, str(self.rng.choice(names, p=np.array(w) / sum(w))))
            return True
        return False

    def locomote(self, actor, other, t):
        loco = self.spec.get("locomotion", {})
        ang, dist = relation(actor, other)
        actor.yaw += float(np.clip(ang, -loco.get("turn", 0.08), loco.get("turn", 0.08)))
        f, r = axes(actor.yaw)
        lo, hi = loco.get("keep", [250, 450]); speed = loco.get("speed", 6.0)
        if dist > hi:
            step = f * min(speed, dist - hi)
        elif dist < lo:
            step = -f * min(speed * 0.7, lo - dist)
        else:
            step = r * loco.get("circle", 3.0) * (1 if (t // 100) % 2 == 0 else -1)
        actor.root += step

    def act(self, actor, other, t, world):
        if actor.move is not None:
            return
        self.idle += 1
        if not self.attack(actor, other, t, world):
            self.locomote(actor, other, t)


class PlayerBot(Brain):
    """Stand-in for a human: reacts to the opponent's wind-up with a dodge (or a jump for low sweeps) and punishes
    recovery frames. Replace act() with controller input for live play."""

    def __init__(self, spec, moves, rng):
        super().__init__(spec, moves, rng); self.read = None

    def act(self, actor, other, t, world):
        if actor.move is not None:
            return
        self.idle += 1
        om = other.move
        if om is not None and om.phase(t) == "windup" and self.read is not om and t - om.t0 >= self.spec.get("reaction_frames", 6):
            self.read = om
            if self.rng.random() < self.spec.get("dodge_chance", 0.7):
                parts = om.spec["hit"]["parts"]; dodge = self.spec["dodge"]
                name = next((m for pre, m in dodge.items() if pre != "default" and any(p.startswith(pre) for p in parts)), dodge["default"])
                ang, _ = relation(other, actor)                         # dodge away from the side the attacker leans to
                side = mirror(self.moves[name]) if (ang > 0) == (self.rng.random() < 0.8) else self.moves[name]
                self.start(actor, other, t, world, name, spec=side, label=name)
                return
        if self.spec.get("punish") and om is not None and om.phase(t) == "recovery":
            if self.attack(actor, other, t, world, force=True):
                return
        if not self.attack(actor, other, t, world):
            self.locomote(actor, other, t)


class World:
    def __init__(self, env, actors, brains, reactions, fps=30):
        self.env, self.actors, self.brains, self.reactions, self.fps = env, actors, brains, reactions, fps
        self.log, self.hits = [], []
        self.cam_pos = self.cam_tgt = None
        self.arena = env.get("platform", {}).get("radius_cm", 1e9)

    def other(self, a):
        return next(x for x in self.actors if x is not a)

    def camera(self, player, subject, dist=620.0, height=280.0, shoulder=230.0, look=0.55, look_z=110.0, alpha=0.18, fov=60.0):
        p, s = flat(player.center()), flat(subject.center())
        d = s - p; n = np.linalg.norm(d); d = d / n if n > 1 else axes(player.yaw)[0]
        right = np.array([-d[1], d[0], 0.0])
        pos = p - d * dist + right * shoulder + UP * height
        tgt = p * (1 - look) + s * look + UP * look_z
        if self.cam_pos is None:
            self.cam_pos, self.cam_tgt = pos, tgt
        self.cam_pos = self.cam_pos + alpha * (pos - self.cam_pos); self.cam_tgt = self.cam_tgt + alpha * (tgt - self.cam_tgt)
        return Camera.look_at(self.cam_pos, self.cam_tgt, fov)

    def _torso_points(self, a):
        idx = [a.sk.index[j] for j in TORSO + ("neck_01",) if j in a.sk.index]
        return np.concatenate([np.linspace(a.pose[i], a.pose[j], 5) for i, j in zip(idx[:-1], idx[1:])])

    @staticmethod
    def _bone_points(a, n=4):
        P = a.pose; pi = a.sk.parent_idx[1:]
        s = np.linspace(0, 1, n)[None, :, None]
        return (P[pi][:, None] * (1 - s) + P[1:][:, None] * s).reshape(-1, 3)

    def _separate(self):
        a, b = self.actors
        pa, pb = self._torso_points(a), self._torso_points(b)
        D = np.linalg.norm(flat(pa[:, None] - pb[None, :].copy()) if False else (pa[:, None, :2] - pb[None, :, :2]), axis=-1)
        i, j = np.unravel_index(np.argmin(D), D.shape)
        need = body_radius(a.sk) + body_radius(b.sk)
        if D[i, j] < need:
            light, heavy = (a, b) if a.sk.height <= b.sk.height else (b, a)
            pl, ph = (pa[i], pb[j]) if light is a else (pb[j], pa[i])
            v = flat(pl - ph); n = np.linalg.norm(v)
            v = v / n if n > 1e-3 else -axes(light.yaw)[0]
            light.shift(v * (need - D[i, j]))
        # limbs / neck / head of either body: keep bones ~limb thickness apart (the lighter body gives way)
        light, heavy = (a, b) if a.sk.height <= b.sk.height else (b, a)
        pl, ph = self._bone_points(light), self._bone_points(heavy)
        D = np.linalg.norm(pl[:, None] - ph[None], axis=-1)
        i, j = np.unravel_index(np.argmin(D), D.shape)
        limb_gap = 14.0
        if D[i, j] < limb_gap:
            v = flat(pl[i] - ph[j]); n = np.linalg.norm(v)
            if n < 1e-3:
                v = flat(light.center() - heavy.center()); n = max(np.linalg.norm(v), 1e-3)
            light.shift(v / n * (limb_gap - D[i, j]))
        for x in self.actors:
            c = flat(x.center()); n = np.linalg.norm(c); lim = self.arena - 120
            if n > lim:
                x.shift(-c / n * (n - lim))

    def step(self, t):
        for a in self.actors:
            self.brains[a.name].act(a, self.other(a), t, self)
        for a in self.actors:
            a.evaluate(t)
        self._separate()
        for a in self.actors:
            mv = a.move
            if mv is None or mv.hit_done or "hit" not in mv.spec or not mv.in_window(t, mv.spec["hit"]["window"]):
                continue
            victim = self.other(a)
            if victim.invulnerable:
                continue
            h = mv.spec["hit"]; sk = victim.sk
            sa, sb = victim.pose[sk.parent_idx[1:]], victim.pose[1:]
            if h["parts"] == ["weapon"]:
                if a.weapon is None:
                    continue
                pts = np.linspace(a.weapon[0], a.weapon[1], 10)
            else:
                pts = np.stack([a.pose[a.sk.index[j]] for j in h["parts"]])
            dmin = min(float(_seg_dist(p, sa, sb).min()) for p in pts)
            if dmin < h["radius"]:
                mv.hit_done = True; victim.hp -= h.get("damage", 1)
                self.hits.append((t, a.name, victim.name, mv.spec["name"]))
                react = self.reactions.get(victim.name)
                if victim.move is not None and victim.move.spec.get("armor"):
                    react = None                                     # hyper armor: damage without flinching
                if react is not None:
                    victim.start(react, a, t + 1)
                    self.log.append((t + 1, victim.name, react["name"]))

    def run(self, frames, out=None, player="player", device=None, render=True, width=1280, height=720):
        pa = next(a for a in self.actors if a.name == player); sa = self.other(pa)
        rnd = Renderer(self.env, width, height, device) if render else None
        writers = None
        if out is not None:
            out = Path(out); out.mkdir(parents=True, exist_ok=True)
            if render:
                writers = (ReadableWriter(out / "readable.mp4", width, height), VideoWriter(out / "cond.mp4", width, height, scale_to=(1024, 576)))
        sim_ms, ren_ms = [], []
        track = {a.name: {"pose": [], "weapon": []} for a in self.actors}
        try:
            for t in range(frames):
                t0 = time.perf_counter()
                self.step(t); cam = self.camera(pa, sa)
                caps = [c for a in self.actors for c in a.capsules()]
                t1 = time.perf_counter()
                sim_ms.append((t1 - t0) * 1000)
                if rnd is not None:
                    rgb, _ = rnd.render(cam, caps)
                    ren_ms.append((time.perf_counter() - t1) * 1000)
                    if writers:
                        writers[0].write(readable_rgb8(rgb)); writers[1].write(rgb)
                for a in self.actors:
                    track[a.name]["pose"].append(a.pose.copy())
                    track[a.name]["weapon"].append(a.weapon.copy() if a.weapon is not None else np.zeros((2, 3)))
        finally:
            if writers:
                writers[0].close(); writers[1].close()
            if rnd is not None:
                rnd.close()
        track = {n: {k: np.stack(v) for k, v in d.items()} for n, d in track.items()}
        stats = {"frames": frames, "sim_ms_mean": float(np.mean(sim_ms)), "sim_ms_p95": float(np.percentile(sim_ms, 95)),
                 "render_ms_mean": float(np.mean(ren_ms)) if ren_ms else None,
                 "render_ms_p95": float(np.percentile(ren_ms, 95)) if ren_ms else None,
                 "moves": self.log, "hits": self.hits, "hp": {a.name: a.hp for a in self.actors},
                 "floor_clamps": {a.name: a.floor_clamps for a in self.actors}}
        if out is not None:
            json.dump(stats, open(out / "runtime.json", "w"), indent=1, default=str)
            np.savez_compressed(out / "track.npz", **{f"{n}_{k}": v for n, d in track.items() for k, v in d.items()})
        return stats, track