-
-
Notifications
You must be signed in to change notification settings - Fork 85
/
Copy pathSerialize.js
418 lines (329 loc) · 12.2 KB
/
Serialize.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
import { $indexBytes, $indexType, $isEidType, $serializeShadow, $storeBase, $storeFlattened, $tagStore, createShadow } from "./Storage.js"
import { $componentMap, addComponent, hasComponent } from "./Component.js"
import { $entityArray, $entitySparseSet, addEntity, eidToWorld } from "./Entity.js"
import { $localEntities, $localEntityLookup } from "./World.js"
import { SparseSet } from "./Util.js"
import { $modifier } from "./Query.js"
export const DESERIALIZE_MODE = {
REPLACE: 0,
APPEND: 1,
MAP: 2
}
let resized = false
export const setSerializationResized = v => { resized = v }
const concat = (a,v) => a.concat(v)
const not = fn => v => !fn(v)
const storeFlattened = c => c[$storeFlattened]
const isFullComponent = storeFlattened
const isProperty = not(isFullComponent)
const isModifier = c => typeof c === "function" && c[$modifier]
const isNotModifier = not(isModifier)
const isChangedModifier = c => isModifier(c) && c()[1] === 'changed'
const isWorld = w => Object.getOwnPropertySymbols(w).includes($componentMap)
const fromModifierToComponent = c => c()[0]
export const canonicalize = target => {
if (isWorld(target)) return [[],new Map()]
// aggregate full components
const fullComponentProps = target
.filter(isNotModifier)
.filter(isFullComponent)
.map(storeFlattened).reduce(concat, [])
// aggregate changed full components
const changedComponentProps = target
.filter(isChangedModifier).map(fromModifierToComponent)
.filter(isFullComponent)
.map(storeFlattened).reduce(concat, [])
// aggregate props
const props = target
.filter(isNotModifier)
.filter(isProperty)
// aggregate changed props
const changedProps = target
.filter(isChangedModifier).map(fromModifierToComponent)
.filter(isProperty)
const componentProps = [...fullComponentProps, ...props, ...changedComponentProps, ...changedProps]
const allChangedProps = [...changedComponentProps, ...changedProps].reduce((map,prop) => {
const $ = Symbol()
createShadow(prop, $)
map.set(prop, $)
return map
}, new Map())
return [componentProps, allChangedProps]
}
/**
* Defines a new serializer which targets the given components to serialize the data of when called on a world or array of EIDs.
*
* @param {object|array} target
* @param {number} [maxBytes=20000000]
* @returns {function} serializer
*/
export const defineSerializer = (target, maxBytes = 20000000) => {
const worldSerializer = isWorld(target)
let [componentProps, changedProps] = canonicalize(target)
// TODO: calculate max bytes based on target & recalc upon resize
const buffer = new ArrayBuffer(maxBytes)
const view = new DataView(buffer)
const entityComponentCache = new Map()
return (ents) => {
if (resized) {
[componentProps, changedProps] = canonicalize(target)
resized = false
}
if (worldSerializer) {
componentProps = []
target[$componentMap].forEach((c, component) => {
if (component[$storeFlattened])
componentProps.push(...component[$storeFlattened])
else componentProps.push(component)
})
}
let world
if (Object.getOwnPropertySymbols(ents).includes($componentMap)) {
world = ents
ents = ents[$entityArray]
} else {
world = eidToWorld.get(ents[0])
}
let where = 0
if (!ents.length) return buffer.slice(0, where)
const cache = new Map()
// iterate over component props
for (let pid = 0; pid < componentProps.length; pid++) {
const prop = componentProps[pid]
const component = prop[$storeBase]()
const $diff = changedProps.get(prop)
const shadow = $diff ? prop[$diff] : null
if (!cache.has(component)) cache.set(component, new Map())
// write pid
view.setUint8(where, pid)
where += 1
// save space for entity count
const countWhere = where
where += 4
let writeCount = 0
// write eid,val
for (let i = 0; i < ents.length; i++) {
const eid = ents[i]
let componentCache = entityComponentCache.get(eid)
if (!componentCache) componentCache = entityComponentCache.set(eid, new Set()).get(eid)
componentCache.add(eid)
const newlyAddedComponent =
// if we are diffing
shadow
// and we have already iterated over this component for this entity
// retrieve cached value
&& cache.get(component).get(eid)
// or if entity did not have component last call
|| !componentCache.has(component)
// and entity has component this call
&& hasComponent(world, component, eid)
cache.get(component).set(eid, newlyAddedComponent)
if (newlyAddedComponent) {
componentCache.add(component)
} else if (!hasComponent(world, component, eid)) {
// skip if entity doesn't have this component
componentCache.delete(component)
continue
}
const rewindWhere = where
// write eid
view.setUint32(where, eid)
where += 4
// if it's a tag store we can stop here
if (prop[$tagStore]) {
writeCount++
continue
}
// if property is an array
if (ArrayBuffer.isView(prop[eid])) {
const type = prop[eid].constructor.name.replace('Array', '')
const indexType = prop[eid][$indexType]
const indexBytes = prop[eid][$indexBytes]
// save space for count of dirty array elements
const countWhere2 = where
where += indexBytes
let arrayWriteCount = 0
// write index,value
for (let i = 0; i < prop[eid].length; i++) {
if (shadow) {
const changed = shadow[eid][i] !== prop[eid][i]
// sync shadow
shadow[eid][i] = prop[eid][i]
// if state has not changed since the last call
// todo: if newly added then entire component will serialize (instead of only changed values)
if (!changed && !newlyAddedComponent) {
// skip writing this value
continue
}
}
// write array index
view[`set${indexType}`](where, i)
where += indexBytes
// write value at that index
const value = prop[eid][i]
view[`set${type}`](where, value)
where += prop[eid].BYTES_PER_ELEMENT
arrayWriteCount++
}
if (arrayWriteCount > 0) {
// write total element count
view[`set${indexType}`](countWhere2, arrayWriteCount)
writeCount++
} else {
where = rewindWhere
continue
}
} else {
if (shadow) {
const changed = shadow[eid] !== prop[eid]
shadow[eid] = prop[eid]
// do not write value if diffing and no change
if (!changed && !newlyAddedComponent) {
// rewind the serializer
where = rewindWhere
// skip writing this value
continue
}
}
const type = prop.constructor.name.replace('Array', '')
// set value next [type] bytes
view[`set${type}`](where, prop[eid])
where += prop.BYTES_PER_ELEMENT
writeCount++
}
}
if (writeCount > 0) {
// write how many eid/value pairs were written
view.setUint32(countWhere, writeCount)
} else {
// if nothing was written (diffed with no changes)
// then move cursor back 5 bytes (remove PID and countWhere space)
where -= 5
}
}
return buffer.slice(0, where)
}
}
const newEntities = new Map()
/**
* Defines a new deserializer which targets the given components to deserialize onto a given world.
*
* @param {object|array} target
* @returns {function} deserializer
*/
export const defineDeserializer = (target) => {
const isWorld = Object.getOwnPropertySymbols(target).includes($componentMap)
let [componentProps] = canonicalize(target)
const deserializedEntities = new Set()
return (world, packet, mode=0) => {
newEntities.clear()
if (resized) {
[componentProps] = canonicalize(target)
resized = false
}
if (isWorld) {
componentProps = []
target[$componentMap].forEach((c, component) => {
if (component[$storeFlattened])
componentProps.push(...component[$storeFlattened])
else componentProps.push(component)
})
}
const localEntities = world[$localEntities]
const localEntityLookup = world[$localEntityLookup]
const view = new DataView(packet)
let where = 0
while (where < packet.byteLength) {
// pid
const pid = view.getUint8(where)
where += 1
// entity count
const entityCount = view.getUint32(where)
where += 4
// component property
const prop = componentProps[pid]
// Get the entities and set their prop values
for (let i = 0; i < entityCount; i++) {
let eid = view.getUint32(where) // throws with [changed, c, changed]
where += 4
if (mode === DESERIALIZE_MODE.MAP) {
if (localEntities.has(eid)) {
eid = localEntities.get(eid)
} else if (newEntities.has(eid)) {
eid = newEntities.get(eid)
} else {
const newEid = addEntity(world)
localEntities.set(eid, newEid)
localEntityLookup.set(newEid, eid)
newEntities.set(eid, newEid)
eid = newEid
}
}
if (mode === DESERIALIZE_MODE.APPEND ||
mode === DESERIALIZE_MODE.REPLACE && !world[$entitySparseSet].has(eid)
) {
const newEid = newEntities.get(eid) || addEntity(world)
newEntities.set(eid, newEid)
eid = newEid
}
const component = prop[$storeBase]()
if (!hasComponent(world, component, eid)) {
addComponent(world, component, eid)
}
// add eid to deserialized ents after it has been transformed by MAP mode
deserializedEntities.add(eid)
if (component[$tagStore]) {
continue
}
if (ArrayBuffer.isView(prop[eid])) {
const array = prop[eid]
const count = view[`get${array[$indexType]}`](where)
where += array[$indexBytes]
// iterate over count
for (let i = 0; i < count; i++) {
const index = view[`get${array[$indexType]}`](where)
where += array[$indexBytes]
const value = view[`get${array.constructor.name.replace('Array', '')}`](where)
where += array.BYTES_PER_ELEMENT
if (prop[$isEidType]) {
let localEid
if (localEntities.has(value)) {
localEid = localEntities.get(value)
} else if (newEntities.has(value)) {
localEid = newEntities.get(value)
} else {
const newEid = addEntity(world)
localEntities.set(value, newEid)
localEntityLookup.set(newEid, value)
newEntities.set(value, newEid)
localEid = newEid
}
prop[eid][index] = localEid
} else prop[eid][index] = value
}
} else {
const value = view[`get${prop.constructor.name.replace('Array', '')}`](where)
where += prop.BYTES_PER_ELEMENT
if (prop[$isEidType]) {
let localEid
if (localEntities.has(value)) {
localEid = localEntities.get(value)
} else if (newEntities.has(value)) {
localEid = newEntities.get(value)
} else {
const newEid = addEntity(world)
localEntities.set(value, newEid)
localEntityLookup.set(newEid, value)
newEntities.set(value, newEid)
localEid = newEid
}
prop[eid] = localEid
} else prop[eid] = value
}
}
}
const ents = Array.from(deserializedEntities)
deserializedEntities.clear()
return ents
}
}