refactor: track informables and move init to entity creation

This commit is contained in:
cha0s 2019-03-21 00:59:00 -05:00
parent fdf569ee65
commit 6d5b00b44c

View File

@ -16,6 +16,7 @@ export default function(avocadoServer) {
} }
// Entity tracking. // Entity tracking.
const entityList = new EntityList(); const entityList = new EntityList();
const informables = [];
const stateSynchronizer = new StateSynchronizer({ const stateSynchronizer = new StateSynchronizer({
entityList, entityList,
}); });
@ -29,11 +30,10 @@ for (let i = 0; i < 20; ++i) {
function createConnectionListener(avocadoServer) { function createConnectionListener(avocadoServer) {
return (socket) => { return (socket) => {
// Create and track a new entity for the connection. // Create and track a new entity for the connection.
const entity = createEntityForConnection(); const entity = createEntityForConnection(socket);
entityList.addEntity(entity); entityList.addEntity(entity);
// Right in the middle. TODO: camera. // Right in the middle. TODO: camera.
entity.listLocator = () => [640, 360]; entity.listLocator = () => [640, 360];
entity.socket = socket;
// Listen for events. // Listen for events.
socket.on('message', createMessageListener(avocadoServer, socket)); socket.on('message', createMessageListener(avocadoServer, socket));
socket.on('disconnect', createDisconnectionListener(avocadoServer, socket)); socket.on('disconnect', createDisconnectionListener(avocadoServer, socket));
@ -58,9 +58,9 @@ function createDisconnectionListener(avocadoServer, socket) {
}; };
} }
// Create an entity for a new connection. // Create an entity for a new connection.
function createEntityForConnection() { function createEntityForConnection(socket) {
const entity = createEntity(); let entity = createEntity();
return entity.fromJSON({ entity = entity.fromJSON({
traits: { traits: {
animated: { animated: {
params: { params: {
@ -98,6 +98,17 @@ function createEntityForConnection() {
}, },
}, },
}); });
// Track informables.
informables.push(entity);
entity.on('destroyed', () => {
const index = informables.indexOf(entity);
if (-1 !== index) {
informables.splice(index, 1);
}
});
// Embed socket.
entity.socket = socket;
return entity;
} }
// Create a flower barrel. // Create a flower barrel.
function createFlowerBarrelEntity(position) { function createFlowerBarrelEntity(position) {
@ -138,10 +149,7 @@ function createMainLoop(avocadoServer) {
return; return;
} }
// All informed entities get their own slice. // All informed entities get their own slice.
for (const entity of entityList) { for (const entity of informables) {
if (!('inform' in entity)) {
continue;
}
const reduced = entity.reduceStateDiff(diff); const reduced = entity.reduceStateDiff(diff);
entity.inform(reduced); entity.inform(reduced);
} }