# dedicated_v.cpp

Go to the documentation of this file.

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