dedicated_v.cpp

Go to the documentation of this file.
00001 /* $Id: dedicated_v.cpp 26543 2014-04-29 18:35:01Z frosch $ */
00002 
00003 /*
00004  * This file is part of OpenTTD.
00005  * 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.
00006  * 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.
00007  * 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/>.
00008  */
00009 
00012 #include "../stdafx.h"
00013 
00014 #ifdef ENABLE_NETWORK
00015 
00016 #include "../gfx_func.h"
00017 #include "../network/network.h"
00018 #include "../network/network_internal.h"
00019 #include "../console_func.h"
00020 #include "../genworld.h"
00021 #include "../fileio_type.h"
00022 #include "../fios.h"
00023 #include "../blitter/factory.hpp"
00024 #include "../company_func.h"
00025 #include "../core/random_func.hpp"
00026 #include "../saveload/saveload.h"
00027 #include "dedicated_v.h"
00028 
00029 #ifdef BEOS_NET_SERVER
00030 #include <net/socket.h>
00031 #endif
00032 
00033 #ifdef __OS2__
00034 # include <sys/time.h> /* gettimeofday */
00035 # include <sys/types.h>
00036 # include <unistd.h>
00037 # include <conio.h>
00038 
00039 # define INCL_DOS
00040 # include <os2.h>
00041 
00042 # define STDIN 0  /* file descriptor for standard input */
00043 
00048 static void OS2_SwitchToConsoleMode()
00049 {
00050   PPIB pib;
00051   PTIB tib;
00052 
00053   DosGetInfoBlocks(&tib, &pib);
00054 
00055   /* Change flag from PM to VIO */
00056   pib->pib_ultype = 3;
00057 }
00058 #endif
00059 
00060 #if defined(UNIX) || defined(PSP)
00061 # include <sys/time.h> /* gettimeofday */
00062 # include <sys/types.h>
00063 # include <unistd.h>
00064 # include <signal.h>
00065 # define STDIN 0  /* file descriptor for standard input */
00066 # if defined(PSP)
00067 #   include <sys/fd_set.h>
00068 #   include <sys/select.h>
00069 # endif /* PSP */
00070 
00071 /* Signal handlers */
00072 static void DedicatedSignalHandler(int sig)
00073 {
00074   if (_game_mode == GM_NORMAL && _settings_client.gui.autosave_on_exit) DoExitSave();
00075   _exit_game = true;
00076   signal(sig, DedicatedSignalHandler);
00077 }
00078 #endif
00079 
00080 #if defined(WIN32)
00081 # include <windows.h> /* GetTickCount */
00082 # if !defined(WINCE)
00083 #  include <conio.h>
00084 # endif
00085 # include <time.h>
00086 # include <tchar.h>
00087 static HANDLE _hInputReady, _hWaitForInputHandling;
00088 static HANDLE _hThread; // Thread to close
00089 static char _win_console_thread_buffer[200];
00090 
00091 /* Windows Console thread. Just loop and signal when input has been received */
00092 static void WINAPI CheckForConsoleInput()
00093 {
00094 #if defined(WINCE)
00095   /* WinCE doesn't support console stuff */
00096   return;
00097 #else
00098   DWORD nb;
00099   HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
00100   for (;;) {
00101     ReadFile(hStdin, _win_console_thread_buffer, lengthof(_win_console_thread_buffer), &nb, NULL);
00102     if (nb >= lengthof(_win_console_thread_buffer)) nb = lengthof(_win_console_thread_buffer) - 1;
00103     _win_console_thread_buffer[nb] = '\0';
00104 
00105     /* Signal input waiting that input is read and wait for it being handled
00106      * SignalObjectAndWait() should be used here, but it's unsupported in Win98< */
00107     SetEvent(_hInputReady);
00108     WaitForSingleObject(_hWaitForInputHandling, INFINITE);
00109   }
00110 #endif
00111 }
00112 
00113 static void CreateWindowsConsoleThread()
00114 {
00115   DWORD dwThreadId;
00116   /* Create event to signal when console input is ready */
00117   _hInputReady = CreateEvent(NULL, false, false, NULL);
00118   _hWaitForInputHandling = CreateEvent(NULL, false, false, NULL);
00119   if (_hInputReady == NULL || _hWaitForInputHandling == NULL) usererror("Cannot create console event!");
00120 
00121   _hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)CheckForConsoleInput, NULL, 0, &dwThreadId);
00122   if (_hThread == NULL) usererror("Cannot create console thread!");
00123 
00124   DEBUG(driver, 2, "Windows console thread started");
00125 }
00126 
00127 static void CloseWindowsConsoleThread()
00128 {
00129   CloseHandle(_hThread);
00130   CloseHandle(_hInputReady);
00131   CloseHandle(_hWaitForInputHandling);
00132   DEBUG(driver, 2, "Windows console thread shut down");
00133 }
00134 
00135 #endif
00136 
00137 
00138 static void *_dedicated_video_mem;
00139 
00140 /* Whether a fork has been done. */
00141 bool _dedicated_forks;
00142 
00143 extern bool SafeLoad(const char *filename, int mode, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf = NULL);
00144 
00145 static FVideoDriver_Dedicated iFVideoDriver_Dedicated;
00146 
00147 
00148 const char *VideoDriver_Dedicated::Start(const char * const *parm)
00149 {
00150   int bpp = BlitterFactory::GetCurrentBlitter()->GetScreenDepth();
00151   _dedicated_video_mem = (bpp == 0) ? NULL : MallocT<byte>(_cur_resolution.width * _cur_resolution.height * (bpp / 8));
00152 
00153   _screen.width  = _screen.pitch = _cur_resolution.width;
00154   _screen.height = _cur_resolution.height;
00155   _screen.dst_ptr = _dedicated_video_mem;
00156   ScreenSizeChanged();
00157   BlitterFactory::GetCurrentBlitter()->PostResize();
00158 
00159 #if defined(WINCE)
00160   /* WinCE doesn't support console stuff */
00161 #elif defined(WIN32)
00162   /* For win32 we need to allocate a console (debug mode does the same) */
00163   CreateConsole();
00164   CreateWindowsConsoleThread();
00165   SetConsoleTitle(_T("OpenTTD Dedicated Server"));
00166 #endif
00167 
00168 #ifdef _MSC_VER
00169   /* Disable the MSVC assertion message box. */
00170   _set_error_mode(_OUT_TO_STDERR);
00171 #endif
00172 
00173 #ifdef __OS2__
00174   /* For OS/2 we also need to switch to console mode instead of PM mode */
00175   OS2_SwitchToConsoleMode();
00176 #endif
00177 
00178   DEBUG(driver, 1, "Loading dedicated server");
00179   return NULL;
00180 }
00181 
00182 void VideoDriver_Dedicated::Stop()
00183 {
00184 #ifdef WIN32
00185   CloseWindowsConsoleThread();
00186 #endif
00187   free(_dedicated_video_mem);
00188 }
00189 
00190 void VideoDriver_Dedicated::MakeDirty(int left, int top, int width, int height) {}
00191 bool VideoDriver_Dedicated::ChangeResolution(int w, int h) { return false; }
00192 bool VideoDriver_Dedicated::ToggleFullscreen(bool fs) { return false; }
00193 
00194 #if defined(UNIX) || defined(__OS2__) || defined(PSP)
00195 static bool InputWaiting()
00196 {
00197   struct timeval tv;
00198   fd_set readfds;
00199 
00200   tv.tv_sec = 0;
00201   tv.tv_usec = 1;
00202 
00203   FD_ZERO(&readfds);
00204   FD_SET(STDIN, &readfds);
00205 
00206   /* don't care about writefds and exceptfds: */
00207   return select(STDIN + 1, &readfds, NULL, NULL, &tv) > 0;
00208 }
00209 
00210 static uint32 GetTime()
00211 {
00212   struct timeval tim;
00213 
00214   gettimeofday(&tim, NULL);
00215   return tim.tv_usec / 1000 + tim.tv_sec * 1000;
00216 }
00217 
00218 #else
00219 
00220 static bool InputWaiting()
00221 {
00222   return WaitForSingleObject(_hInputReady, 1) == WAIT_OBJECT_0;
00223 }
00224 
00225 static uint32 GetTime()
00226 {
00227   return GetTickCount();
00228 }
00229 
00230 #endif
00231 
00232 static void DedicatedHandleKeyInput()
00233 {
00234   static char input_line[1024] = "";
00235 
00236   if (!InputWaiting()) return;
00237 
00238   if (_exit_game) return;
00239 
00240 #if defined(UNIX) || defined(__OS2__) || defined(PSP)
00241   if (fgets(input_line, lengthof(input_line), stdin) == NULL) return;
00242 #else
00243   /* Handle console input, and signal console thread, it can accept input again */
00244   assert_compile(lengthof(_win_console_thread_buffer) <= lengthof(input_line));
00245   strecpy(input_line, _win_console_thread_buffer, lastof(input_line));
00246   SetEvent(_hWaitForInputHandling);
00247 #endif
00248 
00249   /* Remove trailing \r or \n */
00250   for (char *c = input_line; *c != '\0'; c++) {
00251     if (*c == '\n' || *c == '\r' || c == lastof(input_line)) {
00252       *c = '\0';
00253       break;
00254     }
00255   }
00256   str_validate(input_line, lastof(input_line));
00257 
00258   IConsoleCmdExec(input_line); // execute command
00259 }
00260 
00261 void VideoDriver_Dedicated::MainLoop()
00262 {
00263   uint32 cur_ticks = GetTime();
00264   uint32 next_tick = cur_ticks + MILLISECONDS_PER_TICK;
00265 
00266   /* Signal handlers */
00267 #if defined(UNIX) || defined(PSP)
00268   signal(SIGTERM, DedicatedSignalHandler);
00269   signal(SIGINT, DedicatedSignalHandler);
00270   signal(SIGQUIT, DedicatedSignalHandler);
00271 #endif
00272 
00273   /* Load the dedicated server stuff */
00274   _is_network_server = true;
00275   _network_dedicated = true;
00276   _current_company = _local_company = COMPANY_SPECTATOR;
00277 
00278   /* If SwitchMode is SM_LOAD_GAME, it means that the user used the '-g' options */
00279   if (_switch_mode != SM_LOAD_GAME) {
00280     StartNewGameWithoutGUI(GENERATE_NEW_SEED);
00281     SwitchToMode(_switch_mode);
00282     _switch_mode = SM_NONE;
00283   } else {
00284     _switch_mode = SM_NONE;
00285     /* First we need to test if the savegame can be loaded, else we will end up playing the
00286      *  intro game... */
00287     if (!SafeLoad(_file_to_saveload.name, _file_to_saveload.mode, GM_NORMAL, BASE_DIR)) {
00288       /* Loading failed, pop out.. */
00289       DEBUG(net, 0, "Loading requested map failed, aborting");
00290       _networking = false;
00291     } else {
00292       /* We can load this game, so go ahead */
00293       SwitchToMode(SM_LOAD_GAME);
00294     }
00295   }
00296 
00297   /* Done loading, start game! */
00298 
00299   if (!_networking) {
00300     DEBUG(net, 0, "Dedicated server could not be started, aborting");
00301     return;
00302   }
00303 
00304   while (!_exit_game) {
00305     uint32 prev_cur_ticks = cur_ticks; // to check for wrapping
00306     InteractiveRandom(); // randomness
00307 
00308     if (!_dedicated_forks) DedicatedHandleKeyInput();
00309 
00310     cur_ticks = GetTime();
00311     _realtime_tick += cur_ticks - prev_cur_ticks;
00312     if (cur_ticks >= next_tick || cur_ticks < prev_cur_ticks || _ddc_fastforward) {
00313       next_tick = cur_ticks + MILLISECONDS_PER_TICK;
00314 
00315       GameLoop();
00316       UpdateWindows();
00317     }
00318 
00319     /* Don't sleep when fast forwarding (for desync debugging) */
00320     if (!_ddc_fastforward) CSleep(1);
00321   }
00322 }
00323 
00324 #endif /* ENABLE_NETWORK */