Changeset - r14733:d5287af271c9
[Not reviewed]
master
0 3 0
yexo - 14 years ago 2010-03-06 01:58:55
yexo@openttd.org
(svn r19331) -Fix: when deleting an airport the size from the AirportSpec was used instead of the stored airport size
-Fix (r19319): detecting if a plane was landed at an airport failed
-Fix: reset the airporttile mapping when restarting a game
3 files changed with 4 insertions and 7 deletions:
0 comments (0 inline, 0 general)
src/newgrf_airporttiles.h
Show inline comments
 
/* $Id$ */
 

	
 
/*
 
 * This file is part of OpenTTD.
 
 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
 
 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 
 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
 
 */
 

	
 
/** @file newgrf_airporttiles.h NewGRF handling of airport tiles. */
 

	
 
#ifndef NEWGRF_AIRPORTTILES_H
 
#define NEWGRF_AIRPORTTILES_H
 

	
 
#include "airport.h"
 
#include "station_map.h"
 
#include "newgrf_commons.h"
 
#include "airport.h"
 

	
 
/** Animation triggers for airport tiles */
 
enum AirpAnimationTrigger {
 
	AAT_BUILT,               ///< Triggered when the airport it build (for all tiles at the same time)
 
	AAT_TILELOOP,            ///< Triggered in the periodic tile loop
 
	AAT_STATION_NEW_CARGO,   ///< Triggered when new cargo arrives at the station (for all tiles at the same time)
 
	AAT_STATION_CARGO_TAKEN, ///< Triggered when a cargo type is completely removed from the station (for all tiles at the same time)
 
	AAT_STATION_250_ticks,   ///< Triggered every 250 ticks (for all tiles at the same time)
 
};
 

	
 
/**
 
 * Defines the data structure of each indivudual tile of an airport.
 
 */
 
struct AirportTileSpec {
 
	uint16 animation_info;                ///< Information about the animation (is it looping, how many loops etc)
 
	uint8 animation_speed;                ///< The speed of the animation
 

	
 
	StringID name;                        ///< Tile Subname string, land information on this tile will give you "AirportName (TileSubname)"
 
	uint8 callback_flags;                 ///< Flags telling which grf callback is set
 
	uint8 animation_triggers;             ///< When to start the animation
 
	uint8 animation_special_flags;        ///< Extra flags to influence the animation
 
	bool enabled;                         ///< entity still available (by default true). newgrf can disable it, though
 
	GRFFileProps grf_prop;                ///< properties related the the grf file
 

	
 
	static const AirportTileSpec *Get(StationGfx gfx);
 

	
 
	static void ResetAirportTiles();
 

	
 
private:
 
	static AirportTileSpec tiles[NUM_AIRPORTTILES];
 

	
 
	friend void AirportTileOverrideManager::SetEntitySpec(const AirportTileSpec *airpts);
 
};
 

	
 
StationGfx GetTranslatedAirportTileID(StationGfx gfx);
 
void AnimateAirportTile(TileIndex tile);
 
void AirportTileAnimationTrigger(Station *st, TileIndex tile, AirpAnimationTrigger trigger, CargoID cargo_type = CT_INVALID);
 
void AirportAnimationTrigger(Station *st, AirpAnimationTrigger trigger, CargoID cargo_type = CT_INVALID);
 
bool DrawNewAirportTile(TileInfo *ti, Station *st, StationGfx gfx, const AirportTileSpec *airts);
 

	
 
#endif /* NEWGRF_AIRPORTTILES_H */
src/openttd.cpp
Show inline comments
 
/* $Id$ */
 

	
 
/*
 
 * This file is part of OpenTTD.
 
 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
 
 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 
 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
 
 */
 

	
 
/** @file openttd.cpp Functions related to starting OpenTTD. */
 

	
 
#include "stdafx.h"
 

	
 
#define VARDEF
 
#include "variables.h"
 
#undef VARDEF
 

	
 

	
 
#include "blitter/factory.hpp"
 
#include "sound/sound_driver.hpp"
 
#include "music/music_driver.hpp"
 
#include "video/video_driver.hpp"
 

	
 
#include "fontcache.h"
 
#include "gui.h"
 
#include "sound_func.h"
 
#include "window_func.h"
 

	
 
#include "base_media_base.h"
 
#include "saveload/saveload.h"
 
#include "landscape.h"
 
#include "company_func.h"
 
#include "command_func.h"
 
#include "news_func.h"
 
#include "fios.h"
 
#include "aircraft.h"
 
#include "roadveh.h"
 
#include "train.h"
 
#include "console_func.h"
 
#include "screenshot.h"
 
#include "network/network.h"
 
#include "network/network_func.h"
 
#include "signs_base.h"
 
#include "ai/ai.hpp"
 
#include "ai/ai_config.hpp"
 
#include "settings_func.h"
 
#include "genworld.h"
 
#include "group.h"
 
#include "strings_func.h"
 
#include "date_func.h"
 
#include "vehicle_func.h"
 
#include "gamelog.h"
 
#include "cheat_type.h"
 
#include "animated_tile_func.h"
 
#include "roadstop_base.h"
 
#include "functions.h"
 
#include "elrail_func.h"
 
#include "rev.h"
 
#include "highscore.h"
 
#include "thread/thread.h"
 
#include "station_base.h"
 
#include "crashlog.h"
 
#include "company_base.h"
 
#include "engine_base.h"
 
#include "engine_func.h"
 
#include "core/random_func.hpp"
 

	
 
#include "newgrf_commons.h"
 

	
 
#include "town.h"
 
#include "industry.h"
 

	
 
#include <stdarg.h>
 

	
 
#include "table/strings.h"
 

	
 
StringID _switch_mode_errorstr;
 

	
 
void CallLandscapeTick();
 
void IncreaseDate();
 
void DoPaletteAnimations();
 
void MusicLoop();
 
void ResetMusic();
 
void ProcessAsyncSaveFinish();
 
void CallWindowTickEvent();
 

	
 
extern void SetDifficultyLevel(int mode, DifficultySettings *gm_opt);
 
extern Company *DoStartupNewCompany(bool is_ai, CompanyID company = INVALID_COMPANY);
 
extern void ShowOSErrorBox(const char *buf, bool system);
 
extern void InitializeRailGUI();
 

	
 
/**
 
 * Error handling for fatal user errors.
 
 * @param s the string to print.
 
 * @note Does NEVER return.
 
 */
 
void CDECL usererror(const char *s, ...)
 
{
 
	va_list va;
 
	char buf[512];
 

	
 
	va_start(va, s);
 
	vsnprintf(buf, lengthof(buf), s, va);
 
	va_end(va);
 

	
 
	ShowOSErrorBox(buf, false);
 
	if (_video_driver != NULL) _video_driver->Stop();
 

	
 
	exit(1);
 
}
 

	
 
/**
 
 * Error handling for fatal non-user errors.
 
 * @param s the string to print.
 
 * @note Does NEVER return.
 
 */
 
void CDECL error(const char *s, ...)
 
{
 
	va_list va;
 
	char buf[512];
 

	
 
	va_start(va, s);
 
	vsnprintf(buf, lengthof(buf), s, va);
 
	va_end(va);
 

	
 
	ShowOSErrorBox(buf, true);
 

	
 
	/* Set the error message for the crash log and then invoke it. */
 
	CrashLog::SetErrorMessage(buf);
 
	abort();
 
}
 

	
 
/**
 
 * Shows some information on the console/a popup box depending on the OS.
 
 * @param str the text to show.
 
 */
 
void CDECL ShowInfoF(const char *str, ...)
 
{
 
	va_list va;
 
	char buf[1024];
 
	va_start(va, str);
 
	vsnprintf(buf, lengthof(buf), str, va);
 
	va_end(va);
 
	ShowInfo(buf);
 
}
 

	
 
/**
 
 * Show the help message when someone passed a wrong parameter.
 
 */
 
static void ShowHelp()
 
{
 
	char buf[8192];
 
	char *p = buf;
 

	
 
	p += seprintf(p, lastof(buf), "OpenTTD %s\n", _openttd_revision);
 
	p = strecpy(p,
 
		"\n"
 
		"\n"
 
		"Command line options:\n"
 
		"  -v drv              = Set video driver (see below)\n"
 
		"  -s drv              = Set sound driver (see below) (param bufsize,hz)\n"
 
		"  -m drv              = Set music driver (see below)\n"
 
		"  -b drv              = Set the blitter to use (see below)\n"
 
		"  -r res              = Set resolution (for instance 800x600)\n"
 
		"  -h                  = Display this help text\n"
 
		"  -t year             = Set starting year\n"
 
		"  -d [[fac=]lvl[,...]]= Debug mode\n"
 
		"  -e                  = Start Editor\n"
 
		"  -g [savegame]       = Start new/save game immediately\n"
 
		"  -G seed             = Set random seed\n"
 
#if defined(ENABLE_NETWORK)
 
		"  -n [ip:port#company]= Start networkgame\n"
 
		"  -p password         = Password to join server\n"
 
		"  -P password         = Password to join company\n"
 
		"  -D [ip][:port]      = Start dedicated server\n"
 
		"  -l ip[:port]        = Redirect DEBUG()\n"
 
#if !defined(__MORPHOS__) && !defined(__AMIGA__) && !defined(WIN32)
 
		"  -f                  = Fork into the background (dedicated only)\n"
 
#endif
 
#endif /* ENABLE_NETWORK */
 
		"  -i palette          = Force to use the DOS (0) or Windows (1) palette\n"
 
		"                          (defines default setting when adding newgrfs)\n"
 
		"                        Default value (2) lets OpenTTD use the palette\n"
 
		"                          specified in graphics set file (see below)\n"
 
		"  -I graphics_set     = Force the graphics set (see below)\n"
 
		"  -S sounds_set       = Force the sounds set (see below)\n"
 
		"  -M music_set        = Force the music set (see below)\n"
 
		"  -c config_file      = Use 'config_file' instead of 'openttd.cfg'\n"
 
		"  -x                  = Do not automatically save to config file on exit\n"
 
		"\n",
 
		lastof(buf)
 
	);
 

	
 
	/* List the graphics packs */
 
	p = BaseGraphics::GetSetsList(p, lastof(buf));
 

	
 
	/* List the sounds packs */
 
	p = BaseSounds::GetSetsList(p, lastof(buf));
 

	
 
	/* List the music packs */
 
	p = BaseMusic::GetSetsList(p, lastof(buf));
 

	
 
	/* List the drivers */
 
	p = VideoDriverFactoryBase::GetDriversInfo(p, lastof(buf));
 

	
 
	/* List the blitters */
 
	p = BlitterFactoryBase::GetBlittersInfo(p, lastof(buf));
 

	
 
	/* We need to initialize the AI, so it finds the AIs */
 
	AI::Initialize();
 
	p = AI::GetConsoleList(p, lastof(buf));
 
	AI::Uninitialize(true);
 

	
 
	/* ShowInfo put output to stderr, but version information should go
 
	 * to stdout; this is the only exception */
 
#if !defined(WIN32) && !defined(WIN64)
 
	printf("%s\n", buf);
 
#else
 
	ShowInfo(buf);
 
#endif
 
}
 

	
 

	
 
struct MyGetOptData {
 
	char *opt;
 
	int numleft;
 
	char **argv;
 
	const char *options;
 
	char *cont;
 

	
 
	MyGetOptData(int argc, char **argv, const char *options)
 
	{
 
		opt = NULL;
 
		numleft = argc;
 
		this->argv = argv;
 
		this->options = options;
 
		cont = NULL;
 
	}
 
};
 

	
 
static int MyGetOpt(MyGetOptData *md)
 
{
 
	char *s = md->cont;
 
	if (s != NULL)
 
		goto md_continue_here;
 

	
 
	for (;;) {
 
		if (--md->numleft < 0) return -1;
 

	
 
		s = *md->argv++;
 
		if (*s == '-') {
 
md_continue_here:;
 
			s++;
 
			if (*s != 0) {
 
				const char *r;
 
				/* Found argument, try to locate it in options. */
 
				if (*s == ':' || (r = strchr(md->options, *s)) == NULL) {
 
					/* ERROR! */
 
					return -2;
 
				}
 
				if (r[1] == ':') {
 
					char *t;
 
					/* Item wants an argument. Check if the argument follows, or if it comes as a separate arg. */
 
					if (!*(t = s + 1)) {
 
						/* It comes as a separate arg. Check if out of args? */
 
						if (--md->numleft < 0 || *(t = *md->argv) == '-') {
 
							/* Check if item is optional? */
 
							if (r[2] != ':')
 
								return -2;
 
							md->numleft++;
 
							t = NULL;
 
						} else {
 
							md->argv++;
 
						}
 
					}
 
					md->opt = t;
 
					md->cont = NULL;
 
					return *s;
 
				}
 
				md->opt = NULL;
 
				md->cont = s;
 
				return *s;
 
			}
 
		} else {
 
			/* This is currently not supported. */
 
			return -2;
 
		}
 
	}
 
}
 

	
 
/**
 
 * Extract the resolution from the given string and store
 
 * it in the 'res' parameter.
 
 * @param res variable to store the resolution in.
 
 * @param s   the string to decompose.
 
 */
 
static void ParseResolution(Dimension *res, const char *s)
 
{
 
	const char *t = strchr(s, 'x');
 
	if (t == NULL) {
 
		ShowInfoF("Invalid resolution '%s'", s);
 
		return;
 
	}
 

	
 
	res->width  = max(strtoul(s, NULL, 0), 64UL);
 
	res->height = max(strtoul(t + 1, NULL, 0), 64UL);
 
}
 

	
 
static void InitializeDynamicVariables()
 
{
 
	/* Dynamic stuff needs to be initialized somewhere... */
 
	_engine_mngr.ResetToDefaultMapping();
 
	_house_mngr.ResetMapping();
 
	_industry_mngr.ResetMapping();
 
	_industile_mngr.ResetMapping();
 
	_airporttile_mngr.ResetMapping();
 
}
 

	
 

	
 
/** Unitializes drivers, frees allocated memory, cleans pools, ...
 
 * Generally, prepares the game for shutting down
 
 */
 
static void ShutdownGame()
 
