67 lines
2.0 KiB
TypeScript
Raw Normal View History

2022-12-04 22:10:30 +08:00
import { ApiMsgEnum, InputTypeEnum } from "./Enum";
import { strencode } from "./Utils";
export const binaryEncode = (proto: ApiMsgEnum, data: any): DataView => {
if (proto === ApiMsgEnum.MsgClientSync) {
switch (data.type) {
case InputTypeEnum.ActorMove: {
let index = 0
const ab = new ArrayBuffer(3 + 12)
const view = new DataView(ab)
view.setUint8(index++, proto)
view.setUint8(index++, data.type)
view.setUint8(index++, data.id)
view.setFloat32(index, data.direction.x)
index += 4
view.setFloat32(index, data.direction.y)
index += 4
view.setFloat32(index, data.dt)
index += 4
return view
}
case InputTypeEnum.WeaponShoot: {
let index = 0
const ab = new ArrayBuffer(3 + 16)
const view = new DataView(ab)
view.setUint8(index++, proto)
view.setUint8(index++, data.type)
view.setUint8(index++, data.id)
view.setFloat32(index, data.position.x)
index += 4
view.setFloat32(index, data.position.y)
index += 4
view.setFloat32(index, data.direction.x)
index += 4
view.setFloat32(index, data.direction.y)
index += 4
return view
}
case InputTypeEnum.TimePast: {
let index = 0
const ab = new ArrayBuffer(1 + 1 + 4)
const view = new DataView(ab)
view.setUint8(index++, proto)
view.setUint8(index++, data.type)
view.setFloat32(index, data.dt)
index += 4
return view
}
default: {
const ab = new ArrayBuffer(0)
const view = new DataView(ab)
return view
}
}
} else {
let index = 0
const str = JSON.stringify(data)
const ta = strencode(str)
const ab = new ArrayBuffer(ta.length + 1)
const view = new DataView(ab)
view.setUint8(index++, proto)
for (let i = 0; i < ta.length; i++) {
view.setUint8(index++, ta[i])
}
return view
}
}