avocado-old/packages/input/packet/input.packet.js
2020-06-15 17:26:20 -05:00

47 lines
1.1 KiB
JavaScript

import * as I from 'immutable';
import {Packet} from '@avocado/net';
export default class InputPacket extends Packet {
static setActionIds(actionIds) {
this._actionIds = actionIds;
this._idActions = {};
for (const action in this._actionIds) {
this._idActions[this._actionIds[action]] = action;
}
}
static pack(packet) {
const data = packet.data[1];
for (let i = 0; i < data.length; i++) {
const {action, value} = data[i];
const actionId = this._actionIds[action];
data[i] = ((actionId & 0xFF) << 24) | (value & 0xFFFFFF);
}
return super.pack(packet);
}
static get schema() {
return {
...super.schema,
data: ['uint32'],
};
}
static unpack(packet) {
const data = super.unpack(packet);
for (let i = 0; i < data.length; i++) {
const actionId = data[i] >> 24;
const value = data[i] & 0xFFFFFF;
data[i] = {
action: this._idActions[actionId],
// -1 is nice to handle, anyway. We'll be a pal.
value: 16777214 === value ? -1 : value,
};
}
return data;
}
}