Add: INR currency (#8136)
[openttd-github.git] / src / video / dedicated_v.cpp
blobac7d38bb7f53d2b302f686302d4a1ceb47a8f736
1 /*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6 */
8 /** @file dedicated_v.cpp Dedicated server video 'driver'. */
10 #include "../stdafx.h"
12 #include "../gfx_func.h"
13 #include "../network/network.h"
14 #include "../network/network_internal.h"
15 #include "../console_func.h"
16 #include "../genworld.h"
17 #include "../fileio_type.h"
18 #include "../fios.h"
19 #include "../blitter/factory.hpp"
20 #include "../company_func.h"
21 #include "../core/random_func.hpp"
22 #include "../saveload/saveload.h"
23 #include "../thread.h"
24 #include "dedicated_v.h"
26 #ifdef __OS2__
27 # include <sys/time.h> /* gettimeofday */
28 # include <sys/types.h>
29 # include <unistd.h>
30 # include <conio.h>
32 # define INCL_DOS
33 # include <os2.h>
35 # define STDIN 0 /* file descriptor for standard input */
37 /**
38 * Switches OpenTTD to a console app at run-time, instead of a PM app
39 * Necessary to see stdout, etc.
41 static void OS2_SwitchToConsoleMode()
43 PPIB pib;
44 PTIB tib;
46 DosGetInfoBlocks(&tib, &pib);
48 /* Change flag from PM to VIO */
49 pib->pib_ultype = 3;
51 #endif
53 #if defined(UNIX)
54 # include <sys/time.h> /* gettimeofday */
55 # include <sys/types.h>
56 # include <unistd.h>
57 # include <signal.h>
58 # define STDIN 0 /* file descriptor for standard input */
60 /* Signal handlers */
61 static void DedicatedSignalHandler(int sig)
63 if (_game_mode == GM_NORMAL && _settings_client.gui.autosave_on_exit) DoExitSave();
64 _exit_game = true;
65 signal(sig, DedicatedSignalHandler);
67 #endif
69 #if defined(_WIN32)
70 # include <windows.h> /* GetTickCount */
71 # include <conio.h>
72 # include <time.h>
73 # include <tchar.h>
74 # include "../os/windows/win32.h"
76 static HANDLE _hInputReady, _hWaitForInputHandling;
77 static HANDLE _hThread; // Thread to close
78 static char _win_console_thread_buffer[200];
80 /* Windows Console thread. Just loop and signal when input has been received */
81 static void WINAPI CheckForConsoleInput()
83 SetCurrentThreadName("ottd:win-console");
85 DWORD nb;
86 HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
87 for (;;) {
88 ReadFile(hStdin, _win_console_thread_buffer, lengthof(_win_console_thread_buffer), &nb, nullptr);
89 if (nb >= lengthof(_win_console_thread_buffer)) nb = lengthof(_win_console_thread_buffer) - 1;
90 _win_console_thread_buffer[nb] = '\0';
92 /* Signal input waiting that input is read and wait for it being handled
93 * SignalObjectAndWait() should be used here, but it's unsupported in Win98< */
94 SetEvent(_hInputReady);
95 WaitForSingleObject(_hWaitForInputHandling, INFINITE);
99 static void CreateWindowsConsoleThread()
101 DWORD dwThreadId;
102 /* Create event to signal when console input is ready */
103 _hInputReady = CreateEvent(nullptr, false, false, nullptr);
104 _hWaitForInputHandling = CreateEvent(nullptr, false, false, nullptr);
105 if (_hInputReady == nullptr || _hWaitForInputHandling == nullptr) usererror("Cannot create console event!");
107 _hThread = CreateThread(nullptr, 0, (LPTHREAD_START_ROUTINE)CheckForConsoleInput, nullptr, 0, &dwThreadId);
108 if (_hThread == nullptr) usererror("Cannot create console thread!");
110 DEBUG(driver, 2, "Windows console thread started");
113 static void CloseWindowsConsoleThread()
115 CloseHandle(_hThread);
116 CloseHandle(_hInputReady);
117 CloseHandle(_hWaitForInputHandling);
118 DEBUG(driver, 2, "Windows console thread shut down");
121 #endif
123 #include "../safeguards.h"
126 static void *_dedicated_video_mem;
128 /* Whether a fork has been done. */
129 bool _dedicated_forks;
131 extern bool SafeLoad(const char *filename, SaveLoadOperation fop, DetailedFileType dft, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf = nullptr);
133 static FVideoDriver_Dedicated iFVideoDriver_Dedicated;
136 const char *VideoDriver_Dedicated::Start(const char * const *parm)
138 int bpp = BlitterFactory::GetCurrentBlitter()->GetScreenDepth();
139 _dedicated_video_mem = (bpp == 0) ? nullptr : MallocT<byte>(_cur_resolution.width * _cur_resolution.height * (bpp / 8));
141 _screen.width = _screen.pitch = _cur_resolution.width;
142 _screen.height = _cur_resolution.height;
143 _screen.dst_ptr = _dedicated_video_mem;
144 ScreenSizeChanged();
145 BlitterFactory::GetCurrentBlitter()->PostResize();
147 #if defined(_WIN32)
148 /* For win32 we need to allocate a console (debug mode does the same) */
149 CreateConsole();
150 CreateWindowsConsoleThread();
151 SetConsoleTitle(_T("OpenTTD Dedicated Server"));
152 #endif
154 #ifdef _MSC_VER
155 /* Disable the MSVC assertion message box. */
156 _set_error_mode(_OUT_TO_STDERR);
157 #endif
159 #ifdef __OS2__
160 /* For OS/2 we also need to switch to console mode instead of PM mode */
161 OS2_SwitchToConsoleMode();
162 #endif
164 DEBUG(driver, 1, "Loading dedicated server");
165 return nullptr;
168 void VideoDriver_Dedicated::Stop()
170 #ifdef _WIN32
171 CloseWindowsConsoleThread();
172 #endif
173 free(_dedicated_video_mem);
176 void VideoDriver_Dedicated::MakeDirty(int left, int top, int width, int height) {}
177 bool VideoDriver_Dedicated::ChangeResolution(int w, int h) { return false; }
178 bool VideoDriver_Dedicated::ToggleFullscreen(bool fs) { return false; }
180 #if defined(UNIX) || defined(__OS2__)
181 static bool InputWaiting()
183 struct timeval tv;
184 fd_set readfds;
186 tv.tv_sec = 0;
187 tv.tv_usec = 1;
189 FD_ZERO(&readfds);
190 FD_SET(STDIN, &readfds);
192 /* don't care about writefds and exceptfds: */
193 return select(STDIN + 1, &readfds, nullptr, nullptr, &tv) > 0;
196 static uint32 GetTime()
198 struct timeval tim;
200 gettimeofday(&tim, nullptr);
201 return tim.tv_usec / 1000 + tim.tv_sec * 1000;
204 #else
206 static bool InputWaiting()
208 return WaitForSingleObject(_hInputReady, 1) == WAIT_OBJECT_0;
211 static uint32 GetTime()
213 return GetTickCount();
216 #endif
218 static void DedicatedHandleKeyInput()
220 static char input_line[1024] = "";
222 if (!InputWaiting()) return;
224 if (_exit_game) return;
226 #if defined(UNIX) || defined(__OS2__)
227 if (fgets(input_line, lengthof(input_line), stdin) == nullptr) return;
228 #else
229 /* Handle console input, and signal console thread, it can accept input again */
230 assert_compile(lengthof(_win_console_thread_buffer) <= lengthof(input_line));
231 strecpy(input_line, _win_console_thread_buffer, lastof(input_line));
232 SetEvent(_hWaitForInputHandling);
233 #endif
235 /* Remove trailing \r or \n */
236 for (char *c = input_line; *c != '\0'; c++) {
237 if (*c == '\n' || *c == '\r' || c == lastof(input_line)) {
238 *c = '\0';
239 break;
242 str_validate(input_line, lastof(input_line));
244 IConsoleCmdExec(input_line); // execute command
247 void VideoDriver_Dedicated::MainLoop()
249 uint32 cur_ticks = GetTime();
250 uint32 next_tick = cur_ticks + MILLISECONDS_PER_TICK;
252 /* Signal handlers */
253 #if defined(UNIX)
254 signal(SIGTERM, DedicatedSignalHandler);
255 signal(SIGINT, DedicatedSignalHandler);
256 signal(SIGQUIT, DedicatedSignalHandler);
257 #endif
259 /* Load the dedicated server stuff */
260 _is_network_server = true;
261 _network_dedicated = true;
262 _current_company = _local_company = COMPANY_SPECTATOR;
264 /* If SwitchMode is SM_LOAD_GAME, it means that the user used the '-g' options */
265 if (_switch_mode != SM_LOAD_GAME) {
266 StartNewGameWithoutGUI(GENERATE_NEW_SEED);
267 SwitchToMode(_switch_mode);
268 _switch_mode = SM_NONE;
269 } else {
270 _switch_mode = SM_NONE;
271 /* First we need to test if the savegame can be loaded, else we will end up playing the
272 * intro game... */
273 if (!SafeLoad(_file_to_saveload.name, _file_to_saveload.file_op, _file_to_saveload.detail_ftype, GM_NORMAL, BASE_DIR)) {
274 /* Loading failed, pop out.. */
275 DEBUG(net, 0, "Loading requested map failed, aborting");
276 _networking = false;
277 } else {
278 /* We can load this game, so go ahead */
279 SwitchToMode(SM_LOAD_GAME);
283 /* Done loading, start game! */
285 if (!_networking) {
286 DEBUG(net, 0, "Dedicated server could not be started, aborting");
287 return;
290 while (!_exit_game) {
291 uint32 prev_cur_ticks = cur_ticks; // to check for wrapping
292 InteractiveRandom(); // randomness
294 if (!_dedicated_forks) DedicatedHandleKeyInput();
296 cur_ticks = GetTime();
297 _realtime_tick += cur_ticks - prev_cur_ticks;
298 if (cur_ticks >= next_tick || cur_ticks < prev_cur_ticks || _ddc_fastforward) {
299 next_tick = cur_ticks + MILLISECONDS_PER_TICK;
301 GameLoop();
302 UpdateWindows();
305 /* Don't sleep when fast forwarding (for desync debugging) */
306 if (!_ddc_fastforward) {
307 /* Sleep longer on a dedicated server, if the game is paused and no clients connected.
308 * That can allow the CPU to better use deep sleep states. */
309 if (_pause_mode != 0 && !HasClients()) {
310 CSleep(100);
311 } else {
312 CSleep(1);