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
 
@@ -61,69 +61,69 @@ 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;
 
			}
 
@@ -240,46 +240,46 @@ enum StationNaming {
 

	
 
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;
 
		}
 
	}
 
@@ -338,29 +338,29 @@ static bool GenerateStationName(Station 
 
			(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;
 
			}
 
		}
 
	}
 

	
 
@@ -376,25 +376,25 @@ static void UpdateStationVirtCoord(Stati
 

	
 
	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
 
@@ -523,25 +523,25 @@ void GetAcceptanceAroundTiles(AcceptedCa
 
			}
 
		}
 
	}
 
}
 

	
 
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
 
@@ -555,36 +555,32 @@ static void UpdateStationAcceptance(Stat
 
	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);
 
	}
 

	
 
@@ -600,34 +596,34 @@ static void UpdateStationAcceptance(Stat
 
		);
 
	} 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,
 
@@ -767,25 +763,25 @@ CommandCost CheckFlatLandBelow(TileIndex
 
				}
 
			}
 
		} 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;
 
@@ -890,57 +886,56 @@ static void GetStationLayout(byte *layou
 
 * @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);
 
@@ -1230,30 +1225,30 @@ CommandCost CmdRemoveFromRailroadStation
 
	} 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;
 
@@ -1293,25 +1288,25 @@ static CommandCost RemoveRailroadStation
 
		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;
 
	}
 
@@ -1339,51 +1334,50 @@ CommandCost CmdBuildRoadStop(TileIndex t
 
	/* 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);
 

	
 
@@ -1661,36 +1655,36 @@ static const byte * const _airport_secti
 
 * @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);
 
@@ -1707,31 +1701,33 @@ CommandCost CmdBuildAirport(TileIndex ti
 
	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;
 

	
 
@@ -1781,36 +1777,37 @@ CommandCost CmdBuildAirport(TileIndex ti
 
		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);
 
@@ -1902,25 +1899,25 @@ bool HasStationInUse(StationID station, 
 
				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;
 
@@ -1949,79 +1946,76 @@ static const TileIndexDiffC _dock_tileof
 
};
 
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;
 

	
 
@@ -2043,24 +2037,25 @@ CommandCost CmdBuildDock(TileIndex 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;
 
@@ -2122,26 +2117,24 @@ static void DrawTile_Station(TileInfo *t
 
		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) {
 
@@ -2475,25 +2468,29 @@ static VehicleEnterTileStatus VehicleEnt
 
	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
 
@@ -2613,36 +2610,37 @@ void OnTick_Station()
 

	
 
	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));
 
@@ -2685,32 +2683,32 @@ CommandCost CmdRenameStation(TileIndex t
 
		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;
 
@@ -2881,42 +2879,42 @@ void BuildOilRig(TileIndex tile)
 
		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);
 
@@ -2986,25 +2984,24 @@ static CommandCost ClearTile_Station(Til
 

	
 
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);
 
@@ -3079,61 +3076,59 @@ static const SaveLoad _roadstop_desc[] =
 
	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),
src/station_gui.cpp
Show inline comments
 
@@ -85,164 +85,163 @@ static void StationsWndShowStationRating
 
	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;
 
@@ -268,25 +267,25 @@ static void BuildStationsList(plstations
 
	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]);
 

	
 
@@ -740,28 +739,25 @@ struct CargoData {
 
};
 

	
 
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 */
 
@@ -799,31 +795,33 @@ static void DrawStationViewWindow(Window
 

	
 
	/* 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) {
0 comments (0 inline, 0 general)