import Client from '@/net/client.js'; import {decode, encode} from '@/net/packets/index.js'; import {CLIENT_INTERPOLATION, CLIENT_PREDICTION} from '@/util/constants.js'; export default class LocalClient extends Client { server = null; interpolator = null; predictor = null; async connect() { this.server = new Worker( new URL('../server/worker.js', import.meta.url), {type: 'module'}, ); if (CLIENT_INTERPOLATION) { this.interpolator = new Worker( new URL('./interpolator.js', import.meta.url), {type: 'module'}, ); this.interpolator.addEventListener('message', (event) => { const packet = event.data; if (CLIENT_PREDICTION) { this.predictor.postMessage([1, packet]); } else { this.accept(packet); } }); } if (CLIENT_PREDICTION) { this.predictor = new Worker( new URL('./predictor.js', import.meta.url), {type: 'module'}, ); this.predictor.addEventListener('message', (event) => { const [flow, packet] = event.data; switch (flow) { case 0: { const packed = encode(packet); this.throughput.$$up += packed.byteLength; this.server.postMessage(packed); break; } case 1: { this.accept(packet); break; } } }); } this.server.addEventListener('message', (event) => { if (0 === event.data) { this.server.terminate(); this.server = null; return; } this.throughput.$$down += event.data.byteLength; const packet = decode(event.data); if (CLIENT_INTERPOLATION) { this.interpolator.postMessage(packet); } else if (CLIENT_PREDICTION) { this.predictor.postMessage([1, packet]); } else { this.accept(packet); } }); } disconnect() { this.server.postMessage(0); if (CLIENT_INTERPOLATION) { this.interpolator.terminate(); } } transmit(packet) { if (CLIENT_PREDICTION) { this.predictor.postMessage([0, packet]); } else { const packed = encode(packet); this.throughput.$$up += packed.byteLength; this.server.postMessage(packed); } } }