{
 
	IConsoleFree();
 

	
 
	if (_network_available) NetworkShutDown(); // Shut down the network and close any open connections
 

	
 
	DriverFactoryBase::ShutdownDrivers();
 

	
 
	UnInitWindowSystem();
 

	
 
	/* stop the AI */
 
	AI::Uninitialize(false);
 

	
 
	/* Uninitialize airport state machines */
 
	UnInitializeAirports();
 

	
 
	/* Uninitialize variables that are allocated dynamically */
 
	GamelogReset();
 
	_town_pool.CleanPool();
 
	_industry_pool.CleanPool();
 
	_station_pool.CleanPool();
 
	_roadstop_pool.CleanPool();
 
	_vehicle_pool.CleanPool();
 
	_sign_pool.CleanPool();
 
	_order_pool.CleanPool();
 
	_group_pool.CleanPool();
 
	_cargopacket_pool.CleanPool();
 
	_engine_pool.CleanPool();
 
	_company_pool.CleanPool();
 

	
 
	free(_config_file);
 

	
 
	/* Close all and any open filehandles */
 
	FioCloseAll();
 
}
 

	
 
static void LoadIntroGame()
 
{
 
	_game_mode = GM_MENU;
 

	
 
	ResetGRFConfig(false);
 

	
 
	/* Setup main window */
 
	ResetWindowSystem();
 
	SetupColoursAndInitialWindow();
 

	
 
	/* Load the default opening screen savegame */
 
	if (SaveOrLoad("opntitle.dat", SL_LOAD, DATA_DIR) != SL_OK) {
 
		GenerateWorld(GWM_EMPTY, 64, 64); // if failed loading, make empty world.
 
		WaitTillGeneratedWorld();
 
		SetLocalCompany(COMPANY_SPECTATOR);
 
	} else {
 
		SetLocalCompany(COMPANY_FIRST);
 
	}
 

	
 
	_pause_mode = PM_UNPAUSED;
 
	_cursor.fix_at = false;
 

	
 
	CheckForMissingGlyphsInLoadedLanguagePack();
 

	
 
	/* Play main theme */
 
	if (_music_driver->IsSongPlaying()) ResetMusic();
 
}
 

	
 
void MakeNewgameSettingsLive()
 
{
 
#ifdef ENABLE_AI
 
	for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
 
		if (_settings_game.ai_config[c] != NULL) {
 
			delete _settings_game.ai_config[c];
 
		}
 
	}
 
#endif /* ENABLE_AI */
 

	
 
	_settings_game = _settings_newgame;
 

	
 
#ifdef ENABLE_AI
 
	for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
 
		_settings_game.ai_config[c] = NULL;
 
		if (_settings_newgame.ai_config[c] != NULL) {
 
			_settings_game.ai_config[c] = new AIConfig(_settings_newgame.ai_config[c]);
 
		}
 
	}
 
#endif /* ENABLE_AI */
 
}
 

	
 
byte _savegame_sort_order;
 
#if defined(UNIX) && !defined(__MORPHOS__)
 
extern void DedicatedFork();
 
#endif
 

	
 
int ttd_main(int argc, char *argv[])
 
{
 
	int i;
 
	const char *optformat;
 
	char *musicdriver = NULL;
 
	char *sounddriver = NULL;
 
	char *videodriver = NULL;
 
	char *blitter = NULL;
 
	char *graphics_set = NULL;
 
	char *sounds_set = NULL;
 
	char *music_set = NULL;
 
	Dimension resolution = {0, 0};
 
	Year startyear = INVALID_YEAR;
 
	uint generation_seed = GENERATE_NEW_SEED;
 
	bool save_config = true;
 
#if defined(ENABLE_NETWORK)
 
	bool dedicated = false;
 
	bool network   = false;
 
	char *network_conn = NULL;
 
	char *debuglog_conn = NULL;
 
	char *dedicated_host = NULL;
 
	uint16 dedicated_port = 0;
 
	char *join_server_password = NULL;
 
	char *join_company_password = NULL;
 
#endif /* ENABLE_NETWORK */
 

	
 
	_game_mode = GM_MENU;
 
	_switch_mode = SM_MENU;
 
	_switch_mode_errorstr = INVALID_STRING_ID;
 
	_dedicated_forks = false;
 
	_config_file = NULL;
 

	
 
	/* The last param of the following function means this:
 
	 *   a letter means: it accepts that param (e.g.: -h)
 
	 *   a ':' behind it means: it need a param (e.g.: -m<driver>)
 
	 *   a '::' behind it means: it can optional have a param (e.g.: -d<debug>) */
 
	optformat = "m:s:v:b:hD::n::ei::I:S:M:t:d::r:g::G:c:xl:p:P:"
 
#if !defined(__MORPHOS__) && !defined(__AMIGA__) && !defined(WIN32)
 
		"f"
 
#endif
 
	;
 

	
 
	MyGetOptData mgo(argc - 1, argv + 1, optformat);
 

	
 
	while ((i = MyGetOpt(&mgo)) != -1) {
 
		switch (i) {
 
		case 'I': free(graphics_set); graphics_set = strdup(mgo.opt); break;
 
		case 'S': free(sounds_set); sounds_set = strdup(mgo.opt); break;
 
		case 'M': free(music_set); music_set = strdup(mgo.opt); break;
 
		case 'm': free(musicdriver); musicdriver = strdup(mgo.opt); break;
 
		case 's': free(sounddriver); sounddriver = strdup(mgo.opt); break;
 
		case 'v': free(videodriver); videodriver = strdup(mgo.opt); break;
 
		case 'b': free(blitter); blitter = strdup(mgo.opt); break;
 
#if defined(ENABLE_NETWORK)
 
		case 'D':
 
			free(musicdriver);
 
			free(sounddriver);
 
			free(videodriver);
 
			free(blitter);
 
			musicdriver = strdup("null");
 
			sounddriver = strdup("null");
 
			videodriver = strdup("dedicated");
 
			blitter = strdup("null");
 
			dedicated = true;
 
			SetDebugString("net=6");
 
			if (mgo.opt != NULL) {
 
				/* Use the existing method for parsing (openttd -n).
 
				 * However, we do ignore the #company part. */
 
				const char *temp = NULL;
 
				const char *port = NULL;
 
				ParseConnectionString(&temp, &port, mgo.opt);
 
				if (!StrEmpty(mgo.opt)) dedicated_host = mgo.opt;
 
				if (port != NULL) dedicated_port = atoi(port);
 
			}
 
			break;
 
		case 'f': _dedicated_forks = true; break;
 
		case 'n':
 
			network = true;
 
			network_conn = mgo.opt; // optional IP parameter, NULL if unset
 
			break;
 
		case 'l':
 
			debuglog_conn = mgo.opt;
 
			break;
 
		case 'p':
 
			join_server_password = mgo.opt;
 
			break;
 
		case 'P':
 
			join_company_password = mgo.opt;
 
			break;
 
#endif /* ENABLE_NETWORK */
 
		case 'r': ParseResolution(&resolution, mgo.opt); break;
 
		case 't': startyear = atoi(mgo.opt); break;
 
		case 'd': {
 
#if defined(WIN32)
 
				CreateConsole();
 
#endif
 
				if (mgo.opt != NULL) SetDebugString(mgo.opt);
 
			} break;
 
		case 'e': _switch_mode = SM_EDITOR; break;
 
		case 'i':
 
			/* there is an argument, it is not empty, and it is exactly 1 char long */
 
			if (!StrEmpty(mgo.opt) && mgo.opt[1] == '\0') {
 
				_use_palette = (PaletteType)(mgo.opt[0] - '0');
 
				if (_use_palette <= MAX_PAL) break;
 
			}
 
			usererror("Valid value for '-i' is 0, 1 or 2");
 
		case 'g':
 
			if (mgo.opt != NULL) {
 
				strecpy(_file_to_saveload.name, mgo.opt, lastof(_file_to_saveload.name));
 
				_switch_mode = SM_LOAD;
 
				_file_to_saveload.mode = SL_LOAD;
 

	
 
				/* if the file doesn't exist or it is not a valid savegame, let the saveload code show an error */
 
				const char *t = strrchr(_file_to_saveload.name, '.');
 
				if (t != NULL) {
 
					FiosType ft = FiosGetSavegameListCallback(SLD_LOAD_GAME, _file_to_saveload.name, t, NULL, NULL);
 
					if (ft != FIOS_TYPE_INVALID) SetFiosType(ft);
 
				}
 

	
 
				break;
 
			}
 

	
 
			_switch_mode = SM_NEWGAME;
 
			/* Give a random map if no seed has been given */
 
			if (generation_seed == GENERATE_NEW_SEED) {
 
				generation_seed = InteractiveRandom();
 
			}
 
			break;
 
		case 'G': generation_seed = atoi(mgo.opt); break;
 
		case 'c': _config_file = strdup(mgo.opt); break;
 
		case 'x': save_config = false; break;
 
		case -2:
 
		case 'h':
 
			/* The next two functions are needed to list the graphics sets.
 
			 * We can't do them earlier because then we can't show it on
 
			 * the debug console as that hasn't been configured yet. */
 
			DeterminePaths(argv[0]);
 
			BaseGraphics::FindSets();
 
			BaseSounds::FindSets();
 
			BaseMusic::FindSets();
 
			ShowHelp();
 
			return 0;
 
		}
 
	}
 

	
 
#if defined(WINCE) && defined(_DEBUG)
 
	/* Switch on debug lvl 4 for WinCE if Debug release, as you can't give params, and you most likely do want this information */
 
	SetDebugString("4");
 
#endif
 

	
 
	DeterminePaths(argv[0]);
 
	BaseGraphics::FindSets();
 
	BaseSounds::FindSets();
 
	BaseMusic::FindSets();
 

	
 
#if defined(UNIX) && !defined(__MORPHOS__)
 
	/* We must fork here, or we'll end up without some resources we need (like sockets) */
 
	if (_dedicated_forks)
 
		DedicatedFork();
 
#endif
 

	
 
	AI::Initialize();
 
	LoadFromConfig();
 
	AI::Uninitialize(true);
 
	CheckConfig();
 
	LoadFromHighScore();
 

	
 
	if (resolution.width != 0) { _cur_resolution = resolution; }
 
	if (startyear != INVALID_YEAR) _settings_newgame.game_creation.starting_year = startyear;
 
	if (generation_seed != GENERATE_NEW_SEED) _settings_newgame.game_creation.generation_seed = generation_seed;
 

	
 
	/*
 
	 * The width and height must be at least 1 pixel and width times
 
	 * height must still fit within a 32 bits integer, this way all
 
	 * internal drawing routines work correctly.
 
	 */
 
	_cur_resolution.width  = ClampU(_cur_resolution.width,  1, UINT16_MAX);
 
	_cur_resolution.height = ClampU(_cur_resolution.height, 1, UINT16_MAX);
 

	
 
#if defined(ENABLE_NETWORK)
 
	if (dedicated_host) {
 
		_network_bind_list.Clear();
 
		*_network_bind_list.Append() = strdup(dedicated_host);
 
	}
 
	if (dedicated_port) _settings_client.network.server_port = dedicated_port;
 
	if (_dedicated_forks && !dedicated) _dedicated_forks = false;
 
#endif /* ENABLE_NETWORK */
 

	
 
	/* enumerate language files */
 
	InitializeLanguagePacks();
 

	
 
	/* initialize screenshot formats */
 
	InitializeScreenshotFormats();
 

	
 
	/* initialize airport state machines */
 
	InitializeAirports();
 

	
 
	/* initialize all variables that are allocated dynamically */
 
	InitializeDynamicVariables();
 

	
 
	/* Initialize FreeType */
 
	InitFreeType();
 

	
 
	/* This must be done early, since functions use the SetWindowDirty* calls */
 
	InitWindowSystem();
 

	
 
	/* Look for the sounds before the graphics. Otherwise none would be set and
 
	 * the first initialisation of the video happens on the wrong data. Now it
 
	 * can do the first initialisation right. */
 
	if (sounds_set == NULL && BaseSounds::ini_set != NULL) sounds_set = strdup(BaseSounds::ini_set);
 
	if (!BaseSounds::SetSet(sounds_set)) {
 
		StrEmpty(sounds_set) ?
 
			usererror("Failed to find a sounds set. Please acquire a sounds set for OpenTTD. See section 4.1 of readme.txt.") :
 
			usererror("Failed to select requested sounds set '%s'", sounds_set);
 
	}
 
	free(sounds_set);
 

	
 
	if (graphics_set == NULL && BaseGraphics::ini_set != NULL) graphics_set = strdup(BaseGraphics::ini_set);
 
	if (!BaseGraphics::SetSet(graphics_set)) {
 
		StrEmpty(graphics_set) ?
 
			usererror("Failed to find a graphics set. Please acquire a graphics set for OpenTTD. See section 4.1 of readme.txt.") :
 
			usererror("Failed to select requested graphics set '%s'", graphics_set);
 
	}
 
	free(graphics_set);
 

	
 
	if (music_set == NULL && BaseMusic::ini_set != NULL) music_set = strdup(BaseMusic::ini_set);
 
	if (!BaseMusic::SetSet(music_set)) {
 
		StrEmpty(music_set) ?
 
			usererror("Failed to find a music set. Please acquire a music set for OpenTTD. See section 4.1 of readme.txt.") :
 
			usererror("Failed to select requested music set '%s'", music_set);
 
	}
 
	free(music_set);
 

	
 
	/* Initialize game palette */
 
	GfxInitPalettes();
 

	
 
	DEBUG(misc, 1, "Loading blitter...");
 
	if (blitter == NULL && _ini_blitter != NULL) blitter = strdup(_ini_blitter);
 
	if (BlitterFactoryBase::SelectBlitter(blitter) == NULL)
 
		StrEmpty(blitter) ?
 
			usererror("Failed to autoprobe blitter") :
 
			usererror("Failed to select requested blitter '%s'; does it exist?", blitter);
 
	free(blitter);
 

	
 
	DEBUG(driver, 1, "Loading drivers...");
 

	
 
	if (sounddriver == NULL && _ini_sounddriver != NULL) sounddriver = strdup(_ini_sounddriver);
 
	_sound_driver = (SoundDriver*)SoundDriverFactoryBase::SelectDriver(sounddriver, Driver::DT_SOUND);
 
	if (_sound_driver == NULL) {
 
		StrEmpty(sounddriver) ?
 
			usererror("Failed to autoprobe sound driver") :
 
			usererror("Failed to select requested sound driver '%s'", sounddriver);
 
	}
 
	free(sounddriver);
 

	
 
	if (videodriver == NULL && _ini_videodriver != NULL) videodriver = strdup(_ini_videodriver);
 
	_video_driver = (VideoDriver*)VideoDriverFactoryBase::SelectDriver(videodriver, Driver::DT_VIDEO);
 
	if (_video_driver == NULL) {
 
		StrEmpty(videodriver) ?
 
			usererror("Failed to autoprobe video driver") :
 
			usererror("Failed to select requested video driver '%s'", videodriver);
 
	}
 
	free(videodriver);
 

	
 
	if (musicdriver == NULL && _ini_musicdriver != NULL) musicdriver = strdup(_ini_musicdriver);
 
	_music_driver = (MusicDriver*)MusicDriverFactoryBase::SelectDriver(musicdriver, Driver::DT_MUSIC);
 
	if (_music_driver == NULL) {
 
		StrEmpty(musicdriver) ?
 
			usererror("Failed to autoprobe music driver") :
 
			usererror("Failed to select requested music driver '%s'", musicdriver);
 
	}
 
	free(musicdriver);
 

	
 
	_savegame_sort_order = SORT_BY_DATE | SORT_DESCENDING;
 
	/* Initialize the zoom level of the screen to normal */
 
	_screen.zoom = ZOOM_LVL_NORMAL;
 

	
 
	/* restore saved music volume */
 
	_music_driver->SetVolume(msf.music_vol);
 

	
 
	NetworkStartUp(); // initialize network-core
 

	
 
#if defined(ENABLE_NETWORK)
 
	if (debuglog_conn != NULL && _network_available) {
 
		const char *not_used = NULL;
 
		const char *port = NULL;
 
		uint16 rport;
 

	
 
		rport = NETWORK_DEFAULT_DEBUGLOG_PORT;
 

	
 
		ParseConnectionString(&not_used, &port, debuglog_conn);
 
		if (port != NULL) rport = atoi(port);
 

	
 
		NetworkStartDebugLog(NetworkAddress(debuglog_conn, rport));
 
	}
 
#endif /* ENABLE_NETWORK */
 

	
 
	ScanNewGRFFiles();
 

	
 
	ResetGRFConfig(false);
 

	
 
	/* Make sure _settings is filled with _settings_newgame if we switch to a game directly */
 
	if (_switch_mode != SM_NONE) MakeNewgameSettingsLive();
 

	
 
	/* initialize the ingame console */
 
	IConsoleInit();
 
	_cursor.in_window = true;
 
	InitializeGUI();
 
	IConsoleCmdExec("exec scripts/autoexec.scr 0");
 

	
 
	/* Take our initial lock on whatever we might want to do! */
 
	_genworld_paint_mutex->BeginCritical();
 
	_genworld_mapgen_mutex->BeginCritical();
 

	
 
	GenerateWorld(GWM_EMPTY, 64, 64); // Make the viewport initialization happy
 
	WaitTillGeneratedWorld();
 

	
 
	CheckForMissingGlyphsInLoadedLanguagePack();
 

	
 
#ifdef ENABLE_NETWORK
 
	if (network && _network_available) {
 
		if (network_conn != NULL) {
 
			const char *port = NULL;
 
			const char *company = NULL;
 
			uint16 rport = NETWORK_DEFAULT_PORT;
 
			CompanyID join_as = COMPANY_NEW_COMPANY;
 

	
 
			ParseConnectionString(&company, &port, network_conn);
 

	
 
			if (company != NULL) {
 
				join_as = (CompanyID)atoi(company);
 

	
 
				if (join_as != COMPANY_SPECTATOR) {
 
					join_as--;
 
					if (join_as >= MAX_COMPANIES) return false;
 
				}
 
			}
 
			if (port != NULL) rport = atoi(port);
 

	
 
			LoadIntroGame();
 
			_switch_mode = SM_NONE;
 
			NetworkClientConnectGame(NetworkAddress(network_conn, rport), join_as, join_server_password, join_company_password);
 
		}
 
	}
 
#endif /* ENABLE_NETWORK */
 

	
 
	_video_driver->MainLoop();
 

	
 
	WaitTillSaved();
 

	
 
	/* only save config if we have to */
 
	if (save_config) {
 
		SaveToConfig();
 
		SaveToHighScore();
 
	}
 

	
 
	/* Reset windowing system, stop drivers, free used memory, ... */
 
	ShutdownGame();
 

	
 
	free(const_cast<char *>(BaseGraphics::ini_set));
 
	free(const_cast<char *>(BaseSounds::ini_set));
 
	free(const_cast<char *>(BaseMusic::ini_set));
 
	free(_ini_musicdriver);
 
	free(_ini_sounddriver);
 
	free(_ini_videodriver);
 
	free(_ini_blitter);
 

	
 
	return 0;
 
}
 

	
 
