Changeset - r8964:d804b28173fd
[Not reviewed]
master
0 2 0
smatz - 16 years ago 2008-04-17 20:03:28
smatz@openttd.org
(svn r12756) -Cleanup: variable scope and coding style in station*
2 files changed with 97 insertions and 104 deletions:
0 comments (0 inline, 0 general)
src/station_cmd.cpp
Show inline comments
 
@@ -25,141 +25,141 @@
 
#include "newgrf_callbacks.h"
 
#include "newgrf_station.h"
 
#include "yapf/yapf.h"
 
#include "misc/autoptr.hpp"
 
#include "road_type.h"
 
#include "road_internal.h" /* For drawing catenary/checking road removal */
 
#include "cargotype.h"
 
#include "variables.h"
 
#include "autoslope.h"
 
#include "transparency.h"
 
#include "water.h"
 
#include "station_gui.h"
 
#include "strings_func.h"
 
#include "functions.h"
 
#include "window_func.h"
 
#include "date_func.h"
 
#include "vehicle_func.h"
 
#include "string_func.h"
 
#include "signal_func.h"
 
#include "oldpool_func.h"
 

	
 
#include "table/sprites.h"
 
#include "table/strings.h"
 

	
 
DEFINE_OLD_POOL_GENERIC(Station, Station)
 
DEFINE_OLD_POOL_GENERIC(RoadStop, RoadStop)
 

	
 

	
 
/**
 
 * Check whether the given tile is a hangar.
 
 * @param t the tile to of whether it is a hangar.
 
 * @pre IsTileType(t, MP_STATION)
 
 * @return true if and only if the tile is a hangar.
 
 */
 
bool IsHangar(TileIndex t)
 
{
 
	assert(IsTileType(t, MP_STATION));
 

	
 
	const Station *st = GetStationByTile(t);
 
	const AirportFTAClass *apc = st->Airport();
 

	
 
	for (uint i = 0; i < apc->nof_depots; i++) {
 
		if (st->airport_tile + ToTileIndexDiff(apc->airport_depots[i]) == t) return true;
 
	}
 

	
 
	return false;
 
}
 

	
 
RoadStop* GetRoadStopByTile(TileIndex tile, RoadStopType type)
 
RoadStop *GetRoadStopByTile(TileIndex tile, RoadStopType type)
 
{
 
	const Station* st = GetStationByTile(tile);
 
	const Station *st = GetStationByTile(tile);
 

	
 
	for (RoadStop *rs = st->GetPrimaryRoadStop(type);; rs = rs->next) {
 
		if (rs->xy == tile) return rs;
 
		assert(rs->next != NULL);
 
	}
 
}
 

	
 

	
 
static uint GetNumRoadStopsInStation(const Station* st, RoadStopType type)
 
static uint GetNumRoadStopsInStation(const Station *st, RoadStopType type)
 
{
 
	uint num = 0;
 

	
 
	assert(st != NULL);
 
	for (const RoadStop *rs = st->GetPrimaryRoadStop(type); rs != NULL; rs = rs->next) {
 
		num++;
 
	}
 

	
 
	return num;
 
}
 

	
 

	
 
/** Calculate the radius of the station. Basicly it is the biggest
 
 *  radius that is available within the station
 
 * @param st Station to query
 
 * @return the so calculated radius
 
 */
 
static uint FindCatchmentRadius(const Station* st)
 
static uint FindCatchmentRadius(const Station *st)
 
{
 
	uint ret = CA_NONE;
 

	
 
	if (st->bus_stops   != NULL) ret = max<uint>(ret, CA_BUS);
 
	if (st->truck_stops != NULL) ret = max<uint>(ret, CA_TRUCK);
 
	if (st->train_tile  != 0)    ret = max<uint>(ret, CA_TRAIN);
 
	if (st->dock_tile   != 0)    ret = max<uint>(ret, CA_DOCK);
 
	if (st->airport_tile)        ret = max<uint>(ret, st->Airport()->catchment);
 

	
 
	return ret;
 
}
 

	
 
#define CHECK_STATIONS_ERR ((Station*)-1)
 

	
 
static Station* GetStationAround(TileIndex tile, int w, int h, StationID closest_station)
 
static Station *GetStationAround(TileIndex tile, int w, int h, StationID closest_station)
 
{
 
	/* check around to see if there's any stations there */
 
	BEGIN_TILE_LOOP(tile_cur, w + 2, h + 2, tile - TileDiffXY(1, 1))
 
		if (IsTileType(tile_cur, MP_STATION)) {
 
			StationID t = GetStationIndex(tile_cur);
 

	
 
			if (closest_station == INVALID_STATION) {
 
				closest_station = t;
 
			} else if (closest_station != t) {
 
				_error_message = STR_3006_ADJOINS_MORE_THAN_ONE_EXISTING;
 
				return CHECK_STATIONS_ERR;
 
			}
 
		}
 
	END_TILE_LOOP(tile_cur, w + 2, h + 2, tile - TileDiffXY(1, 1))
 
	return (closest_station == INVALID_STATION) ? NULL : GetStation(closest_station);
 
}
 

	
 
/**
 
 * Function to check whether the given tile matches some criterion.
 
 * @param tile the tile to check
 
 * @return true if it matches, false otherwise
 
 */
 
typedef bool (*CMSAMatcher)(TileIndex tile);
 

	
 
/**
 
 * Counts the numbers of tiles matching a specific type in the area around
 
 * @param tile the center tile of the 'count area'
 
 * @param type the type of tile searched for
 
 * @param industry when type == MP_INDUSTRY, the type of the industry,
 
 *                 in all other cases this parameter is ignored
 
 * @return the result the noumber of matching tiles around
 
 */
 
static int CountMapSquareAround(TileIndex tile, CMSAMatcher cmp)
 
{
 
	int num = 0;
 

	
 
	for (int dx = -3; dx <= 3; dx++) {
 
		for (int dy = -3; dy <= 3; dy++) {
 
			if (cmp(TILE_MASK(tile + TileDiffXY(dx, dy)))) num++;
 
		}
 
	}
 

	
 
	return num;
 
}
 

	
 
/**
 
 * Check whether the tile is a mine.
 
 * @param tile the tile to investigate.
 
@@ -204,233 +204,233 @@ static bool CMSATree(TileIndex tile)
 
}
 

	
 
/**
 
 * Check whether the tile is a forest.
 
 * @param tile the tile to investigate.
 
 * @return true if and only if the tile is a mine
 
 */
 
static bool CMSAForest(TileIndex tile)
 
{
 
	/* No industry */
 
	if (!IsTileType(tile, MP_INDUSTRY)) return false;
 

	
 
	const Industry *ind = GetIndustryByTile(tile);
 

	
 
	/* No extractive industry */
 
	if ((GetIndustrySpec(ind->type)->life_type & INDUSTRYLIFE_ORGANIC) == 0) return false;
 

	
 
	for (uint i = 0; i < lengthof(ind->produced_cargo); i++) {
 
		/* The industry produces wood. */
 
		if (ind->produced_cargo[i] != CT_INVALID && GetCargo(ind->produced_cargo[i])->label == 'WOOD') return true;
 
	}
 

	
 
	return false;
 
}
 

	
 
#define M(x) ((x) - STR_SV_STNAME)
 

	
 
enum StationNaming {
 
	STATIONNAMING_RAIL = 0,
 
	STATIONNAMING_ROAD = 0,
 
	STATIONNAMING_AIRPORT,
 
	STATIONNAMING_OILRIG,
 
	STATIONNAMING_DOCK,
 
	STATIONNAMING_BUOY,
 
	STATIONNAMING_HELIPORT,
 
};
 

	
 
static bool GenerateStationName(Station *st, TileIndex tile, int flag)
 
{
 
	static const uint32 _gen_station_name_bits[] = {
 
		0,                                      /* 0 */
 
		1 << M(STR_SV_STNAME_AIRPORT),          /* 1 */
 
		1 << M(STR_SV_STNAME_OILFIELD),         /* 2 */
 
		1 << M(STR_SV_STNAME_DOCKS),            /* 3 */
 
		0x1FF << M(STR_SV_STNAME_BUOY_1),       /* 4 */
 
		1 << M(STR_SV_STNAME_HELIPORT),         /* 5 */
 
	};
 

	
 
	Town *t = st->town;
 
	uint32 free_names = (uint32)-1;
 
	int found;
 
	unsigned long tmp;
 
	const Town *t = st->town;
 
	uint32 free_names = UINT32_MAX;
 

	
 
	{
 
		Station *s;
 
		const Station *s;
 

	
 
		FOR_ALL_STATIONS(s) {
 
			if (s != st && s->town == t) {
 
				uint str = M(s->string_id);
 
				if (str <= 0x20) {
 
					if (str == M(STR_SV_STNAME_FOREST))
 
					if (str == M(STR_SV_STNAME_FOREST)) {
 
						str = M(STR_SV_STNAME_WOODS);
 
					}
 
					ClrBit(free_names, str);
 
				}
 
			}
 
		}
 
	}
 

	
 
	/* check default names */
 
	tmp = free_names & _gen_station_name_bits[flag];
 
	uint32 tmp = free_names & _gen_station_name_bits[flag];
 
	int found;
 
	if (tmp != 0) {
 
		found = FindFirstBit(tmp);
 
		goto done;
 
	}
 

	
 
	/* check mine? */
 
	if (HasBit(free_names, M(STR_SV_STNAME_MINES))) {
 
		if (CountMapSquareAround(tile, CMSAMine) >= 2) {
 
			found = M(STR_SV_STNAME_MINES);
 
			goto done;
 
		}
 
	}
 

	
 
	/* check close enough to town to get central as name? */
 
	if (DistanceMax(tile, t->xy) < 8) {
 
		found = M(STR_SV_STNAME);
 
		if (HasBit(free_names, M(STR_SV_STNAME))) goto done;
 

	
 
		found = M(STR_SV_STNAME_CENTRAL);
 
		if (HasBit(free_names, M(STR_SV_STNAME_CENTRAL))) goto done;
 
	}
 

	
 
	/* Check lakeside */
 
	if (HasBit(free_names, M(STR_SV_STNAME_LAKESIDE)) &&
 
			DistanceFromEdge(tile) < 20 &&
 
			CountMapSquareAround(tile, CMSAWater) >= 5) {
 
		found = M(STR_SV_STNAME_LAKESIDE);
 
		goto done;
 
	}
 

	
 
	/* Check woods */
 
	if (HasBit(free_names, M(STR_SV_STNAME_WOODS)) && (
 
				CountMapSquareAround(tile, CMSATree) >= 8 ||
 
				CountMapSquareAround(tile, CMSAForest) >= 2)
 
			) {
 
		found = _opt.landscape == LT_TROPIC ?
 
			M(STR_SV_STNAME_FOREST) : M(STR_SV_STNAME_WOODS);
 
		goto done;
 
	}
 

	
 
	/* check elevation compared to town */
 
	{
 
		uint z = GetTileZ(tile);
 
		uint z2 = GetTileZ(t->xy);
 
		if (z < z2) {
 
			found = M(STR_SV_STNAME_VALLEY);
 
			if (HasBit(free_names, M(STR_SV_STNAME_VALLEY))) goto done;
 
		} else if (z > z2) {
 
			found = M(STR_SV_STNAME_HEIGHTS);
 
			if (HasBit(free_names, M(STR_SV_STNAME_HEIGHTS))) goto done;
 
		}
 
	}
 

	
 
	/* check direction compared to town */
 
	{
 
		static const int8 _direction_and_table[] = {
 
			~( (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_EAST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
 
			~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
 
			~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_EAST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
 
			~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_EAST)) ),
 
		};
 

	
 
		free_names &= _direction_and_table[
 
			(TileX(tile) < TileX(t->xy)) +
 
			(TileY(tile) < TileY(t->xy)) * 2];
 
	}
 

	
 
	tmp = free_names & ((1 << 1) | (1 << 2) | (1 << 3) | (1 << 4) | (1 << 6) | (1 << 7) | (1 << 12) | (1 << 26) | (1 << 27) | (1 << 28) | (1 << 29) | (1 << 30));
 
	found = (tmp == 0) ? M(STR_SV_STNAME_FALLBACK) : FindFirstBit(tmp);
 

	
 
done:
 
	st->string_id = found + STR_SV_STNAME;
 
	return true;
 
}
 
#undef M
 

	
 
static Station* GetClosestStationFromTile(TileIndex tile)
 
static Station *GetClosestStationFromTile(TileIndex tile)
 
{
 
	uint threshold = 8;
 
	Station* best_station = NULL;
 
	Station* st;
 
	Station *best_station = NULL;
 
	Station *st;
 

	
 
	FOR_ALL_STATIONS(st) {
 
		if (st->facilities == 0 && st->owner == _current_player) {
 
			uint cur_dist = DistanceManhattan(tile, st->xy);
 

	
 
			if (cur_dist < threshold) {
 
				threshold = cur_dist;
 
				best_station = st;
 
			}
 
		}
 
	}
 

	
 
	return best_station;
 
}
 

	
 
/** Update the virtual coords needed to draw the station sign.
 
 * @param st Station to update for.
 
 */
 
static void UpdateStationVirtCoord(Station *st)
 
{
 
	Point pt = RemapCoords2(TileX(st->xy) * TILE_SIZE, TileY(st->xy) * TILE_SIZE);
 

	
 
	pt.y -= 32;
 
	if (st->facilities & FACIL_AIRPORT && st->airport_type == AT_OILRIG) pt.y -= 16;
 

	
 
	SetDParam(0, st->index);
 
	SetDParam(1, st->facilities);
 
	UpdateViewportSignPos(&st->sign, pt.x, pt.y, STR_305C_0);
 
}
 

	
 
/** Update the virtual coords needed to draw the station sign for all stations. */
 
void UpdateAllStationVirtCoord()
 
{
 
	Station* st;
 
	Station *st;
 

	
 
	FOR_ALL_STATIONS(st) {
 
		UpdateStationVirtCoord(st);
 
	}
 
}
 

	
 
