binary encode

This commit is contained in:
sli97
2022-12-04 22:10:30 +08:00
parent a678a5b3fc
commit c31af6b02a
23 changed files with 1089 additions and 745 deletions

View File

@@ -1,4 +1,5 @@
import { SpriteFrame } from "cc"
import { ApiMsgEnum, InputTypeEnum, strdecode } from "../Common"
const INDEX_REG = /\((\d+)\)/
@@ -9,4 +10,78 @@ export const sortSpriteFrame = (spriteFrame: Array<SpriteFrame>) =>
export const rad2Angle = (rad: number) => rad / Math.PI * 180
export const toFixed = (num: number, digit: number = 4): number => Math.floor(num * 10 ** digit) / 10 ** digit
export const binaryDecode = (buffer: ArrayBuffer) => {
let index = 0
const view = new DataView(buffer)
const type = view.getUint8(index++)
if (type === ApiMsgEnum.MsgClientSync) {
const inputType = view.getUint8(index++)
if (inputType === InputTypeEnum.ActorMove) {
const id = view.getUint8(index++)
const directionX = view.getFloat32(index)
index += 4
const directionY = view.getFloat32(index)
index += 4
const dt = view.getFloat32(index)
index += 4
const msg = {
name: ApiMsgEnum.MsgClientSync,
data: {
type: InputTypeEnum.ActorMove,
id,
direction: {
x: directionX,
y: directionY,
},
dt
}
}
return msg
} else if (inputType === InputTypeEnum.WeaponShoot) {
const id = view.getUint8(index++)
const positionX = view.getFloat32(index)
index += 4
const positionY = view.getFloat32(index)
index += 4
const directionX = view.getFloat32(index)
index += 4
const directionY = view.getFloat32(index)
index += 4
const msg = {
name: ApiMsgEnum.MsgClientSync,
data: {
type: InputTypeEnum.WeaponShoot,
id,
position: {
x: positionX,
y: positionY,
},
direction: {
x: directionX,
y: directionY,
},
}
}
return msg
} else {
const dt = view.getFloat32(index)
index += 4
const msg = {
name: ApiMsgEnum.MsgClientSync,
data: {
type: InputTypeEnum.TimePast,
dt,
}
}
return msg
}
} else {
return {
name: type,
data: JSON.parse(strdecode(new Uint8Array(buffer.slice(1))))
}
}
}