Introduction
Checkout this short introduction video on YouTube!
https://youtu.be/TBd1miOrLPQ
Install
Install from npm.
npm install @geckos.io/typed-array-buffer-schema
Or use the bundled version.
<script src="https://unpkg.com/@geckos.io/typed-array-buffer-schema@1.0.2/bundle/typed-array-buffer-schema.js"></script>
<script>
const { BufferSchema, Model } = Schema
const { uint8, int16, uint16, int64, string8, ...more } Schema
</script>
Snapshot Interpolation
You can easily combine this library with the Snapshot Interpolation library @geckos.io/snapshot-interpolation.
Usage
model.js
import { BufferSchema, Model } from '@geckos.io/typed-array-buffer-schema'
import { uint8, int16, uint16, int64, string8 } from '@geckos.io/typed-array-buffer-schema'
const playerSchema = BufferSchema.schema('player', {
id: uint8,
name: { type: string8, length: 6 },
x: { type: int16, digits: 2 },
y: { type: int16, digits: 2 }
})
const towerSchema = BufferSchema.schema('tower', {
id: uint8,
health: uint8,
team: uint8
})
const mainSchema = BufferSchema.schema('main', {
time: int64,
tick: uint16,
players: [playerSchema],
towers: [towerSchema]
})
export const mainModel = new Model(mainSchema)
export const mainModel = new Model(mainSchema, 8)
server.js
import { mainModel } from './model'
const gameState = {
time: new Date().getTime(),
tick: 32580,
players: [
{ id: 0, name: 'Mistin', x: -14.43, y: 47.78 },
{ id: 1, name: 'Coobim', x: 21.85, y: -78.48 }
],
towers: [
{ id: 0, health: 100, team: 0 },
{ id: 1, health: 89, team: 0 },
{ id: 2, health: 45, team: 1 }
]
}
const buffer = mainModel.toBuffer(gameState)
console.log(JSON.stringify(gameState).length)
console.log(buffer.byteLength)
sendMessage(buffer)
client.js
import { mainModel } from './model'
onMessage(buffer => {
const gameState = mainModel.fromBuffer(buffer)
})
Schema ID
Each Schema has an unique ID. To get the Schema ID from the Schema, Model or Buffer, use the helper functions listed below:
const schemaId = BufferSchema.getIdFromSchema(schema)
const modelId = BufferSchema.getIdFromModel(model)
const bufferId = BufferSchema.getIdFromBuffer(buffer)
DataViews
A list of all supported dataViews
export const int8 = { _type: 'Int8Array', _bytes: 1 }
export const uint8 = { _type: 'Uint8Array', _bytes: 1 }
export const int16 = { _type: 'Int16Array', _bytes: 2 }
export const uint16 = { _type: 'Uint16Array', _bytes: 2 }
export const int32 = { _type: 'Int32Array', _bytes: 4 }
export const uint32 = { _type: 'Uint32Array', _bytes: 4 }
export const int64 = { _type: 'BigInt64Array', _bytes: 8 }
export const uint64 = { _type: 'BigUint64Array', _bytes: 8 }
export const float32 = { _type: 'Float32Array', _bytes: 4 }
export const float64 = { _type: 'Float64Array', _bytes: 8 }
export const string8 = { _type: 'String8', _bytes: 1 }
export const string16 = { _type: 'String16', _bytes: 2 }
export const bool8 = { _type: 'BitArray8', _bytes: 1 }
export const bool16 = { _type: 'BitArray16', _bytes: 2 }