src/openttd.cpp
branchcpp_gui
changeset 6303 84c215fc8eb8
parent 6298 c30fe89622df
child 6307 f40e88cff863
equal deleted inserted replaced
6302:bd80897189ba 6303:84c215fc8eb8
     1 /* $Id$ */
     1 /* $Id$ */
       
     2 
       
     3 /** @file openttd.cpp */
     2 
     4 
     3 #include "stdafx.h"
     5 #include "stdafx.h"
     4 #define VARDEF
     6 #define VARDEF
     5 #include "string.h"
     7 #include "string.h"
     6 #include "table/strings.h"
     8 #include "table/strings.h"
    54 #include "genworld.h"
    56 #include "genworld.h"
    55 #include "date.h"
    57 #include "date.h"
    56 #include "clear_map.h"
    58 #include "clear_map.h"
    57 #include "fontcache.h"
    59 #include "fontcache.h"
    58 #include "newgrf_config.h"
    60 #include "newgrf_config.h"
       
    61 #include "newgrf_house.h"
    59 #include "player_face.h"
    62 #include "player_face.h"
    60 
    63 
    61 #include "bridge_map.h"
    64 #include "bridge_map.h"
    62 #include "clear_map.h"
    65 #include "clear_map.h"
    63 #include "rail_map.h"
    66 #include "rail_map.h"
   217 		s = *md->argv++;
   220 		s = *md->argv++;
   218 		if (*s == '-') {
   221 		if (*s == '-') {
   219 md_continue_here:;
   222 md_continue_here:;
   220 			s++;
   223 			s++;
   221 			if (*s != 0) {
   224 			if (*s != 0) {
   222 				// Found argument, try to locate it in options.
   225 				/* Found argument, try to locate it in options. */
   223 				if (*s == ':' || (r = strchr(md->options, *s)) == NULL) {
   226 				if (*s == ':' || (r = strchr(md->options, *s)) == NULL) {
   224 					// ERROR!
   227 					/* ERROR! */
   225 					return -2;
   228 					return -2;
   226 				}
   229 				}
   227 				if (r[1] == ':') {
   230 				if (r[1] == ':') {
   228 					// Item wants an argument. Check if the argument follows, or if it comes as a separate arg.
   231 					/* Item wants an argument. Check if the argument follows, or if it comes as a separate arg. */
   229 					if (!*(t = s + 1)) {
   232 					if (!*(t = s + 1)) {
   230 						// It comes as a separate arg. Check if out of args?
   233 						/* It comes as a separate arg. Check if out of args? */
   231 						if (--md->numleft < 0 || *(t = *md->argv) == '-') {
   234 						if (--md->numleft < 0 || *(t = *md->argv) == '-') {
   232 							// Check if item is optional?
   235 							/* Check if item is optional? */
   233 							if (r[2] != ':')
   236 							if (r[2] != ':')
   234 								return -2;
   237 								return -2;
   235 							md->numleft++;
   238 							md->numleft++;
   236 							t = NULL;
   239 							t = NULL;
   237 						} else {
   240 						} else {
   245 				md->opt = NULL;
   248 				md->opt = NULL;
   246 				md->cont = s;
   249 				md->cont = s;
   247 				return *s;
   250 				return *s;
   248 			}
   251 			}
   249 		} else {
   252 		} else {
   250 			// This is currently not supported.
   253 			/* This is currently not supported. */
   251 			return -2;
   254 			return -2;
   252 		}
   255 		}
   253 	}
   256 	}
   254 }
   257 }
   255 
   258 
   302 	_game_mode = GM_MENU;
   305 	_game_mode = GM_MENU;
   303 	CLRBITS(_display_opt, DO_TRANS_BUILDINGS); // don't make buildings transparent in intro
   306 	CLRBITS(_display_opt, DO_TRANS_BUILDINGS); // don't make buildings transparent in intro
   304 	_opt_ptr = &_opt_newgame;
   307 	_opt_ptr = &_opt_newgame;
   305 	ResetGRFConfig(false);
   308 	ResetGRFConfig(false);
   306 
   309 
   307 	// Setup main window
   310 	/* Setup main window */
   308 	ResetWindowSystem();
   311 	ResetWindowSystem();
   309 	SetupColorsAndInitialWindow();
   312 	SetupColorsAndInitialWindow();
   310 
   313 
   311 	// Generate a world.
   314 	/* Generate a world. */
   312 	snprintf(filename, lengthof(filename), "%sopntitle.dat",  _paths.data_dir);
   315 	snprintf(filename, lengthof(filename), "%sopntitle.dat",  _paths.data_dir);
   313 #if defined SECOND_DATA_DIR
   316 #if defined SECOND_DATA_DIR
   314 	if (SaveOrLoad(filename, SL_LOAD) != SL_OK) {
   317 	if (SaveOrLoad(filename, SL_LOAD) != SL_OK) {
   315 		snprintf(filename, lengthof(filename), "%sopntitle.dat",  _paths.second_data_dir);
   318 		snprintf(filename, lengthof(filename), "%sopntitle.dat",  _paths.second_data_dir);
   316 	}
   319 	}
   325 	/* Make sure you can't scroll in the menu */
   328 	/* Make sure you can't scroll in the menu */
   326 	_scrolling_viewport = 0;
   329 	_scrolling_viewport = 0;
   327 	_cursor.fix_at = false;
   330 	_cursor.fix_at = false;
   328 	MarkWholeScreenDirty();
   331 	MarkWholeScreenDirty();
   329 
   332 
   330 	// Play main theme
   333 	/* Play main theme */
   331 	if (_music_driver->is_song_playing()) ResetMusic();
   334 	if (_music_driver->is_song_playing()) ResetMusic();
   332 }
   335 }
   333 
   336 
   334 #if defined(UNIX) && !defined(__MORPHOS__)
   337 #if defined(UNIX) && !defined(__MORPHOS__)
   335 extern void DedicatedFork();
   338 extern void DedicatedFork();
   359 	_switch_mode = SM_MENU;
   362 	_switch_mode = SM_MENU;
   360 	_switch_mode_errorstr = INVALID_STRING_ID;
   363 	_switch_mode_errorstr = INVALID_STRING_ID;
   361 	_dedicated_forks = false;
   364 	_dedicated_forks = false;
   362 	_config_file = NULL;
   365 	_config_file = NULL;
   363 
   366 
   364 	// The last param of the following function means this:
   367 	/* The last param of the following function means this:
   365 	//   a letter means: it accepts that param (e.g.: -h)
   368 	 *   a letter means: it accepts that param (e.g.: -h)
   366 	//   a ':' behind it means: it need a param (e.g.: -m<driver>)
   369 	 *   a ':' behind it means: it need a param (e.g.: -m<driver>)
   367 	//   a '::' behind it means: it can optional have a param (e.g.: -d<debug>)
   370 	 *   a '::' behind it means: it can optional have a param (e.g.: -d<debug>) */
   368 	optformat = "m:s:v:hD::n::eit:d::r:g::G:c:xl:"
   371 	optformat = "m:s:v:hD::n::eit:d::r:g::G:c:xl:"
   369 #if !defined(__MORPHOS__) && !defined(__AMIGA__) && !defined(WIN32)
   372 #if !defined(__MORPHOS__) && !defined(__AMIGA__) && !defined(WIN32)
   370 		"f"
   373 		"f"
   371 #endif
   374 #endif
   372 	;
   375 	;
   417 			if (mgo.opt != NULL) {
   420 			if (mgo.opt != NULL) {
   418 				strcpy(_file_to_saveload.name, mgo.opt);
   421 				strcpy(_file_to_saveload.name, mgo.opt);
   419 				_switch_mode = SM_LOAD;
   422 				_switch_mode = SM_LOAD;
   420 			} else {
   423 			} else {
   421 				_switch_mode = SM_NEWGAME;
   424 				_switch_mode = SM_NEWGAME;
       
   425 				/* Give a random map */
       
   426 				generation_seed = InteractiveRandom();
   422 			}
   427 			}
   423 			break;
   428 			break;
   424 		case 'G': generation_seed = atoi(mgo.opt); break;
   429 		case 'G': generation_seed = atoi(mgo.opt); break;
   425 		case 'c': _config_file = strdup(mgo.opt); break;
   430 		case 'c': _config_file = strdup(mgo.opt); break;
   426 		case 'x': save_config = false; break;
   431 		case 'x': save_config = false; break;
   429 			showhelp();
   434 			showhelp();
   430 			return 0;
   435 			return 0;
   431 		}
   436 		}
   432 	}
   437 	}
   433 
   438 
   434 	DeterminePaths();
   439 	DeterminePaths(argv[0]);
   435 	CheckExternalFiles();
   440 	CheckExternalFiles();
   436 
   441 
   437 #if defined(UNIX) && !defined(__MORPHOS__)
   442 #if defined(UNIX) && !defined(__MORPHOS__)
   438 	// We must fork here, or we'll end up without some resources we need (like sockets)
   443 	/* We must fork here, or we'll end up without some resources we need (like sockets) */
   439 	if (_dedicated_forks)
   444 	if (_dedicated_forks)
   440 		DedicatedFork();
   445 		DedicatedFork();
   441 #endif
   446 #endif
   442 
   447 
   443 	LoadFromConfig();
   448 	LoadFromConfig();
   444 	CheckConfig();
   449 	CheckConfig();
   445 	LoadFromHighScore();
   450 	LoadFromHighScore();
   446 
   451 
   447 	// override config?
   452 	/* override config? */
   448 	if (!StrEmpty(musicdriver)) ttd_strlcpy(_ini_musicdriver, musicdriver, sizeof(_ini_musicdriver));
   453 	if (!StrEmpty(musicdriver)) ttd_strlcpy(_ini_musicdriver, musicdriver, sizeof(_ini_musicdriver));
   449 	if (!StrEmpty(sounddriver)) ttd_strlcpy(_ini_sounddriver, sounddriver, sizeof(_ini_sounddriver));
   454 	if (!StrEmpty(sounddriver)) ttd_strlcpy(_ini_sounddriver, sounddriver, sizeof(_ini_sounddriver));
   450 	if (!StrEmpty(videodriver)) ttd_strlcpy(_ini_videodriver, videodriver, sizeof(_ini_videodriver));
   455 	if (!StrEmpty(videodriver)) ttd_strlcpy(_ini_videodriver, videodriver, sizeof(_ini_videodriver));
   451 	if (resolution[0] != 0) { _cur_resolution[0] = resolution[0]; _cur_resolution[1] = resolution[1]; }
   456 	if (resolution[0] != 0) { _cur_resolution[0] = resolution[0]; _cur_resolution[1] = resolution[1]; }
   452 	if (startyear != INVALID_YEAR) _patches_newgame.starting_year = startyear;
   457 	if (startyear != INVALID_YEAR) _patches_newgame.starting_year = startyear;
   456 	if (dedicated_host) snprintf(_network_server_bind_ip_host, NETWORK_HOSTNAME_LENGTH, "%s", dedicated_host);
   461 	if (dedicated_host) snprintf(_network_server_bind_ip_host, NETWORK_HOSTNAME_LENGTH, "%s", dedicated_host);
   457 	if (dedicated_port) _network_server_port = dedicated_port;
   462 	if (dedicated_port) _network_server_port = dedicated_port;
   458 	if (_dedicated_forks && !dedicated) _dedicated_forks = false;
   463 	if (_dedicated_forks && !dedicated) _dedicated_forks = false;
   459 #endif /* ENABLE_NETWORK */
   464 #endif /* ENABLE_NETWORK */
   460 
   465 
   461 	// enumerate language files
   466 	/* enumerate language files */
   462 	InitializeLanguagePacks();
   467 	InitializeLanguagePacks();
   463 
   468 
   464 	// initialize screenshot formats
   469 	/* initialize screenshot formats */
   465 	InitializeScreenshotFormats();
   470 	InitializeScreenshotFormats();
   466 
   471 
   467 	// initialize airport state machines
   472 	/* initialize airport state machines */
   468 	InitializeAirports();
   473 	InitializeAirports();
   469 
   474 
   470 	/* initialize all variables that are allocated dynamically */
   475 	/* initialize all variables that are allocated dynamically */
   471 	InitializeDynamicVariables();
   476 	InitializeDynamicVariables();
   472 
   477 
   473 	/* start the AI */
   478 	/* start the AI */
   474 	AI_Initialize();
   479 	AI_Initialize();
   475 
   480 
   476 	// Sample catalogue
   481 	/* Sample catalogue */
   477 	DEBUG(misc, 1, "Loading sound effects...");
   482 	DEBUG(misc, 1, "Loading sound effects...");
   478 	MxInitialize(11025);
   483 	MxInitialize(11025);
   479 	SoundInitialize("sample.cat");
   484 	SoundInitialize("sample.cat");
   480 
   485 
   481 	/* Initialize FreeType */
   486 	/* Initialize FreeType */
   482 	InitFreeType();
   487 	InitFreeType();
   483 
   488 
   484 	// This must be done early, since functions use the InvalidateWindow* calls
   489 	/* This must be done early, since functions use the InvalidateWindow* calls */
   485 	InitWindowSystem();
   490 	InitWindowSystem();
   486 
   491 
   487 	/* Initialize game palette */
   492 	/* Initialize game palette */
   488 	GfxInitPalettes();
   493 	GfxInitPalettes();
   489 
   494 
   491 	LoadDriver(SOUND_DRIVER, _ini_sounddriver);
   496 	LoadDriver(SOUND_DRIVER, _ini_sounddriver);
   492 	LoadDriver(MUSIC_DRIVER, _ini_musicdriver);
   497 	LoadDriver(MUSIC_DRIVER, _ini_musicdriver);
   493 	LoadDriver(VIDEO_DRIVER, _ini_videodriver); // load video last, to prevent an empty window while sound and music loads
   498 	LoadDriver(VIDEO_DRIVER, _ini_videodriver); // load video last, to prevent an empty window while sound and music loads
   494 	_savegame_sort_order = SORT_BY_DATE | SORT_DESCENDING;
   499 	_savegame_sort_order = SORT_BY_DATE | SORT_DESCENDING;
   495 
   500 
   496 	// restore saved music volume
   501 	/* restore saved music volume */
   497 	_music_driver->set_volume(msf.music_vol);
   502 	_music_driver->set_volume(msf.music_vol);
   498 
   503 
   499 	NetworkStartUp(); // initialize network-core
   504 	NetworkStartUp(); // initialize network-core
   500 
   505 
   501 #if defined(ENABLE_NETWORK)
   506 #if defined(ENABLE_NETWORK)
   525 	if (_switch_mode != SM_NONE) {
   530 	if (_switch_mode != SM_NONE) {
   526 		_opt = _opt_newgame;
   531 		_opt = _opt_newgame;
   527 		UpdatePatches();
   532 		UpdatePatches();
   528 	}
   533 	}
   529 
   534 
   530 	// initialize the ingame console
   535 	/* initialize the ingame console */
   531 	IConsoleInit();
   536 	IConsoleInit();
   532 	_cursor.in_window = true;
   537 	_cursor.in_window = true;
   533 	InitializeGUI();
   538 	InitializeGUI();
   534 	IConsoleCmdExec("exec scripts/autoexec.scr 0");
   539 	IConsoleCmdExec("exec scripts/autoexec.scr 0");
   535 
   540 
   673 static void MakeNewGame(bool from_heightmap)
   678 static void MakeNewGame(bool from_heightmap)
   674 {
   679 {
   675 	_game_mode = GM_NORMAL;
   680 	_game_mode = GM_NORMAL;
   676 
   681 
   677 	ResetGRFConfig(true);
   682 	ResetGRFConfig(true);
       
   683 	ResetHouseIDMapping();
   678 
   684 
   679 	GenerateWorldSetCallback(&MakeNewGameDone);
   685 	GenerateWorldSetCallback(&MakeNewGameDone);
   680 	GenerateWorld(from_heightmap ? GW_HEIGHTMAP : GW_NEWGAME, 1 << _patches.map_x, 1 << _patches.map_y);
   686 	GenerateWorld(from_heightmap ? GW_HEIGHTMAP : GW_NEWGAME, 1 << _patches.map_x, 1 << _patches.map_y);
   681 }
   687 }
   682 
   688 
   708  */
   714  */
   709 static void StartScenario()
   715 static void StartScenario()
   710 {
   716 {
   711 	_game_mode = GM_NORMAL;
   717 	_game_mode = GM_NORMAL;
   712 
   718 
   713 	// invalid type
   719 	/* invalid type */
   714 	if (_file_to_saveload.mode == SL_INVALID) {
   720 	if (_file_to_saveload.mode == SL_INVALID) {
   715 		DEBUG(sl, 0, "Savegame is obsolete or invalid format: '%s'", _file_to_saveload.name);
   721 		DEBUG(sl, 0, "Savegame is obsolete or invalid format: '%s'", _file_to_saveload.name);
   716 		ShowErrorMessage(INVALID_STRING_ID, STR_4009_GAME_LOAD_FAILED, 0, 0);
   722 		ShowErrorMessage(INVALID_STRING_ID, STR_4009_GAME_LOAD_FAILED, 0, 0);
   717 		_game_mode = GM_MENU;
   723 		_game_mode = GM_MENU;
   718 		return;
   724 		return;
   719 	}
   725 	}
   720 
   726 
   721 	// Reinitialize windows
   727 	/* Reinitialize windows */
   722 	ResetWindowSystem();
   728 	ResetWindowSystem();
   723 
   729 
   724 	SetupColorsAndInitialWindow();
   730 	SetupColorsAndInitialWindow();
   725 
   731 
   726 	ResetGRFConfig(true);
   732 	ResetGRFConfig(true);
   727 
   733 
   728 	// Load game
   734 	/* Load game */
   729 	if (SaveOrLoad(_file_to_saveload.name, _file_to_saveload.mode) != SL_OK) {
   735 	if (SaveOrLoad(_file_to_saveload.name, _file_to_saveload.mode) != SL_OK) {
   730 		LoadIntroGame();
   736 		LoadIntroGame();
   731 		ShowErrorMessage(INVALID_STRING_ID, STR_4009_GAME_LOAD_FAILED, 0, 0);
   737 		ShowErrorMessage(INVALID_STRING_ID, STR_4009_GAME_LOAD_FAILED, 0, 0);
   732 	}
   738 	}
   733 
   739 
   734 	_opt_ptr = &_opt;
   740 	_opt_ptr = &_opt;
   735 	_opt_ptr->diff = _opt_newgame.diff;
   741 	_opt_ptr->diff = _opt_newgame.diff;
   736 	_opt.diff_level = _opt_newgame.diff_level;
   742 	_opt.diff_level = _opt_newgame.diff_level;
   737 
   743 
   738 	// Inititalize data
   744 	/* Inititalize data */
   739 	StartupEconomy();
   745 	StartupEconomy();
   740 	StartupPlayers();
   746 	StartupPlayers();
   741 	StartupEngines();
   747 	StartupEngines();
   742 	StartupDisasters();
   748 	StartupDisasters();
   743 
   749 
   771 }
   777 }
   772 
   778 
   773 void SwitchMode(int new_mode)
   779 void SwitchMode(int new_mode)
   774 {
   780 {
   775 #ifdef ENABLE_NETWORK
   781 #ifdef ENABLE_NETWORK
   776 	// If we are saving something, the network stays in his current state
   782 	/* If we are saving something, the network stays in his current state */
   777 	if (new_mode != SM_SAVE) {
   783 	if (new_mode != SM_SAVE) {
   778 		// If the network is active, make it not-active
   784 		/* If the network is active, make it not-active */
   779 		if (_networking) {
   785 		if (_networking) {
   780 			if (_network_server && (new_mode == SM_LOAD || new_mode == SM_NEWGAME)) {
   786 			if (_network_server && (new_mode == SM_LOAD || new_mode == SM_NEWGAME)) {
   781 				NetworkReboot();
   787 				NetworkReboot();
   782 				NetworkUDPCloseAll();
   788 				NetworkUDPCloseAll();
   783 			} else {
   789 			} else {
   784 				NetworkDisconnect();
   790 				NetworkDisconnect();
   785 				NetworkUDPCloseAll();
   791 				NetworkUDPCloseAll();
   786 			}
   792 			}
   787 		}
   793 		}
   788 
   794 
   789 		// If we are a server, we restart the server
   795 		/* If we are a server, we restart the server */
   790 		if (_is_network_server) {
   796 		if (_is_network_server) {
   791 			// But not if we are going to the menu
   797 			/* But not if we are going to the menu */
   792 			if (new_mode != SM_MENU) {
   798 			if (new_mode != SM_MENU) {
   793 				NetworkServerStart();
   799 				NetworkServerStart();
   794 			} else {
   800 			} else {
   795 				// This client no longer wants to be a network-server
   801 				/* This client no longer wants to be a network-server */
   796 				_is_network_server = false;
   802 				_is_network_server = false;
   797 			}
   803 			}
   798 		}
   804 		}
   799 	}
   805 	}
   800 #endif /* ENABLE_NETWORK */
   806 #endif /* ENABLE_NETWORK */
   884 		break;
   890 		break;
   885 
   891 
   886 	case SM_GENRANDLAND: /* Generate random land within scenario editor */
   892 	case SM_GENRANDLAND: /* Generate random land within scenario editor */
   887 		SetLocalPlayer(OWNER_NONE);
   893 		SetLocalPlayer(OWNER_NONE);
   888 		GenerateWorld(GW_RANDOM, 1 << _patches.map_x, 1 << _patches.map_y);
   894 		GenerateWorld(GW_RANDOM, 1 << _patches.map_x, 1 << _patches.map_y);
   889 		// XXX: set date
   895 		/* XXX: set date */
   890 		MarkWholeScreenDirty();
   896 		MarkWholeScreenDirty();
   891 		break;
   897 		break;
   892 	}
   898 	}
   893 
   899 
   894 	if (_switch_mode_errorstr != INVALID_STRING_ID) {
   900 	if (_switch_mode_errorstr != INVALID_STRING_ID) {
   895 		ShowErrorMessage(INVALID_STRING_ID, _switch_mode_errorstr, 0, 0);
   901 		ShowErrorMessage(INVALID_STRING_ID, _switch_mode_errorstr, 0, 0);
   896 	}
   902 	}
   897 }
   903 }
   898 
   904 
   899 
   905 
   900 // State controlling game loop.
   906 /* State controlling game loop.
   901 // The state must not be changed from anywhere
   907  * The state must not be changed from anywhere
   902 // but here.
   908  * but here.
   903 // That check is enforced in DoCommand.
   909  * That check is enforced in DoCommand. */
   904 void StateGameLoop()
   910 void StateGameLoop()
   905 {
   911 {
   906 	// dont execute the state loop during pause
   912 	/* dont execute the state loop during pause */
   907 	if (_pause_game) return;
   913 	if (_pause_game) return;
   908 	if (IsGeneratingWorld()) return;
   914 	if (IsGeneratingWorld()) return;
   909 
   915 
   910 	if (_game_mode == GM_EDITOR) {
   916 	if (_game_mode == GM_EDITOR) {
   911 		RunTileLoop();
   917 		RunTileLoop();
   912 		CallVehicleTicks();
   918 		CallVehicleTicks();
   913 		CallLandscapeTick();
   919 		CallLandscapeTick();
   914 		CallWindowTickEvent();
   920 		CallWindowTickEvent();
   915 		NewsLoop();
   921 		NewsLoop();
   916 	} else {
   922 	} else {
   917 		// All these actions has to be done from OWNER_NONE
   923 		/* All these actions has to be done from OWNER_NONE
   918 		//  for multiplayer compatibility
   924 		 *  for multiplayer compatibility */
   919 		PlayerID p = _current_player;
   925 		PlayerID p = _current_player;
   920 		_current_player = OWNER_NONE;
   926 		_current_player = OWNER_NONE;
   921 
   927 
   922 		AnimateAnimatedTiles();
   928 		AnimateAnimatedTiles();
   923 		IncreaseDate();
   929 		IncreaseDate();
   952 		SetDParam(0, p->name_1);
   958 		SetDParam(0, p->name_1);
   953 		SetDParam(1, p->name_2);
   959 		SetDParam(1, p->name_2);
   954 		SetDParam(2, _date);
   960 		SetDParam(2, _date);
   955 		s = GetString(s, STR_4004, lastof(buf));
   961 		s = GetString(s, STR_4004, lastof(buf));
   956 		strecpy(s, ".sav", lastof(buf));
   962 		strecpy(s, ".sav", lastof(buf));
   957 	} else { /* generate a savegame name and number according to _patches.max_num_autosaves */
   963 	} else { // generate a savegame name and number according to _patches.max_num_autosaves
   958 		snprintf(buf, lengthof(buf), "%s%sautosave%d.sav", _paths.autosave_dir, PATHSEP, _autosave_ctr);
   964 		snprintf(buf, lengthof(buf), "%s%sautosave%d.sav", _paths.autosave_dir, PATHSEP, _autosave_ctr);
   959 
   965 
   960 		_autosave_ctr++;
   966 		_autosave_ctr++;
   961 		if (_autosave_ctr >= _patches.max_num_autosaves) {
   967 		if (_autosave_ctr >= _patches.max_num_autosaves) {
   962 			// we reached the limit for numbers of autosaves. We will start over
   968 			/* we reached the limit for numbers of autosaves. We will start over */
   963 			_autosave_ctr = 0;
   969 			_autosave_ctr = 0;
   964 		}
   970 		}
   965 	}
   971 	}
   966 
   972 
   967 	DEBUG(sl, 2, "Autosaving to '%s'", buf);
   973 	DEBUG(sl, 2, "Autosaving to '%s'", buf);
   980 	}
   986 	}
   981 }
   987 }
   982 
   988 
   983 static const int8 scrollamt[16][2] = {
   989 static const int8 scrollamt[16][2] = {
   984 	{ 0,  0},
   990 	{ 0,  0},
   985 	{-2,  0}, //  1 : left
   991 	{-2,  0}, ///<  1 : left
   986 	{ 0, -2}, //  2 : up
   992 	{ 0, -2}, ///<  2 : up
   987 	{-2, -1}, //  3 : left + up
   993 	{-2, -1}, ///<  3 : left + up
   988 	{ 2,  0}, //  4 : right
   994 	{ 2,  0}, ///<  4 : right
   989 	{ 0,  0}, //  5 : left + right
   995 	{ 0,  0}, ///<  5 : left + right
   990 	{ 2, -1}, //  6 : right + up
   996 	{ 2, -1}, ///<  6 : right + up
   991 	{ 0, -2}, //  7 : left + right + up = up
   997 	{ 0, -2}, ///<  7 : left + right + up = up
   992 	{ 0  ,2}, //  8 : down
   998 	{ 0  ,2}, ///<  8 : down
   993 	{-2  ,1}, //  9 : down+left
   999 	{-2  ,1}, ///<  9 : down+left
   994 	{ 0,  0}, // 10 : impossible
  1000 	{ 0,  0}, ///< 10 : impossible
   995 	{-2,  0}, // 11 : left + up + down = left
  1001 	{-2,  0}, ///< 11 : left + up + down = left
   996 	{ 2,  1}, // 12 : down+right
  1002 	{ 2,  1}, ///< 12 : down+right
   997 	{ 0,  2}, // 13 : left + right + down = down
  1003 	{ 0,  2}, ///< 13 : left + right + down = down
   998 	{ 0, -2}, // 14 : left + right + up = up
  1004 	{ 0, -2}, ///< 14 : left + right + up = up
   999 	{ 0,  0}, // 15 : impossible
  1005 	{ 0,  0}, ///< 15 : impossible
  1000 };
  1006 };
  1001 
  1007 
  1002 static void HandleKeyScrolling()
  1008 static void HandleKeyScrolling()
  1003 {
  1009 {
  1004 	if (_dirkeys && !_no_scroll) {
  1010 	if (_dirkeys && !_no_scroll) {
  1011 {
  1017 {
  1012 	ThreadMsg message;
  1018 	ThreadMsg message;
  1013 
  1019 
  1014 	if ((message = OTTD_PollThreadEvent()) != 0) ProcessSentMessage(message);
  1020 	if ((message = OTTD_PollThreadEvent()) != 0) ProcessSentMessage(message);
  1015 
  1021 
  1016 	// autosave game?
  1022 	/* autosave game? */
  1017 	if (_do_autosave) {
  1023 	if (_do_autosave) {
  1018 		_do_autosave = false;
  1024 		_do_autosave = false;
  1019 		DoAutosave();
  1025 		DoAutosave();
  1020 		RedrawAutosave();
  1026 		RedrawAutosave();
  1021 	}
  1027 	}
  1022 
  1028 
  1023 	// handle scrolling of the main window
  1029 	/* handle scrolling of the main window */
  1024 	HandleKeyScrolling();
  1030 	HandleKeyScrolling();
  1025 
  1031 
  1026 	// make a screenshot?
  1032 	/* make a screenshot? */
  1027 	if (IsScreenshotRequested()) ShowScreenshotResult(MakeScreenshot());
  1033 	if (IsScreenshotRequested()) ShowScreenshotResult(MakeScreenshot());
  1028 
  1034 
  1029 	// switch game mode?
  1035 	/* switch game mode? */
  1030 	if (_switch_mode != SM_NONE) {
  1036 	if (_switch_mode != SM_NONE) {
  1031 		SwitchMode(_switch_mode);
  1037 		SwitchMode(_switch_mode);
  1032 		_switch_mode = SM_NONE;
  1038 		_switch_mode = SM_NONE;
  1033 	}
  1039 	}
  1034 
  1040 
  1044 	_caret_timer += 3;
  1050 	_caret_timer += 3;
  1045 	_timer_counter += 8;
  1051 	_timer_counter += 8;
  1046 	CursorTick();
  1052 	CursorTick();
  1047 
  1053 
  1048 #ifdef ENABLE_NETWORK
  1054 #ifdef ENABLE_NETWORK
  1049 	// Check for UDP stuff
  1055 	/* Check for UDP stuff */
  1050 	if (_network_available) NetworkUDPGameLoop();
  1056 	if (_network_available) NetworkUDPGameLoop();
  1051 
  1057 
  1052 	if (_networking && !IsGeneratingWorld()) {
  1058 	if (_networking && !IsGeneratingWorld()) {
  1053 		// Multiplayer
  1059 		/* Multiplayer */
  1054 		NetworkGameLoop();
  1060 		NetworkGameLoop();
  1055 	} else {
  1061 	} else {
  1056 		if (_network_reconnect > 0 && --_network_reconnect == 0) {
  1062 		if (_network_reconnect > 0 && --_network_reconnect == 0) {
  1057 			// This means that we want to reconnect to the last host
  1063 			/* This means that we want to reconnect to the last host
  1058 			// We do this here, because it means that the network is really closed
  1064 			 * We do this here, because it means that the network is really closed */
  1059 			NetworkClientConnectGame(_network_last_host, _network_last_port);
  1065 			NetworkClientConnectGame(_network_last_host, _network_last_port);
  1060 		}
  1066 		}
  1061 		// Singleplayer
  1067 		/* Singleplayer */
  1062 		StateGameLoop();
  1068 		StateGameLoop();
  1063 	}
  1069 	}
  1064 #else
  1070 #else
  1065 	StateGameLoop();
  1071 	StateGameLoop();
  1066 #endif /* ENABLE_NETWORK */
  1072 #endif /* ENABLE_NETWORK */
  1104 			default: break;
  1110 			default: break;
  1105 		}
  1111 		}
  1106 	}
  1112 	}
  1107 }
  1113 }
  1108 
  1114 
  1109 // before savegame version 4, the name of the company determined if it existed
  1115 /* before savegame version 4, the name of the company determined if it existed */
  1110 static void CheckIsPlayerActive()
  1116 static void CheckIsPlayerActive()
  1111 {
  1117 {
  1112 	Player *p;
  1118 	Player *p;
  1113 
  1119 
  1114 	FOR_ALL_PLAYERS(p) {
  1120 	FOR_ALL_PLAYERS(p) {
  1115 		if (p->name_1 != 0) p->is_active = true;
  1121 		if (p->name_1 != 0) p->is_active = true;
  1116 	}
  1122 	}
  1117 }
  1123 }
  1118 
  1124 
  1119 // since savegame version 4.1, exclusive transport rights are stored at towns
  1125 /* since savegame version 4.1, exclusive transport rights are stored at towns */
  1120 static void UpdateExclusiveRights()
  1126 static void UpdateExclusiveRights()
  1121 {
  1127 {
  1122 	Town *t;
  1128 	Town *t;
  1123 
  1129 
  1124 	FOR_ALL_TOWNS(t) {
  1130 	FOR_ALL_TOWNS(t) {
  1140 	10, 14, 19,  4,  5,
  1146 	10, 14, 19,  4,  5,
  1141 	 9, 11, 13,  6, 17,
  1147 	 9, 11, 13,  6, 17,
  1142 	16, 22, 21,  7, 15,
  1148 	16, 22, 21,  7, 15,
  1143 	18,  2, 20, };
  1149 	18,  2, 20, };
  1144 
  1150 
  1145 // since savegame version 4.2 the currencies are arranged differently
  1151 /* since savegame version 4.2 the currencies are arranged differently */
  1146 static void UpdateCurrencies()
  1152 static void UpdateCurrencies()
  1147 {
  1153 {
  1148 	_opt.currency = convert_currency[_opt.currency];
  1154 	_opt.currency = convert_currency[_opt.currency];
  1149 }
  1155 }
  1150 
  1156 
  1157 
  1163 
  1158 	for (i = 0; i < MapMaxY(); ++i) MakeVoid(i * MapSizeX() + MapMaxX());
  1164 	for (i = 0; i < MapMaxY(); ++i) MakeVoid(i * MapSizeX() + MapMaxX());
  1159 	for (i = 0; i < MapSizeX(); ++i) MakeVoid(MapSizeX() * MapMaxY() + i);
  1165 	for (i = 0; i < MapSizeX(); ++i) MakeVoid(MapSizeX() * MapMaxY() + i);
  1160 }
  1166 }
  1161 
  1167 
  1162 // since savegame version 6.0 each sign has an "owner", signs without owner (from old games are set to 255)
  1168 /* since savegame version 6.0 each sign has an "owner", signs without owner (from old games are set to 255) */
  1163 static void UpdateSignOwner()
  1169 static void UpdateSignOwner()
  1164 {
  1170 {
  1165 	Sign *si;
  1171 	Sign *si;
  1166 
  1172 
  1167 	FOR_ALL_SIGNS(si) si->owner = OWNER_NONE;
  1173 	FOR_ALL_SIGNS(si) si->owner = OWNER_NONE;
  1180 	TileIndex map_size = MapSize();
  1186 	TileIndex map_size = MapSize();
  1181 	BaseWindow *w;
  1187 	BaseWindow *w;
  1182 	ViewPort *vp;
  1188 	ViewPort *vp;
  1183 	Player *p;
  1189 	Player *p;
  1184 
  1190 
  1185 	// in version 2.1 of the savegame, town owner was unified.
  1191 	/* in version 2.1 of the savegame, town owner was unified. */
  1186 	if (CheckSavegameVersionOldStyle(2, 1)) ConvertTownOwner();
  1192 	if (CheckSavegameVersionOldStyle(2, 1)) ConvertTownOwner();
  1187 
  1193 
  1188 	// from version 4.1 of the savegame, exclusive rights are stored at towns
  1194 	/* from version 4.1 of the savegame, exclusive rights are stored at towns */
  1189 	if (CheckSavegameVersionOldStyle(4, 1)) UpdateExclusiveRights();
  1195 	if (CheckSavegameVersionOldStyle(4, 1)) UpdateExclusiveRights();
  1190 
  1196 
  1191 	// from version 4.2 of the savegame, currencies are in a different order
  1197 	/* from version 4.2 of the savegame, currencies are in a different order */
  1192 	if (CheckSavegameVersionOldStyle(4, 2)) UpdateCurrencies();
  1198 	if (CheckSavegameVersionOldStyle(4, 2)) UpdateCurrencies();
  1193 
  1199 
  1194 	// from version 6.1 of the savegame, signs have an "owner"
  1200 	/* from version 6.1 of the savegame, signs have an "owner" */
  1195 	if (CheckSavegameVersionOldStyle(6, 1)) UpdateSignOwner();
  1201 	if (CheckSavegameVersionOldStyle(6, 1)) UpdateSignOwner();
  1196 
  1202 
  1197 	/* In old version there seems to be a problem that water is owned by
  1203 	/* In old version there seems to be a problem that water is owned by
  1198 	    OWNER_NONE, not OWNER_WATER.. I can't replicate it for the current
  1204 	    OWNER_NONE, not OWNER_WATER.. I can't replicate it for the current
  1199 	    (4.3) version, so I just check when versions are older, and then
  1205 	    (4.3) version, so I just check when versions are older, and then
  1204 				SetTileOwner(t, OWNER_WATER);
  1210 				SetTileOwner(t, OWNER_WATER);
  1205 			}
  1211 			}
  1206 		}
  1212 		}
  1207 	}
  1213 	}
  1208 
  1214 
  1209 	// convert road side to my format.
  1215 	/* convert road side to my format. */
  1210 	if (_opt.road_side) _opt.road_side = 1;
  1216 	if (_opt.road_side) _opt.road_side = 1;
  1211 
  1217 
  1212 	/* Check if all NewGRFs are present, we are very strict in MP mode */
  1218 	/* Check if all NewGRFs are present, we are very strict in MP mode */
  1213 	GRFListCompatibility gcf_res = IsGoodGRFConfigList();
  1219 	GRFListCompatibility gcf_res = IsGoodGRFConfigList();
  1214 	if (_networking && gcf_res != GLC_ALL_GOOD) return false;
  1220 	if (_networking && gcf_res != GLC_ALL_GOOD) return false;
  1221 
  1227 
  1222 	/* Update current year
  1228 	/* Update current year
  1223 	 * must be done before loading sprites as some newgrfs check it */
  1229 	 * must be done before loading sprites as some newgrfs check it */
  1224 	SetDate(_date);
  1230 	SetDate(_date);
  1225 
  1231 
  1226 	// Load the sprites
  1232 	/* Load the sprites */
  1227 	GfxLoadSprites();
  1233 	GfxLoadSprites();
  1228 	LoadStringWidthTable();
  1234 	LoadStringWidthTable();
  1229 
  1235 
  1230 	/* Connect front and rear engines of multiheaded trains and converts
  1236 	/* Connect front and rear engines of multiheaded trains and converts
  1231 	 * subtype to the new format */
  1237 	 * subtype to the new format */
  1232 	if (CheckSavegameVersionOldStyle(17, 1)) ConvertOldMultiheadToNew();
  1238 	if (CheckSavegameVersionOldStyle(17, 1)) ConvertOldMultiheadToNew();
  1233 
  1239 
  1234 	/* Connect front and rear engines of multiheaded trains */
  1240 	/* Connect front and rear engines of multiheaded trains */
  1235 	ConnectMultiheadedTrains();
  1241 	ConnectMultiheadedTrains();
  1236 
  1242 
  1237 	// reinit the landscape variables (landscape might have changed)
  1243 	/* reinit the landscape variables (landscape might have changed) */
  1238 	InitializeLandscapeVariables(true);
  1244 	InitializeLandscapeVariables(true);
  1239 
  1245 
  1240 	// Update all vehicles
  1246 	/* Update all vehicles */
  1241 	AfterLoadVehicles();
  1247 	AfterLoadVehicles();
  1242 
  1248 
  1243 	// Update all waypoints
  1249 	/* Update all waypoints */
  1244 	if (CheckSavegameVersion(12)) FixOldWaypoints();
  1250 	if (CheckSavegameVersion(12)) FixOldWaypoints();
  1245 
  1251 
  1246 	UpdateAllWaypointSigns();
  1252 	UpdateAllWaypointSigns();
  1247 
  1253 
  1248 	// in version 2.2 of the savegame, we have new airports
  1254 	/* in version 2.2 of the savegame, we have new airports */
  1249 	if (CheckSavegameVersionOldStyle(2, 2)) UpdateOldAircraft();
  1255 	if (CheckSavegameVersionOldStyle(2, 2)) UpdateOldAircraft();
  1250 
  1256 
  1251 	UpdateAllStationVirtCoord();
  1257 	UpdateAllStationVirtCoord();
  1252 
  1258 
  1253 	// Setup town coords
  1259 	/* Setup town coords */
  1254 	AfterLoadTown();
  1260 	AfterLoadTown();
  1255 	UpdateAllSignVirtCoords();
  1261 	UpdateAllSignVirtCoords();
  1256 
  1262 
  1257 	// make sure there is a town in the game
  1263 	/* make sure there is a town in the game */
  1258 	if (_game_mode == GM_NORMAL && !ClosestTownFromTile(0, (uint)-1)) {
  1264 	if (_game_mode == GM_NORMAL && !ClosestTownFromTile(0, (uint)-1)) {
  1259 		_error_message = STR_NO_TOWN_IN_SCENARIO;
  1265 		_error_message = STR_NO_TOWN_IN_SCENARIO;
  1260 		return false;
  1266 		return false;
  1261 	}
  1267 	}
  1262 
  1268 
  1263 	// Initialize windows
  1269 	/* Initialize windows */
  1264 	ResetWindowSystem();
  1270 	ResetWindowSystem();
  1265 	SetupColorsAndInitialWindow();
  1271 	SetupColorsAndInitialWindow();
  1266 
  1272 
  1267 	w = BaseWindow::FindById(WC_MAIN_WINDOW, 0);
  1273 	w = BaseWindow::FindById(WC_MAIN_WINDOW, 0);
  1268 
  1274 
  1272 	vp = w->viewport;
  1278 	vp = w->viewport;
  1273 	vp->zoom = _saved_scrollpos_zoom;
  1279 	vp->zoom = _saved_scrollpos_zoom;
  1274 	vp->virtual_width = vp->width << vp->zoom;
  1280 	vp->virtual_width = vp->width << vp->zoom;
  1275 	vp->virtual_height = vp->height << vp->zoom;
  1281 	vp->virtual_height = vp->height << vp->zoom;
  1276 
  1282 
  1277 	// in version 4.1 of the savegame, is_active was introduced to determine
  1283 	/* in version 4.1 of the savegame, is_active was introduced to determine
  1278 	// if a player does exist, rather then checking name_1
  1284 	 * if a player does exist, rather then checking name_1 */
  1279 	if (CheckSavegameVersionOldStyle(4, 1)) CheckIsPlayerActive();
  1285 	if (CheckSavegameVersionOldStyle(4, 1)) CheckIsPlayerActive();
  1280 
  1286 
  1281 	// the void tiles on the southern border used to belong to a wrong class (pre 4.3).
  1287 	/* the void tiles on the southern border used to belong to a wrong class (pre 4.3). */
  1282 	if (CheckSavegameVersionOldStyle(4, 3)) UpdateVoidTiles();
  1288 	if (CheckSavegameVersionOldStyle(4, 3)) UpdateVoidTiles();
  1283 
  1289 
  1284 	// If Load Scenario / New (Scenario) Game is used,
  1290 	/* If Load Scenario / New (Scenario) Game is used,
  1285 	//  a player does not exist yet. So create one here.
  1291 	 *  a player does not exist yet. So create one here.
  1286 	// 1 exeption: network-games. Those can have 0 players
  1292 	 * 1 exeption: network-games. Those can have 0 players
  1287 	//   But this exeption is not true for network_servers!
  1293 	 *   But this exeption is not true for network_servers! */
  1288 	if (!_players[0].is_active && (!_networking || (_networking && _network_server)))
  1294 	if (!_players[0].is_active && (!_networking || (_networking && _network_server)))
  1289 		DoStartupNewPlayer(false);
  1295 		DoStartupNewPlayer(false);
  1290 
  1296 
  1291 	DoZoomInOutWindow(ZOOM_NONE, w); // update button status
  1297 	DoZoomInOutWindow(ZOOM_NONE, w); // update button status
  1292 	MarkWholeScreenDirty();
  1298 	MarkWholeScreenDirty();
  1578 				if (statspec != NULL) {
  1584 				if (statspec != NULL) {
  1579 					wp->stat_id = _m[wp->xy].m4 + 1;
  1585 					wp->stat_id = _m[wp->xy].m4 + 1;
  1580 					wp->grfid = statspec->grfid;
  1586 					wp->grfid = statspec->grfid;
  1581 					wp->localidx = statspec->localidx;
  1587 					wp->localidx = statspec->localidx;
  1582 				} else {
  1588 				} else {
  1583 					// No custom graphics set, so set to default.
  1589 					/* No custom graphics set, so set to default. */
  1584 					wp->stat_id = 0;
  1590 					wp->stat_id = 0;
  1585 					wp->grfid = 0;
  1591 					wp->grfid = 0;
  1586 					wp->localidx = 0;
  1592 					wp->localidx = 0;
  1587 				}
  1593 				}
  1588 
  1594 
  1589 				// Move ground type bits from m2 to m4.
  1595 				/* Move ground type bits from m2 to m4. */
  1590 				_m[wp->xy].m4 = GB(_m[wp->xy].m2, 0, 4);
  1596 				_m[wp->xy].m4 = GB(_m[wp->xy].m2, 0, 4);
  1591 				// Store waypoint index in the tile.
  1597 				/* Store waypoint index in the tile. */
  1592 				_m[wp->xy].m2 = wp->index;
  1598 				_m[wp->xy].m2 = wp->index;
  1593 			}
  1599 			}
  1594 		}
  1600 		}
  1595 	} else {
  1601 	} else {
  1596 		/* As of version 17, we recalculate the custom graphic ID of waypoints
  1602 		/* As of version 17, we recalculate the custom graphic ID of waypoints
  1603 	if (CheckSavegameVersion(21) && !CheckSavegameVersion(15)) {
  1609 	if (CheckSavegameVersion(21) && !CheckSavegameVersion(15)) {
  1604 		for (TileIndex t = 0; t < map_size; t++) {
  1610 		for (TileIndex t = 0; t < map_size; t++) {
  1605 			switch (GetTileType(t)) {
  1611 			switch (GetTileType(t)) {
  1606 				case MP_RAILWAY:
  1612 				case MP_RAILWAY:
  1607 					if (HasSignals(t)) {
  1613 					if (HasSignals(t)) {
  1608 						// convert PBS signals to combo-signals
  1614 						/* convert PBS signals to combo-signals */
  1609 						if (HASBIT(_m[t].m2, 2)) SetSignalType(t, SIGTYPE_COMBO);
  1615 						if (HASBIT(_m[t].m2, 2)) SetSignalType(t, SIGTYPE_COMBO);
  1610 
  1616 
  1611 						// move the signal variant back
  1617 						/* move the signal variant back */
  1612 						SetSignalVariant(t, HASBIT(_m[t].m2, 3) ? SIG_SEMAPHORE : SIG_ELECTRIC);
  1618 						SetSignalVariant(t, HASBIT(_m[t].m2, 3) ? SIG_SEMAPHORE : SIG_ELECTRIC);
  1613 						CLRBIT(_m[t].m2, 3);
  1619 						CLRBIT(_m[t].m2, 3);
  1614 					}
  1620 					}
  1615 
  1621 
  1616 					// Clear PBS reservation on track
  1622 					/* Clear PBS reservation on track */
  1617 					if (!IsTileDepotType(t, TRANSPORT_RAIL)) {
  1623 					if (!IsTileDepotType(t, TRANSPORT_RAIL)) {
  1618 						SB(_m[t].m4, 4, 4, 0);
  1624 						SB(_m[t].m4, 4, 4, 0);
  1619 					} else {
  1625 					} else {
  1620 						CLRBIT(_m[t].m3, 6);
  1626 						CLRBIT(_m[t].m3, 6);
  1621 					}
  1627 					}
  1622 					break;
  1628 					break;
  1623 
  1629 
  1624 				case MP_STREET:
  1630 				case MP_STREET: /* Clear PBS reservation on crossing */
  1625 					// Clear PBS reservation on crossing
       
  1626 					if (IsLevelCrossing(t)) CLRBIT(_m[t].m5, 0);
  1631 					if (IsLevelCrossing(t)) CLRBIT(_m[t].m5, 0);
  1627 					break;
  1632 					break;
  1628 
  1633 
  1629 				case MP_STATION:
  1634 				case MP_STATION: /* Clear PBS reservation on station */
  1630 					// Clear PBS reservation on station
       
  1631 					CLRBIT(_m[t].m3, 6);
  1635 					CLRBIT(_m[t].m3, 6);
  1632 					break;
  1636 					break;
  1633 
  1637 
  1634 				default: break;
  1638 				default: break;
  1635 			}
  1639 			}
  1751 	/* from version 38 we have optional elrails, since we cannot know the
  1755 	/* from version 38 we have optional elrails, since we cannot know the
  1752 	 * preference of a user, let elrails enabled; it can be disabled manually */
  1756 	 * preference of a user, let elrails enabled; it can be disabled manually */
  1753 	if (CheckSavegameVersion(38)) _patches.disable_elrails = false;
  1757 	if (CheckSavegameVersion(38)) _patches.disable_elrails = false;
  1754 	/* do the same as when elrails were enabled/disabled manually just now */
  1758 	/* do the same as when elrails were enabled/disabled manually just now */
  1755 	SettingsDisableElrail(_patches.disable_elrails);
  1759 	SettingsDisableElrail(_patches.disable_elrails);
       
  1760 
       
  1761 	/* From version 53, the map array was changed for house tiles to allow
       
  1762 	 * space for newhouses grf features. A new byte, m7, was also added. */
       
  1763 	if (CheckSavegameVersion(53)) {
       
  1764 		for (TileIndex t = 0; t < map_size; t++) {
       
  1765 			_me[t].m7 = 0;
       
  1766 
       
  1767 			if (IsTileType(t, MP_HOUSE)) {
       
  1768 				if (GB(_m[t].m3, 6, 2) != TOWN_HOUSE_COMPLETED) {
       
  1769 					/* Move the construction stage from m3[7..6] to m5[5..4].
       
  1770 					 * The construction counter does not have to move. */
       
  1771 					SB(_m[t].m5, 3, 2, GB(_m[t].m3, 6, 2));
       
  1772 					SB(_m[t].m3, 6, 2, 0);
       
  1773 
       
  1774 					/* The "house is completed" bit is now in m6[2]. */
       
  1775 					SetHouseCompleted(t, false);
       
  1776 				} else {
       
  1777 					/* The "lift has destination" bit has been moved from
       
  1778 					 * m5[7] to m7[0]. */
       
  1779 					SB(_me[t].m7, 0, 1, HASBIT(_m[t].m5, 7));
       
  1780 					CLRBIT(_m[t].m5, 7);
       
  1781 
       
  1782 					/* The "lift is moving" bit has been removed, as it does
       
  1783 					 * the same job as the "lift has destination" bit. */
       
  1784 					CLRBIT(_m[t].m1, 7);
       
  1785 
       
  1786 					/* The position of the lift goes from m1[7..0] to m6[7..2],
       
  1787 					 * making m1 totally free, now. The lift position does not
       
  1788 					 * have to be a full byte since the maximum value is 36. */
       
  1789 					SetLiftPosition(t, GB(_m[t].m1, 0, 6 ));
       
  1790 
       
  1791 					_m[t].m1 = 0;
       
  1792 					_m[t].m3 = 0;
       
  1793 					SetHouseCompleted(t, true);
       
  1794 				}
       
  1795 			}
       
  1796 		}
       
  1797 	}
       
  1798 
       
  1799 	/* Count the buildings after updating the map array. */
       
  1800 	AfterLoadCountBuildings();
  1756 
  1801 
  1757 	if (CheckSavegameVersion(43)) {
  1802 	if (CheckSavegameVersion(43)) {
  1758 		for (TileIndex t = 0; t < map_size; t++) {
  1803 		for (TileIndex t = 0; t < map_size; t++) {
  1759 			if (IsTileType(t, MP_INDUSTRY)) {
  1804 			if (IsTileType(t, MP_INDUSTRY)) {
  1760 				switch (GetIndustryGfx(t)) {
  1805 				switch (GetIndustryGfx(t)) {
  1789 		 * where this situation exists, the cargo-source information is lost. in this case, we set the origin
  1834 		 * where this situation exists, the cargo-source information is lost. in this case, we set the origin
  1790 		 * to the current tile of the vehicle to prevent excessive profits
  1835 		 * to the current tile of the vehicle to prevent excessive profits
  1791 		 */
  1836 		 */
  1792 		FOR_ALL_VEHICLES(v) {
  1837 		FOR_ALL_VEHICLES(v) {
  1793 			v->cargo_source_xy = IsValidStationID(v->cargo_source) ? GetStation(v->cargo_source)->xy : v->tile;
  1838 			v->cargo_source_xy = IsValidStationID(v->cargo_source) ? GetStation(v->cargo_source)->xy : v->tile;
       
  1839 		}
       
  1840 
       
  1841 		/* Store position of the station where the goods come from, so there
       
  1842 		 * are no very high payments when stations get removed. However, if the
       
  1843 		 * station where the goods came from is already removed, the source
       
  1844 		 * information is lost. In that case we set it to the position of this
       
  1845 		 * station */
       
  1846 		Station *st;
       
  1847 		FOR_ALL_STATIONS(st) {
       
  1848 			for (CargoID c = 0; c < NUM_CARGO; c++) {
       
  1849 				GoodsEntry *ge = &st->goods[c];
       
  1850 
       
  1851 				/* In old versions, enroute_from used 0xFF as INVALID_STATION */
       
  1852 				if (CheckSavegameVersion(7) && ge->enroute_from == 0xFF) {
       
  1853 					ge->enroute_from = INVALID_STATION;
       
  1854 				}
       
  1855 
       
  1856 				ge->enroute_from_xy = IsValidStationID(ge->enroute_from) ? GetStation(ge->enroute_from)->xy : st->xy;
       
  1857 			}
  1794 		}
  1858 		}
  1795 	}
  1859 	}
  1796 
  1860 
  1797 	if (CheckSavegameVersion(45)) {
  1861 	if (CheckSavegameVersion(45)) {
  1798 		Vehicle *v;
  1862 		Vehicle *v;
  1863 	AfterLoadVehicles();
  1927 	AfterLoadVehicles();
  1864 	StartupEngines();
  1928 	StartupEngines();
  1865 	/* update station and waypoint graphics */
  1929 	/* update station and waypoint graphics */
  1866 	AfterLoadWaypoints();
  1930 	AfterLoadWaypoints();
  1867 	AfterLoadStations();
  1931 	AfterLoadStations();
       
  1932 	/* check that house ids are still valid */
       
  1933 	CheckHouseIDs();
  1868 	/* redraw the whole screen */
  1934 	/* redraw the whole screen */
  1869 	MarkWholeScreenDirty();
  1935 	MarkWholeScreenDirty();
  1870 }
  1936 }
  1871 
  1937 
  1872 HalMusicDriver *_music_driver;
  1938 HalMusicDriver *_music_driver;