void HandleExitGameRequest()
 
{
 
	if (_game_mode == GM_MENU) { // do not ask to quit on the main screen
 
		_exit_game = true;
 
	} else if (_settings_client.gui.autosave_on_exit) {
 
		DoExitSave();
 
		_exit_game = true;
 
	} else {
 
		AskExitGame();
 
	}
 
}
 

	
 
static void MakeNewGameDone()
 
{
 
	SettingsDisableElrail(_settings_game.vehicle.disable_elrails);
 

	
 
	/* In a dedicated server, the server does not play */
 
	if (BlitterFactoryBase::GetCurrentBlitter()->GetScreenDepth() == 0) {
 
		SetLocalCompany(COMPANY_SPECTATOR);
 
		IConsoleCmdExec("exec scripts/game_start.scr 0");
 
		return;
 
	}
 

	
 
	/* Create a single company */
 
	DoStartupNewCompany(false);
 

	
 
	Company *c = Company::Get(COMPANY_FIRST);
 
	c->settings = _settings_client.company;
 

	
 
	IConsoleCmdExec("exec scripts/game_start.scr 0");
 

	
 
	SetLocalCompany(COMPANY_FIRST);
 
	_current_company = _local_company;
 

	
 
	InitializeRailGUI();
 

	
 
#ifdef ENABLE_NETWORK
 
	/* We are the server, we start a new company (not dedicated),
 
	 * so set the default password *if* needed. */
 
	if (_network_server && !StrEmpty(_settings_client.network.default_company_pass)) {
 
		NetworkChangeCompanyPassword(_settings_client.network.default_company_pass);
 
	}
 
#endif /* ENABLE_NETWORK */
 

	
 
	MarkWholeScreenDirty();
 
}
 

	
 
static void MakeNewGame(bool from_heightmap, bool reset_settings)
 
{
 
	_game_mode = GM_NORMAL;
 

	
 
	ResetGRFConfig(true);
 
	InitializeDynamicVariables();
 

	
 
	GenerateWorldSetCallback(&MakeNewGameDone);
 
	GenerateWorld(from_heightmap ? GWM_HEIGHTMAP : GWM_NEWGAME, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y, reset_settings);
 
}
 

	
 
static void MakeNewEditorWorldDone()
 
{
 
	SetLocalCompany(OWNER_NONE);
 
}
 

	
 
static void MakeNewEditorWorld()
 
{
 
	_game_mode = GM_EDITOR;
 

	
 
	ResetGRFConfig(true);
 

	
 
	GenerateWorldSetCallback(&MakeNewEditorWorldDone);
 
	GenerateWorld(GWM_EMPTY, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
 
}
 

	
 
void StartupCompanies();
 
void StartupDisasters();
 
extern void StartupEconomy();
 

	
 
/**
 
 * Start Scenario starts a new game based on a scenario.
 
 * Eg 'New Game' --> select a preset scenario
 
 * This starts a scenario based on your current difficulty settings
 
 */
 
static void StartScenario()
 
{
 
	_game_mode = GM_NORMAL;
 

	
 
	/* invalid type */
 
	if (_file_to_saveload.mode == SL_INVALID) {
 
		DEBUG(sl, 0, "Savegame is obsolete or invalid format: '%s'", _file_to_saveload.name);
 
		SetDParamStr(0, GetSaveLoadErrorString());
 
		ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
 
		_game_mode = GM_MENU;
 
		return;
 
	}
 

	
 
	/* Reinitialize windows */
 
	ResetWindowSystem();
 

	
 
	SetupColoursAndInitialWindow();
 

	
 
	ResetGRFConfig(true);
 

	
 
	/* Load game */
 
	if (SaveOrLoad(_file_to_saveload.name, _file_to_saveload.mode, SCENARIO_DIR) != SL_OK) {
 
		LoadIntroGame();
 
		SetDParamStr(0, GetSaveLoadErrorString());
 
		ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
 
	}
 

	
 
	_settings_game.difficulty = _settings_newgame.difficulty;
 

	
 
	/* Inititalize data */
 
	StartupEconomy();
 
	StartupCompanies();
 
	StartupEngines();
 
	StartupDisasters();
 

	
 
	SetLocalCompany(COMPANY_FIRST);
 
	_current_company = _local_company;
 
	Company *c = Company::Get(COMPANY_FIRST);
 
	c->settings = _settings_client.company;
 

	
 
	MarkWholeScreenDirty();
 
}
 

	
 
/** Load the specified savegame but on error do different things.
 
 * If loading fails due to corrupt savegame, bad version, etc. go back to
 
 * a previous correct state. In the menu for example load the intro game again.
 
 * @param filename file to be loaded
 
 * @param mode mode of loading, either SL_LOAD or SL_OLD_LOAD
 
 * @param newgm switch to this mode of loading fails due to some unknown error
 
 * @param subdir default directory to look for filename, set to 0 if not needed
 
 */
 
bool SafeSaveOrLoad(const char *filename, int mode, GameMode newgm, Subdirectory subdir)
 
{
 
	GameMode ogm = _game_mode;
 

	
 
	_game_mode = newgm;
 
	assert(mode == SL_LOAD || mode == SL_OLD_LOAD);
 
	switch (SaveOrLoad(filename, mode, subdir)) {
 
		case SL_OK: return true;
 

	
 
		case SL_REINIT:
 
			switch (ogm) {
 
				default:
 
				case GM_MENU:   LoadIntroGame();      break;
 
				case GM_EDITOR: MakeNewEditorWorld(); break;
 
			}
 
			return false;
 

	
 
		default:
 
			_game_mode = ogm;
 
			return false;
 
	}
 
}
 

	
 
void SwitchToMode(SwitchMode new_mode)
 
{
 
#ifdef ENABLE_NETWORK
 
	/* If we are saving something, the network stays in his current state */
 
	if (new_mode != SM_SAVE) {
 
		/* If the network is active, make it not-active */
 
		if (_networking) {
 
			if (_network_server && (new_mode == SM_LOAD || new_mode == SM_NEWGAME || new_mode == SM_RESTARTGAME)) {
 
				NetworkReboot();
 
			} else {
 
				NetworkDisconnect();
 
			}
 
		}
 

	
 
		/* If we are a server, we restart the server */
 
		if (_is_network_server) {
 
			/* But not if we are going to the menu */
 
			if (new_mode != SM_MENU) {
 
				/* check if we should reload the config */
 
				if (_settings_client.network.reload_cfg) {
 
					LoadFromConfig();
 
					MakeNewgameSettingsLive();
 
					ResetGRFConfig(false);
 
				}
 
				NetworkServerStart();
 
			} else {
 
				/* This client no longer wants to be a network-server */
 
				_is_network_server = false;
 
			}
 
		}
 
	}
 
#endif /* ENABLE_NETWORK */
 
	/* Make sure all AI controllers are gone at quiting game */
 
	if (new_mode != SM_SAVE) AI::KillAll();
 

	
 
	switch (new_mode) {
 
		case SM_EDITOR: // Switch to scenario editor
 
			MakeNewEditorWorld();
 
			break;
 

	
 
		case SM_RESTARTGAME: // Restart --> 'Random game' with current settings
 
		case SM_NEWGAME: // New Game --> 'Random game'
 
#ifdef ENABLE_NETWORK
 
			if (_network_server) {
 
				snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "Random Map");
 
			}
 
#endif /* ENABLE_NETWORK */
 
			MakeNewGame(false, new_mode == SM_NEWGAME);
 
			break;
 

	
 
		case SM_START_SCENARIO: // New Game --> Choose one of the preset scenarios
 
#ifdef ENABLE_NETWORK
 
			if (_network_server) {
 
				snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "%s (Loaded scenario)", _file_to_saveload.title);
 
			}
 
#endif /* ENABLE_NETWORK */
 
			StartScenario();
 
			break;
 

	
 
		case SM_LOAD: { // Load game, Play Scenario
 
			ResetGRFConfig(true);
 
			ResetWindowSystem();
 

	
 
			if (!SafeSaveOrLoad(_file_to_saveload.name, _file_to_saveload.mode, GM_NORMAL, NO_DIRECTORY)) {
 
				LoadIntroGame();
 
				SetDParamStr(0, GetSaveLoadErrorString());
 
				ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
 
			} else {
 
				if (_saveload_mode == SLD_LOAD_SCENARIO) {
 
					StartupEngines();
 
				}
 
				/* Update the local company for a loaded game. It is either always
 
				 * company #1 (eg 0) or in the case of a dedicated server a spectator */
 
				SetLocalCompany(_network_dedicated ? COMPANY_SPECTATOR : COMPANY_FIRST);
 
				/* Execute the game-start script */
 
				IConsoleCmdExec("exec scripts/game_start.scr 0");
 
				/* Decrease pause counter (was increased from opening load dialog) */
 
				DoCommandP(0, PM_PAUSED_SAVELOAD, 0, CMD_PAUSE);
 
#ifdef ENABLE_NETWORK
 
				if (_network_server) {
 
					snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "%s (Loaded game)", _file_to_saveload.title);
 
				}
 
#endif /* ENABLE_NETWORK */
 
			}
 
			break;
 
		}
 

	
 
		case SM_START_HEIGHTMAP: // Load a heightmap and start a new game from it
 
#ifdef ENABLE_NETWORK
 
			if (_network_server) {
 
				snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "%s (Heightmap)", _file_to_saveload.title);
 
			}
 
