@@ -1591,2692 +1591,2689 @@ CommandCost CmdRemoveFromRailWaypoint(Ti
return RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_WAYPOINT_RAIL], HasBit(p2, 0));
}
/**
* Remove a rail station/waypoint
* @param st The station/waypoint to remove the rail part from
* @param flags operation to perform
* @tparam T the type of station to remove
* @return cost or failure of operation
*/
template <class T>
CommandCost RemoveRailStation(T *st, DoCommandFlag flags)
{
/* Current company owns the station? */
if (_current_company != OWNER_WATER) {
CommandCost ret = CheckOwnership(st->owner);
if (ret.Failed()) return ret;
/* determine width and height of platforms */
TileArea ta = st->train_station;
assert(ta.w != 0 && ta.h != 0);
CommandCost cost(EXPENSES_CONSTRUCTION);
/* clear all areas of the station */
TILE_AREA_LOOP(tile, ta) {
/* only remove tiles that are actually train station tiles */
if (!st->TileBelongsToRailStation(tile)) continue;
CommandCost ret = EnsureNoVehicleOnGround(tile);
cost.AddCost(_price[PR_CLEAR_STATION_RAIL]);
if (flags & DC_EXEC) {
/* read variables before the station tile is removed */
Track track = GetRailStationTrack(tile);
Owner owner = GetTileOwner(tile); // _current_company can be OWNER_WATER
Train *v = NULL;
if (HasStationReservation(tile)) {
v = GetTrainForReservation(tile, track);
if (v != NULL) FreeTrainTrackReservation(v);
if (!IsStationTileBlocked(tile)) Company::Get(owner)->infrastructure.rail[GetRailType(tile)]--;
Company::Get(owner)->infrastructure.station--;
DoClearSquare(tile);
DeleteNewGRFInspectWindow(GSF_STATIONS, tile);
AddTrackToSignalBuffer(tile, track, owner);
YapfNotifyTrackLayoutChange(tile, track);
if (v != NULL) TryPathReserve(v, true);
st->rect.AfterRemoveRect(st, st->train_station);
st->train_station.Clear();
st->facilities &= ~FACIL_TRAIN;
free(st->speclist);
st->num_specs = 0;
st->speclist = NULL;
st->cached_anim_triggers = 0;
DirtyCompanyInfrastructureWindows(st->owner);
SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
st->UpdateVirtCoord();
DeleteStationIfEmpty(st);
return cost;
* Remove a rail station
* @param tile Tile of the station.
static CommandCost RemoveRailStation(TileIndex tile, DoCommandFlag flags)
/* if there is flooding, remove platforms tile by tile */
if (_current_company == OWNER_WATER) {
return DoCommand(tile, 0, 0, DC_EXEC, CMD_REMOVE_FROM_RAIL_STATION);
Station *st = Station::GetByTile(tile);
CommandCost cost = RemoveRailStation(st, flags);
if (flags & DC_EXEC) st->RecomputeIndustriesNear();
* Remove a rail waypoint
* @param tile Tile of the waypoint.
static CommandCost RemoveRailWaypoint(TileIndex tile, DoCommandFlag flags)
/* if there is flooding, remove waypoints tile by tile */
return DoCommand(tile, 0, 0, DC_EXEC, CMD_REMOVE_FROM_RAIL_WAYPOINT);
return RemoveRailStation(Waypoint::GetByTile(tile), flags);
* @param truck_station Determines whether a stop is #ROADSTOP_BUS or #ROADSTOP_TRUCK
* @param st The Station to do the whole procedure for
* @return a pointer to where to link a new RoadStop*
static RoadStop **FindRoadStopSpot(bool truck_station, Station *st)
RoadStop **primary_stop = (truck_station) ? &st->truck_stops : &st->bus_stops;
if (*primary_stop == NULL) {
/* we have no roadstop of the type yet, so write a "primary stop" */
return primary_stop;
} else {
/* there are stops already, so append to the end of the list */
RoadStop *stop = *primary_stop;
while (stop->next != NULL) stop = stop->next;
return &stop->next;
static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags);
* Find a nearby station that joins this road stop.
* @param existing_stop an existing road stop we build over
* @param station_to_join the station to join to
* @param adjacent whether adjacent stations are allowed
* @param ta the area of the newly build station
* @param st 'return' pointer for the found station
* @return command cost with the error or 'okay'
static CommandCost FindJoiningRoadStop(StationID existing_stop, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
return FindJoiningBaseStation<Station, STR_ERROR_MUST_REMOVE_ROAD_STOP_FIRST>(existing_stop, station_to_join, adjacent, ta, st);
* Build a bus or truck stop.
* @param tile Northernmost tile of the stop.
* @param flags Operation to perform.
* @param p1 bit 0..7: Width of the road stop.
* bit 8..15: Length of the road stop.
* @param p2 bit 0: 0 For bus stops, 1 for truck stops.
* bit 1: 0 For normal stops, 1 for drive-through.
* bit 2..3: The roadtypes.
* bit 5: Allow stations directly adjacent to other stations.
* bit 6..7: Entrance direction (#DiagDirection).
* bit 16..31: Station ID to join (NEW_STATION if build new one).
* @param text Unused.
* @return The cost of this operation or an error.
CommandCost CmdBuildRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
bool type = HasBit(p2, 0);
bool is_drive_through = HasBit(p2, 1);
RoadTypes rts = Extract<RoadTypes, 2, 2>(p2);
StationID station_to_join = GB(p2, 16, 16);
bool reuse = (station_to_join != NEW_STATION);
if (!reuse) station_to_join = INVALID_STATION;
bool distant_join = (station_to_join != INVALID_STATION);
uint8 width = (uint8)GB(p1, 0, 8);
uint8 lenght = (uint8)GB(p1, 8, 8);
/* Check if the requested road stop is too big */
if (width > _settings_game.station.station_spread || lenght > _settings_game.station.station_spread) return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
/* Check for incorrect width / length. */
if (width == 0 || lenght == 0) return CMD_ERROR;
/* Check if the first tile and the last tile are valid */
if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, lenght - 1) == INVALID_TILE) return CMD_ERROR;
TileArea roadstop_area(tile, width, lenght);
if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
if (!HasExactlyOneBit(rts) || !HasRoadTypesAvail(_current_company, rts)) return CMD_ERROR;
/* Trams only have drive through stops */
if (!is_drive_through && HasBit(rts, ROADTYPE_TRAM)) return CMD_ERROR;
DiagDirection ddir = Extract<DiagDirection, 6, 2>(p2);
/* Safeguard the parameters. */
if (!IsValidDiagDirection(ddir)) return CMD_ERROR;
/* If it is a drive-through stop, check for valid axis. */
if (is_drive_through && !IsValidAxis((Axis)ddir)) return CMD_ERROR;
CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
/* Total road stop cost. */
CommandCost cost(EXPENSES_CONSTRUCTION, roadstop_area.w * roadstop_area.h * _price[type ? PR_BUILD_STATION_TRUCK : PR_BUILD_STATION_BUS]);
StationID est = INVALID_STATION;
ret = CheckFlatLandRoadStop(roadstop_area, flags, is_drive_through ? 5 << ddir : 1 << ddir, is_drive_through, type, DiagDirToAxis(ddir), &est, rts);
cost.AddCost(ret);
Station *st = NULL;
ret = FindJoiningRoadStop(est, station_to_join, HasBit(p2, 5), roadstop_area, &st);
/* Check if this number of road stops can be allocated. */
if (!RoadStop::CanAllocateItem(roadstop_area.w * roadstop_area.h)) return_cmd_error(type ? STR_ERROR_TOO_MANY_TRUCK_STOPS : STR_ERROR_TOO_MANY_BUS_STOPS);
ret = BuildStationPart(&st, flags, reuse, roadstop_area, STATIONNAMING_ROAD);
/* Check every tile in the area. */
TILE_AREA_LOOP(cur_tile, roadstop_area) {
RoadTypes cur_rts = GetRoadTypes(cur_tile);
Owner road_owner = HasBit(cur_rts, ROADTYPE_ROAD) ? GetRoadOwner(cur_tile, ROADTYPE_ROAD) : _current_company;
Owner tram_owner = HasBit(cur_rts, ROADTYPE_TRAM) ? GetRoadOwner(cur_tile, ROADTYPE_TRAM) : _current_company;
if (IsTileType(cur_tile, MP_STATION) && IsRoadStop(cur_tile)) {
RemoveRoadStop(cur_tile, flags);
RoadStop *road_stop = new RoadStop(cur_tile);
/* Insert into linked list of RoadStops. */
RoadStop **currstop = FindRoadStopSpot(type, st);
*currstop = road_stop;
if (type) {
st->truck_station.Add(cur_tile);
st->bus_station.Add(cur_tile);
/* Initialize an empty station. */
st->AddFacility((type) ? FACIL_TRUCK_STOP : FACIL_BUS_STOP, cur_tile);
st->rect.BeforeAddTile(cur_tile, StationRect::ADD_TRY);
RoadStopType rs_type = type ? ROADSTOP_TRUCK : ROADSTOP_BUS;
if (is_drive_through) {
/* Update company infrastructure counts. If the current tile is a normal
* road tile, count only the new road bits needed to get a full diagonal road. */
RoadType rt;
FOR_EACH_SET_ROADTYPE(rt, cur_rts | rts) {
Company *c = Company::GetIfValid(rt == ROADTYPE_ROAD ? road_owner : tram_owner);
if (c != NULL) {
c->infrastructure.road[rt] += 2 - (IsNormalRoadTile(cur_tile) && HasBit(cur_rts, rt) ? CountBits(GetRoadBits(cur_tile, rt)) : 0);
DirtyCompanyInfrastructureWindows(c->index);
MakeDriveThroughRoadStop(cur_tile, st->owner, road_owner, tram_owner, st->index, rs_type, rts | cur_rts, DiagDirToAxis(ddir));
road_stop->MakeDriveThrough();
/* Non-drive-through stop never overbuild and always count as two road bits. */
Company::Get(st->owner)->infrastructure.road[FIND_FIRST_BIT(rts)] += 2;
MakeRoadStop(cur_tile, st->owner, st->index, rs_type, rts, ddir);
Company::Get(st->owner)->infrastructure.station++;
MarkTileDirtyByTile(cur_tile);
if (st != NULL) {
UpdateStationAcceptance(st, false);
st->RecomputeIndustriesNear();
InvalidateWindowData(WC_SELECT_STATION, 0, 0);
InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_ROADVEHS);
static Vehicle *ClearRoadStopStatusEnum(Vehicle *v, void *)
if (v->type == VEH_ROAD) {
/* Okay... we are a road vehicle on a drive through road stop.
* But that road stop has just been removed, so we need to make
* sure we are in a valid state... however, vehicles can also
* turn on road stop tiles, so only clear the 'road stop' state
* bits and only when the state was 'in road stop', otherwise
* we'll end up clearing the turn around bits. */
RoadVehicle *rv = RoadVehicle::From(v);
if (HasBit(rv->state, RVS_IN_DT_ROAD_STOP)) rv->state &= RVSB_ROAD_STOP_TRACKDIR_MASK;
return NULL;
* Remove a bus station/truck stop
* @param tile TileIndex been queried
static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags)
bool is_truck = IsTruckStop(tile);
RoadStop **primary_stop;
RoadStop *cur_stop;
if (is_truck) { // truck stop
primary_stop = &st->truck_stops;
cur_stop = RoadStop::GetByTile(tile, ROADSTOP_TRUCK);
primary_stop = &st->bus_stops;
cur_stop = RoadStop::GetByTile(tile, ROADSTOP_BUS);
assert(cur_stop != NULL);
/* don't do the check for drive-through road stops when company bankrupts */
if (IsDriveThroughStopTile(tile) && (flags & DC_BANKRUPT)) {
/* remove the 'going through road stop' status from all vehicles on that tile */
if (flags & DC_EXEC) FindVehicleOnPos(tile, NULL, &ClearRoadStopStatusEnum);
if (*primary_stop == cur_stop) {
/* removed the first stop in the list */
*primary_stop = cur_stop->next;
/* removed the only stop? */
st->facilities &= (is_truck ? ~FACIL_TRUCK_STOP : ~FACIL_BUS_STOP);
/* tell the predecessor in the list to skip this stop */
RoadStop *pred = *primary_stop;
while (pred->next != cur_stop) pred = pred->next;
pred->next = cur_stop->next;
/* Update company infrastructure counts. */
FOR_EACH_SET_ROADTYPE(rt, GetRoadTypes(tile)) {
Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
c->infrastructure.road[rt] -= 2;
Company::Get(st->owner)->infrastructure.station--;
if (IsDriveThroughStopTile(tile)) {
/* Clears the tile for us */
cur_stop->ClearDriveThrough();
delete cur_stop;
/* Make sure no vehicle is going to the old roadstop */
RoadVehicle *v;
FOR_ALL_ROADVEHICLES(v) {
if (v->First() == v && v->current_order.IsType(OT_GOTO_STATION) &&
v->dest_tile == tile) {
v->dest_tile = v->GetOrderStationLocation(st->index);
st->rect.AfterRemoveTile(st, tile);
/* Update the tile area of the truck/bus stop */
if (is_truck) {
st->truck_station.Clear();
for (const RoadStop *rs = st->truck_stops; rs != NULL; rs = rs->next) st->truck_station.Add(rs->xy);
st->bus_station.Clear();
for (const RoadStop *rs = st->bus_stops; rs != NULL; rs = rs->next) st->bus_station.Add(rs->xy);
return CommandCost(EXPENSES_CONSTRUCTION, _price[is_truck ? PR_CLEAR_STATION_TRUCK : PR_CLEAR_STATION_BUS]);
* Remove bus or truck stops.
* @param tile Northernmost tile of the removal area.
* @param p1 bit 0..7: Width of the removal area.
* bit 8..15: Height of the removal area.
CommandCost CmdRemoveRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
uint8 height = (uint8)GB(p1, 8, 8);
/* Check for incorrect width / height. */
if (width == 0 || height == 0) return CMD_ERROR;
if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, height - 1) == INVALID_TILE) return CMD_ERROR;
TileArea roadstop_area(tile, width, height);
int quantity = 0;
/* Make sure the specified tile is a road stop of the correct type */
if (!IsTileType(cur_tile, MP_STATION) || !IsRoadStop(cur_tile) || (uint32)GetRoadStopType(cur_tile) != GB(p2, 0, 1)) continue;
/* Save the stop info before it is removed */
bool is_drive_through = IsDriveThroughStopTile(cur_tile);
RoadTypes rts = GetRoadTypes(cur_tile);
RoadBits road_bits = IsDriveThroughStopTile(cur_tile) ?
((GetRoadStopDir(cur_tile) == DIAGDIR_NE) ? ROAD_X : ROAD_Y) :
DiagDirToRoadBits(GetRoadStopDir(cur_tile));
Owner road_owner = GetRoadOwner(cur_tile, ROADTYPE_ROAD);
Owner tram_owner = GetRoadOwner(cur_tile, ROADTYPE_TRAM);
CommandCost ret = RemoveRoadStop(cur_tile, flags);
quantity++;
/* If the stop was a drive-through stop replace the road */
if ((flags & DC_EXEC) && is_drive_through) {
MakeRoadNormal(cur_tile, road_bits, rts, ClosestTownFromTile(cur_tile, UINT_MAX)->index,
road_owner, tram_owner);
FOR_EACH_SET_ROADTYPE(rt, rts) {
Company *c = Company::GetIfValid(GetRoadOwner(cur_tile, rt));
c->infrastructure.road[rt] += CountBits(road_bits);
if (quantity == 0) return_cmd_error(STR_ERROR_THERE_IS_NO_STATION);
* Computes the minimal distance from town's xy to any airport's tile.
* @param it An iterator over all airport tiles.
* @param town_tile town's tile (t->xy)
* @return minimal manhattan distance from town_tile to any airport's tile
static uint GetMinimalAirportDistanceToTile(TileIterator &it, TileIndex town_tile)
uint mindist = UINT_MAX;
for (TileIndex cur_tile = it; cur_tile != INVALID_TILE; cur_tile = ++it) {
mindist = min(mindist, DistanceManhattan(town_tile, cur_tile));
return mindist;
* Get a possible noise reduction factor based on distance from town center.
* The further you get, the less noise you generate.
* So all those folks at city council can now happily slee... work in their offices
* @param as airport information
* @param town_tile TileIndex of town's center, the one who will receive the airport's candidature
* @return the noise that will be generated, according to distance
uint8 GetAirportNoiseLevelForTown(const AirportSpec *as, TileIterator &it, TileIndex town_tile)
/* 0 cannot be accounted, and 1 is the lowest that can be reduced from town.
* So no need to go any further*/
if (as->noise_level < 2) return as->noise_level;
uint distance = GetMinimalAirportDistanceToTile(it, town_tile);
/* The steps for measuring noise reduction are based on the "magical" (and arbitrary) 8 base distance
* adding the town_council_tolerance 4 times, as a way to graduate, depending of the tolerance.
* Basically, it says that the less tolerant a town is, the bigger the distance before
* an actual decrease can be granted */
uint8 town_tolerance_distance = 8 + (_settings_game.difficulty.town_council_tolerance * 4);
/* now, we want to have the distance segmented using the distance judged bareable by town
* This will give us the coefficient of reduction the distance provides. */
uint noise_reduction = distance / town_tolerance_distance;
/* If the noise reduction equals the airport noise itself, don't give it for free.
* Otherwise, simply reduce the airport's level. */
return noise_reduction >= as->noise_level ? 1 : as->noise_level - noise_reduction;
* Finds the town nearest to given airport. Based on minimal manhattan distance to any airport's tile.
* If two towns have the same distance, town with lower index is returned.
* @param as airport's description
* @param it An iterator over all airport tiles
* @return nearest town to airport
Town *AirportGetNearestTown(const AirportSpec *as, const TileIterator &it)
Town *t, *nearest = NULL;
uint add = as->size_x + as->size_y - 2; // GetMinimalAirportDistanceToTile can differ from DistanceManhattan by this much
uint mindist = UINT_MAX - add; // prevent overflow
FOR_ALL_TOWNS(t) {
if (DistanceManhattan(t->xy, it) < mindist + add) { // avoid calling GetMinimalAirportDistanceToTile too often
TileIterator *copy = it.Clone();
uint dist = GetMinimalAirportDistanceToTile(*copy, t->xy);
delete copy;
if (dist < mindist) {
nearest = t;
mindist = dist;
return nearest;
/** Recalculate the noise generated by the airports of each town */
void UpdateAirportsNoise()
Town *t;
const Station *st;
FOR_ALL_TOWNS(t) t->noise_reached = 0;
FOR_ALL_STATIONS(st) {
if (st->airport.tile != INVALID_TILE && st->airport.type != AT_OILRIG) {
const AirportSpec *as = st->airport.GetSpec();
AirportTileIterator it(st);
Town *nearest = AirportGetNearestTown(as, it);
nearest->noise_reached += GetAirportNoiseLevelForTown(as, it, nearest->xy);
* Place an Airport.
* @param tile tile where airport will be built
* @param p1
* - p1 = (bit 0- 7) - airport type, @see airport.h
* - p1 = (bit 8-15) - airport layout
* @param p2 various bitstuffed elements
* - p2 = (bit 0) - allow airports directly adjacent to other airports.
* - p2 = (bit 16-31) - station ID to join (NEW_STATION if build new one)
* @param text unused
* @return the cost of this operation or an error
CommandCost CmdBuildAirport(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
byte airport_type = GB(p1, 0, 8);
byte layout = GB(p1, 8, 8);
if (airport_type >= NUM_AIRPORTS) return CMD_ERROR;
/* Check if a valid, buildable airport was chosen for construction */
const AirportSpec *as = AirportSpec::Get(airport_type);
if (!as->IsAvailable() || layout >= as->num_table) return CMD_ERROR;
Direction rotation = as->rotation[layout];
int w = as->size_x;
int h = as->size_y;
if (rotation == DIR_E || rotation == DIR_W) Swap(w, h);
TileArea airport_area = TileArea(tile, w, h);
if (w > _settings_game.station.station_spread || h > _settings_game.station.station_spread) {
return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
CommandCost cost = CheckFlatLand(airport_area, flags);
if (cost.Failed()) return cost;
/* The noise level is the noise from the airport and reduce it to account for the distance to the town center. */
AirportTileTableIterator iter(as->table[layout], tile);
Town *nearest = AirportGetNearestTown(as, iter);
uint newnoise_level = GetAirportNoiseLevelForTown(as, iter, nearest->xy);
/* Check if local auth would allow a new airport */
StringID authority_refuse_message = STR_NULL;
Town *authority_refuse_town = NULL;
if (_settings_game.economy.station_noise_level) {
/* do not allow to build a new airport if this raise the town noise over the maximum allowed by town */
if ((nearest->noise_reached + newnoise_level) > nearest->MaxTownNoise()) {
authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_NOISE;
authority_refuse_town = nearest;
Town *t = ClosestTownFromTile(tile, UINT_MAX);
uint num = 0;
if (st->town == t && (st->facilities & FACIL_AIRPORT) && st->airport.type != AT_OILRIG) num++;
if (num >= 2) {
authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_AIRPORT;
authority_refuse_town = t;
if (authority_refuse_message != STR_NULL) {
SetDParam(0, authority_refuse_town->index);
return_cmd_error(authority_refuse_message);
ret = FindJoiningStation(INVALID_STATION, station_to_join, HasBit(p2, 0), airport_area, &st);
/* Distant join */
if (st == NULL && distant_join) st = Station::GetIfValid(station_to_join);
ret = BuildStationPart(&st, flags, reuse, airport_area, (GetAirport(airport_type)->flags & AirportFTAClass::AIRPLANES) ? STATIONNAMING_AIRPORT : STATIONNAMING_HELIPORT);
if (st != NULL && st->airport.tile != INVALID_TILE) {
return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_AIRPORT);
for (AirportTileTableIterator iter(as->table[layout], tile); iter != INVALID_TILE; ++iter) {
cost.AddCost(_price[PR_BUILD_STATION_AIRPORT]);
/* Always add the noise, so there will be no need to recalculate when option toggles */
nearest->noise_reached += newnoise_level;
st->AddFacility(FACIL_AIRPORT, tile);
st->airport.type = airport_type;
st->airport.layout = layout;
st->airport.flags = 0;
st->airport.rotation = rotation;
st->rect.BeforeAddRect(tile, w, h, StationRect::ADD_TRY);
MakeAirport(iter, st->owner, st->index, iter.GetStationGfx(), WATER_CLASS_INVALID);
SetStationTileRandomBits(iter, GB(Random(), 0, 4));
st->airport.Add(iter);
if (AirportTileSpec::Get(GetTranslatedAirportTileID(iter.GetStationGfx()))->animation.status != ANIM_STATUS_NO_ANIMATION) AddAnimatedTile(iter);
/* Only call the animation trigger after all tiles have been built */
AirportTileAnimationTrigger(st, iter, AAT_BUILT);
UpdateAirplanesOnNewStation(st);
Company::Get(st->owner)->infrastructure.airport++;
InvalidateWindowData(WC_STATION_VIEW, st->index, -1);
SetWindowDirty(WC_TOWN_VIEW, st->town->index);
* Remove an airport
static CommandCost RemoveAirport(TileIndex tile, DoCommandFlag flags)
tile = st->airport.tile;
const Aircraft *a;
FOR_ALL_AIRCRAFT(a) {
if (!a->IsNormalAircraft()) continue;
if (a->targetairport == st->index && a->state != FLYING) return CMD_ERROR;
/* The noise level is the noise from the airport and reduce it to account for the distance to the town center.
* And as for construction, always remove it, even if the setting is not set, in order to avoid the
* need of recalculation */
nearest->noise_reached -= GetAirportNoiseLevelForTown(as, it, nearest->xy);
TILE_AREA_LOOP(tile_cur, st->airport) {
if (!st->TileBelongsToAirport(tile_cur)) continue;
CommandCost ret = EnsureNoVehicleOnGround(tile_cur);
cost.AddCost(_price[PR_CLEAR_STATION_AIRPORT]);
if (IsHangarTile(tile_cur)) OrderBackup::Reset(tile_cur, false);
DeleteAnimatedTile(tile_cur);
DoClearSquare(tile_cur);
DeleteNewGRFInspectWindow(GSF_AIRPORTTILES, tile_cur);
/* Clear the persistent storage. */
delete st->airport.psa;
for (uint i = 0; i < st->airport.GetNumHangars(); ++i) {
DeleteWindowById(
WC_VEHICLE_DEPOT, st->airport.GetHangarTile(i)
);
st->rect.AfterRemoveRect(st, st->airport);
st->airport.Clear();
st->facilities &= ~FACIL_AIRPORT;
Company::Get(st->owner)->infrastructure.airport--;
DeleteNewGRFInspectWindow(GSF_AIRPORTS, st->index);
* Open/close an airport to incoming aircraft.
* @param tile Unused.
* @param p1 Station ID of the airport.
* @param p2 Unused.
CommandCost CmdOpenCloseAirport(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
if (!Station::IsValidID(p1)) return CMD_ERROR;
Station *st = Station::Get(p1);
if (!(st->facilities & FACIL_AIRPORT) || st->owner == OWNER_NONE) return CMD_ERROR;
st->airport.flags ^= AIRPORT_CLOSED_block;
SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_CLOSE_AIRPORT);
return CommandCost();
* Tests whether the company's vehicles have this station in orders
* @param station station ID
* @param include_company If true only check vehicles of \a company, if false only check vehicles of other companies
* @param company company ID
bool HasStationInUse(StationID station, bool include_company, CompanyID company)
const Vehicle *v;
FOR_ALL_VEHICLES(v) {
if ((v->owner == company) == include_company) {
const Order *order;
FOR_VEHICLE_ORDERS(v, order) {
if ((order->IsType(OT_GOTO_STATION) || order->IsType(OT_GOTO_WAYPOINT)) && order->GetDestination() == station) {
return true;
return false;
static const TileIndexDiffC _dock_tileoffs_chkaround[] = {
{-1, 0},
{ 0, 0},
{ 0, -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 p1 (bit 0) - allow docks directly adjacent to other docks.
* @param p2 bit 16-31: station ID to join (NEW_STATION if build new one)
CommandCost CmdBuildDock(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
DiagDirection direction = GetInclinedSlopeDirection(GetTileSlope(tile));
if (direction == INVALID_DIAGDIR) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
direction = ReverseDiagDir(direction);
/* Docks cannot be placed on rapids */
if (HasTileWaterGround(tile)) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
TileIndex tile_cur = tile + TileOffsByDiagDir(direction);
if (!IsTileType(tile_cur, MP_WATER) || GetTileSlope(tile_cur) != SLOPE_FLAT) {
return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
if (MayHaveBridgeAbove(tile_cur) && IsBridgeAbove(tile_cur)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
/* Get the water class of the water tile before it is cleared.*/
WaterClass wc = GetWaterClass(tile_cur);
ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
tile_cur += TileOffsByDiagDir(direction);
TileArea dock_area = TileArea(tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
_dock_w_chk[direction], _dock_h_chk[direction]);
/* middle */
ret = FindJoiningStation(INVALID_STATION, station_to_join, HasBit(p1, 0), dock_area, &st);
ret = BuildStationPart(&st, flags, reuse, dock_area, STATIONNAMING_DOCK);
if (st != NULL && st->dock_tile != INVALID_TILE) return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_DOCK);
st->dock_tile = tile;
st->AddFacility(FACIL_DOCK, tile);
st->rect.BeforeAddRect(dock_area.tile, dock_area.w, dock_area.h, StationRect::ADD_TRY);
/* If the water part of the dock is on a canal, update infrastructure counts.
* This is needed as we've unconditionally cleared that tile before. */
if (wc == WATER_CLASS_CANAL) {
Company::Get(st->owner)->infrastructure.water++;
Company::Get(st->owner)->infrastructure.station += 2;
MakeDock(tile, st->owner, st->index, direction, wc);
SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_SHIPS);
return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_STATION_DOCK]);
* Remove a dock
static CommandCost RemoveDock(TileIndex tile, DoCommandFlag flags)
TileIndex docking_location = TILE_ADD(st->dock_tile, ToTileIndexDiff(GetDockOffset(st->dock_tile)));
TileIndex tile1 = st->dock_tile;
TileIndex tile2 = tile1 + TileOffsByDiagDir(GetDockDirection(tile1));
ret = EnsureNoVehicleOnGround(tile1);
if (ret.Succeeded()) ret = EnsureNoVehicleOnGround(tile2);
DoClearSquare(tile1);
MarkTileDirtyByTile(tile1);
MakeWaterKeepingClass(tile2, st->owner);
st->rect.AfterRemoveTile(st, tile1);
st->rect.AfterRemoveTile(st, tile2);
st->dock_tile = INVALID_TILE;
st->facilities &= ~FACIL_DOCK;
Company::Get(st->owner)->infrastructure.station -= 2;
/* All ships that were going to our station, can't go to it anymore.
* Just clear the order, then automatically the next appropriate order
* will be selected and in case of no appropriate order it will just
* wander around the world. */
Ship *s;
FOR_ALL_SHIPS(s) {
if (s->current_order.IsType(OT_LOADING) && s->tile == docking_location) {
s->LeaveStation();
if (s->dest_tile == docking_location) {
s->dest_tile = 0;
s->current_order.Free();
return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_STATION_DOCK]);
#include "table/station_land.h"
const DrawTileSprites *GetStationTileLayout(StationType st, byte gfx)
return &_station_display_datas[st][gfx];
* Check whether a sprite is a track sprite, which can be replaced by a non-track ground sprite and a rail overlay.
* If the ground sprite is suitable, \a ground is replaced with the new non-track ground sprite, and \a overlay_offset
* is set to the overlay to draw.
* @param ti Positional info for the tile to decide snowyness etc. May be NULL.
* @param [in,out] ground Groundsprite to draw.
* @param [out] overlay_offset Overlay to draw.
* @return true if overlay can be drawn.
bool SplitGroundSpriteForOverlay(const TileInfo *ti, SpriteID *ground, RailTrackOffset *overlay_offset)
bool snow_desert;
switch (*ground) {
case SPR_RAIL_TRACK_X:
snow_desert = false;
*overlay_offset = RTO_X;
break;
case SPR_RAIL_TRACK_Y:
*overlay_offset = RTO_Y;
case SPR_RAIL_TRACK_X_SNOW:
snow_desert = true;
case SPR_RAIL_TRACK_Y_SNOW:
default:
if (ti != NULL) {
/* Decide snow/desert from tile */
switch (_settings_game.game_creation.landscape) {
case LT_ARCTIC:
snow_desert = (uint)ti->z > GetSnowLine() * TILE_HEIGHT;
case LT_TROPIC:
snow_desert = GetTropicZone(ti->tile) == TROPICZONE_DESERT;
*ground = snow_desert ? SPR_FLAT_SNOW_DESERT_TILE : SPR_FLAT_GRASS_TILE;
static void DrawTile_Station(TileInfo *ti)
const NewGRFSpriteLayout *layout = NULL;
DrawTileSprites tmp_rail_layout;
const DrawTileSprites *t = NULL;
RoadTypes roadtypes;
int32 total_offset;
const RailtypeInfo *rti = NULL;
uint32 relocation = 0;
uint32 ground_relocation = 0;
BaseStation *st = NULL;
const StationSpec *statspec = NULL;
uint tile_layout = 0;
if (HasStationRail(ti->tile)) {
rti = GetRailTypeInfo(GetRailType(ti->tile));
roadtypes = ROADTYPES_NONE;
total_offset = rti->GetRailtypeSpriteOffset();
if (IsCustomStationSpecIndex(ti->tile)) {
/* look for customization */
st = BaseStation::GetByTile(ti->tile);
statspec = st->speclist[GetCustomStationSpecIndex(ti->tile)].spec;
if (statspec != NULL) {
tile_layout = GetStationGfx(ti->tile);
if (HasBit(statspec->callback_mask, CBM_STATION_SPRITE_LAYOUT)) {
uint16 callback = GetStationCallback(CBID_STATION_SPRITE_LAYOUT, 0, 0, statspec, st, ti->tile);
if (callback != CALLBACK_FAILED) tile_layout = (callback & ~1) + GetRailStationAxis(ti->tile);
/* Ensure the chosen tile layout is valid for this custom station */
if (statspec->renderdata != NULL) {
layout = &statspec->renderdata[tile_layout < statspec->tiles ? tile_layout : (uint)GetRailStationAxis(ti->tile)];
if (!layout->NeedsPreprocessing()) {
t = layout;
layout = NULL;
roadtypes = IsRoadStop(ti->tile) ? GetRoadTypes(ti->tile) : ROADTYPES_NONE;
total_offset = 0;
StationGfx gfx = GetStationGfx(ti->tile);
if (IsAirport(ti->tile)) {
gfx = GetAirportGfx(ti->tile);
if (gfx >= NEW_AIRPORTTILE_OFFSET) {
const AirportTileSpec *ats = AirportTileSpec::Get(gfx);
if (ats->grf_prop.spritegroup[0] != NULL && DrawNewAirportTile(ti, Station::GetByTile(ti->tile), gfx, ats)) {
return;
/* No sprite group (or no valid one) found, meaning no graphics associated.
* Use the substitute one instead */
assert(ats->grf_prop.subst_id != INVALID_AIRPORTTILE);
gfx = ats->grf_prop.subst_id;
switch (gfx) {
case APT_RADAR_GRASS_FENCE_SW:
t = &_station_display_datas_airport_radar_grass_fence_sw[GetAnimationFrame(ti->tile)];
case APT_GRASS_FENCE_NE_FLAG:
t = &_station_display_datas_airport_flag_grass_fence_ne[GetAnimationFrame(ti->tile)];
case APT_RADAR_FENCE_SW:
t = &_station_display_datas_airport_radar_fence_sw[GetAnimationFrame(ti->tile)];
case APT_RADAR_FENCE_NE:
t = &_station_display_datas_airport_radar_fence_ne[GetAnimationFrame(ti->tile)];
case APT_GRASS_FENCE_NE_FLAG_2:
t = &_station_display_datas_airport_flag_grass_fence_ne_2[GetAnimationFrame(ti->tile)];
Owner owner = GetTileOwner(ti->tile);
PaletteID palette;
if (Company::IsValidID(owner)) {
palette = COMPANY_SPRITE_COLOUR(owner);
/* Some stations are not owner by a company, namely oil rigs */
palette = PALETTE_TO_GREY;
if (layout == NULL && (t == NULL || t->seq == NULL)) t = GetStationTileLayout(GetStationType(ti->tile), gfx);
/* don't show foundation for docks */
if (ti->tileh != SLOPE_FLAT && !IsDock(ti->tile)) {
if (statspec != NULL && HasBit(statspec->flags, SSF_CUSTOM_FOUNDATIONS)) {
/* Station has custom foundations.
* Check whether the foundation continues beyond the tile's upper sides. */
uint edge_info = 0;
int z;
Slope slope = GetFoundationPixelSlope(ti->tile, &z);
if (!HasFoundationNW(ti->tile, slope, z)) SetBit(edge_info, 0);
if (!HasFoundationNE(ti->tile, slope, z)) SetBit(edge_info, 1);
SpriteID image = GetCustomStationFoundationRelocation(statspec, st, ti->tile, tile_layout, edge_info);
if (image == 0) goto draw_default_foundation;
if (HasBit(statspec->flags, SSF_EXTENDED_FOUNDATIONS)) {
/* Station provides extended foundations. */
static const uint8 foundation_parts[] = {
0, 0, 0, 0, // Invalid, Invalid, Invalid, SLOPE_SW
0, 1, 2, 3, // Invalid, SLOPE_EW, SLOPE_SE, SLOPE_WSE
0, 4, 5, 6, // Invalid, SLOPE_NW, SLOPE_NS, SLOPE_NWS
7, 8, 9 // SLOPE_NE, SLOPE_ENW, SLOPE_SEN
AddSortableSpriteToDraw(image + foundation_parts[ti->tileh], PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
/* Draw simple foundations, built up from 8 possible foundation sprites. */
/* Each set bit represents one of the eight composite sprites to be drawn.
* 'Invalid' entries will not drawn but are included for completeness. */
static const uint8 composite_foundation_parts[] = {
/* Invalid (00000000), Invalid (11010001), Invalid (11100100), SLOPE_SW (11100000) */
0x00, 0xD1, 0xE4, 0xE0,
/* Invalid (11001010), SLOPE_EW (11001001), SLOPE_SE (11000100), SLOPE_WSE (11000000) */
0xCA, 0xC9, 0xC4, 0xC0,
/* Invalid (11010010), SLOPE_NW (10010001), SLOPE_NS (11100100), SLOPE_NWS (10100000) */
0xD2, 0x91, 0xE4, 0xA0,
/* SLOPE_NE (01001010), SLOPE_ENW (00001001), SLOPE_SEN (01000100) */
0x4A, 0x09, 0x44
uint8 parts = composite_foundation_parts[ti->tileh];
/* If foundations continue beyond the tile's upper sides then
* mask out the last two pieces. */
if (HasBit(edge_info, 0)) ClrBit(parts, 6);
if (HasBit(edge_info, 1)) ClrBit(parts, 7);
if (parts == 0) {
/* We always have to draw at least one sprite to make sure there is a boundingbox and a sprite with the
* correct offset for the childsprites.
* So, draw the (completely empty) sprite of the default foundations. */
goto draw_default_foundation;
StartSpriteCombine();
for (int i = 0; i < 8; i++) {
if (HasBit(parts, i)) {
AddSortableSpriteToDraw(image + i, PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
EndSpriteCombine();
OffsetGroundSprite(31, 1);
ti->z += ApplyPixelFoundationToSlope(FOUNDATION_LEVELED, &ti->tileh);
draw_default_foundation:
DrawFoundation(ti, FOUNDATION_LEVELED);
if (IsBuoy(ti->tile)) {
DrawWaterClassGround(ti);
SpriteID sprite = GetCanalSprite(CF_BUOY, ti->tile);
if (sprite != 0) total_offset = sprite - SPR_IMG_BUOY;
} else if (IsDock(ti->tile) || (IsOilRig(ti->tile) && IsTileOnWater(ti->tile))) {
if (ti->tileh == SLOPE_FLAT) {
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);
DrawClearLandTile(ti, 3);
if (layout != NULL) {
/* Sprite layout which needs preprocessing */
bool separate_ground = HasBit(statspec->flags, SSF_SEPARATE_GROUND);
uint32 var10_values = layout->PrepareLayout(total_offset, rti->fallback_railtype, 0, 0, separate_ground);
uint8 var10;
FOR_EACH_SET_BIT(var10, var10_values) {
uint32 var10_relocation = GetCustomStationRelocation(statspec, st, ti->tile, var10);
layout->ProcessRegisters(var10, var10_relocation, separate_ground);
tmp_rail_layout.seq = layout->GetLayout(&tmp_rail_layout.ground);
t = &tmp_rail_layout;
} else if (statspec != NULL) {
/* Simple sprite layout */
ground_relocation = relocation = GetCustomStationRelocation(statspec, st, ti->tile, 0);
if (HasBit(statspec->flags, SSF_SEPARATE_GROUND)) {
ground_relocation = GetCustomStationRelocation(statspec, st, ti->tile, 1);
ground_relocation += rti->fallback_railtype;
SpriteID image = t->ground.sprite;
PaletteID pal = t->ground.pal;
RailTrackOffset overlay_offset;
if (rti != NULL && rti->UsesOverlay() && SplitGroundSpriteForOverlay(ti, &image, &overlay_offset)) {
SpriteID ground = GetCustomRailSprite(rti, ti->tile, RTSG_GROUND);
DrawGroundSprite(image, PAL_NONE);
DrawGroundSprite(ground + overlay_offset, PAL_NONE);
if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationReservation(ti->tile)) {
SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
DrawGroundSprite(overlay + overlay_offset, PALETTE_CRASH);
image += HasBit(image, SPRITE_MODIFIER_CUSTOM_SPRITE) ? ground_relocation : total_offset;
if (HasBit(pal, SPRITE_MODIFIER_CUSTOM_SPRITE)) pal += ground_relocation;
DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, palette));
/* PBS debugging, draw reserved tracks darker */
if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationRail(ti->tile) && HasStationReservation(ti->tile)) {
const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
DrawGroundSprite(GetRailStationAxis(ti->tile) == AXIS_X ? rti->base_sprites.single_x : rti->base_sprites.single_y, PALETTE_CRASH);
if (HasStationRail(ti->tile) && HasCatenaryDrawn(GetRailType(ti->tile))) DrawCatenary(ti);
if (HasBit(roadtypes, ROADTYPE_TRAM)) {
Axis axis = GetRoadStopDir(ti->tile) == DIAGDIR_NE ? AXIS_X : AXIS_Y;
DrawGroundSprite((HasBit(roadtypes, ROADTYPE_ROAD) ? SPR_TRAMWAY_OVERLAY : SPR_TRAMWAY_TRAM) + (axis ^ 1), PAL_NONE);
DrawTramCatenary(ti, axis == AXIS_X ? ROAD_X : ROAD_Y);
if (IsRailWaypoint(ti->tile)) {
/* Don't offset the waypoint graphics; they're always the same. */
DrawRailTileSeq(ti, t, TO_BUILDINGS, total_offset, relocation, palette);
void StationPickerDrawSprite(int x, int y, StationType st, RailType railtype, RoadType roadtype, int image)
int32 total_offset = 0;
PaletteID pal = COMPANY_SPRITE_COLOUR(_local_company);
const DrawTileSprites *t = GetStationTileLayout(st, image);
if (railtype != INVALID_RAILTYPE) {
rti = GetRailTypeInfo(railtype);
SpriteID img = t->ground.sprite;
if (rti != NULL && rti->UsesOverlay() && SplitGroundSpriteForOverlay(NULL, &img, &overlay_offset)) {
SpriteID ground = GetCustomRailSprite(rti, INVALID_TILE, RTSG_GROUND);
DrawSprite(img, PAL_NONE, x, y);
DrawSprite(ground + overlay_offset, PAL_NONE, x, y);
DrawSprite(img + total_offset, HasBit(img, PALETTE_MODIFIER_COLOUR) ? pal : PAL_NONE, x, y);
if (roadtype == ROADTYPE_TRAM) {
DrawSprite(SPR_TRAMWAY_TRAM + (t->ground.sprite == SPR_ROAD_PAVED_STRAIGHT_X ? 1 : 0), PAL_NONE, x, y);
/* Default waypoint has no railtype specific sprites */
DrawRailTileSeqInGUI(x, y, t, st == STATION_WAYPOINT ? 0 : total_offset, 0, pal);
static int GetSlopePixelZ_Station(TileIndex tile, uint x, uint y)
return GetTileMaxPixelZ(tile);
static Foundation GetFoundation_Station(TileIndex tile, Slope tileh)
return FlatteningFoundation(tileh);
static void GetTileDesc_Station(TileIndex tile, TileDesc *td)
td->owner[0] = GetTileOwner(tile);
Owner road_owner = INVALID_OWNER;
Owner tram_owner = INVALID_OWNER;
RoadTypes rts = GetRoadTypes(tile);
if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
/* Is there a mix of owners? */
if ((tram_owner != INVALID_OWNER && tram_owner != td->owner[0]) ||
(road_owner != INVALID_OWNER && road_owner != td->owner[0])) {
uint i = 1;
if (road_owner != INVALID_OWNER) {
td->owner_type[i] = STR_LAND_AREA_INFORMATION_ROAD_OWNER;
td->owner[i] = road_owner;
i++;
if (tram_owner != INVALID_OWNER) {
td->owner_type[i] = STR_LAND_AREA_INFORMATION_TRAM_OWNER;
td->owner[i] = tram_owner;
td->build_date = BaseStation::GetByTile(tile)->build_date;
if (HasStationTileRail(tile)) {
const StationSpec *spec = GetStationSpec(tile);
if (spec != NULL) {
td->station_class = StationClass::Get(spec->cls_id)->name;
td->station_name = spec->name;
if (spec->grf_prop.grffile != NULL) {
const GRFConfig *gc = GetGRFConfig(spec->grf_prop.grffile->grfid);
td->grf = gc->GetName();
const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(tile));
td->rail_speed = rti->max_speed;
if (IsAirport(tile)) {
const AirportSpec *as = Station::GetByTile(tile)->airport.GetSpec();
td->airport_class = AirportClass::Get(as->cls_id)->name;
td->airport_name = as->name;
const AirportTileSpec *ats = AirportTileSpec::GetByTile(tile);
td->airport_tile_name = ats->name;
if (as->grf_prop.grffile != NULL) {
const GRFConfig *gc = GetGRFConfig(as->grf_prop.grffile->grfid);
} else if (ats->grf_prop.grffile != NULL) {
const GRFConfig *gc = GetGRFConfig(ats->grf_prop.grffile->grfid);
StringID str;
switch (GetStationType(tile)) {
default: NOT_REACHED();
case STATION_RAIL: str = STR_LAI_STATION_DESCRIPTION_RAILROAD_STATION; break;
case STATION_AIRPORT:
str = (IsHangar(tile) ? STR_LAI_STATION_DESCRIPTION_AIRCRAFT_HANGAR : STR_LAI_STATION_DESCRIPTION_AIRPORT);
case STATION_TRUCK: str = STR_LAI_STATION_DESCRIPTION_TRUCK_LOADING_AREA; break;
case STATION_BUS: str = STR_LAI_STATION_DESCRIPTION_BUS_STATION; break;
case STATION_OILRIG: str = STR_INDUSTRY_NAME_OIL_RIG; break;
case STATION_DOCK: str = STR_LAI_STATION_DESCRIPTION_SHIP_DOCK; break;
case STATION_BUOY: str = STR_LAI_STATION_DESCRIPTION_BUOY; break;
case STATION_WAYPOINT: str = STR_LAI_STATION_DESCRIPTION_WAYPOINT; break;
td->str = str;
static TrackStatus GetTileTrackStatus_Station(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
TrackBits trackbits = TRACK_BIT_NONE;
switch (mode) {
case TRANSPORT_RAIL:
if (HasStationRail(tile) && !IsStationTileBlocked(tile)) {
trackbits = TrackToTrackBits(GetRailStationTrack(tile));
case TRANSPORT_WATER:
/* buoy is coded as a station, it is always on open water */
if (IsBuoy(tile)) {
trackbits = TRACK_BIT_ALL;
/* remove tracks that connect NE map edge */
if (TileX(tile) == 0) trackbits &= ~(TRACK_BIT_X | TRACK_BIT_UPPER | TRACK_BIT_RIGHT);
/* remove tracks that connect NW map edge */
if (TileY(tile) == 0) trackbits &= ~(TRACK_BIT_Y | TRACK_BIT_LEFT | TRACK_BIT_UPPER);
case TRANSPORT_ROAD:
if ((GetRoadTypes(tile) & sub_mode) != 0 && IsRoadStop(tile)) {
DiagDirection dir = GetRoadStopDir(tile);
Axis axis = DiagDirToAxis(dir);
if (side != INVALID_DIAGDIR) {
if (axis != DiagDirToAxis(side) || (IsStandardRoadStopTile(tile) && dir != side)) break;
trackbits = AxisToTrackBits(axis);
return CombineTrackStatus(TrackBitsToTrackdirBits(trackbits), TRACKDIR_BIT_NONE);
static void TileLoop_Station(TileIndex tile)
/* FIXME -- GetTileTrackStatus_Station -> animated stationtiles
* hardcoded.....not good */
AirportTileAnimationTrigger(Station::GetByTile(tile), tile, AAT_TILELOOP);
case STATION_DOCK:
if (GetTileSlope(tile) != SLOPE_FLAT) break; // only handle water part
/* FALL THROUGH */
case STATION_OILRIG: //(station part)
case STATION_BUOY:
TileLoop_Water(tile);
default: break;
static void AnimateTile_Station(TileIndex tile)
if (HasStationRail(tile)) {
AnimateStationTile(tile);
AnimateAirportTile(tile);
static bool ClickTile_Station(TileIndex tile)
const BaseStation *bst = BaseStation::GetByTile(tile);
if (bst->facilities & FACIL_WAYPOINT) {
ShowWaypointWindow(Waypoint::From(bst));
} else if (IsHangar(tile)) {
const Station *st = Station::From(bst);
ShowDepotWindow(st->airport.GetHangarTile(st->airport.GetHangarNum(tile)), VEH_AIRCRAFT);
ShowStationViewWindow(bst->index);
static VehicleEnterTileStatus VehicleEnter_Station(Vehicle *v, TileIndex tile, int x, int y)
if (v->type == VEH_TRAIN) {
StationID station_id = GetStationIndex(tile);
if (!v->current_order.ShouldStopAtStation(v, station_id)) return VETSB_CONTINUE;
if (!IsRailStation(tile) || !v->IsFrontEngine()) return VETSB_CONTINUE;
int station_ahead;
int station_length;
int stop = GetTrainStopLocation(station_id, tile, Train::From(v), &station_ahead, &station_length);
/* Stop whenever that amount of station ahead + the distance from the
* begin of the platform to the stop location is longer than the length
* of the platform. Station ahead 'includes' the current tile where the
* vehicle is on, so we need to subtract that. */
if (!IsInsideBS(stop + station_ahead, station_length, TILE_SIZE)) return VETSB_CONTINUE;
if (stop + station_ahead - (int)TILE_SIZE >= station_length) return VETSB_CONTINUE;
DiagDirection dir = DirToDiagDir(v->direction);
x &= 0xF;
y &= 0xF;
if (DiagDirToAxis(dir) != AXIS_X) Swap(x, y);
if (y == TILE_SIZE / 2) {
if (dir != DIAGDIR_SE && dir != DIAGDIR_SW) x = TILE_SIZE - 1 - x;
stop &= TILE_SIZE - 1;
if (x == stop) return VETSB_ENTERED_STATION | (VehicleEnterTileStatus)(station_id << VETS_STATION_ID_OFFSET); // enter station
if (x < stop) {
uint16 spd;
if (x >= stop) return VETSB_ENTERED_STATION | (VehicleEnterTileStatus)(station_id << VETS_STATION_ID_OFFSET); // enter station
v->vehstatus |= VS_TRAIN_SLOWING;
spd = max(0, (stop - x) * 20 - 15);
uint16 spd = max(0, (stop - x) * 20 - 15);
if (spd < v->cur_speed) v->cur_speed = spd;
} else if (v->type == VEH_ROAD) {
if (rv->state < RVSB_IN_ROAD_STOP && !IsReversingRoadTrackdir((Trackdir)rv->state) && rv->frame == 0) {
if (IsRoadStop(tile) && rv->IsFrontEngine()) {
/* Attempt to allocate a parking bay in a road stop */
return RoadStop::GetByTile(tile, GetRoadStopType(tile))->Enter(rv) ? VETSB_CONTINUE : VETSB_CANNOT_ENTER;
return VETSB_CONTINUE;
* Run the watched cargo callback for all houses in the catchment area.
* @param st Station.
void TriggerWatchedCargoCallbacks(Station *st)
/* Collect cargoes accepted since the last big tick. */
uint cargoes = 0;
for (CargoID cid = 0; cid < NUM_CARGO; cid++) {
if (HasBit(st->goods[cid].acceptance_pickup, GoodsEntry::GES_ACCEPTED_BIGTICK)) SetBit(cargoes, cid);
/* Anything to do? */
if (cargoes == 0) return;
/* Loop over all houses in the catchment. */
Rect r = st->GetCatchmentRect();
TileArea ta(TileXY(r.left, r.top), TileXY(r.right, r.bottom));
if (IsTileType(tile, MP_HOUSE)) {
WatchedCargoCallback(tile, cargoes);
* This function is called for each station once every 250 ticks.
* Not all stations will get the tick at the same time.
* @param st the station receiving the tick.
* @return true if the station is still valid (wasn't deleted)
static bool StationHandleBigTick(BaseStation *st)
if (!st->IsInUse()) {
if (++st->delete_ctr >= 8) delete st;
if (Station::IsExpected(st)) {
TriggerWatchedCargoCallbacks(Station::From(st));
for (CargoID i = 0; i < NUM_CARGO; i++) {
ClrBit(Station::From(st)->goods[i].acceptance_pickup, GoodsEntry::GES_ACCEPTED_BIGTICK);
if ((st->facilities & FACIL_WAYPOINT) == 0) UpdateStationAcceptance(Station::From(st), true);
static inline void byte_inc_sat(byte *p)
byte b = *p + 1;
if (b != 0) *p = b;
static void UpdateStationRating(Station *st)
bool waiting_changed = false;
byte_inc_sat(&st->time_since_load);
byte_inc_sat(&st->time_since_unload);
const CargoSpec *cs;
FOR_ALL_CARGOSPECS(cs) {
GoodsEntry *ge = &st->goods[cs->Index()];
/* Slowly increase the rating back to his original level in the case we
* didn't deliver cargo yet to this station. This happens when a bribe
* failed while you didn't moved that cargo yet to a station. */
if (!ge->HasRating() && ge->rating < INITIAL_STATION_RATING) {
ge->rating++;
/* Only change the rating if we are moving this cargo */
if (ge->HasRating()) {
byte_inc_sat(&ge->time_since_pickup);
bool skip = false;
int rating = 0;
uint waiting = ge->cargo.TotalCount();
/* num_dests is at least 1 if there is any cargo as
* INVALID_STATION is also a destination.
uint num_dests = (uint)ge->cargo.Packets()->MapSize();
/* Average amount of cargo per next hop, but prefer solitary stations
* with only one or two next hops. They are allowed to have more
* cargo waiting per next hop.
* With manual cargo distribution waiting_avg = waiting / 2 as then
* INVALID_STATION is the only destination.
uint waiting_avg = waiting / (num_dests + 1);
if (HasBit(cs->callback_mask, CBM_CARGO_STATION_RATING_CALC)) {
/* Perform custom station rating. If it succeeds the speed, days in transit and
* waiting cargo ratings must not be executed. */
/* NewGRFs expect last speed to be 0xFF when no vehicle has arrived yet. */
uint last_speed = ge->HasVehicleEverTriedLoading() ? ge->last_speed : 0xFF;
uint32 var18 = min(ge->time_since_pickup, 0xFF) | (min(ge->max_waiting_cargo, 0xFFFF) << 8) | (min(last_speed, 0xFF) << 24);
/* Convert to the 'old' vehicle types */
uint32 var10 = (st->last_vehicle_type == VEH_INVALID) ? 0x0 : (st->last_vehicle_type + 0x10);
uint16 callback = GetCargoCallback(CBID_CARGO_STATION_RATING_CALC, var10, var18, cs);
if (callback != CALLBACK_FAILED) {
skip = true;
rating = GB(callback, 0, 14);
/* Simulate a 15 bit signed value */
if (HasBit(callback, 14)) rating -= 0x4000;
if (!skip) {
int b = ge->last_speed - 85;
if (b >= 0) rating += b >> 2;
byte waittime = ge->time_since_pickup;
if (st->last_vehicle_type == VEH_SHIP) waittime >>= 2;
(waittime > 21) ||
(rating += 25, waittime > 12) ||
(rating += 25, waittime > 6) ||
(rating += 45, waittime > 3) ||
(rating += 35, true);
(rating -= 90, ge->max_waiting_cargo > 1500) ||
(rating += 55, ge->max_waiting_cargo > 1000) ||
(rating += 35, ge->max_waiting_cargo > 600) ||
(rating += 10, ge->max_waiting_cargo > 300) ||
(rating += 20, ge->max_waiting_cargo > 100) ||
(rating += 10, true);
if (Company::IsValidID(st->owner) && HasBit(st->town->statues, st->owner)) rating += 26;
byte age = ge->last_age;
(age >= 3) ||
(rating += 10, age >= 2) ||
(rating += 10, age >= 1) ||
(rating += 13, true);
int or_ = ge->rating; // old rating
/* only modify rating in steps of -2, -1, 0, 1 or 2 */
ge->rating = rating = or_ + Clamp(Clamp(rating, 0, 255) - or_, -2, 2);
/* if rating is <= 64 and more than 100 items waiting on average per destination,
* remove some random amount of goods from the station */
if (rating <= 64 && waiting_avg >= 100) {
int dec = Random() & 0x1F;
if (waiting_avg < 200) dec &= 7;
waiting -= (dec + 1) * num_dests;
waiting_changed = true;
/* if rating is <= 127 and there are any items waiting, maybe remove some goods. */
if (rating <= 127 && waiting != 0) {
uint32 r = Random();
if (rating <= (int)GB(r, 0, 7)) {
/* Need to have int, otherwise it will just overflow etc. */
waiting = max((int)waiting - (int)((GB(r, 8, 2) - 1) * num_dests), 0);
/* At some point we really must cap the cargo. Previously this
* was a strict 4095, but now we'll have a less strict, but
* increasingly aggressive truncation of the amount of cargo. */
static const uint WAITING_CARGO_THRESHOLD = 1 << 12;
static const uint WAITING_CARGO_CUT_FACTOR = 1 << 6;
static const uint MAX_WAITING_CARGO = 1 << 15;
if (waiting > WAITING_CARGO_THRESHOLD) {
uint difference = waiting - WAITING_CARGO_THRESHOLD;
waiting -= (difference / WAITING_CARGO_CUT_FACTOR);
waiting = min(waiting, MAX_WAITING_CARGO);
/* We can't truncate cargo that's already reserved for loading.
* Thus StoredCount() here. */
if (waiting_changed && waiting < ge->cargo.AvailableCount()) {
/* Feed back the exact own waiting cargo at this station for the
* next rating calculation. */
ge->max_waiting_cargo = 0;
/* If truncating also punish the source stations' ratings to
* decrease the flow of incoming cargo. */
StationCargoAmountMap waiting_per_source;
ge->cargo.Truncate(ge->cargo.AvailableCount() - waiting, &waiting_per_source);
for (StationCargoAmountMap::iterator i(waiting_per_source.begin()); i != waiting_per_source.end(); ++i) {
Station *source_station = Station::GetIfValid(i->first);
if (source_station == NULL) continue;
GoodsEntry &source_ge = source_station->goods[cs->Index()];
source_ge.max_waiting_cargo = max(source_ge.max_waiting_cargo, i->second);
/* If the average number per next hop is low, be more forgiving. */
ge->max_waiting_cargo = waiting_avg;
StationID index = st->index;
if (waiting_changed) {
SetWindowDirty(WC_STATION_VIEW, index); // update whole window
SetWindowWidgetDirty(WC_STATION_VIEW, index, WID_SV_ACCEPT_RATING_LIST); // update only ratings list
* Reroute cargo of type c at station st or in any vehicles unloading there.
* Make sure the cargo's new next hop is neither "avoid" nor "avoid2".
* @param st Station to be rerouted at.
* @param c Type of cargo.
* @param avoid Original next hop of cargo, avoid this.
* @param avoid2 Another station to be avoided when rerouting.
void RerouteCargo(Station *st, CargoID c, StationID avoid, StationID avoid2)
GoodsEntry &ge = st->goods[c];
/* Reroute cargo in station. */
ge.cargo.Reroute(UINT_MAX, &ge.cargo, avoid, avoid2, &ge);
/* Reroute cargo staged to be transfered. */
for (std::list<Vehicle *>::iterator it(st->loading_vehicles.begin()); it != st->loading_vehicles.end(); ++it) {
for (Vehicle *v = *it; v != NULL; v = v->Next()) {
if (v->cargo_type != c) continue;
v->cargo.Reroute(UINT_MAX, &v->cargo, avoid, avoid2, &ge);
* Check all next hops of cargo packets in this station for existance of a
* a valid link they may use to travel on. Reroute any cargo not having a valid
* link and remove timed out links found like this from the linkgraph. We're
* not all links here as that is expensive and useless. A link no one is using
* doesn't hurt either.
* @param from Station to check.
void DeleteStaleLinks(Station *from)
for (CargoID c = 0; c < NUM_CARGO; ++c) {
GoodsEntry &ge = from->goods[c];
LinkGraph *lg = LinkGraph::GetIfValid(ge.link_graph);
if (lg == NULL) continue;
Node node = (*lg)[ge.node];
for (EdgeIterator it(node.Begin()); it != node.End();) {
Edge edge = it->second;
Station *to = Station::Get((*lg)[it->first].Station());
assert(to->goods[c].node == it->first);
++it; // Do that before removing the node. Anything else may crash.
assert(_date >= edge.LastUpdate());
if ((uint)(_date - edge.LastUpdate()) > LinkGraph::MIN_TIMEOUT_DISTANCE +
(DistanceManhattan(from->xy, to->xy) >> 2)) {
node.RemoveEdge(to->goods[c].node);
ge.flows.DeleteFlows(to->index);
RerouteCargo(from, c, to->index, from->index);
assert(_date >= lg->LastCompression());
if ((uint)(_date - lg->LastCompression()) > LinkGraph::COMPRESSION_INTERVAL) {
lg->Compress();
* Increase capacity for a link stat given by station cargo and next hop.
* @param st Station to get the link stats from.
* @param cargo Cargo to increase stat for.
* @param next_station_id Station the consist will be travelling to next.
* @param capacity Capacity to add to link stat.
* @param usage Usage to add to link stat. If UINT_MAX refresh the link instead of increasing.
void IncreaseStats(Station *st, CargoID cargo, StationID next_station_id, uint capacity, uint usage)
GoodsEntry &ge1 = st->goods[cargo];
Station *st2 = Station::Get(next_station_id);
GoodsEntry &ge2 = st2->goods[cargo];
LinkGraph *lg = NULL;
if (ge1.link_graph == INVALID_LINK_GRAPH) {
if (ge2.link_graph == INVALID_LINK_GRAPH) {
if (LinkGraph::CanAllocateItem()) {
lg = new LinkGraph(cargo);
LinkGraphSchedule::Instance()->Queue(lg);
ge2.link_graph = lg->index;
ge2.node = lg->AddNode(st2);
DEBUG(misc, 0, "Can't allocate link graph");
lg = LinkGraph::Get(ge2.link_graph);
if (lg) {
ge1.link_graph = lg->index;
ge1.node = lg->AddNode(st);
} else if (ge2.link_graph == INVALID_LINK_GRAPH) {
lg = LinkGraph::Get(ge1.link_graph);
if (ge1.link_graph != ge2.link_graph) {
LinkGraph *lg2 = LinkGraph::Get(ge2.link_graph);
if (lg->Size() < lg2->Size()) {
LinkGraphSchedule::Instance()->Unqueue(lg);
lg2->Merge(lg); // Updates GoodsEntries of lg
lg = lg2;
LinkGraphSchedule::Instance()->Unqueue(lg2);
lg->Merge(lg2); // Updates GoodsEntries of lg2
if (lg != NULL) {
(*lg)[ge1.node].UpdateEdge(ge2.node, capacity, usage);
* Increase capacity for all link stats associated with vehicles in the given consist.
* @param front First vehicle in the consist.
void IncreaseStats(Station *st, const Vehicle *front, StationID next_station_id)
for (const Vehicle *v = front; v != NULL; v = v->Next()) {
if (v->refit_cap > 0) {
/* The cargo count can indeed be higher than the refit_cap if
* wagons have been auto-replaced and subsequently auto-
* refitted to a higher capacity. The cargo gets redistributed
* among the wagons in that case.
* As usage is not such an important figure anyway we just
* ignore the additional cargo then.*/
IncreaseStats(st, v->cargo_type, next_station_id, v->refit_cap,
min(v->refit_cap, v->cargo.StoredCount()));
/* called for every station each tick */
static void StationHandleSmallTick(BaseStation *st)
if ((st->facilities & FACIL_WAYPOINT) != 0 || !st->IsInUse()) return;
byte b = st->delete_ctr + 1;
if (b >= STATION_RATING_TICKS) b = 0;
st->delete_ctr = b;
if (b == 0) UpdateStationRating(Station::From(st));
void OnTick_Station()
if (_game_mode == GM_EDITOR) return;
BaseStation *st;
FOR_ALL_BASE_STATIONS(st) {
StationHandleSmallTick(st);
/* Clean up the link graph about once a week. */
if (Station::IsExpected(st) && (_tick_counter + st->index) % STATION_LINKGRAPH_TICKS == 0) {
DeleteStaleLinks(Station::From(st));
/* Run STATION_ACCEPTANCE_TICKS = 250 tick interval trigger for station animation.
* Station index is included so that triggers are not all done
* at the same time. */
if ((_tick_counter + st->index) % STATION_ACCEPTANCE_TICKS == 0) {
/* Stop processing this station if it was deleted */
if (!StationHandleBigTick(st)) continue;
TriggerStationAnimation(st, st->xy, SAT_250_TICKS);
if (Station::IsExpected(st)) AirportAnimationTrigger(Station::From(st), AAT_STATION_250_TICKS);
/** Monthly loop for stations. */
void StationMonthlyLoop()
Station *st;
GoodsEntry *ge = &st->goods[i];
SB(ge->acceptance_pickup, GoodsEntry::GES_LAST_MONTH, 1, GB(ge->acceptance_pickup, GoodsEntry::GES_CURRENT_MONTH, 1));
ClrBit(ge->acceptance_pickup, GoodsEntry::GES_CURRENT_MONTH);
void ModifyStationRatingAround(TileIndex tile, Owner owner, int amount, uint radius)
if (st->owner == owner &&
DistanceManhattan(tile, st->xy) <= radius) {
if (ge->acceptance_pickup != 0) {
ge->rating = Clamp(ge->rating + amount, 0, 255);
static uint UpdateStationWaiting(Station *st, CargoID type, uint amount, SourceType source_type, SourceID source_id)
/* We can't allocate a CargoPacket? Then don't do anything
* at all; i.e. just discard the incoming cargo. */
if (!CargoPacket::CanAllocateItem()) return 0;
GoodsEntry &ge = st->goods[type];
amount += ge.amount_fract;
ge.amount_fract = GB(amount, 0, 8);
amount >>= 8;
/* No new "real" cargo item yet. */
if (amount == 0) return 0;
StationID next = ge.GetVia(st->index);
ge.cargo.Append(new CargoPacket(st->index, st->xy, amount, source_type, source_id), next);
if (ge.link_graph == INVALID_LINK_GRAPH) {
lg = new LinkGraph(type);
ge.link_graph = lg->index;
ge.node = lg->AddNode(st);
lg = LinkGraph::Get(ge.link_graph);
if (lg != NULL) (*lg)[ge.node].UpdateSupply(amount);
if (!ge.HasRating()) {
InvalidateWindowData(WC_STATION_LIST, st->index);
SetBit(ge.acceptance_pickup, GoodsEntry::GES_PICKUP);
TriggerStationRandomisation(st, st->xy, SRT_NEW_CARGO, type);
TriggerStationAnimation(st, st->xy, SAT_NEW_CARGO, type);
AirportAnimationTrigger(st, AAT_STATION_NEW_CARGO, type);
SetWindowDirty(WC_STATION_VIEW, st->index);
st->MarkTilesDirty(true);
return amount;
static bool IsUniqueStationName(const char *name)
if (st->name != NULL && strcmp(st->name, name) == 0) return false;
* Rename a station
* @param tile unused
* @param p1 station ID that is to be renamed
* @param p2 unused
* @param text the new name or an empty string when resetting to the default
CommandCost CmdRenameStation(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Station *st = Station::GetIfValid(p1);
if (st == NULL) return CMD_ERROR;
bool reset = StrEmpty(text);
if (!reset) {
if (Utf8StringLength(text) >= MAX_LENGTH_STATION_NAME_CHARS) return CMD_ERROR;
if (!IsUniqueStationName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
free(st->name);
st->name = reset ? NULL : strdup(text);
InvalidateWindowData(WC_STATION_LIST, st->owner, 1);
* Find all stations around a rectangular producer (industry, house, headquarter, ...)
*
* @param location The location/area of the producer
* @param stations The list to store the stations in
void FindStationsAroundTiles(const TileArea &location, StationList *stations)
/* area to search = producer plus station catchment radius */
uint max_rad = (_settings_game.station.modified_catchment ? MAX_CATCHMENT : CA_UNMODIFIED);
uint x = TileX(location.tile);
uint y = TileY(location.tile);
uint min_x = (x > max_rad) ? x - max_rad : 0;
uint max_x = x + location.w + max_rad;
uint min_y = (y > max_rad) ? y - max_rad : 0;
uint max_y = y + location.h + max_rad;
if (min_x == 0 && _settings_game.construction.freeform_edges) min_x = 1;
if (min_y == 0 && _settings_game.construction.freeform_edges) min_y = 1;
if (max_x >= MapSizeX()) max_x = MapSizeX() - 1;
if (max_y >= MapSizeY()) max_y = MapSizeY() - 1;
for (uint cy = min_y; cy < max_y; cy++) {
for (uint cx = min_x; cx < max_x; cx++) {
TileIndex cur_tile = TileXY(cx, cy);
if (!IsTileType(cur_tile, MP_STATION)) continue;
Station *st = Station::GetByTile(cur_tile);
/* st can be NULL in case of waypoints */
if (st == NULL) continue;
if (_settings_game.station.modified_catchment) {
int rad = st->GetCatchmentRadius();
int rad_x = cx - x;
int rad_y = cy - y;
if (rad_x < -rad || rad_x >= rad + location.w) continue;
if (rad_y < -rad || rad_y >= rad + location.h) continue;
/* Insert the station in the set. This will fail if it has
* already been added.
stations->Include(st);
* Run a tile loop to find stations around a tile, on demand. Cache the result for further requests
* @return pointer to a StationList containing all stations found
const StationList *StationFinder::GetStations()
if (this->tile != INVALID_TILE) {
FindStationsAroundTiles(*this, &this->stations);
this->tile = INVALID_TILE;
return &this->stations;
uint MoveGoodsToStation(CargoID type, uint amount, SourceType source_type, SourceID source_id, const StationList *all_stations)
/* Return if nothing to do. Also the rounding below fails for 0. */
Station *st1 = NULL; // Station with best rating
Station *st2 = NULL; // Second best station
uint best_rating1 = 0; // rating of st1
uint best_rating2 = 0; // rating of st2
for (Station * const *st_iter = all_stations->Begin(); st_iter != all_stations->End(); ++st_iter) {
Station *st = *st_iter;
/* Is the station reserved exclusively for somebody else? */
if (st->town->exclusive_counter > 0 && st->town->exclusivity != st->owner) continue;
if (st->goods[type].rating == 0) continue; // Lowest possible rating, better not to give cargo anymore
if (_settings_game.order.selectgoods && !st->goods[type].HasVehicleEverTriedLoading()) continue; // Selectively servicing stations, and not this one
if (IsCargoInClass(type, CC_PASSENGERS)) {
if (st->facilities == FACIL_TRUCK_STOP) continue; // passengers are never served by just a truck stop
if (st->facilities == FACIL_BUS_STOP) continue; // non-passengers are never served by just a bus stop
/* This station can be used, add it to st1/st2 */
if (st1 == NULL || st->goods[type].rating >= best_rating1) {
st2 = st1; best_rating2 = best_rating1; st1 = st; best_rating1 = st->goods[type].rating;
} else if (st2 == NULL || st->goods[type].rating >= best_rating2) {
st2 = st; best_rating2 = st->goods[type].rating;
/* no stations around at all? */
if (st1 == NULL) return 0;
/* From now we'll calculate with fractal cargo amounts.
* First determine how much cargo we really have. */
amount *= best_rating1 + 1;
if (st2 == NULL) {
/* only one station around */
return UpdateStationWaiting(st1, type, amount, source_type, source_id);
/* several stations around, the best two (highest rating) are in st1 and st2 */
assert(st1 != NULL);
assert(st2 != NULL);
assert(best_rating1 != 0 || best_rating2 != 0);
/* Then determine the amount the worst station gets. We do it this way as the
* best should get a bonus, which in this case is the rounding difference from
* this calculation. In reality that will mean the bonus will be pretty low.
* Nevertheless, the best station should always get the most cargo regardless
* of rounding issues. */
uint worst_cargo = amount * best_rating2 / (best_rating1 + best_rating2);
assert(worst_cargo <= (amount - worst_cargo));
/* And then send the cargo to the stations! */
uint moved = UpdateStationWaiting(st1, type, amount - worst_cargo, source_type, source_id);
/* These two UpdateStationWaiting's can't be in the statement as then the order
* of execution would be undefined and that could cause desyncs with callbacks. */
return moved + UpdateStationWaiting(st2, type, worst_cargo, source_type, source_id);
void BuildOilRig(TileIndex tile)
if (!Station::CanAllocateItem()) {
DEBUG(misc, 0, "Can't allocate station for oilrig at 0x%X, reverting to oilrig only", tile);
Station *st = new Station(tile);
st->town = ClosestTownFromTile(tile, UINT_MAX);
st->string_id = GenerateStationName(st, tile, STATIONNAMING_OILRIG);
assert(IsTileType(tile, MP_INDUSTRY));
DeleteAnimatedTile(tile);
MakeOilrig(tile, st->index, GetWaterClass(tile));
st->owner = OWNER_NONE;
st->airport.type = AT_OILRIG;
st->airport.Add(tile);
st->facilities = FACIL_AIRPORT | FACIL_DOCK;
st->build_date = _date;
st->rect.BeforeAddTile(tile, StationRect::ADD_FORCE);
void DeleteOilRig(TileIndex tile)
MakeWaterKeepingClass(tile, OWNER_NONE);
st->facilities &= ~(FACIL_AIRPORT | FACIL_DOCK);
if (!st->IsInUse()) delete st;
static void ChangeTileOwner_Station(TileIndex tile, Owner old_owner, Owner new_owner)
if (IsRoadStopTile(tile)) {
for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
/* Update all roadtypes, no matter if they are present */
if (GetRoadOwner(tile, rt) == old_owner) {
if (HasTileRoadType(tile, rt)) {
/* A drive-through road-stop has always two road bits. No need to dirty windows here, we'll redraw the whole screen anyway. */
Company::Get(old_owner)->infrastructure.road[rt] -= 2;
if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.road[rt] += 2;
SetRoadOwner(tile, rt, new_owner == INVALID_OWNER ? OWNER_NONE : new_owner);
if (!IsTileOwner(tile, old_owner)) return;
if (new_owner != INVALID_OWNER) {
/* Update company infrastructure counts. Only do it here
* if the new owner is valid as otherwise the clear
* command will do it for us. No need to dirty windows
* here, we'll redraw the whole screen anyway.*/
Company *old_company = Company::Get(old_owner);
Company *new_company = Company::Get(new_owner);
/* Update counts for underlying infrastructure. */
case STATION_RAIL:
case STATION_WAYPOINT:
if (!IsStationTileBlocked(tile)) {
old_company->infrastructure.rail[GetRailType(tile)]--;
new_company->infrastructure.rail[GetRailType(tile)]++;
case STATION_BUS:
case STATION_TRUCK:
/* Road stops were already handled above. */
if (GetWaterClass(tile) == WATER_CLASS_CANAL) {
old_company->infrastructure.water--;
new_company->infrastructure.water++;
/* Update station tile count. */
if (!IsBuoy(tile) && !IsAirport(tile)) {
old_company->infrastructure.station--;
new_company->infrastructure.station++;
/* for buoys, owner of tile is owner of water, st->owner == OWNER_NONE */
SetTileOwner(tile, new_owner);
InvalidateWindowClassesData(WC_STATION_LIST, 0);
/* Remove the drive-through road stop */
DoCommand(tile, 1 | 1 << 8, (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_owner, new_owner);
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_owner)) 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
* @param flags command flags
* @return true if the road can be cleared
static bool CanRemoveRoadWithStop(TileIndex tile, DoCommandFlag flags)
/* Yeah... water can always remove stops, right? */
if (_current_company == OWNER_WATER) return true;
if (HasBit(rts, ROADTYPE_TRAM)) {
Owner tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
if (tram_owner != OWNER_NONE && CheckOwnership(tram_owner).Failed()) return false;
if (HasBit(rts, ROADTYPE_ROAD)) {
Owner road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
if (road_owner != OWNER_TOWN) {
if (road_owner != OWNER_NONE && CheckOwnership(road_owner).Failed()) return false;
if (CheckAllowRemoveRoad(tile, GetAnyRoadBits(tile, ROADTYPE_ROAD), OWNER_TOWN, ROADTYPE_ROAD, flags).Failed()) return false;
* Clear a single tile of a station.
* @param tile The tile to clear.
* @param flags The DoCommand flags related to the "command".
* @return The cost, or error of clearing.
CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags)
if (flags & DC_AUTO) {
case STATION_RAIL: return_cmd_error(STR_ERROR_MUST_DEMOLISH_RAILROAD);
case STATION_WAYPOINT: return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
case STATION_AIRPORT: return_cmd_error(STR_ERROR_MUST_DEMOLISH_AIRPORT_FIRST);
case STATION_TRUCK: return_cmd_error(HasTileRoadType(tile, ROADTYPE_TRAM) ? STR_ERROR_MUST_DEMOLISH_CARGO_TRAM_STATION_FIRST : STR_ERROR_MUST_DEMOLISH_TRUCK_STATION_FIRST);
case STATION_BUS: return_cmd_error(HasTileRoadType(tile, ROADTYPE_TRAM) ? STR_ERROR_MUST_DEMOLISH_PASSENGER_TRAM_STATION_FIRST : STR_ERROR_MUST_DEMOLISH_BUS_STATION_FIRST);
case STATION_BUOY: return_cmd_error(STR_ERROR_BUOY_IN_THE_WAY);
case STATION_DOCK: return_cmd_error(STR_ERROR_MUST_DEMOLISH_DOCK_FIRST);
case STATION_OILRIG:
SetDParam(1, STR_INDUSTRY_NAME_OIL_RIG);
return_cmd_error(STR_ERROR_GENERIC_OBJECT_IN_THE_WAY);
case STATION_RAIL: return RemoveRailStation(tile, flags);
case STATION_WAYPOINT: return RemoveRailWaypoint(tile, flags);
case STATION_AIRPORT: return RemoveAirport(tile, flags);
if (IsDriveThroughStopTile(tile) && !CanRemoveRoadWithStop(tile, flags)) {
return_cmd_error(STR_ERROR_MUST_DEMOLISH_TRUCK_STATION_FIRST);
return RemoveRoadStop(tile, flags);
return_cmd_error(STR_ERROR_MUST_DEMOLISH_BUS_STATION_FIRST);
case STATION_BUOY: return RemoveBuoy(tile, flags);
case STATION_DOCK: return RemoveDock(tile, flags);
return CMD_ERROR;
static CommandCost TerraformTile_Station(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
if (_settings_game.construction.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 (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new)) {
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[PR_BUILD_FOUNDATION]);
case STATION_BUS: {
DiagDirection direction = GetRoadStopDir(tile);
return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
* Get flow for a station.
* @param st Station to get flow for.
* @return Flow for st.
uint FlowStat::GetShare(StationID st) const
uint32 prev = 0;
for (SharesMap::const_iterator it = this->shares.begin(); it != this->shares.end(); ++it) {
if (it->second == st) {
return it->first - prev;
prev = it->first;
return 0;
* Get a station a package can be routed to, but exclude the given one.
* @param excluded StationID not to be selected.
* @return A station ID from the shares map.
StationID FlowStat::GetVia(StationID excluded, StationID excluded2) const
assert(!this->shares.empty());
uint max = (--this->shares.end())->first - 1;
SharesMap::const_iterator it = this->shares.upper_bound(RandomRange(max));
assert(it != this->shares.end());
if (it->second != excluded && it->second != excluded2) return it->second;
/* We've hit one of the excluded stations.
* Draw another share, from outside its range. */
uint end = it->first;
uint begin = (it == this->shares.begin() ? 0 : (--it)->first);
uint interval = end - begin;
if (interval > max) return INVALID_STATION; // Only one station in the map.
uint new_max = max - interval;
uint rand = RandomRange(new_max);
SharesMap::const_iterator it2 = (rand < begin) ? this->shares.upper_bound(rand) :
this->shares.upper_bound(rand + interval);
assert(it2 != this->shares.end());
if (it2->second != excluded && it2->second != excluded2) return it2->second;
/* We've hit the second excluded station.
* Same as before, only a bit more complicated. */
uint end2 = it2->first;
uint begin2 = (it2 == this->shares.begin() ? 0 : (--it2)->first);
uint interval2 = end2 - begin2;
if (interval2 > new_max) return INVALID_STATION; // Only the two excluded stations in the map.
new_max -= interval2;
if (begin > begin2) {
Swap(begin, begin2);
Swap(end, end2);
Swap(interval, interval2);
rand = RandomRange(new_max);
SharesMap::const_iterator it3 = this->shares.end();
if (rand < begin) {
it3 = this->shares.upper_bound(rand);
} else if (rand < begin2 - interval) {
it3 = this->shares.upper_bound(rand + interval);
it3 = this->shares.upper_bound(rand + interval + interval2);
assert(it3 != this->shares.end());
return it3->second;
* Reduce all flows to minimum capacity so that they don't get in the way of
* link usage statistics too much. Keep them around, though, to continue
* routing any remaining cargo.
void FlowStat::Invalidate()
SharesMap new_shares;
uint i = 0;
for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
new_shares[++i] = it->second;
this->shares.swap(new_shares);
* Change share for specified station. By specifing INT_MIN as parameter you
* can erase a share.
* @param st Next Hop to be removed.
* @param flow Share to be added or removed.
void FlowStat::ChangeShare(StationID st, int flow)
/* We assert only before changing as afterwards the shares can actually
* be empty. In that case the whole flow stat must be deleted then. */
uint removed_shares = 0;
uint added_shares = 0;
uint last_share = 0;
if (flow < 0) {
uint share = it->first - last_share;
if (flow == INT_MIN || (uint)(-flow) >= share) {
removed_shares += share;
if (flow != INT_MIN) flow += share;
last_share = it->first;
continue; // remove the whole share
removed_shares += (uint)(-flow);
added_shares += (uint)(flow);
/* If we don't continue above the whole flow has been added or
* removed. */
flow = 0;
new_shares[it->first + added_shares - removed_shares] = it->second;
if (flow > 0) new_shares[last_share + (uint)flow] = st;
* Add some flow from "origin", going via "via".
* @param origin Origin of the flow.
* @param via Next hop.
* @param flow Amount of flow to be added.
void FlowStatMap::AddFlow(StationID origin, StationID via, uint flow)
FlowStatMap::iterator origin_it = this->find(origin);
if (origin_it == this->end()) {
this->insert(std::make_pair(origin, FlowStat(via, flow)));
origin_it->second.ChangeShare(via, flow);
assert(!origin_it->second.GetShares()->empty());
* Pass on some flow, remembering it as invalid, for later subtraction from
* locally consumed flow. This is necessary because we can't have negative
* flows and we don't want to sort the flows before adding them up.
* @param flow Amount of flow to be passed.
void FlowStatMap::PassOnFlow(StationID origin, StationID via, uint flow)
FlowStatMap::iterator prev_it = this->find(origin);
if (prev_it == this->end()) {
FlowStat fs(via, flow);
fs.AppendShare(INVALID_STATION, flow);
this->insert(std::make_pair(origin, fs));
prev_it->second.ChangeShare(via, flow);
prev_it->second.ChangeShare(INVALID_STATION, flow);
assert(!prev_it->second.GetShares()->empty());
* Subtract invalid flows from locally consumed flow.
* @param self ID of own station.
void FlowStatMap::FinalizeLocalConsumption(StationID self)
for (FlowStatMap::iterator i = this->begin(); i != this->end(); ++i) {
FlowStat &fs = i->second;
uint local = fs.GetShare(INVALID_STATION);
if (local > INT_MAX) { // make sure it fits in an int
fs.ChangeShare(self, -INT_MAX);
fs.ChangeShare(INVALID_STATION, -INT_MAX);
local -= INT_MAX;
fs.ChangeShare(self, -(int)local);
fs.ChangeShare(INVALID_STATION, -(int)local);
/* If the local share is used up there must be a share for some
* remote station. */
assert(!fs.GetShares()->empty());
* Delete all flows at a station for specific cargo and destination.
* @param via Remote station of flows to be deleted.
void FlowStatMap::DeleteFlows(StationID via)
for (FlowStatMap::iterator f_it = this->begin(); f_it != this->end();) {
FlowStat &s_flows = f_it->second;
s_flows.ChangeShare(via, INT_MIN);
if (s_flows.GetShares()->empty()) {
this->erase(f_it++);
++f_it;
* Get the sum of flows via a specific station from this GoodsEntry.
* @param via Remote station to look for.
* @return a FlowStat with all flows for 'via' added up.
uint GoodsEntry::GetSumFlowVia(StationID via) const
uint ret = 0;
for (FlowStatMap::const_iterator i = this->flows.begin(); i != this->flows.end(); ++i) {
ret += i->second.GetShare(via);
return ret;
extern const TileTypeProcs _tile_type_station_procs = {
DrawTile_Station, // draw_tile_proc
GetSlopePixelZ_Station, // get_slope_z_proc
ClearTile_Station, // clear_tile_proc
NULL, // add_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_proc
ChangeTileOwner_Station, // change_tile_owner_proc
NULL, // add_produced_cargo_proc
VehicleEnter_Station, // vehicle_enter_tile_proc
GetFoundation_Station, // get_foundation_proc
TerraformTile_Station, // terraform_tile_proc
Status change: