aorecomp

Anarchy Online classic in the browser

git clone https://aorecomp.ubeagle.com/code/aorecomp.git


client/runtime/browser_profile.js (6265B)


      1 addToLibrary({
      2   $AOProfile__deps: ['browser_profile_configuration', 'pthread_self', '$UTF8ToString'],
      3   $AOProfile: {
      4     channel: null,
      5     detailed: false,
      6     events: [],
      7     metrics: {},
      8     dropped: 0,
      9     frames: [],
     10     previousFrame: 0,
     11     lastFlush: 0,
     12     phases: [],
     13     phaseAddress: 0,
     14     connect() {
     15       if (this.channel) return true;
     16       const configuration = _browser_profile_configuration();
     17       if (!configuration) return false;
     18       const [detailed, session, phase, thread] = UTF8ToString(configuration).split(':');
     19       this.detailed = detailed === '1';
     20       this.thread = _pthread_self();
     21       this.phaseAddress = this.detailed && this.thread === Number(thread) ? Number(phase) : 0;
     22       this.channel = new BroadcastChannel(`ao-profile-${session}`);
     23       this.lastFlush = this.now();
     24       setInterval(() => this.flush(), 1000);
     25       return true;
     26     },
     27     now() { return performance.timeOrigin + performance.now(); },
     28     begin(name) {
     29       if (!this.connect()) return 0;
     30       if (this.phaseAddress) {
     31         this.phases.push(Atomics.load(HEAPU32, this.phaseAddress >>> 2));
     32         const phase = name === 'raf wait' ? 1 : name === 'render scene' ? 2 :
     33           name === 'file read' ? 3 : name === 'asset setup' ? 4 : 5;
     34         Atomics.store(HEAPU32, this.phaseAddress >>> 2, phase);
     35       }
     36       return this.now();
     37     },
     38     end(name, start, detail) {
     39       if (!start) return;
     40       const now = this.now(), duration = now - start;
     41       if (this.phaseAddress) Atomics.store(HEAPU32, this.phaseAddress >>> 2, this.phases.pop());
     42       const metric = this.metrics[name] ||= {count: 0, ms: 0, max: 0};
     43       ++metric.count;
     44       metric.ms += duration;
     45       metric.max = Math.max(metric.max, duration);
     46       // Cached reads remain in aggregates without crowding out meaningful waits.
     47       if (this.detailed && (name !== 'file read' || duration >= 0.1)) {
     48         if (this.events.length < 2048)
     49           this.events.push({name, ph: 'X', ts: start * 1000, dur: duration * 1000,
     50             pid: 1, tid: this.thread,
     51             args: typeof detail === 'string' ? {detail: detail.slice(0, 128)} : detail || {}});
     52         else ++this.dropped;
     53       }
     54       // The game worker cannot run its timer while it is inside guest code.
     55       if (this.events.length >= 128 || now - this.lastFlush >= 1000 ||
     56           name === 'sound load/decode' || name === 'music load/decode') this.flush();
     57     },
     58     frame() {
     59       if (!this.connect()) return;
     60       const now = this.now();
     61       if (this.previousFrame) {
     62         const duration = now - this.previousFrame;
     63         if (this.detailed) {
     64           if (this.events.length < 2048)
     65             this.events.push({name: 'frame interval', ph: 'X', ts: this.previousFrame * 1000,
     66               dur: duration * 1000, pid: 1, tid: 0});
     67           else ++this.dropped;
     68         }
     69         this.frames.push(duration);
     70         if (this.frames.length >= 120) this.flush();
     71       }
     72       this.previousFrame = now;
     73     },
     74     flush() {
     75       if (!this.events.length && !this.frames.length && !Object.keys(this.metrics).length) return;
     76       this.channel.postMessage({events: this.events, frames: this.frames,
     77         metrics: this.metrics, dropped: this.dropped});
     78       this.lastFlush = this.now();
     79       this.events = []; this.frames = []; this.metrics = {}; this.dropped = 0;
     80     }
     81   },
     82   ao_profile_thread_start__deps: ['$AOProfile'],
     83   ao_profile_thread_start: (sample, entry) => {
     84     if (!AOProfile.connect()) return;
     85     AOProfile.thread = _pthread_self();
     86     AOProfile.phaseAddress = sample + 4;
     87     AOProfile.channel.postMessage({register: {sample, entry, thread: AOProfile.thread}});
     88   },
     89   ao_profile_thread_stop__deps: ['$AOProfile'],
     90   ao_profile_thread_stop: sample => {
     91     AOProfile.flush();
     92     AOProfile.phaseAddress = 0;
     93     AOProfile.channel.postMessage({unregister: sample});
     94   },
     95   ao_profile_start__deps: ['$stringToNewUTF8', 'free'],
     96   ao_profile_start__proxy: 'sync',
     97   ao_profile_start: (currentFunction, phase, thread) => {
     98     const detailed = new URLSearchParams(location.search).get('profile') === '1';
     99     if (!detailed) return 0;
    100     const session = crypto.randomUUID();
    101     let worker;
    102     try {
    103       worker = new Worker(new URL('wasm/profile-worker.js', document.baseURI));
    104     } catch (error) {
    105       console.warn('Profiling unavailable; gameplay continues', error);
    106       return 0;
    107     }
    108     const channel = new BroadcastChannel(`ao-profile-${session}`);
    109     // Send shared memory directly between workers in this page's agent cluster.
    110     // BroadcastChannel carries only the registration's addresses and identity.
    111     channel.onmessage = event => worker.postMessage(event.data.register ?
    112       {...event.data, memory: wasmMemory.buffer} : event.data);
    113     worker.postMessage({init: {session, detailed, memory: wasmMemory.buffer,
    114       currentFunction, phase, thread, started: performance.timeOrigin + performance.now(), visibility: document.visibilityState,
    115       client: {userAgent: navigator.userAgent, width: Module.canvas.width, height: Module.canvas.height}}});
    116     if (Module.audioContext) {
    117       const recordAudioState = () => worker.postMessage({
    118         events: [{name: 'audio context state', ph: 'i', s: 't', pid: 1, tid: 0,
    119           ts: (performance.timeOrigin + performance.now()) * 1000,
    120           args: {state: Module.audioContext.state}}], frames: [], metrics: {}, dropped: 0
    121       });
    122       Module.audioContext.addEventListener('statechange', recordAudioState);
    123       recordAudioState();
    124     }
    125     worker.onmessage = event => {
    126       if (event.data.free) _free(event.data.free);
    127       else console.log(event.data);
    128     };
    129     worker.onerror = () => {
    130       channel.close();
    131       console.warn('Profiler stopped; gameplay continues');
    132     };
    133     document.addEventListener('visibilitychange', () => {
    134       worker.postMessage({visibility: document.visibilityState});
    135     });
    136     return stringToNewUTF8(`${detailed ? 1 : 0}:${session}:${phase}:${thread}`);
    137   },
    138   ao_profile_begin__deps: ['$AOProfile'],
    139   ao_profile_begin: name => AOProfile.begin(UTF8ToString(name)),
    140   ao_profile_end__deps: ['$AOProfile'],
    141   ao_profile_end: (name, start, detail) => AOProfile.end(UTF8ToString(name), start,
    142     detail ? UTF8ToString(detail) : '')
    143 });