OpenTTD
dedicated_v.cpp
Go to the documentation of this file.
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  */
7 
10 #include "../stdafx.h"
11 
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"
25 
26 #ifdef __OS2__
27 # include <sys/time.h> /* gettimeofday */
28 # include <sys/types.h>
29 # include <unistd.h>
30 # include <conio.h>
31 
32 # define INCL_DOS
33 # include <os2.h>
34 
35 # define STDIN 0 /* file descriptor for standard input */
36 
41 static void OS2_SwitchToConsoleMode()
42 {
43  PPIB pib;
44  PTIB tib;
45 
46  DosGetInfoBlocks(&tib, &pib);
47 
48  /* Change flag from PM to VIO */
49  pib->pib_ultype = 3;
50 }
51 #endif
52 
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 */
59 
60 /* Signal handlers */
61 static void DedicatedSignalHandler(int sig)
62 {
63  if (_game_mode == GM_NORMAL && _settings_client.gui.autosave_on_exit) DoExitSave();
64  _exit_game = true;
65  signal(sig, DedicatedSignalHandler);
66 }
67 #endif
68 
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"
75 
76 static HANDLE _hInputReady, _hWaitForInputHandling;
77 static HANDLE _hThread; // Thread to close
78 static char _win_console_thread_buffer[200];
79 
80 /* Windows Console thread. Just loop and signal when input has been received */
81 static void WINAPI CheckForConsoleInput()
82 {
83  SetCurrentThreadName("ottd:win-console");
84 
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';
91 
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);
96  }
97 }
98 
99 static void CreateWindowsConsoleThread()
100 {
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!");
106 
107  _hThread = CreateThread(nullptr, 0, (LPTHREAD_START_ROUTINE)CheckForConsoleInput, nullptr, 0, &dwThreadId);
108  if (_hThread == nullptr) usererror("Cannot create console thread!");
109 
110  DEBUG(driver, 2, "Windows console thread started");
111 }
112 
113 static void CloseWindowsConsoleThread()
114 {
115  CloseHandle(_hThread);
116  CloseHandle(_hInputReady);
117  CloseHandle(_hWaitForInputHandling);
118  DEBUG(driver, 2, "Windows console thread shut down");
119 }
120 
121 #endif
122 
123 #include "../safeguards.h"
124 
125 
126 static void *_dedicated_video_mem;
127 
128 /* Whether a fork has been done. */
129 bool _dedicated_forks;
130 
131 extern bool SafeLoad(const char *filename, SaveLoadOperation fop, DetailedFileType dft, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf = nullptr);
132 
133 static FVideoDriver_Dedicated iFVideoDriver_Dedicated;
134 
135 
136 const char *VideoDriver_Dedicated::Start(const char * const *parm)
137 {
139  _dedicated_video_mem = (bpp == 0) ? nullptr : MallocT<byte>(_cur_resolution.width * _cur_resolution.height * (bpp / 8));
140 
141  _screen.width = _screen.pitch = _cur_resolution.width;
142  _screen.height = _cur_resolution.height;
143  _screen.dst_ptr = _dedicated_video_mem;
144  ScreenSizeChanged();
146 
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
153 
154 #ifdef _MSC_VER
155  /* Disable the MSVC assertion message box. */
156  _set_error_mode(_OUT_TO_STDERR);
157 #endif
158 
159 #ifdef __OS2__
160  /* For OS/2 we also need to switch to console mode instead of PM mode */
161  OS2_SwitchToConsoleMode();
162 #endif
163 
164  DEBUG(driver, 1, "Loading dedicated server");
165  return nullptr;
166 }
167 
169 {
170 #ifdef _WIN32
171  CloseWindowsConsoleThread();
172 #endif
173  free(_dedicated_video_mem);
174 }
175 
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; }
179 
180 #if defined(UNIX) || defined(__OS2__)
181 static bool InputWaiting()
182 {
183  struct timeval tv;
184  fd_set readfds;
185 
186  tv.tv_sec = 0;
187  tv.tv_usec = 1;
188 
189  FD_ZERO(&readfds);
190  FD_SET(STDIN, &readfds);
191 
192  /* don't care about writefds and exceptfds: */
193  return select(STDIN + 1, &readfds, nullptr, nullptr, &tv) > 0;
194 }
195 
196 static uint32 GetTime()
197 {
198  struct timeval tim;
199 
200  gettimeofday(&tim, nullptr);
201  return tim.tv_usec / 1000 + tim.tv_sec * 1000;
202 }
203 
204 #else
205 
206 static bool InputWaiting()
207 {
208  return WaitForSingleObject(_hInputReady, 1) == WAIT_OBJECT_0;
209 }
210 
211 static uint32 GetTime()
212 {
213  return GetTickCount();
214 }
215 
216 #endif
217 
218 static void DedicatedHandleKeyInput()
219 {
220  static char input_line[1024] = "";
221 
222  if (!InputWaiting()) return;
223 
224  if (_exit_game) return;
225 
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
234 
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;
240  }
241  }
242  str_validate(input_line, lastof(input_line));
243 
244  IConsoleCmdExec(input_line); // execute command
245 }
246 
248 {
249  uint32 cur_ticks = GetTime();
250  uint32 next_tick = cur_ticks + MILLISECONDS_PER_TICK;
251 
252  /* Signal handlers */
253 #if defined(UNIX)
254  signal(SIGTERM, DedicatedSignalHandler);
255  signal(SIGINT, DedicatedSignalHandler);
256  signal(SIGQUIT, DedicatedSignalHandler);
257 #endif
258 
259  /* Load the dedicated server stuff */
260  _is_network_server = true;
261  _network_dedicated = true;
263 
264  /* If SwitchMode is SM_LOAD_GAME, it means that the user used the '-g' options */
265  if (_switch_mode != SM_LOAD_GAME) {
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... */
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);
280  }
281  }
282 
283  /* Done loading, start game! */
284 
285  if (!_networking) {
286  DEBUG(net, 0, "Dedicated server could not be started, aborting");
287  return;
288  }
289 
290  while (!_exit_game) {
291  uint32 prev_cur_ticks = cur_ticks; // to check for wrapping
292  InteractiveRandom(); // randomness
293 
294  if (!_dedicated_forks) DedicatedHandleKeyInput();
295 
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;
300 
301  GameLoop();
302  UpdateWindows();
303  }
304 
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);
313  }
314  }
315  }
316 }
bool _networking
are we in networking mode?
Definition: network.cpp:52
uint32 _realtime_tick
The real time in the game.
Definition: debug.cpp:48
Subdirectory
The different kinds of subdirectories OpenTTD uses.
Definition: fileio_type.h:108
void MainLoop() override
Perform the actual drawing.
Load game, Play Scenario.
Definition: openttd.h:29
void SetCurrentThreadName(const char *)
Name the thread this function is called on for the debugger.
Definition: os2.cpp:215
FileToSaveLoad _file_to_saveload
File to save or load in the openttd loop.
Definition: saveload.cpp:58
bool ToggleFullscreen(bool fullscreen) override
Change the full screen setting.
#define _ddc_fastforward
Helper variable to make the dedicated server go fast until the (first) join.
void CSleep(int milliseconds)
Sleep on the current thread for a defined time.
Definition: thread.h:25
void Stop() override
Stop this driver.
Dimension _cur_resolution
The current resolution.
Definition: driver.cpp:21
void DoExitSave()
Do a save when exiting the game (_settings_client.gui.autosave_on_exit)
Definition: saveload.cpp:2802
#define lastof(x)
Get the last element of an fixed size array.
Definition: depend.cpp:48
virtual void PostResize()
Post resize event.
Definition: base.hpp:201
bool SafeLoad(const char *filename, SaveLoadOperation fop, DetailedFileType dft, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf=nullptr)
Load the specified savegame but on error do different things.
Definition: openttd.cpp:1001
static const uint32 GENERATE_NEW_SEED
Create a new random seed.
Definition: genworld.h:24
bool _network_dedicated
are we a dedicated server?
Definition: network.cpp:55
Interface for filtering a savegame till it is loaded.
void StartNewGameWithoutGUI(uint32 seed)
Start a normal game without the GUI.
bool _is_network_server
Does this client wants to be a network-server?
Definition: network.cpp:56
The client is spectating.
Definition: company_type.h:35
void str_validate(char *str, const char *last, StringValidationSettings settings)
Scans the string for valid characters and if it finds invalid ones, replaces them with a question mar...
Definition: string.cpp:194
GameMode
Mode which defines the state of the game.
Definition: openttd.h:16
bool ChangeResolution(int w, int h) override
Change the resolution of the window.
void IConsoleCmdExec(const char *cmdstr)
Execute a given command passed to us.
Definition: console.cpp:401
ClientSettings _settings_client
The current settings for this game.
Definition: settings.cpp:78
void CDECL usererror(const char *s,...)
Error handling for fatal user errors.
Definition: openttd.cpp:92
static const uint MILLISECONDS_PER_TICK
The number of milliseconds per game tick.
Definition: gfx_type.h:305
Base directory for all subdirectories.
Definition: fileio_type.h:109
bool autosave_on_exit
save an autosave when you quit the game, but do not ask "Do you really want to quit?"
#define lengthof(x)
Return the length of an fixed size array.
Definition: depend.cpp:40
static Blitter * GetCurrentBlitter()
Get the current active blitter (always set by calling SelectBlitter).
Definition: factory.hpp:145
PauseMode _pause_mode
The current pause mode.
Definition: gfx.cpp:47
SaveLoadOperation
Operation performed on the file.
Definition: fileio_type.h:47
#define DEBUG(name, level,...)
Output a line of debugging information.
Definition: debug.h:35
bool HasClients()
Return whether there is any client connected or trying to connect at all.
Definition: network.cpp:100
GUISettings gui
settings related to the GUI
char * strecpy(char *dst, const char *src, const char *last)
Copies characters from one buffer to another.
Definition: depend.cpp:66
SwitchMode _switch_mode
The next mainloop command.
Definition: gfx.cpp:46
Base for the dedicated video driver.
Factory for the dedicated server video driver.
Definition: dedicated_v.h:34
char name[MAX_PATH]
Name of the file.
Definition: saveload.h:320
SaveLoadOperation file_op
File operation to perform.
Definition: saveload.h:317
CompanyID _current_company
Company currently doing an action.
Definition: company_cmd.cpp:45
virtual uint8 GetScreenDepth()=0
Get the screen depth this blitter works for.
static void free(const void *ptr)
Version of the standard free that accepts const pointers.
Definition: depend.cpp:129
void MakeDirty(int left, int top, int width, int height) override
Mark a particular area dirty.
DetailedFileType detail_ftype
Concrete file type (PNG, BMP, old save, etc).
Definition: saveload.h:318
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
Definition: company_cmd.cpp:44
DetailedFileType
Kinds of files in each AbstractFileType.
Definition: fileio_type.h:28
const char * Start(const char *const *param) override
Start this driver.
void UpdateWindows()
Update the continuously changing contents of the windows, such as the viewports.
Definition: window.cpp:3128