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/>.
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"
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 "../window_func.h"
25 #include "dedicated_v.h"
28 # include <sys/time.h> /* gettimeofday */
29 # include <sys/types.h>
36 # define STDIN 0 /* file descriptor for standard input */
39 * Switches OpenTTD to a console app at run-time, instead of a PM app
40 * Necessary to see stdout, etc.
42 static void OS2_SwitchToConsoleMode()
47 DosGetInfoBlocks(&tib
, &pib
);
49 /* Change flag from PM to VIO */
55 # include <sys/time.h> /* gettimeofday */
56 # include <sys/types.h>
59 # define STDIN 0 /* file descriptor for standard input */
62 static void DedicatedSignalHandler(int sig
)
64 if (_game_mode
== GM_NORMAL
&& _settings_client
.gui
.autosave_on_exit
) DoExitSave();
66 signal(sig
, DedicatedSignalHandler
);
71 # include <windows.h> /* GetTickCount */
75 # include "../os/windows/win32.h"
77 static HANDLE _hInputReady
, _hWaitForInputHandling
;
78 static HANDLE _hThread
; // Thread to close
79 static char _win_console_thread_buffer
[200];
81 /* Windows Console thread. Just loop and signal when input has been received */
82 static void WINAPI
CheckForConsoleInput()
84 SetCurrentThreadName("ottd:win-console");
87 HANDLE hStdin
= GetStdHandle(STD_INPUT_HANDLE
);
89 ReadFile(hStdin
, _win_console_thread_buffer
, lengthof(_win_console_thread_buffer
), &nb
, nullptr);
90 if (nb
>= lengthof(_win_console_thread_buffer
)) nb
= lengthof(_win_console_thread_buffer
) - 1;
91 _win_console_thread_buffer
[nb
] = '\0';
93 /* Signal input waiting that input is read and wait for it being handled
94 * SignalObjectAndWait() should be used here, but it's unsupported in Win98< */
95 SetEvent(_hInputReady
);
96 WaitForSingleObject(_hWaitForInputHandling
, INFINITE
);
100 static void CreateWindowsConsoleThread()
103 /* Create event to signal when console input is ready */
104 _hInputReady
= CreateEvent(nullptr, false, false, nullptr);
105 _hWaitForInputHandling
= CreateEvent(nullptr, false, false, nullptr);
106 if (_hInputReady
== nullptr || _hWaitForInputHandling
== nullptr) usererror("Cannot create console event!");
108 _hThread
= CreateThread(nullptr, 0, (LPTHREAD_START_ROUTINE
)CheckForConsoleInput
, nullptr, 0, &dwThreadId
);
109 if (_hThread
== nullptr) usererror("Cannot create console thread!");
111 Debug(driver
, 2, "Windows console thread started");
114 static void CloseWindowsConsoleThread()
116 CloseHandle(_hThread
);
117 CloseHandle(_hInputReady
);
118 CloseHandle(_hWaitForInputHandling
);
119 Debug(driver
, 2, "Windows console thread shut down");
124 #include "../safeguards.h"
127 static void *_dedicated_video_mem
;
129 /* Whether a fork has been done. */
130 bool _dedicated_forks
;
132 extern bool SafeLoad(const std::string
&filename
, SaveLoadOperation fop
, DetailedFileType dft
, GameMode newgm
, Subdirectory subdir
, struct LoadFilter
*lf
= nullptr);
134 static FVideoDriver_Dedicated iFVideoDriver_Dedicated
;
137 const char *VideoDriver_Dedicated::Start(const StringList
&parm
)
139 this->UpdateAutoResolution();
141 int bpp
= BlitterFactory::GetCurrentBlitter()->GetScreenDepth();
142 _dedicated_video_mem
= (bpp
== 0) ? nullptr : MallocT
<byte
>(_cur_resolution
.width
* _cur_resolution
.height
* (bpp
/ 8));
144 _screen
.width
= _screen
.pitch
= _cur_resolution
.width
;
145 _screen
.height
= _cur_resolution
.height
;
146 _screen
.dst_ptr
= _dedicated_video_mem
;
148 BlitterFactory::GetCurrentBlitter()->PostResize();
151 /* For win32 we need to allocate a console (debug mode does the same) */
153 CreateWindowsConsoleThread();
154 SetConsoleTitle(L
"OpenTTD Dedicated Server");
158 /* Disable the MSVC assertion message box. */
159 _set_error_mode(_OUT_TO_STDERR
);
163 /* For OS/2 we also need to switch to console mode instead of PM mode */
164 OS2_SwitchToConsoleMode();
167 Debug(driver
, 1, "Loading dedicated server");
171 void VideoDriver_Dedicated::Stop()
174 CloseWindowsConsoleThread();
176 free(_dedicated_video_mem
);
179 void VideoDriver_Dedicated::MakeDirty(int left
, int top
, int width
, int height
) {}
180 bool VideoDriver_Dedicated::ChangeResolution(int w
, int h
) { return false; }
181 bool VideoDriver_Dedicated::ToggleFullscreen(bool fs
) { return false; }
183 #if defined(UNIX) || defined(__OS2__)
184 static bool InputWaiting()
193 FD_SET(STDIN
, &readfds
);
195 /* don't care about writefds and exceptfds: */
196 return select(STDIN
+ 1, &readfds
, nullptr, nullptr, &tv
) > 0;
201 static bool InputWaiting()
203 return WaitForSingleObject(_hInputReady
, 1) == WAIT_OBJECT_0
;
208 static void DedicatedHandleKeyInput()
210 static char input_line
[1024] = "";
212 if (!InputWaiting()) return;
214 if (_exit_game
) return;
216 #if defined(UNIX) || defined(__OS2__)
217 if (fgets(input_line
, lengthof(input_line
), stdin
) == nullptr) return;
219 /* Handle console input, and signal console thread, it can accept input again */
220 static_assert(lengthof(_win_console_thread_buffer
) <= lengthof(input_line
));
221 strecpy(input_line
, _win_console_thread_buffer
, lastof(input_line
));
222 SetEvent(_hWaitForInputHandling
);
225 /* Remove trailing \r or \n */
226 for (char *c
= input_line
; *c
!= '\0'; c
++) {
227 if (*c
== '\n' || *c
== '\r' || c
== lastof(input_line
)) {
232 StrMakeValidInPlace(input_line
, lastof(input_line
));
234 IConsoleCmdExec(input_line
); // execute command
237 void VideoDriver_Dedicated::MainLoop()
239 /* Signal handlers */
241 signal(SIGTERM
, DedicatedSignalHandler
);
242 signal(SIGINT
, DedicatedSignalHandler
);
243 signal(SIGQUIT
, DedicatedSignalHandler
);
246 /* Load the dedicated server stuff */
247 _is_network_server
= true;
248 _network_dedicated
= true;
249 _current_company
= _local_company
= COMPANY_SPECTATOR
;
251 /* If SwitchMode is SM_LOAD_GAME, it means that the user used the '-g' options */
252 if (_switch_mode
!= SM_LOAD_GAME
) {
253 StartNewGameWithoutGUI(GENERATE_NEW_SEED
);
255 /* First we need to test if the savegame can be loaded, else we will end up playing the
257 if (SaveOrLoad(_file_to_saveload
.name
, _file_to_saveload
.file_op
, _file_to_saveload
.detail_ftype
, BASE_DIR
) == SL_ERROR
) {
258 /* Loading failed, pop out.. */
259 Debug(net
, 0, "Loading requested map failed; closing server.");
262 /* We can load this game, so go ahead */
263 _switch_mode
= SM_LOAD_GAME
;
267 this->is_game_threaded
= false;
269 /* Done loading, start game! */
271 while (!_exit_game
) {
272 if (!_dedicated_forks
) DedicatedHandleKeyInput();
273 this->DrainCommandQueue();
275 ChangeGameSpeed(_ddc_fastforward
);
277 this->SleepTillNextTick();