#endif /* ENABLE_NETWORK */
 
			MakeNewGame(true, true);
 
			break;
 

	
 
		case SM_LOAD_HEIGHTMAP: // Load heightmap from scenario editor
 
			SetLocalCompany(OWNER_NONE);
 

	
 
			GenerateWorld(GWM_HEIGHTMAP, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
 
			MarkWholeScreenDirty();
 
			break;
 

	
 
		case SM_LOAD_SCENARIO: { // Load scenario from scenario editor
 
			if (SafeSaveOrLoad(_file_to_saveload.name, _file_to_saveload.mode, GM_EDITOR, NO_DIRECTORY)) {
 
				SetLocalCompany(OWNER_NONE);
 
				_settings_newgame.game_creation.starting_year = _cur_year;
 
				/* Cancel the saveload pausing */
 
				DoCommandP(0, PM_PAUSED_SAVELOAD, 0, CMD_PAUSE);
 
			} else {
 
				SetDParamStr(0, GetSaveLoadErrorString());
 
				ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
 
			}
 
			break;
 
		}
 

	
 
		case SM_MENU: // Switch to game intro menu
 
			LoadIntroGame();
 
			if (BaseSounds::ini_set == NULL && BaseSounds::GetUsedSet()->fallback) {
 
				ShowErrorMessage(STR_WARNING_FALLBACK_SOUNDSET, INVALID_STRING_ID, WL_CRITICAL);
 
				BaseSounds::ini_set = strdup(BaseSounds::GetUsedSet()->name);
 
			}
 
			break;
 

	
 
		case SM_SAVE: // Save game
 
			/* Make network saved games on pause compatible to singleplayer */
 
			if (SaveOrLoad(_file_to_saveload.name, SL_SAVE, NO_DIRECTORY) != SL_OK) {
 
				SetDParamStr(0, GetSaveLoadErrorString());
 
				ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
 
			} else {
 
				DeleteWindowById(WC_SAVELOAD, 0);
 
			}
 
			break;
 

	
 
		case SM_GENRANDLAND: // Generate random land within scenario editor
 
			SetLocalCompany(OWNER_NONE);
 
			GenerateWorld(GWM_RANDOM, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
 
			/* XXX: set date */
 
			MarkWholeScreenDirty();
 
			break;
 

	
 
		default: NOT_REACHED();
 
	}
 

	
 
	if (_switch_mode_errorstr != INVALID_STRING_ID) {
src/station_cmd.cpp
Show inline comments
 
@@ -1464,1577 +1464,1574 @@ CommandCost RemoveFromRailBaseStation(Ti
 
 */
 
CommandCost CmdRemoveFromRailStation(TileIndex start, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
 
{
 
	TileIndex end = p1 == 0 ? start : p1;
 
	if (start >= MapSize() || end >= MapSize()) return CMD_ERROR;
 

	
 
	TileArea ta(start, end);
 
	SmallVector<Station *, 4> affected_stations;
 

	
 
	CommandCost ret = RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_STATION_RAIL], HasBit(p2, 0));
 
	if (ret.Failed()) return ret;
 

	
 
	/* Do all station specific functions here. */
 
	for (Station **stp = affected_stations.Begin(); stp != affected_stations.End(); stp++) {
 
		Station *st = *stp;
 

	
 
		if (st->train_station.tile == INVALID_TILE) SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_TRAINS);
 
		st->MarkTilesDirty(false);
 
		st->RecomputeIndustriesNear();
 
	}
 

	
 
	/* Now apply the rail cost to the number that we deleted */
 
	return ret;
 
}
 

	
 
/** Remove a single tile from a waypoint.
 
 * This allows for custom-built waypoint with holes and weird layouts
 
 * @param start tile of waypoint piece to remove
 
 * @param flags operation to perform
 
 * @param p1 start_tile
 
 * @param p2 various bitstuffed elements
 
 * - p2 = bit 0 - if set keep the rail
 
 * @param text unused
 
 * @return the cost of this operation or an error
 
 */
 
CommandCost CmdRemoveFromRailWaypoint(TileIndex start, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
 
{
 
	TileIndex end = p1 == 0 ? start : p1;
 
	if (start >= MapSize() || end >= MapSize()) return CMD_ERROR;
 

	
 
	TileArea ta(start, end);
 
	SmallVector<Waypoint *, 4> affected_stations;
 

	
 
	return RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_WAYPOINT_RAIL], HasBit(p2, 0));
 
}
 

	
 

	
 
/**
 
 * Remove a rail road station/waypoint
 
 * @param st The station/waypoint to remove the rail part from
 
 * @param flags operation to perform
 
 * @tparam T the type of station to remove
 
 * @return cost or failure of operation
 
 */
 
template <class T>
 
CommandCost RemoveRailStation(T *st, DoCommandFlag flags)
 
{
 
	/* Current company owns the station? */
 
	if (_current_company != OWNER_WATER && !CheckOwnership(st->owner)) return CMD_ERROR;
 

	
 
	/* determine width and height of platforms */
 
	TileArea ta = st->train_station;
 

	
 
	assert(ta.w != 0 && ta.h != 0);
 

	
 
	CommandCost cost(EXPENSES_CONSTRUCTION);
 
	/* clear all areas of the station */
 
	TILE_AREA_LOOP(tile, ta) {
 
		/* for nonuniform stations, only remove tiles that are actually train station tiles */
 
		if (!st->TileBelongsToRailStation(tile)) continue;
 

	
 
		CommandCost ret = EnsureNoVehicleOnGround(tile);
 
		ret.SetGlobalErrorMessage();
 
		if (ret.Failed()) return ret;
 

	
 
		cost.AddCost(_price[PR_CLEAR_STATION_RAIL]);
 
		if (flags & DC_EXEC) {
 
			/* read variables before the station tile is removed */
 
			Track track = GetRailStationTrack(tile);
 
			Owner owner = GetTileOwner(tile); // _current_company can be OWNER_WATER
 
			Train *v = NULL;
 
			if (HasStationReservation(tile)) {
 
				v = GetTrainForReservation(tile, track);
 
				if (v != NULL) FreeTrainTrackReservation(v);
 
			}
 
			DoClearSquare(tile);
 
			AddTrackToSignalBuffer(tile, track, owner);
 
			YapfNotifyTrackLayoutChange(tile, track);
 
			if (v != NULL) TryPathReserve(v, true);
 
		}
 
	}
 

	
 
	if (flags & DC_EXEC) {
 
		st->rect.AfterRemoveRect(st, st->train_station.tile, st->train_station.w, st->train_station.h);
 

	
 
		st->train_station.Clear();
 

	
 
		st->facilities &= ~FACIL_TRAIN;
 

	
 
		free(st->speclist);
 
		st->num_specs = 0;
 
		st->speclist  = NULL;
 
		st->cached_anim_triggers = 0;
 

	
 
		SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_TRAINS);
 
		st->UpdateVirtCoord();
 
		DeleteStationIfEmpty(st);
 
	}
 

	
 
	return cost;
 
}
 

	
 
/**
 
 * Remove a rail road station
 
 * @param tile TileIndex been queried
 
 * @param flags operation to perform
 
 * @return cost or failure of operation
 
 */
 
static CommandCost RemoveRailStation(TileIndex tile, DoCommandFlag flags)
 
{
 
	/* if there is flooding and non-uniform stations are enabled, remove platforms tile by tile */
 
	if (_current_company == OWNER_WATER && _settings_game.station.nonuniform_stations) {
 
		return DoCommand(tile, 0, 0, DC_EXEC, CMD_REMOVE_FROM_RAIL_STATION);
 
	}
 

	
 
	Station *st = Station::GetByTile(tile);
 
	CommandCost cost = RemoveRailStation(st, flags);
 

	
 
	if (flags & DC_EXEC) st->RecomputeIndustriesNear();
 

	
 
	return cost;
 
}
 

	
 
/**
 
 * Remove a rail waypoint
 
 * @param tile TileIndex been queried
 
 * @param flags operation to perform
 
 * @return cost or failure of operation
 
 */
 
static CommandCost RemoveRailWaypoint(TileIndex tile, DoCommandFlag flags)
 
{
 
	/* if there is flooding and non-uniform stations are enabled, remove waypoints tile by tile */
 
	if (_current_company == OWNER_WATER && _settings_game.station.nonuniform_stations) {
 
		return DoCommand(tile, 0, 0, DC_EXEC, CMD_REMOVE_FROM_RAIL_WAYPOINT);
 
	}
 

	
 
	return RemoveRailStation(Waypoint::GetByTile(tile), flags);
 
}
 

	
 

	
 
/**
 
 * @param truck_station Determines whether a stop is ROADSTOP_BUS or ROADSTOP_TRUCK
 
 * @param st The Station to do the whole procedure for
 
 * @return a pointer to where to link a new RoadStop*
 
 */
 
static RoadStop **FindRoadStopSpot(bool truck_station, Station *st)
 
{
 
	RoadStop **primary_stop = (truck_station) ? &st->truck_stops : &st->bus_stops;
 

	
 
	if (*primary_stop == NULL) {
 
		/* we have no roadstop of the type yet, so write a "primary stop" */
 
		return primary_stop;
 
	} else {
 
		/* there are stops already, so append to the end of the list */
 
		RoadStop *stop = *primary_stop;
 
		while (stop->next != NULL) stop = stop->next;
 
		return &stop->next;
 
	}
 
}
 

	
 
static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags);
 

	
 
/**
 
 * Find a nearby station that joins this road stop.
 
 * @param existing_stop an existing road stop we build over
 
 * @param station_to_join the station to join to
 
 * @param adjacent whether adjacent stations are allowed
 
 * @param ta the area of the newly build station
 
 * @param st 'return' pointer for the found station
 
 * @return command cost with the error or 'okay'
 
 */
 
static CommandCost FindJoiningRoadStop(StationID existing_stop, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
 
{
 
	return FindJoiningBaseStation<Station, STR_ERROR_MUST_REMOVE_ROAD_STOP_FIRST>(existing_stop, station_to_join, adjacent, ta, st);
 
}
 

	
 
/** Build a bus or truck stop.
 
 * @param tile Northernmost tile of the stop.
 
 * @param flags Operation to perform.
 
 * @param p1 bit 0..7: Width of the road stop.
 
 *           bit 8..15: Lenght of the road stop.
 
 * @param p2 bit 0: 0 For bus stops, 1 for truck stops.
 
 *           bit 1: 0 For normal stops, 1 for drive-through.
 
 *           bit 2..3: The roadtypes.
 
 *           bit 5: Allow stations directly adjacent to other stations.
 
 *           bit 6..7: Entrance direction (DiagDirection).
 
 *           bit 16..31: Station ID to join (NEW_STATION if build new one).
 
 * @param text Unused.
 
 * @return The cost of this operation or an error.
 
 */
 
CommandCost CmdBuildRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
 
{
 
	bool type = HasBit(p2, 0);
 
	bool is_drive_through = HasBit(p2, 1);
 
	RoadTypes rts = (RoadTypes)GB(p2, 2, 2);
 
	StationID station_to_join = GB(p2, 16, 16);
 
	bool reuse = (station_to_join != NEW_STATION);
 
	if (!reuse) station_to_join = INVALID_STATION;
 
	bool distant_join = (station_to_join != INVALID_STATION);
 
	Owner tram_owner = _current_company;
 
	Owner road_owner = _current_company;
 

	
 
	uint8 width = (uint8)GB(p1, 0, 8);
 
	uint8 lenght = (uint8)GB(p1, 8, 8);
 

	
 
	/* Check if the requested road stop is too big */
 
	if (width > _settings_game.station.station_spread || lenght > _settings_game.station.station_spread) return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
 
	/* Check for incorrect width / lenght. */
 
	if (width == 0 || lenght == 0) return CMD_ERROR;
 
	/* Check if the first tile and the last tile are valid */
 
	if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, lenght - 1) == INVALID_TILE) return CMD_ERROR;
 

	
 
	TileArea roadstop_area(tile, width, lenght);
 

	
 
	if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
 

	
 
	if (!AreValidRoadTypes(rts) || !HasRoadTypesAvail(_current_company, rts)) return CMD_ERROR;
 

	
 
	/* Trams only have drive through stops */
 
	if (!is_drive_through && HasBit(rts, ROADTYPE_TRAM)) return CMD_ERROR;
 

	
 
	DiagDirection ddir = (DiagDirection)GB(p2, 6, 2);
 

	
 
	/* Safeguard the parameters. */
 
	if (!IsValidDiagDirection(ddir)) return CMD_ERROR;
 
	/* If it is a drive-through stop, check for valid axis. */
 
	if (is_drive_through && !IsValidAxis((Axis)ddir)) return CMD_ERROR;
 

	
 
	CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
 
	ret.SetGlobalErrorMessage();
 
	if (ret.Failed()) return ret;
 

	
 
	/* Total road stop cost. */
 
	CommandCost cost(EXPENSES_CONSTRUCTION, roadstop_area.w * roadstop_area.h * _price[type ? PR_BUILD_STATION_TRUCK : PR_BUILD_STATION_BUS]);
 
	StationID est = INVALID_STATION;
 
	ret = CheckFlatLandRoadStop(roadstop_area, flags, is_drive_through ? 5 << ddir : 1 << ddir, is_drive_through, type, DiagDirToAxis(ddir), &est, rts);
 
	if (ret.Failed()) return ret;
 
	cost.AddCost(ret);
 

	
 
	Station *st = NULL;
 
	ret = FindJoiningRoadStop(est, station_to_join, HasBit(p2, 5), roadstop_area, &st);
 
	ret.SetGlobalErrorMessage();
 
	if (ret.Failed()) return ret;
 

	
 
	/* Find a deleted station close to us */
 
	if (st == NULL && reuse) st = GetClosestDeletedStation(tile);
 

	
 
	/* Check if this number of road stops can be allocated. */
 
	if (!RoadStop::CanAllocateItem(roadstop_area.w * roadstop_area.h)) return_cmd_error(type ? STR_ERROR_TOO_MANY_TRUCK_STOPS : STR_ERROR_TOO_MANY_BUS_STOPS);
 

	
 
	if (st != NULL) {
 
		if (st->owner != _current_company) {
 
			return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_STATION);
 
		}
 

	
 
		if (!st->rect.BeforeAddRect(roadstop_area.tile, roadstop_area.w, roadstop_area.h, StationRect::ADD_TEST)) return CMD_ERROR;
 
	} else {
 
		/* allocate and initialize new station */
 
		if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
 

	
 
		if (flags & DC_EXEC) {
 
			st = new Station(tile);
 

	
 
			st->town = ClosestTownFromTile(tile, UINT_MAX);
 
			st->string_id = GenerateStationName(st, tile, STATIONNAMING_ROAD);
 

	
 
			if (Company::IsValidID(_current_company)) {
 
				SetBit(st->town->have_ratings, _current_company);
 
			}
 
		}
 
	}
 

	
 
	if (flags & DC_EXEC) {
 
		/* Check every tile in the area. */
 
		TILE_AREA_LOOP(cur_tile, roadstop_area) {
 
			if (IsTileType(cur_tile, MP_STATION) && IsRoadStop(cur_tile)) {
 
				RemoveRoadStop(cur_tile, flags);
 
			}
 

	
 
			RoadStop *road_stop = new RoadStop(cur_tile);
 
			/* Insert into linked list of RoadStops. */
 
			RoadStop **currstop = FindRoadStopSpot(type, st);
 
			*currstop = road_stop;
 

	
 
			if (type) {
 
				st->truck_station.Add(cur_tile);
 
			} else {
 
				st->bus_station.Add(cur_tile);
 
			}
 

	
 
			/* Initialize an empty station. */
 
			st->AddFacility((type) ? FACIL_TRUCK_STOP : FACIL_BUS_STOP, cur_tile);
 

	
 
			st->rect.BeforeAddTile(cur_tile, StationRect::ADD_TRY);
 

	
 
			RoadStopType rs_type = type ? ROADSTOP_TRUCK : ROADSTOP_BUS;
 
			if (is_drive_through) {
 
				MakeDriveThroughRoadStop(cur_tile, st->owner, road_owner, tram_owner, st->index, rs_type, rts, DiagDirToAxis(ddir));
 
				road_stop->MakeDriveThrough();
 
			} else {
 
				MakeRoadStop(cur_tile, st->owner, st->index, rs_type, rts, ddir);
 
			}
 

	
 
			MarkTileDirtyByTile(cur_tile);
 
		}
 
	}
 

	
 
	if (st != NULL) {
 
		st->UpdateVirtCoord();
 
		UpdateStationAcceptance(st, false);
 
		st->RecomputeIndustriesNear();
 
		InvalidateWindowData(WC_SELECT_STATION, 0, 0);
 
		InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
 
		SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_ROADVEHS);
 
	}
 
	return cost;
 
}
 

	
 

	
 
