File size: 13,064 Bytes
dc5a369
5320df1
dc5a369
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// Case = Arena + Body + Boss stepped at 60 Hz, and the Gym-style env of proposal 4.4 on top of it.
// No DOM here: the same file runs in the browser and in Node.
// Game-agnostic: a game registers BB.CASES[id] = {title, Body, Boss} and provides BB.ARENA {W, H}.
// Body contract: id, keys {action: 'K1|K2'}, manual [..], NAIL (damage per hit), reset, update(c, input), box,
//   hurtBox, centre, slashBox() -> {pts, tink, dir} | null, slashHits {}, slashFacing, onSlashContact(c, kind),
//   hurt(c, dmg, fromX) -> bool, hp, max_hp, state().
// Boss contract: spec (BB.SPECS), reset, update(c), st, x, hp, max_hp, dmg, bodyBox | hitTargets, tinkBox (opt.),
//   onNailHit(c, dmg, dir, facing, partId) -> contact kind, hazards() -> [{kind, box | seg + r | circle, dmg?}], state().
(function (g) {
  var BB = g.BB;
  var KEYS = ['W', 'A', 'S', 'D', 'SPACE', 'SHIFT', 'J', 'K', 'L', 'Q', 'E', 'R', 'LMB', 'RMB'];
  var CANON = { SPACE: 'Space', SHIFT: 'Shift' };

  // ---------------- Case ----------------
  function Case(id) {
    var def = BB.CASES[id];
    if (!def) throw new Error('unknown case ' + id);
    this.id = id; this.def = def;
    this.arena = def.bounds || BB.ARENA;
    this.body = new def.Body(); this.boss = new def.Boss();
  }
  Case.prototype.reset = function (seed, d, options) {
    this.seed = seed >>> 0; this.d = Math.min(1, Math.max(0, +d));
    this.rng = new BB.RNG(this.seed); this.t = 0; this.events = []; this.trauma = 0;
    this.options = options || {};
    this.body.reset(this); this.boss.reset(this);
    this.result = null;
  };
  Case.prototype.emit = function (name, x, y) {      // x, y: optional world position for presentation cues
    var e = { t: this.t, name: name }; if (x != null) { e.x = x; e.y = y; } this.events.push(e);
  };
  Case.prototype.shake = function (a) { this.events.push({ t: this.t, name: 'shake', a: a }); };   // render-only cue
  // keys: a Set-like object {Space:true, D:true, ...} held during this tick
  Case.prototype.input = function (keys) {
    var m = this.body.keys, out = {};
    Object.keys(m).forEach(function (act) {
      out[act] = m[act].split('|').some(function (k) { return !!keys[k]; });
    });
    return out;
  };
  Case.prototype.tick = function (keys, mouse) {
    if (this.result) return;
    if (mouse && typeof this.body.mouse === 'function') this.body.mouse(this, mouse);
    this.body.update(this, this.input(keys || {}));
    this.boss.update(this);
    this.interact();
    this.t++;
    this.result = this.outcome();
  };
  Case.prototype.interact = function () {
    if (typeof this.body.resolveInteractions === 'function') return this.body.resolveInteractions(this);
    var body = this.body, boss = this.boss, sb = body.slashBox();
    if (sb && boss.st !== 'dead') {
      // a boss may expose several hittable parts (hitTargets: [{id, box}]); default = one body box
      var tg = boss.hitTargets ? boss.hitTargets() : [{ id: 'boss', box: boss.bodyBox() }];
      var tb = boss.tinkBox ? boss.tinkBox() : null, landed = false;
      for (var t = 0; t < tg.length; t++) {
        var tid = tg[t].id;
        if (!tg[t].box || body.slashHits[tid] || !BB.polyBox(sb.pts, tg[t].box)) continue;
        body.slashHits[tid] = true; landed = true;
        var kind = boss.onNailHit(this, body.NAIL, sb.dir, body.slashFacing, tid);
        if (kind) body.onSlashContact(this, kind);
        if (!body.multiTargetSlash) break;
      }
      if (!landed && !body.slashHits.needle && tb && BB.polyBox(sb.tink, tb)) {
        body.slashHits.needle = true; this.emit('tink');
        body.onSlashContact(this, 'tink');
      }
    }
    if (body.hp <= 0 || boss.st === 'dead') return;
    var hb = body.hurtBox(), hz = boss.hazards();
    for (var i = 0; i < hz.length; i++) {
      var h = hz[i], hit = false;
      if (h.box) hit = BB.overlap(h.box, hb);
      else if (h.seg) hit = BB.segBox(h.seg[0], h.seg[1], h.seg[2], h.seg[3], h.r, hb);
      else if (h.circle) hit = BB.circleBox(h.circle[0], h.circle[1], h.circle[2], hb);
      if (hit && body.hurt(this, h.dmg || boss.dmg, h.fromX != null ? h.fromX : boss.x, h)) { this.events.push({ t: this.t, name: 'hurt_by', by: h.kind }); this.shake(0.6); break; }
    }
  };
  Case.prototype.outcome = function () {
    // A game can express its own victory conditions (e.g. a timed duel) without falsifying HP.
    if (typeof this.def.outcome === 'function') {
      var custom = this.def.outcome(this);
      // undefined delegates to the default; null keeps this game running, subject to the shared cap.
      if (custom !== undefined) return custom == null && this.t >= BB.MAX_SECONDS * BB.FPS ? 'timeout' : custom;
    }
    if (this.boss.hp <= 0) return 'win';
    if (this.body.hp <= 0) return 'loss';
    if (this.boss.despawned) return 'timeout';
    if (this.t >= BB.MAX_SECONDS * BB.FPS) return 'timeout';
    return null;
  };
  Case.prototype.state = function () {
    return { t: BB.r4(this.t / BB.FPS), d: this.d, arena: { w: BB.r4(this.arena.W), h: this.arena.H },
             body: this.body.state(), boss: this.boss.state() };
  };
  Case.prototype.verifier = function () {           // = prototype/bossbench/core.py verifier
    var boss = this.boss, frac = 1 - boss.hp / boss.max_hp, win = this.result === 'win';
    return { reward: win ? 1 : BB.r4(-1 + frac), win: win, outcome: this.result, boss_damage: BB.r4(frac),
             seconds: BB.r4(this.t / BB.FPS), d: this.d, player_hp: this.body.hp };
  };
  // proposal 4.4: control manual + boss skill table, as optional prompt context
  Case.prototype.manual = function () {
    var spec = this.boss.spec;
    return {
      controls: this.body.manual.slice(),
      skills: spec.moves.map(function (m) { return { move: m.name, cue: m.cue, punish: m.punish || null, damage: m.damage }; })
    };
  };
  BB.Case = Case;

  // ---------------- packets ----------------
  // "<|action_start|> dx dy dz ; K1 ; ... ; K6 <|action_end|>",  K = 0-4 keys joined by ','
  BB.parsePacket = function (text) {
    var m = /^\s*<\|action_start\|>([\s\S]*)<\|action_end\|>\s*$/.exec(String(text == null ? '' : text));
    if (!m) return null;
    var parts = m[1].split(';');
    if (parts.length !== 1 + BB.SUBSTEPS) return null;
    var mouse = parts[0].trim().split(/\s+/);
    if (mouse.length !== 3 || !mouse.every(function (v) { return /^-?\d+$/.test(v); })) return null;
    var dx = +mouse[0], dy = +mouse[1], dz = +mouse[2];
    if (Math.abs(dx) > 1000 || Math.abs(dy) > 1000 || Math.abs(dz) > 5) return null;
    var subs = [];
    for (var i = 1; i < parts.length; i++) {
      var s = parts[i].trim(), held = {};
      if (s) {
        var ks = s.split(',');
        if (ks.length > 4) return null;
        for (var j = 0; j < ks.length; j++) {
          var k = ks[j].trim().toUpperCase();
          if (KEYS.indexOf(k) < 0 || held[CANON[k] || k]) return null;
          held[CANON[k] || k] = true;
        }
      }
      subs.push(held);
    }
    return { mouse: [dx, dy, dz], subs: subs };
  };
  BB.formatPacket = function (subs, mouse) {
    mouse = mouse || [0, 0, 0];
    return '<|action_start|> ' + mouse.join(' ') + ' ; ' +
      subs.map(function (h) { return Object.keys(h).filter(function (k) { return h[k]; }).join(','); }).join(' ; ') +
      ' <|action_end|>';
  };
  BB.NOOP = BB.formatPacket([{}, {}, {}, {}, {}, {}]);
  // Standard scripted-controller hook for every BB.Case game: BB.GAME.scripted(case) returns a text packet,
  // {subs|holds: 6 key sets, mouse: [dx, dy, dz]}, or 6 key sets. It may read privileged state but must
  // not change the simulation; the result is normalized and validated like any policy packet.
  BB.scriptedPacket = function (c) {
    if (!BB.GAME || typeof BB.GAME.scripted !== 'function') throw new Error('this game has no BB.GAME.scripted controller');
    var before = BB.hashState(c), out = BB.GAME.scripted(c);
    if (BB.hashState(c) !== before) throw new Error('scripted controller changed the simulation state');
    var text = out;
    if (typeof out !== 'string') {
      var subs = Array.isArray(out) ? out : (out.subs || out.holds), mouse = (!Array.isArray(out) && out.mouse) || [0, 0, 0];
      if (!Array.isArray(subs) || subs.length !== BB.SUBSTEPS) throw new Error('scripted controller must return 6 key sets');
      text = BB.formatPacket(subs.map(function (h) {
        if (Array.isArray(h)) { var o = {}; h.forEach(function (k) { o[k] = true; }); return o; }
        return h || {};
      }), mouse.map(function (v) { return Math.round(v); }));
    }
    if (!BB.parsePacket(text)) throw new Error('scripted controller returned an illegal packet: ' + text);
    return text;
  };
  BB.PACKET_SECONDS = BB.SUBSTEPS * BB.TICKS_PER_SUB / BB.FPS;   // 0.2

  // ---------------- Env (Gymnasium semantics) ----------------
  // opts: obs_mode 'rgb'|'symbolic', time_mode 'paused'|'virtual_rt'|'wallclock_rt', latency (s, virtual_rt),
  //       renderer: function(case) -> frame (browser); now: clock in ms (wallclock_rt)
  function Env(id, opts) {
    opts = opts || {};
    this.id = id; this.case = new Case(id);
    this.obs_mode = opts.obs_mode || 'rgb';
    this.time_mode = opts.time_mode || 'paused';
    if (['paused', 'virtual_rt', 'wallclock_rt'].indexOf(this.time_mode) < 0) throw new Error('bad time_mode');
    this.latency = +opts.latency || 0;
    this.renderer = opts.renderer || null;
    this.now = opts.now || function () { return Date.now(); };
    this.with_text = !!opts.with_text;
  }
  Env.prototype.reset = function (seed, options) {
    options = options || {};
    var d = options.difficulty != null ? options.difficulty : 0.5;
    if (options.latency != null) this.latency = +options.latency;
    this.case.reset(seed || 0, d, options);
    this.steps = 0; this.format_errors = 0; this.trace = []; this.lastReturn = this.now();
    var info = this.info(true, 0, []);
    info.manual = this.case.manual();
    return { obs: this.observe(), info: info };
  };
  Env.prototype.observe = function () {
    if (this.obs_mode === 'symbolic') return this.case.state();
    return this.renderer ? this.renderer(this.case) : null;
  };
  Env.prototype.info = function (ok, frames, events) {
    var c = this.case;
    return { outcome: c.result, player_hp: c.body.hp, boss_hp: c.boss.hp, boss_max_hp: c.boss.max_hp,
             format_ok: ok, frames: frames, t: BB.r4(c.t / BB.FPS), events: events, steps: this.steps,
             format_errors: this.format_errors };
  };
  Env.prototype.runPacket = function (p) {          // 6 sub-steps x 2 ticks, keys held per sub-step
    var c = this.case, n = 0;
    for (var s = 0; s < BB.SUBSTEPS; s++) for (var k = 0; k < BB.TICKS_PER_SUB; k++) {
      if (c.result) return n;
      c.tick(p ? p.subs[s] : null, p ? p.mouse.map(function (v) { return v / (BB.SUBSTEPS * BB.TICKS_PER_SUB); }) : null); n++;
    }
    return n;
  };
  // latency (optional, virtual_rt): this step's think time in seconds, overrides env.latency
  Env.prototype.step = function (action, latency) {
    var c = this.case, ev0 = c.events.length, frames = 0, lag = 0;
    if (c.result) throw new Error('episode is over; call reset()');
    if (this.time_mode === 'virtual_rt') lag = Math.ceil((latency != null ? latency : this.latency) / BB.PACKET_SECONDS - 1e-9);
    else if (this.time_mode === 'wallclock_rt') lag = Math.floor((this.now() - this.lastReturn) / 1000 / BB.PACKET_SECONDS);
    for (var i = 0; i < lag && !c.result; i++) frames += this.runPacket(null);   // the world did not wait
    var p = BB.parsePacket(action), ok = !!p;
    if (!ok) this.format_errors++;
    this.trace.push(ok ? action : BB.NOOP);
    frames += this.runPacket(p);
    this.steps++;
    var term = c.result === 'win' || c.result === 'loss', trunc = c.result === 'timeout';
    var reward = 0;
    if (term || trunc) reward = c.verifier().reward;
    var info = this.info(ok, frames, c.events.slice(ev0).filter(function (e) { return e.name !== 'shake'; }).map(function (e) { return e.name; }));
    info.noop_packets = lag;
    if (term || trunc) info.verifier = c.verifier();
    var obs = this.observe();
    this.lastReturn = this.now();
    return { obs: obs, reward: reward, terminated: term, truncated: trunc, info: info };
  };
  Env.prototype.verifier = function () { return this.case.verifier(); };
  BB.Env = Env;

  // FNV-1a over the symbolic state, for determinism checks
  BB.hashState = function (c) {
    var s = JSON.stringify(c.state()), h = 0x811c9dc5;
    for (var i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 0x01000193); }
    return (h >>> 0).toString(16);
  };

  // ---------------- registry ----------------
  BB.CASES = BB.CASES || {};
  BB.make = function (id, opts) { return new Env(id, opts); };
})(typeof window !== 'undefined' ? window : globalThis);