In this case Iām packing 100 buffer objects (x 100, one for each player)
Each character table is 12 string keys with numbers, and one Vector3 field.
The final result is a lua ābufferā object containing the contents of 100 pairs of player character data tables.
Packing a character view happens two ways - either like so:
function CharacterData:SerializeToBitBufferFast(buf : buffer, offset: number)
local contentWritePos = offset
offset += 2 --2 bytes contents
local contentBits = 0xFFFF
local serialized = self.serialized
offset = WriteVector3(buf, offset, serialized.pos)
offset = WriteFloat16(buf, offset, serialized.angle)
offset = WriteFloat16(buf, offset, serialized.stepUp)
offset = WriteFloat16(buf, offset, serialized.flatSpeed)
offset = WriteFloat32(buf, offset, serialized.exclusiveAnimTime)
offset = WriteByte(buf, offset, serialized.animCounter0)
offset = WriteByte(buf, offset, serialized.animNum0)
offset = WriteByte(buf, offset, serialized.animCounter1)
offset = WriteByte(buf, offset, serialized.animNum1)
offset = WriteByte(buf, offset, serialized.animCounter2)
offset = WriteByte(buf, offset, serialized.animNum2)
offset = WriteByte(buf, offset, serialized.animCounter3)
offset = WriteByte(buf, offset, serialized.animNum3)
buffer.writeu16(buf, contentWritePos, contentBits)
return offset
end
or like so:
function CharacterData:SerializeToBitBuffer(previousData, buf : buffer, offset: number)
if (previousData == nil) then
return self:SerializeToBitBufferFast(buf, offset)
end
local contentWritePos = offset
offset += 2 --2 bytes contents
local contentBits = 0
local bitIndex = 0
--calculate bits
for keyIndex, key in CharacterData.keys do
local value = self.serialized[key]
local func = CharacterData.methods[CharacterData.packFunctions[key]]
local valueA = previousData.serialized[key]
local valueB = value
if func.compare(valueA, valueB) == false then
contentBits = bit32.bor(contentBits, bit32.lshift(1, bitIndex))
offset = func.write(buf, offset, value)
end
bitIndex += 1
end
buffer.writeu16(buf, contentWritePos, contentBits)
return offset
end
In testing, I pay about 1ms to create this shared table from a regular table and freeze it.
And then the loop that does this runs about 4x slower than if I just let it run on the main thread.
To be doubly clear - this table is frozen and is only used in a read-access way.