static Vehicle *ClearRoadStopStatusEnum(Vehicle *v, void *)
 
{
 
	if (v->type == VEH_ROAD) {
 
		/* Okay... we are a road vehicle on a drive through road stop.
 
		 * But that road stop has just been removed, so we need to make
 
		 * sure we are in a valid state... however, vehicles can also
 
		 * turn on road stop tiles, so only clear the 'road stop' state
 
		 * bits and only when the state was 'in road stop', otherwise
 
		 * we'll end up clearing the turn around bits. */
 
		RoadVehicle *rv = RoadVehicle::From(v);
 
		if (HasBit(rv->state, RVS_IN_DT_ROAD_STOP)) rv->state &= RVSB_ROAD_STOP_TRACKDIR_MASK;
 
	}
 

	
 
	return NULL;
 
}
 

	
 

	
 
/**
 
 * Remove a bus station/truck stop
 
 * @param tile TileIndex been queried
 
 * @param flags operation to perform
 
 * @return cost or failure of operation
 
 */
 
static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags)
 
{
 
	Station *st = Station::GetByTile(tile);
 

	
 
	if (_current_company != OWNER_WATER && !CheckOwnership(st->owner)) {
 
		return CMD_ERROR;
 
	}
 

	
 
	bool is_truck = IsTruckStop(tile);
 

	
 
	RoadStop **primary_stop;
 
	RoadStop *cur_stop;
 
	if (is_truck) { // truck stop
 
		primary_stop = &st->truck_stops;
 
		cur_stop = RoadStop::GetByTile(tile, ROADSTOP_TRUCK);
 
	} else {
 
		primary_stop = &st->bus_stops;
 
		cur_stop = RoadStop::GetByTile(tile, ROADSTOP_BUS);
 
	}
 

	
 
	assert(cur_stop != NULL);
 

	
 
	/* don't do the check for drive-through road stops when company bankrupts */
 
	if (IsDriveThroughStopTile(tile) && (flags & DC_BANKRUPT)) {
 
		/* remove the 'going through road stop' status from all vehicles on that tile */
 
		if (flags & DC_EXEC) FindVehicleOnPos(tile, NULL, &ClearRoadStopStatusEnum);
 
	} else {
 
		CommandCost ret = EnsureNoVehicleOnGround(tile);
 
		ret.SetGlobalErrorMessage();
 
		if (ret.Failed()) return ret;
 
	}
 

	
 
	if (flags & DC_EXEC) {
 
		if (*primary_stop == cur_stop) {
 
			/* removed the first stop in the list */
 
			*primary_stop = cur_stop->next;
 
			/* removed the only stop? */
 
			if (*primary_stop == NULL) {
 
				st->facilities &= (is_truck ? ~FACIL_TRUCK_STOP : ~FACIL_BUS_STOP);
 
			}
 
		} else {
 
			/* tell the predecessor in the list to skip this stop */
 
			RoadStop *pred = *primary_stop;
 
			while (pred->next != cur_stop) pred = pred->next;
 
			pred->next = cur_stop->next;
 
		}
 

	
 
		if (IsDriveThroughStopTile(tile)) {
 
			/* Clears the tile for us */
 
			cur_stop->ClearDriveThrough();
 
		} else {
 
			DoClearSquare(tile);
 
		}
 

	
 
		SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_ROADVEHS);
 
		delete cur_stop;
 

	
 
		/* Make sure no vehicle is going to the old roadstop */
 
		RoadVehicle *v;
 
		FOR_ALL_ROADVEHICLES(v) {
 
			if (v->First() == v && v->current_order.IsType(OT_GOTO_STATION) &&
 
					v->dest_tile == tile) {
 
				v->dest_tile = v->GetOrderStationLocation(st->index);
 
			}
 
		}
 

	
 
		st->rect.AfterRemoveTile(st, tile);
 

	
 
		st->UpdateVirtCoord();
 
		st->RecomputeIndustriesNear();
 
		DeleteStationIfEmpty(st);
 

	
 
		/* Update the tile area of the truck/bus stop */
 
		if (is_truck) {
 
			st->truck_station.Clear();
 
			for (const RoadStop *rs = st->truck_stops; rs != NULL; rs = rs->next) st->truck_station.Add(rs->xy);
 
		} else {
 
			st->bus_station.Clear();
 
			for (const RoadStop *rs = st->bus_stops; rs != NULL; rs = rs->next) st->bus_station.Add(rs->xy);
 
		}
 
	}
 

	
 
	return CommandCost(EXPENSES_CONSTRUCTION, _price[is_truck ? PR_CLEAR_STATION_TRUCK : PR_CLEAR_STATION_BUS]);
 
}
 

	
 
/** Remove bus or truck stops.
 
 * @param tile Northernmost tile of the removal area.
 
 * @param flags Operation to perform.
 
 * @param p1 bit 0..7: Width of the removal area.
 
 *           bit 8..15: Height of the removal area.
 
 * @param p2 bit 0: 0 For bus stops, 1 for truck stops.
 
 * @param text Unused.
 
 * @return The cost of this operation or an error.
 
 */
 
CommandCost CmdRemoveRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
 
{
 
	uint8 width = (uint8)GB(p1, 0, 8);
 
	uint8 height = (uint8)GB(p1, 8, 8);
 

	
 
	/* Check for incorrect width / height. */
 
	if (width == 0 || height == 0) return CMD_ERROR;
 
	/* Check if the first tile and the last tile are valid */
 
	if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, height - 1) == INVALID_TILE) return CMD_ERROR;
 

	
 
	TileArea roadstop_area(tile, width, height);
 

	
 
	int quantity = 0;
 
	CommandCost cost(EXPENSES_CONSTRUCTION);
 
	TILE_AREA_LOOP(cur_tile, roadstop_area) {
 
		/* Make sure the specified tile is a road stop of the correct type */
 
		if (!IsTileType(cur_tile, MP_STATION) || !IsRoadStop(cur_tile) || (uint32)GetRoadStopType(cur_tile) != GB(p2, 0, 1)) continue;
 

	
 
		/* Save the stop info before it is removed */
 
		bool is_drive_through = IsDriveThroughStopTile(cur_tile);
 
		RoadTypes rts = GetRoadTypes(cur_tile);
 
		RoadBits road_bits = IsDriveThroughStopTile(cur_tile) ?
 
				((GetRoadStopDir(cur_tile) == DIAGDIR_NE) ? ROAD_X : ROAD_Y) :
 
				DiagDirToRoadBits(GetRoadStopDir(cur_tile));
 

	
 
		Owner road_owner = GetRoadOwner(cur_tile, ROADTYPE_ROAD);
 
		Owner tram_owner = GetRoadOwner(cur_tile, ROADTYPE_TRAM);
 
		CommandCost ret = RemoveRoadStop(cur_tile, flags);
 
		if (ret.Failed()) return ret;
 
		cost.AddCost(ret);
 

	
 
		quantity++;
 
		/* If the stop was a drive-through stop replace the road */
 
		if ((flags & DC_EXEC) && is_drive_through) {
 
			MakeRoadNormal(cur_tile, road_bits, rts, ClosestTownFromTile(cur_tile, UINT_MAX)->index,
 
					road_owner, tram_owner);
 
		}
 
	}
 

	
 
	if (quantity == 0) return CMD_ERROR;
 

	
 
	return cost;
 
}
 

	
 
/**
 
 * Computes the minimal distance from town's xy to any airport's tile.
 
 * @param as airport's description
 
 * @param town_tile town's tile (t->xy)
 
 * @param airport_tile st->airport.tile
 
 * @return minimal manhattan distance from town_tile to any airport's tile
 
 */
 
static uint GetMinimalAirportDistanceToTile(const AirportSpec *as, TileIndex town_tile, TileIndex airport_tile)
 
{
 
	uint ttx = TileX(town_tile); // X, Y of town
 
	uint tty = TileY(town_tile);
 

	
 
	uint atx = TileX(airport_tile); // X, Y of northern airport corner
 
	uint aty = TileY(airport_tile);
 

	
 
	uint btx = TileX(airport_tile) + as->size_x - 1; // X, Y of southern corner
 
	uint bty = TileY(airport_tile) + as->size_y - 1;
 

	
 
	/* if ttx < atx, dx = atx - ttx
 
	 * if atx <= ttx <= btx, dx = 0
 
	 * else, dx = ttx - btx (similiar for dy) */
 
	uint dx = ttx < atx ? atx - ttx : (ttx <= btx ? 0 : ttx - btx);
 
	uint dy = tty < aty ? aty - tty : (tty <= bty ? 0 : tty - bty);
 

	
 
	return dx + dy;
 
}
 

	
 
/** Get a possible noise reduction factor based on distance from town center.
 
 * The further you get, the less noise you generate.
 
 * So all those folks at city council can now happily slee...  work in their offices
 
 * @param as airport information
 
 * @param town_tile TileIndex of town's center, the one who will receive the airport's candidature
 
 * @param tile TileIndex of northern tile of an airport (present or to-be-built), NOT the station tile
 
 * @return the noise that will be generated, according to distance
 
 */
 
uint8 GetAirportNoiseLevelForTown(const AirportSpec *as, TileIndex town_tile, TileIndex tile)
 
{
 
	/* 0 cannot be accounted, and 1 is the lowest that can be reduced from town.
 
	 * So no need to go any further*/
 
	if (as->noise_level < 2) return as->noise_level;
 

	
 
	uint distance = GetMinimalAirportDistanceToTile(as, town_tile, tile);
 

	
 
	/* The steps for measuring noise reduction are based on the "magical" (and arbitrary) 8 base distance
 
	 * adding the town_council_tolerance 4 times, as a way to graduate, depending of the tolerance.
 
	 * Basically, it says that the less tolerant a town is, the bigger the distance before
 
	 * an actual decrease can be granted */
 
	uint8 town_tolerance_distance = 8 + (_settings_game.difficulty.town_council_tolerance * 4);
 

	
 
	/* now, we want to have the distance segmented using the distance judged bareable by town
 
	 * This will give us the coefficient of reduction the distance provides. */
 
	uint noise_reduction = distance / town_tolerance_distance;
 

	
 
	/* If the noise reduction equals the airport noise itself, don't give it for free.
 
	 * Otherwise, simply reduce the airport's level. */
 
	return noise_reduction >= as->noise_level ? 1 : as->noise_level - noise_reduction;
 
}
 

	
 
/**
 
 * Finds the town nearest to given airport. Based on minimal manhattan distance to any airport's tile.
 
 * If two towns have the same distance, town with lower index is returned.
 
 * @param as airport's description
 
 * @param airport_tile st->airport.tile
 
 * @return nearest town to airport
 
 */
 
Town *AirportGetNearestTown(const AirportSpec *as, TileIndex airport_tile)
 
{
 
	Town *t, *nearest = NULL;
 
	uint add = as->size_x + as->size_y - 2; // GetMinimalAirportDistanceToTile can differ from DistanceManhattan by this much
 
	uint mindist = UINT_MAX - add; // prevent overflow
 
	FOR_ALL_TOWNS(t) {
 
		if (DistanceManhattan(t->xy, airport_tile) < mindist + add) { // avoid calling GetMinimalAirportDistanceToTile too often
 
			uint dist = GetMinimalAirportDistanceToTile(as, t->xy, airport_tile);
 
			if (dist < mindist) {
 
				nearest = t;
 
				mindist = dist;
 
			}
 
		}
 
	}
 

	
 
	return nearest;
 
}
 

	
 

	
 
/** Recalculate the noise generated by the airports of each town */
 
void UpdateAirportsNoise()
 
{
 
	Town *t;
 
	const Station *st;
 

	
 
	FOR_ALL_TOWNS(t) t->noise_reached = 0;
 

	
 
	FOR_ALL_STATIONS(st) {
 
		if (st->airport.tile != INVALID_TILE) {
 
			const AirportSpec *as = st->GetAirportSpec();
 
			Town *nearest = AirportGetNearestTown(as, st->airport.tile);
 
			nearest->noise_reached += GetAirportNoiseLevelForTown(as, nearest->xy, st->airport.tile);
 
		}
 
	}
 
}
 

	
 
/** Place an Airport.
 
 * @param tile tile where airport will be built
 
 * @param flags operation to perform
 
 * @param p1 airport type, @see airport.h
 
 * @param p2 various bitstuffed elements
 
 * - p2 = (bit     0) - allow airports directly adjacent to other airports.
 
 * - p2 = (bit 16-31) - station ID to join (NEW_STATION if build new one)
 
 * @param text unused
 
 * @return the cost of this operation or an error
 
 */
 
