server console input

This commit is contained in:
2023-08-13 13:44:05 +02:00
parent ddbba997e5
commit d529c79150
4 changed files with 104 additions and 28 deletions

View File

@@ -10,8 +10,8 @@
namespace td {
namespace server {
Server::Server(const std::string& worldFilePath) : m_ServerRunning(false) {
m_Game.GetWorld()->LoadMapFromFile(worldFilePath);
Server::Server() : m_ServerRunning(false) {
}
Server::~Server() {
@@ -19,24 +19,36 @@ Server::~Server() {
m_Thread.join();
}
bool Server::LoadMap(const std::string& worldFilePath) {
return m_Game.GetWorld()->LoadMapFromFile(worldFilePath);
}
bool Server::IsMapLoaded() {
return !m_Game.GetWorld()->GetTilePalette().empty();
}
void Server::ServerLoop() {
std::uint64_t lastTime = td::utils::GetTime();
while (m_ServerRunning) {
std::uint64_t time = td::utils::GetTime();
std::uint64_t delta = time - lastTime;
if (delta >= SERVER_TICK) {
Tick(delta);
lastTime = td::utils::GetTime();
m_TickCounter.SetMSPT(lastTime - time);
std::uint64_t sleepTime = SERVER_TICK - (delta - SERVER_TICK);
std::this_thread::sleep_for(std::chrono::milliseconds(sleepTime));
}
}
Clean();
}
void Server::StartThread() {
m_Thread = std::thread([this]() {
std::uint64_t lastTime = td::utils::GetTime();
while (m_ServerRunning) {
std::uint64_t time = td::utils::GetTime();
std::uint64_t delta = time - lastTime;
if (delta >= SERVER_TICK) {
Tick(delta);
lastTime = td::utils::GetTime();
m_TickCounter.SetMSPT(lastTime - time);
std::uint64_t sleepTime = SERVER_TICK - (delta - SERVER_TICK);
std::this_thread::sleep_for(std::chrono::milliseconds(sleepTime));
}
}
Clean();
ServerLoop();
});
}
@@ -48,7 +60,11 @@ void Server::StopThread() {
m_ServerRunning = false;
}
bool Server::Start(std::uint16_t port) {
bool Server::Start(std::uint16_t port, bool blocking) {
if (!IsMapLoaded()) {
utils::LOGE(utils::format("No map loaded !"));
return false;
}
if (!m_Listener.Listen(port, 10)) {
utils::LOGE(utils::format("Failed to bind port %u !", port));
return false;
@@ -60,7 +76,11 @@ bool Server::Start(std::uint16_t port) {
utils::LOG(utils::format("Server started at port %u !", port));
m_TickCounter.Reset();
m_ServerRunning = true;
StartThread();
if (blocking) {
ServerLoop();
} else {
StartThread();
}
return true;
}
@@ -145,6 +165,11 @@ void Server::OnPlayerJoin(std::uint8_t id) {
void Server::OnPlayerLeave(std::uint8_t id) {
protocol::PlayerLeavePacket packet(id);
BroadcastPacket(&packet);
if (GetPlayers().empty()) {
utils::LOG("All players left. Stopping server ...");
Stop();
}
}
} // namespace server