OpenTTD
openttd.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 "blitter/factory.hpp"
15 #include "sound/sound_driver.hpp"
16 #include "music/music_driver.hpp"
17 #include "video/video_driver.hpp"
18 
19 #include "fontcache.h"
20 #include "error.h"
21 #include "gui.h"
22 
23 #include "base_media_base.h"
24 #include "saveload/saveload.h"
25 #include "company_func.h"
26 #include "command_func.h"
27 #include "news_func.h"
28 #include "fios.h"
29 #include "aircraft.h"
30 #include "roadveh.h"
31 #include "train.h"
32 #include "ship.h"
33 #include "console_func.h"
34 #include "screenshot.h"
35 #include "network/network.h"
36 #include "network/network_func.h"
37 #include "ai/ai.hpp"
38 #include "ai/ai_config.hpp"
39 #include "settings_func.h"
40 #include "genworld.h"
41 #include "progress.h"
42 #include "strings_func.h"
43 #include "date_func.h"
44 #include "vehicle_func.h"
45 #include "gamelog.h"
46 #include "animated_tile_func.h"
47 #include "roadstop_base.h"
48 #include "elrail_func.h"
49 #include "rev.h"
50 #include "highscore.h"
51 #include "station_base.h"
52 #include "crashlog.h"
53 #include "engine_func.h"
54 #include "core/random_func.hpp"
55 #include "rail_gui.h"
56 #include "core/backup_type.hpp"
57 #include "hotkeys.h"
58 #include "newgrf.h"
59 #include "misc/getoptdata.h"
60 #include "game/game.hpp"
61 #include "game/game_config.hpp"
62 #include "town.h"
63 #include "subsidy_func.h"
64 #include "gfx_layout.h"
65 #include "viewport_func.h"
66 #include "viewport_sprite_sorter.h"
67 #include "framerate_type.h"
68 
70 
71 #include <stdarg.h>
72 
73 #include "safeguards.h"
74 
75 void CallLandscapeTick();
76 void IncreaseDate();
77 void DoPaletteAnimations();
78 void MusicLoop();
79 void ResetMusic();
81 bool HandleBootstrap();
82 
83 extern Company *DoStartupNewCompany(bool is_ai, CompanyID company = INVALID_COMPANY);
84 extern void ShowOSErrorBox(const char *buf, bool system);
85 extern char *_config_file;
86 
92 void CDECL usererror(const char *s, ...)
93 {
94  va_list va;
95  char buf[512];
96 
97  va_start(va, s);
98  vseprintf(buf, lastof(buf), s, va);
99  va_end(va);
100 
101  ShowOSErrorBox(buf, false);
103 
104  exit(1);
105 }
106 
112 void CDECL error(const char *s, ...)
113 {
114  va_list va;
115  char buf[512];
116 
117  va_start(va, s);
118  vseprintf(buf, lastof(buf), s, va);
119  va_end(va);
120 
121  if (VideoDriver::GetInstance() == NULL || VideoDriver::GetInstance()->HasGUI()) {
122  ShowOSErrorBox(buf, true);
123  }
124 
125  /* Set the error message for the crash log and then invoke it. */
127  abort();
128 }
129 
134 void CDECL ShowInfoF(const char *str, ...)
135 {
136  va_list va;
137  char buf[1024];
138  va_start(va, str);
139  vseprintf(buf, lastof(buf), str, va);
140  va_end(va);
141  ShowInfo(buf);
142 }
143 
147 static void ShowHelp()
148 {
149  char buf[8192];
150  char *p = buf;
151 
152  p += seprintf(p, lastof(buf), "OpenTTD %s\n", _openttd_revision);
153  p = strecpy(p,
154  "\n"
155  "\n"
156  "Command line options:\n"
157  " -v drv = Set video driver (see below)\n"
158  " -s drv = Set sound driver (see below) (param bufsize,hz)\n"
159  " -m drv = Set music driver (see below)\n"
160  " -b drv = Set the blitter to use (see below)\n"
161  " -r res = Set resolution (for instance 800x600)\n"
162  " -h = Display this help text\n"
163  " -t year = Set starting year\n"
164  " -d [[fac=]lvl[,...]]= Debug mode\n"
165  " -e = Start Editor\n"
166  " -g [savegame] = Start new/save game immediately\n"
167  " -G seed = Set random seed\n"
168 #if defined(ENABLE_NETWORK)
169  " -n [ip:port#company]= Join network game\n"
170  " -p password = Password to join server\n"
171  " -P password = Password to join company\n"
172  " -D [ip][:port] = Start dedicated server\n"
173  " -l ip[:port] = Redirect DEBUG()\n"
174 #if !defined(__MORPHOS__) && !defined(__AMIGA__) && !defined(_WIN32)
175  " -f = Fork into the background (dedicated only)\n"
176 #endif
177 #endif /* ENABLE_NETWORK */
178  " -I graphics_set = Force the graphics set (see below)\n"
179  " -S sounds_set = Force the sounds set (see below)\n"
180  " -M music_set = Force the music set (see below)\n"
181  " -c config_file = Use 'config_file' instead of 'openttd.cfg'\n"
182  " -x = Do not automatically save to config file on exit\n"
183  " -q savegame = Write some information about the savegame and exit\n"
184  "\n",
185  lastof(buf)
186  );
187 
188  /* List the graphics packs */
189  p = BaseGraphics::GetSetsList(p, lastof(buf));
190 
191  /* List the sounds packs */
192  p = BaseSounds::GetSetsList(p, lastof(buf));
193 
194  /* List the music packs */
195  p = BaseMusic::GetSetsList(p, lastof(buf));
196 
197  /* List the drivers */
199 
200  /* List the blitters */
202 
203  /* List the debug facilities. */
204  p = DumpDebugFacilityNames(p, lastof(buf));
205 
206  /* We need to initialize the AI, so it finds the AIs */
207  AI::Initialize();
208  p = AI::GetConsoleList(p, lastof(buf), true);
209  AI::Uninitialize(true);
210 
211  /* We need to initialize the GameScript, so it finds the GSs */
213  p = Game::GetConsoleList(p, lastof(buf), true);
214  Game::Uninitialize(true);
215 
216  /* ShowInfo put output to stderr, but version information should go
217  * to stdout; this is the only exception */
218 #if !defined(_WIN32)
219  printf("%s\n", buf);
220 #else
221  ShowInfo(buf);
222 #endif
223 }
224 
225 static void WriteSavegameInfo(const char *name)
226 {
228  uint32 last_ottd_rev = 0;
229  byte ever_modified = 0;
230  bool removed_newgrfs = false;
231 
232  GamelogInfo(_load_check_data.gamelog_action, _load_check_data.gamelog_actions, &last_ottd_rev, &ever_modified, &removed_newgrfs);
233 
234  char buf[8192];
235  char *p = buf;
236  p += seprintf(p, lastof(buf), "Name: %s\n", name);
237  p += seprintf(p, lastof(buf), "Savegame ver: %d\n", _sl_version);
238  p += seprintf(p, lastof(buf), "NewGRF ver: 0x%08X\n", last_ottd_rev);
239  p += seprintf(p, lastof(buf), "Modified: %d\n", ever_modified);
240 
241  if (removed_newgrfs) {
242  p += seprintf(p, lastof(buf), "NewGRFs have been removed\n");
243  }
244 
245  p = strecpy(p, "NewGRFs:\n", lastof(buf));
247  for (GRFConfig *c = _load_check_data.grfconfig; c != NULL; c = c->next) {
248  char md5sum[33];
249  md5sumToString(md5sum, lastof(md5sum), HasBit(c->flags, GCF_COMPATIBLE) ? c->original_md5sum : c->ident.md5sum);
250  p += seprintf(p, lastof(buf), "%08X %s %s\n", c->ident.grfid, md5sum, c->filename);
251  }
252  }
253 
254  /* ShowInfo put output to stderr, but version information should go
255  * to stdout; this is the only exception */
256 #if !defined(_WIN32)
257  printf("%s\n", buf);
258 #else
259  ShowInfo(buf);
260 #endif
261 }
262 
263 
270 static void ParseResolution(Dimension *res, const char *s)
271 {
272  const char *t = strchr(s, 'x');
273  if (t == NULL) {
274  ShowInfoF("Invalid resolution '%s'", s);
275  return;
276  }
277 
278  res->width = max(strtoul(s, NULL, 0), 64UL);
279  res->height = max(strtoul(t + 1, NULL, 0), 64UL);
280 }
281 
282 
287 static void ShutdownGame()
288 {
289  IConsoleFree();
290 
291  if (_network_available) NetworkShutDown(); // Shut down the network and close any open connections
292 
294 
296 
297  /* stop the scripts */
298  AI::Uninitialize(false);
299  Game::Uninitialize(false);
300 
301  /* Uninitialize variables that are allocated dynamically */
302  GamelogReset();
303 
304 #ifdef ENABLE_NETWORK
306 #endif
307 
310 
311  /* No NewGRFs were loaded when it was still bootstrapping. */
312  if (_game_mode != GM_BOOTSTRAP) ResetNewGRFData();
313 
314  /* Close all and any open filehandles */
315  FioCloseAll();
316 
317  UninitFreeType();
318 }
319 
324 static void LoadIntroGame(bool load_newgrfs = true)
325 {
326  _game_mode = GM_MENU;
327 
328  if (load_newgrfs) ResetGRFConfig(false);
329 
330  /* Setup main window */
333 
334  /* Load the default opening screen savegame */
335  if (SaveOrLoad("opntitle.dat", SLO_LOAD, DFT_GAME_FILE, BASESET_DIR) != SL_OK) {
336  GenerateWorld(GWM_EMPTY, 64, 64); // if failed loading, make empty world.
339  } else {
341  }
342 
343  FixTitleGameZoom();
345  _cursor.fix_at = false;
346 
348 
349  MusicLoop(); // ensure music is correct
350 }
351 
352 void MakeNewgameSettingsLive()
353 {
354  for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
355  if (_settings_game.ai_config[c] != NULL) {
356  delete _settings_game.ai_config[c];
357  }
358  }
359  if (_settings_game.game_config != NULL) {
361  }
362 
363  /* Copy newgame settings to active settings.
364  * Also initialise old settings needed for savegame conversion. */
367 
368  for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
369  _settings_game.ai_config[c] = NULL;
370  if (_settings_newgame.ai_config[c] != NULL) {
372  if (!AIConfig::GetConfig(c, AIConfig::SSS_FORCE_GAME)->HasScript()) {
374  }
375  }
376  }
378  if (_settings_newgame.game_config != NULL) {
380  }
381 }
382 
383 void OpenBrowser(const char *url)
384 {
385  /* Make sure we only accept urls that are sure to open a browser. */
386  if (strstr(url, "http://") != url && strstr(url, "https://") != url) return;
387 
388  extern void OSOpenBrowser(const char *url);
389  OSOpenBrowser(url);
390 }
391 
397  uint16 dedicated_port;
398  char *network_conn;
399  const char *join_server_password;
400  const char *join_company_password;
402  bool save_config;
403 
409  AfterNewGRFScan(bool *save_config_ptr) :
410  startyear(INVALID_YEAR), generation_seed(GENERATE_NEW_SEED),
411  dedicated_host(NULL), dedicated_port(0), network_conn(NULL),
412  join_server_password(NULL), join_company_password(NULL),
413  save_config_ptr(save_config_ptr), save_config(true)
414  {
415  /* Visual C++ 2015 fails compiling this line (AfterNewGRFScan::generation_seed undefined symbol)
416  * if it's placed outside a member function, directly in the struct body. */
417  assert_compile(sizeof(generation_seed) == sizeof(_settings_game.game_creation.generation_seed));
418  }
419 
420  virtual void OnNewGRFsScanned()
421  {
422  ResetGRFConfig(false);
423 
425 
426  AI::Initialize();
428 
429  /* We want the new (correct) NewGRF count to survive the loading. */
430  uint last_newgrf_count = _settings_client.gui.last_newgrf_count;
431  LoadFromConfig();
432  _settings_client.gui.last_newgrf_count = last_newgrf_count;
433  /* Since the default for the palette might have changed due to
434  * reading the configuration file, recalculate that now. */
436 
437  Game::Uninitialize(true);
438  AI::Uninitialize(true);
439  CheckConfig();
443 
444  /* We have loaded the config, so we may possibly save it. */
445  *save_config_ptr = save_config;
446 
447  /* restore saved music volume */
449 
452 
453 #if defined(ENABLE_NETWORK)
454  if (dedicated_host != NULL) {
456  *_network_bind_list.Append() = stredup(dedicated_host);
457  }
458  if (dedicated_port != 0) _settings_client.network.server_port = dedicated_port;
459 #endif /* ENABLE_NETWORK */
460 
461  /* initialize the ingame console */
462  IConsoleInit();
463  InitializeGUI();
464  IConsoleCmdExec("exec scripts/autoexec.scr 0");
465 
466  /* Make sure _settings is filled with _settings_newgame if we switch to a game directly */
467  if (_switch_mode != SM_NONE) MakeNewgameSettingsLive();
468 
469 #ifdef ENABLE_NETWORK
470  if (_network_available && network_conn != NULL) {
471  const char *port = NULL;
472  const char *company = NULL;
473  uint16 rport = NETWORK_DEFAULT_PORT;
474  CompanyID join_as = COMPANY_NEW_COMPANY;
475 
476  ParseConnectionString(&company, &port, network_conn);
477 
478  if (company != NULL) {
479  join_as = (CompanyID)atoi(company);
480 
481  if (join_as != COMPANY_SPECTATOR) {
482  join_as--;
483  if (join_as >= MAX_COMPANIES) {
484  delete this;
485  return;
486  }
487  }
488  }
489  if (port != NULL) rport = atoi(port);
490 
491  LoadIntroGame();
492  _switch_mode = SM_NONE;
493  NetworkClientConnectGame(NetworkAddress(network_conn, rport), join_as, join_server_password, join_company_password);
494  }
495 #endif /* ENABLE_NETWORK */
496 
497  /* After the scan we're not used anymore. */
498  delete this;
499  }
500 };
501 
502 #if defined(UNIX) && !defined(__MORPHOS__)
503 extern void DedicatedFork();
504 #endif
505 
507 static const OptionData _options[] = {
508  GETOPT_SHORT_VALUE('I'),
509  GETOPT_SHORT_VALUE('S'),
510  GETOPT_SHORT_VALUE('M'),
511  GETOPT_SHORT_VALUE('m'),
512  GETOPT_SHORT_VALUE('s'),
513  GETOPT_SHORT_VALUE('v'),
514  GETOPT_SHORT_VALUE('b'),
515 #if defined(ENABLE_NETWORK)
516  GETOPT_SHORT_OPTVAL('D'),
517  GETOPT_SHORT_OPTVAL('n'),
518  GETOPT_SHORT_VALUE('l'),
519  GETOPT_SHORT_VALUE('p'),
520  GETOPT_SHORT_VALUE('P'),
521 #if !defined(__MORPHOS__) && !defined(__AMIGA__) && !defined(_WIN32)
522  GETOPT_SHORT_NOVAL('f'),
523 #endif
524 #endif /* ENABLE_NETWORK */
525  GETOPT_SHORT_VALUE('r'),
526  GETOPT_SHORT_VALUE('t'),
527  GETOPT_SHORT_OPTVAL('d'),
528  GETOPT_SHORT_NOVAL('e'),
529  GETOPT_SHORT_OPTVAL('g'),
530  GETOPT_SHORT_VALUE('G'),
531  GETOPT_SHORT_VALUE('c'),
532  GETOPT_SHORT_NOVAL('x'),
533  GETOPT_SHORT_VALUE('q'),
534  GETOPT_SHORT_NOVAL('h'),
535  GETOPT_END()
536 };
537 
544 int openttd_main(int argc, char *argv[])
545 {
546  char *musicdriver = NULL;
547  char *sounddriver = NULL;
548  char *videodriver = NULL;
549  char *blitter = NULL;
550  char *graphics_set = NULL;
551  char *sounds_set = NULL;
552  char *music_set = NULL;
553  Dimension resolution = {0, 0};
554  /* AfterNewGRFScan sets save_config to true after scanning completed. */
555  bool save_config = false;
556  AfterNewGRFScan *scanner = new AfterNewGRFScan(&save_config);
557 #if defined(ENABLE_NETWORK)
558  bool dedicated = false;
559  char *debuglog_conn = NULL;
560 
561  extern bool _dedicated_forks;
562  _dedicated_forks = false;
563 #endif /* ENABLE_NETWORK */
564 
565  _game_mode = GM_MENU;
567  _config_file = NULL;
568 
569  GetOptData mgo(argc - 1, argv + 1, _options);
570  int ret = 0;
571 
572  int i;
573  while ((i = mgo.GetOpt()) != -1) {
574  switch (i) {
575  case 'I': free(graphics_set); graphics_set = stredup(mgo.opt); break;
576  case 'S': free(sounds_set); sounds_set = stredup(mgo.opt); break;
577  case 'M': free(music_set); music_set = stredup(mgo.opt); break;
578  case 'm': free(musicdriver); musicdriver = stredup(mgo.opt); break;
579  case 's': free(sounddriver); sounddriver = stredup(mgo.opt); break;
580  case 'v': free(videodriver); videodriver = stredup(mgo.opt); break;
581  case 'b': free(blitter); blitter = stredup(mgo.opt); break;
582 #if defined(ENABLE_NETWORK)
583  case 'D':
584  free(musicdriver);
585  free(sounddriver);
586  free(videodriver);
587  free(blitter);
588  musicdriver = stredup("null");
589  sounddriver = stredup("null");
590  videodriver = stredup("dedicated");
591  blitter = stredup("null");
592  dedicated = true;
593  SetDebugString("net=6");
594  if (mgo.opt != NULL) {
595  /* Use the existing method for parsing (openttd -n).
596  * However, we do ignore the #company part. */
597  const char *temp = NULL;
598  const char *port = NULL;
599  ParseConnectionString(&temp, &port, mgo.opt);
600  if (!StrEmpty(mgo.opt)) scanner->dedicated_host = mgo.opt;
601  if (port != NULL) scanner->dedicated_port = atoi(port);
602  }
603  break;
604  case 'f': _dedicated_forks = true; break;
605  case 'n':
606  scanner->network_conn = mgo.opt; // optional IP parameter, NULL if unset
607  break;
608  case 'l':
609  debuglog_conn = mgo.opt;
610  break;
611  case 'p':
612  scanner->join_server_password = mgo.opt;
613  break;
614  case 'P':
615  scanner->join_company_password = mgo.opt;
616  break;
617 #endif /* ENABLE_NETWORK */
618  case 'r': ParseResolution(&resolution, mgo.opt); break;
619  case 't': scanner->startyear = atoi(mgo.opt); break;
620  case 'd': {
621 #if defined(_WIN32)
622  CreateConsole();
623 #endif
624  if (mgo.opt != NULL) SetDebugString(mgo.opt);
625  break;
626  }
628  case 'g':
629  if (mgo.opt != NULL) {
631  bool is_scenario = _switch_mode == SM_EDITOR || _switch_mode == SM_LOAD_SCENARIO;
632  _switch_mode = is_scenario ? SM_LOAD_SCENARIO : SM_LOAD_GAME;
634 
635  /* if the file doesn't exist or it is not a valid savegame, let the saveload code show an error */
636  const char *t = strrchr(_file_to_saveload.name, '.');
637  if (t != NULL) {
639  if (ft != FIOS_TYPE_INVALID) _file_to_saveload.SetMode(ft);
640  }
641 
642  break;
643  }
644 
646  /* Give a random map if no seed has been given */
647  if (scanner->generation_seed == GENERATE_NEW_SEED) {
648  scanner->generation_seed = InteractiveRandom();
649  }
650  break;
651  case 'q': {
652  DeterminePaths(argv[0]);
653  if (StrEmpty(mgo.opt)) {
654  ret = 1;
655  goto exit_noshutdown;
656  }
657 
658  char title[80];
659  title[0] = '\0';
660  FiosGetSavegameListCallback(SLO_LOAD, mgo.opt, strrchr(mgo.opt, '.'), title, lastof(title));
661 
664  if (res != SL_OK || _load_check_data.HasErrors()) {
665  fprintf(stderr, "Failed to open savegame\n");
666  if (_load_check_data.HasErrors()) {
667  char buf[256];
669  GetString(buf, _load_check_data.error, lastof(buf));
670  fprintf(stderr, "%s\n", buf);
671  }
672  goto exit_noshutdown;
673  }
674 
675  WriteSavegameInfo(title);
676 
677  goto exit_noshutdown;
678  }
679  case 'G': scanner->generation_seed = strtoul(mgo.opt, NULL, 10); break;
680  case 'c': free(_config_file); _config_file = stredup(mgo.opt); break;
681  case 'x': scanner->save_config = false; break;
682  case 'h':
683  i = -2; // Force printing of help.
684  break;
685  }
686  if (i == -2) break;
687  }
688 
689  if (i == -2 || mgo.numleft > 0) {
690  /* Either the user typed '-h', he made an error, or he added unrecognized command line arguments.
691  * In all cases, print the help, and exit.
692  *
693  * The next two functions are needed to list the graphics sets. We can't do them earlier
694  * because then we cannot show it on the debug console as that hasn't been configured yet. */
695  DeterminePaths(argv[0]);
700  ShowHelp();
701 
702  goto exit_noshutdown;
703  }
704 
705  DeterminePaths(argv[0]);
707 
708 #if defined(ENABLE_NETWORK)
709  if (dedicated) DEBUG(net, 0, "Starting dedicated version %s", _openttd_revision);
710  if (_dedicated_forks && !dedicated) _dedicated_forks = false;
711 
712 #if defined(UNIX) && !defined(__MORPHOS__)
713  /* We must fork here, or we'll end up without some resources we need (like sockets) */
714  if (_dedicated_forks) DedicatedFork();
715 #endif
716 #endif
717 
718  LoadFromConfig(true);
719 
720  if (resolution.width != 0) _cur_resolution = resolution;
721 
722  /*
723  * The width and height must be at least 1 pixel and width times
724  * height times bytes per pixel must still fit within a 32 bits
725  * integer, even for 32 bpp video modes. This way all internal
726  * drawing routines work correctly.
727  */
728  _cur_resolution.width = ClampU(_cur_resolution.width, 1, UINT16_MAX / 2);
729  _cur_resolution.height = ClampU(_cur_resolution.height, 1, UINT16_MAX / 2);
730 
731  /* Assume the cursor starts within the game as not all video drivers
732  * get an event that the cursor is within the window when it is opened.
733  * Saying the cursor is there makes no visible difference as it would
734  * just be out of the bounds of the window. */
735  _cursor.in_window = true;
736 
737  /* enumerate language files */
739 
740  /* Initialize the regular font for FreeType */
741  InitFreeType(false);
742 
743  /* This must be done early, since functions use the SetWindowDirty* calls */
745 
747  if (graphics_set == NULL && BaseGraphics::ini_set != NULL) graphics_set = stredup(BaseGraphics::ini_set);
748  if (!BaseGraphics::SetSet(graphics_set)) {
749  if (!StrEmpty(graphics_set)) {
750  BaseGraphics::SetSet(NULL);
751 
752  ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_GRAPHICS_NOT_FOUND);
753  msg.SetDParamStr(0, graphics_set);
755  }
756  }
757  free(graphics_set);
758 
759  /* Initialize game palette */
760  GfxInitPalettes();
761 
762  DEBUG(misc, 1, "Loading blitter...");
763  if (blitter == NULL && _ini_blitter != NULL) blitter = stredup(_ini_blitter);
764  _blitter_autodetected = StrEmpty(blitter);
765  /* Activate the initial blitter.
766  * This is only some initial guess, after NewGRFs have been loaded SwitchNewGRFBlitter may switch to a different one.
767  * - Never guess anything, if the user specified a blitter. (_blitter_autodetected)
768  * - Use 32bpp blitter if baseset or 8bpp-support settings says so.
769  * - Use 8bpp blitter otherwise.
770  */
771  if (!_blitter_autodetected ||
772  (_support8bpp != S8BPP_NONE && (BaseGraphics::GetUsedSet() == NULL || BaseGraphics::GetUsedSet()->blitter == BLT_8BPP)) ||
773  BlitterFactory::SelectBlitter("32bpp-anim") == NULL) {
774  if (BlitterFactory::SelectBlitter(blitter) == NULL) {
775  StrEmpty(blitter) ?
776  usererror("Failed to autoprobe blitter") :
777  usererror("Failed to select requested blitter '%s'; does it exist?", blitter);
778  }
779  }
780  free(blitter);
781 
782  if (videodriver == NULL && _ini_videodriver != NULL) videodriver = stredup(_ini_videodriver);
784  free(videodriver);
785 
787 
788  /* Initialize the zoom level of the screen to normal */
789  _screen.zoom = ZOOM_LVL_NORMAL;
790 
791  NetworkStartUp(); // initialize network-core
792 
793 #if defined(ENABLE_NETWORK)
794  if (debuglog_conn != NULL && _network_available) {
795  const char *not_used = NULL;
796  const char *port = NULL;
797  uint16 rport;
798 
800 
801  ParseConnectionString(&not_used, &port, debuglog_conn);
802  if (port != NULL) rport = atoi(port);
803 
804  NetworkStartDebugLog(NetworkAddress(debuglog_conn, rport));
805  }
806 #endif /* ENABLE_NETWORK */
807 
808  if (!HandleBootstrap()) {
809  ShutdownGame();
810 
811  goto exit_bootstrap;
812  }
813 
814  VideoDriver::GetInstance()->ClaimMousePointer();
815 
816  /* initialize screenshot formats */
818 
820  if (sounds_set == NULL && BaseSounds::ini_set != NULL) sounds_set = stredup(BaseSounds::ini_set);
821  if (!BaseSounds::SetSet(sounds_set)) {
822  if (StrEmpty(sounds_set) || !BaseSounds::SetSet(NULL)) {
823  usererror("Failed to find a sounds set. Please acquire a sounds set for OpenTTD. See section 4.1 of README.md.");
824  } else {
825  ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_SOUNDS_NOT_FOUND);
826  msg.SetDParamStr(0, sounds_set);
828  }
829  }
830  free(sounds_set);
831 
833  if (music_set == NULL && BaseMusic::ini_set != NULL) music_set = stredup(BaseMusic::ini_set);
834  if (!BaseMusic::SetSet(music_set)) {
835  if (StrEmpty(music_set) || !BaseMusic::SetSet(NULL)) {
836  usererror("Failed to find a music set. Please acquire a music set for OpenTTD. See section 4.1 of README.md.");
837  } else {
838  ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_MUSIC_NOT_FOUND);
839  msg.SetDParamStr(0, music_set);
841  }
842  }
843  free(music_set);
844 
845  if (sounddriver == NULL && _ini_sounddriver != NULL) sounddriver = stredup(_ini_sounddriver);
847  free(sounddriver);
848 
849  if (musicdriver == NULL && _ini_musicdriver != NULL) musicdriver = stredup(_ini_musicdriver);
851  free(musicdriver);
852 
853  /* Take our initial lock on whatever we might want to do! */
856 
857  GenerateWorld(GWM_EMPTY, 64, 64); // Make the viewport initialization happy
859 
860  LoadIntroGame(false);
861 
863 
864  /* ScanNewGRFFiles now has control over the scanner. */
865  ScanNewGRFFiles(scanner);
866  scanner = NULL;
867 
869 
870  WaitTillSaved();
871 
872  /* only save config if we have to */
873  if (save_config) {
874  SaveToConfig();
877  SaveToHighScore();
878  }
879 
880  /* Reset windowing system, stop drivers, free used memory, ... */
881  ShutdownGame();
882  goto exit_normal;
883 
884 exit_noshutdown:
885  /* These three are normally freed before bootstrap. */
886  free(graphics_set);
887  free(videodriver);
888  free(blitter);
889 
890 exit_bootstrap:
891  /* These are normally freed before exit, but after bootstrap. */
892  free(sounds_set);
893  free(music_set);
894  free(musicdriver);
895  free(sounddriver);
896 
897 exit_normal:
901 
906 
907  delete scanner;
908 
909 #ifdef ENABLE_NETWORK
910  extern FILE *_log_fd;
911  if (_log_fd != NULL) {
912  fclose(_log_fd);
913  }
914 #endif /* ENABLE_NETWORK */
915 
916  return ret;
917 }
918 
919 void HandleExitGameRequest()
920 {
921  if (_game_mode == GM_MENU || _game_mode == GM_BOOTSTRAP) { // do not ask to quit on the main screen
922  _exit_game = true;
924  DoExitSave();
925  _exit_game = true;
926  } else {
927  AskExitGame();
928  }
929 }
930 
931 static void MakeNewGameDone()
932 {
934 
935  /* In a dedicated server, the server does not play */
936  if (!VideoDriver::GetInstance()->HasGUI()) {
939  IConsoleCmdExec("exec scripts/game_start.scr 0");
940  return;
941  }
942 
943  /* Create a single company */
944  DoStartupNewCompany(false);
945 
948 
949  /* Overwrite color from settings if needed
950  * COLOUR_END corresponds to Random colour */
951  if (_settings_client.gui.starting_colour != COLOUR_END) {
954  _company_colours[c->index] = (Colours)c->colour;
955  }
956 
957  IConsoleCmdExec("exec scripts/game_start.scr 0");
958 
960 
962 
963 #ifdef ENABLE_NETWORK
964  /* We are the server, we start a new company (not dedicated),
965  * so set the default password *if* needed. */
968  }
969 #endif /* ENABLE_NETWORK */
970 
972 
973  CheckEngines();
974  CheckIndustries();
976 }
977 
978 static void MakeNewGame(bool from_heightmap, bool reset_settings)
979 {
980  _game_mode = GM_NORMAL;
981 
982  ResetGRFConfig(true);
983 
984  GenerateWorldSetCallback(&MakeNewGameDone);
986 }
987 
988 static void MakeNewEditorWorldDone()
989 {
991 }
992 
993 static void MakeNewEditorWorld()
994 {
995  _game_mode = GM_EDITOR;
996 
997  ResetGRFConfig(true);
998 
999  GenerateWorldSetCallback(&MakeNewEditorWorldDone);
1001 }
1002 
1013 bool SafeLoad(const char *filename, SaveLoadOperation fop, DetailedFileType dft, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf = NULL)
1014 {
1015  assert(fop == SLO_LOAD);
1016  assert(dft == DFT_GAME_FILE || (lf == NULL && dft == DFT_OLD_GAME_FILE));
1017  GameMode ogm = _game_mode;
1018 
1019  _game_mode = newgm;
1020 
1021  switch (lf == NULL ? SaveOrLoad(filename, fop, dft, subdir) : LoadWithFilter(lf)) {
1022  case SL_OK: return true;
1023 
1024  case SL_REINIT:
1025 #ifdef ENABLE_NETWORK
1026  if (_network_dedicated) {
1027  /*
1028  * We need to reinit a network map...
1029  * We can't simply load the intro game here as that game has many
1030  * special cases which make clients desync immediately. So we fall
1031  * back to just generating a new game with the current settings.
1032  */
1033  DEBUG(net, 0, "Loading game failed, so a new (random) game will be started!");
1034  MakeNewGame(false, true);
1035  return false;
1036  }
1037  if (_network_server) {
1038  /* We can't load the intro game as server, so disconnect first. */
1040  }
1041 #endif /* ENABLE_NETWORK */
1042 
1043  switch (ogm) {
1044  default:
1045  case GM_MENU: LoadIntroGame(); break;
1046  case GM_EDITOR: MakeNewEditorWorld(); break;
1047  }
1048  return false;
1049 
1050  default:
1051  _game_mode = ogm;
1052  return false;
1053  }
1054 }
1055 
1056 void SwitchToMode(SwitchMode new_mode)
1057 {
1058 #ifdef ENABLE_NETWORK
1059  /* If we are saving something, the network stays in his current state */
1060  if (new_mode != SM_SAVE_GAME) {
1061  /* If the network is active, make it not-active */
1062  if (_networking) {
1063  if (_network_server && (new_mode == SM_LOAD_GAME || new_mode == SM_NEWGAME || new_mode == SM_RESTARTGAME)) {
1064  NetworkReboot();
1065  } else {
1067  }
1068  }
1069 
1070  /* If we are a server, we restart the server */
1071  if (_is_network_server) {
1072  /* But not if we are going to the menu */
1073  if (new_mode != SM_MENU) {
1074  /* check if we should reload the config */
1076  LoadFromConfig();
1077  MakeNewgameSettingsLive();
1078  ResetGRFConfig(false);
1079  }
1080  NetworkServerStart();
1081  } else {
1082  /* This client no longer wants to be a network-server */
1083  _is_network_server = false;
1084  }
1085  }
1086  }
1087 #endif /* ENABLE_NETWORK */
1088  /* Make sure all AI controllers are gone at quitting game */
1089  if (new_mode != SM_SAVE_GAME) AI::KillAll();
1090 
1091  switch (new_mode) {
1092  case SM_EDITOR: // Switch to scenario editor
1093  MakeNewEditorWorld();
1094  break;
1095 
1096  case SM_RESTARTGAME: // Restart --> 'Random game' with current settings
1097  case SM_NEWGAME: // New Game --> 'Random game'
1098 #ifdef ENABLE_NETWORK
1099  if (_network_server) {
1101  }
1102 #endif /* ENABLE_NETWORK */
1103  MakeNewGame(false, new_mode == SM_NEWGAME);
1104  break;
1105 
1106  case SM_LOAD_GAME: { // Load game, Play Scenario
1107  ResetGRFConfig(true);
1109 
1112  ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
1113  } else {
1115  /* Reset engine pool to simplify changing engine NewGRFs in scenario editor. */
1117  }
1118  /* Update the local company for a loaded game. It is either always
1119  * company #1 (eg 0) or in the case of a dedicated server a spectator */
1121  /* Execute the game-start script */
1122  IConsoleCmdExec("exec scripts/game_start.scr 0");
1123  /* Decrease pause counter (was increased from opening load dialog) */
1125 #ifdef ENABLE_NETWORK
1126  if (_network_server) {
1128  }
1129 #endif /* ENABLE_NETWORK */
1130  }
1131  break;
1132  }
1133 
1134  case SM_START_HEIGHTMAP: // Load a heightmap and start a new game from it
1135 #ifdef ENABLE_NETWORK
1136  if (_network_server) {
1138  }
1139 #endif /* ENABLE_NETWORK */
1140  MakeNewGame(true, true);
1141  break;
1142 
1143  case SM_LOAD_HEIGHTMAP: // Load heightmap from scenario editor
1145 
1148  break;
1149 
1150  case SM_LOAD_SCENARIO: { // Load scenario from scenario editor
1154  /* Cancel the saveload pausing */
1156  } else {
1158  ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
1159  }
1160  break;
1161  }
1162 
1163  case SM_MENU: // Switch to game intro menu
1164  LoadIntroGame();
1165  if (BaseSounds::ini_set == NULL && BaseSounds::GetUsedSet()->fallback) {
1166  ShowErrorMessage(STR_WARNING_FALLBACK_SOUNDSET, INVALID_STRING_ID, WL_CRITICAL);
1168  }
1169  break;
1170 
1171  case SM_SAVE_GAME: // Save game.
1172  /* Make network saved games on pause compatible to singleplayer */
1175  ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
1176  } else {
1178  }
1179  break;
1180 
1181  case SM_SAVE_HEIGHTMAP: // Save heightmap.
1184  break;
1185 
1186  case SM_GENRANDLAND: // Generate random land within scenario editor
1189  /* XXX: set date */
1191  break;
1192 
1193  default: NOT_REACHED();
1194  }
1195 }
1196 
1197 
1204 static void CheckCaches()
1205 {
1206  /* Return here so it is easy to add checks that are run
1207  * always to aid testing of caches. */
1208  if (_debug_desync_level <= 1) return;
1209 
1210  /* Check the town caches. */
1211  SmallVector<TownCache, 4> old_town_caches;
1212  Town *t;
1213  FOR_ALL_TOWNS(t) {
1214  MemCpyT(old_town_caches.Append(), &t->cache);
1215  }
1216 
1217  extern void RebuildTownCaches();
1220 
1221  uint i = 0;
1222  FOR_ALL_TOWNS(t) {
1223  if (MemCmpT(old_town_caches.Get(i), &t->cache) != 0) {
1224  DEBUG(desync, 2, "town cache mismatch: town %i", (int)t->index);
1225  }
1226  i++;
1227  }
1228 
1229  /* Check company infrastructure cache. */
1230  SmallVector<CompanyInfrastructure, 4> old_infrastructure;
1231  Company *c;
1232  FOR_ALL_COMPANIES(c) MemCpyT(old_infrastructure.Append(), &c->infrastructure);
1233 
1234  extern void AfterLoadCompanyStats();
1236 
1237  i = 0;
1238  FOR_ALL_COMPANIES(c) {
1239  if (MemCmpT(old_infrastructure.Get(i), &c->infrastructure) != 0) {
1240  DEBUG(desync, 2, "infrastructure cache mismatch: company %i", (int)c->index);
1241  }
1242  i++;
1243  }
1244 
1245  /* Strict checking of the road stop cache entries */
1246  const RoadStop *rs;
1247  FOR_ALL_ROADSTOPS(rs) {
1248  if (IsStandardRoadStopTile(rs->xy)) continue;
1249 
1250  assert(rs->GetEntry(DIAGDIR_NE) != rs->GetEntry(DIAGDIR_NW));
1253  }
1254 
1255  Vehicle *v;
1256  FOR_ALL_VEHICLES(v) {
1257  extern void FillNewGRFVehicleCache(const Vehicle *v);
1258  if (v != v->First() || v->vehstatus & VS_CRASHED || !v->IsPrimaryVehicle()) continue;
1259 
1260  uint length = 0;
1261  for (const Vehicle *u = v; u != NULL; u = u->Next()) length++;
1262 
1263  NewGRFCache *grf_cache = CallocT<NewGRFCache>(length);
1264  VehicleCache *veh_cache = CallocT<VehicleCache>(length);
1265  GroundVehicleCache *gro_cache = CallocT<GroundVehicleCache>(length);
1266  TrainCache *tra_cache = CallocT<TrainCache>(length);
1267 
1268  length = 0;
1269  for (const Vehicle *u = v; u != NULL; u = u->Next()) {
1271  grf_cache[length] = u->grf_cache;
1272  veh_cache[length] = u->vcache;
1273  switch (u->type) {
1274  case VEH_TRAIN:
1275  gro_cache[length] = Train::From(u)->gcache;
1276  tra_cache[length] = Train::From(u)->tcache;
1277  break;
1278  case VEH_ROAD:
1279  gro_cache[length] = RoadVehicle::From(u)->gcache;
1280  break;
1281  default:
1282  break;
1283  }
1284  length++;
1285  }
1286 
1287  switch (v->type) {
1288  case VEH_TRAIN: Train::From(v)->ConsistChanged(CCF_TRACK); break;
1291  case VEH_SHIP: Ship::From(v)->UpdateCache(); break;
1292  default: break;
1293  }
1294 
1295  length = 0;
1296  for (const Vehicle *u = v; u != NULL; u = u->Next()) {
1298  if (memcmp(&grf_cache[length], &u->grf_cache, sizeof(NewGRFCache)) != 0) {
1299  DEBUG(desync, 2, "newgrf cache mismatch: type %i, vehicle %i, company %i, unit number %i, wagon %i", (int)v->type, v->index, (int)v->owner, v->unitnumber, length);
1300  }
1301  if (memcmp(&veh_cache[length], &u->vcache, sizeof(VehicleCache)) != 0) {
1302  DEBUG(desync, 2, "vehicle cache mismatch: type %i, vehicle %i, company %i, unit number %i, wagon %i", (int)v->type, v->index, (int)v->owner, v->unitnumber, length);
1303  }
1304  switch (u->type) {
1305  case VEH_TRAIN:
1306  if (memcmp(&gro_cache[length], &Train::From(u)->gcache, sizeof(GroundVehicleCache)) != 0) {
1307  DEBUG(desync, 2, "train ground vehicle cache mismatch: vehicle %i, company %i, unit number %i, wagon %i", v->index, (int)v->owner, v->unitnumber, length);
1308  }
1309  if (memcmp(&tra_cache[length], &Train::From(u)->tcache, sizeof(TrainCache)) != 0) {
1310  DEBUG(desync, 2, "train cache mismatch: vehicle %i, company %i, unit number %i, wagon %i", v->index, (int)v->owner, v->unitnumber, length);
1311  }
1312  break;
1313  case VEH_ROAD:
1314  if (memcmp(&gro_cache[length], &RoadVehicle::From(u)->gcache, sizeof(GroundVehicleCache)) != 0) {
1315  DEBUG(desync, 2, "road vehicle ground vehicle cache mismatch: vehicle %i, company %i, unit number %i, wagon %i", v->index, (int)v->owner, v->unitnumber, length);
1316  }
1317  break;
1318  default:
1319  break;
1320  }
1321  length++;
1322  }
1323 
1324  free(grf_cache);
1325  free(veh_cache);
1326  free(gro_cache);
1327  free(tra_cache);
1328  }
1329 
1330  /* Check whether the caches are still valid */
1331  FOR_ALL_VEHICLES(v) {
1332  byte buff[sizeof(VehicleCargoList)];
1333  memcpy(buff, &v->cargo, sizeof(VehicleCargoList));
1334  v->cargo.InvalidateCache();
1335  assert(memcmp(&v->cargo, buff, sizeof(VehicleCargoList)) == 0);
1336  }
1337 
1338  Station *st;
1339  FOR_ALL_STATIONS(st) {
1340  for (CargoID c = 0; c < NUM_CARGO; c++) {
1341  byte buff[sizeof(StationCargoList)];
1342  memcpy(buff, &st->goods[c].cargo, sizeof(StationCargoList));
1343  st->goods[c].cargo.InvalidateCache();
1344  assert(memcmp(&st->goods[c].cargo, buff, sizeof(StationCargoList)) == 0);
1345  }
1346  }
1347 }
1348 
1355 {
1356  /* don't execute the state loop during pause */
1357  if (_pause_mode != PM_UNPAUSED) {
1365 
1367 #ifndef DEBUG_DUMP_COMMANDS
1368  Game::GameLoop();
1369 #endif
1370  return;
1371  }
1372 
1373  PerformanceMeasurer framerate(PFE_GAMELOOP);
1375  if (HasModalProgress()) return;
1376 
1378 
1379  if (_game_mode == GM_EDITOR) {
1381  RunTileLoop();
1382  CallVehicleTicks();
1383  CallLandscapeTick();
1386 
1388  NewsLoop();
1389  } else {
1390  if (_debug_desync_level > 2 && _date_fract == 0 && (_date & 0x1F) == 0) {
1391  /* Save the desync savegame if needed. */
1392  char name[MAX_PATH];
1393  seprintf(name, lastof(name), "dmp_cmds_%08x_%08x.sav", _settings_game.game_creation.generation_seed, _date);
1395  }
1396 
1397  CheckCaches();
1398 
1399  /* All these actions has to be done from OWNER_NONE
1400  * for multiplayer compatibility */
1401  Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
1402 
1405  IncreaseDate();
1406  RunTileLoop();
1407  CallVehicleTicks();
1408  CallLandscapeTick();
1410 
1411 #ifndef DEBUG_DUMP_COMMANDS
1412  {
1414  AI::GameLoop();
1415  Game::GameLoop();
1416  }
1417 #endif
1419 
1421  NewsLoop();
1422  cur_company.Restore();
1423  }
1424 
1425  assert(IsLocalCompany());
1426 }
1427 
1432 static void DoAutosave()
1433 {
1434  char buf[MAX_PATH];
1435 
1437  GenerateDefaultSaveName(buf, lastof(buf));
1438  strecat(buf, ".sav", lastof(buf));
1439  } else {
1440  static int _autosave_ctr = 0;
1441 
1442  /* generate a savegame name and number according to _settings_client.gui.max_num_autosaves */
1443  seprintf(buf, lastof(buf), "autosave%d.sav", _autosave_ctr);
1444 
1445  if (++_autosave_ctr >= _settings_client.gui.max_num_autosaves) _autosave_ctr = 0;
1446  }
1447 
1448  DEBUG(sl, 2, "Autosaving to '%s'", buf);
1450  ShowErrorMessage(STR_ERROR_AUTOSAVE_FAILED, INVALID_STRING_ID, WL_ERROR);
1451  }
1452 }
1453 
1454 void GameLoop()
1455 {
1456  if (_game_mode == GM_BOOTSTRAP) {
1457 #ifdef ENABLE_NETWORK
1458  /* Check for UDP stuff */
1460 #endif
1461  InputLoop();
1462  return;
1463  }
1464 
1466 
1467  /* autosave game? */
1468  if (_do_autosave) {
1469  DoAutosave();
1470  _do_autosave = false;
1472  }
1473 
1474  /* switch game mode? */
1475  if (_switch_mode != SM_NONE && !HasModalProgress()) {
1476  SwitchToMode(_switch_mode);
1477  _switch_mode = SM_NONE;
1478  }
1479 
1480  IncreaseSpriteLRU();
1481  InteractiveRandom();
1482 
1483 #ifdef ENABLE_NETWORK
1484  /* Check for UDP stuff */
1486 
1487  if (_networking && !HasModalProgress()) {
1488  /* Multiplayer */
1489  NetworkGameLoop();
1490  } else {
1491  if (_network_reconnect > 0 && --_network_reconnect == 0) {
1492  /* This means that we want to reconnect to the last host
1493  * We do this here, because it means that the network is really closed */
1495  }
1496  /* Singleplayer */
1497  StateGameLoop();
1498  }
1499 #else
1500  StateGameLoop();
1501 #endif /* ENABLE_NETWORK */
1502 
1503  if (!_pause_mode && HasBit(_display_opt, DO_FULL_ANIMATION)) DoPaletteAnimations();
1504 
1505  InputLoop();
1506 
1508  MusicLoop();
1509 }
bool disable_elrails
when true, the elrails are disabled
FiosType
Elements of a file system that are recognized.
Definition: fileio_type.h:69
void SetupColoursAndInitialWindow()
Initialise the default colours (remaps and the likes), and load the main windows. ...
Definition: main_gui.cpp:564
Functions related to OTTD&#39;s strings.
void UpdateLandscapingLimits()
Update the landscaping limits per company.
char * _ini_videodriver
The video driver a stored in the configuration file.
Definition: driver.cpp:21
Road vehicle states.
All pool types.
Definition: pool_type.hpp:25
VehicleSettings vehicle
options for vehicles
Cached often queried (NewGRF) values.
Definition: vehicle_base.h:67
static bool IsLocalCompany()
Is the current company the local company?
Definition: company_func.h:45
Time spent processing cargo movement.
VehicleCargoList cargo
The cargo this vehicle is carrying.
Definition: vehicle_base.h:309
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition: settings.cpp:77
void CheckForMissingGlyphs(bool base_font, MissingGlyphSearcher *searcher)
Check whether the currently loaded language pack uses characters that the currently loaded font does ...
Definition: strings.cpp:2101
void ParseConnectionString(const char **company, const char **port, char *connection_string)
Converts a string to ip/port/company Format: IP:port::company.
Definition: network.cpp:474
bool _networking
are we in networking mode?
Definition: network.cpp:56
Base of all video drivers.
void InitializeScreenshotFormats()
Initialize screenshot format information on startup, with _screenshot_format_name filled from the loa...
Definition: screenshot.cpp:580
#define GETOPT_SHORT_OPTVAL(shortname)
Short option with optional value.
Definition: getoptdata.h:106
void CheckEngines()
Check for engines that have an appropriate availability.
Definition: engine.cpp:1136
Scan for base sets.
Definition: fileio_func.h:102
Company * DoStartupNewCompany(bool is_ai, CompanyID company=INVALID_COMPANY)
Create a new company and sets all company variables default values.
bool _blitter_autodetected
Was the blitter autodetected or specified by the user?
Definition: driver.cpp:32
FiosType FiosGetSavegameListCallback(SaveLoadOperation fop, const char *file, const char *ext, char *title, const char *last)
Callback for FiosGetFileList.
Definition: fios.cpp:474
virtual void MainLoop()
Called once every tick.
bool HandleBootstrap()
Handle all procedures for bootstrapping OpenTTD without a base graphics set.
A game normally paused.
Definition: openttd.h:59
FILE * _log_fd
File to reroute output of a forked OpenTTD to.
Definition: dedicated.cpp:17
A normal unpaused game.
Definition: openttd.h:58
#define GETOPT_SHORT_VALUE(shortname)
Short option with value.
Definition: getoptdata.h:99
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
Definition: window.cpp:3201
static int MemCmpT(const T *ptr1, const T *ptr2, size_t num=1)
Type-safe version of memcmp().
Definition: mem_func.hpp:65
int openttd_main(int argc, char *argv[])
Main entry point for this lovely game.
Definition: openttd.cpp:544
static char * strecat(char *dst, const char *src, const char *last)
Appends characters from one string to another.
Definition: depend.cpp:99
void SetDParamStr(uint n, const char *str)
Set a rawstring parameter.
Definition: error_gui.cpp:158
Base class for roadstops.
Subdirectory
The different kinds of subdirectories OpenTTD uses.
Definition: fileio_type.h:110
bool keep_all_autosave
name the autosave in a different way
uint16 last_port
port of the last joined server
Load heightmap from scenario editor.
Definition: openttd.h:38
#define GETOPT_SHORT_NOVAL(shortname)
Short option without value.
Definition: getoptdata.h:93
void GenerateDefaultSaveName(char *buf, const char *last)
Fill the buffer with the default name for a savegame or screenshot.
Definition: saveload.cpp:2816
static void GameLoop()
Called every game-tick to let Game do something.
Definition: game_core.cpp:33
Saveload window; Window numbers:
Definition: window_type.h:139
SaveLoadVersion
SaveLoad versions Previous savegame versions, the trunk revision where they were introduced and the r...
Definition: saveload.h:31
GameConfig stores the configuration settings of every Game.
byte _display_opt
What do we want to draw/do?
void AfterLoadCompanyStats()
Rebuilding of company statistics after loading a savegame.
Definition: company_sl.cpp:96
CargoList that is used for stations.
Definition: cargopacket.h:463
static Titem * Get(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:246
struct LoggedAction * gamelog_action
Gamelog actions.
Definition: fios.h:48
Switch to game intro menu.
Definition: openttd.h:32
void SetName(const char *name)
Set the name of the file.
Definition: saveload.cpp:2879
static uint FindSets()
Do the scan for files.
Hotkey related functions.
Functions related to dates.
Generate a map for a new game.
Definition: genworld.h:29
int CDECL seprintf(char *str, const char *last, const char *format,...)
Safer implementation of snprintf; same as snprintf except:
Definition: string.cpp:409
Load game, Play Scenario.
Definition: openttd.h:31
static const OptionData _options[]
Options of OpenTTD.
Definition: openttd.cpp:507
Base for the train class.
bool pause_on_newgame
whether to start new games paused or not
bool * save_config_ptr
The pointer to the save config setting.
Definition: openttd.cpp:401
static char * GetConsoleList(char *p, const char *last, bool newest_only=false)
Wrapper function for AIScanner::GetAIConsoleList.
Definition: ai_core.cpp:322
Maximal number of cargo types in a game.
Definition: cargo_type.h:66
Functions to be called to log possibly unsafe game events.
Types for recording game performance data.
Generic functions for replacing base data (graphics, sounds).
FileToSaveLoad _file_to_saveload
File to save or load in the openttd loop.
Definition: saveload.cpp:59
void InitWindowSystem()
(re)initialize the windowing system
Definition: window.cpp:1877
static void Paused(PerformanceElement elem)
Indicate that a cycle of "pause" where no processing occurs.
static void Uninitialize(bool keepConfig)
Uninitialize the Game system.
Definition: game_core.cpp:99
TileIndex xy
Position on the map.
Definition: roadstop_base.h:69
void RebuildTownCaches()
Rebuild all the cached variables of towns.
Definition: town_sl.cpp:27
int CDECL vseprintf(char *str, const char *last, const char *format, va_list ap)
Safer implementation of vsnprintf; same as vsnprintf except:
Definition: string.cpp:62
Functions related to vehicles.
char * md5sumToString(char *buf, const char *last, const uint8 md5sum[16])
Convert the md5sum to a hexadecimal string representation.
Definition: string.cpp:427
SaveLoadVersion _sl_version
the major savegame version identifier
Definition: saveload.cpp:62
static void ShutdownDrivers()
Shuts down all active drivers.
Definition: driver.h:115
char title[255]
Internal name of the game.
Definition: saveload.h:311
MusicSettings music
settings related to music/sound
Base for all sound drivers.
static void Initialize()
Initialize the AI system.
Definition: ai_core.cpp:165
Vehicle data structure.
Definition: vehicle_base.h:212
void Change(const char *name, int version=-1, bool force_exact_match=false, bool is_random=false)
Set another Script to be loaded in this slot.
GRFConfig * grfconfig
NewGrf configuration from save.
Definition: fios.h:45
void FioCloseAll()
Close all slotted open files.
Definition: fileio.cpp:213
static const Year INVALID_YEAR
Representation of an invalid year.
Definition: date_type.h:109
Wrapper for (un)resolved network addresses; there&#39;s no reason to transform a numeric IP to a string a...
Definition: address.h:31
Generate a newgame from a heightmap.
Definition: genworld.h:32
static void Clean(PoolType)
Clean all pools of given type.
Definition: pool_func.cpp:32
Tindex index
Index of this pool item.
Definition: pool_type.hpp:147
void NetworkStartUp()
This tries to launch the network for a given OS.
Definition: network.cpp:1070
Northeast, upper right on your monitor.
Cached often queried values common to all vehicles.
Definition: vehicle_base.h:122
Dimension _cur_resolution
The current resolution.
Definition: driver.cpp:24
uint16 dedicated_port
Port for the dedicated server.
Definition: openttd.cpp:397
Data of an option.
Definition: getoptdata.h:24
void DoExitSave()
Do a save when exiting the game (_settings_client.gui.autosave_on_exit)
Definition: saveload.cpp:2806
Base for aircraft.
#define lastof(x)
Get the last element of an fixed size array.
Definition: depend.cpp:50
The client is spectating.
Definition: company_type.h:37
The client wants a new company.
Definition: company_type.h:36
Simple vector template class.
Functions related to world/map generation.
static char * GetDriversInfo(char *p, const char *last)
Build a human readable list of available drivers, grouped by type.
Definition: driver.cpp:191
Functions to make screenshots.
bool UpdateNewGRFConfigPalette(int32 p1)
Update the palettes of the graphics from the config file.
bool reload_cfg
reload the config file before restarting
static bool SetSet(const char *name)
Set the set to be used.
static bool IsStandardRoadStopTile(TileIndex t)
Is tile t a standard (non-drive through) road stop station?
Definition: station_map.h:224
void SaveToConfig()
Save the values to the configuration file.
Definition: settings.cpp:1740
Base set has 8 bpp sprites only.
int32 Year
Type for the year, note: 0 based, i.e. starts at the year 0.
Definition: date_type.h:20
uint8 map_x
X size of map.
RAII class for measuring simple elements of performance.
StationCargoList cargo
The cargo packets of cargo waiting in this station.
Definition: station_base.h:255
Subdirectory for all base data (base sets, intro game)
Definition: fileio_type.h:118
static T max(const T a, const T b)
Returns the maximum of two values.
Definition: math_func.hpp:26
uint32 last_newgrf_count
the numbers of NewGRFs we found during the last scan
Functions related to laying out the texts.
byte vehstatus
Status.
Definition: vehicle_base.h:317
Year _cur_year
Current year, starting at 0.
Definition: date.cpp:26
Cached, frequently calculated values.
Time spent processing aircraft.
static void Reset(PerformanceElement elem)
Store the previous accumulator value and reset for a new cycle of accumulating measurements.
static Train * From(Vehicle *v)
Converts a Vehicle to SpecializedVehicle with type checking.
void InputLoop()
Regular call from the global game loop.
Definition: window.cpp:3068
CompanySettings settings
settings specific for each company
Definition: company_base.h:126
const char * GetSaveLoadErrorString()
Get the string representation of the error message.
Definition: saveload.cpp:2427
GoodsEntry goods[NUM_CARGO]
Goods at this station.
Definition: station_base.h:472
File is being saved.
Definition: fileio_type.h:52
struct GRFConfig * next
NOSAVE: Next item in the linked list.
Speed of gameloop processing.
Functions/types etc.
Load file for checking and/or preview.
Definition: fileio_type.h:50
static const uint32 GENERATE_NEW_SEED
Create a new random seed.
Definition: genworld.h:25
static uint ClampU(const uint a, const uint min, const uint max)
Clamp an unsigned integer between an interval.
Definition: math_func.hpp:184
bool _network_available
is network mode available?
Definition: network.cpp:58
Variables that are cached to improve performance and such.
Definition: train.h:72
bool _network_dedicated
are we a dedicated server?
Definition: network.cpp:59
T * Append(uint to_add=1)
Append an item and return it.
Class to backup a specific variable and restore it later.
Definition: backup_type.hpp:23
CompanyByte _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
Definition: company_cmd.cpp:46
static char * GetConsoleList(char *p, const char *last, bool newest_only=false)
Wrapper function for GameScanner::GetConsoleList.
Definition: game_core.cpp:230
static void CheckCaches()
Check the validity of some of the caches.
Definition: openttd.cpp:1204
ThreadMutex * _modal_progress_work_mutex
Rights for the performing work.
Definition: progress.cpp:21
Functions related to (drawing on) viewports.
Pseudo random number generator.
uint8 map_y
Y size of map.
void InitFreeType(bool monospace)
(Re)initialize the freetype related things, i.e.
Definition: fontcache.cpp:662
Library for parsing command-line options.
void ProcessAsyncSaveFinish()
Handle async save finishes.
Definition: saveload.cpp:392
void CDECL ShowInfoF(const char *str,...)
Shows some information on the console/a popup box depending on the OS.
Definition: openttd.cpp:134
Save game or scenario file.
Definition: fileio_type.h:33
Interface for filtering a savegame till it is loaded.
old or new savegame
Definition: fileio_type.h:20
old or new scenario
Definition: fileio_type.h:21
Functions to read fonts from files and cache them.
Critical errors, the MessageBox is shown in all cases.
Definition: error.h:26
void ShowErrorMessage(StringID summary_msg, StringID detailed_msg, WarningLevel wl, int x=0, int y=0, const GRFFile *textref_stack_grffile=NULL, uint textref_stack_size=0, const uint32 *textref_stack=NULL)
Display an error message in a window.
Definition: error_gui.cpp:378
void SetDParamStr(uint n, const char *str)
This function is used to "bind" a C string to a OpenTTD dparam slot.
Definition: strings.cpp:282
LoadCheckData _load_check_data
Data loaded from save during SL_LOAD_CHECK.
Definition: fios_gui.cpp:40
Aircraft vehicle type.
Definition: vehicle_type.h:29
Tile animation!
static char * GetBlittersInfo(char *p, const char *last)
Fill a buffer with information about the blitters.
Definition: factory.hpp:158
Callback structure of statements to be executed after the NewGRF scan.
Definition: openttd.cpp:393
void GamelogInfo(LoggedAction *gamelog_action, uint gamelog_actions, uint32 *last_ottd_rev, byte *ever_modified, bool *removed_newgrfs)
Get some basic information from the given gamelog.
Definition: gamelog.cpp:802
NetworkSettings network
settings related to the network
Vehicle is crashed.
Definition: vehicle_base.h:39
bool _is_network_server
Does this client wants to be a network-server?
Definition: network.cpp:60
void UpdateCache()
Update the caches of this ship.
Definition: ship_cmd.cpp:205
void GamelogReset()
Resets and frees all memory allocated - used before loading or starting a new game.
Definition: gamelog.cpp:112
Functions/types related to saving and loading games.
virtual bool IsPrimaryVehicle() const
Whether this is the primary vehicle in the chain.
Definition: vehicle_base.h:433
void MusicLoop()
Check music playback status and start/stop/song-finished.
Definition: music_gui.cpp:426
void GenerateWorld(GenWorldMode mode, uint size_x, uint size_y, bool reset_settings)
Generate a world.
Definition: genworld.cpp:298
A music driver, needs to be before sound to properly shut down extmidi forked music players...
Definition: driver.h:43
Functions related to errors.
Load a heightmap and start a new game from it.
Definition: openttd.h:37
char * _ini_blitter
The blitter as stored in the configuration file.
Definition: driver.cpp:31
UnitID unitnumber
unit number, for display purposes only
Definition: vehicle_base.h:291
virtual void SetVolume(byte vol)=0
Set the volume, if possible.
Switch to scenario editor.
Definition: openttd.h:30
DateFract _date_fract
Fractional part of the day.
Definition: date.cpp:29
static void GameLoop()
Called every game-tick to let AIs do something.
Definition: ai_core.cpp:69
SaveOrLoadResult
Save or load result codes.
Definition: saveload.h:299
static void ShowHelp()
Show the help message when someone passed a wrong parameter.
Definition: openttd.cpp:147
void UpdateAircraftCache(Aircraft *v, bool update_range=false)
Update cached values of an aircraft.
virtual void Stop()=0
Stop this driver.
CompanySettings company
default values for per-company settings
Information about GRF, used in the game and (part of it) in savegames.
char * _ini_sounddriver
The sound driver a stored in the configuration file.
Definition: driver.cpp:27
void ConsistChanged(ConsistChangeFlags allowed_changes)
Recalculates the cached stuff of a train.
Definition: train_cmd.cpp:109
GameMode
Mode which defines the state of the game.
Definition: openttd.h:18
Old save game or scenario file.
Definition: fileio_type.h:32
VehicleDefaultSettings vehicle
default settings for vehicles
Functions related to engines.
static void SwitchMode(PersistentStorageMode mode, bool ignore_prev_mode=false)
Clear temporary changes made since the last call to SwitchMode, and set whether subsequent changes sh...
static void Uninitialize(bool keepConfig)
Uninitialize the AI system.
Definition: ai_core.cpp:179
static Blitter * SelectBlitter(const char *name)
Find the requested blitter and return his class.
Definition: factory.hpp:96
Time spend processing road vehicles.
void IConsoleCmdExec(const char *cmdstr)
Execute a given command passed to us.
Definition: console.cpp:409
Functions related to setting/changing the settings.
static const uint16 NETWORK_DEFAULT_DEBUGLOG_PORT
The default port debug-log is sent to (TCP)
Definition: config.h:33
ClientSettings _settings_client
The current settings for this game.
Definition: settings.cpp:76
void CheckIntegrity(const RoadStop *rs) const
Check the integrity of the data in this struct.
Definition: roadstop.cpp:382
Functions related to modal progress.
A path without any base directory.
Definition: fileio_type.h:127
virtual void OnNewGRFsScanned()
Called whenever the NewGRF scan completed.
Definition: openttd.cpp:420
Base for all music playback.
Definition of base types and functions in a cross-platform compatible way.
Enter the gameloop, changes will be permanent.
char * _config_file
Configuration file of OpenTTD.
Definition: settings.cpp:80
void Clear()
Reset read data.
Definition: fios_gui.cpp:49
void CDECL usererror(const char *s,...)
Error handling for fatal user errors.
Definition: openttd.cpp:92
A number of safeguards to prevent using unsafe methods.
void StateGameLoop()
State controlling game loop.
Definition: openttd.cpp:1354
void SetLocalCompany(CompanyID new_company)
Sets the local company and updates the settings that are set on a per-company basis to reflect the co...
Declaration of link graph schedule used for cargo distribution.
GameSettings _settings_newgame
Game settings for new games (updated from the intro screen).
Definition: settings.cpp:78
First company, same as owner.
Definition: company_type.h:24
static void SaveToConfig()
Save all WindowDesc settings to _windows_file.
Definition: window.cpp:166
uint8 _network_reconnect
Reconnect timeout.
Definition: network.cpp:66
void FillNewGRFVehicleCache(const Vehicle *v)
Fill the grf_cache of the given vehicle.
Scan for scenarios and heightmaps.
Definition: fileio_func.h:105
Base directory for all savegames.
Definition: fileio_type.h:112
Subdirectory of save for autosaves.
Definition: fileio_type.h:113
const char * join_server_password
The password to join the server with.
Definition: openttd.cpp:399
byte starting_colour
default color scheme for the company to start a new game with
static AIConfig * GetConfig(CompanyID company, ScriptSettingSource source=SSS_DEFAULT)
Get the config of a company.
Definition: ai_config.cpp:47
void InvalidateCache()
Invalidates the cached data and rebuild it.
char * stredup(const char *s, const char *last)
Create a duplicate of the given string.
Definition: string.cpp:138
AfterNewGRFScan(bool *save_config_ptr)
Create a new callback.
Definition: openttd.cpp:409
void LoadFromConfig(bool minimal)
Load the values from the configuration files.
Definition: settings.cpp:1710
Console functions used outside of the console code.
char * error_data
Data to pass to SetDParamStr when displaying error.
Definition: fios.h:36
#define GETOPT_END()
Option terminator.
Definition: getoptdata.h:109
void ScheduleErrorMessage(const ErrorMessageData &data)
Schedule an error.
Definition: error_gui.cpp:440
char * DumpDebugFacilityNames(char *buf, char *last)
Dump the available debug facility names in the help text.
Definition: debug.cpp:88
bool SafeLoad(const char *filename, SaveLoadOperation fop, DetailedFileType dft, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf=NULL)
Load the specified savegame but on error do different things.
Definition: openttd.cpp:1013
A sound driver.
Definition: driver.h:44
static void ShutdownGame()
Uninitializes drivers, frees allocated memory, cleans pools, ...
Definition: openttd.cpp:287
bool fix_at
mouse is moving, but cursor is not (used for scrolling)
Definition: gfx_type.h:122
SaveOrLoadResult LoadWithFilter(LoadFilter *reader)
Load the game using a (reader) filter.
Definition: saveload.cpp:2701
const char * join_company_password
The password to join the company with.
Definition: openttd.cpp:400
bool HasErrors()
Check whether loading the game resulted in errors.
Definition: fios.h:69
The tile has no ownership.
Definition: company_type.h:27
bool autosave_on_exit
save an autosave when you quit the game, but do not ask "Do you really want to quit?"
Northwest.
void CheckIndustries()
Verify whether the generated industries are complete, and warn the user if not.
Generate an empty map (sea-level)
Definition: genworld.h:30
static MusicDriver * GetInstance()
Get the currently active instance of the music driver.
char * opt
Option value, if available (else NULL).
Definition: getoptdata.h:33
Basic functions/variables used all over the place.
Time spent processing other world features.
SaveOrLoadResult SaveOrLoad(const char *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:2721
void NetworkShutDown()
This shuts the network down.
Definition: network.cpp:1091
bool DoCommandP(const CommandContainer *container, bool my_cmd)
Shortcut for the long DoCommandP when having a container with the data.
Definition: command.cpp:531
NetworkServerGameInfo _network_game_info
Information about our game.
Definition: network.cpp:61
PauseModeByte _pause_mode
The current pause mode.
Definition: gfx.cpp:48
Road vehicle type.
Definition: vehicle_type.h:27
bool save_config
The save config setting.
Definition: openttd.cpp:402
File is being loaded.
Definition: fileio_type.h:51
void InitializeLanguagePacks()
Make a list of the available language packs.
Definition: strings.cpp:1958
ThreadMutex * _modal_progress_paint_mutex
Rights for the painting.
Definition: progress.cpp:23
StringID error
Error message from loading. INVALID_STRING_ID if no error.
Definition: fios.h:35
Vehicle * First() const
Get the first vehicle of this vehicle chain.
Definition: vehicle_base.h:594
void WaitTillGeneratedWorld()
This will wait for the thread to finish up his work.
Definition: genworld.cpp:242
SaveLoadOperation
Operation performed on the file.
Definition: fileio_type.h:49
void CallWindowGameTickEvent()
Dispatch OnGameTick event over all windows.
Definition: window.cpp:3333
Maximum number of companies.
Definition: company_type.h:25
void UnInitWindowSystem()
Close down the windowing system.
Definition: window.cpp:1898
class GameConfig * game_config
settings for gamescript
Save game.
Definition: openttd.h:33
Functions to be called to log a crash.
char * dedicated_host
Hostname for the dedicated server.
Definition: openttd.cpp:396
Ship vehicle type.
Definition: vehicle_type.h:28
uint DoScan(Subdirectory sd)
Perform the scanning of a particular subdirectory.
Definition: fileio.cpp:637
static void MemCpyT(T *destination, const T *source, size_t num=1)
Type-safe version of memcpy().
Definition: mem_func.hpp:25
StringID name
The name for this object.
Definition: newgrf_object.h:64
#define DEBUG(name, level,...)
Output a line of debugging information.
Definition: debug.h:36
static void Initialize()
Initialize the Game system.
Definition: game_core.cpp:59
char map_name[NETWORK_NAME_LENGTH]
Map which is played ["random" for a randomized map].
Definition: game.h:29
uint16 server_port
port the server listens on
CompanyInfrastructure infrastructure
NOSAVE: Counts of company owned infrastructure.
Definition: company_base.h:130
static SoundDriver * GetInstance()
Get the currently active instance of the sound driver.
void DeleteWindowById(WindowClass cls, WindowNumber number, bool force)
Delete a window by its class and window number (if it is open).
Definition: window.cpp:1146
void GenerateWorldSetCallback(GWDoneProc *proc)
Set here the function, if any, that you want to be called when landscape generation is done...
Definition: genworld.cpp:223
Callback for NewGRF scanning.
byte music_vol
The requested music volume.
void IncreaseDate()
Increases the tick counter, increases date and possibly calls procedures that have to be called daily...
Definition: date.cpp:275
void LoadHotkeysFromConfig()
Load the hotkeys from the config file.
Definition: hotkeys.cpp:331
Functions related to companies.
No support for 8bpp by OS or hardware, force 32bpp blitters.
Definition: gfx_type.h:317
static const uint16 NETWORK_DEFAULT_PORT
The default port of the game server (TCP & UDP)
Definition: config.h:31
The data of the error message.
Definition: error.h:30
Leave the gameloop, changes will be temporary.
uint32 generation_seed
noise seed for world generation
Declaration of functions and types defined in highscore.h and highscore_gui.h.
Data storage for parsing command line options.
Definition: getoptdata.h:32
GUISettings gui
settings related to the GUI
static bool ResetToCurrentNewGRFConfig()
Tries to reset the engine mapping to match the current NewGRF configuration.
Definition: engine.cpp:528
CargoList that is used for vehicles.
Definition: cargopacket.h:283
Time spent processing ships.
void DeterminePaths(const char *exe)
Acquire the base paths (personal dir and game data dir), fill all other paths (save dir...
Definition: fileio.cpp:1162
static void DoAutosave()
Create an autosave.
Definition: openttd.cpp:1432
void RoadVehUpdateCache(RoadVehicle *v, bool same_length=false)
Update the cache of a road vehicle.
static bool StrEmpty(const char *s)
Check if a string buffer is empty.
Definition: string_func.h:59
static void SelectDriver(const char *name, Driver::Type type)
Find the requested driver and return its class.
Definition: driver.cpp:88
void ResetNewGRFData()
Reset all NewGRF loaded data.
Definition: newgrf.cpp:8268
Declarations for savegames operations.
CompanyByte _current_company
Company currently doing an action.
Definition: company_cmd.cpp:47
Vehicle * Next() const
Get the next vehicle of this vehicle.
Definition: vehicle_base.h:581
static VideoDriver * GetInstance()
Get the currently active instance of the video driver.
byte colour
Company colour.
Definition: company_base.h:68
static void KillAll()
Kill any and all AIs we manage.
Definition: ai_core.cpp:154
static void LoadFromConfig()
Load all WindowDesc settings from _windows_file.
Definition: window.cpp:143
Restart –> &#39;Random game&#39; with current settings.
Definition: openttd.h:29
void CDECL error(const char *s,...)
Error handling for fatal non-user errors.
Definition: openttd.cpp:112
static char * GetSetsList(char *p, const char *last)
Returns a list with the sets.
OwnerByte owner
Which company owns the vehicle?
Definition: vehicle_base.h:273
void ResetGRFConfig(bool defaults)
Reset the current GRF Config to either blank or newgame settings.
char * network_conn
Information about the server to connect to, or NULL.
Definition: openttd.cpp:398
void RebuildSubsidisedSourceAndDestinationCache()
Perform a full rebuild of the subsidies cache.
Definition: subsidy.cpp:133
static void Clear()
Clear all link graphs and jobs from the schedule.
virtual void MainLoop()=0
Perform the actual drawing.
char * strecpy(char *dst, const char *src, const char *last)
Copies characters from one buffer to another.
Definition: depend.cpp:68
VehicleDefaultSettings _old_vds
Used for loading default vehicles settings from old savegames.
Definition: settings.cpp:79
TownCache cache
Container for all cacheable data.
Definition: town.h:58
Town data structure.
Definition: town.h:55
bool in_window
mouse inside this window, determines drawing logic
Definition: gfx_type.h:143
SwitchMode _switch_mode
The next mainloop command.
Definition: gfx.cpp:47
char default_company_pass[NETWORK_PASSWORD_LENGTH]
default password for new companies in encrypted form
uint gamelog_actions
Number of gamelog actions.
Definition: fios.h:49
const Entry * GetEntry(DiagDirection dir) const
Get the drive through road stop entry struct for the given direction.
void ScanNewGRFFiles(NewGRFScanCallback *callback)
Scan for all NewGRFs.
Statusbar (at the bottom of your screen); Window numbers:
Definition: window_type.h:59
Base functions for all Games.
Functions related to commands.
Network functions used by other parts of OpenTTD.
char name[MAX_PATH]
Name of the file.
Definition: saveload.h:310
bool _network_server
network-server is active
Definition: network.cpp:57
SaveLoadOperation file_op
File operation to perform.
Definition: saveload.h:307
A Stop for a Road Vehicle.
Definition: roadstop_base.h:24
static void ReduceLineCache()
Reduce the size of linecache if necessary to prevent infinite growth.
Definition: gfx_layout.cpp:895
void SaveHotkeysToConfig()
Save the hotkeys to the config file.
Definition: hotkeys.cpp:337
void Clear()
Remove all items from the list.
void UninitFreeType()
Free everything allocated w.r.t.
Definition: fontcache.cpp:679
void InitializeRailGUI()
Resets the rail GUI - sets default railtype to build and resets the signal GUI.
Definition: rail_gui.cpp:1973
Perform palette animation.
Definition: openttd.h:46
static void LoadIntroGame(bool load_newgrfs=true)
Load the introduction game.
Definition: openttd.cpp:324
class AIConfig * ai_config[MAX_COMPANIES]
settings per company
Colours _company_colours[MAX_COMPANIES]
NOSAVE: can be determined from company structs.
Definition: company_cmd.cpp:48
void NetworkBackgroundLoop()
We have to do some (simple) background stuff that runs normally, even when we are not in multiplayer...
Definition: network.cpp:856
AbstractFileType abstract_ftype
Abstract type of file (scenario, heightmap, etc).
Definition: saveload.h:309
byte max_num_autosaves
controls how many autosavegames are made before the game starts to overwrite (names them 0 to max_num...
header file for electrified rail specific functions
A video driver.
Definition: driver.h:45
int GetOpt()
Find the next option.
Definition: getoptdata.cpp:24
Base for ships.
void NetworkDisconnect(bool blocking, bool close_admins)
We want to disconnect from the host/clients.
Definition: network.cpp:798
Load scenario from scenario editor.
Definition: openttd.h:36
uint32 generation_seed
Seed for the new game.
Definition: openttd.cpp:395
static const StringID INVALID_STRING_ID
Constant representing an invalid string (16bit in case it is used in savegames)
Definition: strings_type.h:19
static void free(const void *ptr)
Version of the standard free that accepts const pointers.
Definition: depend.cpp:114
static void ParseResolution(Dimension *res, const char *s)
Extract the resolution from the given string and store it in the &#39;res&#39; parameter. ...
Definition: openttd.cpp:270
char last_host[NETWORK_HOSTNAME_LENGTH]
IP address of the last joined server.
declaration of OTTD revision dependent variables
static bool HasBit(const T x, const uint8 y)
Checks if a bit in a value is set.
bool HasNewGrfs()
Check whether the game uses any NewGrfs.
Definition: fios.h:78
completed successfully
Definition: saveload.h:300
void InitializeSpriteSorter()
Choose the "best" sprite sorter and set _vp_sprite_sorter.
Definition: viewport.cpp:3120
Types related to sprite sorting.
void Restore()
Restore the variable.
Base functions for all AIs.
#define FOR_ALL_VEHICLES(var)
Iterate over all vehicles.
Definition: vehicle_base.h:987
char * _ini_musicdriver
The music driver a stored in the configuration file.
Definition: driver.cpp:29
Base of the town class.
const T * Get(uint index) const
Get the pointer to item "number" (const)
The normal zoom level.
Definition: zoom_type.h:24
void RunTileLoop()
Gradually iterate over all tiles on the map, calling their TileLoopProcs once every 256 ticks...
Definition: landscape.cpp:803
GRF file does not exactly match the requested GRF (different MD5SUM), but grfid matches) ...
Definition: newgrf_config.h:27
GameCreationSettings game_creation
settings used during the creation of a game (map)
void SetMode(FiosType ft)
Set the mode and file type of the file to save or load based on the type of file entry at the file sy...
Definition: saveload.cpp:2850
byte CargoID
Cargo slots to indicate a cargo type within a game.
Definition: cargo_type.h:22
DetailedFileType detail_ftype
Concrete file type (PNG, BMP, old save, etc).
Definition: saveload.h:308
void SetDebugString(const char *s)
Set debugging levels by parsing the text in s.
Definition: debug.cpp:180
StringList _network_bind_list
The addresses to bind on.
Definition: network.cpp:67
A game paused for saving/loading.
Definition: openttd.h:60
Generate random land within scenario editor.
Definition: openttd.h:35
virtual void BeginCritical(bool allow_recursive=false)=0
Begin the critical section.
AIConfig stores the configuration settings of every AI.
Owner
Enum for all companies/owners.
Definition: company_type.h:20
void ResetWindowSystem()
Reset the windowing system, by means of shutting it down followed by re-initialization.
Definition: window.cpp:1918
void InvalidateCache()
Invalidates the cached data and rebuilds it.
int numleft
Number of arguments left in argv.
Definition: getoptdata.h:34
const char * NetworkChangeCompanyPassword(CompanyID company_id, const char *password)
Change the company password of a given company.
Definition: network.cpp:174
GUI functions that shouldn&#39;t be here.
Functions related to news.
void SaveToHighScore()
Save HighScore table to file.
Definition: highscore.cpp:128
bool MakeHeightmapScreenshot(const char *filename)
Make a heightmap of the current map.
Definition: screenshot.cpp:793
Base classes/functions for stations.
Errors (eg. saving/loading failed)
Definition: error.h:25
Date _date
Current date in days (day counter)
Definition: date.cpp:28
void ResetCompanyLivery(Company *c)
Reset the livery schemes to the company&#39;s primary colour.
Get the Script config from the current game.
An invalid company.
Definition: company_type.h:32
Year startyear
The start year.
Definition: openttd.cpp:394
DetailedFileType
Kinds of files in each AbstractFileType.
Definition: fileio_type.h:30
VehicleTypeByte type
Type of vehicle.
Definition: vehicle_type.h:56
Dimensions (a width and height) of a rectangle in 2D.
Valid changes while vehicle is driving, and possibly changing tracks.
Definition: train.h:51
static void SetErrorMessage(const char *message)
Sets a message for the error message handler.
Definition: crashlog.cpp:497
Generate a random map for SE.
Definition: genworld.h:31
bool _do_autosave
are we doing an autosave at the moment?
Definition: saveload.cpp:65
Year starting_year
starting date
void AnimateAnimatedTiles()
Animate all tiles in the animated tile list, i.e. call AnimateTile on them.
Class for backupping variables and making sure they are restored later.
Station data structure.
Definition: station_base.h:446
Time spent processing trains.
Factory to &#39;query&#39; all available blitters.
static const GraphicsSet * GetUsedSet()
Return the used set.
Functions related to subsidies.
New Game –> &#39;Random game&#39;.
Definition: openttd.h:28
SwitchMode
Mode which defines what mode we&#39;re switching to.
Definition: openttd.h:26
static bool HasModalProgress()
Check if we are currently in a modal progress state.
Definition: progress.h:23
void LoadFromHighScore()
Initialize the highscore table to 0 and if any file exists, load in values.
Definition: highscore.cpp:156
Save heightmap.
Definition: openttd.h:34
GroundVehicleCache gcache
Cache of often calculated values.
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
Definition: gfx.cpp:1463
Train vehicle type.
Definition: vehicle_type.h:26
Sum of all GS/AI scripts.
bool SettingsDisableElrail(int32 p1)
_settings_game.disable_elrail callback
Definition: elrail.cpp:594
Base for the NewGRF implementation.
static const char * ini_set
The set as saved in the config file.
error that was caught in the middle of updating game state, need to clear it. (can only happen during...
Definition: saveload.h:302
pause the game
Definition: command_type.h:255