OpenTTD
dedicated_v.cpp
Go to the documentation of this file.
1 /* $Id$ */
2 
3 /*
4  * This file is part of OpenTTD.
5  * 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.
6  * 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.
7  * 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  */
9 
12 #include "../stdafx.h"
13 
14 #include "../gfx_func.h"
15 #include "../network/network.h"
16 #include "../network/network_internal.h"
17 #include "../console_func.h"
18 #include "../genworld.h"
19 #include "../fileio_type.h"
20 #include "../fios.h"
21 #include "../blitter/factory.hpp"
22 #include "../company_func.h"
23 #include "../core/random_func.hpp"
24 #include "../saveload/saveload.h"
25 #include "../thread.h"
26 #include "dedicated_v.h"
27 
28 #ifdef __OS2__
29 # include <sys/time.h> /* gettimeofday */
30 # include <sys/types.h>
31 # include <unistd.h>
32 # include <conio.h>
33 
34 # define INCL_DOS
35 # include <os2.h>
36 
37 # define STDIN 0 /* file descriptor for standard input */
38 
43 static void OS2_SwitchToConsoleMode()
44 {
45  PPIB pib;
46  PTIB tib;
47 
48  DosGetInfoBlocks(&tib, &pib);
49 
50  /* Change flag from PM to VIO */
51  pib->pib_ultype = 3;
52 }
53 #endif
54 
55 #if defined(UNIX)
56 # include <sys/time.h> /* gettimeofday */
57 # include <sys/types.h>
58 # include <unistd.h>
59 # include <signal.h>
60 # define STDIN 0 /* file descriptor for standard input */
61 
62 /* Signal handlers */
63 static void DedicatedSignalHandler(int sig)
64 {
65  if (_game_mode == GM_NORMAL && _settings_client.gui.autosave_on_exit) DoExitSave();
66  _exit_game = true;
67  signal(sig, DedicatedSignalHandler);
68 }
69 #endif
70 
71 #if defined(_WIN32)
72 # include <windows.h> /* GetTickCount */
73 # include <conio.h>
74 # include <time.h>
75 # include <tchar.h>
76 # include "../os/windows/win32.h"
77 
78 static HANDLE _hInputReady, _hWaitForInputHandling;
79 static HANDLE _hThread; // Thread to close
80 static char _win_console_thread_buffer[200];
81 
82 /* Windows Console thread. Just loop and signal when input has been received */
83 static void WINAPI CheckForConsoleInput()
84 {
85  SetCurrentThreadName("ottd:win-console");
86 
87  DWORD nb;
88  HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
89  for (;;) {
90  ReadFile(hStdin, _win_console_thread_buffer, lengthof(_win_console_thread_buffer), &nb, nullptr);
91  if (nb >= lengthof(_win_console_thread_buffer)) nb = lengthof(_win_console_thread_buffer) - 1;
92  _win_console_thread_buffer[nb] = '\0';
93 
94  /* Signal input waiting that input is read and wait for it being handled
95  * SignalObjectAndWait() should be used here, but it's unsupported in Win98< */
96  SetEvent(_hInputReady);
97  WaitForSingleObject(_hWaitForInputHandling, INFINITE);
98  }
99 }
100 
101 static void CreateWindowsConsoleThread()
102 {
103  DWORD dwThreadId;
104  /* Create event to signal when console input is ready */
105  _hInputReady = CreateEvent(nullptr, false, false, nullptr);
106  _hWaitForInputHandling = CreateEvent(nullptr, false, false, nullptr);
107  if (_hInputReady == nullptr || _hWaitForInputHandling == nullptr) usererror("Cannot create console event!");
108 
109  _hThread = CreateThread(nullptr, 0, (LPTHREAD_START_ROUTINE)CheckForConsoleInput, nullptr, 0, &dwThreadId);
110  if (_hThread == nullptr) usererror("Cannot create console thread!");
111 
112  DEBUG(driver, 2, "Windows console thread started");
113 }
114 
115 static void CloseWindowsConsoleThread()
116 {
117  CloseHandle(_hThread);
118  CloseHandle(_hInputReady);
119  CloseHandle(_hWaitForInputHandling);
120  DEBUG(driver, 2, "Windows console thread shut down");
121 }
122 
123 #endif
124 
125 #include "../safeguards.h"
126 
127 
128 static void *_dedicated_video_mem;
129 
130 /* Whether a fork has been done. */
131 bool _dedicated_forks;
132 
133 extern bool SafeLoad(const char *filename, SaveLoadOperation fop, DetailedFileType dft, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf = nullptr);
134 
135 static FVideoDriver_Dedicated iFVideoDriver_Dedicated;
136 
137 
138 const char *VideoDriver_Dedicated::Start(const char * const *parm)
139 {
141  _dedicated_video_mem = (bpp == 0) ? nullptr : MallocT<byte>(_cur_resolution.width * _cur_resolution.height * (bpp / 8));
142 
143  _screen.width = _screen.pitch = _cur_resolution.width;
144  _screen.height = _cur_resolution.height;
145  _screen.dst_ptr = _dedicated_video_mem;
146  ScreenSizeChanged();
148 
149 #if defined(_WIN32)
150  /* For win32 we need to allocate a console (debug mode does the same) */
151  CreateConsole();
152  CreateWindowsConsoleThread();
153  SetConsoleTitle(_T("OpenTTD Dedicated Server"));
154 #endif
155 
156 #ifdef _MSC_VER
157  /* Disable the MSVC assertion message box. */
158  _set_error_mode(_OUT_TO_STDERR);
159 #endif
160 
161 #ifdef __OS2__
162  /* For OS/2 we also need to switch to console mode instead of PM mode */
163  OS2_SwitchToConsoleMode();
164 #endif
165 
166  DEBUG(driver, 1, "Loading dedicated server");
167  return nullptr;
168 }
169 
171 {
172 #ifdef _WIN32
173  CloseWindowsConsoleThread();
174 #endif
175  free(_dedicated_video_mem);
176 }
177 
178 void VideoDriver_Dedicated::MakeDirty(int left, int top, int width, int height) {}
179 bool VideoDriver_Dedicated::ChangeResolution(int w, int h) { return false; }
180 bool VideoDriver_Dedicated::ToggleFullscreen(bool fs) { return false; }
181 
182 #if defined(UNIX) || defined(__OS2__)
183 static bool InputWaiting()
184 {
185  struct timeval tv;
186  fd_set readfds;
187 
188  tv.tv_sec = 0;
189  tv.tv_usec = 1;
190 
191  FD_ZERO(&readfds);
192  FD_SET(STDIN, &readfds);
193 
194  /* don't care about writefds and exceptfds: */
195  return select(STDIN + 1, &readfds, nullptr, nullptr, &tv) > 0;
196 }
197 
198 static uint32 GetTime()
199 {
200  struct timeval tim;
201 
202  gettimeofday(&tim, nullptr);
203  return tim.tv_usec / 1000 + tim.tv_sec * 1000;
204 }
205 
206 #else
207 
208 static bool InputWaiting()
209 {
210  return WaitForSingleObject(_hInputReady, 1) == WAIT_OBJECT_0;
211 }
212 
213 static uint32 GetTime()
214 {
215  return GetTickCount();
216 }
217 
218 #endif
219 
220 static void DedicatedHandleKeyInput()
221 {
222  static char input_line[1024] = "";
223 
224  if (!InputWaiting()) return;
225 
226  if (_exit_game) return;
227 
228 #if defined(UNIX) || defined(__OS2__)
229  if (fgets(input_line, lengthof(input_line), stdin) == nullptr) return;
230 #else
231  /* Handle console input, and signal console thread, it can accept input again */
232  assert_compile(lengthof(_win_console_thread_buffer) <= lengthof(input_line));
233  strecpy(input_line, _win_console_thread_buffer, lastof(input_line));
234  SetEvent(_hWaitForInputHandling);
235 #endif
236 
237  /* Remove trailing \r or \n */
238  for (char *c = input_line; *c != '\0'; c++) {
239  if (*c == '\n' || *c == '\r' || c == lastof(input_line)) {
240  *c = '\0';
241  break;
242  }
243  }
244  str_validate(input_line, lastof(input_line));
245 
246  IConsoleCmdExec(input_line); // execute command
247 }
248 
250 {
251  uint32 cur_ticks = GetTime();
252  uint32 next_tick = cur_ticks + MILLISECONDS_PER_TICK;
253 
254  /* Signal handlers */
255 #if defined(UNIX)
256  signal(SIGTERM, DedicatedSignalHandler);
257  signal(SIGINT, DedicatedSignalHandler);
258  signal(SIGQUIT, DedicatedSignalHandler);
259 #endif
260 
261  /* Load the dedicated server stuff */
262  _is_network_server = true;
263  _network_dedicated = true;
265 
266  /* If SwitchMode is SM_LOAD_GAME, it means that the user used the '-g' options */
267  if (_switch_mode != SM_LOAD_GAME) {
269  SwitchToMode(_switch_mode);
270  _switch_mode = SM_NONE;
271  } else {
272  _switch_mode = SM_NONE;
273  /* First we need to test if the savegame can be loaded, else we will end up playing the
274  * intro game... */
276  /* Loading failed, pop out.. */
277  DEBUG(net, 0, "Loading requested map failed, aborting");
278  _networking = false;
279  } else {
280  /* We can load this game, so go ahead */
281  SwitchToMode(SM_LOAD_GAME);
282  }
283  }
284 
285  /* Done loading, start game! */
286 
287  if (!_networking) {
288  DEBUG(net, 0, "Dedicated server could not be started, aborting");
289  return;
290  }
291 
292  while (!_exit_game) {
293  uint32 prev_cur_ticks = cur_ticks; // to check for wrapping
294  InteractiveRandom(); // randomness
295 
296  if (!_dedicated_forks) DedicatedHandleKeyInput();
297 
298  cur_ticks = GetTime();
299  _realtime_tick += cur_ticks - prev_cur_ticks;
300  if (cur_ticks >= next_tick || cur_ticks < prev_cur_ticks || _ddc_fastforward) {
301  next_tick = cur_ticks + MILLISECONDS_PER_TICK;
302 
303  GameLoop();
304  UpdateWindows();
305  }
306 
307  /* Don't sleep when fast forwarding (for desync debugging) */
308  if (!_ddc_fastforward) {
309  /* Sleep longer on a dedicated server, if the game is paused and no clients connected.
310  * That can allow the CPU to better use deep sleep states. */
311  if (_pause_mode != 0 && !HasClients()) {
312  CSleep(100);
313  } else {
314  CSleep(1);
315  }
316  }
317  }
318 }
bool _networking
are we in networking mode?
Definition: network.cpp:54
uint32 _realtime_tick
The real time in the game.
Definition: debug.cpp:50
Subdirectory
The different kinds of subdirectories OpenTTD uses.
Definition: fileio_type.h:110
void MainLoop() override
Perform the actual drawing.
Load game, Play Scenario.
Definition: openttd.h:31
void SetCurrentThreadName(const char *)
Name the thread this function is called on for the debugger.
Definition: os2.cpp:217
FileToSaveLoad _file_to_saveload
File to save or load in the openttd loop.
Definition: saveload.cpp:60
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:27
void Stop() override
Stop this driver.
Dimension _cur_resolution
The current resolution.
Definition: driver.cpp:23
void DoExitSave()
Do a save when exiting the game (_settings_client.gui.autosave_on_exit)
Definition: saveload.cpp:2804
#define lastof(x)
Get the last element of an fixed size array.
Definition: depend.cpp:50
virtual void PostResize()
Post resize event.
Definition: base.hpp:203
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:1003
static const uint32 GENERATE_NEW_SEED
Create a new random seed.
Definition: genworld.h:26
bool _network_dedicated
are we a dedicated server?
Definition: network.cpp:57
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:58
The client is spectating.
Definition: company_type.h:37
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:196
GameMode
Mode which defines the state of the game.
Definition: openttd.h:18
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:403
ClientSettings _settings_client
The current settings for this game.
Definition: settings.cpp:80
void CDECL usererror(const char *s,...)
Error handling for fatal user errors.
Definition: openttd.cpp:94
static const uint MILLISECONDS_PER_TICK
The number of milliseconds per game tick.
Definition: gfx_type.h:306
Base directory for all subdirectories.
Definition: fileio_type.h:111
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:42
static Blitter * GetCurrentBlitter()
Get the current active blitter (always set by calling SelectBlitter).
Definition: factory.hpp:147
PauseMode _pause_mode
The current pause mode.
Definition: gfx.cpp:49
SaveLoadOperation
Operation performed on the file.
Definition: fileio_type.h:49
#define DEBUG(name, level,...)
Output a line of debugging information.
Definition: debug.h:37
bool HasClients()
Return whether there is any client connected or trying to connect at all.
Definition: network.cpp:102
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:68
SwitchMode _switch_mode
The next mainloop command.
Definition: gfx.cpp:48
Base for the dedicated video driver.
Factory for the dedicated server video driver.
Definition: dedicated_v.h:36
char name[MAX_PATH]
Name of the file.
Definition: saveload.h:322
SaveLoadOperation file_op
File operation to perform.
Definition: saveload.h:319
CompanyID _current_company
Company currently doing an action.
Definition: company_cmd.cpp:47
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:131
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:320
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
Definition: company_cmd.cpp:46
DetailedFileType
Kinds of files in each AbstractFileType.
Definition: fileio_type.h:30
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:3112