CommandCost CmdBuildAirport(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
 
{
 
	bool airport_upgrade = true;
 
	StationID station_to_join = GB(p2, 16, 16);
 
	bool reuse = (station_to_join != NEW_STATION);
 
	if (!reuse) station_to_join = INVALID_STATION;
 
	bool distant_join = (station_to_join != INVALID_STATION);
 

	
 
	if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
 

	
 
	if (p1 >= NUM_AIRPORTS) return CMD_ERROR;
 

	
 
	CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
 
	ret.SetGlobalErrorMessage();
 
	if (ret.Failed()) return ret;
 

	
 
	/* Check if a valid, buildable airport was chosen for construction */
 
	const AirportSpec *as = AirportSpec::Get(p1);
 
	if (!as->IsAvailable()) return CMD_ERROR;
 

	
 
	Town *t = ClosestTownFromTile(tile, UINT_MAX);
 
	int w = as->size_x;
 
	int h = as->size_y;
 

	
 
	if (w > _settings_game.station.station_spread || h > _settings_game.station.station_spread) {
 
		return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
 
	}
 

	
 
	CommandCost cost = CheckFlatLand(TileArea(tile, w, h), flags);
 
	if (cost.Failed()) return cost;
 

	
 
	/* Go get the final noise level, that is base noise minus factor from distance to town center */
 
	Town *nearest = AirportGetNearestTown(as, tile);
 
	uint newnoise_level = GetAirportNoiseLevelForTown(as, nearest->xy, tile);
 

	
 
	/* Check if local auth would allow a new airport */
 
	StringID authority_refuse_message = STR_NULL;
 

	
 
	if (_settings_game.economy.station_noise_level) {
 
		/* do not allow to build a new airport if this raise the town noise over the maximum allowed by town */
 
		if ((nearest->noise_reached + newnoise_level) > nearest->MaxTownNoise()) {
 
			authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_NOISE;
 
		}
 
	} else {
 
		uint num = 0;
 
		const Station *st;
 
		FOR_ALL_STATIONS(st) {
 
			if (st->town == t && (st->facilities & FACIL_AIRPORT) && st->airport_type != AT_OILRIG) num++;
 
		}
 
		if (num >= 2) {
 
			authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_AIRPORT;
 
		}
 
	}
 

	
 
	if (authority_refuse_message != STR_NULL) {
 
		SetDParam(0, t->index);
 
		return_cmd_error(authority_refuse_message);
 
	}
 

	
 
	Station *st = NULL;
 
	ret = FindJoiningStation(INVALID_STATION, station_to_join, HasBit(p2, 0), TileArea(tile, w, h), &st);
 
	ret.SetGlobalErrorMessage();
 
	if (ret.Failed()) return ret;
 

	
 
	/* Distant join */
 
	if (st == NULL && distant_join) st = Station::GetIfValid(station_to_join);
 

	
 
	/* Find a deleted station close to us */
 
	if (st == NULL && reuse) st = GetClosestDeletedStation(tile);
 

	
 
	if (st != NULL) {
 
		if (st->owner != _current_company) {
 
			return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_STATION);
 
		}
 

	
 
		if (!st->rect.BeforeAddRect(tile, w, h, StationRect::ADD_TEST)) return CMD_ERROR;
 

	
 
		if (st->airport.tile != INVALID_TILE) {
 
			return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_AIRPORT);
 
		}
 
	} else {
 
		airport_upgrade = false;
 

	
 
		/* allocate and initialize new station */
 
		if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
 

	
 
		if (flags & DC_EXEC) {
 
			st = new Station(tile);
 

	
 
			st->town = t;
 
			st->string_id = GenerateStationName(st, tile, !(GetAirport(p1)->flags & AirportFTAClass::AIRPLANES) ? STATIONNAMING_HELIPORT : STATIONNAMING_AIRPORT);
 

	
 
			if (Company::IsValidID(_current_company)) {
 
				SetBit(st->town->have_ratings, _current_company);
 
			}
 
		}
 
	}
 

	
 
	cost.AddCost(_price[PR_BUILD_STATION_AIRPORT] * w * h);
 

	
 
	if (flags & DC_EXEC) {
 
		/* Always add the noise, so there will be no need to recalculate when option toggles */
 
		nearest->noise_reached += newnoise_level;
 

	
 
		st->AddFacility(FACIL_AIRPORT, tile);
 
		st->airport_type = (byte)p1;
 
		st->airport_flags = 0;
 

	
 
		st->rect.BeforeAddRect(tile, w, h, StationRect::ADD_TRY);
 

	
 
		const AirportTileTable *it = as->table[0];
 
		do {
 
			TileIndex cur_tile = tile + ToTileIndexDiff(it->ti);
 
			MakeAirport(cur_tile, st->owner, st->index, it->gfx);
 
			SetStationTileRandomBits(cur_tile, GB(Random(), 0, 4));
 
			st->airport.Add(cur_tile);
 

	
 
			if (AirportTileSpec::Get(GetTranslatedAirportTileID(it->gfx))->animation_info != 0xFFFF) AddAnimatedTile(cur_tile);
 
		} while ((++it)->ti.x != -0x80);
 

	
 
		/* Only call the animation trigger after all tiles have been built */
 
		it = as->table[0];
 
		do {
 
			TileIndex cur_tile = tile + ToTileIndexDiff(it->ti);
 
			AirportTileAnimationTrigger(st, cur_tile, AAT_BUILT);
 
		} while ((++it)->ti.x != -0x80);
 

	
 
		/* if airport was demolished while planes were en-route to it, the
 
		 * positions can no longer be the same (v->u.air.pos), since different
 
		 * airports have different indexes. So update all planes en-route to this
 
		 * airport. Only update if
 
		 * 1. airport is upgraded
 
		 * 2. airport is added to existing station (unfortunately unavoideable)
 
		 */
 
		if (airport_upgrade) UpdateAirplanesOnNewStation(st);
 

	
 
		st->UpdateVirtCoord();
 
		UpdateStationAcceptance(st, false);
 
		st->RecomputeIndustriesNear();
 
		InvalidateWindowData(WC_SELECT_STATION, 0, 0);
 
		InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
 
		SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_PLANES);
 

	
 
		if (_settings_game.economy.station_noise_level) {
 
			SetWindowDirty(WC_TOWN_VIEW, st->town->index);
 
		}
 
	}
 

	
 
	return cost;
 
}
 

	
 
/**
 
 * Remove an airport
 
 * @param tile TileIndex been queried
 
 * @param flags operation to perform
 
 * @return cost or failure of operation
 
 */
 
static CommandCost RemoveAirport(TileIndex tile, DoCommandFlag flags)
 
{
 
	Station *st = Station::GetByTile(tile);
 

	
 
	if (_current_company != OWNER_WATER && !CheckOwnership(st->owner)) {
 
		return CMD_ERROR;
 
	}
 

	
 
	tile = st->airport.tile;
 

	
 
	const AirportSpec *as = st->GetAirportSpec();
 
	int w = as->size_x;
 
	int h = as->size_y;
 

	
 
	CommandCost cost(EXPENSES_CONSTRUCTION);
 

	
 
	const Aircraft *a;
 
	FOR_ALL_AIRCRAFT(a) {
 
		if (!a->IsNormalAircraft()) continue;
 
		if (a->targetairport == st->index && a->state != FLYING) return CMD_ERROR;
 
	}
 

	
 
	TILE_AREA_LOOP(tile_cur, st->airport) {
 
		if (!st->TileBelongsToAirport(tile_cur)) continue;
 

	
 
		CommandCost ret = EnsureNoVehicleOnGround(tile);
 
		CommandCost ret = EnsureNoVehicleOnGround(tile_cur);
 
		ret.SetGlobalErrorMessage();
 
		if (ret.Failed()) return ret;
 

	
 
		cost.AddCost(_price[PR_CLEAR_STATION_AIRPORT]);
 

	
 
		if (flags & DC_EXEC) {
 
			DeleteAnimatedTile(tile_cur);
 
			DoClearSquare(tile_cur);
 
		}
 
	}
 

	
 
	if (flags & DC_EXEC) {
 
		const AirportSpec *as = st->GetAirportSpec();
 
		for (uint i = 0; i < as->nof_depots; ++i) {
 
			DeleteWindowById(
 
				WC_VEHICLE_DEPOT, st->GetHangarTile(i)
 
			);
 
		}
 

	
 
		/* Go get the final noise level, that is base noise minus factor from distance to town center.
 
		 * And as for construction, always remove it, even if the setting is not set, in order to avoid the
 
		 * need of recalculation */
 
		Town *nearest = AirportGetNearestTown(as, tile);
 
		nearest->noise_reached -= GetAirportNoiseLevelForTown(as, nearest->xy, tile);
 

	
 
		st->rect.AfterRemoveRect(st, tile, w, h);
 
		st->rect.AfterRemoveRect(st, tile, st->airport.w, st->airport.h);
 

	
 
		st->airport.Clear();
 
		st->facilities &= ~FACIL_AIRPORT;
 

	
 
		SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_PLANES);
 

	
 
		if (_settings_game.economy.station_noise_level) {
 
			SetWindowDirty(WC_TOWN_VIEW, st->town->index);
 
		}
 

	
 
		st->UpdateVirtCoord();
 
		st->RecomputeIndustriesNear();
 
		DeleteStationIfEmpty(st);
 
	}
 

	
 
	return cost;
 
}
 

	
 
/**
 
 * Tests whether the company's vehicles have this station in orders
 
 * When company == INVALID_COMPANY, then check all vehicles
 
 * @param station station ID
 
 * @param company company ID, INVALID_COMPANY to disable the check
 
 */
 
bool HasStationInUse(StationID station, CompanyID company)
 
{
 
	const Vehicle *v;
 
	FOR_ALL_VEHICLES(v) {
 
		if (company == INVALID_COMPANY || v->owner == company) {
 
			const Order *order;
 
			FOR_VEHICLE_ORDERS(v, order) {
 
				if ((order->IsType(OT_GOTO_STATION) || order->IsType(OT_GOTO_WAYPOINT)) && order->GetDestination() == station) {
 
					return true;
 
				}
 
			}
 
		}
 
	}
 
	return false;
 
}
 

	
 
static const TileIndexDiffC _dock_tileoffs_chkaround[] = {
 
	{-1,  0},
 
	{ 0,  0},
 
	{ 0,  0},
 
	{ 0, -1}
 
};
 
static const byte _dock_w_chk[4] = { 2, 1, 2, 1 };
 
static const byte _dock_h_chk[4] = { 1, 2, 1, 2 };
 

	
 
/** Build a dock/haven.
 
 * @param tile tile where dock will be built
 
 * @param flags operation to perform
 
 * @param p1 (bit 0) - allow docks directly adjacent to other docks.
 
 * @param p2 bit 16-31: station ID to join (NEW_STATION if build new one)
 
 * @param text unused
 
 * @return the cost of this operation or an error
 
 */
 
CommandCost CmdBuildDock(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
 
{
 
	StationID station_to_join = GB(p2, 16, 16);
 
	bool reuse = (station_to_join != NEW_STATION);
 
	if (!reuse) station_to_join = INVALID_STATION;
 
	bool distant_join = (station_to_join != INVALID_STATION);
 

	
 
	if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
 

	
 
	DiagDirection direction = GetInclinedSlopeDirection(GetTileSlope(tile, NULL));
 
	if (direction == INVALID_DIAGDIR) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
 
	direction = ReverseDiagDir(direction);
 

	
 
	/* Docks cannot be placed on rapids */
 
	if (IsWaterTile(tile)) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
 

	
 
	CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
 
	ret.SetGlobalErrorMessage();
 
	if (ret.Failed()) return ret;
 

	
 
	if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
 

	
 
	if (DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR).Failed()) return CMD_ERROR;
 

	
 
	TileIndex tile_cur = tile + TileOffsByDiagDir(direction);
 

	
 
	if (!IsTileType(tile_cur, MP_WATER) || GetTileSlope(tile_cur, NULL) != SLOPE_FLAT) {
 
		return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
 
	}
 

	
 
	if (MayHaveBridgeAbove(tile_cur) && IsBridgeAbove(tile_cur)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
 

	
 
	/* Get the water class of the water tile before it is cleared.*/
 
	WaterClass wc = GetWaterClass(tile_cur);
 

	
 
	if (DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR).Failed()) return CMD_ERROR;
 

	
 
	tile_cur += TileOffsByDiagDir(direction);
 
	if (!IsTileType(tile_cur, MP_WATER) || GetTileSlope(tile_cur, NULL) != SLOPE_FLAT) {
 
		return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
 
	}
 

	
 
	/* middle */
 
	Station *st = NULL;
 
	ret = FindJoiningStation(INVALID_STATION, station_to_join, HasBit(p1, 0),
 
			TileArea(tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
 
					_dock_w_chk[direction], _dock_h_chk[direction]), &st);
 
	ret.SetGlobalErrorMessage();
 
	if (ret.Failed()) return ret;
 

	
 
	/* Distant join */
 
	if (st == NULL && distant_join) st = Station::GetIfValid(station_to_join);
 

	
 
	/* Find a deleted station close to us */
 
	if (st == NULL && reuse) st = GetClosestDeletedStation(tile);
 

	
 
	if (st != NULL) {
 
		if (st->owner != _current_company) {
 
			return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_STATION);
 
		}
 

	
 
		if (!st->rect.BeforeAddRect(
 
				tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
 
				_dock_w_chk[direction], _dock_h_chk[direction], StationRect::ADD_TEST)) return CMD_ERROR;
 

	
 
		if (st->dock_tile != INVALID_TILE) return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_DOCK);
 
	} else {
 
		/* allocate and initialize new station */
 
		if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
 

	
 
		if (flags & DC_EXEC) {
 
			st = new Station(tile);
 

	
 
			st->town = ClosestTownFromTile(tile, UINT_MAX);
 
			st->string_id = GenerateStationName(st, tile, STATIONNAMING_DOCK);
 

	
 
			if (Company::IsValidID(_current_company)) {
 
				SetBit(st->town->have_ratings, _current_company);
 
			}
 
		}
 
	}
 

	
 
	if (flags & DC_EXEC) {
 
		st->dock_tile = tile;
 
		st->AddFacility(FACIL_DOCK, tile);
 

	
 
		st->rect.BeforeAddRect(
 
				tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
 
				_dock_w_chk[direction], _dock_h_chk[direction], StationRect::ADD_TRY);
 

	
 
		MakeDock(tile, st->owner, st->index, direction, wc);
 

	
 
		st->UpdateVirtCoord();
 
		UpdateStationAcceptance(st, false);
 
		st->RecomputeIndustriesNear();
 
		InvalidateWindowData(WC_SELECT_STATION, 0, 0);
 
		InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
 
		SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_SHIPS);
 
	}
 

	
 
	return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_STATION_DOCK]);
 
}
 

	
 
/**
 
 * Remove a dock
 
 * @param tile TileIndex been queried
 
 * @param flags operation to perform
 
 * @return cost or failure of operation
 
 */
 
