silphius/app/client/local.js

86 lines
2.3 KiB
JavaScript
Raw Normal View History

2024-07-21 02:57:29 -05:00
import Client from '@/net/client.js';
2024-08-29 15:43:50 -05:00
import {decode, encode} from '@/net/packets/index.js';
2024-09-05 07:15:55 -05:00
import {CLIENT_INTERPOLATION, CLIENT_PREDICTION} from '@/util/constants.js';
2024-06-10 22:42:30 -05:00
export default class LocalClient extends Client {
2024-08-29 15:43:50 -05:00
server = null;
interpolator = null;
2024-09-05 07:15:55 -05:00
predictor = null;
2024-06-10 22:42:30 -05:00
async connect() {
2024-08-29 15:43:50 -05:00
this.server = new Worker(
2024-06-10 22:42:30 -05:00
new URL('../server/worker.js', import.meta.url),
{type: 'module'},
);
2024-09-05 07:15:55 -05:00
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);
}
2024-09-05 07:15:55 -05:00
});
}
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);
2024-09-05 07:15:55 -05:00
break;
}
}
});
}
2024-08-29 15:43:50 -05:00
this.server.addEventListener('message', (event) => {
2024-06-15 20:59:11 -05:00
if (0 === event.data) {
2024-08-29 15:43:50 -05:00
this.server.terminate();
this.server = null;
2024-06-15 20:59:11 -05:00
return;
}
2024-08-06 00:40:43 -05:00
this.throughput.$$down += event.data.byteLength;
2024-09-05 07:15:55 -05:00
const packet = decode(event.data);
if (CLIENT_INTERPOLATION) {
2024-09-05 07:15:55 -05:00
this.interpolator.postMessage(packet);
}
else if (CLIENT_PREDICTION) {
this.predictor.postMessage([1, packet]);
}
2024-09-05 07:15:55 -05:00
else {
this.accept(packet);
}
2024-06-15 20:59:11 -05:00
});
2024-06-10 22:42:30 -05:00
}
disconnect() {
2024-08-29 15:43:50 -05:00
this.server.postMessage(0);
2024-09-05 07:15:55 -05:00
if (CLIENT_INTERPOLATION) {
this.interpolator.terminate();
}
2024-06-10 22:42:30 -05:00
}
2024-08-29 15:43:50 -05:00
transmit(packet) {
2024-09-05 07:15:55 -05:00
if (CLIENT_PREDICTION) {
this.predictor.postMessage([0, packet]);
}
else {
const packed = encode(packet);
this.throughput.$$up += packed.byteLength;
this.server.postMessage(packed);
}
2024-06-10 22:42:30 -05:00
}
}