humus-old/common/traits/informed.trait.js
2019-10-01 22:43:10 -05:00

93 lines
2.2 KiB
JavaScript

// import {performance} from 'perf_hooks';
import * as I from 'immutable';
import immutablediff from 'immutablediff';
import {compose} from '@avocado/core';
import {Trait} from '@avocado/entity';
import {Rectangle, Vector} from '@avocado/math';
import {BundlePacket, ServerSynchronizer} from '@avocado/net';
const decorate = compose(
);
export class Informed extends decorate(Trait) {
static type() {
return 'informed';
}
constructor(entity, params, state) {
super(entity, params, state);
this._triedPackets = [];
this._queuedPackets = [];
this._sentSelfEntityPacket = false;
this._socket = undefined;
this._synchronizer = new ServerSynchronizer();
}
destroy() {
this._queuedPackets = [];
if (this._socket) {
delete this._socket.entity;
delete this._socket;
}
this._synchronizer.destroy();
}
get areaToInform() {
// Reduce entity list to visible.
const room = this.entity.room;
const camera = this.entity.camera;
// Blow up camera rectangle to compensate for camera desync.
const size = Rectangle.size(camera.rectangle);
return Rectangle.expand(
camera.rectangle,
Vector.scale(size, 0.5),
);
}
get socket() {
return this._socket;
}
set socket(socket) {
socket.entity = this.entity;
this._socket = socket;
}
methods() {
return {
inform: () => {
const synchronizerPackets = this._synchronizer.packetsFor(this.entity);
for (let i = 0; i < synchronizerPackets.length; i++) {
this._triedPackets.push(synchronizerPackets[i]);
}
for (let i = 0; i < this._queuedPackets.length; i++) {
this._triedPackets.push(this._queuedPackets[i]);
}
this._queuedPackets = [];
if (this._socket && this._triedPackets.length > 0) {
this._socket.send(new BundlePacket(this._triedPackets));
this._triedPackets = [];
}
},
addSynchronized: (synchronized) => {
this._synchronizer.addSynchronized(synchronized);
},
queuePacket: (packet) => {
this._queuedPackets.push(packet);
},
removeSynchronized: (synchronized) => {
this._synchronizer.removeSynchronized(synchronized);
},
};
}
}