feat: save ECS

This commit is contained in:
cha0s 2024-06-21 18:16:41 -05:00
parent b56d95f4fa
commit 945e759942
2 changed files with 24 additions and 6 deletions

View File

@ -22,6 +22,8 @@ export default class Engine {
frame = 0; frame = 0;
handle;
last = Date.now(); last = Date.now();
server; server;
@ -97,11 +99,7 @@ export default class Engine {
System.active = true; System.active = true;
} }
}); });
const view = Ecs.serialize(ecs); this.saveEcs(join('homesteads', `${id}`), ecs);
await this.server.writeData(
join('homesteads', `${id}`),
view,
);
} }
async createPlayer(id) { async createPlayer(id) {
@ -167,6 +165,19 @@ export default class Engine {
return JSON.parse((new TextDecoder()).decode(buffer)); return JSON.parse((new TextDecoder()).decode(buffer));
} }
async saveEcs(path, ecs) {
const view = Ecs.serialize(ecs);
await this.server.writeData(path, view);
}
async saveEcses() {
const promises = []
for (const i in this.ecses) {
promises.push(this.saveEcs(i, this.ecses[i]));
}
await Promise.all(promises);
}
async savePlayer(id, entity) { async savePlayer(id, entity) {
const encoder = new TextEncoder(); const encoder = new TextEncoder();
const buffer = encoder.encode(JSON.stringify(entity.toJSON())); const buffer = encoder.encode(JSON.stringify(entity.toJSON()));
@ -174,7 +185,7 @@ export default class Engine {
} }
start() { start() {
return setInterval(() => { this.handle = setInterval(() => {
const elapsed = (Date.now() - this.last) / 1000; const elapsed = (Date.now() - this.last) / 1000;
this.last = Date.now(); this.last = Date.now();
this.tick(elapsed); this.tick(elapsed);
@ -183,6 +194,11 @@ export default class Engine {
}, 1000 / TPS); }, 1000 / TPS);
} }
stop() {
clearInterval(this.handle);
this.handle = undefined;
}
tick(elapsed) { tick(elapsed) {
for (const i in this.ecses) { for (const i in this.ecses) {
this.ecses[i].setClean(); this.ecses[i].setClean();

View File

@ -32,7 +32,9 @@ const engine = new Engine(WorkerServer);
onmessage = async (event) => { onmessage = async (event) => {
if (0 === event.data) { if (0 === event.data) {
engine.stop();
await engine.disconnectPlayer(0, 0); await engine.disconnectPlayer(0, 0);
await engine.saveEcses();
postMessage(0); postMessage(0);
return; return;
} }