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
|
#include "Museum.h"
using namespace std;
Museum::Museum() : people(*this), canvas(*this), collision(*this), pathfinding(*this) {
this->worker = new std::thread(&Museum::work, this);
}
Museum::~Museum() {
this->working = false;
this->worker->join();
if (this->worker != nullptr) {
delete this->worker;
this->worker = nullptr;
}
}
void Museum::update() {
this->people.update();
this->canvas.update();
this->collision.update();
this->tick++;
unsigned long long next_snapshot = this->snapshot_ticks;
if (!this->history.empty()) next_snapshot += this->history.top().tick;
if (next_snapshot > this->tick) return;
this->history.push(this->save_snapshot());
printf("saved snapshot at tick %llu\n", this->tick);
}
void Museum::skip_forward() {
this->jump++;
}
void Museum::skip_backward() {
this->jump--;
}
void Museum::work() {
while (this->working) {
// immediately process jumps, even if paused
if (this->jump > 0) {
// forward jump
for (; this->jump != 0; this->jump--) {
printf("jumping forward %u ticks\n", this->snapshot_ticks);
for (size_t i = 0; i < this->snapshot_ticks; i++)
this->update();
}
} else if (this->jump < 0) {
// backward jump
for (; this->jump != 0; this->jump++) {
if (this->history.empty()) continue;
printf("restoring snapshot from tick %llu\n", this->history.top().tick);
this->restore_snapshot(this->history.top());
this->history.pop();
}
}
// wait with regular update if paused
if (this->paused) continue;
// regular update
auto next = chrono::steady_clock::now() + this->tick_interval;
this->update();
this_thread::sleep_until(next);
}
}
static void memories_concat(Memories & a, Memories b) {
a.insert(a.end(), make_move_iterator(b.begin()), make_move_iterator(b.end()));
}
Museum::Snapshot Museum::save_snapshot() {
Snapshot snapshot = {
.tick = this->tick,
.memories = {},
};
memories_concat(snapshot.memories, this->canvas.save());
memories_concat(snapshot.memories, this->people.save());
return snapshot;
}
void Museum::restore_snapshot(const Snapshot & snapshot) {
this->tick = snapshot.tick;
this->canvas.restore(snapshot.memories);
this->people.restore(snapshot.memories);
}
|