aboutsummaryrefslogtreecommitdiff
path: root/src/crepe/api/Engine.cpp
blob: bbb44941adfc2d09505e5f5d5856c8f8869dad5e (plain)
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
#include "../util/Log.h"

#include "Engine.h"

using namespace crepe;
using namespace std;

int Engine::main() noexcept {
	try {
		this->setup();
	} catch (const exception & e) {
		Log::logf(Log::Level::ERROR, "Uncaught exception in setup: {}\n", e.what());
		return EXIT_FAILURE;
	}

	try {
		this->loop();
	} catch (const exception & e) {
		Log::logf(Log::Level::ERROR, "Uncaught exception in main loop: {}\n", e.what());
		this->event_manager.trigger_event<ShutDownEvent>();
	}

	return EXIT_SUCCESS;
}

void Engine::setup() {
	this->loop_timer.start();
	this->scene_manager.load_next_scene();

	this->event_manager.subscribe<ShutDownEvent>([this](const ShutDownEvent & event) {
		this->game_running = false;

		// propagate to possible user ShutDownEvent listeners
		return false;
	});
}

void Engine::loop() {
	LoopTimerManager & timer = this->loop_timer;
	SystemManager & systems = this->system_manager;

	while (game_running) {
		timer.update();

		while (timer.get_lag() >= timer.get_fixed_delta_time()) {
			try {
				systems.fixed_update();
			} catch (const exception & e) {
				Log::logf(Log::Level::WARNING,
						  "Uncaught exception in fixed update function: {}\n", e.what());
			}
			timer.advance_fixed_elapsed_time();
		}

		try {
			systems.frame_update();
		} catch (const exception & e) {
			Log::logf(Log::Level::WARNING, "Uncaught exception in frame update function: {}\n",
					  e.what());
		}
		timer.enforce_frame_rate();
	}
}