static CommandCost RemoveDock(TileIndex tile, DoCommandFlag flags)
 
{
 
	Station *st = Station::GetByTile(tile);
 
	if (!CheckOwnership(st->owner)) return CMD_ERROR;
 

	
 
	TileIndex tile1 = st->dock_tile;
 
	TileIndex tile2 = tile1 + TileOffsByDiagDir(GetDockDirection(tile1));
 

	
 
	CommandCost ret = EnsureNoVehicleOnGround(tile1);
 
	if (ret.Succeeded()) ret = EnsureNoVehicleOnGround(tile2);
 
	ret.SetGlobalErrorMessage();
 
	if (ret.Failed()) return ret;
 

	
 
	if (flags & DC_EXEC) {
 
		DoClearSquare(tile1);
 
		MakeWaterKeepingClass(tile2, st->owner);
 

	
 
		st->rect.AfterRemoveTile(st, tile1);
 
		st->rect.AfterRemoveTile(st, tile2);
 

	
 
		MarkTileDirtyByTile(tile2);
 

	
 
		st->dock_tile = INVALID_TILE;
 
		st->facilities &= ~FACIL_DOCK;
 

	
 
		SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_SHIPS);
 
		st->UpdateVirtCoord();
 
		st->RecomputeIndustriesNear();
 
		DeleteStationIfEmpty(st);
 
	}
 

	
 
	return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_STATION_DOCK]);
 
}
 

	
 
#include "table/station_land.h"
 

	
 
const DrawTileSprites *GetStationTileLayout(StationType st, byte gfx)
 
{
 
	return &_station_display_datas[st][gfx];
 
}
 

	
 
static void DrawTile_Station(TileInfo *ti)
 
{
 
	const DrawTileSprites *t = NULL;
 
	RoadTypes roadtypes;
 
	int32 total_offset;
 
	int32 custom_ground_offset;
 
	const RailtypeInfo *rti = NULL;
 
	uint32 relocation = 0;
 
	const BaseStation *st = NULL;
 
	const StationSpec *statspec = NULL;
 

	
 
	if (HasStationRail(ti->tile)) {
 
		rti = GetRailTypeInfo(GetRailType(ti->tile));
 
		roadtypes = ROADTYPES_NONE;
 
		total_offset = rti->total_offset;
 
		custom_ground_offset = rti->custom_ground_offset;
 

	
 
		if (IsCustomStationSpecIndex(ti->tile)) {
 
			/* look for customization */
 
			st = BaseStation::GetByTile(ti->tile);
 
			statspec = st->speclist[GetCustomStationSpecIndex(ti->tile)].spec;
 

	
 
			if (statspec != NULL) {
 
				uint tile = GetStationGfx(ti->tile);
 

	
 
				relocation = GetCustomStationRelocation(statspec, st, ti->tile);
 

	
 
				if (HasBit(statspec->callback_mask, CBM_STATION_SPRITE_LAYOUT)) {
 
					uint16 callback = GetStationCallback(CBID_STATION_SPRITE_LAYOUT, 0, 0, statspec, st, ti->tile);
 
					if (callback != CALLBACK_FAILED) tile = (callback & ~1) + GetRailStationAxis(ti->tile);
 
				}
 

	
 
				/* Ensure the chosen tile layout is valid for this custom station */
 
				if (statspec->renderdata != NULL) {
 
					t = &statspec->renderdata[tile < statspec->tiles ? tile : (uint)GetRailStationAxis(ti->tile)];
 
				}
 
			}
 
		}
 
	} else {
 
		roadtypes = IsRoadStop(ti->tile) ? GetRoadTypes(ti->tile) : ROADTYPES_NONE;
 
		total_offset = 0;
 
		custom_ground_offset = 0;
 
	}
 

	
 
	if (IsAirport(ti->tile)) {
 
		StationGfx gfx = GetAirportGfx(ti->tile);
 
		if (gfx >= NEW_AIRPORTTILE_OFFSET) {
 
			const AirportTileSpec *ats = AirportTileSpec::Get(gfx);
 
			if (ats->grf_prop.spritegroup != NULL && DrawNewAirportTile(ti, Station::GetByTile(ti->tile), gfx, ats)) {
 
				return;
 
			}
 
			/* No sprite group (or no valid one) found, meaning no graphics associated.
 
			 * Use the substitute one instead */
 
			assert(ats->grf_prop.subst_id != INVALID_AIRPORTTILE);
 
			gfx = ats->grf_prop.subst_id;
 
		}
 
		switch (gfx) {
 
			case APT_RADAR_GRASS_FENCE_SW:
 
				t = &_station_display_datas_airport_radar_grass_fence_sw[GetStationAnimationFrame(ti->tile)];
 
				break;
 
			case APT_GRASS_FENCE_NE_FLAG:
 
				t = &_station_display_datas_airport_flag_grass_fence_ne[GetStationAnimationFrame(ti->tile)];
 
				break;
 
			case APT_RADAR_FENCE_SW:
 
				t = &_station_display_datas_airport_radar_fence_sw[GetStationAnimationFrame(ti->tile)];
 
				break;
 
			case APT_RADAR_FENCE_NE:
 
				t = &_station_display_datas_airport_radar_fence_ne[GetStationAnimationFrame(ti->tile)];
 
				break;
 
			case APT_GRASS_FENCE_NE_FLAG_2:
 
				t = &_station_display_datas_airport_flag_grass_fence_ne_2[GetStationAnimationFrame(ti->tile)];
 
				break;
 
		}
 
	}
 

	
 
	Owner owner = GetTileOwner(ti->tile);
 

	
 
	PaletteID palette;
 
	if (Company::IsValidID(owner)) {
 
		palette = COMPANY_SPRITE_COLOUR(owner);
 
	} else {
 
		/* Some stations are not owner by a company, namely oil rigs */
 
		palette = PALETTE_TO_GREY;
 
	}
 

	
 
	if (t == NULL || t->seq == NULL) t = &_station_display_datas[GetStationType(ti->tile)][GetStationGfx(ti->tile)];
 

	
 
	/* don't show foundation for docks */
 
	if (ti->tileh != SLOPE_FLAT && !IsDock(ti->tile)) {
 
		if (statspec != NULL && HasBit(statspec->flags, SSF_CUSTOM_FOUNDATIONS)) {
 
			/* Station has custom foundations. */
 
			SpriteID image = GetCustomStationFoundationRelocation(statspec, st, ti->tile);
 

	
 
			if (HasBit(statspec->flags, SSF_EXTENDED_FOUNDATIONS)) {
 
				/* Station provides extended foundations. */
 

	
 
				static const uint8 foundation_parts[] = {
 
					0, 0, 0, 0, // Invalid,  Invalid,   Invalid,   SLOPE_SW
 
					0, 1, 2, 3, // Invalid,  SLOPE_EW,  SLOPE_SE,  SLOPE_WSE
 
					0, 4, 5, 6, // Invalid,  SLOPE_NW,  SLOPE_NS,  SLOPE_NWS
 
					7, 8, 9     // SLOPE_NE, SLOPE_ENW, SLOPE_SEN
 
				};
 

	
 
				AddSortableSpriteToDraw(image + foundation_parts[ti->tileh], PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
 
			} else {
 
				/* Draw simple foundations, built up from 8 possible foundation sprites. */
 

	
 
				/* Each set bit represents one of the eight composite sprites to be drawn.
 
				 * 'Invalid' entries will not drawn but are included for completeness. */
 
				static const uint8 composite_foundation_parts[] = {
 
					/* Invalid  (00000000), Invalid   (11010001), Invalid   (11100100), SLOPE_SW  (11100000) */
 
					   0x00,                0xD1,                 0xE4,                 0xE0,
 
					/* Invalid  (11001010), SLOPE_EW  (11001001), SLOPE_SE  (11000100), SLOPE_WSE (11000000) */
 
					   0xCA,                0xC9,                 0xC4,                 0xC0,
 
					/* Invalid  (11010010), SLOPE_NW  (10010001), SLOPE_NS  (11100100), SLOPE_NWS (10100000) */
 
					   0xD2,                0x91,                 0xE4,                 0xA0,
 
					/* SLOPE_NE (01001010), SLOPE_ENW (00001001), SLOPE_SEN (01000100) */
 
					   0x4A,                0x09,                 0x44
 
				};
 

	
 
				uint8 parts = composite_foundation_parts[ti->tileh];
 

	
 
				/* If foundations continue beyond the tile's upper sides then
 
				 * mask out the last two pieces. */
 
				uint z;
 
				Slope slope = GetFoundationSlope(ti->tile, &z);
 
				if (!HasFoundationNW(ti->tile, slope, z)) ClrBit(parts, 6);
 
				if (!HasFoundationNE(ti->tile, slope, z)) ClrBit(parts, 7);
 

	
 
				StartSpriteCombine();
 
				for (int i = 0; i < 8; i++) {
 
					if (HasBit(parts, i)) {
 
						AddSortableSpriteToDraw(image + i, PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
 
					}
 
				}
 
				EndSpriteCombine();
 
			}
 

	
 
			OffsetGroundSprite(31, 1);
 
			ti->z += ApplyFoundationToSlope(FOUNDATION_LEVELED, &ti->tileh);
 
		} else {
 
			DrawFoundation(ti, FOUNDATION_LEVELED);
 
		}
 
	}
 

	
 
	if (IsBuoy(ti->tile) || IsDock(ti->tile) || (IsOilRig(ti->tile) && GetWaterClass(ti->tile) != WATER_CLASS_INVALID)) {
 
		if (ti->tileh == SLOPE_FLAT) {
 
			DrawWaterClassGround(ti);
 
		} else {
 
			assert(IsDock(ti->tile));
 
			TileIndex water_tile = ti->tile + TileOffsByDiagDir(GetDockDirection(ti->tile));
 
			WaterClass wc = GetWaterClass(water_tile);
 
			if (wc == WATER_CLASS_SEA) {
 
				DrawShoreTile(ti->tileh);
 
			} else {
 
				DrawClearLandTile(ti, 3);
 
			}
 
		}
 
	} else {
 
		SpriteID image = t->ground.sprite;
 
		PaletteID pal  = t->ground.pal;
 
		if (rti != NULL && rti->UsesOverlay() && (image == SPR_RAIL_TRACK_X || image == SPR_RAIL_TRACK_Y)) {
 
			SpriteID ground = GetCustomRailSprite(rti, ti->tile, RTSG_GROUND);
 
			DrawGroundSprite(SPR_FLAT_GRASS_TILE, PAL_NONE);
 
			DrawGroundSprite(ground + (image == SPR_RAIL_TRACK_X ? RTO_X : RTO_Y), PAL_NONE);
 

	
 
			if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationReservation(ti->tile)) {
 
				SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
 
				DrawGroundSprite(overlay + (image == SPR_RAIL_TRACK_X ? RTO_X : RTO_Y), PALETTE_CRASH);
 
			}
 
		} else {
 
			if (HasBit(image, SPRITE_MODIFIER_CUSTOM_SPRITE)) {
 
				image += GetCustomStationGroundRelocation(statspec, st, ti->tile);
 
				image += custom_ground_offset;
 
			} else {
 
				image += total_offset;
 
			}
 
			DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, palette));
 

	
 
			/* PBS debugging, draw reserved tracks darker */
 
			if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationRail(ti->tile) && HasStationReservation(ti->tile)) {
 
				const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
 
				DrawGroundSprite(GetRailStationAxis(ti->tile) == AXIS_X ? rti->base_sprites.single_x : rti->base_sprites.single_y, PALETTE_CRASH);
 
			}
 
		}
 
	}
 

	
 
	if (HasStationRail(ti->tile) && HasCatenaryDrawn(GetRailType(ti->tile)) && IsStationTileElectrifiable(ti->tile)) DrawCatenary(ti);
 

	
 
	if (HasBit(roadtypes, ROADTYPE_TRAM)) {
 
		Axis axis = GetRoadStopDir(ti->tile) == DIAGDIR_NE ? AXIS_X : AXIS_Y;
 
		DrawGroundSprite((HasBit(roadtypes, ROADTYPE_ROAD) ? SPR_TRAMWAY_OVERLAY : SPR_TRAMWAY_TRAM) + (axis ^ 1), PAL_NONE);
 
		DrawTramCatenary(ti, axis == AXIS_X ? ROAD_X : ROAD_Y);
 
	}
 

	
 
	if (IsRailWaypoint(ti->tile)) {
 
		/* Don't offset the waypoint graphics; they're always the same. */
 
		total_offset = 0;
 
	}
 

	
 
	DrawRailTileSeq(ti, t, TO_BUILDINGS, total_offset, relocation, palette);
 
}
 

	
 
void StationPickerDrawSprite(int x, int y, StationType st, RailType railtype, RoadType roadtype, int image)
 
{
 
	int32 total_offset = 0;
 
	PaletteID pal = COMPANY_SPRITE_COLOUR(_local_company);
 
	const DrawTileSprites *t = &_station_display_datas[st][image];
 
	const RailtypeInfo *rti = NULL;
 

	
 
	if (railtype != INVALID_RAILTYPE) {
 
		rti = GetRailTypeInfo(railtype);
 
		total_offset = rti->total_offset;
 
	}
 

	
 
	SpriteID img = t->ground.sprite;
 
	if ((img == SPR_RAIL_TRACK_X || img == SPR_RAIL_TRACK_Y) && rti->UsesOverlay()) {
 
		SpriteID ground = GetCustomRailSprite(rti, INVALID_TILE, RTSG_GROUND);
 
		DrawSprite(SPR_FLAT_GRASS_TILE, PAL_NONE, x, y);
 
		DrawSprite(ground + (img == SPR_RAIL_TRACK_X ? RTO_X : RTO_Y), PAL_NONE, x, y);
 
	} else {
 
		DrawSprite(img + total_offset, HasBit(img, PALETTE_MODIFIER_COLOUR) ? pal : PAL_NONE, x, y);
 
	}
 

	
 
	if (roadtype == ROADTYPE_TRAM) {
 
		DrawSprite(SPR_TRAMWAY_TRAM + (t->ground.sprite == SPR_ROAD_PAVED_STRAIGHT_X ? 1 : 0), PAL_NONE, x, y);
 
	}
 

	
 
	/* Default waypoint has no railtype specific sprites */
 
	DrawRailTileSeqInGUI(x, y, t, st == STATION_WAYPOINT ? 0 : total_offset, 0, pal);
 
}
 

	
 
static uint GetSlopeZ_Station(TileIndex tile, uint x, uint y)
 
{
 
	return GetTileMaxZ(tile);
 
}
 

	
 
static Foundation GetFoundation_Station(TileIndex tile, Slope tileh)
 
{
 
	return FlatteningFoundation(tileh);
 
}
 

	
 
static void GetTileDesc_Station(TileIndex tile, TileDesc *td)
 
{
 
	td->owner[0] = GetTileOwner(tile);
 
	if (IsDriveThroughStopTile(tile)) {
 
		Owner road_owner = INVALID_OWNER;
 
		Owner tram_owner = INVALID_OWNER;
 
		RoadTypes rts = GetRoadTypes(tile);
 
		if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
 
		if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
 

	
 
		/* Is there a mix of owners? */
 
		if ((tram_owner != INVALID_OWNER && tram_owner != td->owner[0]) ||
 
				(road_owner != INVALID_OWNER && road_owner != td->owner[0])) {
 
			uint i = 1;
 
			if (road_owner != INVALID_OWNER) {
 
				td->owner_type[i] = STR_LAND_AREA_INFORMATION_ROAD_OWNER;
 
				td->owner[i] = road_owner;
 
				i++;
 
			}
 
			if (tram_owner != INVALID_OWNER) {
 
				td->owner_type[i] = STR_LAND_AREA_INFORMATION_TRAM_OWNER;
 
				td->owner[i] = tram_owner;
 
			}
 
		}
 
	}
 
	td->build_date = BaseStation::GetByTile(tile)->build_date;
 

	
 
	if (HasStationTileRail(tile)) {
 
		const StationSpec *spec = GetStationSpec(tile);
 

	
 
		if (spec != NULL) {
 
			td->station_class = GetStationClassName(spec->sclass);
 
			td->station_name  = spec->name;
 

	
 
			if (spec->grffile != NULL) {
 
				const GRFConfig *gc = GetGRFConfig(spec->grffile->grfid);
 
				td->grf = gc->GetName();
 
			}
 
		}
 
	}
 

	
 
	if (IsAirport(tile)) {
 
		const AirportTileSpec *ats = AirportTileSpec::Get(GetAirportGfx(tile));
 
		td->airport_tile_name = ats->name;
 

	
 
		if (ats->grf_prop.grffile != NULL) {
 
			const GRFConfig *gc = GetGRFConfig(ats->grf_prop.grffile->grfid);
 
			td->grf = gc->GetName();
 
		}
 
	}
 

	
 
	StringID str;
 
	switch (GetStationType(tile)) {
 
		default: NOT_REACHED();
 
		case STATION_RAIL:     str = STR_LAI_STATION_DESCRIPTION_RAILROAD_STATION; break;
 
		case STATION_AIRPORT:
 
			str = (IsHangar(tile) ? STR_LAI_STATION_DESCRIPTION_AIRCRAFT_HANGAR : STR_LAI_STATION_DESCRIPTION_AIRPORT);
 
			break;
 
		case STATION_TRUCK:    str = STR_LAI_STATION_DESCRIPTION_TRUCK_LOADING_AREA; break;
 
		case STATION_BUS:      str = STR_LAI_STATION_DESCRIPTION_BUS_STATION; break;
 
		case STATION_OILRIG:   str = STR_INDUSTRY_NAME_OIL_RIG; break;
 
		case STATION_DOCK:     str = STR_LAI_STATION_DESCRIPTION_SHIP_DOCK; break;
 
		case STATION_BUOY:     str = STR_LAI_STATION_DESCRIPTION_BUOY; break;
 
		case STATION_WAYPOINT: str = STR_LAI_STATION_DESCRIPTION_WAYPOINT; break;
 
	}
 
	td->str = str;
 
}
 

	
 

	
 
static TrackStatus GetTileTrackStatus_Station(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
 
{
 
	TrackBits trackbits = TRACK_BIT_NONE;
 

	
 
	switch (mode) {
 
		case TRANSPORT_RAIL:
 
			if (HasStationRail(tile) && !IsStationTileBlocked(tile)) {
 
				trackbits = TrackToTrackBits(GetRailStationTrack(tile));
 
			}
 
			break;
 

	
 
		case TRANSPORT_WATER:
 
			/* buoy is coded as a station, it is always on open water */
 
			if (IsBuoy(tile)) {
 
				trackbits = TRACK_BIT_ALL;
 
				/* remove tracks that connect NE map edge */
 
				if (TileX(tile) == 0) trackbits &= ~(TRACK_BIT_X | TRACK_BIT_UPPER | TRACK_BIT_RIGHT);
 
				/* remove tracks that connect NW map edge */
 
				if (TileY(tile) == 0) trackbits &= ~(TRACK_BIT_Y | TRACK_BIT_LEFT | TRACK_BIT_UPPER);
 
			}
 
			break;
 

	
 
		case TRANSPORT_ROAD:
 
			if ((GetRoadTypes(tile) & sub_mode) != 0 && IsRoadStop(tile)) {
 
				DiagDirection dir = GetRoadStopDir(tile);
 
				Axis axis = DiagDirToAxis(dir);
 

	
 
				if (side != INVALID_DIAGDIR) {
 
					if (axis != DiagDirToAxis(side) || (IsStandardRoadStopTile(tile) && dir != side)) break;
 
				}
 

	
 
				trackbits = AxisToTrackBits(axis);
 
			}
 
			break;
 

	
 
		default:
 
			break;
 
	}
 

	
 
	return CombineTrackStatus(TrackBitsToTrackdirBits(trackbits), TRACKDIR_BIT_NONE);
 
}
 

	
 

	
 
static void TileLoop_Station(TileIndex tile)
 
{
 
	/* FIXME -- GetTileTrackStatus_Station -> animated stationtiles
 
	 * hardcoded.....not good */
 
	switch (GetStationType(tile)) {
 
		case STATION_AIRPORT:
 
			AirportTileAnimationTrigger(Station::GetByTile(tile), tile, AAT_TILELOOP);
 
			break;
 

	
 
		case STATION_DOCK:
 
			if (GetTileSlope(tile, NULL) != SLOPE_FLAT) break; // only handle water part
 
		/* FALL THROUGH */
 
		case STATION_OILRIG: //(station part)
 
		case STATION_BUOY:
 
			TileLoop_Water(tile);
 
			break;
 

	
 
		default: break;
 
	}
 
}
 

	
 

	
 
static void AnimateTile_Station(TileIndex tile)
 
{
 
	if (HasStationRail(tile)) {
 
		AnimateStationTile(tile);
 
		return;
 
	}
 

	
 
	if (IsAirport(tile)) {
 
		const AirportTileSpec *ats = AirportTileSpec::Get(GetStationGfx(tile));
 
		uint16 mask = (1 << ats->animation_speed) - 1;
 
		if (ats->animation_info != 0xFFFF && (_tick_counter & mask) == 0) {
 
			uint8 next_frame = GetStationAnimationFrame(tile) + 1;
 
			if (next_frame > GB(ats->animation_info, 0, 8)) next_frame = 0;
 
			SetStationAnimationFrame(tile, next_frame);
 
			MarkTileDirtyByTile(tile);
 
		}
 
	}
 
}
 

	
 

	
 
static bool ClickTile_Station(TileIndex tile)
 
{
 
	const BaseStation *st = BaseStation::GetByTile(tile);
 

	
 
	if (st->facilities & FACIL_WAYPOINT) {
 
		ShowWaypointWindow(Waypoint::From(st));
 
	} else if (IsHangar(tile)) {
 
		ShowDepotWindow(tile, VEH_AIRCRAFT);
 
	} else {
 
		ShowStationViewWindow(st->index);
 
	}
 
	return true;
 
}
 

	
 
static VehicleEnterTileStatus VehicleEnter_Station(Vehicle *v, TileIndex tile, int x, int y)
 
{
 
	if (v->type == VEH_TRAIN) {
 
		StationID station_id = GetStationIndex(tile);
 
		if (!v->current_order.ShouldStopAtStation(v, station_id)) return VETSB_CONTINUE;
 
		if (!IsRailStation(tile) || !Train::From(v)->IsFrontEngine()) return VETSB_CONTINUE;
 

	
 
		int station_ahead;
 
		int station_length;
 
		int stop = GetTrainStopLocation(station_id, tile, Train::From(v), &station_ahead, &station_length);
 

	
 
		/* Stop whenever that amount of station ahead + the distance from the
 
		 * begin of the platform to the stop location is longer than the length
 
		 * of the platform. Station ahead 'includes' the current tile where the
 
		 * vehicle is on, so we need to substract that. */
 
		if (!IsInsideBS(stop + station_ahead, station_length, TILE_SIZE)) return VETSB_CONTINUE;
 

	
 
		DiagDirection dir = DirToDiagDir(v->direction);
 

	
 
		x &= 0xF;
 
		y &= 0xF;
 

	
 
		if (DiagDirToAxis(dir) != AXIS_X) Swap(x, y);
 
		if (y == TILE_SIZE / 2) {
 
			if (dir != DIAGDIR_SE && dir != DIAGDIR_SW) x = TILE_SIZE - 1 - x;
 
			stop &= TILE_SIZE - 1;
 

	
 
			if (x == stop) return VETSB_ENTERED_STATION | (VehicleEnterTileStatus)(station_id << VETS_STATION_ID_OFFSET); // enter station
 
			if (x < stop) {
 
				uint16 spd;
 

	
 
				v->vehstatus |= VS_TRAIN_SLOWING;
 
				spd = max(0, (stop - x) * 20 - 15);
 
				if (spd < v->cur_speed) v->cur_speed = spd;
 
			}
 
		}
 
	} else if (v->type == VEH_ROAD) {
 
		RoadVehicle *rv = RoadVehicle::From(v);
 
		if (rv->state < RVSB_IN_ROAD_STOP && !IsReversingRoadTrackdir((Trackdir)rv->state) && rv->frame == 0) {
 
			if (IsRoadStop(tile) && rv->IsRoadVehFront()) {
 
				/* Attempt to allocate a parking bay in a road stop */
 
				return RoadStop::GetByTile(tile, GetRoadStopType(tile))->Enter(rv) ? VETSB_CONTINUE : VETSB_CANNOT_ENTER;
 
			}
 
		}
 
	}
 

	
 
	return VETSB_CONTINUE;
 
}
 

	
 
/**
 
 * This function is called for each station once every 250 ticks.
 
 * Not all stations will get the tick at the same time.
 
 * @param st the station receiving the tick.
 
 * @return true if the station is still valid (wasn't deleted)
 
 */
 
static bool StationHandleBigTick(BaseStation *st)
 
{
 
	if (!st->IsInUse() && ++st->delete_ctr >= 8) {
 
		delete st;
 
		return false;
 
	}
 

	
 
	if ((st->facilities & FACIL_WAYPOINT) == 0) UpdateStationAcceptance(Station::From(st), true);
 

	
 
	return true;
 
}
 

	
 
static inline void byte_inc_sat(byte *p)
 
{
 
	byte b = *p + 1;
 
	if (b != 0) *p = b;
 
}
 

	
 
static void UpdateStationRating(Station *st)
 
{
 
	bool waiting_changed = false;
 

	
 
	byte_inc_sat(&st->time_since_load);
 
	byte_inc_sat(&st->time_since_unload);
 

	
 
	const CargoSpec *cs;
 
	FOR_ALL_CARGOSPECS(cs) {
 
		GoodsEntry *ge = &st->goods[cs->Index()];
 
		/* Slowly increase the rating back to his original level in the case we
 
		 *  didn't deliver cargo yet to this station. This happens when a bribe
 
		 *  failed while you didn't moved that cargo yet to a station. */
 
		if (!HasBit(ge->acceptance_pickup, GoodsEntry::PICKUP) && ge->rating < INITIAL_STATION_RATING) {
 
			ge->rating++;
 
		}
 

	
 
		/* Only change the rating if we are moving this cargo */
 
		if (HasBit(ge->acceptance_pickup, GoodsEntry::PICKUP)) {
 
			byte_inc_sat(&ge->days_since_pickup);
 

	
 
			bool skip = false;
 
			int rating = 0;
 
			uint waiting = ge->cargo.Count();
 

	
 
			if (HasBit(cs->callback_mask, CBM_CARGO_STATION_RATING_CALC)) {
 
				/* Perform custom station rating. If it succeeds the speed, days in transit and
 
				 * waiting cargo ratings must not be executed. */
 

	
 
				/* NewGRFs expect last speed to be 0xFF when no vehicle has arrived yet. */
 
				uint last_speed = ge->last_speed;
 
				if (last_speed == 0) last_speed = 0xFF;
 

	
 
				uint32 var18 = min(ge->days_since_pickup, 0xFF) | (min(waiting, 0xFFFF) << 8) | (min(last_speed, 0xFF) << 24);
 
				/* Convert to the 'old' vehicle types */
 
				uint32 var10 = (st->last_vehicle_type == VEH_INVALID) ? 0x0 : (st->last_vehicle_type + 0x10);
 
				uint16 callback = GetCargoCallback(CBID_CARGO_STATION_RATING_CALC, var10, var18, cs);
 
				if (callback != CALLBACK_FAILED) {
 
					skip = true;
 
					rating = GB(callback, 0, 14);
 

	
 
					/* Simulate a 15 bit signed value */
 
					if (HasBit(callback, 14)) rating -= 0x4000;
 
				}
 
			}
 

	
 
			if (!skip) {
 
				int b = ge->last_speed - 85;
 
				if (b >= 0) rating += b >> 2;
 

	
 
				byte days = ge->days_since_pickup;
 
				if (st->last_vehicle_type == VEH_SHIP) days >>= 2;
 
				(days > 21) ||
 
				(rating += 25, days > 12) ||
 
				(rating += 25, days > 6) ||
 
				(rating += 45, days > 3) ||
 
				(rating += 35, true);
 

	
 
				(rating -= 90, waiting > 1500) ||
 
				(rating += 55, waiting > 1000) ||
 
				(rating += 35, waiting > 600) ||
 
				(rating += 10, waiting > 300) ||
 
				(rating += 20, waiting > 100) ||
 
				(rating += 10, true);
 
			}
 

	
 
			if (Company::IsValidID(st->owner) && HasBit(st->town->statues, st->owner)) rating += 26;
 

	
 
			byte age = ge->last_age;
 
			(age >= 3) ||
 
			(rating += 10, age >= 2) ||
 
			(rating += 10, age >= 1) ||
 
			(rating += 13, true);
 

	
 
			{
 
				int or_ = ge->rating; // old rating
 

	
 
				/* only modify rating in steps of -2, -1, 0, 1 or 2 */
0 comments (0 inline, 0 general)