/**
 
 * Update the station virt coords while making the modified parts dirty.
 
 *
 
 * This function updates the virt coords and mark the modified parts as dirty
 
 *
 
 * @param st The station to update the virt coords
 
 * @ingroup dirty
 
 */
 
static void UpdateStationVirtCoordDirty(Station *st)
 
{
 
	st->MarkDirty();
 
	UpdateStationVirtCoord(st);
 
	st->MarkDirty();
 
}
 

	
 
/** Get a mask of the cargo types that the station accepts.
 
 * @param st Station to query
 
 * @return the expected mask
 
 */
 
static uint GetAcceptanceMask(const Station *st)
 
{
 
	uint mask = 0;
 

	
 
	for (CargoID i = 0; i < NUM_CARGO; i++) {
 
		if (HasBit(st->goods[i].acceptance_pickup, GoodsEntry::ACCEPTANCE)) mask |= 1 << i;
 
	}
 
	return mask;
 
}
 

	
 
/** Items contains the two cargo names that are to be accepted or rejected.
 
 * msg is the string id of the message to display.
 
 */
 
static void ShowRejectOrAcceptNews(const Station *st, uint num_items, CargoID *cargo, StringID msg)
 
{
 
	for (uint i = 0; i < num_items; i++) {
 
		SetDParam(i + 1, GetCargo(cargo[i])->name);
 
	}
 

	
 
	SetDParam(0, st->index);
 
	AddNewsItem(msg, NM_SMALL, NF_VIEWPORT | NF_TILE, NT_ACCEPTANCE, DNC_NONE, st->xy, 0);
 
}
 

	
 
@@ -487,183 +487,179 @@ void GetProductionAroundTiles(AcceptedCa
 
* Get a list of the cargo types that are accepted around the tile.
 
* @param accepts: Destination array of accepted cargo
 
* @param tile: Center of the search area
 
* @param w: Width of the center
 
* @param h: Height of the center
 
* @param rad: Radius of the rectangular search area
 
*/
 
void GetAcceptanceAroundTiles(AcceptedCargo accepts, TileIndex tile,
 
	int w, int h, int rad)
 
{
 
	memset(accepts, 0, sizeof(AcceptedCargo));
 

	
 
	int x = TileX(tile);
 
	int y = TileY(tile);
 

	
 
	/* expand the region by rad tiles on each side
 
	 * while making sure that we remain inside the board. */
 
	int x2 = min(x + w + rad, MapSizeX());
 
	int y2 = min(y + h + rad, MapSizeY());
 
	int x1 = max(x - rad, 0);
 
	int y1 = max(y - rad, 0);
 

	
 
	assert(x1 < x2);
 
	assert(y1 < y2);
 
	assert(w > 0);
 
	assert(h > 0);
 

	
 
	for (int yc = y1; yc != y2; yc++) {
 
		for (int xc = x1; xc != x2; xc++) {
 
			TileIndex tile = TileXY(xc, yc);
 

	
 
			if (!IsTileType(tile, MP_STATION)) {
 
				AcceptedCargo ac;
 

	
 
				GetAcceptedCargo(tile, ac);
 
				for (uint i = 0; i < lengthof(ac); ++i) accepts[i] += ac[i];
 
			}
 
		}
 
	}
 
}
 

	
 
struct ottd_Rectangle {
 
	uint min_x;
 
	uint min_y;
 
	uint max_x;
 
	uint max_y;
 
};
 

	
 
static inline void MergePoint(ottd_Rectangle* rect, TileIndex tile)
 
static inline void MergePoint(ottd_Rectangle *rect, TileIndex tile)
 
{
 
	uint x = TileX(tile);
 
	uint y = TileY(tile);
 

	
 
	if (rect->min_x > x) rect->min_x = x;
 
	if (rect->min_y > y) rect->min_y = y;
 
	if (rect->max_x < x) rect->max_x = x;
 
	if (rect->max_y < y) rect->max_y = y;
 
}
 

	
 
/** Update the acceptance for a station.
 
 * @param st Station to update
 
 * @param show_msg controls whether to display a message that acceptance was changed.
 
 */
 
static void UpdateStationAcceptance(Station *st, bool show_msg)
 
{
 
	/* Don't update acceptance for a buoy */
 
	if (st->IsBuoy()) return;
 

	
 
	ottd_Rectangle rect;
 
	rect.min_x = MapSizeX();
 
	rect.min_y = MapSizeY();
 
	rect.max_x = 0;
 
	rect.max_y = 0;
 

	
 
	/* old accepted goods types */
 
	uint old_acc = GetAcceptanceMask(st);
 

	
 
	/* Put all the tiles that span an area in the table. */
 
	if (st->train_tile != 0) {
 
		MergePoint(&rect, st->train_tile);
 
		MergePoint(&rect,
 
			st->train_tile + TileDiffXY(st->trainst_w - 1, st->trainst_h - 1)
 
		);
 
		MergePoint(&rect, st->train_tile + TileDiffXY(st->trainst_w - 1, st->trainst_h - 1));
 
	}
 

	
 
	if (st->airport_tile != 0) {
 
		const AirportFTAClass* afc = st->Airport();
 
		const AirportFTAClass *afc = st->Airport();
 

	
 
		MergePoint(&rect, st->airport_tile);
 
		MergePoint(&rect,
 
			st->airport_tile + TileDiffXY(afc->size_x - 1, afc->size_y - 1)
 
		);
 
		MergePoint(&rect, st->airport_tile + TileDiffXY(afc->size_x - 1, afc->size_y - 1));
 
	}
 

	
 
	if (st->dock_tile != 0) MergePoint(&rect, st->dock_tile);
 

	
 
	for (const RoadStop *rs = st->bus_stops; rs != NULL; rs = rs->next) {
 
		MergePoint(&rect, rs->xy);
 
	}
 

	
 
	for (const RoadStop *rs = st->truck_stops; rs != NULL; rs = rs->next) {
 
		MergePoint(&rect, rs->xy);
 
	}
 

	
 
	/* And retrieve the acceptance. */
 
	AcceptedCargo accepts;
 
	if (rect.max_x >= rect.min_x) {
 
		GetAcceptanceAroundTiles(
 
			accepts,
 
			TileXY(rect.min_x, rect.min_y),
 
			rect.max_x - rect.min_x + 1,
 
			rect.max_y - rect.min_y + 1,
 
			_patches.modified_catchment ? FindCatchmentRadius(st) : (uint)CA_UNMODIFIED
 
		);
 
	} else {
 
		memset(accepts, 0, sizeof(accepts));
 
	}
 

	
 
	/* Adjust in case our station only accepts fewer kinds of goods */
 
	for (CargoID i = 0; i < NUM_CARGO; i++) {
 
		uint amt = min(accepts[i], 15);
 

	
 
		/* Make sure the station can accept the goods type. */
 
		bool is_passengers = IsCargoInClass(i, CC_PASSENGERS);
 
		if ((!is_passengers && !(st->facilities & (byte)~FACIL_BUS_STOP)) ||
 
				(is_passengers && !(st->facilities & (byte)~FACIL_TRUCK_STOP)))
 
				(is_passengers && !(st->facilities & (byte)~FACIL_TRUCK_STOP))) {
 
			amt = 0;
 
		}
 

	
 
		SB(st->goods[i].acceptance_pickup, GoodsEntry::ACCEPTANCE, 1, amt >= 8);
 
	}
 

	
 
	/* Only show a message in case the acceptance was actually changed. */
 
	uint new_acc = GetAcceptanceMask(st);
 
	if (old_acc == new_acc)
 
		return;
 
	if (old_acc == new_acc) return;
 

	
 
	/* show a message to report that the acceptance was changed? */
 
	if (show_msg && st->owner == _local_player && st->facilities) {
 
		/* List of accept and reject strings for different number of
 
		 * cargo types */
 
		static const StringID accept_msg[] = {
 
			STR_3040_NOW_ACCEPTS,
 
			STR_3041_NOW_ACCEPTS_AND,
 
		};
 
		static const StringID reject_msg[] = {
 
			STR_303E_NO_LONGER_ACCEPTS,
 
			STR_303F_NO_LONGER_ACCEPTS_OR,
 
		};
 

	
 
		/* Array of accepted and rejected cargo types */
 
		CargoID accepts[2] = { CT_INVALID, CT_INVALID };
 
		CargoID rejects[2] = { CT_INVALID, CT_INVALID };
 
		uint num_acc = 0;
 
		uint num_rej = 0;
 

	
 
		/* Test each cargo type to see if its acceptange has changed */
 
		for (CargoID i = 0; i < NUM_CARGO; i++) {
 
			if (HasBit(new_acc, i)) {
 
				if (!HasBit(old_acc, i) && num_acc < lengthof(accepts)) {
 
					/* New cargo is accepted */
 
					accepts[num_acc++] = i;
 
				}
 
			} else {
 
				if (HasBit(old_acc, i) && num_rej < lengthof(rejects)) {
 
					/* Old cargo is no longer accepted */
 
					rejects[num_rej++] = i;
 
				}
 
			}
 
		}
 

	
 
		/* Show news message if there are any changes */
 
		if (num_acc > 0) ShowRejectOrAcceptNews(st, num_acc, accepts, accept_msg[num_acc - 1]);
 
		if (num_rej > 0) ShowRejectOrAcceptNews(st, num_rej, rejects, reject_msg[num_rej - 1]);
 
	}
 

	
 
	/* redraw the station view since acceptance changed */
 
	InvalidateWindowWidget(WC_STATION_VIEW, st->index, SVW_ACCEPTLIST);
 
}
 

	
 
static void UpdateStationSignCoord(Station *st)
 
{
 
	const StationRect *r = &st->rect;
 

	
 
@@ -731,97 +727,97 @@ CommandCost CheckFlatLandBelow(TileIndex
 
		}
 

	
 
		int flat_z = z;
 
		if (tileh != SLOPE_FLAT) {
 
			/* need to check so the entrance to the station is not pointing at a slope.
 
			 * This must be valid for all station tiles, as the user can remove single station tiles. */
 
			if ((HasBit(invalid_dirs, DIAGDIR_NE) && !(tileh & SLOPE_NE)) ||
 
			    (HasBit(invalid_dirs, DIAGDIR_SE) && !(tileh & SLOPE_SE)) ||
 
			    (HasBit(invalid_dirs, DIAGDIR_SW) && !(tileh & SLOPE_SW)) ||
 
			    (HasBit(invalid_dirs, DIAGDIR_NW) && !(tileh & SLOPE_NW))) {
 
				return_cmd_error(STR_0007_FLAT_LAND_REQUIRED);
 
			}
 
			cost.AddCost(_price.terraform);
 
			flat_z += TILE_HEIGHT;
 
		}
 

	
 
		/* get corresponding flat level and make sure that all parts of the station have the same level. */
 
		if (allowed_z == -1) {
 
			/* first tile */
 
			allowed_z = flat_z;
 
		} else if (allowed_z != flat_z) {
 
			return_cmd_error(STR_0007_FLAT_LAND_REQUIRED);
 
		}
 

	
 
		/* if station is set, then we have special handling to allow building on top of already existing stations.
 
		 * so station points to INVALID_STATION if we can build on any station.
 
		 * Or it points to a station if we're only allowed to build on exactly that station. */
 
		if (station != NULL && IsTileType(tile_cur, MP_STATION)) {
 
			if (!IsRailwayStation(tile_cur)) {
 
				return ClearTile_Station(tile_cur, DC_AUTO); // get error message
 
			} else {
 
				StationID st = GetStationIndex(tile_cur);
 
				if (*station == INVALID_STATION) {
 
					*station = st;
 
				} else if (*station != st) {
 
					return_cmd_error(STR_3006_ADJOINS_MORE_THAN_ONE_EXISTING);
 
				}
 
			}
 
		} else if (check_clear) {
 
			CommandCost ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
 
			if (CmdFailed(ret)) return ret;
 
			cost.AddCost(ret);
 
		}
 
	} END_TILE_LOOP(tile_cur, w, h, tile)
 

	
 
	return cost;
 
}
 

	
 
static bool CanExpandRailroadStation(const Station* st, uint* fin, Axis axis)
 
static bool CanExpandRailroadStation(const Station *st, uint *fin, Axis axis)
 
