85 lines
2.3 KiB
JavaScript
85 lines
2.3 KiB
JavaScript
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) => {
|
|
this.accept(event.data);
|
|
});
|
|
}
|
|
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: {
|
|
if (CLIENT_INTERPOLATION) {
|
|
this.interpolator.postMessage(packet);
|
|
}
|
|
else {
|
|
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_PREDICTION) {
|
|
this.predictor.postMessage([1, packet]);
|
|
}
|
|
else if (CLIENT_INTERPOLATION) {
|
|
this.interpolator.postMessage(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);
|
|
}
|
|
}
|
|
}
|