OpenTTD Source  1.11.2
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 "../window_func.h"
25 #include "dedicated_v.h"
26 
27 #ifdef __OS2__
28 # include <sys/time.h> /* gettimeofday */
29 # include <sys/types.h>
30 # include <unistd.h>
31 # include <conio.h>
32 
33 # define INCL_DOS
34 # include <os2.h>
35 
36 # define STDIN 0 /* file descriptor for standard input */
37 
42 static void OS2_SwitchToConsoleMode()
43 {
44  PPIB pib;
45  PTIB tib;
46 
47  DosGetInfoBlocks(&tib, &pib);
48 
49  /* Change flag from PM to VIO */
50  pib->pib_ultype = 3;
51 }
52 #endif
53 
54 #if defined(UNIX)
55 # include <sys/time.h> /* gettimeofday */
56 # include <sys/types.h>
57 # include <unistd.h>
58 # include <signal.h>
59 # define STDIN 0 /* file descriptor for standard input */
60 
61 /* Signal handlers */
62 static void DedicatedSignalHandler(int sig)
63 {
64  if (_game_mode == GM_NORMAL && _settings_client.gui.autosave_on_exit) DoExitSave();
65  _exit_game = true;
66  signal(sig, DedicatedSignalHandler);
67 }
68 #endif
69 
70 #if defined(_WIN32)
71 # include <windows.h> /* GetTickCount */
72 # include <conio.h>
73 # include <time.h>
74 # include <tchar.h>
75 # include "../os/windows/win32.h"
76 
77 static HANDLE _hInputReady, _hWaitForInputHandling;
78 static HANDLE _hThread; // Thread to close
79 static char _win_console_thread_buffer[200];
80 
81 /* Windows Console thread. Just loop and signal when input has been received */
82 static void WINAPI CheckForConsoleInput()
83 {
84  SetCurrentThreadName("ottd:win-console");
85 
86  DWORD nb;
87  HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
88  for (;;) {
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';
92 
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);
97  }
98 }
99 
100 static void CreateWindowsConsoleThread()
101 {
102  DWORD dwThreadId;
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!");
107 
108  _hThread = CreateThread(nullptr, 0, (LPTHREAD_START_ROUTINE)CheckForConsoleInput, nullptr, 0, &dwThreadId);
109  if (_hThread == nullptr) usererror("Cannot create console thread!");
110 
111  DEBUG(driver, 2, "Windows console thread started");
112 }
113 
114 static void CloseWindowsConsoleThread()
115 {
116  CloseHandle(_hThread);
117  CloseHandle(_hInputReady);
118  CloseHandle(_hWaitForInputHandling);
119  DEBUG(driver, 2, "Windows console thread shut down");
120 }
121 
122 #endif
123 
124 #include "../safeguards.h"
125 
126 
127 static void *_dedicated_video_mem;
128 
129 /* Whether a fork has been done. */
130 bool _dedicated_forks;
131 
132 extern bool SafeLoad(const std::string &filename, SaveLoadOperation fop, DetailedFileType dft, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf = nullptr);
133 
134 static FVideoDriver_Dedicated iFVideoDriver_Dedicated;
135 
136 
137 const char *VideoDriver_Dedicated::Start(const StringList &parm)
138 {
139  this->UpdateAutoResolution();
140 
142  _dedicated_video_mem = (bpp == 0) ? nullptr : MallocT<byte>(_cur_resolution.width * _cur_resolution.height * (bpp / 8));
143 
144  _screen.width = _screen.pitch = _cur_resolution.width;
145  _screen.height = _cur_resolution.height;
146  _screen.dst_ptr = _dedicated_video_mem;
147  ScreenSizeChanged();
149 
150 #if defined(_WIN32)
151  /* For win32 we need to allocate a console (debug mode does the same) */
152  CreateConsole();
153  CreateWindowsConsoleThread();
154  SetConsoleTitle(L"OpenTTD Dedicated Server");
155 #endif
156 
157 #ifdef _MSC_VER
158  /* Disable the MSVC assertion message box. */
159  _set_error_mode(_OUT_TO_STDERR);
160 #endif
161 
162 #ifdef __OS2__
163  /* For OS/2 we also need to switch to console mode instead of PM mode */
164  OS2_SwitchToConsoleMode();
165 #endif
166 
167  DEBUG(driver, 1, "Loading dedicated server");
168  return nullptr;
169 }
170 
172 {
173 #ifdef _WIN32
174  CloseWindowsConsoleThread();
175 #endif
176  free(_dedicated_video_mem);
177 }
178 
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; }
182 
183 #if defined(UNIX) || defined(__OS2__)
184 static bool InputWaiting()
185 {
186  struct timeval tv;
187  fd_set readfds;
188 
189  tv.tv_sec = 0;
190  tv.tv_usec = 1;
191 
192  FD_ZERO(&readfds);
193  FD_SET(STDIN, &readfds);
194 
195  /* don't care about writefds and exceptfds: */
196  return select(STDIN + 1, &readfds, nullptr, nullptr, &tv) > 0;
197 }
198 
199 #else
200 
201 static bool InputWaiting()
202 {
203  return WaitForSingleObject(_hInputReady, 1) == WAIT_OBJECT_0;
204 }
205 
206 #endif
207 
208 static void DedicatedHandleKeyInput()
209 {
210  static char input_line[1024] = "";
211 
212  if (!InputWaiting()) return;
213 
214  if (_exit_game) return;
215 
216 #if defined(UNIX) || defined(__OS2__)
217  if (fgets(input_line, lengthof(input_line), stdin) == nullptr) return;
218 #else
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);
223 #endif
224 
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)) {
228  *c = '\0';
229  break;
230  }
231  }
232  str_validate(input_line, lastof(input_line));
233 
234  IConsoleCmdExec(input_line); // execute command
235 }
236 
238 {
239  /* Signal handlers */
240 #if defined(UNIX)
241  signal(SIGTERM, DedicatedSignalHandler);
242  signal(SIGINT, DedicatedSignalHandler);
243  signal(SIGQUIT, DedicatedSignalHandler);
244 #endif
245 
246  /* Load the dedicated server stuff */
247  _is_network_server = true;
248  _network_dedicated = true;
250 
251  /* If SwitchMode is SM_LOAD_GAME, it means that the user used the '-g' options */
252  if (_switch_mode != SM_LOAD_GAME) {
254  } else {
255  /* First we need to test if the savegame can be loaded, else we will end up playing the
256  * intro game... */
258  /* Loading failed, pop out.. */
259  DEBUG(net, 0, "Loading requested map failed, aborting");
260  return;
261  } else {
262  /* We can load this game, so go ahead */
264  }
265  }
266 
267  this->is_game_threaded = false;
268 
269  /* Done loading, start game! */
270 
271  while (!_exit_game) {
272  if (!_dedicated_forks) DedicatedHandleKeyInput();
273 
274  ChangeGameSpeed(_ddc_fastforward);
275  this->Tick();
276  this->SleepTillNextTick();
277  }
278 }
VideoDriver::Tick
void Tick()
Give the video-driver a tick.
Definition: video_driver.cpp:100
usererror
void CDECL usererror(const char *s,...)
Error handling for fatal user errors.
Definition: openttd.cpp:103
SM_LOAD_GAME
@ SM_LOAD_GAME
Load game, Play Scenario.
Definition: openttd.h:30
str_validate
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:255
DoExitSave
void DoExitSave()
Do a save when exiting the game (_settings_client.gui.autosave_on_exit)
Definition: saveload.cpp:2851
GUISettings::autosave_on_exit
bool autosave_on_exit
save an autosave when you quit the game, but do not ask "Do you really want to quit?...
Definition: settings_type.h:124
SaveOrLoad
SaveOrLoadResult SaveOrLoad(const std::string &filename, SaveLoadOperation fop, DetailedFileType dft, Subdirectory sb, bool threaded)
Main Save or Load function where the high-level saveload functions are handled.
Definition: saveload.cpp:2764
SaveLoadOperation
SaveLoadOperation
Operation performed on the file.
Definition: fileio_type.h:47
FileToSaveLoad::name
std::string name
Name of the file.
Definition: saveload.h:344
Blitter::GetScreenDepth
virtual uint8 GetScreenDepth()=0
Get the screen depth this blitter works for.
_settings_client
ClientSettings _settings_client
The current settings for this game.
Definition: settings.cpp:79
SetCurrentThreadName
void SetCurrentThreadName(const char *)
Name the thread this function is called on for the debugger.
Definition: os2.cpp:215
SafeLoad
bool SafeLoad(const std::string &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:954
GENERATE_NEW_SEED
static const uint32 GENERATE_NEW_SEED
Create a new random seed.
Definition: genworld.h:24
dedicated_v.h
BASE_DIR
@ BASE_DIR
Base directory for all subdirectories.
Definition: fileio_type.h:109
DEBUG
#define DEBUG(name, level,...)
Output a line of debugging information.
Definition: debug.h:35
Blitter::PostResize
virtual void PostResize()
Post resize event.
Definition: base.hpp:209
FVideoDriver_Dedicated
Factory for the dedicated server video driver.
Definition: dedicated_v.h:34
BlitterFactory::GetCurrentBlitter
static Blitter * GetCurrentBlitter()
Get the current active blitter (always set by calling SelectBlitter).
Definition: factory.hpp:141
_local_company
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
Definition: company_cmd.cpp:46
StringList
std::vector< std::string > StringList
Type for a list of strings.
Definition: string_type.h:58
VideoDriver_Dedicated::MakeDirty
void MakeDirty(int left, int top, int width, int height) override
Mark a particular area dirty.
Definition: dedicated_v.cpp:179
_network_dedicated
bool _network_dedicated
are we a dedicated server?
Definition: network.cpp:55
GameMode
GameMode
Mode which defines the state of the game.
Definition: openttd.h:16
StartNewGameWithoutGUI
void StartNewGameWithoutGUI(uint32 seed)
Start a normal game without the GUI.
Definition: genworld_gui.cpp:1021
VideoDriver_Dedicated::Start
const char * Start(const StringList &param) override
Start this driver.
Definition: dedicated_v.cpp:137
_switch_mode
SwitchMode _switch_mode
The next mainloop command.
Definition: gfx.cpp:46
_ddc_fastforward
#define _ddc_fastforward
Helper variable to make the dedicated server go fast until the (first) join.
Definition: network_internal.h:47
_current_company
CompanyID _current_company
Company currently doing an action.
Definition: company_cmd.cpp:47
DetailedFileType
DetailedFileType
Kinds of files in each AbstractFileType.
Definition: fileio_type.h:28
VideoDriver_Dedicated::ChangeResolution
bool ChangeResolution(int w, int h) override
Change the resolution of the window.
Definition: dedicated_v.cpp:180
VideoDriver::UpdateAutoResolution
void UpdateAutoResolution()
Apply resolution auto-detection and clamp to sensible defaults.
Definition: video_driver.hpp:239
COMPANY_SPECTATOR
@ COMPANY_SPECTATOR
The client is spectating.
Definition: company_type.h:35
_file_to_saveload
FileToSaveLoad _file_to_saveload
File to save or load in the openttd loop.
Definition: saveload.cpp:62
Subdirectory
Subdirectory
The different kinds of subdirectories OpenTTD uses.
Definition: fileio_type.h:108
LoadFilter
Interface for filtering a savegame till it is loaded.
Definition: saveload_filter.h:14
lengthof
#define lengthof(x)
Return the length of an fixed size array.
Definition: stdafx.h:369
VideoDriver::SleepTillNextTick
void SleepTillNextTick()
Sleep till the next tick is about to happen.
Definition: video_driver.cpp:162
IConsoleCmdExec
void IConsoleCmdExec(const char *cmdstr, const uint recurse_count)
Execute a given command passed to us.
Definition: console.cpp:407
VideoDriver_Dedicated::MainLoop
void MainLoop() override
Perform the actual drawing.
Definition: dedicated_v.cpp:237
VideoDriver_Dedicated::Stop
void Stop() override
Stop this driver.
Definition: dedicated_v.cpp:171
SL_ERROR
@ SL_ERROR
error that was caught before internal structures were modified
Definition: saveload.h:335
FileToSaveLoad::detail_ftype
DetailedFileType detail_ftype
Concrete file type (PNG, BMP, old save, etc).
Definition: saveload.h:342
strecpy
char * strecpy(char *dst, const char *src, const char *last)
Copies characters from one buffer to another.
Definition: string.cpp:112
free
static void free(const void *ptr)
Version of the standard free that accepts const pointers.
Definition: stdafx.h:456
lastof
#define lastof(x)
Get the last element of an fixed size array.
Definition: stdafx.h:385
VideoDriver_Dedicated::ToggleFullscreen
bool ToggleFullscreen(bool fullscreen) override
Change the full screen setting.
Definition: dedicated_v.cpp:181
_cur_resolution
Dimension _cur_resolution
The current resolution.
Definition: driver.cpp:25
_is_network_server
bool _is_network_server
Does this client wants to be a network-server?
Definition: network.cpp:56
ClientSettings::gui
GUISettings gui
settings related to the GUI
Definition: settings_type.h:581
FileToSaveLoad::file_op
SaveLoadOperation file_op
File operation to perform.
Definition: saveload.h:341