{
 
	uint curw = st->trainst_w;
 
	uint curh = st->trainst_h;
 
	TileIndex tile = fin[0];
 
	uint w = fin[1];
 
	uint h = fin[2];
 

	
 
	if (_patches.nonuniform_stations) {
 
		/* determine new size of train station region.. */
 
		int x = min(TileX(st->train_tile), TileX(tile));
 
		int y = min(TileY(st->train_tile), TileY(tile));
 
		curw = max(TileX(st->train_tile) + curw, TileX(tile) + w) - x;
 
		curh = max(TileY(st->train_tile) + curh, TileY(tile) + h) - y;
 
		tile = TileXY(x, y);
 
	} else {
 
		/* do not allow modifying non-uniform stations,
 
		 * the uniform-stations code wouldn't handle it well */
 
		BEGIN_TILE_LOOP(t, st->trainst_w, st->trainst_h, st->train_tile)
 
			if (!st->TileBelongsToRailStation(t)) { // there may be adjoined station
 
				_error_message = STR_NONUNIFORM_STATIONS_DISALLOWED;
 
				return false;
 
			}
 
		END_TILE_LOOP(t, st->trainst_w, st->trainst_h, st->train_tile)
 

	
 
		/* check so the orientation is the same */
 
		if (GetRailStationAxis(st->train_tile) != axis) {
 
			_error_message = STR_NONUNIFORM_STATIONS_DISALLOWED;
 
			return false;
 
		}
 

	
 
		/* check if the new station adjoins the old station in either direction */
 
		if (curw == w && st->train_tile == tile + TileDiffXY(0, h)) {
 
			/* above */
 
			curh += h;
 
		} else if (curw == w && st->train_tile == tile - TileDiffXY(0, curh)) {
 
			/* below */
 
			tile -= TileDiffXY(0, curh);
 
			curh += h;
 
		} else if (curh == h && st->train_tile == tile + TileDiffXY(w, 0)) {
 
			/* to the left */
 
			curw += w;
 
		} else if (curh == h && st->train_tile == tile - TileDiffXY(curw, 0)) {
 
			/* to the right */
 
			tile -= TileDiffXY(curw, 0);
 
			curw += w;
 
		} else {
 
			_error_message = STR_NONUNIFORM_STATIONS_DISALLOWED;
 
			return false;
 
@@ -854,129 +850,128 @@ static inline byte *CreateMulti(byte *la
 
	int i = n;
 
	do *layout++ = b; while (--i);
 
	if (n > 4) {
 
		layout[0 - n] = 0;
 
		layout[n - 1 - n] = 0;
 
	}
 
	return layout;
 
}
 

	
 
static void GetStationLayout(byte *layout, int numtracks, int plat_len, const StationSpec *statspec)
 
{
 
	if (statspec != NULL && statspec->lengths >= plat_len &&
 
			statspec->platforms[plat_len - 1] >= numtracks &&
 
			statspec->layouts[plat_len - 1][numtracks - 1]) {
 
		/* Custom layout defined, follow it. */
 
		memcpy(layout, statspec->layouts[plat_len - 1][numtracks - 1],
 
			plat_len * numtracks);
 
		return;
 
	}
 

	
 
	if (plat_len == 1) {
 
		CreateSingle(layout, numtracks);
 
	} else {
 
		if (numtracks & 1) layout = CreateSingle(layout, plat_len);
 
		numtracks >>= 1;
 

	
 
		while (--numtracks >= 0) {
 
			layout = CreateMulti(layout, plat_len, 4);
 
			layout = CreateMulti(layout, plat_len, 6);
 
		}
 
	}
 
}
 

	
 
/** Build railroad station
 
 * @param tile_org starting position of station dragging/placement
 
 * @param flags operation to perform
 
 * @param p1 various bitstuffed elements
 
 * - p1 = (bit  0)    - orientation (Axis)
 
 * - p1 = (bit  8-15) - number of tracks
 
 * - p1 = (bit 16-23) - platform length
 
 * - p1 = (bit 24)    - allow stations directly adjacent to other stations.
 
 * @param p2 various bitstuffed elements
 
 * - p2 = (bit  0- 3) - railtype (p2 & 0xF)
 
 * - p2 = (bit  8-15) - custom station class
 
 * - p2 = (bit 16-23) - custom station id
 
 */
 
CommandCost CmdBuildRailroadStation(TileIndex tile_org, uint32 flags, uint32 p1, uint32 p2)
 
{
 
	int w_org, h_org;
 
	CommandCost ret;
 

	
 
	/* Does the authority allow this? */
 
	if (!(flags & DC_NO_TOWN_RATING) && !CheckIfAuthorityAllows(tile_org)) return CMD_ERROR;
 
	if (!ValParamRailtype((RailType)(p2 & 0xF))) return CMD_ERROR;
 

	
 
	/* unpack parameters */
 
	Axis axis = Extract<Axis, 0>(p1);
 
	uint numtracks = GB(p1,  8, 8);
 
	uint plat_len  = GB(p1, 16, 8);
 

	
 
	int w_org, h_org;
 
	if (axis == AXIS_X) {
 
		w_org = plat_len;
 
		h_org = numtracks;
 
	} else {
 
		h_org = plat_len;
 
		w_org = numtracks;
 
	}
 

	
 
	if (h_org > _patches.station_spread || w_org > _patches.station_spread) return CMD_ERROR;
 

	
 
	/* these values are those that will be stored in train_tile and station_platforms */
 
	uint finalvalues[3];
 
	finalvalues[0] = tile_org;
 
	finalvalues[1] = w_org;
 
	finalvalues[2] = h_org;
 

	
 
	/* Make sure the area below consists of clear tiles. (OR tiles belonging to a certain rail station) */
 
	StationID est = INVALID_STATION;
 
	/* If DC_EXEC is in flag, do not want to pass it to CheckFlatLandBelow, because of a nice bug
 
	 * for detail info, see:
 
	 * https://sourceforge.net/tracker/index.php?func=detail&aid=1029064&group_id=103924&atid=636365 */
 
	ret = CheckFlatLandBelow(tile_org, w_org, h_org, flags & ~DC_EXEC, 5 << axis, _patches.nonuniform_stations ? &est : NULL);
 
	CommandCost ret = CheckFlatLandBelow(tile_org, w_org, h_org, flags & ~DC_EXEC, 5 << axis, _patches.nonuniform_stations ? &est : NULL);
 
	if (CmdFailed(ret)) return ret;
 
	CommandCost cost(EXPENSES_CONSTRUCTION, ret.GetCost() + (numtracks * _price.train_station_track + _price.train_station_length) * plat_len);
 

	
 
	Station *st = NULL;
 
	bool check_surrounding = true;
 

	
 
	if (_patches.adjacent_stations) {
 
		if (est != INVALID_STATION) {
 
			if (HasBit(p1, 24)) {
 
				/* You can't build an adjacent station over the top of one that
 
				 * already exists. */
 
				return_cmd_error(STR_MUST_REMOVE_RAILWAY_STATION_FIRST);
 
			} else {
 
				/* Extend the current station, and don't check whether it will
 
				 * be near any other stations. */
 
				st = GetStation(est);
 
				check_surrounding = false;
 
			}
 
		} else {
 
			/* There's no station here. Don't check the tiles surrounding this
 
			 * one if the player wanted to build an adjacent station. */
 
			if (HasBit(p1, 24)) check_surrounding = false;
 
		}
 
	}
 

	
 
	if (check_surrounding) {
 
		/* Make sure there are no similar stations around us. */
 
		st = GetStationAround(tile_org, w_org, h_org, est);
 
		if (st == CHECK_STATIONS_ERR) return CMD_ERROR;
 
	}
 

	
 
	/* See if there is a deleted station close to us. */
 
	if (st == NULL) st = GetClosestStationFromTile(tile_org);
 

	
 
	/* In case of new station if DC_EXEC is NOT set we still need to create the station
 
	 * to test if everything is OK. In this case we need to delete it before return. */
 
	AutoPtrT<Station> st_auto_delete;
 

	
 
	if (st != NULL) {
 
		/* Reuse an existing station. */
 
		if (st->owner != _current_player)
 
			return_cmd_error(STR_3009_TOO_CLOSE_TO_ANOTHER_STATION);
 

	
 
		if (st->train_tile != 0) {
 
			/* check if we want to expanding an already existing station? */
 
			if (_is_old_ai_player || !_patches.join_stations)
 
				return_cmd_error(STR_3005_TOO_CLOSE_TO_ANOTHER_RAILROAD);
 
			if (!CanExpandRailroadStation(st, finalvalues, axis))
 
@@ -1194,232 +1189,231 @@ CommandCost CmdRemoveFromRailroadStation
 
		/* Do not allow removing from stations if non-uniform stations are not enabled
 
		 * The check must be here to give correct error message
 
 		 */
 
		if (!_patches.nonuniform_stations) return_cmd_error(STR_NONUNIFORM_STATIONS_DISALLOWED);
 

	
 
		/* If we reached here, the tile is valid so increase the quantity of tiles we will remove */
 
		quantity++;
 

	
 
		if (flags & DC_EXEC) {
 
			/* read variables before the station tile is removed */
 
			uint specindex = GetCustomStationSpecIndex(tile2);
 
			Track track = GetRailStationTrack(tile2);
 
			Owner owner = GetTileOwner(tile2);
 

	
 
			DoClearSquare(tile2);
 
			st->rect.AfterRemoveTile(st, tile2);
 
			AddTrackToSignalBuffer(tile2, track, owner);
 
			YapfNotifyTrackLayoutChange(tile2, track);
 

	
 
			DeallocateSpecFromStation(st, specindex);
 

	
 
			/* now we need to make the "spanned" area of the railway station smaller
 
			 * if we deleted something at the edges.
 
			 * we also need to adjust train_tile. */
 
			MakeRailwayStationAreaSmaller(st);
 
			st->MarkTilesDirty(false);
 
			UpdateStationSignCoord(st);
 

	
 
			/* if we deleted the whole station, delete the train facility. */
 
			if (st->train_tile == 0) {
 
				st->facilities &= ~FACIL_TRAIN;
 
				InvalidateWindowWidget(WC_STATION_VIEW, st->index, SVW_TRAINS);
 
				UpdateStationVirtCoordDirty(st);
 
				DeleteStationIfEmpty(st);
 
			}
 
		}
 
	} END_TILE_LOOP(tile2, size_x, size_y, tile)
 

	
 
	/* If we've not removed any tiles, give an error */
 
	if (quantity == 0) return CMD_ERROR;
 

	
 
	return CommandCost(EXPENSES_CONSTRUCTION, _price.remove_rail_station * quantity);
 
}
 

	
 

	
 
static CommandCost RemoveRailroadStation(Station *st, TileIndex tile, uint32 flags)
 
{
 
	/* if there is flooding and non-uniform stations are enabled, remove platforms tile by tile */
 
	if (_current_player == OWNER_WATER && _patches.nonuniform_stations)
 
	if (_current_player == OWNER_WATER && _patches.nonuniform_stations) {
 
		return DoCommand(tile, 0, 0, DC_EXEC, CMD_REMOVE_FROM_RAILROAD_STATION);
 
	}
 

	
 
	/* Current player owns the station? */
 
	if (_current_player != OWNER_WATER && !CheckOwnership(st->owner))
 
		return CMD_ERROR;
 
	if (_current_player != OWNER_WATER && !CheckOwnership(st->owner)) return CMD_ERROR;
 

	
 
	/* determine width and height of platforms */
 
	tile = st->train_tile;
 
	int w = st->trainst_w;
 
	int h = st->trainst_h;
 

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

	
 
	CommandCost cost(EXPENSES_CONSTRUCTION);
 
	/* clear all areas of the station */
 
	do {
 
		int w_bak = w;
 
		do {
 
			/* for nonuniform stations, only remove tiles that are actually train station tiles */
 
			if (st->TileBelongsToRailStation(tile)) {
 
				if (!EnsureNoVehicleOnGround(tile))
 
					return CMD_ERROR;
 
				cost.AddCost(_price.remove_rail_station);
 
				if (flags & DC_EXEC) {
 
					/* read variables before the station tile is removed */
 
					Track track = GetRailStationTrack(tile);
 
					Owner owner = GetTileOwner(tile); // _current_player can be OWNER_WATER
 
					DoClearSquare(tile);
 
					AddTrackToSignalBuffer(tile, track, owner);
 
					YapfNotifyTrackLayoutChange(tile, track);
 
				}
 
			}
 
			tile += TileDiffXY(1, 0);
 
		} while (--w);
 
		w = w_bak;
 
		tile += TileDiffXY(-w, 1);
 
	} while (--h);
 

	
 
	if (flags & DC_EXEC) {
 
		st->rect.AfterRemoveRect(st, st->train_tile, st->trainst_w, st->trainst_h);
 

	
 
		st->train_tile = 0;
 
		st->trainst_w = st->trainst_h = 0;
 
		st->facilities &= ~FACIL_TRAIN;
 

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

	
 
		InvalidateWindowWidget(WC_STATION_VIEW, st->index, SVW_TRAINS);
 
		UpdateStationVirtCoordDirty(st);
 
		DeleteStationIfEmpty(st);
 
	}
 

	
 
	return cost;
 
}
 

	
 
/**
 
 * @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)
 
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;
 
	}
 
}
 

	
 
/** Build a bus or truck stop
 
 * @param tile tile to build the stop at
 
 * @param flags operation to perform
 
 * @param p1 entrance direction (DiagDirection)
 
 * @param p2 bit 0: 0 for Bus stops, 1 for truck stops
 
 *           bit 1: 0 for normal, 1 for drive-through
 
 *           bit 2..4: the roadtypes
 
 *           bit 5: allow stations directly adjacent to other stations.
 
 */
 
CommandCost CmdBuildRoadStop(TileIndex tile, uint32 flags, uint32 p1, uint32 p2)
 
{
 
	bool type = HasBit(p2, 0);
 
	bool is_drive_through = HasBit(p2, 1);
 
	bool build_over_road  = is_drive_through && IsNormalRoadTile(tile);
 
	bool town_owned_road  = build_over_road && IsTileOwner(tile, OWNER_TOWN);
 
	RoadTypes rts = (RoadTypes)GB(p2, 2, 3);
 

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

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

	
 
	/* Saveguard the parameters */
 
	if (!IsValidDiagDirection((DiagDirection)p1)) return CMD_ERROR;
 
	/* If it is a drive-through stop check for valid axis */
 
	if (is_drive_through && !IsValidAxis((Axis)p1)) return CMD_ERROR;
 
	/* Road bits in the wrong direction */
 
	if (build_over_road && (GetAllRoadBits(tile) & ((Axis)p1 == AXIS_X ? ROAD_Y : ROAD_X)) != 0) return_cmd_error(STR_DRIVE_THROUGH_ERROR_DIRECTION);
 

	
 
	if (!(flags & DC_NO_TOWN_RATING) && !CheckIfAuthorityAllows(tile)) return CMD_ERROR;
 

	
 
	CommandCost cost;
 

	
 
	/* Not allowed to build over this road */
 
	if (build_over_road) {
 
		if (IsTileOwner(tile, OWNER_TOWN) && !_patches.road_stop_on_town_road) return_cmd_error(STR_DRIVE_THROUGH_ERROR_ON_TOWN_ROAD);
 

	
 
		RoadTypes cur_rts = GetRoadTypes(tile);
 

	
 
		/* there is a road, check if we can build road+tram stop over it */
 
		if (HasBit(cur_rts, ROADTYPE_ROAD)) {
 
			Owner road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
 
			if (road_owner != OWNER_TOWN && road_owner != OWNER_NONE && !CheckOwnership(road_owner)) return CMD_ERROR;
 
		}
 

	
 
		/* there is a tram, check if we can build road+tram stop over it */
 
		if (HasBit(cur_rts, ROADTYPE_TRAM)) {
 
			Owner tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
 
			if (tram_owner != OWNER_NONE && !CheckOwnership(tram_owner)) return CMD_ERROR;
 
		}
 

	
 
		/* Don't allow building the roadstop when vehicles are already driving on it */
 
		if (!EnsureNoVehicleOnGround(tile)) return CMD_ERROR;
 

	
 
		/* Do not remove roadtypes! */
 
		rts |= cur_rts;
 
	}
 
	cost = CheckFlatLandBelow(tile, 1, 1, flags, is_drive_through ? 5 << p1 : 1 << p1, NULL, !build_over_road);
 

	
 
	CommandCost cost = CheckFlatLandBelow(tile, 1, 1, flags, is_drive_through ? 5 << p1 : 1 << p1, NULL, !build_over_road);
 
	if (CmdFailed(cost)) return cost;
 

	
 
	Station *st = NULL;
 

	
 
	if (!_patches.adjacent_stations || !HasBit(p2, 5)) {
 
		st = GetStationAround(tile, 1, 1, INVALID_STATION);
 
		if (st == CHECK_STATIONS_ERR) return CMD_ERROR;
 
	}
 

	
 
	/* Find a station close to us */
 
	if (st == NULL) st = GetClosestStationFromTile(tile);
 

	
 
	/* give us a road stop in the list, and check if something went wrong */
 
	RoadStop *road_stop = new RoadStop(tile);
 
	if (road_stop == NULL) {
 
		return_cmd_error(type ? STR_TOO_MANY_TRUCK_STOPS : STR_TOO_MANY_BUS_STOPS);
 
	}
 

	
 
	/* ensure that in case of error (or no DC_EXEC) the new road stop gets deleted upon return */
 
	AutoPtrT<RoadStop> rs_auto_delete(road_stop);
 

	
 
	if (st != NULL &&
 
			GetNumRoadStopsInStation(st, ROADSTOP_BUS) + GetNumRoadStopsInStation(st, ROADSTOP_TRUCK) >= RoadStop::LIMIT) {
 
		return_cmd_error(type ? STR_TOO_MANY_TRUCK_STOPS : STR_TOO_MANY_BUS_STOPS);
 
	}
 

	
 
	/* In case of new station if DC_EXEC is NOT set we still need to create the station
 
	 * to test if everything is OK. In this case we need to delete it before return. */
 
	AutoPtrT<Station> st_auto_delete;
 

	
 
	if (st != NULL) {
 
		if (st->owner != _current_player) {
 
			return_cmd_error(STR_3009_TOO_CLOSE_TO_ANOTHER_STATION);
 
		}
 

	
 
		if (!st->rect.BeforeAddTile(tile, StationRect::ADD_TEST)) return CMD_ERROR;
 
	} else {
 
		/* allocate and initialize new station */
 
		st = new Station(tile);
 
		if (st == NULL) return_cmd_error(STR_3008_TOO_MANY_STATIONS_LOADING);
 

	
 
		/* ensure that in case of error (or no DC_EXEC) the new station gets deleted upon return */
 
		st_auto_delete = st;
 

	
 

	
 
		Town *t = st->town = ClosestTownFromTile(tile, (uint)-1);
 
		if (!GenerateStationName(st, tile, STATIONNAMING_ROAD)) return CMD_ERROR;
 

	
 
@@ -1625,228 +1619,231 @@ static const byte _airport_sections_comm
 
	85, 30, 115, 115, 32,
 
	87, 8,    8,   8, 10,
 
	87, 11,  11,  11, 10,
 
	26, 23,  23,  23, 26
 
};
 

	
 
/* Heliport */
 
static const byte _airport_sections_heliport[] = {
 
	66,
 
};
 

	
 
/* Helidepot */
 
static const byte _airport_sections_helidepot[] = {
 
	124, 32,
 
	122, 123
 
};
 

	
 
/* Helistation */
 
static const byte _airport_sections_helistation[] = {
 
	 32, 134, 159, 158,
 
	161, 142, 142, 157
 
};
 

	
 
static const byte * const _airport_sections[] = {
 
	_airport_sections_country,           // Country Airfield (small)
 
	_airport_sections_town,              // City Airport (large)
 
	_airport_sections_heliport,          // Heliport
 
	_airport_sections_metropolitan,      // Metropolitain Airport (large)
 
	_airport_sections_international,     // International Airport (xlarge)
 
	_airport_sections_commuter,          // Commuter Airport (small)
 
	_airport_sections_helidepot,         // Helidepot
 
	_airport_sections_intercontinental,  // Intercontinental Airport (xxlarge)
 
	_airport_sections_helistation        // Helistation
 
};
 

	
 
/** 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 (bit 0) - allow airports directly adjacent to other airports.
 
 */
 
CommandCost CmdBuildAirport(TileIndex tile, uint32 flags, uint32 p1, uint32 p2)
 
{
 
	bool airport_upgrade = true;
 

	
 
	/* Check if a valid, buildable airport was chosen for construction */
 
	if (p1 > lengthof(_airport_sections) || !HasBit(GetValidAirports(), p1)) return CMD_ERROR;
 

	
 
	if (!(flags & DC_NO_TOWN_RATING) && !CheckIfAuthorityAllows(tile))
 
	if (!(flags & DC_NO_TOWN_RATING) && !CheckIfAuthorityAllows(tile)) {
 
		return CMD_ERROR;
 

	
 
	Town *t = ClosestTownFromTile(tile, (uint)-1);
 
	}
 

	
 
	Town *t = ClosestTownFromTile(tile, UINT_MAX);
 

	
 
	/* Check if local auth refuses a new airport */
 
	{
 
		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 (st->town == t && st->facilities & FACIL_AIRPORT && st->airport_type != AT_OILRIG) num++;
 
		}
 
		if (num >= 2) {
 
			SetDParam(0, t->index);
 
			return_cmd_error(STR_2035_LOCAL_AUTHORITY_REFUSES);
 
		}
 
	}
 

	
 
	const AirportFTAClass *afc = GetAirport(p1);
 
	int w = afc->size_x;
 
	int h = afc->size_y;
 

	
 
	CommandCost cost = CheckFlatLandBelow(tile, w, h, flags, 0, NULL);
 
	if (CmdFailed(cost)) return cost;
 

	
 
	Station *st = NULL;
 

	
 
	if (!_patches.adjacent_stations || !HasBit(p2, 0)) {
 
		st = GetStationAround(tile, w, h, INVALID_STATION);
 
		if (st == CHECK_STATIONS_ERR) return CMD_ERROR;
 
	}
 

	
 
	/* Find a station close to us */
 
	if (st == NULL) st = GetClosestStationFromTile(tile);
 

	
 
	if (w > _patches.station_spread || h > _patches.station_spread) {
 
		_error_message = STR_306C_STATION_TOO_SPREAD_OUT;
 
		return CMD_ERROR;
 
	}
 

	
 
	/* In case of new station if DC_EXEC is NOT set we still need to create the station
 
	 * to test if everything is OK. In this case we need to delete it before return. */
 
	AutoPtrT<Station> st_auto_delete;
 

	
 
	if (st != NULL) {
 
		if (st->owner != _current_player)
 
		if (st->owner != _current_player) {
 
			return_cmd_error(STR_3009_TOO_CLOSE_TO_ANOTHER_STATION);
 
		}
 

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

	
 
		if (st->airport_tile != 0)
 
		if (st->airport_tile != 0) {
 
			return_cmd_error(STR_300D_TOO_CLOSE_TO_ANOTHER_AIRPORT);
 
		}
 
	} else {
 
		airport_upgrade = false;
 

	
 
		/* allocate and initialize new station */
 
		st = new Station(tile);
 
		if (st == NULL) return_cmd_error(STR_3008_TOO_MANY_STATIONS_LOADING);
 

	
 
		/* ensure that in case of error (or no DC_EXEC) the station gets deleted upon return */
 
		st_auto_delete = st;
 

	
 
		st->town = t;
 

	
 
		if (IsValidPlayer(_current_player) && (flags & DC_EXEC) != 0) {
 
			SetBit(t->have_ratings, _current_player);
 
		}
 

	
 
		st->sign.width_1 = 0;
 

	
 
		/* If only helicopters may use the airport generate a helicopter related (5)
 
		 * station name, otherwise generate a normal airport name (1) */
 
		if (!GenerateStationName(st, tile, !(afc->flags & AirportFTAClass::AIRPLANES) ? STATIONNAMING_HELIPORT : STATIONNAMING_AIRPORT)) {
 
			return CMD_ERROR;
 
		}
 
	}
 

	
 
	cost.AddCost(_price.build_airport * w * h);
 

	
 
	if (flags & DC_EXEC) {
 
		st->airport_tile = tile;
 
		st->AddFacility(FACIL_AIRPORT, tile);
 
		st->airport_type = (byte)p1;
 
		st->airport_flags = 0;
 

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

	
 
		/* 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);
 

	
 
		{
 
			const byte *b = _airport_sections[p1];
 

	
 
			BEGIN_TILE_LOOP(tile_cur, w, h, tile) {
 
				MakeAirport(tile_cur, st->owner, st->index, *b - ((*b < 67) ? 8 : 24));
 
				b++;
 
			} END_TILE_LOOP(tile_cur, w, h, tile)
 
		}
 

	
 
		UpdateStationVirtCoordDirty(st);
 
		UpdateStationAcceptance(st, false);
 
		RebuildStationLists();
 
		InvalidateWindow(WC_STATION_LIST, st->owner);
 
		InvalidateWindowWidget(WC_STATION_VIEW, st->index, SVW_PLANES);
 
		/* success, so don't delete the new station */
 
		st_auto_delete.Detach();
 
	}
 

	
 
	return cost;
 
}
 

	
 
static CommandCost RemoveAirport(Station *st, uint32 flags)
 
{
 
	if (_current_player != OWNER_WATER && !CheckOwnership(st->owner))
 
	if (_current_player != OWNER_WATER && !CheckOwnership(st->owner)) {
 
		return CMD_ERROR;
 
	}
 

	
 
	TileIndex tile = st->airport_tile;
 

	
 
	const AirportFTAClass *afc = st->Airport();
 
	int w = afc->size_x;
 
	int h = afc->size_y;
 

	
 
	CommandCost cost(EXPENSES_CONSTRUCTION, w * h * _price.remove_airport);
 

	
 
	Vehicle *v;
 
	const Vehicle *v;
 
	FOR_ALL_VEHICLES(v) {
 
		if (!(v->type == VEH_AIRCRAFT && IsNormalAircraft(v))) continue;
 

	
 
		if (v->u.air.targetairport == st->index && v->u.air.state != FLYING) return CMD_ERROR;
 
	}
 

	
 
	BEGIN_TILE_LOOP(tile_cur, w, h, tile) {
 
		if (!EnsureNoVehicleOnGround(tile_cur)) return CMD_ERROR;
 

	
 
		if (flags & DC_EXEC) {
 
			DeleteAnimatedTile(tile_cur);
 
			DoClearSquare(tile_cur);
 
		}
 
	} END_TILE_LOOP(tile_cur, w, h, tile)
 

	
 
	if (flags & DC_EXEC) {
 
		for (uint i = 0; i < afc->nof_depots; ++i) {
 
			DeleteWindowById(
 
				WC_VEHICLE_DEPOT, tile + ToTileIndexDiff(afc->airport_depots[i])
 
			);
 
		}
 

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

	
 
		st->airport_tile = 0;
 
		st->facilities &= ~FACIL_AIRPORT;
 

	
 
		InvalidateWindowWidget(WC_STATION_VIEW, st->index, SVW_PLANES);
 
		UpdateStationVirtCoordDirty(st);
 
		DeleteStationIfEmpty(st);
 
	}
 

	
 
	return cost;
 
}
 

	
 
/** Build a buoy.
 
 * @param tile tile where to place the bouy
 
 * @param flags operation to perform
 
 * @param p1 unused
 
 * @param p2 unused
 
 */
 
CommandCost CmdBuildBuoy(TileIndex tile, uint32 flags, uint32 p1, uint32 p2)
 
{
 
	if (!IsWaterTile(tile) || tile == 0) return_cmd_error(STR_304B_SITE_UNSUITABLE);
 
	if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return_cmd_error(STR_5007_MUST_DEMOLISH_BRIDGE_FIRST);
 

	
 
	if (GetTileSlope(tile, NULL) != SLOPE_FLAT) return_cmd_error(STR_304B_SITE_UNSUITABLE);
 

	
 
@@ -1866,318 +1863,314 @@ CommandCost CmdBuildBuoy(TileIndex tile,
 
		st->dock_tile = tile;
 
		st->facilities |= FACIL_DOCK;
 
		/* Buoys are marked in the Station struct by this flag. Yes, it is this
 
		 * braindead.. */
 
		st->had_vehicle_of_type |= HVOT_BUOY;
 
		st->owner = OWNER_NONE;
 

	
 
		st->build_date = _date;
 

	
 
		MakeBuoy(tile, st->index, GetWaterClass(tile));
 

	
 
		UpdateStationVirtCoordDirty(st);
 
		UpdateStationAcceptance(st, false);
 
		RebuildStationLists();
 
		InvalidateWindow(WC_STATION_LIST, st->owner);
 
		InvalidateWindowWidget(WC_STATION_VIEW, st->index, SVW_SHIPS);
 
		/* success, so don't delete the new station */
 
		st_auto_delete.Detach();
 
	}
 

	
 
	return CommandCost(EXPENSES_CONSTRUCTION, _price.build_dock);
 
}
 

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

	
 
static CommandCost RemoveBuoy(Station *st, uint32 flags)
 
{
 
	/* XXX: strange stuff */
 
	if (!IsValidPlayer(_current_player))  return_cmd_error(INVALID_STRING_ID);
 
	if (!IsValidPlayer(_current_player)) return_cmd_error(INVALID_STRING_ID);
 

	
 
	TileIndex tile = st->dock_tile;
 

	
 
	if (HasStationInUse(st->index, INVALID_PLAYER)) return_cmd_error(STR_BUOY_IS_IN_USE);
 
	/* remove the buoy if there is a ship on tile when company goes bankrupt... */
 
	if (!(flags & DC_BANKRUPT) && !EnsureNoVehicleOnGround(tile)) return CMD_ERROR;
 

	
 
	if (flags & DC_EXEC) {
 
		st->dock_tile = 0;
 
		/* Buoys are marked in the Station struct by this flag. Yes, it is this
 
		 * braindead.. */
 
		st->facilities &= ~FACIL_DOCK;
 
		st->had_vehicle_of_type &= ~HVOT_BUOY;
 

	
 
		InvalidateWindowWidget(WC_STATION_VIEW, st->index, SVW_SHIPS);
 

	
 
		/* We have to set the water tile's state to the same state as before the
 
		 * buoy was placed. Otherwise one could plant a buoy on a canal edge,
 
		 * remove it and flood the land (if the canal edge is at level 0) */
 
		MakeWaterKeepingClass(tile, GetTileOwner(tile));
 
		MarkTileDirtyByTile(tile);
 

	
 
		UpdateStationVirtCoordDirty(st);
 
		DeleteStationIfEmpty(st);
 
	}
 

	
 
	return CommandCost(EXPENSES_CONSTRUCTION, _price.remove_truck_station);
 
}
 

	
 
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 unused
 
 */
 
CommandCost CmdBuildDock(TileIndex tile, uint32 flags, uint32 p1, uint32 p2)
 
{
 
	CommandCost cost;
 

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

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

	
 
	if (!(flags & DC_NO_TOWN_RATING) && !CheckIfAuthorityAllows(tile)) return CMD_ERROR;
 

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

	
 
	cost = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
 
	if (CmdFailed(cost)) return CMD_ERROR;
 
	if (CmdFailed(DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR))) 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_304B_SITE_UNSUITABLE);
 
	}
 

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

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

	
 
	cost = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
 
	if (CmdFailed(cost)) return CMD_ERROR;
 
	if (CmdFailed(DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR))) return CMD_ERROR;
 

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

	
 
	/* middle */
 
	Station *st = NULL;
 

	
 
	if (!_patches.adjacent_stations || !HasBit(p1, 0)) {
 
		st = GetStationAround(
 
				tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
 
				_dock_w_chk[direction], _dock_h_chk[direction], INVALID_STATION);
 
		if (st == CHECK_STATIONS_ERR) return CMD_ERROR;
 
	}
 

	
 
	/* Find a station close to us */
 
	if (st == NULL) st = GetClosestStationFromTile(tile);
 

	
 
	/* In case of new station if DC_EXEC is NOT set we still need to create the station
 
	 * to test if everything is OK. In this case we need to delete it before return. */
 
	AutoPtrT<Station> st_auto_delete;
 

	
 
	if (st != NULL) {
 
		if (st->owner != _current_player)
 
		if (st->owner != _current_player) {
 
			return_cmd_error(STR_3009_TOO_CLOSE_TO_ANOTHER_STATION);
 
		}
 

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

	
 
		if (st->dock_tile != 0) return_cmd_error(STR_304C_TOO_CLOSE_TO_ANOTHER_DOCK);
 
	} else {
 
		/* allocate and initialize new station */
 
		st = new Station(tile);
 
		if (st == NULL) return_cmd_error(STR_3008_TOO_MANY_STATIONS_LOADING);
 

	
 
		/* ensure that in case of error (or no DC_EXEC) the station gets deleted upon return */
 
		st_auto_delete = st;
 

	
 
		Town *t = st->town = ClosestTownFromTile(tile, (uint)-1);
 

	
 
		if (IsValidPlayer(_current_player) && (flags & DC_EXEC) != 0) {
 
			SetBit(t->have_ratings, _current_player);
 
		}
 

	
 
		st->sign.width_1 = 0;
 

	
 
		if (!GenerateStationName(st, tile, STATIONNAMING_DOCK)) return CMD_ERROR;
 
	}
 

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

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

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

	
 
		UpdateStationVirtCoordDirty(st);
 
		UpdateStationAcceptance(st, false);
 
		RebuildStationLists();
 
		InvalidateWindow(WC_STATION_LIST, st->owner);
 
		InvalidateWindowWidget(WC_STATION_VIEW, st->index, SVW_SHIPS);
 
		/* success, so don't delete the new station */
 
		st_auto_delete.Detach();
 
	}
 

	
 
	return CommandCost(EXPENSES_CONSTRUCTION, _price.build_dock);
 
}
 

	
 
static CommandCost RemoveDock(Station *st, uint32 flags)
 
{
 
	if (!CheckOwnership(st->owner)) return CMD_ERROR;
 

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

	
 
	if (!EnsureNoVehicleOnGround(tile1)) return CMD_ERROR;
 
	if (!EnsureNoVehicleOnGround(tile2)) return CMD_ERROR;
 

	
 
	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 = 0;
 
		st->facilities &= ~FACIL_DOCK;
 

	
 
		InvalidateWindowWidget(WC_STATION_VIEW, st->index, SVW_SHIPS);
 
		UpdateStationVirtCoordDirty(st);
 
		DeleteStationIfEmpty(st);
 
	}
 

	
 
	return CommandCost(EXPENSES_CONSTRUCTION, _price.remove_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;
 

	
 
	if (IsRailwayStation(ti->tile)) {
 
		const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
 
		roadtypes = ROADTYPES_NONE;
 
		total_offset = rti->total_offset;
 
		custom_ground_offset = rti->custom_ground_offset;
 
	} else {
 
		roadtypes = IsRoadStop(ti->tile) ? GetRoadTypes(ti->tile) : ROADTYPES_NONE;
 
		total_offset = 0;
 
		custom_ground_offset = 0;
 
	}
 
	uint32 relocation = 0;
 
	const Station *st = NULL;
 
	const StationSpec *statspec = NULL;
 
	PlayerID owner = GetTileOwner(ti->tile);
 

	
 
	SpriteID palette;
 
	if (IsValidPlayer(owner)) {
 
		palette = PLAYER_SPRITE_COLOR(owner);
 
	} else {
 
		/* Some stations are not owner by a player, namely oil rigs */
 
		palette = PALETTE_TO_GREY;
 
	}
 

	
 
	/* don't show foundation for docks */
 
	if (ti->tileh != SLOPE_FLAT && !IsDock(ti->tile))
 
		DrawFoundation(ti, FOUNDATION_LEVELED);
 

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

	
 
		//debug("Cust-o-mized %p", statspec);
 

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

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

	
 
			if (HasBit(statspec->callbackmask, 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)];
 
			}
 
		}
 
	}
 

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

	
 

	
 
	if (IsBuoy(ti->tile) || IsDock(ti->tile)) {
 
		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;
 
		if (HasBit(image, SPRITE_MODIFIER_USE_OFFSET)) {
 
			image += GetCustomStationGroundRelocation(statspec, st, ti->tile);
 
			image += custom_ground_offset;
 
		} else {
 
			image += total_offset;
 
		}
 
		DrawGroundSprite(image, HasBit(image, PALETTE_MODIFIER_COLOR) ? palette : PAL_NONE);
 
	}
 

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

	
 
	if (HasBit(roadtypes, ROADTYPE_TRAM)) {
 
		Axis axis = GetRoadStopDir(ti->tile) == DIAGDIR_NE ? AXIS_X : AXIS_Y;
 
@@ -2439,97 +2432,101 @@ static VehicleEnterTileStatus VehicleEnt
 

	
 
					/* Vehicles entering a drive-through stop from the 'normal' side use first bay (bay 0). */
 
					byte side = ((DirToDiagDir(v->direction) == ReverseDiagDir(GetRoadStopDir(tile))) == (v->u.road.overtaking == 0)) ? 0 : 1;
 

	
 
					if (!rs->IsFreeBay(side)) return VETSB_CANNOT_ENTER;
 

	
 
					/* Check if the vehicle is stopping at this road stop */
 
					if (GetRoadStopType(tile) == (IsCargoInClass(v->cargo_type, CC_PASSENGERS) ? ROADSTOP_BUS : ROADSTOP_TRUCK) &&
 
							v->current_order.GetDestination() == GetStationIndex(tile)) {
 
						SetBit(v->u.road.state, RVS_IS_STOPPING);
 
						rs->AllocateDriveThroughBay(side);
 
					}
 

	
 
					/* Indicate if vehicle is using second bay. */
 
					if (side == 1) SetBit(v->u.road.state, RVS_USING_SECOND_BAY);
 
					/* Indicate a drive-through stop */
 
					SetBit(v->u.road.state, RVS_IN_DT_ROAD_STOP);
 
					return VETSB_CONTINUE;
 
				}
 

	
 
				/* For normal (non drive-through) road stops */
 
				/* Check if station is busy or if there are no free bays or whether it is a articulated vehicle. */
 
				if (rs->IsEntranceBusy() || !rs->HasFreeBay() || RoadVehHasArticPart(v)) return VETSB_CANNOT_ENTER;
 

	
 
				SetBit(v->u.road.state, RVS_IN_ROAD_STOP);
 

	
 
				/* Allocate a bay and update the road state */
 
				uint bay_nr = rs->AllocateBay();
 
				SB(v->u.road.state, RVS_USING_SECOND_BAY, 1, bay_nr);
 

	
 
				/* Mark the station entrace as busy */
 
				rs->SetEntranceBusy(true);
 
			}
 
		}
 
	}
 

	
 
	return VETSB_CONTINUE;
 
}
 

	
 
