freeblox/packages/engine/src/net/packet.ts

98 lines
2.5 KiB
TypeScript

import { PacketType } from './packet-type.enum';
import { SmartBuffer } from 'smart-buffer';
import { Instancable } from '../types/instancable';
import { Quaternion, Vector3 } from 'three';
export class Packet {
private buffer = new SmartBuffer();
constructor(public packet?: PacketType) {}
write(data: any, type: Instancable<any> | string) {
switch (type) {
case 'string':
case String:
this.buffer.writeStringNT(data);
break;
case 'bool':
case Boolean:
this.buffer.writeUInt8(data ? 1 : 0);
break;
case 'float':
case Number:
this.buffer.writeFloatLE(data);
break;
case 'uint8':
this.buffer.writeUInt8(data);
break;
case 'int32':
this.buffer.writeInt32LE(data);
break;
case 'uint32':
this.buffer.writeUInt32LE(data);
break;
case 'vec3':
this.buffer.writeFloatLE(data.x);
this.buffer.writeFloatLE(data.y);
this.buffer.writeFloatLE(data.z);
break;
case 'quat':
this.buffer.writeFloatLE(data.x);
this.buffer.writeFloatLE(data.y);
this.buffer.writeFloatLE(data.z);
this.buffer.writeFloatLE(data.w);
break;
}
return this;
}
read<T = string>(type: Instancable<any> | string) {
switch (type) {
case 'string':
case String:
return this.buffer.readStringNT() as T;
case 'bool':
case Boolean:
return this.buffer.readUInt8() as T;
case 'float':
case Number:
return this.buffer.readFloatLE() as T;
case 'uint8':
return this.buffer.readUInt8() as T;
case 'int32':
return this.buffer.readInt32LE() as T;
case 'uint32':
return this.buffer.readUInt32LE() as T;
case 'vec3':
return new Vector3(
this.buffer.readFloatLE(),
this.buffer.readFloatLE(),
this.buffer.readFloatLE()
) as T;
case 'quat':
return new Quaternion(
this.buffer.readFloatLE(),
this.buffer.readFloatLE(),
this.buffer.readFloatLE(),
this.buffer.readFloatLE()
) as T;
}
}
writeHeader() {
if (this.packet === undefined) return;
this.buffer.insertUInt8(this.packet, 0);
}
toBuffer() {
this.writeHeader();
return this.buffer.toBuffer();
}
static from(buffer: Buffer) {
const packet = new Packet();
packet.buffer = SmartBuffer.fromBuffer(buffer);
packet.packet = packet.buffer.readUInt8();
return packet;
}
}