File size: 7,477 Bytes
c04dd6a | 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 | // Optional game-independent recording/replay panel. Simulation uses the same Case tick path as live play.
(function(g){
var BB=g.BB;if(!BB)return;
var schema='bossbench/recording@1';
function canonical(v){
if(Array.isArray(v))return v.map(canonical);
if(v&&typeof v==='object'){var o={};Object.keys(v).sort().forEach(function(k){o[k]=canonical(v[k]);});return o;}return v;
}
function same(a,b){return JSON.stringify(canonical(a))===JSON.stringify(canonical(b));}
function validate(run){
if(!run||typeof run!=='object'||!Object.prototype.hasOwnProperty.call(BB.CASES,run.case))throw Error('Select a replay from this game.');
if(run.game&&run.game!==BB.GAME.id)throw Error('This replay belongs to another game.');
if(run.schema&&run.schema!==schema)throw Error('Unsupported replay format.');
if(run.rules&&BB.GAME.rules&&run.rules!==BB.GAME.rules)throw Error('Replay rule version differs; use the matching game version.');
if(!Number.isInteger(run.seed)||run.seed<0||run.seed>4294967295||!Number.isFinite(run.d)||run.d<0||run.d>1)throw Error('Invalid replay seed or difficulty.');
if(!Array.isArray(run.packets)||!run.packets.length||run.packets.length>Math.ceil(BB.MAX_SECONDS/BB.PACKET_SECONDS)+1)throw Error('Invalid number of replay actions.');
if(run.options!=null&&(typeof run.options!=='object'||Array.isArray(run.options)))throw Error('Invalid replay start options.');
var packets=run.packets.map(BB.parsePacket);if(packets.some(function(p){return !p;}))throw Error('Replay contains invalid keyboard or mouse actions.');return packets;
}
function reset(run){var e=BB.make(run.case,{obs_mode:'symbolic'});e.reset(run.seed,Object.assign({},run.options||{},{difficulty:run.d}));return e;}
function replay(run){validate(run);var e=reset(run);run.packets.forEach(function(p){if(e.case.result)throw Error('Replay contains actions after the match ended.');e.step(p);});return e;}
function matches(run,c){return (!run.verifier||same(run.verifier,c.verifier()))&&(!run.final_hash||run.final_hash===BB.hashState(c));}
BB.Recordings={schema:schema,validate:validate,replay:replay,matches:matches,same:same};
if(!g.document||!g.BossBench)return;
var doc=g.document,api=g.BossBench,$=function(id){return doc.getElementById(id);};
if(!$('replay-status'))return;
var status=$('replay-status'),active=null,notice=null,last=performance.now(),acc=0;
// The basic six controls are supplied by each game's page; transport controls are shared.
var parent=$('replay-back')&&$('replay-back').parentNode;
if(parent){
[['replay-step','Step'],['replay-restart','Restart replay']].forEach(function(pair){if($(pair[0]))return;var b=doc.createElement('button');b.id=pair[0];b.className='b';b.textContent=pair[1];parent.appendChild(b);});
if(!$('replay-speed')){var label=doc.createElement('label');label.textContent='Speed ';var speed=doc.createElement('select');speed.id='replay-speed';speed.setAttribute('aria-label','Replay speed');[.5,1,2,4].forEach(function(n){var op=doc.createElement('option');op.value=n;op.textContent=n+'×';op.selected=n===1;speed.appendChild(op);});label.appendChild(speed);parent.appendChild(label);}
if(!$('replay-progress')){var progress=doc.createElement('input');progress.id='replay-progress';progress.type='range';progress.min=0;progress.max=0;progress.value=0;progress.setAttribute('aria-label','Replay progress');parent.appendChild(progress);}
}
function update(){
if($('save-run'))$('save-run').disabled=!api.lastRun;
if(notice){status.textContent=notice;return;}
if(!active)return;
var c=active.env.case,total=active.run.packets.length,ended=!!c.result||active.frame>=total*12;
if(ended)active.playing=false;
if($('replay-toggle'))$('replay-toggle').textContent=active.playing?'Pause Replay':'ResumeReplay';
if($('replay-progress')){$('replay-progress').max=total;$('replay-progress').value=Math.floor(active.frame/12);}
var words={win:'Victory',loss:'Failure',timeout:'Timeout'};
status.textContent='Replay '+BB.CASES[active.run.case].title+' · '+(c.t/BB.FPS).toFixed(1)+' seconds · '+Math.ceil(active.frame/12)+' / '+total+' packets'+
(ended?' · '+(words[c.result]||'Replay ended')+(active.run.verifier?(matches(active.run,c)?' · result matches replay':' · result differs from replay; check the rule version'):''):'');
}
function load(run,playing){
var parsed=validate(run),checked=replay(run);
if(!matches(run,checked.case))throw Error('Replay result differs from current rules; use the matching version.');
active={run:run,parsed:parsed,env:reset(run),frame:0,playing:playing!==false};notice=null;acc=0;api.watch(active.env,'ReplayReplay');update();
}
function tick(){
var c=active.env.case;if(c.result||active.frame>=active.parsed.length*12){active.playing=false;return;}
var p=active.parsed[Math.floor(active.frame/12)],sub=Math.floor(active.frame%12/2);c.tick(p.subs[sub],p.mouse.map(function(v){return v/12;}));active.frame++;
}
function showError(e){notice=e.message||String(e);if(active)active.playing=false;update();}
if($('save-run'))$('save-run').addEventListener('click',function(){
if(!api.lastRun){status.textContent='Complete a match to download its replay.';return;}
var run=Object.assign({schema:schema,game:BB.GAME.id,rules:BB.GAME.rules},api.lastRun);
var url=URL.createObjectURL(new Blob([JSON.stringify(run,null,2)],{type:'application/json'})),a=doc.createElement('a');a.href=url;a.download=run.case.replace('/','-')+'-seed'+run.seed+'.json';a.click();setTimeout(function(){URL.revokeObjectURL(url);},1000);
});
if($('load-run'))$('load-run').addEventListener('change',async function(){try{var f=this.files[0];if(f){if(f.size>8*1024*1024)throw Error('Replay file exceeds 8 MB.');load(JSON.parse(await f.text()),true);}}catch(e){showError(e);}this.value='';});
if($('replay-toggle'))$('replay-toggle').addEventListener('click',function(){if(active){notice=null;active.playing=!active.playing;acc=0;update();}});
if($('replay-step'))$('replay-step').addEventListener('click',function(){if(!active)return;notice=null;active.playing=false;var end=Math.min((Math.floor(active.frame/12)+1)*12,active.parsed.length*12);while(active.frame<end&&!active.env.case.result)tick();api.redraw();update();});
if($('replay-restart'))$('replay-restart').addEventListener('click',function(){if(active)load(active.run,false);});
if($('replay-progress'))$('replay-progress').addEventListener('input',function(){if(!active)return;var end=+this.value*12,run=active.run;load(run,false);while(active.frame<end&&!active.env.case.result)tick();api.redraw();update();});
if($('replay-back'))$('replay-back').addEventListener('click',function(){g.location.reload();});
g.addEventListener('blur',function(){if(active){active.playing=false;acc=0;update();}});
function frame(now){
var dt=Math.min(.1,Math.max(0,(now-last)/1000));last=now;
if(active&&active.playing){try{acc+=dt*($('replay-speed')?+$('replay-speed').value:1);while(acc>=BB.DT&&active.playing){tick();acc-=BB.DT;}api.redraw();}catch(e){active.playing=false;showError(e);}}
update();g.requestAnimationFrame(frame);
}
g.BossBenchReplay={load:load,state:function(){return active?{frame:active.frame,playing:active.playing,hash:BB.hashState(active.env.case),verifier:active.env.case.verifier()}:null;}};
g.requestAnimationFrame(frame);
})(typeof window!=='undefined'?window:globalThis);
|