R-Type  2
Doom but in better
Loading...
Searching...
No Matches
main.cpp
Go to the documentation of this file.
1#include "src/server.hpp"
2#include <thread>
3#include <iostream>
4#include <string>
5
10// A small helper to print usage
11static void print_usage(const char* progName) {
12 std::cout << "Usage: " << progName << " [OPTIONS]\n"
13 << "\nOptions:\n"
14 << " --help Show this help message and exit\n"
15 << " --port <number> Specify the UDP port to use (default: 9000)\n"
16 << std::endl;
17}
18
19int main(int argc, char* argv[])
20{
21 // Default port
22 unsigned short port = 9000;
23
24 // Parse command-line arguments
25 for (int i = 1; i < argc; ++i) {
26 std::string arg = argv[i];
27
28 if (arg == "--help") {
29 // Print usage and exit
30 print_usage(argv[0]);
31 return 0;
32 }
33 else if (arg == "--port") {
34 if (i + 1 < argc) {
35 ++i; // move to the next argument
36 try {
37 port = static_cast<unsigned short>(std::stoi(argv[i]));
38 } catch (...) {
39 std::cerr << "[Error] Invalid or out-of-range port: " << argv[i] << "\n";
40 return 1;
41 }
42 } else {
43 // Missing port number
44 std::cerr << "[Error] '--port' requires an argument.\n";
45 print_usage(argv[0]);
46 return 1;
47 }
48 }
49 else {
50 std::cerr << "[Error] Unknown option: " << arg << "\n";
51 print_usage(argv[0]);
52 return 1;
53 }
54 }
55 try {
56 // Create the io_context
57 asio::io_context io_context;
58
59 // Create the server listening on the parsed 'port'
60 auto server = std::make_shared<Server>(io_context, port);
61
62 // Start multiple I/O threads
63 unsigned int numThreads = std::max(4u, std::thread::hardware_concurrency());
64 std::vector<std::thread> threadPool;
65 threadPool.reserve(numThreads);
66 for (unsigned i = 0; i < numThreads; ++i) {
67 threadPool.emplace_back([&io_context]() {
68 io_context.run();
69 });
70 }
71
72 // Run game loop
73 bool running = true;
74 std::thread gameLoopThread([&]() {
75 using clock = std::chrono::steady_clock;
76 auto lastTime = clock::now();
77
78 while (running) {
79 auto now = clock::now();
80 float dt = std::chrono::duration<float>(now - lastTime).count();
81 lastTime = now;
82
83 // Update the Game instances
84 server->getGameManager().updateAllGames(dt);
85
86 // Sleep ~16ms => ~60 FPS
87 std::this_thread::sleep_for(std::chrono::milliseconds(16));
88 }
89 });
90
91 // Inform user
92 std::cout << "[Server] Listening on 0.0.0.0:" << port << " (UDP)\n";
93 std::cout << "[Server] Press ENTER to quit.\n";
94 std::cin.get();
95
96 // Stop
97 running = false;
98 io_context.stop();
99
100 for (auto &t : threadPool) {
101 if (t.joinable()) t.join();
102 }
103 if (gameLoopThread.joinable()) {
104 gameLoopThread.join();
105 }
106
107 }
108 catch (std::exception &e) {
109 std::cerr << "[Server] Exception: " << e.what() << "\n";
110 return 1;
111 }
112
113 return 0;
114}
int main(void)
Definition main.cpp:3