src/openttd.c
branchcustombridgeheads
changeset 5649 55c8267c933f
parent 5648 1608018c5ff2
child 5650 aefc131bf5ce
equal deleted inserted replaced
5648:1608018c5ff2 5649:55c8267c933f
     1 /* $Id$ */
       
     2 
       
     3 #include "stdafx.h"
       
     4 #include "string.h"
       
     5 #include "table/strings.h"
       
     6 #include "debug.h"
       
     7 #include "driver.h"
       
     8 #include "saveload.h"
       
     9 #include "strings.h"
       
    10 #include "map.h"
       
    11 #include "tile.h"
       
    12 #include "void_map.h"
       
    13 
       
    14 #define VARDEF
       
    15 #include "openttd.h"
       
    16 #include "bridge_map.h"
       
    17 #include "functions.h"
       
    18 #include "mixer.h"
       
    19 #include "spritecache.h"
       
    20 #include "strings.h"
       
    21 #include "gfx.h"
       
    22 #include "gfxinit.h"
       
    23 #include "gui.h"
       
    24 #include "station.h"
       
    25 #include "station_map.h"
       
    26 #include "town_map.h"
       
    27 #include "tunnel_map.h"
       
    28 #include "vehicle.h"
       
    29 #include "viewport.h"
       
    30 #include "window.h"
       
    31 #include "player.h"
       
    32 #include "command.h"
       
    33 #include "town.h"
       
    34 #include "industry.h"
       
    35 #include "news.h"
       
    36 #include "engine.h"
       
    37 #include "sound.h"
       
    38 #include "economy.h"
       
    39 #include "fileio.h"
       
    40 #include "hal.h"
       
    41 #include "airport.h"
       
    42 #include "console.h"
       
    43 #include "screenshot.h"
       
    44 #include "network/network.h"
       
    45 #include "signs.h"
       
    46 #include "depot.h"
       
    47 #include "waypoint.h"
       
    48 #include "ai/ai.h"
       
    49 #include "train.h"
       
    50 #include "yapf/yapf.h"
       
    51 #include "settings.h"
       
    52 #include "genworld.h"
       
    53 #include "date.h"
       
    54 #include "clear_map.h"
       
    55 #include "fontcache.h"
       
    56 #include "newgrf_config.h"
       
    57 
       
    58 #include "bridge_map.h"
       
    59 #include "clear_map.h"
       
    60 #include "rail_map.h"
       
    61 #include "road_map.h"
       
    62 #include "water_map.h"
       
    63 #include "industry_map.h"
       
    64 
       
    65 #include <stdarg.h>
       
    66 
       
    67 void CallLandscapeTick(void);
       
    68 void IncreaseDate(void);
       
    69 void DoPaletteAnimations(void);
       
    70 void MusicLoop(void);
       
    71 void ResetMusic(void);
       
    72 void InitializeStations(void);
       
    73 void DeleteAllPlayerStations(void);
       
    74 
       
    75 extern void SetDifficultyLevel(int mode, GameOptions *gm_opt);
       
    76 extern void DoStartupNewPlayer(bool is_ai);
       
    77 extern void ShowOSErrorBox(const char *buf);
       
    78 
       
    79 /* TODO: usrerror() for errors which are not of an internal nature but
       
    80  * caused by the user, i.e. missing files or fatal configuration errors.
       
    81  * Post-0.4.0 since Celestar doesn't want this in SVN before. --pasky */
       
    82 
       
    83 void CDECL error(const char *s, ...)
       
    84 {
       
    85 	va_list va;
       
    86 	char buf[512];
       
    87 
       
    88 	va_start(va, s);
       
    89 	vsnprintf(buf, lengthof(buf), s, va);
       
    90 	va_end(va);
       
    91 
       
    92 	ShowOSErrorBox(buf);
       
    93 	if (_video_driver != NULL) _video_driver->stop();
       
    94 
       
    95 	assert(0);
       
    96 	exit(1);
       
    97 }
       
    98 
       
    99 void CDECL ShowInfoF(const char *str, ...)
       
   100 {
       
   101 	va_list va;
       
   102 	char buf[1024];
       
   103 	va_start(va, str);
       
   104 	vsnprintf(buf, lengthof(buf), str, va);
       
   105 	va_end(va);
       
   106 	ShowInfo(buf);
       
   107 }
       
   108 
       
   109 
       
   110 void *ReadFileToMem(const char *filename, size_t *lenp, size_t maxsize)
       
   111 {
       
   112 	FILE *in;
       
   113 	byte *mem;
       
   114 	size_t len;
       
   115 
       
   116 	in = fopen(filename, "rb");
       
   117 	if (in == NULL) return NULL;
       
   118 
       
   119 	fseek(in, 0, SEEK_END);
       
   120 	len = ftell(in);
       
   121 	fseek(in, 0, SEEK_SET);
       
   122 	if (len > maxsize || (mem = malloc(len + 1)) == NULL) {
       
   123 		fclose(in);
       
   124 		return NULL;
       
   125 	}
       
   126 	mem[len] = 0;
       
   127 	if (fread(mem, len, 1, in) != 1) {
       
   128 		fclose(in);
       
   129 		free(mem);
       
   130 		return NULL;
       
   131 	}
       
   132 	fclose(in);
       
   133 
       
   134 	*lenp = len;
       
   135 	return mem;
       
   136 }
       
   137 
       
   138 static void showhelp(void)
       
   139 {
       
   140 	extern const char _openttd_revision[];
       
   141 	char buf[4096], *p;
       
   142 
       
   143 	p = buf;
       
   144 
       
   145 	p += snprintf(p, lengthof(buf), "OpenTTD %s\n", _openttd_revision);
       
   146 	p = strecpy(p,
       
   147 		"\n"
       
   148 		"\n"
       
   149 		"Command line options:\n"
       
   150 		"  -v drv              = Set video driver (see below)\n"
       
   151 		"  -s drv              = Set sound driver (see below)\n"
       
   152 		"  -m drv              = Set music driver (see below)\n"
       
   153 		"  -r res              = Set resolution (for instance 800x600)\n"
       
   154 		"  -h                  = Display this help text\n"
       
   155 		"  -t year             = Set starting year\n"
       
   156 		"  -d [[fac=]lvl[,...]]= Debug mode\n"
       
   157 		"  -e                  = Start Editor\n"
       
   158 		"  -g [savegame]       = Start new/save game immediately\n"
       
   159 		"  -G seed             = Set random seed\n"
       
   160 		"  -n [ip:port#player] = Start networkgame\n"
       
   161 		"  -D [ip][:port]      = Start dedicated server\n"
       
   162 #if !defined(__MORPHOS__) && !defined(__AMIGA__) && !defined(WIN32)
       
   163 		"  -f                  = Fork into the background (dedicated only)\n"
       
   164 #endif
       
   165 		"  -i                  = Force to use the DOS palette\n"
       
   166 		"                          (use this if you see a lot of pink)\n"
       
   167 		"  -c config_file      = Use 'config_file' instead of 'openttd.cfg'\n"
       
   168 		"  -x                  = Do not automatically save to config file on exit\n",
       
   169 		lastof(buf)
       
   170 	);
       
   171 
       
   172 	p = GetDriverList(p, lastof(buf));
       
   173 
       
   174 	ShowInfo(buf);
       
   175 }
       
   176 
       
   177 
       
   178 typedef struct {
       
   179 	char *opt;
       
   180 	int numleft;
       
   181 	char **argv;
       
   182 	const char *options;
       
   183 	char *cont;
       
   184 } MyGetOptData;
       
   185 
       
   186 static void MyGetOptInit(MyGetOptData *md, int argc, char **argv, const char *options)
       
   187 {
       
   188 	md->cont = NULL;
       
   189 	md->numleft = argc;
       
   190 	md->argv = argv;
       
   191 	md->options = options;
       
   192 }
       
   193 
       
   194 static int MyGetOpt(MyGetOptData *md)
       
   195 {
       
   196 	char *s,*r,*t;
       
   197 
       
   198 	s = md->cont;
       
   199 	if (s != NULL)
       
   200 		goto md_continue_here;
       
   201 
       
   202 	for (;;) {
       
   203 		if (--md->numleft < 0) return -1;
       
   204 
       
   205 		s = *md->argv++;
       
   206 		if (*s == '-') {
       
   207 md_continue_here:;
       
   208 			s++;
       
   209 			if (*s != 0) {
       
   210 				// Found argument, try to locate it in options.
       
   211 				if (*s == ':' || (r = strchr(md->options, *s)) == NULL) {
       
   212 					// ERROR!
       
   213 					return -2;
       
   214 				}
       
   215 				if (r[1] == ':') {
       
   216 					// Item wants an argument. Check if the argument follows, or if it comes as a separate arg.
       
   217 					if (!*(t = s + 1)) {
       
   218 						// It comes as a separate arg. Check if out of args?
       
   219 						if (--md->numleft < 0 || *(t = *md->argv) == '-') {
       
   220 							// Check if item is optional?
       
   221 							if (r[2] != ':')
       
   222 								return -2;
       
   223 							md->numleft++;
       
   224 							t = NULL;
       
   225 						} else {
       
   226 							md->argv++;
       
   227 						}
       
   228 					}
       
   229 					md->opt = t;
       
   230 					md->cont = NULL;
       
   231 					return *s;
       
   232 				}
       
   233 				md->opt = NULL;
       
   234 				md->cont = s;
       
   235 				return *s;
       
   236 			}
       
   237 		} else {
       
   238 			// This is currently not supported.
       
   239 			return -2;
       
   240 		}
       
   241 	}
       
   242 }
       
   243 
       
   244 
       
   245 static void ParseResolution(int res[2], const char *s)
       
   246 {
       
   247 	char *t = strchr(s, 'x');
       
   248 	if (t == NULL) {
       
   249 		ShowInfoF("Invalid resolution '%s'", s);
       
   250 		return;
       
   251 	}
       
   252 
       
   253 	res[0] = clamp(strtoul(s, NULL, 0), 64, MAX_SCREEN_WIDTH);
       
   254 	res[1] = clamp(strtoul(t + 1, NULL, 0), 64, MAX_SCREEN_HEIGHT);
       
   255 }
       
   256 
       
   257 static void InitializeDynamicVariables(void)
       
   258 {
       
   259 	/* Dynamic stuff needs to be initialized somewhere... */
       
   260 	_town_sort     = NULL;
       
   261 	_industry_sort = NULL;
       
   262 }
       
   263 
       
   264 static void UnInitializeDynamicVariables(void)
       
   265 {
       
   266 	/* Dynamic stuff needs to be free'd somewhere... */
       
   267 	CleanPool(&_Town_pool);
       
   268 	CleanPool(&_Industry_pool);
       
   269 	CleanPool(&_Station_pool);
       
   270 	CleanPool(&_Vehicle_pool);
       
   271 	CleanPool(&_Sign_pool);
       
   272 	CleanPool(&_Order_pool);
       
   273 
       
   274 	free((void*)_town_sort);
       
   275 	free((void*)_industry_sort);
       
   276 }
       
   277 
       
   278 static void UnInitializeGame(void)
       
   279 {
       
   280 	UnInitWindowSystem();
       
   281 
       
   282 	free(_config_file);
       
   283 }
       
   284 
       
   285 static void LoadIntroGame(void)
       
   286 {
       
   287 	char filename[256];
       
   288 
       
   289 	_game_mode = GM_MENU;
       
   290 	CLRBITS(_display_opt, DO_TRANS_BUILDINGS); // don't make buildings transparent in intro
       
   291 	_opt_ptr = &_opt_newgame;
       
   292 	ResetGRFConfig(false);
       
   293 
       
   294 	// Setup main window
       
   295 	ResetWindowSystem();
       
   296 	SetupColorsAndInitialWindow();
       
   297 
       
   298 	// Generate a world.
       
   299 	snprintf(filename, lengthof(filename), "%sopntitle.dat",  _paths.data_dir);
       
   300 #if defined SECOND_DATA_DIR
       
   301 	if (SaveOrLoad(filename, SL_LOAD) != SL_OK) {
       
   302 		snprintf(filename, lengthof(filename), "%sopntitle.dat",  _paths.second_data_dir);
       
   303 	}
       
   304 #endif
       
   305 	if (SaveOrLoad(filename, SL_LOAD) != SL_OK) {
       
   306 		GenerateWorld(GW_EMPTY, 64, 64); // if failed loading, make empty world.
       
   307 		WaitTillGeneratedWorld();
       
   308 	}
       
   309 
       
   310 	_pause = 0;
       
   311 	SetLocalPlayer(0);
       
   312 	/* Make sure you can't scroll in the menu */
       
   313 	_scrolling_viewport = 0;
       
   314 	_cursor.fix_at = false;
       
   315 	MarkWholeScreenDirty();
       
   316 
       
   317 	// Play main theme
       
   318 	if (_music_driver->is_song_playing()) ResetMusic();
       
   319 }
       
   320 
       
   321 #if defined(UNIX) && !defined(__MORPHOS__)
       
   322 extern void DedicatedFork(void);
       
   323 #endif
       
   324 
       
   325 int ttd_main(int argc, char *argv[])
       
   326 {
       
   327 	MyGetOptData mgo;
       
   328 	int i;
       
   329 	const char *optformat;
       
   330 	char musicdriver[16], sounddriver[16], videodriver[16];
       
   331 	int resolution[2] = {0,0};
       
   332 	Year startyear = INVALID_YEAR;
       
   333 	uint generation_seed = GENERATE_NEW_SEED;
       
   334 	bool dedicated = false;
       
   335 	bool network   = false;
       
   336 	bool save_config = true;
       
   337 	char *network_conn = NULL;
       
   338 	char *dedicated_host = NULL;
       
   339 	uint16 dedicated_port = 0;
       
   340 
       
   341 	musicdriver[0] = sounddriver[0] = videodriver[0] = 0;
       
   342 
       
   343 	_game_mode = GM_MENU;
       
   344 	_switch_mode = SM_MENU;
       
   345 	_switch_mode_errorstr = INVALID_STRING_ID;
       
   346 	_dedicated_forks = false;
       
   347 	_config_file = NULL;
       
   348 
       
   349 	// The last param of the following function means this:
       
   350 	//   a letter means: it accepts that param (e.g.: -h)
       
   351 	//   a ':' behind it means: it need a param (e.g.: -m<driver>)
       
   352 	//   a '::' behind it means: it can optional have a param (e.g.: -d<debug>)
       
   353 	optformat = "m:s:v:hD::n::eit:d::r:g::G:c:x"
       
   354 #if !defined(__MORPHOS__) && !defined(__AMIGA__) && !defined(WIN32)
       
   355 		"f"
       
   356 #endif
       
   357 	;
       
   358 
       
   359 	MyGetOptInit(&mgo, argc-1, argv+1, optformat);
       
   360 	while ((i = MyGetOpt(&mgo)) != -1) {
       
   361 		switch (i) {
       
   362 		case 'm': ttd_strlcpy(musicdriver, mgo.opt, sizeof(musicdriver)); break;
       
   363 		case 's': ttd_strlcpy(sounddriver, mgo.opt, sizeof(sounddriver)); break;
       
   364 		case 'v': ttd_strlcpy(videodriver, mgo.opt, sizeof(videodriver)); break;
       
   365 		case 'D':
       
   366 			strcpy(musicdriver, "null");
       
   367 			strcpy(sounddriver, "null");
       
   368 			strcpy(videodriver, "dedicated");
       
   369 			dedicated = true;
       
   370 			if (mgo.opt != NULL)
       
   371 			{
       
   372 				/* Use the existing method for parsing (openttd -n).
       
   373 				 * However, we do ignore the #player part. */
       
   374 				const char *temp = NULL;
       
   375 				const char *port = NULL;
       
   376 				ParseConnectionString(&temp, &port, mgo.opt);
       
   377 				if (*mgo.opt != '\0') dedicated_host = mgo.opt;
       
   378 				if (port != NULL) dedicated_port = atoi(port);
       
   379 			}
       
   380 			break;
       
   381 		case 'f': _dedicated_forks = true; break;
       
   382 		case 'n':
       
   383 			network = true;
       
   384 			network_conn = mgo.opt; // optional IP parameter, NULL if unset
       
   385 			break;
       
   386 		case 'r': ParseResolution(resolution, mgo.opt); break;
       
   387 		case 't': startyear = atoi(mgo.opt); break;
       
   388 		case 'd': {
       
   389 #if defined(WIN32)
       
   390 				CreateConsole();
       
   391 #endif
       
   392 				if (mgo.opt != NULL) SetDebugString(mgo.opt);
       
   393 			} break;
       
   394 		case 'e': _switch_mode = SM_EDITOR; break;
       
   395 		case 'i': _use_dos_palette = true; break;
       
   396 		case 'g':
       
   397 			if (mgo.opt != NULL) {
       
   398 				strcpy(_file_to_saveload.name, mgo.opt);
       
   399 				_switch_mode = SM_LOAD;
       
   400 			} else {
       
   401 				_switch_mode = SM_NEWGAME;
       
   402 			}
       
   403 			break;
       
   404 		case 'G': generation_seed = atoi(mgo.opt); break;
       
   405 		case 'c': _config_file = strdup(mgo.opt); break;
       
   406 		case 'x': save_config = false; break;
       
   407 		case -2:
       
   408 		case 'h':
       
   409 			showhelp();
       
   410 			return 0;
       
   411 		}
       
   412 	}
       
   413 
       
   414 	DeterminePaths();
       
   415 	CheckExternalFiles();
       
   416 
       
   417 #if defined(UNIX) && !defined(__MORPHOS__)
       
   418 	// We must fork here, or we'll end up without some resources we need (like sockets)
       
   419 	if (_dedicated_forks)
       
   420 		DedicatedFork();
       
   421 #endif
       
   422 
       
   423 	LoadFromConfig();
       
   424 	CheckConfig();
       
   425 	LoadFromHighScore();
       
   426 
       
   427 	// override config?
       
   428 	if (musicdriver[0]) ttd_strlcpy(_ini_musicdriver, musicdriver, sizeof(_ini_musicdriver));
       
   429 	if (sounddriver[0]) ttd_strlcpy(_ini_sounddriver, sounddriver, sizeof(_ini_sounddriver));
       
   430 	if (videodriver[0]) ttd_strlcpy(_ini_videodriver, videodriver, sizeof(_ini_videodriver));
       
   431 	if (resolution[0]) { _cur_resolution[0] = resolution[0]; _cur_resolution[1] = resolution[1]; }
       
   432 	if (startyear != INVALID_YEAR) _patches_newgame.starting_year = startyear;
       
   433 	if (generation_seed != GENERATE_NEW_SEED) _patches_newgame.generation_seed = generation_seed;
       
   434 
       
   435 	if (dedicated_host) snprintf(_network_server_bind_ip_host, NETWORK_HOSTNAME_LENGTH, "%s", dedicated_host);
       
   436 	if (dedicated_port) _network_server_port = dedicated_port;
       
   437 	if (_dedicated_forks && !dedicated) _dedicated_forks = false;
       
   438 
       
   439 	// enumerate language files
       
   440 	InitializeLanguagePacks();
       
   441 
       
   442 	// initialize screenshot formats
       
   443 	InitializeScreenshotFormats();
       
   444 
       
   445 	// initialize airport state machines
       
   446 	InitializeAirports();
       
   447 
       
   448 	/* initialize all variables that are allocated dynamically */
       
   449 	InitializeDynamicVariables();
       
   450 
       
   451 	/* start the AI */
       
   452 	AI_Initialize();
       
   453 
       
   454 	// Sample catalogue
       
   455 	DEBUG(misc, 1, "Loading sound effects...");
       
   456 	MxInitialize(11025);
       
   457 	SoundInitialize("sample.cat");
       
   458 
       
   459 	/* Initialize FreeType */
       
   460 	InitFreeType();
       
   461 
       
   462 	// This must be done early, since functions use the InvalidateWindow* calls
       
   463 	InitWindowSystem();
       
   464 
       
   465 	/* Initialize game palette */
       
   466 	GfxInitPalettes();
       
   467 
       
   468 	DEBUG(driver, 1, "Loading drivers...");
       
   469 	LoadDriver(SOUND_DRIVER, _ini_sounddriver);
       
   470 	LoadDriver(MUSIC_DRIVER, _ini_musicdriver);
       
   471 	LoadDriver(VIDEO_DRIVER, _ini_videodriver); // load video last, to prevent an empty window while sound and music loads
       
   472 	_savegame_sort_order = SORT_BY_DATE | SORT_DESCENDING;
       
   473 
       
   474 	// restore saved music volume
       
   475 	_music_driver->set_volume(msf.music_vol);
       
   476 
       
   477 	NetworkStartUp(); // initialize network-core
       
   478 
       
   479 	ScanNewGRFFiles();
       
   480 
       
   481 	_opt_ptr = &_opt_newgame;
       
   482 	ResetGRFConfig(false);
       
   483 
       
   484 	/* XXX - ugly hack, if diff_level is 9, it means we got no setting from the config file */
       
   485 	if (_opt_newgame.diff_level == 9) SetDifficultyLevel(0, &_opt_newgame);
       
   486 
       
   487 	/* Make sure _patches is filled with _patches_newgame if we switch to a game directly */
       
   488 	if (_switch_mode != SM_NONE) {
       
   489 		_opt = _opt_newgame;
       
   490 		UpdatePatches();
       
   491 	}
       
   492 
       
   493 	// initialize the ingame console
       
   494 	IConsoleInit();
       
   495 	_cursor.in_window = true;
       
   496 	InitializeGUI();
       
   497 	IConsoleCmdExec("exec scripts/autoexec.scr 0");
       
   498 
       
   499 	GenerateWorld(GW_EMPTY, 64, 64); // Make the viewport initialization happy
       
   500 	WaitTillGeneratedWorld();
       
   501 
       
   502 #ifdef ENABLE_NETWORK
       
   503 	if (network && _network_available) {
       
   504 		if (network_conn != NULL) {
       
   505 			const char *port = NULL;
       
   506 			const char *player = NULL;
       
   507 			uint16 rport;
       
   508 
       
   509 			rport = NETWORK_DEFAULT_PORT;
       
   510 			_network_playas = PLAYER_NEW_COMPANY;
       
   511 
       
   512 			ParseConnectionString(&player, &port, network_conn);
       
   513 
       
   514 			if (player != NULL) {
       
   515 				_network_playas = atoi(player);
       
   516 
       
   517 				if (_network_playas != PLAYER_SPECTATOR) {
       
   518 					_network_playas--;
       
   519 					if (!IsValidPlayer(_network_playas)) return false;
       
   520 				}
       
   521 			}
       
   522 			if (port != NULL) rport = atoi(port);
       
   523 
       
   524 			LoadIntroGame();
       
   525 			_switch_mode = SM_NONE;
       
   526 			NetworkClientConnectGame(network_conn, rport);
       
   527 		}
       
   528 	}
       
   529 #endif /* ENABLE_NETWORK */
       
   530 
       
   531 	_video_driver->main_loop();
       
   532 
       
   533 	WaitTillSaved();
       
   534 	IConsoleFree();
       
   535 
       
   536 	if (_network_available) NetworkShutDown(); // Shut down the network and close any open connections
       
   537 
       
   538 	_video_driver->stop();
       
   539 	_music_driver->stop();
       
   540 	_sound_driver->stop();
       
   541 
       
   542 	/* only save config if we have to */
       
   543 	if (save_config) {
       
   544 		SaveToConfig();
       
   545 		SaveToHighScore();
       
   546 	}
       
   547 
       
   548 	// uninitialize airport state machines
       
   549 	UnInitializeAirports();
       
   550 
       
   551 	/* uninitialize variables that are allocated dynamic */
       
   552 	UnInitializeDynamicVariables();
       
   553 
       
   554 	/* stop the AI */
       
   555 	AI_Uninitialize();
       
   556 
       
   557 	/* Close all and any open filehandles */
       
   558 	FioCloseAll();
       
   559 	UnInitializeGame();
       
   560 
       
   561 	return 0;
       
   562 }
       
   563 
       
   564 void HandleExitGameRequest(void)
       
   565 {
       
   566 	if (_game_mode == GM_MENU) { // do not ask to quit on the main screen
       
   567 		_exit_game = true;
       
   568 	} else if (_patches.autosave_on_exit) {
       
   569 		DoExitSave();
       
   570 		_exit_game = true;
       
   571 	} else {
       
   572 		AskExitGame();
       
   573 	}
       
   574 }
       
   575 
       
   576 
       
   577 /** Mutex so that only one thread can communicate with the main program
       
   578  * at any given time */
       
   579 static ThreadMsg _message = MSG_OTTD_NO_MESSAGE;
       
   580 
       
   581 static inline void OTTD_ReleaseMutex(void) {_message = MSG_OTTD_NO_MESSAGE;}
       
   582 static inline ThreadMsg OTTD_PollThreadEvent(void) {return _message;}
       
   583 
       
   584 /** Called by running thread to execute some action in the main game.
       
   585  * It will stall as long as the mutex is not freed (handled) by the game */
       
   586 void OTTD_SendThreadMessage(ThreadMsg msg)
       
   587 {
       
   588 	if (_exit_game) return;
       
   589 	while (_message != MSG_OTTD_NO_MESSAGE) CSleep(10);
       
   590 
       
   591 	_message = msg;
       
   592 }
       
   593 
       
   594 
       
   595 /** Handle the user-messages sent to us
       
   596  * @param message message sent
       
   597  */
       
   598 static void ProcessSentMessage(ThreadMsg message)
       
   599 {
       
   600 	switch (message) {
       
   601 		case MSG_OTTD_SAVETHREAD_DONE:  SaveFileDone(); break;
       
   602 		case MSG_OTTD_SAVETHREAD_ERROR: SaveFileError(); break;
       
   603 		default: NOT_REACHED();
       
   604 	}
       
   605 
       
   606 	OTTD_ReleaseMutex(); // release mutex so that other threads, messages can be handled
       
   607 }
       
   608 
       
   609 static void ShowScreenshotResult(bool b)
       
   610 {
       
   611 	if (b) {
       
   612 		SetDParamStr(0, _screenshot_name);
       
   613 		ShowErrorMessage(INVALID_STRING_ID, STR_031B_SCREENSHOT_SUCCESSFULLY, 0, 0);
       
   614 	} else {
       
   615 		ShowErrorMessage(INVALID_STRING_ID, STR_031C_SCREENSHOT_FAILED, 0, 0);
       
   616 	}
       
   617 
       
   618 }
       
   619 
       
   620 static void MakeNewGameDone(void)
       
   621 {
       
   622 	/* In a dedicated server, the server does not play */
       
   623 	if (_network_dedicated) {
       
   624 		SetLocalPlayer(PLAYER_SPECTATOR);
       
   625 		return;
       
   626 	}
       
   627 
       
   628 	/* Create a single player */
       
   629 	DoStartupNewPlayer(false);
       
   630 
       
   631 	SetLocalPlayer(0);
       
   632 	_current_player = _local_player;
       
   633 	DoCommandP(0, (_patches.autorenew << 15 ) | (_patches.autorenew_months << 16) | 4, _patches.autorenew_money, NULL, CMD_SET_AUTOREPLACE);
       
   634 
       
   635 	SettingsDisableElrail(_patches.disable_elrails);
       
   636 
       
   637 	MarkWholeScreenDirty();
       
   638 }
       
   639 
       
   640 static void MakeNewGame(bool from_heightmap)
       
   641 {
       
   642 	_game_mode = GM_NORMAL;
       
   643 
       
   644 	ResetGRFConfig(true);
       
   645 
       
   646 	GenerateWorldSetCallback(&MakeNewGameDone);
       
   647 	GenerateWorld(from_heightmap ? GW_HEIGHTMAP : GW_NEWGAME, 1 << _patches.map_x, 1 << _patches.map_y);
       
   648 }
       
   649 
       
   650 static void MakeNewEditorWorldDone(void)
       
   651 {
       
   652 	SetLocalPlayer(OWNER_NONE);
       
   653 
       
   654 	MarkWholeScreenDirty();
       
   655 }
       
   656 
       
   657 static void MakeNewEditorWorld(void)
       
   658 {
       
   659 	_game_mode = GM_EDITOR;
       
   660 
       
   661 	ResetGRFConfig(true);
       
   662 
       
   663 	GenerateWorldSetCallback(&MakeNewEditorWorldDone);
       
   664 	GenerateWorld(GW_EMPTY, 1 << _patches.map_x, 1 << _patches.map_y);
       
   665 }
       
   666 
       
   667 void StartupPlayers(void);
       
   668 void StartupDisasters(void);
       
   669 extern void StartupEconomy(void);
       
   670 
       
   671 /**
       
   672  * Start Scenario starts a new game based on a scenario.
       
   673  * Eg 'New Game' --> select a preset scenario
       
   674  * This starts a scenario based on your current difficulty settings
       
   675  */
       
   676 static void StartScenario(void)
       
   677 {
       
   678 	_game_mode = GM_NORMAL;
       
   679 
       
   680 	// invalid type
       
   681 	if (_file_to_saveload.mode == SL_INVALID) {
       
   682 		DEBUG(sl, 0, "Savegame is obsolete or invalid format: '%s'", _file_to_saveload.name);
       
   683 		ShowErrorMessage(INVALID_STRING_ID, STR_4009_GAME_LOAD_FAILED, 0, 0);
       
   684 		_game_mode = GM_MENU;
       
   685 		return;
       
   686 	}
       
   687 
       
   688 	// Reinitialize windows
       
   689 	ResetWindowSystem();
       
   690 
       
   691 	SetupColorsAndInitialWindow();
       
   692 
       
   693 	ResetGRFConfig(true);
       
   694 
       
   695 	// Load game
       
   696 	if (SaveOrLoad(_file_to_saveload.name, _file_to_saveload.mode) != SL_OK) {
       
   697 		LoadIntroGame();
       
   698 		ShowErrorMessage(INVALID_STRING_ID, STR_4009_GAME_LOAD_FAILED, 0, 0);
       
   699 	}
       
   700 
       
   701 	_opt_ptr = &_opt;
       
   702 	_opt_ptr->diff = _opt_newgame.diff;
       
   703 	_opt.diff_level = _opt_newgame.diff_level;
       
   704 
       
   705 	// Inititalize data
       
   706 	StartupEconomy();
       
   707 	StartupPlayers();
       
   708 	StartupEngines();
       
   709 	StartupDisasters();
       
   710 
       
   711 	SetLocalPlayer(0);
       
   712 	_current_player = _local_player;
       
   713 	DoCommandP(0, (_patches.autorenew << 15 ) | (_patches.autorenew_months << 16) | 4, _patches.autorenew_money, NULL, CMD_SET_AUTOREPLACE);
       
   714 
       
   715 	MarkWholeScreenDirty();
       
   716 }
       
   717 
       
   718 bool SafeSaveOrLoad(const char *filename, int mode, int newgm)
       
   719 {
       
   720 	byte ogm = _game_mode;
       
   721 
       
   722 	_game_mode = newgm;
       
   723 	switch (SaveOrLoad(filename, mode)) {
       
   724 		case SL_OK: return true;
       
   725 
       
   726 		case SL_REINIT:
       
   727 			switch (ogm) {
       
   728 				case GM_MENU:   LoadIntroGame();      break;
       
   729 				case GM_EDITOR: MakeNewEditorWorld(); break;
       
   730 				default:        MakeNewGame(false);   break;
       
   731 			}
       
   732 			return false;
       
   733 
       
   734 		default:
       
   735 			_game_mode = ogm;
       
   736 			return false;
       
   737 	}
       
   738 }
       
   739 
       
   740 void SwitchMode(int new_mode)
       
   741 {
       
   742 #ifdef ENABLE_NETWORK
       
   743 	// If we are saving something, the network stays in his current state
       
   744 	if (new_mode != SM_SAVE) {
       
   745 		// If the network is active, make it not-active
       
   746 		if (_networking) {
       
   747 			if (_network_server && (new_mode == SM_LOAD || new_mode == SM_NEWGAME)) {
       
   748 				NetworkReboot();
       
   749 				NetworkUDPStop();
       
   750 			} else {
       
   751 				NetworkDisconnect();
       
   752 				NetworkUDPStop();
       
   753 			}
       
   754 		}
       
   755 
       
   756 		// If we are a server, we restart the server
       
   757 		if (_is_network_server) {
       
   758 			// But not if we are going to the menu
       
   759 			if (new_mode != SM_MENU) {
       
   760 				NetworkServerStart();
       
   761 			} else {
       
   762 				// This client no longer wants to be a network-server
       
   763 				_is_network_server = false;
       
   764 			}
       
   765 		}
       
   766 	}
       
   767 #endif /* ENABLE_NETWORK */
       
   768 
       
   769 	switch (new_mode) {
       
   770 	case SM_EDITOR: /* Switch to scenario editor */
       
   771 		MakeNewEditorWorld();
       
   772 		break;
       
   773 
       
   774 	case SM_NEWGAME: /* New Game --> 'Random game' */
       
   775 #ifdef ENABLE_NETWORK
       
   776 		if (_network_server) {
       
   777 			snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "Random Map");
       
   778 		}
       
   779 #endif /* ENABLE_NETWORK */
       
   780 		MakeNewGame(false);
       
   781 		break;
       
   782 
       
   783 	case SM_START_SCENARIO: /* New Game --> Choose one of the preset scenarios */
       
   784 #ifdef ENABLE_NETWORK
       
   785 		if (_network_server) {
       
   786 			snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "%s (Loaded scenario)", _file_to_saveload.title);
       
   787 		}
       
   788 #endif /* ENABLE_NETWORK */
       
   789 		StartScenario();
       
   790 		break;
       
   791 
       
   792 	case SM_LOAD: { /* Load game, Play Scenario */
       
   793 		_opt_ptr = &_opt;
       
   794 		ResetGRFConfig(true);
       
   795 
       
   796 		if (!SafeSaveOrLoad(_file_to_saveload.name, _file_to_saveload.mode, GM_NORMAL)) {
       
   797 			LoadIntroGame();
       
   798 			ShowErrorMessage(INVALID_STRING_ID, STR_4009_GAME_LOAD_FAILED, 0, 0);
       
   799 		} else {
       
   800 			/* Update the local player for a loaded game. It is either always
       
   801 			 * player #1 (eg 0) or in the case of a dedicated server a spectator */
       
   802 			SetLocalPlayer(_network_dedicated ? PLAYER_SPECTATOR : 0);
       
   803 			DoCommandP(0, 0, 0, NULL, CMD_PAUSE); // decrease pause counter (was increased from opening load dialog)
       
   804 #ifdef ENABLE_NETWORK
       
   805 			if (_network_server) {
       
   806 				snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "%s (Loaded game)", _file_to_saveload.title);
       
   807 			}
       
   808 #endif /* ENABLE_NETWORK */
       
   809 		}
       
   810 		break;
       
   811 	}
       
   812 
       
   813 	case SM_START_HEIGHTMAP: /* Load a heightmap and start a new game from it */
       
   814 #ifdef ENABLE_NETWORK
       
   815 		if (_network_server) {
       
   816 			snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "%s (Heightmap)", _file_to_saveload.title);
       
   817 		}
       
   818 #endif /* ENABLE_NETWORK */
       
   819 		MakeNewGame(true);
       
   820 		break;
       
   821 
       
   822 	case SM_LOAD_HEIGHTMAP: /* Load heightmap from scenario editor */
       
   823 		SetLocalPlayer(OWNER_NONE);
       
   824 
       
   825 		GenerateWorld(GW_HEIGHTMAP, 1 << _patches.map_x, 1 << _patches.map_y);
       
   826 		MarkWholeScreenDirty();
       
   827 		break;
       
   828 
       
   829 	case SM_LOAD_SCENARIO: { /* Load scenario from scenario editor */
       
   830 		if (SafeSaveOrLoad(_file_to_saveload.name, _file_to_saveload.mode, GM_EDITOR)) {
       
   831 			Player *p;
       
   832 
       
   833 			_opt_ptr = &_opt;
       
   834 
       
   835 			SetLocalPlayer(OWNER_NONE);
       
   836 			_generating_world = true;
       
   837 			/* Delete all players */
       
   838 			FOR_ALL_PLAYERS(p) {
       
   839 				if (p->is_active) {
       
   840 					ChangeOwnershipOfPlayerItems(p->index, PLAYER_SPECTATOR);
       
   841 					p->is_active = false;
       
   842 				}
       
   843 			}
       
   844 			_generating_world = false;
       
   845 			_patches_newgame.starting_year = _cur_year;
       
   846 			// delete all stations owned by a player
       
   847 			DeleteAllPlayerStations();
       
   848 		} else {
       
   849 			ShowErrorMessage(INVALID_STRING_ID, STR_4009_GAME_LOAD_FAILED, 0, 0);
       
   850 		}
       
   851 		break;
       
   852 	}
       
   853 
       
   854 	case SM_MENU: /* Switch to game intro menu */
       
   855 		LoadIntroGame();
       
   856 		break;
       
   857 
       
   858 	case SM_SAVE: /* Save game */
       
   859 		if (SaveOrLoad(_file_to_saveload.name, SL_SAVE) != SL_OK) {
       
   860 			ShowErrorMessage(INVALID_STRING_ID, STR_4007_GAME_SAVE_FAILED, 0, 0);
       
   861 		} else {
       
   862 			DeleteWindowById(WC_SAVELOAD, 0);
       
   863 		}
       
   864 		break;
       
   865 
       
   866 	case SM_GENRANDLAND: /* Generate random land within scenario editor */
       
   867 		SetLocalPlayer(OWNER_NONE);
       
   868 		GenerateWorld(GW_RANDOM, 1 << _patches.map_x, 1 << _patches.map_y);
       
   869 		// XXX: set date
       
   870 		MarkWholeScreenDirty();
       
   871 		break;
       
   872 	}
       
   873 
       
   874 	if (_switch_mode_errorstr != INVALID_STRING_ID) {
       
   875 		ShowErrorMessage(INVALID_STRING_ID, _switch_mode_errorstr, 0, 0);
       
   876 	}
       
   877 }
       
   878 
       
   879 
       
   880 // State controlling game loop.
       
   881 // The state must not be changed from anywhere
       
   882 // but here.
       
   883 // That check is enforced in DoCommand.
       
   884 void StateGameLoop(void)
       
   885 {
       
   886 	// dont execute the state loop during pause
       
   887 	if (_pause) return;
       
   888 	if (IsGeneratingWorld()) return;
       
   889 
       
   890 	if (_game_mode == GM_EDITOR) {
       
   891 		RunTileLoop();
       
   892 		CallVehicleTicks();
       
   893 		CallLandscapeTick();
       
   894 		CallWindowTickEvent();
       
   895 		NewsLoop();
       
   896 	} else {
       
   897 		// All these actions has to be done from OWNER_NONE
       
   898 		//  for multiplayer compatibility
       
   899 		PlayerID p = _current_player;
       
   900 		_current_player = OWNER_NONE;
       
   901 
       
   902 		AnimateAnimatedTiles();
       
   903 		IncreaseDate();
       
   904 		RunTileLoop();
       
   905 		CallVehicleTicks();
       
   906 		CallLandscapeTick();
       
   907 
       
   908 		AI_RunGameLoop();
       
   909 
       
   910 		CallWindowTickEvent();
       
   911 		NewsLoop();
       
   912 		_current_player = p;
       
   913 	}
       
   914 }
       
   915 
       
   916 static void DoAutosave(void)
       
   917 {
       
   918 	char buf[200];
       
   919 
       
   920 	if (_patches.keep_all_autosave && _local_player != PLAYER_SPECTATOR) {
       
   921 		const Player *p = GetPlayer(_local_player);
       
   922 		char* s = buf;
       
   923 
       
   924 		s += snprintf(buf, lengthof(buf), "%s%s", _paths.autosave_dir, PATHSEP);
       
   925 
       
   926 		SetDParam(0, p->name_1);
       
   927 		SetDParam(1, p->name_2);
       
   928 		SetDParam(2, _date);
       
   929 		s = GetString(s, STR_4004, lastof(buf));
       
   930 		strecpy(s, ".sav", lastof(buf));
       
   931 	} else { /* generate a savegame name and number according to _patches.max_num_autosaves */
       
   932 		snprintf(buf, lengthof(buf), "%s%sautosave%d.sav", _paths.autosave_dir, PATHSEP, _autosave_ctr);
       
   933 
       
   934 		_autosave_ctr++;
       
   935 		if (_autosave_ctr >= _patches.max_num_autosaves) {
       
   936 			// we reached the limit for numbers of autosaves. We will start over
       
   937 			_autosave_ctr = 0;
       
   938 		}
       
   939 	}
       
   940 
       
   941 	DEBUG(sl, 2, "Autosaving to '%s'", buf);
       
   942 	if (SaveOrLoad(buf, SL_SAVE) != SL_OK)
       
   943 		ShowErrorMessage(INVALID_STRING_ID, STR_AUTOSAVE_FAILED, 0, 0);
       
   944 }
       
   945 
       
   946 static void ScrollMainViewport(int x, int y)
       
   947 {
       
   948 	if (_game_mode != GM_MENU) {
       
   949 		Window *w = FindWindowById(WC_MAIN_WINDOW, 0);
       
   950 		assert(w);
       
   951 
       
   952 		WP(w,vp_d).scrollpos_x += x << w->viewport->zoom;
       
   953 		WP(w,vp_d).scrollpos_y += y << w->viewport->zoom;
       
   954 	}
       
   955 }
       
   956 
       
   957 static const int8 scrollamt[16][2] = {
       
   958 	{ 0,  0},
       
   959 	{-2,  0}, //  1 : left
       
   960 	{ 0, -2}, //  2 : up
       
   961 	{-2, -1}, //  3 : left + up
       
   962 	{ 2,  0}, //  4 : right
       
   963 	{ 0,  0}, //  5 : left + right
       
   964 	{ 2, -1}, //  6 : right + up
       
   965 	{ 0, -2}, //  7 : left + right + up = up
       
   966 	{ 0  ,2}, //  8 : down
       
   967 	{-2  ,1}, //  9 : down+left
       
   968 	{ 0,  0}, // 10 : impossible
       
   969 	{-2,  0}, // 11 : left + up + down = left
       
   970 	{ 2,  1}, // 12 : down+right
       
   971 	{ 0,  2}, // 13 : left + right + down = down
       
   972 	{ 0, -2}, // 14 : left + right + up = up
       
   973 	{ 0,  0}, // 15 : impossible
       
   974 };
       
   975 
       
   976 static void HandleKeyScrolling(void)
       
   977 {
       
   978 	if (_dirkeys && !_no_scroll) {
       
   979 		int factor = _shift_pressed ? 50 : 10;
       
   980 		ScrollMainViewport(scrollamt[_dirkeys][0] * factor, scrollamt[_dirkeys][1] * factor);
       
   981 	}
       
   982 }
       
   983 
       
   984 void GameLoop(void)
       
   985 {
       
   986 	ThreadMsg message;
       
   987 
       
   988 	if ((message = OTTD_PollThreadEvent()) != 0) ProcessSentMessage(message);
       
   989 
       
   990 	// autosave game?
       
   991 	if (_do_autosave) {
       
   992 		_do_autosave = false;
       
   993 		DoAutosave();
       
   994 		RedrawAutosave();
       
   995 	}
       
   996 
       
   997 	// handle scrolling of the main window
       
   998 	HandleKeyScrolling();
       
   999 
       
  1000 	// make a screenshot?
       
  1001 	if (IsScreenshotRequested()) ShowScreenshotResult(MakeScreenshot());
       
  1002 
       
  1003 	// switch game mode?
       
  1004 	if (_switch_mode != SM_NONE) {
       
  1005 		SwitchMode(_switch_mode);
       
  1006 		_switch_mode = SM_NONE;
       
  1007 	}
       
  1008 
       
  1009 	IncreaseSpriteLRU();
       
  1010 	InteractiveRandom();
       
  1011 
       
  1012 	if (_scroller_click_timeout > 3) {
       
  1013 		_scroller_click_timeout -= 3;
       
  1014 	} else {
       
  1015 		_scroller_click_timeout = 0;
       
  1016 	}
       
  1017 
       
  1018 	_caret_timer += 3;
       
  1019 	_timer_counter += 8;
       
  1020 	CursorTick();
       
  1021 
       
  1022 #ifdef ENABLE_NETWORK
       
  1023 	// Check for UDP stuff
       
  1024 	if (_network_available) NetworkUDPGameLoop();
       
  1025 
       
  1026 	if (_networking && !IsGeneratingWorld()) {
       
  1027 		// Multiplayer
       
  1028 		NetworkGameLoop();
       
  1029 	} else {
       
  1030 		if (_network_reconnect > 0 && --_network_reconnect == 0) {
       
  1031 			// This means that we want to reconnect to the last host
       
  1032 			// We do this here, because it means that the network is really closed
       
  1033 			NetworkClientConnectGame(_network_last_host, _network_last_port);
       
  1034 		}
       
  1035 		// Singleplayer
       
  1036 		StateGameLoop();
       
  1037 	}
       
  1038 #else
       
  1039 	StateGameLoop();
       
  1040 #endif /* ENABLE_NETWORK */
       
  1041 
       
  1042 	if (!_pause && _display_opt & DO_FULL_ANIMATION) DoPaletteAnimations();
       
  1043 
       
  1044 	if (!_pause || _cheats.build_in_pause.value) MoveAllTextEffects();
       
  1045 
       
  1046 	InputLoop();
       
  1047 
       
  1048 	MusicLoop();
       
  1049 }
       
  1050 
       
  1051 void BeforeSaveGame(void)
       
  1052 {
       
  1053 	const Window *w = FindWindowById(WC_MAIN_WINDOW, 0);
       
  1054 
       
  1055 	if (w != NULL) {
       
  1056 		_saved_scrollpos_x = WP(w, const vp_d).scrollpos_x;
       
  1057 		_saved_scrollpos_y = WP(w, const vp_d).scrollpos_y;
       
  1058 		_saved_scrollpos_zoom = w->viewport->zoom;
       
  1059 	}
       
  1060 }
       
  1061 
       
  1062 static void ConvertTownOwner(void)
       
  1063 {
       
  1064 	TileIndex tile;
       
  1065 
       
  1066 	for (tile = 0; tile != MapSize(); tile++) {
       
  1067 		switch (GetTileType(tile)) {
       
  1068 			case MP_STREET:
       
  1069 				if (IsLevelCrossing(tile) && GetCrossingRoadOwner(tile) & 0x80) {
       
  1070 					SetCrossingRoadOwner(tile, OWNER_TOWN);
       
  1071 				}
       
  1072 				/* FALLTHROUGH */
       
  1073 
       
  1074 			case MP_TUNNEL: case MP_STREET_BRIDGE:
       
  1075 				if (GetTileOwner(tile) & 0x80) SetTileOwner(tile, OWNER_TOWN);
       
  1076 				break;
       
  1077 
       
  1078 			default: break;
       
  1079 		}
       
  1080 	}
       
  1081 }
       
  1082 
       
  1083 // before savegame version 4, the name of the company determined if it existed
       
  1084 static void CheckIsPlayerActive(void)
       
  1085 {
       
  1086 	Player *p;
       
  1087 
       
  1088 	FOR_ALL_PLAYERS(p) {
       
  1089 		if (p->name_1 != 0) p->is_active = true;
       
  1090 	}
       
  1091 }
       
  1092 
       
  1093 // since savegame version 4.1, exclusive transport rights are stored at towns
       
  1094 static void UpdateExclusiveRights(void)
       
  1095 {
       
  1096 	Town *t;
       
  1097 
       
  1098 	FOR_ALL_TOWNS(t) {
       
  1099 		t->exclusivity = (byte)-1;
       
  1100 	}
       
  1101 
       
  1102 	/* FIXME old exclusive rights status is not being imported (stored in s->blocked_months_obsolete)
       
  1103 	 *   could be implemented this way:
       
  1104 	 * 1.) Go through all stations
       
  1105 	 *     Build an array town_blocked[ town_id ][ player_id ]
       
  1106 	 *     that stores if at least one station in that town is blocked for a player
       
  1107 	 * 2.) Go through that array, if you find a town that is not blocked for
       
  1108 	 *     one player, but for all others, then give him exclusivity.
       
  1109 	 */
       
  1110 }
       
  1111 
       
  1112 static const byte convert_currency[] = {
       
  1113 	 0,  1, 12,  8,  3,
       
  1114 	10, 14, 19,  4,  5,
       
  1115 	 9, 11, 13,  6, 17,
       
  1116 	16, 22, 21,  7, 15,
       
  1117 	18,  2, 20, };
       
  1118 
       
  1119 // since savegame version 4.2 the currencies are arranged differently
       
  1120 static void UpdateCurrencies(void)
       
  1121 {
       
  1122 	_opt.currency = convert_currency[_opt.currency];
       
  1123 }
       
  1124 
       
  1125 /* Up to revision 1413 the invisible tiles at the southern border have not been
       
  1126  * MP_VOID, even though they should have. This is fixed by this function
       
  1127  */
       
  1128 static void UpdateVoidTiles(void)
       
  1129 {
       
  1130 	uint i;
       
  1131 
       
  1132 	for (i = 0; i < MapMaxY(); ++i) MakeVoid(i * MapSizeX() + MapMaxX());
       
  1133 	for (i = 0; i < MapSizeX(); ++i) MakeVoid(MapSizeX() * MapMaxY() + i);
       
  1134 }
       
  1135 
       
  1136 // since savegame version 6.0 each sign has an "owner", signs without owner (from old games are set to 255)
       
  1137 static void UpdateSignOwner(void)
       
  1138 {
       
  1139 	Sign *si;
       
  1140 
       
  1141 	FOR_ALL_SIGNS(si) si->owner = OWNER_NONE;
       
  1142 }
       
  1143 
       
  1144 extern void UpdateOldAircraft( void );
       
  1145 extern void UpdateOilRig( void );
       
  1146 
       
  1147 
       
  1148 static inline RailType UpdateRailType(RailType rt, RailType min)
       
  1149 {
       
  1150 	return rt >= min ? (RailType)(rt + 1): rt;
       
  1151 }
       
  1152 
       
  1153 bool AfterLoadGame(void)
       
  1154 {
       
  1155 	Window *w;
       
  1156 	ViewPort *vp;
       
  1157 	Player *p;
       
  1158 
       
  1159 	// in version 2.1 of the savegame, town owner was unified.
       
  1160 	if (CheckSavegameVersionOldStyle(2, 1)) ConvertTownOwner();
       
  1161 
       
  1162 	// from version 4.1 of the savegame, exclusive rights are stored at towns
       
  1163 	if (CheckSavegameVersionOldStyle(4, 1)) UpdateExclusiveRights();
       
  1164 
       
  1165 	// from version 4.2 of the savegame, currencies are in a different order
       
  1166 	if (CheckSavegameVersionOldStyle(4, 2)) UpdateCurrencies();
       
  1167 
       
  1168 	// from version 6.1 of the savegame, signs have an "owner"
       
  1169 	if (CheckSavegameVersionOldStyle(6, 1)) UpdateSignOwner();
       
  1170 
       
  1171 	/* In old version there seems to be a problem that water is owned by
       
  1172 	    OWNER_NONE, not OWNER_WATER.. I can't replicate it for the current
       
  1173 	    (4.3) version, so I just check when versions are older, and then
       
  1174 	    walk through the whole map.. */
       
  1175 	if (CheckSavegameVersionOldStyle(4, 3)) {
       
  1176 		TileIndex tile = TileXY(0, 0);
       
  1177 		uint w = MapSizeX();
       
  1178 		uint h = MapSizeY();
       
  1179 
       
  1180 		BEGIN_TILE_LOOP(tile_cur, w, h, tile)
       
  1181 			if (IsTileType(tile_cur, MP_WATER) && GetTileOwner(tile_cur) >= MAX_PLAYERS)
       
  1182 				SetTileOwner(tile_cur, OWNER_WATER);
       
  1183 		END_TILE_LOOP(tile_cur, w, h, tile)
       
  1184 	}
       
  1185 
       
  1186 	// convert road side to my format.
       
  1187 	if (_opt.road_side) _opt.road_side = 1;
       
  1188 
       
  1189 	/* Check all NewGRFs are present */
       
  1190 	if (!IsGoodGRFConfigList()) return false;
       
  1191 
       
  1192 	/* Update current year
       
  1193 	 * must be done before loading sprites as some newgrfs check it */
       
  1194 	SetDate(_date);
       
  1195 
       
  1196 	// Load the sprites
       
  1197 	GfxLoadSprites();
       
  1198 	LoadStringWidthTable();
       
  1199 
       
  1200 	/* Connect front and rear engines of multiheaded trains and converts
       
  1201 	 * subtype to the new format */
       
  1202 	if (CheckSavegameVersionOldStyle(17, 1)) ConvertOldMultiheadToNew();
       
  1203 
       
  1204 	/* Connect front and rear engines of multiheaded trains */
       
  1205 	ConnectMultiheadedTrains();
       
  1206 
       
  1207 	// reinit the landscape variables (landscape might have changed)
       
  1208 	InitializeLandscapeVariables(true);
       
  1209 
       
  1210 	// Update all vehicles
       
  1211 	AfterLoadVehicles();
       
  1212 
       
  1213 	// Update all waypoints
       
  1214 	if (CheckSavegameVersion(12)) FixOldWaypoints();
       
  1215 
       
  1216 	UpdateAllWaypointSigns();
       
  1217 
       
  1218 	// in version 2.2 of the savegame, we have new airports
       
  1219 	if (CheckSavegameVersionOldStyle(2, 2)) UpdateOldAircraft();
       
  1220 
       
  1221 	UpdateAllStationVirtCoord();
       
  1222 
       
  1223 	// Setup town coords
       
  1224 	AfterLoadTown();
       
  1225 	UpdateAllSignVirtCoords();
       
  1226 
       
  1227 	// make sure there is a town in the game
       
  1228 	if (_game_mode == GM_NORMAL && !ClosestTownFromTile(0, (uint)-1)) {
       
  1229 		_error_message = STR_NO_TOWN_IN_SCENARIO;
       
  1230 		return false;
       
  1231 	}
       
  1232 
       
  1233 	// Initialize windows
       
  1234 	ResetWindowSystem();
       
  1235 	SetupColorsAndInitialWindow();
       
  1236 
       
  1237 	w = FindWindowById(WC_MAIN_WINDOW, 0);
       
  1238 
       
  1239 	WP(w,vp_d).scrollpos_x = _saved_scrollpos_x;
       
  1240 	WP(w,vp_d).scrollpos_y = _saved_scrollpos_y;
       
  1241 
       
  1242 	vp = w->viewport;
       
  1243 	vp->zoom = _saved_scrollpos_zoom;
       
  1244 	vp->virtual_width = vp->width << vp->zoom;
       
  1245 	vp->virtual_height = vp->height << vp->zoom;
       
  1246 
       
  1247 	// in version 4.1 of the savegame, is_active was introduced to determine
       
  1248 	// if a player does exist, rather then checking name_1
       
  1249 	if (CheckSavegameVersionOldStyle(4, 1)) CheckIsPlayerActive();
       
  1250 
       
  1251 	// the void tiles on the southern border used to belong to a wrong class (pre 4.3).
       
  1252 	if (CheckSavegameVersionOldStyle(4, 3)) UpdateVoidTiles();
       
  1253 
       
  1254 	// If Load Scenario / New (Scenario) Game is used,
       
  1255 	//  a player does not exist yet. So create one here.
       
  1256 	// 1 exeption: network-games. Those can have 0 players
       
  1257 	//   But this exeption is not true for network_servers!
       
  1258 	if (!_players[0].is_active && (!_networking || (_networking && _network_server)))
       
  1259 		DoStartupNewPlayer(false);
       
  1260 
       
  1261 	DoZoomInOutWindow(ZOOM_NONE, w); // update button status
       
  1262 	MarkWholeScreenDirty();
       
  1263 
       
  1264 	// In 5.1, Oilrigs have been moved (again)
       
  1265 	if (CheckSavegameVersionOldStyle(5, 1)) UpdateOilRig();
       
  1266 
       
  1267 	/* In version 6.1 we put the town index in the map-array. To do this, we need
       
  1268 	 *  to use m2 (16bit big), so we need to clean m2, and that is where this is
       
  1269 	 *  all about ;) */
       
  1270 	if (CheckSavegameVersionOldStyle(6, 1)) {
       
  1271 		BEGIN_TILE_LOOP(tile, MapSizeX(), MapSizeY(), 0) {
       
  1272 			switch (GetTileType(tile)) {
       
  1273 				case MP_HOUSE:
       
  1274 					_m[tile].m4 = _m[tile].m2;
       
  1275 					SetTownIndex(tile, CalcClosestTownFromTile(tile, (uint)-1)->index);
       
  1276 					break;
       
  1277 
       
  1278 				case MP_STREET:
       
  1279 					_m[tile].m4 |= (_m[tile].m2 << 4);
       
  1280 					if (IsTileOwner(tile, OWNER_TOWN)) {
       
  1281 						SetTownIndex(tile, CalcClosestTownFromTile(tile, (uint)-1)->index);
       
  1282 					} else {
       
  1283 						SetTownIndex(tile, 0);
       
  1284 					}
       
  1285 					break;
       
  1286 
       
  1287 				default: break;
       
  1288 			}
       
  1289 		} END_TILE_LOOP(tile, MapSizeX(), MapSizeY(), 0);
       
  1290 	}
       
  1291 
       
  1292 	/* From version 9.0, we update the max passengers of a town (was sometimes negative
       
  1293 	 *  before that. */
       
  1294 	if (CheckSavegameVersion(9)) {
       
  1295 		Town *t;
       
  1296 		FOR_ALL_TOWNS(t) UpdateTownMaxPass(t);
       
  1297 	}
       
  1298 
       
  1299 	/* From version 16.0, we included autorenew on engines, which are now saved, but
       
  1300 	 *  of course, we do need to initialize them for older savegames. */
       
  1301 	if (CheckSavegameVersion(16)) {
       
  1302 		FOR_ALL_PLAYERS(p) {
       
  1303 			p->engine_renew_list   = NULL;
       
  1304 			p->engine_renew        = false;
       
  1305 			p->engine_renew_months = -6;
       
  1306 			p->engine_renew_money  = 100000;
       
  1307 		}
       
  1308 
       
  1309 		/* When loading a game, _local_player is not yet set to the correct value.
       
  1310 		 * However, in a dedicated server we are a spectator, so nothing needs to
       
  1311 		 * happen. In case we are not a dedicated server, the local player always
       
  1312 		 * becomes player 0, unless we are in the scenario editor where all the
       
  1313 		 * players are 'invalid'.
       
  1314 		 */
       
  1315 		if (!_network_dedicated && IsValidPlayer(0)) {
       
  1316 			p = GetPlayer(0);
       
  1317 			p->engine_renew        = _patches.autorenew;
       
  1318 			p->engine_renew_months = _patches.autorenew_months;
       
  1319 			p->engine_renew_money  = _patches.autorenew_money;
       
  1320 		}
       
  1321 	}
       
  1322 
       
  1323 	if (CheckSavegameVersion(42)) {
       
  1324 		TileIndex map_end = MapSize();
       
  1325 		TileIndex tile;
       
  1326 
       
  1327 		for (tile = 0; tile != map_end; tile++) {
       
  1328 			if (MayHaveBridgeAbove(tile)) ClearBridgeMiddle(tile);
       
  1329 			if (IsTileType(tile, MP_TUNNEL) && HASBIT(_m[tile].m5, 7)) {
       
  1330 				if (HASBIT(_m[tile].m5, 6)) { // middle part
       
  1331 					Axis axis = (Axis)GB(_m[tile].m5, 0, 1);
       
  1332 
       
  1333 					if (HASBIT(_m[tile].m5, 5)) { // transport route under bridge?
       
  1334 						if (GB(_m[tile].m5, 3, 2) == TRANSPORT_RAIL) {
       
  1335 							MakeRailNormal(
       
  1336 								tile,
       
  1337 								GetTileOwner(tile),
       
  1338 								axis == AXIS_X ? TRACK_BIT_Y : TRACK_BIT_X,
       
  1339 								GetRailType(tile)
       
  1340 							);
       
  1341 						} else {
       
  1342 							TownID town = IsTileOwner(tile, OWNER_TOWN) ? ClosestTownFromTile(tile, (uint)-1)->index : 0;
       
  1343 
       
  1344 							MakeRoadNormal(
       
  1345 								tile,
       
  1346 								GetTileOwner(tile),
       
  1347 								axis == AXIS_X ? ROAD_Y : ROAD_X,
       
  1348 								town
       
  1349 							);
       
  1350 						}
       
  1351 					} else {
       
  1352 						if (GB(_m[tile].m5, 3, 2) == 0) {
       
  1353 							MakeClear(tile, CLEAR_GRASS, 3);
       
  1354 						} else {
       
  1355 							MakeCanal(tile, GetTileOwner(tile));
       
  1356 						}
       
  1357 					}
       
  1358 					SetBridgeMiddle(tile, axis);
       
  1359 				} else { // ramp
       
  1360 					Axis axis = (Axis)GB(_m[tile].m5, 0, 1);
       
  1361 					uint north_south = GB(_m[tile].m5, 5, 1);
       
  1362 					DiagDirection dir = ReverseDiagDir(XYNSToDiagDir(axis, north_south));
       
  1363 					TransportType type = (TransportType)GB(_m[tile].m5, 1, 2);
       
  1364 
       
  1365 					_m[tile].m5 = 1 << 7 | type << 2 | dir;
       
  1366 				}
       
  1367 			}
       
  1368 		}
       
  1369 	}
       
  1370 
       
  1371 	/* Divide MP_TUNNELBRIDGE into more tile types */
       
  1372 	if (CheckSavegameVersion(43)) {
       
  1373 		TileIndex tile;
       
  1374 
       
  1375 		for (tile = 0; tile != MapSize(); tile++) {
       
  1376 			if (IsTileType(tile, MP_TUNNEL)) {
       
  1377 				if (HASBIT(_m[tile].m5, 7)) { /* Bridge */
       
  1378 					DiagDirection dd = GB(_m[tile].m5, 0, 2);
       
  1379 					SB(_m[tile].m5, 0, 2, 0);
       
  1380 					if (GB(_m[tile].m5, 2, 2) == 0) { /* Railway Bridge */
       
  1381 						SetTileType(tile, MP_RAILWAY_BRIDGE);
       
  1382 						if (dd == DIAGDIR_NE || dd == DIAGDIR_SW) {
       
  1383 							SETBIT(_m[tile].m5, 0);
       
  1384 						} else {
       
  1385 							SETBIT(_m[tile].m5, 1);
       
  1386 						}
       
  1387 					} else {
       
  1388 						SetTileType(tile, MP_STREET_BRIDGE);
       
  1389 					}
       
  1390 					CLRBIT(_m[tile].m5, 7);
       
  1391 					SB(_m[tile].m5, 2, 2, 0);
       
  1392 					SB(_m[tile].m4, 5, 2, dd);
       
  1393 					/* Move the bridge type around */
       
  1394 					SB(_m[tile].m2, 12, 4, GB(_m[tile].m2, 4, 4));
       
  1395 					SB(_m[tile].m2, 4, 4, 0);
       
  1396 				} else { /* Tunnel */
       
  1397 					SetTileType(tile, MP_TUNNEL);
       
  1398 				}
       
  1399 			}
       
  1400 		}
       
  1401 	}
       
  1402 
       
  1403 	if (CheckSavegameVersion(42)) {
       
  1404 		Vehicle* v;
       
  1405 		FOR_ALL_VEHICLES(v) {
       
  1406 			if (v->type != VEH_Train && v->type != VEH_Road) continue;
       
  1407 			if (IsBridgeTile(v->tile)) {
       
  1408 				DiagDirection dir = GetBridgeRampDirection(v->tile);
       
  1409 
       
  1410 				if (dir != DirToDiagDir(v->direction)) continue;
       
  1411 				switch (dir) {
       
  1412 					default: NOT_REACHED();
       
  1413 					case DIAGDIR_NE: if ((v->x_pos & 0xF) !=  0)            continue; break;
       
  1414 					case DIAGDIR_SE: if ((v->y_pos & 0xF) != TILE_SIZE - 1) continue; break;
       
  1415 					case DIAGDIR_SW: if ((v->x_pos & 0xF) != TILE_SIZE - 1) continue; break;
       
  1416 					case DIAGDIR_NW: if ((v->y_pos & 0xF) !=  0)            continue; break;
       
  1417 				}
       
  1418 			} else if (v->z_pos > GetSlopeZ(v->x_pos, v->y_pos)) {
       
  1419 				v->tile = GetNorthernBridgeEnd(v->tile);
       
  1420 			} else {
       
  1421 				continue;
       
  1422 			}
       
  1423 			if (v->type == VEH_Train) {
       
  1424 				v->u.rail.track = 0x40;
       
  1425 			} else {
       
  1426 				v->u.road.state = 0xFF;
       
  1427 			}
       
  1428 		}
       
  1429 	}
       
  1430 
       
  1431 	/* Elrails got added in rev 24 */
       
  1432 	if (CheckSavegameVersion(24)) {
       
  1433 		Vehicle *v;
       
  1434 		uint i;
       
  1435 		TileIndex t;
       
  1436 		RailType min_rail = RAILTYPE_ELECTRIC;
       
  1437 
       
  1438 		for (i = 0; i < lengthof(_engines); i++) {
       
  1439 			Engine *e = GetEngine(i);
       
  1440 			if (e->type == VEH_Train &&
       
  1441 					(e->railtype != RAILTYPE_RAIL || RailVehInfo(i)->engclass == 2)) {
       
  1442 				e->railtype++;
       
  1443 			}
       
  1444 		}
       
  1445 
       
  1446 		FOR_ALL_VEHICLES(v) {
       
  1447 			if (v->type == VEH_Train) {
       
  1448 				RailType rt = GetEngine(v->engine_type)->railtype;
       
  1449 
       
  1450 				v->u.rail.railtype = rt;
       
  1451 				if (rt == RAILTYPE_ELECTRIC) min_rail = RAILTYPE_RAIL;
       
  1452 			}
       
  1453 		}
       
  1454 
       
  1455 		/* .. so we convert the entire map from normal to elrail (so maintain "fairness") */
       
  1456 		for (t = 0; t < MapSize(); t++) {
       
  1457 			switch (GetTileType(t)) {
       
  1458 				case MP_RAILWAY:
       
  1459 					SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
       
  1460 					break;
       
  1461 
       
  1462 				case MP_STREET:
       
  1463 					if (IsLevelCrossing(t)) {
       
  1464 						SetRailTypeCrossing(t, UpdateRailType(GetRailTypeCrossing(t), min_rail));
       
  1465 					}
       
  1466 					break;
       
  1467 
       
  1468 				case MP_STATION:
       
  1469 					if (IsRailwayStation(t)) {
       
  1470 						SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
       
  1471 					}
       
  1472 					break;
       
  1473 
       
  1474 				case MP_TUNNEL:
       
  1475 					if (GetTunnelTransportType(t) == TRANSPORT_RAIL) SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
       
  1476 					break;
       
  1477 
       
  1478 				case MP_RAILWAY_BRIDGE:
       
  1479 					SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
       
  1480 					break;
       
  1481 
       
  1482 				default:
       
  1483 					break;
       
  1484 			}
       
  1485 		}
       
  1486 
       
  1487 		FOR_ALL_VEHICLES(v) {
       
  1488 			if (v->type == VEH_Train && (IsFrontEngine(v) || IsFreeWagon(v))) TrainConsistChanged(v);
       
  1489 		}
       
  1490 
       
  1491 	}
       
  1492 
       
  1493 	/* In version 16.1 of the savegame a player can decide if trains, which get
       
  1494 	 * replaced, shall keep their old length. In all prior versions, just default
       
  1495 	 * to false */
       
  1496 	if (CheckSavegameVersionOldStyle(16, 1)) {
       
  1497 		FOR_ALL_PLAYERS(p) p->renew_keep_length = false;
       
  1498 	}
       
  1499 
       
  1500 	/* In version 17, ground type is moved from m2 to m4 for depots and
       
  1501 	 * waypoints to make way for storing the index in m2. The custom graphics
       
  1502 	 * id which was stored in m4 is now saved as a grf/id reference in the
       
  1503 	 * waypoint struct. */
       
  1504 	if (CheckSavegameVersion(17)) {
       
  1505 		Waypoint *wp;
       
  1506 
       
  1507 		FOR_ALL_WAYPOINTS(wp) {
       
  1508 			if (wp->deleted == 0) {
       
  1509 				const StationSpec *statspec = NULL;
       
  1510 
       
  1511 				if (HASBIT(_m[wp->xy].m3, 4))
       
  1512 					statspec = GetCustomStationSpec(STAT_CLASS_WAYP, _m[wp->xy].m4 + 1);
       
  1513 
       
  1514 				if (statspec != NULL) {
       
  1515 					wp->stat_id = _m[wp->xy].m4 + 1;
       
  1516 					wp->grfid = statspec->grfid;
       
  1517 					wp->localidx = statspec->localidx;
       
  1518 				} else {
       
  1519 					// No custom graphics set, so set to default.
       
  1520 					wp->stat_id = 0;
       
  1521 					wp->grfid = 0;
       
  1522 					wp->localidx = 0;
       
  1523 				}
       
  1524 
       
  1525 				// Move ground type bits from m2 to m4.
       
  1526 				_m[wp->xy].m4 = GB(_m[wp->xy].m2, 0, 4);
       
  1527 				// Store waypoint index in the tile.
       
  1528 				_m[wp->xy].m2 = wp->index;
       
  1529 			}
       
  1530 		}
       
  1531 	} else {
       
  1532 		/* As of version 17, we recalculate the custom graphic ID of waypoints
       
  1533 		 * from the GRF ID / station index. */
       
  1534 		AfterLoadWaypoints();
       
  1535 	}
       
  1536 
       
  1537 	/* From version 15, we moved a semaphore bit from bit 2 to bit 3 in m4, making
       
  1538 	 *  room for PBS. Now in version 21 move it back :P. */
       
  1539 	if (CheckSavegameVersion(21) && !CheckSavegameVersion(15)) {
       
  1540 		BEGIN_TILE_LOOP(tile, MapSizeX(), MapSizeY(), 0) {
       
  1541 			if (IsTileType(tile, MP_RAILWAY)) {
       
  1542 				if (HasSignals(tile)) {
       
  1543 					// convert PBS signals to combo-signals
       
  1544 					if (HASBIT(_m[tile].m4, 2)) SetSignalType(tile, SIGTYPE_COMBO);
       
  1545 
       
  1546 					// move the signal variant back
       
  1547 					SetSignalVariant(tile, HASBIT(_m[tile].m4, 3) ? SIG_SEMAPHORE : SIG_ELECTRIC);
       
  1548 					CLRBIT(_m[tile].m4, 3);
       
  1549 				}
       
  1550 
       
  1551 				// Clear PBS reservation on track
       
  1552 				if (!IsTileDepotType(tile, TRANSPORT_RAIL)) {
       
  1553 					SB(_m[tile].m4, 4, 4, 0);
       
  1554 				} else {
       
  1555 					CLRBIT(_m[tile].m3, 6);
       
  1556 				}
       
  1557 			}
       
  1558 
       
  1559 			// Clear PBS reservation on crossing
       
  1560 			if (IsTileType(tile, MP_STREET) && IsLevelCrossing(tile))
       
  1561 				CLRBIT(_m[tile].m5, 0);
       
  1562 
       
  1563 			// Clear PBS reservation on station
       
  1564 			if (IsTileType(tile, MP_STATION))
       
  1565 				CLRBIT(_m[tile].m3, 6);
       
  1566 		} END_TILE_LOOP(tile, MapSizeX(), MapSizeY(), 0);
       
  1567 	}
       
  1568 
       
  1569 	if (CheckSavegameVersion(22))  UpdatePatches();
       
  1570 
       
  1571 	if (CheckSavegameVersion(25)) {
       
  1572 		Vehicle *v;
       
  1573 		FOR_ALL_VEHICLES(v) {
       
  1574 			if (v->type == VEH_Road) {
       
  1575 				v->vehstatus &= ~0x40;
       
  1576 				v->u.road.slot = NULL;
       
  1577 				v->u.road.slot_age = 0;
       
  1578 			}
       
  1579 		}
       
  1580 	}
       
  1581 
       
  1582 	if (CheckSavegameVersion(26)) {
       
  1583 		Station *st;
       
  1584 		FOR_ALL_STATIONS(st) {
       
  1585 			st->last_vehicle_type = VEH_Invalid;
       
  1586 		}
       
  1587 	}
       
  1588 
       
  1589 	YapfNotifyTrackLayoutChange(INVALID_TILE, INVALID_TRACK);
       
  1590 
       
  1591 	if (CheckSavegameVersion(34)) FOR_ALL_PLAYERS(p) ResetPlayerLivery(p);
       
  1592 
       
  1593 	FOR_ALL_PLAYERS(p) p->avail_railtypes = GetPlayerRailtypes(p->index);
       
  1594 
       
  1595 	if (!CheckSavegameVersion(27)) AfterLoadStations();
       
  1596 
       
  1597 	{
       
  1598 		/* Set up the engine count for all players */
       
  1599 		Player *players[MAX_PLAYERS];
       
  1600 		int i;
       
  1601 		const Vehicle *v;
       
  1602 
       
  1603 		for (i = 0; i < MAX_PLAYERS; i++) players[i] = GetPlayer(i);
       
  1604 
       
  1605 		FOR_ALL_VEHICLES(v) {
       
  1606 			if (!IsEngineCountable(v)) continue;
       
  1607 			players[v->owner]->num_engines[v->engine_type]++;
       
  1608 		}
       
  1609 	}
       
  1610 
       
  1611 	/* Time starts at 0 instead of 1920.
       
  1612 	 * Account for this in older games by adding an offset */
       
  1613 	if (CheckSavegameVersion(31)) {
       
  1614 		Station *st;
       
  1615 		Waypoint *wp;
       
  1616 		Engine *e;
       
  1617 		Player *player;
       
  1618 		Industry *i;
       
  1619 		Vehicle *v;
       
  1620 
       
  1621 		_date += DAYS_TILL_ORIGINAL_BASE_YEAR;
       
  1622 		_cur_year += ORIGINAL_BASE_YEAR;
       
  1623 
       
  1624 		FOR_ALL_STATIONS(st)    st->build_date += DAYS_TILL_ORIGINAL_BASE_YEAR;
       
  1625 		FOR_ALL_WAYPOINTS(wp)   wp->build_date += DAYS_TILL_ORIGINAL_BASE_YEAR;
       
  1626 		FOR_ALL_ENGINES(e)      e->intro_date  += DAYS_TILL_ORIGINAL_BASE_YEAR;
       
  1627 		FOR_ALL_PLAYERS(player) player->inaugurated_year += ORIGINAL_BASE_YEAR;
       
  1628 		FOR_ALL_INDUSTRIES(i)   i->last_prod_year        += ORIGINAL_BASE_YEAR;
       
  1629 
       
  1630 		FOR_ALL_VEHICLES(v) {
       
  1631 			v->date_of_last_service += DAYS_TILL_ORIGINAL_BASE_YEAR;
       
  1632 			v->build_year += ORIGINAL_BASE_YEAR;
       
  1633 		}
       
  1634 	}
       
  1635 
       
  1636 	/* From 32 on we save the industry who made the farmland.
       
  1637 	 *  To give this prettyness to old savegames, we remove all farmfields and
       
  1638 	 *  plant new ones. */
       
  1639 	if (CheckSavegameVersion(32)) {
       
  1640 		Industry *i;
       
  1641 
       
  1642 		BEGIN_TILE_LOOP(tile_cur, MapSizeX(), MapSizeY(), 0) {
       
  1643 			if (IsTileType(tile_cur, MP_CLEAR) && IsClearGround(tile_cur, CLEAR_FIELDS)) {
       
  1644 				MakeClear(tile_cur, CLEAR_GRASS, 3);
       
  1645 			}
       
  1646 		} END_TILE_LOOP(tile_cur, MapSizeX(), MapSizeY(), 0)
       
  1647 
       
  1648 		FOR_ALL_INDUSTRIES(i) {
       
  1649 			uint j;
       
  1650 
       
  1651 			if (i->type == IT_FARM || i->type == IT_FARM_2) {
       
  1652 				for (j = 0; j != 50; j++) PlantRandomFarmField(i);
       
  1653 			}
       
  1654 		}
       
  1655 	}
       
  1656 
       
  1657 	/* Setting no refit flags to all orders in savegames from before refit in orders were added */
       
  1658 	if (CheckSavegameVersion(36)) {
       
  1659 		Order *order;
       
  1660 		Vehicle *v;
       
  1661 
       
  1662 		FOR_ALL_ORDERS(order) {
       
  1663 			order->refit_cargo   = CT_NO_REFIT;
       
  1664 			order->refit_subtype = CT_NO_REFIT;
       
  1665 		}
       
  1666 
       
  1667 		FOR_ALL_VEHICLES(v) {
       
  1668 			v->current_order.refit_cargo   = CT_NO_REFIT;
       
  1669 			v->current_order.refit_subtype = CT_NO_REFIT;
       
  1670 		}
       
  1671 	}
       
  1672 
       
  1673 	if (CheckSavegameVersion(37)) {
       
  1674 		ConvertNameArray();
       
  1675 	}
       
  1676 
       
  1677 	/* from version 38 we have optional elrails, since we cannot know the
       
  1678 	 * preference of a user, let elrails enabled; it can be disabled manually */
       
  1679 	if (CheckSavegameVersion(38)) {
       
  1680 		_patches.disable_elrails = false; // enable elrails
       
  1681 		/* do the same as when elrails were enabled/disabled manually just now */
       
  1682 		SettingsDisableElrail(_patches.disable_elrails);
       
  1683 	}
       
  1684 
       
  1685 	if (CheckSavegameVersion(43)) {
       
  1686 		BEGIN_TILE_LOOP(tile_cur, MapSizeX(), MapSizeY(), 0) {
       
  1687 			if (IsTileType(tile_cur, MP_INDUSTRY)) {
       
  1688 				switch (GetIndustryGfx(tile_cur)) {
       
  1689 					case GFX_POWERPLANT_SPARKS:
       
  1690 						SetIndustryAnimationState(tile_cur, GB(_m[tile_cur].m1, 2, 5));
       
  1691 						break;
       
  1692 
       
  1693 					case GFX_OILWELL_ANIMATED_1:
       
  1694 					case GFX_OILWELL_ANIMATED_2:
       
  1695 					case GFX_OILWELL_ANIMATED_3:
       
  1696 						SetIndustryAnimationState(tile_cur, GB(_m[tile_cur].m1, 0, 2));
       
  1697 						break;
       
  1698 
       
  1699 					case GFX_COAL_MINE_TOWER_ANIMATED:
       
  1700 					case GFX_COPPER_MINE_TOWER_ANIMATED:
       
  1701 					case GFX_GOLD_MINE_TOWER_ANIMATED:
       
  1702 						 SetIndustryAnimationState(tile_cur, _m[tile_cur].m1);
       
  1703 						 break;
       
  1704 
       
  1705 					default: /* No animation states to change */
       
  1706 						break;
       
  1707 				}
       
  1708 			}
       
  1709 		} END_TILE_LOOP(tile_cur, MapSizeX(), MapSizeY(), 0)
       
  1710 	}
       
  1711 
       
  1712 	return true;
       
  1713 }
       
  1714 
       
  1715 /** Reload all NewGRF files during a running game. This is a cut-down
       
  1716  * version of AfterLoadGame().
       
  1717  * XXX - We need to reset the vehicle position hash because with a non-empty
       
  1718  * hash AfterLoadVehicles() will loop infinitely. We need AfterLoadVehicles()
       
  1719  * to recalculate vehicle data as some NewGRF vehicle sets could have been
       
  1720  * removed or added and changed statistics */
       
  1721 void ReloadNewGRFData(void)
       
  1722 {
       
  1723 	/* reload grf data */
       
  1724 	GfxLoadSprites();
       
  1725 	LoadStringWidthTable();
       
  1726 	/* reload vehicles */
       
  1727 	ResetVehiclePosHash();
       
  1728 	AfterLoadVehicles();
       
  1729 	/* update station and waypoint graphics */
       
  1730 	AfterLoadWaypoints();
       
  1731 	AfterLoadStations();
       
  1732 	/* redraw the whole screen */
       
  1733 	MarkWholeScreenDirty();
       
  1734 }