/* this function is called for one station each tick */
 
static void StationHandleBigTick(Station *st)
 
{
 
	UpdateStationAcceptance(st, true);
 

	
 
	if (st->facilities == 0 && ++st->delete_ctr >= 8) delete st;
 

	
 
}
 

	
 
static inline void byte_inc_sat(byte *p) { byte b = *p + 1; if (b != 0) *p = b; }
 
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);
 

	
 
	GoodsEntry *ge = st->goods;
 
	do {
 
		/* 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);
 

	
 
			int rating = 0;
 

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

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

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

	
 
			{
 
				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);
 
			}
 
@@ -2577,176 +2574,177 @@ static void UpdateStationRating(Station 
 
				if (waiting > WAITING_CARGO_THRESHOLD) {
 
					uint difference = waiting - WAITING_CARGO_THRESHOLD;
 
					waiting -= (difference / WAITING_CARGO_CUT_FACTOR);
 

	
 
					waiting = min(waiting, MAX_WAITING_CARGO);
 
					waiting_changed = true;
 
				}
 

	
 
				if (waiting_changed) ge->cargo.Truncate(waiting);
 
			}
 
		}
 
	} while (++ge != endof(st->goods));
 

	
 
	StationID index = st->index;
 
	if (waiting_changed) {
 
		InvalidateWindow(WC_STATION_VIEW, index); // update whole window
 
	} else {
 
		InvalidateWindowWidget(WC_STATION_VIEW, index, SVW_RATINGLIST); // update only ratings list
 
	}
 
}
 

	
 
/* called for every station each tick */
 
static void StationHandleSmallTick(Station *st)
 
{
 
	if (st->facilities == 0) return;
 

	
 
	byte b = st->delete_ctr + 1;
 
	if (b >= 185) b = 0;
 
	st->delete_ctr = b;
 

	
 
	if (b == 0) UpdateStationRating(st);
 
}
 

	
 
void OnTick_Station()
 
{
 
	if (_game_mode == GM_EDITOR) return;
 

	
 
	uint i = _station_tick_ctr;
 
	if (++_station_tick_ctr > GetMaxStationIndex()) _station_tick_ctr = 0;
 

	
 
	if (IsValidStationID(i)) StationHandleBigTick(GetStation(i));
 

	
 
	Station *st;
 
	FOR_ALL_STATIONS(st) StationHandleSmallTick(st);
 
}
 

	
 
void StationMonthlyLoop()
 
{
 
	/* not used */
 
}
 

	
 

	
 
void ModifyStationRatingAround(TileIndex tile, PlayerID owner, int amount, uint radius)
 
{
 
	Station *st;
 

	
 
	FOR_ALL_STATIONS(st) {
 
		if (st->owner == owner &&
 
				DistanceManhattan(tile, st->xy) <= radius) {
 
			for (CargoID i = 0; i < NUM_CARGO; i++) {
 
				GoodsEntry* ge = &st->goods[i];
 
				GoodsEntry *ge = &st->goods[i];
 

	
 
				if (ge->acceptance_pickup != 0) {
 
					ge->rating = Clamp(ge->rating + amount, 0, 255);
 
				}
 
			}
 
		}
 
	}
 
}
 

	
 
static void UpdateStationWaiting(Station *st, CargoID type, uint amount)
 
{
 
	st->goods[type].cargo.Append(new CargoPacket(st->index, amount));
 
	SetBit(st->goods[type].acceptance_pickup, GoodsEntry::PICKUP);
 

	
 
	InvalidateWindow(WC_STATION_VIEW, st->index);
 
	st->MarkTilesDirty(true);
 
}
 

	
 
static bool IsUniqueStationName(const char *name)
 
{
 
	const Station *st;
 
	char buf[512];
 

	
 
	FOR_ALL_STATIONS(st) {
 
		SetDParam(0, st->index);
 
		GetString(buf, STR_STATION, lastof(buf));
 
		if (strcmp(buf, name) == 0) return false;
 
	}
 

	
 
	return true;
 
}
 

	
 
/** Rename a station
 
 * @param tile unused
 
 * @param flags operation to perform
 
 * @param p1 station ID that is to be renamed
 
 * @param p2 unused
 
 */
 
CommandCost CmdRenameStation(TileIndex tile, uint32 flags, uint32 p1, uint32 p2)
 
{
 
	if (!IsValidStationID(p1) || StrEmpty(_cmd_text)) return CMD_ERROR;
 
	Station *st = GetStation(p1);
 

	
 
	if (!CheckOwnership(st->owner)) return CMD_ERROR;
 

	
 
	if (!IsUniqueStationName(_cmd_text)) return_cmd_error(STR_NAME_MUST_BE_UNIQUE);
 

	
 
	if (flags & DC_EXEC) {
 
		free(st->name);
 
		st->name = strdup(_cmd_text);
 

	
 
		UpdateStationVirtCoord(st);
 
		ResortStationLists();
 
		MarkWholeScreenDirty();
 
	}
 

	
 
	return CommandCost();
 
}
 

	
 
/**
 
* Find all (non-buoy) stations around an industry tile
 
*
 
* @param tile: Center tile to search from
 
* @param w: Width of the center
 
* @param h: Height of the center
 
*
 
* @return: Set of found stations
 
*/
 
 * Find all (non-buoy) stations around an industry tile
 
 *
 
 * @param tile: Center tile to search from
 
 * @param w: Width of the center
 
 * @param h: Height of the center
 
 *
 
 * @return: Set of found stations
 
 */
 
StationSet FindStationsAroundIndustryTile(TileIndex tile, int w, int h)
 
{
 
	StationSet station_set;
 

	
 
	int w_prod; // width and height of the "producer" of the cargo
 
	int h_prod;
 
	int max_rad;
 
	if (_patches.modified_catchment) {
 
		w_prod = w;
 
		h_prod = h;
 
		w += 2 * MAX_CATCHMENT;
 
		h += 2 * MAX_CATCHMENT;
 
		max_rad = MAX_CATCHMENT;
 
	} else {
 
		w_prod = 0;
 
		h_prod = 0;
 
		w += 8;
 
		h += 8;
 
		max_rad = CA_UNMODIFIED;
 
	}
 

	
 
	BEGIN_TILE_LOOP(cur_tile, w, h, tile - TileDiffXY(max_rad, max_rad))
 
		cur_tile = TILE_MASK(cur_tile);
 
		if (!IsTileType(cur_tile, MP_STATION)) continue;
 

	
 
		Station *st = GetStationByTile(cur_tile);
 

	
 
		if (st->IsBuoy()) continue; // bouys don't accept cargo
 

	
 

	
 
		if (_patches.modified_catchment) {
 
			/* min and max coordinates of the producer relative */
 
			const int x_min_prod = max_rad + 1;
 
			const int x_max_prod = max_rad + w_prod;
 
			const int y_min_prod = max_rad + 1;
 
			const int y_max_prod = max_rad + h_prod;
 

	
 
			int rad = FindCatchmentRadius(st);
 

	
 
			int x_dist = min(w_cur - x_min_prod, x_max_prod - w_cur);
 
			if (w_cur < x_min_prod) {
 
				x_dist = x_min_prod - w_cur;
 
			} else if (w_cur > x_max_prod) {
 
				x_dist = w_cur - x_max_prod;
 
			}
 

	
 
			if (x_dist > rad) continue;
 

	
 
@@ -2845,331 +2843,328 @@ void BuildOilRig(TileIndex tile)
 

	
 
	if (st == NULL) {
 
		DEBUG(misc, 0, "Can't allocate station for oilrig at 0x%X, reverting to oilrig only", tile);
 
		return;
 
	}
 

	
 
	st->town = ClosestTownFromTile(tile, (uint)-1);
 
	st->sign.width_1 = 0;
 

	
 
	if (!GenerateStationName(st, tile, STATIONNAMING_OILRIG)) {
 
		DEBUG(misc, 0, "Can't allocate station-name for oilrig at 0x%X, reverting to oilrig only", tile);
 
		delete st;
 
		return;
 
	}
 

	
 
	MakeOilrig(tile, st->index);
 

	
 
	st->owner = OWNER_NONE;
 
	st->airport_flags = 0;
 
	st->airport_type = AT_OILRIG;
 
	st->xy = tile;
 
	st->bus_stops = NULL;
 
	st->truck_stops = NULL;
 
	st->airport_tile = tile;
 
	st->dock_tile = tile;
 
	st->train_tile = 0;
 
	st->had_vehicle_of_type = 0;
 
	st->time_since_load = 255;
 
	st->time_since_unload = 255;
 
	st->delete_ctr = 0;
 
	st->last_vehicle_type = VEH_INVALID;
 
	st->facilities = FACIL_AIRPORT | FACIL_DOCK;
 
	st->build_date = _date;
 

	
 
	for (CargoID j = 0; j < NUM_CARGO; j++) {
 
		st->goods[j].acceptance_pickup = 0;
 
		st->goods[j].days_since_pickup = 255;
 
		st->goods[j].rating = INITIAL_STATION_RATING;
 
		st->goods[j].last_speed = 0;
 
		st->goods[j].last_age = 255;
 
	}
 

	
 
	UpdateStationVirtCoordDirty(st);
 
	UpdateStationAcceptance(st, false);
 
}
 

	
 
void DeleteOilRig(TileIndex tile)
 
{
 
	Station* st = GetStationByTile(tile);
 
	Station *st = GetStationByTile(tile);
 

	
 
	MakeWater(tile);
 

	
 
	st->dock_tile = 0;
 
	st->airport_tile = 0;
 
	st->facilities &= ~(FACIL_AIRPORT | FACIL_DOCK);
 
	st->airport_flags = 0;
 
	UpdateStationVirtCoordDirty(st);
 
	if (st->facilities == 0) delete st;
 
}
 

	
 
static void ChangeTileOwner_Station(TileIndex tile, PlayerID old_player, PlayerID new_player)
 
{
 
	if (!IsTileOwner(tile, old_player)) return;
 

	
 
	if (new_player != PLAYER_SPECTATOR) {
 
		Station* st = GetStationByTile(tile);
 
		Station *st = GetStationByTile(tile);
 

	
 
		SetTileOwner(tile, new_player);
 
		if (!IsBuoy(tile)) st->owner = new_player; // do not set st->owner for buoys
 
		RebuildStationLists();
 
		InvalidateWindowClasses(WC_STATION_LIST);
 
	} else {
 
		if (IsDriveThroughStopTile(tile)) {
 
			/* Remove the drive-through road stop */
 
			DoCommand(tile, 0, (GetStationType(tile) == STATION_TRUCK) ? ROADSTOP_TRUCK : ROADSTOP_BUS, DC_EXEC | DC_BANKRUPT, CMD_REMOVE_ROAD_STOP);
 
			assert(IsTileType(tile, MP_ROAD));
 
			/* Change owner of tile and all roadtypes */
 
			ChangeTileOwner(tile, old_player, new_player);
 
		} else {
 
			DoCommand(tile, 0, 0, DC_EXEC | DC_BANKRUPT, CMD_LANDSCAPE_CLEAR);
 
			/* Set tile owner of water under (now removed) buoy and dock to OWNER_NONE.
 
			 * Update owner of buoy if it was not removed (was in orders).
 
			 * Do not update when owned by OWNER_WATER (sea and rivers). */
 
			if ((IsTileType(tile, MP_WATER) || IsBuoyTile(tile)) && IsTileOwner(tile, old_player)) SetTileOwner(tile, OWNER_NONE);
 
		}
 
	}
 
}
 

	
 
/**
 
 * Check if a drive-through road stop tile can be cleared.
 
 * Road stops built on town-owned roads check the conditions
 
 * that would allow clearing of the original road.
 
 * @param tile road stop tile to check
 
 * @return true if the road can be cleared
 
 */
 
static bool CanRemoveRoadWithStop(TileIndex tile)
 
{
 
	/* The road can always be cleared if it was not a town-owned road */
 
	if (!GetStopBuiltOnTownRoad(tile)) return true;
 

	
 
	bool edge_road;
 
	return CheckAllowRemoveRoad(tile, GetAnyRoadBits(tile, ROADTYPE_ROAD), OWNER_TOWN, &edge_road, ROADTYPE_ROAD) &&
 
				CheckAllowRemoveRoad(tile, GetAnyRoadBits(tile, ROADTYPE_TRAM), OWNER_TOWN, &edge_road, ROADTYPE_TRAM);
 
}
 

	
 
static CommandCost ClearTile_Station(TileIndex tile, byte flags)
 
{
 
	if (flags & DC_AUTO) {
 
		switch (GetStationType(tile)) {
 
			case STATION_RAIL:    return_cmd_error(STR_300B_MUST_DEMOLISH_RAILROAD);
 
			case STATION_AIRPORT: return_cmd_error(STR_300E_MUST_DEMOLISH_AIRPORT_FIRST);
 
			case STATION_TRUCK:   return_cmd_error(HasTileRoadType(tile, ROADTYPE_TRAM) ? STR_MUST_DEMOLISH_CARGO_TRAM_STATION : STR_3047_MUST_DEMOLISH_TRUCK_STATION);
 
			case STATION_BUS:     return_cmd_error(HasTileRoadType(tile, ROADTYPE_TRAM) ? STR_MUST_DEMOLISH_PASSENGER_TRAM_STATION : STR_3046_MUST_DEMOLISH_BUS_STATION);
 
			case STATION_BUOY:    return_cmd_error(STR_306A_BUOY_IN_THE_WAY);
 
			case STATION_DOCK:    return_cmd_error(STR_304D_MUST_DEMOLISH_DOCK_FIRST);
 
			case STATION_OILRIG:
 
				SetDParam(0, STR_4807_OIL_RIG);
 
				return_cmd_error(STR_4800_IN_THE_WAY);
 
		}
 
	}
 

	
 
	Station *st = GetStationByTile(tile);
 

	
 
	switch (GetStationType(tile)) {
 
		case STATION_RAIL:    return RemoveRailroadStation(st, tile, flags);
 
		case STATION_AIRPORT: return RemoveAirport(st, flags);
 
		case STATION_TRUCK:
 
			if (IsDriveThroughStopTile(tile) && !CanRemoveRoadWithStop(tile))
 
				return_cmd_error(STR_3047_MUST_DEMOLISH_TRUCK_STATION);
 
			return RemoveRoadStop(st, flags, tile);
 
		case STATION_BUS:
 
			if (IsDriveThroughStopTile(tile) && !CanRemoveRoadWithStop(tile))
 
				return_cmd_error(STR_3046_MUST_DEMOLISH_BUS_STATION);
 
			return RemoveRoadStop(st, flags, tile);
 
		case STATION_BUOY:    return RemoveBuoy(st, flags);
 
		case STATION_DOCK:    return RemoveDock(st, flags);
 
		default: break;
 
	}
 

	
 
	return CMD_ERROR;
 
}
 

	
 
void InitializeStations()
 
{
 
	/* Clean the station pool and create 1 block in it */
 
	_Station_pool.CleanPool();
 
	_Station_pool.AddBlockToPool();
 

	
 
	/* Clean the roadstop pool and create 1 block in it */
 
	_RoadStop_pool.CleanPool();
 
	_RoadStop_pool.AddBlockToPool();
 

	
 
	_station_tick_ctr = 0;
 

	
 
}
 

	
 

	
 
void AfterLoadStations()
 
{
 
	/* Update the speclists of all stations to point to the currently loaded custom stations. */
 
	Station *st;
 
	FOR_ALL_STATIONS(st) {
 
		for (uint i = 0; i < st->num_specs; i++) {
 
			if (st->speclist[i].grfid == 0) continue;
 

	
 
			st->speclist[i].spec = GetCustomStationSpecByGrf(st->speclist[i].grfid, st->speclist[i].localidx);
 
		}
 

	
 
		for (CargoID c = 0; c < NUM_CARGO; c++) st->goods[c].cargo.InvalidateCache();
 
	}
 
}
 

	
 
static CommandCost TerraformTile_Station(TileIndex tile, uint32 flags, uint z_new, Slope tileh_new)
 
{
 
	if (_patches.build_on_slopes && AutoslopeEnabled()) {
 
		/* TODO: If you implement newgrf callback 149 'land slope check', you have to decide what to do with it here.
 
		 *       TTDP does not call it.
 
		 */
 
		if (!IsSteepSlope(tileh_new) && (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new))) {
 
			switch (GetStationType(tile)) {
 
				case STATION_RAIL: {
 
					DiagDirection direction = AxisToDiagDir(GetRailStationAxis(tile));
 
					if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
 
					if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
 
					return CommandCost(EXPENSES_CONSTRUCTION, _price.terraform);
 
				}
 

	
 
				case STATION_AIRPORT:
 
					return CommandCost(EXPENSES_CONSTRUCTION, _price.terraform);
 

	
 
				case STATION_TRUCK:
 
				case STATION_BUS: {
 
					DiagDirection direction = GetRoadStopDir(tile);
 
					if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
 
					if (IsDriveThroughStopTile(tile)) {
 
						if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
 
					}
 
					return CommandCost(EXPENSES_CONSTRUCTION, _price.terraform);
 
				}
 

	
 
				default: break;
 
			}
 
		}
 
	}
 
	return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
 
}
 

	
 

	
 
extern const TileTypeProcs _tile_type_station_procs = {
 
	DrawTile_Station,           /* draw_tile_proc */
 
	GetSlopeZ_Station,          /* get_slope_z_proc */
 
	ClearTile_Station,          /* clear_tile_proc */
 
	GetAcceptedCargo_Station,   /* get_accepted_cargo_proc */
 
	GetTileDesc_Station,        /* get_tile_desc_proc */
 
	GetTileTrackStatus_Station, /* get_tile_track_status_proc */
 
	ClickTile_Station,          /* click_tile_proc */
 
	AnimateTile_Station,        /* animate_tile_proc */
 
	TileLoop_Station,           /* tile_loop_clear */
 
	ChangeTileOwner_Station,    /* change_tile_owner_clear */
 
	NULL,                       /* get_produced_cargo_proc */
 
	VehicleEnter_Station,       /* vehicle_enter_tile_proc */
 
	GetFoundation_Station,      /* get_foundation_proc */
 
	TerraformTile_Station,      /* terraform_tile_proc */
 
};
 

	
 
static const SaveLoad _roadstop_desc[] = {
 
	SLE_VAR(RoadStop,xy,           SLE_UINT32),
 
	SLE_CONDNULL(1, 0, 44),
 
	SLE_VAR(RoadStop,status,       SLE_UINT8),
 
	/* Index was saved in some versions, but this is not needed */
 
	SLE_CONDNULL(4, 0, 8),
 
	SLE_CONDNULL(2, 0, 44),
 
	SLE_CONDNULL(1, 0, 25),
 

	
 
	SLE_REF(RoadStop,next,         REF_ROADSTOPS),
 
	SLE_CONDNULL(2, 0, 44),
 

	
 
	SLE_CONDNULL(4, 0, 24),
 
	SLE_CONDNULL(1, 25, 25),
 

	
 
	SLE_END()
 
};
 

	
 
static const SaveLoad _station_desc[] = {
 
	SLE_CONDVAR(Station, xy,                         SLE_FILE_U16 | SLE_VAR_U32,  0, 5),
 
	SLE_CONDVAR(Station, xy,                         SLE_UINT32,                  6, SL_MAX_VERSION),
 
	SLE_CONDNULL(4, 0, 5), // bus/lorry tile
 
	SLE_CONDNULL(4, 0, 5),  ///< bus/lorry tile
 
	SLE_CONDVAR(Station, train_tile,                 SLE_FILE_U16 | SLE_VAR_U32,  0, 5),
 
	SLE_CONDVAR(Station, train_tile,                 SLE_UINT32,                  6, SL_MAX_VERSION),
 
	SLE_CONDVAR(Station, airport_tile,               SLE_FILE_U16 | SLE_VAR_U32,  0, 5),
 
	SLE_CONDVAR(Station, airport_tile,               SLE_UINT32,                  6, SL_MAX_VERSION),
 
	SLE_CONDVAR(Station, dock_tile,                  SLE_FILE_U16 | SLE_VAR_U32,  0, 5),
 
	SLE_CONDVAR(Station, dock_tile,                  SLE_UINT32,                  6, SL_MAX_VERSION),
 
	    SLE_REF(Station, town,                       REF_TOWN),
 
	    SLE_VAR(Station, trainst_w,                  SLE_UINT8),
 
	SLE_CONDVAR(Station, trainst_h,                  SLE_UINT8,                   2, SL_MAX_VERSION),
 

	
 
	/* alpha_order was stored here in savegame format 0 - 3 */
 
	SLE_CONDNULL(1, 0, 3),
 
	SLE_CONDNULL(1, 0, 3),  ///< alpha_order
 

	
 
	    SLE_VAR(Station, string_id,                  SLE_STRINGID),
 
	SLE_CONDSTR(Station, name,                       SLE_STR, 0,                 84, SL_MAX_VERSION),
 
	    SLE_VAR(Station, had_vehicle_of_type,        SLE_UINT16),
 

	
 
	    SLE_VAR(Station, time_since_load,            SLE_UINT8),
 
	    SLE_VAR(Station, time_since_unload,          SLE_UINT8),
 
	    SLE_VAR(Station, delete_ctr,                 SLE_UINT8),
 
	    SLE_VAR(Station, owner,                      SLE_UINT8),
 
	    SLE_VAR(Station, facilities,                 SLE_UINT8),
 
	    SLE_VAR(Station, airport_type,               SLE_UINT8),
 

	
 
	SLE_CONDNULL(2, 0, 5), // Truck/bus stop status
 
	SLE_CONDNULL(1, 0, 4), // Blocked months
 
	SLE_CONDNULL(2, 0, 5),  ///< Truck/bus stop status
 
	SLE_CONDNULL(1, 0, 4),  ///< Blocked months
 

	
 
	SLE_CONDVAR(Station, airport_flags,              SLE_VAR_U64 | SLE_FILE_U16,  0,  2),
 
	SLE_CONDVAR(Station, airport_flags,              SLE_VAR_U64 | SLE_FILE_U32,  3, 45),
 
	SLE_CONDVAR(Station, airport_flags,              SLE_UINT64,                 46, SL_MAX_VERSION),
 

	
 
	SLE_CONDNULL(2, 0, 25), /* Ex last-vehicle */
 
	SLE_CONDNULL(2, 0, 25), ///< last-vehicle
 
	SLE_CONDVAR(Station, last_vehicle_type,          SLE_UINT8,                  26, SL_MAX_VERSION),
 

	
 
	/* Was custom station class and id */
 
	SLE_CONDNULL(2, 3, 25),
 
	SLE_CONDNULL(2, 3, 25), ///< custom station class and id
 
	SLE_CONDVAR(Station, build_date,                 SLE_FILE_U16 | SLE_VAR_I32,  3, 30),
 
	SLE_CONDVAR(Station, build_date,                 SLE_INT32,                  31, SL_MAX_VERSION),
 

	
 
	SLE_CONDREF(Station, bus_stops,                  REF_ROADSTOPS,               6, SL_MAX_VERSION),
 
	SLE_CONDREF(Station, truck_stops,                REF_ROADSTOPS,               6, SL_MAX_VERSION),
 

	
 
	/* Used by newstations for graphic variations */
 
	SLE_CONDVAR(Station, random_bits,                SLE_UINT16,                 27, SL_MAX_VERSION),
 
	SLE_CONDVAR(Station, waiting_triggers,           SLE_UINT8,                  27, SL_MAX_VERSION),
 
	SLE_CONDVAR(Station, num_specs,                  SLE_UINT8,                  27, SL_MAX_VERSION),
 

	
 
	SLE_CONDLST(Station, loading_vehicles,           REF_VEHICLE,                57, SL_MAX_VERSION),
 

	
 
	/* reserve extra space in savegame here. (currently 32 bytes) */
 
	SLE_CONDNULL(32, 2, SL_MAX_VERSION),
 

	
 
	SLE_END()
 
};
 

	
 
static uint16 _waiting_acceptance;
 
static uint16 _cargo_source;
 
static uint32 _cargo_source_xy;
 
static uint16 _cargo_days;
 
static Money  _cargo_feeder_share;
 

	
 
static const SaveLoad _station_speclist_desc[] = {
 
	SLE_CONDVAR(StationSpecList, grfid,    SLE_UINT32, 27, SL_MAX_VERSION),
 
	SLE_CONDVAR(StationSpecList, localidx, SLE_UINT8,  27, SL_MAX_VERSION),
 

	
 
	SLE_END()
 
};
 

	
 

	
 
void SaveLoad_STNS(Station *st)
 
{
 
	static const SaveLoad _goods_desc[] = {
 
		SLEG_CONDVAR(            _waiting_acceptance, SLE_UINT16,                  0, 67),
 
		 SLE_CONDVAR(GoodsEntry, acceptance_pickup,   SLE_UINT8,                  68, SL_MAX_VERSION),
 
		SLE_CONDNULL(2,                                                           51, 67),
 
		     SLE_VAR(GoodsEntry, days_since_pickup,   SLE_UINT8),
 
		     SLE_VAR(GoodsEntry, rating,              SLE_UINT8),
 
		SLEG_CONDVAR(            _cargo_source,       SLE_FILE_U8 | SLE_VAR_U16,   0, 6),
 
		SLEG_CONDVAR(            _cargo_source,       SLE_UINT16,                  7, 67),
 
		SLEG_CONDVAR(            _cargo_source_xy,    SLE_UINT32,                 44, 67),
 
		SLEG_CONDVAR(            _cargo_days,         SLE_UINT8,                   0, 67),
 
		     SLE_VAR(GoodsEntry, last_speed,          SLE_UINT8),
 
		     SLE_VAR(GoodsEntry, last_age,            SLE_UINT8),
 
		SLEG_CONDVAR(            _cargo_feeder_share, SLE_FILE_U32 | SLE_VAR_I64, 14, 64),
src/station_gui.cpp
Show inline comments
 
@@ -49,280 +49,279 @@ bool _station_show_coverage;
 
 * @param amount Cargo amount
 
 * @param rating ratings data for that particular cargo
 
 *
 
 * @note Each cargo-bar is 16 pixels wide and 6 pixels high
 
 * @note Each rating 14 pixels wide and 1 pixel high and is 1 pixel below the cargo-bar
 
 */
 
static void StationsWndShowStationRating(int x, int y, CargoID type, uint amount, byte rating)
 
{
 
	static const uint units_full  = 576; ///< number of units to show station as 'full'
 
	static const uint rating_full = 224; ///< rating needed so it is shown as 'full'
 

	
 
	const CargoSpec *cs = GetCargo(type);
 
	if (!cs->IsValid()) return;
 

	
 
	int colour = cs->rating_colour;
 
	uint w = (minu(amount, units_full) + 5) / 36;
 

	
 
	/* Draw total cargo (limited) on station (fits into 16 pixels) */
 
	if (w != 0) GfxFillRect(x, y, x + w - 1, y + 6, colour);
 

	
 
	/* Draw a one pixel-wide bar of additional cargo meter, useful
 
	 * for stations with only a small amount (<=30) */
 
	if (w == 0) {
 
		uint rest = amount / 5;
 
		if (rest != 0) {
 
			w += x;
 
			GfxFillRect(w, y + 6 - rest, w, y + 6, colour);
 
		}
 
	}
 

	
 
	DrawString(x + 1, y, cs->abbrev, TC_BLACK);
 

	
 
	/* Draw green/red ratings bar (fits into 14 pixels) */
 
	y += 8;
 
	GfxFillRect(x + 1, y, x + 14, y, 0xB8);
 
	rating = minu(rating, rating_full) / 16;
 
	if (rating != 0) GfxFillRect(x + 1, y, x + rating, y, 0xD0);
 
}
 

	
 
const StringID _station_sort_listing[] = {
 
	STR_SORT_BY_DROPDOWN_NAME,
 
	STR_SORT_BY_FACILITY,
 
	STR_SORT_BY_WAITING,
 
	STR_SORT_BY_RATING_MAX,
 
	INVALID_STRING_ID
 
};
 

	
 
static char _bufcache[64];
 
static const Station* _last_station;
 
static const Station *_last_station;
 
static int _internal_sort_order;
 

	
 
static int CDECL StationNameSorter(const void *a, const void *b)
 
{
 
	const Station* st1 = *(const Station**)a;
 
	const Station* st2 = *(const Station**)b;
 
	const Station *st1 = *(const Station**)a;
 
	const Station *st2 = *(const Station**)b;
 
	char buf1[64];
 
	int r;
 

	
 
	SetDParam(0, st1->index);
 
	GetString(buf1, STR_STATION, lastof(buf1));
 

	
 
	if (st2 != _last_station) {
 
		_last_station = st2;
 
		SetDParam(0, st2->index);
 
		GetString(_bufcache, STR_STATION, lastof(_bufcache));
 
	}
 

	
 
	r = strcmp(buf1, _bufcache); // sort by name
 
	int r = strcmp(buf1, _bufcache); // sort by name
 
	return (_internal_sort_order & 1) ? -r : r;
 
}
 

	
 
static int CDECL StationTypeSorter(const void *a, const void *b)
 
{
 
	const Station* st1 = *(const Station**)a;
 
	const Station* st2 = *(const Station**)b;
 
	const Station *st1 = *(const Station**)a;
 
	const Station *st2 = *(const Station**)b;
 
	return (_internal_sort_order & 1) ? st2->facilities - st1->facilities : st1->facilities - st2->facilities;
 
}
 

	
 
static const uint32 _cargo_filter_max = ~0;
 
static const uint32 _cargo_filter_max = UINT32_MAX;
 
static uint32 _cargo_filter = _cargo_filter_max;
 

	
 
static int CDECL StationWaitingSorter(const void *a, const void *b)
 
{
 
	const Station* st1 = *(const Station**)a;
 
	const Station* st2 = *(const Station**)b;
 
	const Station *st1 = *(const Station**)a;
 
	const Station *st2 = *(const Station**)b;
 
	Money sum1 = 0, sum2 = 0;
 

	
 
	for (CargoID j = 0; j < NUM_CARGO; j++) {
 
		if (!HasBit(_cargo_filter, j)) continue;
 
		if (!st1->goods[j].cargo.Empty()) sum1 += GetTransportedGoodsIncome(st1->goods[j].cargo.Count(), 20, 50, j);
 
		if (!st2->goods[j].cargo.Empty()) sum2 += GetTransportedGoodsIncome(st2->goods[j].cargo.Count(), 20, 50, j);
 
	}
 

	
 
	return (_internal_sort_order & 1) ? ClampToI32(sum2 - sum1) : ClampToI32(sum1 - sum2);
 
}
 

	
 
/**
 
 * qsort-compatible version of sorting two stations by maximum rating
 
 * @param a   First object to be sorted, must be of type (const Station *)
 
 * @param b   Second object to be sorted, must be of type (const Station *)
 
 * @return    The sort order
 
 * @retval >0 a should come before b in the list
 
 * @retval <0 b should come before a in the list
 
 */
 
static int CDECL StationRatingMaxSorter(const void *a, const void *b)
 
{
 
	const Station* st1 = *(const Station**)a;
 
	const Station* st2 = *(const Station**)b;
 
	const Station *st1 = *(const Station**)a;
 
	const Station *st2 = *(const Station**)b;
 
	byte maxr1 = 0;
 
	byte maxr2 = 0;
 

	
 
	for (CargoID j = 0; j < NUM_CARGO; j++) {
 
		if (HasBit(st1->goods[j].acceptance_pickup, GoodsEntry::PICKUP)) maxr1 = max(maxr1, st1->goods[j].rating);
 
		if (HasBit(st2->goods[j].acceptance_pickup, GoodsEntry::PICKUP)) maxr2 = max(maxr2, st2->goods[j].rating);
 
	}
 

	
 
	return (_internal_sort_order & 1) ? maxr2 - maxr1 : maxr1 - maxr2;
 
}
 

	
 
/** Flags for station list */
 
enum StationListFlags {
 
	SL_ORDER   = 1 << 0, ///< Order - ascending (=0), descending (=1)
 
	SL_RESORT  = 1 << 1, ///< Resort the list
 
	SL_REBUILD = 1 << 2, ///< Rebuild the list
 
};
 

	
 
DECLARE_ENUM_AS_BIT_SET(StationListFlags);
 

	
 
/** Information about station list */
 
struct plstations_d {
 
	const Station** sort_list; ///< Pointer to list of stations
 
	const Station **sort_list; ///< Pointer to list of stations
 
	uint16 list_length;        ///< Number of stations in list
 
	uint16 resort_timer;       ///< Tick counter to resort the list
 
	byte sort_type;            ///< Sort type - name, waiting, ...
 
	byte flags;                ///< Flags - SL_ORDER, SL_RESORT, SL_REBUILD
 
};
 
assert_compile(WINDOW_CUSTOM_SIZE >= sizeof(plstations_d));
 

	
 
/**
 
 * Set the 'SL_REBUILD' flag for all station lists
 
 */
 
void RebuildStationLists()
 
{
 
	Window* const *wz;
 
	Window *const *wz;
 

	
 
	FOR_ALL_WINDOWS(wz) {
 
		Window *w = *wz;
 
		if (w->window_class == WC_STATION_LIST) {
 
			WP(w, plstations_d).flags |= SL_REBUILD;
 
			SetWindowDirty(w);
 
		}
 
	}
 
}
 

	
 
/**
 
 * Set the 'SL_RESORT' flag for all station lists
 
 */
 
void ResortStationLists()
 
{
 
	Window* const *wz;
 
	Window *const *wz;
 

	
 
	FOR_ALL_WINDOWS(wz) {
 
		Window *w = *wz;
 
		if (w->window_class == WC_STATION_LIST) {
 
			WP(w, plstations_d).flags |= SL_RESORT;
 
			SetWindowDirty(w);
 
		}
 
	}
 
}
 

	
 
/**
 
 * Rebuild station list if the SL_REBUILD flag is set
 
 *
 
 * @param sl pointer to plstations_d (station list and flags)
 
 * @param owner player whose stations are to be in list
 
 * @param facilities types of stations of interest
 
 * @param cargo_filter bitmap of cargo types to include
 
 * @param include_empty whether we should include stations without waiting cargo
 
 */
 
static void BuildStationsList(plstations_d* sl, PlayerID owner, byte facilities, uint32 cargo_filter, bool include_empty)
 
static void BuildStationsList(plstations_d *sl, PlayerID owner, byte facilities, uint32 cargo_filter, bool include_empty)
 
{
 
	uint n = 0;
 
	const Station *st;
 

	
 
	if (!(sl->flags & SL_REBUILD)) return;
 

	
 
	/* Create array for sorting */
 
	const Station** station_sort = MallocT<const Station*>(GetMaxStationIndex() + 1);
 
	const Station **station_sort = MallocT<const Station*>(GetMaxStationIndex() + 1);
 

	
 
	DEBUG(misc, 3, "Building station list for player %d", owner);
 

	
 
	FOR_ALL_STATIONS(st) {
 
		if (st->owner == owner || (st->owner == OWNER_NONE && !st->IsBuoy() && HasStationInUse(st->index, owner))) {
 
			if (facilities & st->facilities) { //only stations with selected facilities
 
				int num_waiting_cargo = 0;
 
				for (CargoID j = 0; j < NUM_CARGO; j++) {
 
					if (!st->goods[j].cargo.Empty()) {
 
						num_waiting_cargo++; //count number of waiting cargo
 
						if (HasBit(cargo_filter, j)) {
 
							station_sort[n++] = st;
 
							break;
 
						}
 
					}
 
				}
 
				/* stations without waiting cargo */
 
				if (num_waiting_cargo == 0 && include_empty) {
 
					station_sort[n++] = st;
 
				}
 
			}
 
		}
 
	}
 

	
 
	free((void*)sl->sort_list);
 
	sl->sort_list = MallocT<const Station*>(n);
 
	sl->list_length = n;
 

	
 
	for (uint i = 0; i < n; ++i) sl->sort_list[i] = station_sort[i];
 

	
 
	sl->flags &= ~SL_REBUILD;
 
	sl->flags |= SL_RESORT;
 
	free((void*)station_sort);
 
}
 

	
 

	
 
/**
 
 * Sort station list if the SL_RESORT flag is set
 
 *
 
 * @param sl pointer to plstations_d (station list and flags)
 
 */
 
static void SortStationsList(plstations_d *sl)
 
{
 
	static StationSortListingTypeFunction* const _station_sorter[] = {
 
	static StationSortListingTypeFunction *const _station_sorter[] = {
 
		&StationNameSorter,
 
		&StationTypeSorter,
 
		&StationWaitingSorter,
 
		&StationRatingMaxSorter
 
	};
 

	
 
	if (!(sl->flags & SL_RESORT)) return;
 

	
 
	_internal_sort_order = sl->flags & SL_ORDER;
 
	_last_station = NULL; // used for "cache" in namesorting
 
	qsort((void*)sl->sort_list, sl->list_length, sizeof(sl->sort_list[0]), _station_sorter[sl->sort_type]);
 

	
 
	sl->resort_timer = DAY_TICKS * PERIODIC_RESORT_DAYS;
 
	sl->flags &= ~SL_RESORT;
 
}
 

	
 
/**
 
 * Fuction called when any WindowEvent occurs for PlayerStations window
 
 *
 
 * @param w pointer to the PlayerStations window
 
 * @param e pointer to window event
 
 */
 
static void PlayerStationsWndProc(Window *w, WindowEvent *e)
 
{
 
	const PlayerID owner = (PlayerID)w->window_number;
 
	static byte facilities = FACIL_TRAIN | FACIL_TRUCK_STOP | FACIL_BUS_STOP | FACIL_AIRPORT | FACIL_DOCK;
 
	static Listing station_sort = {0, 0};
 
	static bool include_empty = true;
 

	
 
	plstations_d *sl = &WP(w, plstations_d);
 

	
 
	switch (e->event) {
 
		case WE_CREATE:
 
			if (_cargo_filter == _cargo_filter_max) _cargo_filter = _cargo_mask;
 

	
 
			for (uint i = 0; i < 5; i++) {
 
				if (HasBit(facilities, i)) w->LowerWidget(i + SLW_TRAIN);
 
			}
 
			w->SetWidgetLoweredState(SLW_FACILALL, facilities == (FACIL_TRAIN | FACIL_TRUCK_STOP | FACIL_BUS_STOP | FACIL_AIRPORT | FACIL_DOCK));
 
			w->SetWidgetLoweredState(SLW_CARGOALL, _cargo_filter == _cargo_mask && include_empty);
 
			w->SetWidgetLoweredState(SLW_NOCARGOWAITING, include_empty);
 

	
 
			sl->sort_list = NULL;
 
			sl->flags = SL_REBUILD;
 
			sl->sort_type = station_sort.criteria;
 
			if (station_sort.order) sl->flags |= SL_ORDER;
 

	
 
			/* set up resort timer */
 
@@ -704,162 +703,161 @@ SpriteID GetCargoSprite(CargoID i)
 
 * Draws icons of waiting cargo in the StationView window
 
 *
 
 * @param i type of cargo
 
 * @param waiting number of waiting units
 
 * @param x x on-screen coordinate where to start with drawing icons
 
 * @param y y coordinate
 
 */
 
static void DrawCargoIcons(CargoID i, uint waiting, int x, int y, uint width)
 
{
 
	uint num = min((waiting + 5) / 10, width / 10); // maximum is width / 10 icons so it won't overflow
 
	if (num == 0) return;
 

	
 
	SpriteID sprite = GetCargoSprite(i);
 

	
 
	do {
 
		DrawSprite(sprite, PAL_NONE, x, y);
 
		x += 10;
 
	} while (--num);
 
}
 

	
 
struct stationview_d {
 
	uint32 cargo;                 ///< Bitmask of cargo types to expand
 
	uint16 cargo_rows[NUM_CARGO]; ///< Header row for each cargo type
 
};
 
assert_compile(WINDOW_CUSTOM_SIZE >= sizeof(stationview_d));
 

	
 
struct CargoData {
 
	CargoID cargo;
 
	StationID source;
 
	uint count;
 

	
 
	CargoData(CargoID cargo, StationID source, uint count) :
 
		cargo(cargo),
 
		source(source),
 
		count(count)
 
	{ }
 
};
 

	
 
typedef std::list<CargoData> CargoDataList;
 

	
 
/**
 
 * Redraws whole StationView window
 
 *
 
 * @param w pointer to window
 
 */
 
static void DrawStationViewWindow(Window *w)
 
{
 
	StationID station_id = w->window_number;
 
	const Station* st = GetStation(station_id);
 
	int x, y;     ///< coordinates used for printing waiting/accepted/rating of cargo
 
	int pos;      ///< = w->vscroll.pos
 
	StringID str;
 
	const Station *st = GetStation(station_id);
 
	CargoDataList cargolist;
 
	uint32 transfers = 0;
 

	
 
	/* count types of cargos waiting in station */
 
	for (CargoID i = 0; i < NUM_CARGO; i++) {
 
		if (st->goods[i].cargo.Empty()) {
 
			WP(w, stationview_d).cargo_rows[i] = 0;
 
		} else {
 
			/* Add an entry for total amount of cargo of this type waiting. */
 
			cargolist.push_back(CargoData(i, INVALID_STATION, st->goods[i].cargo.Count()));
 

	
 
			/* Set the row for this cargo entry for the expand/hide button */
 
			WP(w, stationview_d).cargo_rows[i] = cargolist.size();
 

	
 
			/* Add an entry for each distinct cargo source. */
 
			const CargoList::List *packets = st->goods[i].cargo.Packets();
 
			for (CargoList::List::const_iterator it = packets->begin(); it != packets->end(); it++) {
 
				const CargoPacket *cp = *it;
 
				if (cp->source != station_id) {
 
					bool added = false;
 

	
 
					/* Enable the expand/hide button for this cargo type */
 
					SetBit(transfers, i);
 

	
 
					/* Don't add cargo lines if not expanded */
 
					if (!HasBit(WP(w, stationview_d).cargo, i)) break;
 

	
 
					/* Check if we already have this source in the list */
 
					for (CargoDataList::iterator jt = cargolist.begin(); jt != cargolist.end(); jt++) {
 
						CargoData *cd = &(*jt);
 
						if (cd->cargo == i && cd->source == cp->source) {
 
							cd->count += cp->count;
 
							added = true;
 
							break;
 
						}
 
					}
 

	
 
					if (!added) cargolist.push_back(CargoData(i, cp->source, cp->count));
 
				}
 
			}
 
		}
 
	}
 
	SetVScrollCount(w, cargolist.size() + 1); // update scrollbar
 

	
 
	/* disable some buttons */
 
	w->SetWidgetDisabledState(SVW_RENAME,   st->owner != _local_player);
 
	w->SetWidgetDisabledState(SVW_TRAINS,   !(st->facilities & FACIL_TRAIN));
 
	w->SetWidgetDisabledState(SVW_ROADVEHS, !(st->facilities & FACIL_TRUCK_STOP) && !(st->facilities & FACIL_BUS_STOP));
 
	w->SetWidgetDisabledState(SVW_PLANES,   !(st->facilities & FACIL_AIRPORT));
 
	w->SetWidgetDisabledState(SVW_SHIPS,    !(st->facilities & FACIL_DOCK));
 

	
 
	SetDParam(0, st->index);
 
	SetDParam(1, st->facilities);
 
	DrawWindowWidgets(w);
 

	
 
	x = 2;
 
	y = 15;
 
	pos = w->vscroll.pos;
 
	int x = 2;  ///< coordinates used for printing waiting/accepted/rating of cargo
 
	int y = 15;
 
	int pos = w->vscroll.pos; ///< = w->vscroll.pos
 

	
 
	uint width = w->widget[SVW_WAITING].right - w->widget[SVW_WAITING].left - 4;
 
	int maxrows = w->vscroll.cap;
 

	
 
	StringID str;
 

	
 
	if (--pos < 0) {
 
		str = STR_00D0_NOTHING;
 
		for (CargoID i = 0; i < NUM_CARGO; i++) {
 
			if (!st->goods[i].cargo.Empty()) str = STR_EMPTY;
 
		}
 
		SetDParam(0, str);
 
		DrawString(x, y, STR_0008_WAITING, TC_FROMSTRING);
 
		y += 10;
 
	}
 

	
 
	for (CargoDataList::const_iterator it = cargolist.begin(); it != cargolist.end() && pos > -maxrows; ++it) {
 
		if (--pos < 0) {
 
			const CargoData *cd = &(*it);
 
			if (cd->source == INVALID_STATION) {
 
				/* Heading */
 
				DrawCargoIcons(cd->cargo, cd->count, x, y, width);
 
				SetDParam(0, cd->cargo);
 
				SetDParam(1, cd->count);
 
				if (HasBit(transfers, cd->cargo)) {
 
					/* This cargo has transfers waiting so show the expand or shrink 'button' */
 
					const char *sym = HasBit(WP(w, stationview_d).cargo, cd->cargo) ? "-" : "+";
 
					DrawStringRightAligned(x + width - 8, y, STR_0009, TC_FROMSTRING);
 
					DoDrawString(sym, x + width - 6, y, TC_YELLOW);
 
				} else {
 
					DrawStringRightAligned(x + width, y, STR_0009, TC_FROMSTRING);
 
				}
 
			} else {
 
				SetDParam(0, cd->cargo);
 
				SetDParam(1, cd->count);
 
				SetDParam(2, cd->source);
 
				DrawStringRightAlignedTruncated(x + width, y, STR_EN_ROUTE_FROM, TC_FROMSTRING, width);
 
			}
 

	
 
			y += 10;
 
		}
 
	}
 

	
 
	if (w->widget[SVW_ACCEPTS].data == STR_3032_RATINGS) { // small window with list of accepted cargo
 
		char *b = _userstring;
 
		bool first = true;
 

	
 
		b = InlineString(b, STR_000C_ACCEPTS);
 

	
 
		for (CargoID i = 0; i < NUM_CARGO; i++) {
 
			if (b >= lastof(_userstring) - (1 + 2 * 4)) break; // ',' or ' ' and two calls to Utf8Encode()
 
			if (HasBit(st->goods[i].acceptance_pickup, GoodsEntry::ACCEPTANCE)) {
 
				if (first) {
 
					first = false;
0 comments (0 inline, 0 general)