station_cmd.cpp

Go to the documentation of this file.
00001 /* $Id$ */
00002 
00003 /*
00004  * This file is part of OpenTTD.
00005  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
00006  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
00007  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
00008  */
00009 
00012 #include "stdafx.h"
00013 #include "aircraft.h"
00014 #include "bridge_map.h"
00015 #include "cmd_helper.h"
00016 #include "viewport_func.h"
00017 #include "command_func.h"
00018 #include "town.h"
00019 #include "news_func.h"
00020 #include "train.h"
00021 #include "ship.h"
00022 #include "roadveh.h"
00023 #include "industry.h"
00024 #include "newgrf_cargo.h"
00025 #include "newgrf_debug.h"
00026 #include "newgrf_station.h"
00027 #include "newgrf_canal.h" /* For the buoy */
00028 #include "pathfinder/yapf/yapf_cache.h"
00029 #include "road_internal.h" /* For drawing catenary/checking road removal */
00030 #include "autoslope.h"
00031 #include "water.h"
00032 #include "strings_func.h"
00033 #include "clear_func.h"
00034 #include "date_func.h"
00035 #include "vehicle_func.h"
00036 #include "string_func.h"
00037 #include "animated_tile_func.h"
00038 #include "elrail_func.h"
00039 #include "station_base.h"
00040 #include "roadstop_base.h"
00041 #include "newgrf_railtype.h"
00042 #include "waypoint_base.h"
00043 #include "waypoint_func.h"
00044 #include "pbs.h"
00045 #include "debug.h"
00046 #include "core/random_func.hpp"
00047 #include "company_base.h"
00048 #include "moving_average.h"
00049 #include "table/airporttile_ids.h"
00050 #include "newgrf_airporttiles.h"
00051 #include "order_backup.h"
00052 #include "newgrf_house.h"
00053 #include "company_gui.h"
00054 #include "widgets/station_widget.h"
00055 
00056 #include "table/strings.h"
00057 
00064 bool IsHangar(TileIndex t)
00065 {
00066   assert(IsTileType(t, MP_STATION));
00067 
00068   /* If the tile isn't an airport there's no chance it's a hangar. */
00069   if (!IsAirport(t)) return false;
00070 
00071   const Station *st = Station::GetByTile(t);
00072   const AirportSpec *as = st->airport.GetSpec();
00073 
00074   for (uint i = 0; i < as->nof_depots; i++) {
00075     if (st->airport.GetHangarTile(i) == t) return true;
00076   }
00077 
00078   return false;
00079 }
00080 
00088 template <class T>
00089 CommandCost GetStationAround(TileArea ta, StationID closest_station, T **st)
00090 {
00091   ta.tile -= TileDiffXY(1, 1);
00092   ta.w    += 2;
00093   ta.h    += 2;
00094 
00095   /* check around to see if there's any stations there */
00096   TILE_AREA_LOOP(tile_cur, ta) {
00097     if (IsTileType(tile_cur, MP_STATION)) {
00098       StationID t = GetStationIndex(tile_cur);
00099       if (!T::IsValidID(t)) continue;
00100 
00101       if (closest_station == INVALID_STATION) {
00102         closest_station = t;
00103       } else if (closest_station != t) {
00104         return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
00105       }
00106     }
00107   }
00108   *st = (closest_station == INVALID_STATION) ? NULL : T::Get(closest_station);
00109   return CommandCost();
00110 }
00111 
00117 typedef bool (*CMSAMatcher)(TileIndex tile);
00118 
00125 static int CountMapSquareAround(TileIndex tile, CMSAMatcher cmp)
00126 {
00127   int num = 0;
00128 
00129   for (int dx = -3; dx <= 3; dx++) {
00130     for (int dy = -3; dy <= 3; dy++) {
00131       TileIndex t = TileAddWrap(tile, dx, dy);
00132       if (t != INVALID_TILE && cmp(t)) num++;
00133     }
00134   }
00135 
00136   return num;
00137 }
00138 
00144 static bool CMSAMine(TileIndex tile)
00145 {
00146   /* No industry */
00147   if (!IsTileType(tile, MP_INDUSTRY)) return false;
00148 
00149   const Industry *ind = Industry::GetByTile(tile);
00150 
00151   /* No extractive industry */
00152   if ((GetIndustrySpec(ind->type)->life_type & INDUSTRYLIFE_EXTRACTIVE) == 0) return false;
00153 
00154   for (uint i = 0; i < lengthof(ind->produced_cargo); i++) {
00155     /* The industry extracts something non-liquid, i.e. no oil or plastic, so it is a mine.
00156      * Also the production of passengers and mail is ignored. */
00157     if (ind->produced_cargo[i] != CT_INVALID &&
00158         (CargoSpec::Get(ind->produced_cargo[i])->classes & (CC_LIQUID | CC_PASSENGERS | CC_MAIL)) == 0) {
00159       return true;
00160     }
00161   }
00162 
00163   return false;
00164 }
00165 
00171 static bool CMSAWater(TileIndex tile)
00172 {
00173   return IsTileType(tile, MP_WATER) && IsWater(tile);
00174 }
00175 
00181 static bool CMSATree(TileIndex tile)
00182 {
00183   return IsTileType(tile, MP_TREES);
00184 }
00185 
00186 #define M(x) ((x) - STR_SV_STNAME)
00187 
00188 enum StationNaming {
00189   STATIONNAMING_RAIL,
00190   STATIONNAMING_ROAD,
00191   STATIONNAMING_AIRPORT,
00192   STATIONNAMING_OILRIG,
00193   STATIONNAMING_DOCK,
00194   STATIONNAMING_HELIPORT,
00195 };
00196 
00198 struct StationNameInformation {
00199   uint32 free_names; 
00200   bool *indtypes;    
00201 };
00202 
00211 static bool FindNearIndustryName(TileIndex tile, void *user_data)
00212 {
00213   /* All already found industry types */
00214   StationNameInformation *sni = (StationNameInformation*)user_data;
00215   if (!IsTileType(tile, MP_INDUSTRY)) return false;
00216 
00217   /* If the station name is undefined it means that it doesn't name a station */
00218   IndustryType indtype = GetIndustryType(tile);
00219   if (GetIndustrySpec(indtype)->station_name == STR_UNDEFINED) return false;
00220 
00221   /* In all cases if an industry that provides a name is found two of
00222    * the standard names will be disabled. */
00223   sni->free_names &= ~(1 << M(STR_SV_STNAME_OILFIELD) | 1 << M(STR_SV_STNAME_MINES));
00224   return !sni->indtypes[indtype];
00225 }
00226 
00227 static StringID GenerateStationName(Station *st, TileIndex tile, StationNaming name_class)
00228 {
00229   static const uint32 _gen_station_name_bits[] = {
00230     0,                                       // STATIONNAMING_RAIL
00231     0,                                       // STATIONNAMING_ROAD
00232     1U << M(STR_SV_STNAME_AIRPORT),          // STATIONNAMING_AIRPORT
00233     1U << M(STR_SV_STNAME_OILFIELD),         // STATIONNAMING_OILRIG
00234     1U << M(STR_SV_STNAME_DOCKS),            // STATIONNAMING_DOCK
00235     1U << M(STR_SV_STNAME_HELIPORT),         // STATIONNAMING_HELIPORT
00236   };
00237 
00238   const Town *t = st->town;
00239   uint32 free_names = UINT32_MAX;
00240 
00241   bool indtypes[NUM_INDUSTRYTYPES];
00242   memset(indtypes, 0, sizeof(indtypes));
00243 
00244   const Station *s;
00245   FOR_ALL_STATIONS(s) {
00246     if (s != st && s->town == t) {
00247       if (s->indtype != IT_INVALID) {
00248         indtypes[s->indtype] = true;
00249         continue;
00250       }
00251       uint str = M(s->string_id);
00252       if (str <= 0x20) {
00253         if (str == M(STR_SV_STNAME_FOREST)) {
00254           str = M(STR_SV_STNAME_WOODS);
00255         }
00256         ClrBit(free_names, str);
00257       }
00258     }
00259   }
00260 
00261   TileIndex indtile = tile;
00262   StationNameInformation sni = { free_names, indtypes };
00263   if (CircularTileSearch(&indtile, 7, FindNearIndustryName, &sni)) {
00264     /* An industry has been found nearby */
00265     IndustryType indtype = GetIndustryType(indtile);
00266     const IndustrySpec *indsp = GetIndustrySpec(indtype);
00267     /* STR_NULL means it only disables oil rig/mines */
00268     if (indsp->station_name != STR_NULL) {
00269       st->indtype = indtype;
00270       return STR_SV_STNAME_FALLBACK;
00271     }
00272   }
00273 
00274   /* Oil rigs/mines name could be marked not free by looking for a near by industry. */
00275   free_names = sni.free_names;
00276 
00277   /* check default names */
00278   uint32 tmp = free_names & _gen_station_name_bits[name_class];
00279   if (tmp != 0) return STR_SV_STNAME + FindFirstBit(tmp);
00280 
00281   /* check mine? */
00282   if (HasBit(free_names, M(STR_SV_STNAME_MINES))) {
00283     if (CountMapSquareAround(tile, CMSAMine) >= 2) {
00284       return STR_SV_STNAME_MINES;
00285     }
00286   }
00287 
00288   /* check close enough to town to get central as name? */
00289   if (DistanceMax(tile, t->xy) < 8) {
00290     if (HasBit(free_names, M(STR_SV_STNAME))) return STR_SV_STNAME;
00291 
00292     if (HasBit(free_names, M(STR_SV_STNAME_CENTRAL))) return STR_SV_STNAME_CENTRAL;
00293   }
00294 
00295   /* Check lakeside */
00296   if (HasBit(free_names, M(STR_SV_STNAME_LAKESIDE)) &&
00297       DistanceFromEdge(tile) < 20 &&
00298       CountMapSquareAround(tile, CMSAWater) >= 5) {
00299     return STR_SV_STNAME_LAKESIDE;
00300   }
00301 
00302   /* Check woods */
00303   if (HasBit(free_names, M(STR_SV_STNAME_WOODS)) && (
00304         CountMapSquareAround(tile, CMSATree) >= 8 ||
00305         CountMapSquareAround(tile, IsTileForestIndustry) >= 2)
00306       ) {
00307     return _settings_game.game_creation.landscape == LT_TROPIC ? STR_SV_STNAME_FOREST : STR_SV_STNAME_WOODS;
00308   }
00309 
00310   /* check elevation compared to town */
00311   int z = GetTileZ(tile);
00312   int z2 = GetTileZ(t->xy);
00313   if (z < z2) {
00314     if (HasBit(free_names, M(STR_SV_STNAME_VALLEY))) return STR_SV_STNAME_VALLEY;
00315   } else if (z > z2) {
00316     if (HasBit(free_names, M(STR_SV_STNAME_HEIGHTS))) return STR_SV_STNAME_HEIGHTS;
00317   }
00318 
00319   /* check direction compared to town */
00320   static const int8 _direction_and_table[] = {
00321     ~( (1 << M(STR_SV_STNAME_WEST))  | (1 << M(STR_SV_STNAME_EAST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
00322     ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
00323     ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_EAST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
00324     ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_EAST)) ),
00325   };
00326 
00327   free_names &= _direction_and_table[
00328     (TileX(tile) < TileX(t->xy)) +
00329     (TileY(tile) < TileY(t->xy)) * 2];
00330 
00331   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));
00332   return (tmp == 0) ? STR_SV_STNAME_FALLBACK : (STR_SV_STNAME + FindFirstBit(tmp));
00333 }
00334 #undef M
00335 
00341 static Station *GetClosestDeletedStation(TileIndex tile)
00342 {
00343   uint threshold = 8;
00344   Station *best_station = NULL;
00345   Station *st;
00346 
00347   FOR_ALL_STATIONS(st) {
00348     if (!st->IsInUse() && st->owner == _current_company) {
00349       uint cur_dist = DistanceManhattan(tile, st->xy);
00350 
00351       if (cur_dist < threshold) {
00352         threshold = cur_dist;
00353         best_station = st;
00354       }
00355     }
00356   }
00357 
00358   return best_station;
00359 }
00360 
00361 
00362 void Station::GetTileArea(TileArea *ta, StationType type) const
00363 {
00364   switch (type) {
00365     case STATION_RAIL:
00366       *ta = this->train_station;
00367       return;
00368 
00369     case STATION_AIRPORT:
00370       *ta = this->airport;
00371       return;
00372 
00373     case STATION_TRUCK:
00374       *ta = this->truck_station;
00375       return;
00376 
00377     case STATION_BUS:
00378       *ta = this->bus_station;
00379       return;
00380 
00381     case STATION_DOCK:
00382     case STATION_OILRIG:
00383       ta->tile = this->dock_tile;
00384       break;
00385 
00386     default: NOT_REACHED();
00387   }
00388 
00389   ta->w = 1;
00390   ta->h = 1;
00391 }
00392 
00396 void Station::UpdateVirtCoord()
00397 {
00398   Point pt = RemapCoords2(TileX(this->xy) * TILE_SIZE, TileY(this->xy) * TILE_SIZE);
00399 
00400   pt.y -= 32 * ZOOM_LVL_BASE;
00401   if ((this->facilities & FACIL_AIRPORT) && this->airport.type == AT_OILRIG) pt.y -= 16 * ZOOM_LVL_BASE;
00402 
00403   SetDParam(0, this->index);
00404   SetDParam(1, this->facilities);
00405   this->sign.UpdatePosition(pt.x, pt.y, STR_VIEWPORT_STATION);
00406 
00407   SetWindowDirty(WC_STATION_VIEW, this->index);
00408 }
00409 
00411 void UpdateAllStationVirtCoords()
00412 {
00413   BaseStation *st;
00414 
00415   FOR_ALL_BASE_STATIONS(st) {
00416     st->UpdateVirtCoord();
00417   }
00418 }
00419 
00425 static uint GetAcceptanceMask(const Station *st)
00426 {
00427   uint mask = 0;
00428 
00429   for (CargoID i = 0; i < NUM_CARGO; i++) {
00430     if (HasBit(st->goods[i].acceptance_pickup, GoodsEntry::GES_ACCEPTANCE)) mask |= 1 << i;
00431   }
00432   return mask;
00433 }
00434 
00439 static void ShowRejectOrAcceptNews(const Station *st, uint num_items, CargoID *cargo, StringID msg)
00440 {
00441   for (uint i = 0; i < num_items; i++) {
00442     SetDParam(i + 1, CargoSpec::Get(cargo[i])->name);
00443   }
00444 
00445   SetDParam(0, st->index);
00446   AddNewsItem(msg, NS_ACCEPTANCE, NR_STATION, st->index);
00447 }
00448 
00456 CargoArray GetProductionAroundTiles(TileIndex tile, int w, int h, int rad)
00457 {
00458   CargoArray produced;
00459 
00460   int x = TileX(tile);
00461   int y = TileY(tile);
00462 
00463   /* expand the region by rad tiles on each side
00464    * while making sure that we remain inside the board. */
00465   int x2 = min(x + w + rad, MapSizeX());
00466   int x1 = max(x - rad, 0);
00467 
00468   int y2 = min(y + h + rad, MapSizeY());
00469   int y1 = max(y - rad, 0);
00470 
00471   assert(x1 < x2);
00472   assert(y1 < y2);
00473   assert(w > 0);
00474   assert(h > 0);
00475 
00476   TileArea ta(TileXY(x1, y1), TileXY(x2 - 1, y2 - 1));
00477 
00478   /* Loop over all tiles to get the produced cargo of
00479    * everything except industries */
00480   TILE_AREA_LOOP(tile, ta) AddProducedCargo(tile, produced);
00481 
00482   /* Loop over the industries. They produce cargo for
00483    * anything that is within 'rad' from their bounding
00484    * box. As such if you have e.g. a oil well the tile
00485    * area loop might not hit an industry tile while
00486    * the industry would produce cargo for the station.
00487    */
00488   const Industry *i;
00489   FOR_ALL_INDUSTRIES(i) {
00490     if (!ta.Intersects(i->location)) continue;
00491 
00492     for (uint j = 0; j < lengthof(i->produced_cargo); j++) {
00493       CargoID cargo = i->produced_cargo[j];
00494       if (cargo != CT_INVALID) produced[cargo]++;
00495     }
00496   }
00497 
00498   return produced;
00499 }
00500 
00509 CargoArray GetAcceptanceAroundTiles(TileIndex tile, int w, int h, int rad, uint32 *always_accepted)
00510 {
00511   CargoArray acceptance;
00512   if (always_accepted != NULL) *always_accepted = 0;
00513 
00514   int x = TileX(tile);
00515   int y = TileY(tile);
00516 
00517   /* expand the region by rad tiles on each side
00518    * while making sure that we remain inside the board. */
00519   int x2 = min(x + w + rad, MapSizeX());
00520   int y2 = min(y + h + rad, MapSizeY());
00521   int x1 = max(x - rad, 0);
00522   int y1 = max(y - rad, 0);
00523 
00524   assert(x1 < x2);
00525   assert(y1 < y2);
00526   assert(w > 0);
00527   assert(h > 0);
00528 
00529   for (int yc = y1; yc != y2; yc++) {
00530     for (int xc = x1; xc != x2; xc++) {
00531       TileIndex tile = TileXY(xc, yc);
00532       AddAcceptedCargo(tile, acceptance, always_accepted);
00533     }
00534   }
00535 
00536   return acceptance;
00537 }
00538 
00544 void UpdateStationAcceptance(Station *st, bool show_msg)
00545 {
00546   /* old accepted goods types */
00547   uint old_acc = GetAcceptanceMask(st);
00548 
00549   /* And retrieve the acceptance. */
00550   CargoArray acceptance;
00551   if (!st->rect.IsEmpty()) {
00552     acceptance = GetAcceptanceAroundTiles(
00553       TileXY(st->rect.left, st->rect.top),
00554       st->rect.right  - st->rect.left + 1,
00555       st->rect.bottom - st->rect.top  + 1,
00556       st->GetCatchmentRadius(),
00557       &st->always_accepted
00558     );
00559   }
00560 
00561   /* Adjust in case our station only accepts fewer kinds of goods */
00562   for (CargoID i = 0; i < NUM_CARGO; i++) {
00563     uint amt = min(acceptance[i], 15);
00564 
00565     /* Make sure the station can accept the goods type. */
00566     bool is_passengers = IsCargoInClass(i, CC_PASSENGERS);
00567     if ((!is_passengers && !(st->facilities & ~FACIL_BUS_STOP)) ||
00568         (is_passengers && !(st->facilities & ~FACIL_TRUCK_STOP))) {
00569       amt = 0;
00570     }
00571 
00572     SB(st->goods[i].acceptance_pickup, GoodsEntry::GES_ACCEPTANCE, 1, amt >= 8);
00573   }
00574 
00575   /* Only show a message in case the acceptance was actually changed. */
00576   uint new_acc = GetAcceptanceMask(st);
00577   if (old_acc == new_acc) return;
00578 
00579   /* show a message to report that the acceptance was changed? */
00580   if (show_msg && st->owner == _local_company && st->IsInUse()) {
00581     /* List of accept and reject strings for different number of
00582      * cargo types */
00583     static const StringID accept_msg[] = {
00584       STR_NEWS_STATION_NOW_ACCEPTS_CARGO,
00585       STR_NEWS_STATION_NOW_ACCEPTS_CARGO_AND_CARGO,
00586     };
00587     static const StringID reject_msg[] = {
00588       STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO,
00589       STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO_OR_CARGO,
00590     };
00591 
00592     /* Array of accepted and rejected cargo types */
00593     CargoID accepts[2] = { CT_INVALID, CT_INVALID };
00594     CargoID rejects[2] = { CT_INVALID, CT_INVALID };
00595     uint num_acc = 0;
00596     uint num_rej = 0;
00597 
00598     /* Test each cargo type to see if its acceptange has changed */
00599     for (CargoID i = 0; i < NUM_CARGO; i++) {
00600       if (HasBit(new_acc, i)) {
00601         if (!HasBit(old_acc, i) && num_acc < lengthof(accepts)) {
00602           /* New cargo is accepted */
00603           accepts[num_acc++] = i;
00604         }
00605       } else {
00606         if (HasBit(old_acc, i) && num_rej < lengthof(rejects)) {
00607           /* Old cargo is no longer accepted */
00608           rejects[num_rej++] = i;
00609         }
00610       }
00611     }
00612 
00613     /* Show news message if there are any changes */
00614     if (num_acc > 0) ShowRejectOrAcceptNews(st, num_acc, accepts, accept_msg[num_acc - 1]);
00615     if (num_rej > 0) ShowRejectOrAcceptNews(st, num_rej, rejects, reject_msg[num_rej - 1]);
00616   }
00617 
00618   /* redraw the station view since acceptance changed */
00619   SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_ACCEPT_RATING_LIST);
00620 }
00621 
00622 static void UpdateStationSignCoord(BaseStation *st)
00623 {
00624   const StationRect *r = &st->rect;
00625 
00626   if (r->IsEmpty()) return; // no tiles belong to this station
00627 
00628   /* clamp sign coord to be inside the station rect */
00629   st->xy = TileXY(ClampU(TileX(st->xy), r->left, r->right), ClampU(TileY(st->xy), r->top, r->bottom));
00630   st->UpdateVirtCoord();
00631 }
00632 
00639 static void DeleteStationIfEmpty(BaseStation *st)
00640 {
00641   if (!st->IsInUse()) {
00642     st->delete_ctr = 0;
00643     InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
00644   }
00645   /* station remains but it probably lost some parts - station sign should stay in the station boundaries */
00646   UpdateStationSignCoord(st);
00647 }
00648 
00649 CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags);
00650 
00660 CommandCost CheckBuildableTile(TileIndex tile, uint invalid_dirs, int &allowed_z, bool allow_steep, bool check_bridge = true)
00661 {
00662   if (check_bridge && MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) {
00663     return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
00664   }
00665 
00666   CommandCost ret = EnsureNoVehicleOnGround(tile);
00667   if (ret.Failed()) return ret;
00668 
00669   int z;
00670   Slope tileh = GetTileSlope(tile, &z);
00671 
00672   /* Prohibit building if
00673    *   1) The tile is "steep" (i.e. stretches two height levels).
00674    *   2) The tile is non-flat and the build_on_slopes switch is disabled.
00675    */
00676   if ((!allow_steep && IsSteepSlope(tileh)) ||
00677       ((!_settings_game.construction.build_on_slopes) && tileh != SLOPE_FLAT)) {
00678     return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
00679   }
00680 
00681   CommandCost cost(EXPENSES_CONSTRUCTION);
00682   int flat_z = z + GetSlopeMaxZ(tileh);
00683   if (tileh != SLOPE_FLAT) {
00684     /* Forbid building if the tile faces a slope in a invalid direction. */
00685     for (DiagDirection dir = DIAGDIR_BEGIN; dir != DIAGDIR_END; dir++) {
00686       if (HasBit(invalid_dirs, dir) && !CanBuildDepotByTileh(dir, tileh)) {
00687         return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
00688       }
00689     }
00690     cost.AddCost(_price[PR_BUILD_FOUNDATION]);
00691   }
00692 
00693   /* The level of this tile must be equal to allowed_z. */
00694   if (allowed_z < 0) {
00695     /* First tile. */
00696     allowed_z = flat_z;
00697   } else if (allowed_z != flat_z) {
00698     return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
00699   }
00700 
00701   return cost;
00702 }
00703 
00710 CommandCost CheckFlatLand(TileArea tile_area, DoCommandFlag flags)
00711 {
00712   CommandCost cost(EXPENSES_CONSTRUCTION);
00713   int allowed_z = -1;
00714 
00715   TILE_AREA_LOOP(tile_cur, tile_area) {
00716     CommandCost ret = CheckBuildableTile(tile_cur, 0, allowed_z, true);
00717     if (ret.Failed()) return ret;
00718     cost.AddCost(ret);
00719 
00720     ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00721     if (ret.Failed()) return ret;
00722     cost.AddCost(ret);
00723   }
00724 
00725   return cost;
00726 }
00727 
00742 static CommandCost CheckFlatLandRailStation(TileArea tile_area, DoCommandFlag flags, Axis axis, StationID *station, RailType rt, SmallVector<Train *, 4> &affected_vehicles, StationClassID spec_class, byte spec_index, byte plat_len, byte numtracks)
00743 {
00744   CommandCost cost(EXPENSES_CONSTRUCTION);
00745   int allowed_z = -1;
00746   uint invalid_dirs = 5 << axis;
00747 
00748   const StationSpec *statspec = StationClass::Get(spec_class, spec_index);
00749   bool slope_cb = statspec != NULL && HasBit(statspec->callback_mask, CBM_STATION_SLOPE_CHECK);
00750 
00751   TILE_AREA_LOOP(tile_cur, tile_area) {
00752     CommandCost ret = CheckBuildableTile(tile_cur, invalid_dirs, allowed_z, false);
00753     if (ret.Failed()) return ret;
00754     cost.AddCost(ret);
00755 
00756     if (slope_cb) {
00757       /* Do slope check if requested. */
00758       ret = PerformStationTileSlopeCheck(tile_area.tile, tile_cur, statspec, axis, plat_len, numtracks);
00759       if (ret.Failed()) return ret;
00760     }
00761 
00762     /* if station is set, then we have special handling to allow building on top of already existing stations.
00763      * so station points to INVALID_STATION if we can build on any station.
00764      * Or it points to a station if we're only allowed to build on exactly that station. */
00765     if (station != NULL && IsTileType(tile_cur, MP_STATION)) {
00766       if (!IsRailStation(tile_cur)) {
00767         return ClearTile_Station(tile_cur, DC_AUTO); // get error message
00768       } else {
00769         StationID st = GetStationIndex(tile_cur);
00770         if (*station == INVALID_STATION) {
00771           *station = st;
00772         } else if (*station != st) {
00773           return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
00774         }
00775       }
00776     } else {
00777       /* Rail type is only valid when building a railway station; if station to
00778        * build isn't a rail station it's INVALID_RAILTYPE. */
00779       if (rt != INVALID_RAILTYPE &&
00780           IsPlainRailTile(tile_cur) && !HasSignals(tile_cur) &&
00781           HasPowerOnRail(GetRailType(tile_cur), rt)) {
00782         /* Allow overbuilding if the tile:
00783          *  - has rail, but no signals
00784          *  - it has exactly one track
00785          *  - the track is in line with the station
00786          *  - the current rail type has power on the to-be-built type (e.g. convert normal rail to el rail)
00787          */
00788         TrackBits tracks = GetTrackBits(tile_cur);
00789         Track track = RemoveFirstTrack(&tracks);
00790         Track expected_track = HasBit(invalid_dirs, DIAGDIR_NE) ? TRACK_X : TRACK_Y;
00791 
00792         if (tracks == TRACK_BIT_NONE && track == expected_track) {
00793           /* Check for trains having a reservation for this tile. */
00794           if (HasBit(GetRailReservationTrackBits(tile_cur), track)) {
00795             Train *v = GetTrainForReservation(tile_cur, track);
00796             if (v != NULL) {
00797               *affected_vehicles.Append() = v;
00798             }
00799           }
00800           CommandCost ret = DoCommand(tile_cur, 0, track, flags, CMD_REMOVE_SINGLE_RAIL);
00801           if (ret.Failed()) return ret;
00802           cost.AddCost(ret);
00803           /* With flags & ~DC_EXEC CmdLandscapeClear would fail since the rail still exists */
00804           continue;
00805         }
00806       }
00807       ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00808       if (ret.Failed()) return ret;
00809       cost.AddCost(ret);
00810     }
00811   }
00812 
00813   return cost;
00814 }
00815 
00828 static CommandCost CheckFlatLandRoadStop(TileArea tile_area, DoCommandFlag flags, uint invalid_dirs, bool is_drive_through, bool is_truck_stop, Axis axis, StationID *station, RoadTypes rts)
00829 {
00830   CommandCost cost(EXPENSES_CONSTRUCTION);
00831   int allowed_z = -1;
00832 
00833   TILE_AREA_LOOP(cur_tile, tile_area) {
00834     CommandCost ret = CheckBuildableTile(cur_tile, invalid_dirs, allowed_z, !is_drive_through);
00835     if (ret.Failed()) return ret;
00836     cost.AddCost(ret);
00837 
00838     /* If station is set, then we have special handling to allow building on top of already existing stations.
00839      * Station points to INVALID_STATION if we can build on any station.
00840      * Or it points to a station if we're only allowed to build on exactly that station. */
00841     if (station != NULL && IsTileType(cur_tile, MP_STATION)) {
00842       if (!IsRoadStop(cur_tile)) {
00843         return ClearTile_Station(cur_tile, DC_AUTO); // Get error message.
00844       } else {
00845         if (is_truck_stop != IsTruckStop(cur_tile) ||
00846             is_drive_through != IsDriveThroughStopTile(cur_tile)) {
00847           return ClearTile_Station(cur_tile, DC_AUTO); // Get error message.
00848         }
00849         /* Drive-through station in the wrong direction. */
00850         if (is_drive_through && IsDriveThroughStopTile(cur_tile) && DiagDirToAxis(GetRoadStopDir(cur_tile)) != axis){
00851           return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
00852         }
00853         StationID st = GetStationIndex(cur_tile);
00854         if (*station == INVALID_STATION) {
00855           *station = st;
00856         } else if (*station != st) {
00857           return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
00858         }
00859       }
00860     } else {
00861       bool build_over_road = is_drive_through && IsNormalRoadTile(cur_tile);
00862       /* Road bits in the wrong direction. */
00863       RoadBits rb = IsNormalRoadTile(cur_tile) ? GetAllRoadBits(cur_tile) : ROAD_NONE;
00864       if (build_over_road && (rb & (axis == AXIS_X ? ROAD_Y : ROAD_X)) != 0) {
00865         /* Someone was pedantic and *NEEDED* three fracking different error messages. */
00866         switch (CountBits(rb)) {
00867           case 1:
00868             return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
00869 
00870           case 2:
00871             if (rb == ROAD_X || rb == ROAD_Y) return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
00872             return_cmd_error(STR_ERROR_DRIVE_THROUGH_CORNER);
00873 
00874           default: // 3 or 4
00875             return_cmd_error(STR_ERROR_DRIVE_THROUGH_JUNCTION);
00876         }
00877       }
00878 
00879       RoadTypes cur_rts = IsNormalRoadTile(cur_tile) ? GetRoadTypes(cur_tile) : ROADTYPES_NONE;
00880       uint num_roadbits = 0;
00881       if (build_over_road) {
00882         /* There is a road, check if we can build road+tram stop over it. */
00883         if (HasBit(cur_rts, ROADTYPE_ROAD)) {
00884           Owner road_owner = GetRoadOwner(cur_tile, ROADTYPE_ROAD);
00885           if (road_owner == OWNER_TOWN) {
00886             if (!_settings_game.construction.road_stop_on_town_road) return_cmd_error(STR_ERROR_DRIVE_THROUGH_ON_TOWN_ROAD);
00887           } else if (!_settings_game.construction.road_stop_on_competitor_road && road_owner != OWNER_NONE) {
00888             CommandCost ret = CheckOwnership(road_owner);
00889             if (ret.Failed()) return ret;
00890           }
00891           num_roadbits += CountBits(GetRoadBits(cur_tile, ROADTYPE_ROAD));
00892         }
00893 
00894         /* There is a tram, check if we can build road+tram stop over it. */
00895         if (HasBit(cur_rts, ROADTYPE_TRAM)) {
00896           Owner tram_owner = GetRoadOwner(cur_tile, ROADTYPE_TRAM);
00897           if (!_settings_game.construction.road_stop_on_competitor_road && tram_owner != OWNER_NONE) {
00898             CommandCost ret = CheckOwnership(tram_owner);
00899             if (ret.Failed()) return ret;
00900           }
00901           num_roadbits += CountBits(GetRoadBits(cur_tile, ROADTYPE_TRAM));
00902         }
00903 
00904         /* Take into account existing roadbits. */
00905         rts |= cur_rts;
00906       } else {
00907         ret = DoCommand(cur_tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00908         if (ret.Failed()) return ret;
00909         cost.AddCost(ret);
00910       }
00911 
00912       uint roadbits_to_build = CountBits(rts) * 2 - num_roadbits;
00913       cost.AddCost(_price[PR_BUILD_ROAD] * roadbits_to_build);
00914     }
00915   }
00916 
00917   return cost;
00918 }
00919 
00927 CommandCost CanExpandRailStation(const BaseStation *st, TileArea &new_ta, Axis axis)
00928 {
00929   TileArea cur_ta = st->train_station;
00930 
00931   /* determine new size of train station region.. */
00932   int x = min(TileX(cur_ta.tile), TileX(new_ta.tile));
00933   int y = min(TileY(cur_ta.tile), TileY(new_ta.tile));
00934   new_ta.w = max(TileX(cur_ta.tile) + cur_ta.w, TileX(new_ta.tile) + new_ta.w) - x;
00935   new_ta.h = max(TileY(cur_ta.tile) + cur_ta.h, TileY(new_ta.tile) + new_ta.h) - y;
00936   new_ta.tile = TileXY(x, y);
00937 
00938   /* make sure the final size is not too big. */
00939   if (new_ta.w > _settings_game.station.station_spread || new_ta.h > _settings_game.station.station_spread) {
00940     return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
00941   }
00942 
00943   return CommandCost();
00944 }
00945 
00946 static inline byte *CreateSingle(byte *layout, int n)
00947 {
00948   int i = n;
00949   do *layout++ = 0; while (--i);
00950   layout[((n - 1) >> 1) - n] = 2;
00951   return layout;
00952 }
00953 
00954 static inline byte *CreateMulti(byte *layout, int n, byte b)
00955 {
00956   int i = n;
00957   do *layout++ = b; while (--i);
00958   if (n > 4) {
00959     layout[0 - n] = 0;
00960     layout[n - 1 - n] = 0;
00961   }
00962   return layout;
00963 }
00964 
00972 void GetStationLayout(byte *layout, int numtracks, int plat_len, const StationSpec *statspec)
00973 {
00974   if (statspec != NULL && statspec->lengths >= plat_len &&
00975       statspec->platforms[plat_len - 1] >= numtracks &&
00976       statspec->layouts[plat_len - 1][numtracks - 1]) {
00977     /* Custom layout defined, follow it. */
00978     memcpy(layout, statspec->layouts[plat_len - 1][numtracks - 1],
00979       plat_len * numtracks);
00980     return;
00981   }
00982 
00983   if (plat_len == 1) {
00984     CreateSingle(layout, numtracks);
00985   } else {
00986     if (numtracks & 1) layout = CreateSingle(layout, plat_len);
00987     numtracks >>= 1;
00988 
00989     while (--numtracks >= 0) {
00990       layout = CreateMulti(layout, plat_len, 4);
00991       layout = CreateMulti(layout, plat_len, 6);
00992     }
00993   }
00994 }
00995 
01007 template <class T, StringID error_message>
01008 CommandCost FindJoiningBaseStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, T **st)
01009 {
01010   assert(*st == NULL);
01011   bool check_surrounding = true;
01012 
01013   if (_settings_game.station.adjacent_stations) {
01014     if (existing_station != INVALID_STATION) {
01015       if (adjacent && existing_station != station_to_join) {
01016         /* You can't build an adjacent station over the top of one that
01017          * already exists. */
01018         return_cmd_error(error_message);
01019       } else {
01020         /* Extend the current station, and don't check whether it will
01021          * be near any other stations. */
01022         *st = T::GetIfValid(existing_station);
01023         check_surrounding = (*st == NULL);
01024       }
01025     } else {
01026       /* There's no station here. Don't check the tiles surrounding this
01027        * one if the company wanted to build an adjacent station. */
01028       if (adjacent) check_surrounding = false;
01029     }
01030   }
01031 
01032   if (check_surrounding) {
01033     /* Make sure there are no similar stations around us. */
01034     CommandCost ret = GetStationAround(ta, existing_station, st);
01035     if (ret.Failed()) return ret;
01036   }
01037 
01038   /* Distant join */
01039   if (*st == NULL && station_to_join != INVALID_STATION) *st = T::GetIfValid(station_to_join);
01040 
01041   return CommandCost();
01042 }
01043 
01053 static CommandCost FindJoiningStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
01054 {
01055   return FindJoiningBaseStation<Station, STR_ERROR_MUST_REMOVE_RAILWAY_STATION_FIRST>(existing_station, station_to_join, adjacent, ta, st);
01056 }
01057 
01067 CommandCost FindJoiningWaypoint(StationID existing_waypoint, StationID waypoint_to_join, bool adjacent, TileArea ta, Waypoint **wp)
01068 {
01069   return FindJoiningBaseStation<Waypoint, STR_ERROR_MUST_REMOVE_RAILWAYPOINT_FIRST>(existing_waypoint, waypoint_to_join, adjacent, ta, wp);
01070 }
01071 
01089 CommandCost CmdBuildRailStation(TileIndex tile_org, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01090 {
01091   /* Unpack parameters */
01092   RailType rt    = Extract<RailType, 0, 4>(p1);
01093   Axis axis      = Extract<Axis, 4, 1>(p1);
01094   byte numtracks = GB(p1,  8, 8);
01095   byte plat_len  = GB(p1, 16, 8);
01096   bool adjacent  = HasBit(p1, 24);
01097 
01098   StationClassID spec_class = Extract<StationClassID, 0, 8>(p2);
01099   byte spec_index           = GB(p2, 8, 8);
01100   StationID station_to_join = GB(p2, 16, 16);
01101 
01102   /* Does the authority allow this? */
01103   CommandCost ret = CheckIfAuthorityAllowsNewStation(tile_org, flags);
01104   if (ret.Failed()) return ret;
01105 
01106   if (!ValParamRailtype(rt)) return CMD_ERROR;
01107 
01108   /* Check if the given station class is valid */
01109   if ((uint)spec_class >= StationClass::GetCount() || spec_class == STAT_CLASS_WAYP) return CMD_ERROR;
01110   if (spec_index >= StationClass::GetCount(spec_class)) return CMD_ERROR;
01111   if (plat_len == 0 || numtracks == 0) return CMD_ERROR;
01112 
01113   int w_org, h_org;
01114   if (axis == AXIS_X) {
01115     w_org = plat_len;
01116     h_org = numtracks;
01117   } else {
01118     h_org = plat_len;
01119     w_org = numtracks;
01120   }
01121 
01122   bool reuse = (station_to_join != NEW_STATION);
01123   if (!reuse) station_to_join = INVALID_STATION;
01124   bool distant_join = (station_to_join != INVALID_STATION);
01125 
01126   if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
01127 
01128   if (h_org > _settings_game.station.station_spread || w_org > _settings_game.station.station_spread) return CMD_ERROR;
01129 
01130   /* these values are those that will be stored in train_tile and station_platforms */
01131   TileArea new_location(tile_org, w_org, h_org);
01132 
01133   /* Make sure the area below consists of clear tiles. (OR tiles belonging to a certain rail station) */
01134   StationID est = INVALID_STATION;
01135   SmallVector<Train *, 4> affected_vehicles;
01136   /* Clear the land below the station. */
01137   CommandCost cost = CheckFlatLandRailStation(TileArea(tile_org, w_org, h_org), flags, axis, &est, rt, affected_vehicles, spec_class, spec_index, plat_len, numtracks);
01138   if (cost.Failed()) return cost;
01139   /* Add construction expenses. */
01140   cost.AddCost((numtracks * _price[PR_BUILD_STATION_RAIL] + _price[PR_BUILD_STATION_RAIL_LENGTH]) * plat_len);
01141   cost.AddCost(numtracks * plat_len * RailBuildCost(rt));
01142 
01143   Station *st = NULL;
01144   ret = FindJoiningStation(est, station_to_join, adjacent, new_location, &st);
01145   if (ret.Failed()) return ret;
01146 
01147   /* See if there is a deleted station close to us. */
01148   if (st == NULL && reuse) st = GetClosestDeletedStation(tile_org);
01149 
01150   if (st != NULL) {
01151     /* Reuse an existing station. */
01152     if (st->owner != _current_company) return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_STATION);
01153 
01154     if (st->train_station.tile != INVALID_TILE) {
01155       CommandCost ret = CanExpandRailStation(st, new_location, axis);
01156       if (ret.Failed()) return ret;
01157     }
01158 
01159     /* XXX can't we pack this in the "else" part of the if above? */
01160     CommandCost ret = st->rect.BeforeAddRect(tile_org, w_org, h_org, StationRect::ADD_TEST);
01161     if (ret.Failed()) return ret;
01162   } else {
01163     /* allocate and initialize new station */
01164     if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
01165 
01166     if (flags & DC_EXEC) {
01167       st = new Station(tile_org);
01168 
01169       st->town = ClosestTownFromTile(tile_org, UINT_MAX);
01170       st->string_id = GenerateStationName(st, tile_org, STATIONNAMING_RAIL);
01171 
01172       if (Company::IsValidID(_current_company)) {
01173         SetBit(st->town->have_ratings, _current_company);
01174       }
01175     }
01176   }
01177 
01178   /* Check if we can allocate a custom stationspec to this station */
01179   const StationSpec *statspec = StationClass::Get(spec_class, spec_index);
01180   int specindex = AllocateSpecToStation(statspec, st, (flags & DC_EXEC) != 0);
01181   if (specindex == -1) return_cmd_error(STR_ERROR_TOO_MANY_STATION_SPECS);
01182 
01183   if (statspec != NULL) {
01184     /* Perform NewStation checks */
01185 
01186     /* Check if the station size is permitted */
01187     if (HasBit(statspec->disallowed_platforms, numtracks - 1) || HasBit(statspec->disallowed_lengths, plat_len - 1)) {
01188       return CMD_ERROR;
01189     }
01190 
01191     /* Check if the station is buildable */
01192     if (HasBit(statspec->callback_mask, CBM_STATION_AVAIL)) {
01193       uint16 cb_res = GetStationCallback(CBID_STATION_AVAILABILITY, 0, 0, statspec, NULL, INVALID_TILE);
01194       if (cb_res != CALLBACK_FAILED && !Convert8bitBooleanCallback(statspec->grf_prop.grffile, CBID_STATION_AVAILABILITY, cb_res)) return CMD_ERROR;
01195     }
01196   }
01197 
01198   if (flags & DC_EXEC) {
01199     TileIndexDiff tile_delta;
01200     byte *layout_ptr;
01201     byte numtracks_orig;
01202     Track track;
01203 
01204     st->train_station = new_location;
01205     st->AddFacility(FACIL_TRAIN, new_location.tile);
01206 
01207     st->rect.BeforeAddRect(tile_org, w_org, h_org, StationRect::ADD_TRY);
01208 
01209     if (statspec != NULL) {
01210       /* Include this station spec's animation trigger bitmask
01211        * in the station's cached copy. */
01212       st->cached_anim_triggers |= statspec->animation.triggers;
01213     }
01214 
01215     tile_delta = (axis == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
01216     track = AxisToTrack(axis);
01217 
01218     layout_ptr = AllocaM(byte, numtracks * plat_len);
01219     GetStationLayout(layout_ptr, numtracks, plat_len, statspec);
01220 
01221     numtracks_orig = numtracks;
01222 
01223     Company *c = Company::Get(st->owner);
01224     do {
01225       TileIndex tile = tile_org;
01226       int w = plat_len;
01227       do {
01228         byte layout = *layout_ptr++;
01229         if (IsRailStationTile(tile) && HasStationReservation(tile)) {
01230           /* Check for trains having a reservation for this tile. */
01231           Train *v = GetTrainForReservation(tile, AxisToTrack(GetRailStationAxis(tile)));
01232           if (v != NULL) {
01233             FreeTrainTrackReservation(v);
01234             *affected_vehicles.Append() = v;
01235             if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), false);
01236             for (; v->Next() != NULL; v = v->Next()) { }
01237             if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), false);
01238           }
01239         }
01240 
01241         /* Railtype can change when overbuilding. */
01242         if (IsRailStationTile(tile)) {
01243           if (!IsStationTileBlocked(tile)) c->infrastructure.rail[GetRailType(tile)]--;
01244           c->infrastructure.station--;
01245         }
01246 
01247         /* Remove animation if overbuilding */
01248         DeleteAnimatedTile(tile);
01249         byte old_specindex = HasStationTileRail(tile) ? GetCustomStationSpecIndex(tile) : 0;
01250         MakeRailStation(tile, st->owner, st->index, axis, layout & ~1, rt);
01251         /* Free the spec if we overbuild something */
01252         DeallocateSpecFromStation(st, old_specindex);
01253 
01254         SetCustomStationSpecIndex(tile, specindex);
01255         SetStationTileRandomBits(tile, GB(Random(), 0, 4));
01256         SetAnimationFrame(tile, 0);
01257 
01258         if (!IsStationTileBlocked(tile)) c->infrastructure.rail[rt]++;
01259         c->infrastructure.station++;
01260 
01261         if (statspec != NULL) {
01262           /* Use a fixed axis for GetPlatformInfo as our platforms / numtracks are always the right way around */
01263           uint32 platinfo = GetPlatformInfo(AXIS_X, 0, plat_len, numtracks_orig, plat_len - w, numtracks_orig - numtracks, false);
01264 
01265           /* As the station is not yet completely finished, the station does not yet exist. */
01266           uint16 callback = GetStationCallback(CBID_STATION_TILE_LAYOUT, platinfo, 0, statspec, NULL, tile);
01267           if (callback != CALLBACK_FAILED) {
01268             if (callback < 8) {
01269               SetStationGfx(tile, (callback & ~1) + axis);
01270             } else {
01271               ErrorUnknownCallbackResult(statspec->grf_prop.grffile->grfid, CBID_STATION_TILE_LAYOUT, callback);
01272             }
01273           }
01274 
01275           /* Trigger station animation -- after building? */
01276           TriggerStationAnimation(st, tile, SAT_BUILT);
01277         }
01278 
01279         tile += tile_delta;
01280       } while (--w);
01281       AddTrackToSignalBuffer(tile_org, track, _current_company);
01282       YapfNotifyTrackLayoutChange(tile_org, track);
01283       tile_org += tile_delta ^ TileDiffXY(1, 1); // perpendicular to tile_delta
01284     } while (--numtracks);
01285 
01286     for (uint i = 0; i < affected_vehicles.Length(); ++i) {
01287       /* Restore reservations of trains. */
01288       Train *v = affected_vehicles[i];
01289       if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
01290       TryPathReserve(v, true, true);
01291       for (; v->Next() != NULL; v = v->Next()) { }
01292       if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), true);
01293     }
01294 
01295     st->MarkTilesDirty(false);
01296     st->UpdateVirtCoord();
01297     UpdateStationAcceptance(st, false);
01298     st->RecomputeIndustriesNear();
01299     InvalidateWindowData(WC_SELECT_STATION, 0, 0);
01300     InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
01301     SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
01302     DirtyCompanyInfrastructureWindows(st->owner);
01303   }
01304 
01305   return cost;
01306 }
01307 
01308 static void MakeRailStationAreaSmaller(BaseStation *st)
01309 {
01310   TileArea ta = st->train_station;
01311 
01312 restart:
01313 
01314   /* too small? */
01315   if (ta.w != 0 && ta.h != 0) {
01316     /* check the left side, x = constant, y changes */
01317     for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(0, i));) {
01318       /* the left side is unused? */
01319       if (++i == ta.h) {
01320         ta.tile += TileDiffXY(1, 0);
01321         ta.w--;
01322         goto restart;
01323       }
01324     }
01325 
01326     /* check the right side, x = constant, y changes */
01327     for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(ta.w - 1, i));) {
01328       /* the right side is unused? */
01329       if (++i == ta.h) {
01330         ta.w--;
01331         goto restart;
01332       }
01333     }
01334 
01335     /* check the upper side, y = constant, x changes */
01336     for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(i, 0));) {
01337       /* the left side is unused? */
01338       if (++i == ta.w) {
01339         ta.tile += TileDiffXY(0, 1);
01340         ta.h--;
01341         goto restart;
01342       }
01343     }
01344 
01345     /* check the lower side, y = constant, x changes */
01346     for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(i, ta.h - 1));) {
01347       /* the left side is unused? */
01348       if (++i == ta.w) {
01349         ta.h--;
01350         goto restart;
01351       }
01352     }
01353   } else {
01354     ta.Clear();
01355   }
01356 
01357   st->train_station = ta;
01358 }
01359 
01370 template <class T>
01371 CommandCost RemoveFromRailBaseStation(TileArea ta, SmallVector<T *, 4> &affected_stations, DoCommandFlag flags, Money removal_cost, bool keep_rail)
01372 {
01373   /* Count of the number of tiles removed */
01374   int quantity = 0;
01375   CommandCost total_cost(EXPENSES_CONSTRUCTION);
01376 
01377   /* Do the action for every tile into the area */
01378   TILE_AREA_LOOP(tile, ta) {
01379     /* Make sure the specified tile is a rail station */
01380     if (!HasStationTileRail(tile)) continue;
01381 
01382     /* If there is a vehicle on ground, do not allow to remove (flood) the tile */
01383     CommandCost ret = EnsureNoVehicleOnGround(tile);
01384     if (ret.Failed()) continue;
01385 
01386     /* Check ownership of station */
01387     T *st = T::GetByTile(tile);
01388     if (st == NULL) continue;
01389 
01390     if (_current_company != OWNER_WATER) {
01391       CommandCost ret = CheckOwnership(st->owner);
01392       if (ret.Failed()) continue;
01393     }
01394 
01395     /* If we reached here, the tile is valid so increase the quantity of tiles we will remove */
01396     quantity++;
01397 
01398     if (keep_rail || IsStationTileBlocked(tile)) {
01399       /* Don't refund the 'steel' of the track when we keep the
01400        *  rail, or when the tile didn't have any rail at all. */
01401       total_cost.AddCost(-_price[PR_CLEAR_RAIL]);
01402     }
01403 
01404     if (flags & DC_EXEC) {
01405       /* read variables before the station tile is removed */
01406       uint specindex = GetCustomStationSpecIndex(tile);
01407       Track track = GetRailStationTrack(tile);
01408       Owner owner = GetTileOwner(tile);
01409       RailType rt = GetRailType(tile);
01410       Train *v = NULL;
01411 
01412       if (HasStationReservation(tile)) {
01413         v = GetTrainForReservation(tile, track);
01414         if (v != NULL) {
01415           /* Free train reservation. */
01416           FreeTrainTrackReservation(v);
01417           if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), false);
01418           Vehicle *temp = v;
01419           for (; temp->Next() != NULL; temp = temp->Next()) { }
01420           if (IsRailStationTile(temp->tile)) SetRailStationPlatformReservation(temp->tile, TrackdirToExitdir(ReverseTrackdir(temp->GetVehicleTrackdir())), false);
01421         }
01422       }
01423 
01424       bool build_rail = keep_rail && !IsStationTileBlocked(tile);
01425       if (!build_rail && !IsStationTileBlocked(tile)) Company::Get(owner)->infrastructure.rail[rt]--;
01426 
01427       DoClearSquare(tile);
01428       DeleteNewGRFInspectWindow(GSF_STATIONS, tile);
01429       if (build_rail) MakeRailNormal(tile, owner, TrackToTrackBits(track), rt);
01430       Company::Get(owner)->infrastructure.station--;
01431       DirtyCompanyInfrastructureWindows(owner);
01432 
01433       st->rect.AfterRemoveTile(st, tile);
01434       AddTrackToSignalBuffer(tile, track, owner);
01435       YapfNotifyTrackLayoutChange(tile, track);
01436 
01437       DeallocateSpecFromStation(st, specindex);
01438 
01439       affected_stations.Include(st);
01440 
01441       if (v != NULL) {
01442         /* Restore station reservation. */
01443         if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
01444         TryPathReserve(v, true, true);
01445         for (; v->Next() != NULL; v = v->Next()) { }
01446         if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), true);
01447       }
01448     }
01449   }
01450 
01451   if (quantity == 0) return_cmd_error(STR_ERROR_THERE_IS_NO_STATION);
01452 
01453   for (T **stp = affected_stations.Begin(); stp != affected_stations.End(); stp++) {
01454     T *st = *stp;
01455 
01456     /* now we need to make the "spanned" area of the railway station smaller
01457      * if we deleted something at the edges.
01458      * we also need to adjust train_tile. */
01459     MakeRailStationAreaSmaller(st);
01460     UpdateStationSignCoord(st);
01461 
01462     /* if we deleted the whole station, delete the train facility. */
01463     if (st->train_station.tile == INVALID_TILE) {
01464       st->facilities &= ~FACIL_TRAIN;
01465       SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
01466       st->UpdateVirtCoord();
01467       DeleteStationIfEmpty(st);
01468     }
01469   }
01470 
01471   total_cost.AddCost(quantity * removal_cost);
01472   return total_cost;
01473 }
01474 
01486 CommandCost CmdRemoveFromRailStation(TileIndex start, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01487 {
01488   TileIndex end = p1 == 0 ? start : p1;
01489   if (start >= MapSize() || end >= MapSize()) return CMD_ERROR;
01490 
01491   TileArea ta(start, end);
01492   SmallVector<Station *, 4> affected_stations;
01493 
01494   CommandCost ret = RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_STATION_RAIL], HasBit(p2, 0));
01495   if (ret.Failed()) return ret;
01496 
01497   /* Do all station specific functions here. */
01498   for (Station **stp = affected_stations.Begin(); stp != affected_stations.End(); stp++) {
01499     Station *st = *stp;
01500 
01501     if (st->train_station.tile == INVALID_TILE) SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
01502     st->MarkTilesDirty(false);
01503     st->RecomputeIndustriesNear();
01504   }
01505 
01506   /* Now apply the rail cost to the number that we deleted */
01507   return ret;
01508 }
01509 
01521 CommandCost CmdRemoveFromRailWaypoint(TileIndex start, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01522 {
01523   TileIndex end = p1 == 0 ? start : p1;
01524   if (start >= MapSize() || end >= MapSize()) return CMD_ERROR;
01525 
01526   TileArea ta(start, end);
01527   SmallVector<Waypoint *, 4> affected_stations;
01528 
01529   return RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_WAYPOINT_RAIL], HasBit(p2, 0));
01530 }
01531 
01532 
01540 template <class T>
01541 CommandCost RemoveRailStation(T *st, DoCommandFlag flags)
01542 {
01543   /* Current company owns the station? */
01544   if (_current_company != OWNER_WATER) {
01545     CommandCost ret = CheckOwnership(st->owner);
01546     if (ret.Failed()) return ret;
01547   }
01548 
01549   /* determine width and height of platforms */
01550   TileArea ta = st->train_station;
01551 
01552   assert(ta.w != 0 && ta.h != 0);
01553 
01554   CommandCost cost(EXPENSES_CONSTRUCTION);
01555   /* clear all areas of the station */
01556   TILE_AREA_LOOP(tile, ta) {
01557     /* only remove tiles that are actually train station tiles */
01558     if (!st->TileBelongsToRailStation(tile)) continue;
01559 
01560     CommandCost ret = EnsureNoVehicleOnGround(tile);
01561     if (ret.Failed()) return ret;
01562 
01563     cost.AddCost(_price[PR_CLEAR_STATION_RAIL]);
01564     if (flags & DC_EXEC) {
01565       /* read variables before the station tile is removed */
01566       Track track = GetRailStationTrack(tile);
01567       Owner owner = GetTileOwner(tile); // _current_company can be OWNER_WATER
01568       Train *v = NULL;
01569       if (HasStationReservation(tile)) {
01570         v = GetTrainForReservation(tile, track);
01571         if (v != NULL) FreeTrainTrackReservation(v);
01572       }
01573       if (!IsStationTileBlocked(tile)) Company::Get(owner)->infrastructure.rail[GetRailType(tile)]--;
01574       Company::Get(owner)->infrastructure.station--;
01575       DoClearSquare(tile);
01576       DeleteNewGRFInspectWindow(GSF_STATIONS, tile);
01577       AddTrackToSignalBuffer(tile, track, owner);
01578       YapfNotifyTrackLayoutChange(tile, track);
01579       if (v != NULL) TryPathReserve(v, true);
01580     }
01581   }
01582 
01583   if (flags & DC_EXEC) {
01584     st->rect.AfterRemoveRect(st, st->train_station);
01585 
01586     st->train_station.Clear();
01587 
01588     st->facilities &= ~FACIL_TRAIN;
01589 
01590     free(st->speclist);
01591     st->num_specs = 0;
01592     st->speclist  = NULL;
01593     st->cached_anim_triggers = 0;
01594 
01595     DirtyCompanyInfrastructureWindows(st->owner);
01596     SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
01597     st->UpdateVirtCoord();
01598     DeleteStationIfEmpty(st);
01599   }
01600 
01601   return cost;
01602 }
01603 
01610 static CommandCost RemoveRailStation(TileIndex tile, DoCommandFlag flags)
01611 {
01612   /* if there is flooding, remove platforms tile by tile */
01613   if (_current_company == OWNER_WATER) {
01614     return DoCommand(tile, 0, 0, DC_EXEC, CMD_REMOVE_FROM_RAIL_STATION);
01615   }
01616 
01617   Station *st = Station::GetByTile(tile);
01618   CommandCost cost = RemoveRailStation(st, flags);
01619 
01620   if (flags & DC_EXEC) st->RecomputeIndustriesNear();
01621 
01622   return cost;
01623 }
01624 
01631 static CommandCost RemoveRailWaypoint(TileIndex tile, DoCommandFlag flags)
01632 {
01633   /* if there is flooding, remove waypoints tile by tile */
01634   if (_current_company == OWNER_WATER) {
01635     return DoCommand(tile, 0, 0, DC_EXEC, CMD_REMOVE_FROM_RAIL_WAYPOINT);
01636   }
01637 
01638   return RemoveRailStation(Waypoint::GetByTile(tile), flags);
01639 }
01640 
01641 
01647 static RoadStop **FindRoadStopSpot(bool truck_station, Station *st)
01648 {
01649   RoadStop **primary_stop = (truck_station) ? &st->truck_stops : &st->bus_stops;
01650 
01651   if (*primary_stop == NULL) {
01652     /* we have no roadstop of the type yet, so write a "primary stop" */
01653     return primary_stop;
01654   } else {
01655     /* there are stops already, so append to the end of the list */
01656     RoadStop *stop = *primary_stop;
01657     while (stop->next != NULL) stop = stop->next;
01658     return &stop->next;
01659   }
01660 }
01661 
01662 static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags);
01663 
01673 static CommandCost FindJoiningRoadStop(StationID existing_stop, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
01674 {
01675   return FindJoiningBaseStation<Station, STR_ERROR_MUST_REMOVE_ROAD_STOP_FIRST>(existing_stop, station_to_join, adjacent, ta, st);
01676 }
01677 
01693 CommandCost CmdBuildRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01694 {
01695   bool type = HasBit(p2, 0);
01696   bool is_drive_through = HasBit(p2, 1);
01697   RoadTypes rts = Extract<RoadTypes, 2, 2>(p2);
01698   StationID station_to_join = GB(p2, 16, 16);
01699   bool reuse = (station_to_join != NEW_STATION);
01700   if (!reuse) station_to_join = INVALID_STATION;
01701   bool distant_join = (station_to_join != INVALID_STATION);
01702 
01703   uint8 width = (uint8)GB(p1, 0, 8);
01704   uint8 lenght = (uint8)GB(p1, 8, 8);
01705 
01706   /* Check if the requested road stop is too big */
01707   if (width > _settings_game.station.station_spread || lenght > _settings_game.station.station_spread) return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
01708   /* Check for incorrect width / lenght. */
01709   if (width == 0 || lenght == 0) return CMD_ERROR;
01710   /* Check if the first tile and the last tile are valid */
01711   if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, lenght - 1) == INVALID_TILE) return CMD_ERROR;
01712 
01713   TileArea roadstop_area(tile, width, lenght);
01714 
01715   if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
01716 
01717   if (!HasExactlyOneBit(rts) || !HasRoadTypesAvail(_current_company, rts)) return CMD_ERROR;
01718 
01719   /* Trams only have drive through stops */
01720   if (!is_drive_through && HasBit(rts, ROADTYPE_TRAM)) return CMD_ERROR;
01721 
01722   DiagDirection ddir = Extract<DiagDirection, 6, 2>(p2);
01723 
01724   /* Safeguard the parameters. */
01725   if (!IsValidDiagDirection(ddir)) return CMD_ERROR;
01726   /* If it is a drive-through stop, check for valid axis. */
01727   if (is_drive_through && !IsValidAxis((Axis)ddir)) return CMD_ERROR;
01728 
01729   CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
01730   if (ret.Failed()) return ret;
01731 
01732   /* Total road stop cost. */
01733   CommandCost cost(EXPENSES_CONSTRUCTION, roadstop_area.w * roadstop_area.h * _price[type ? PR_BUILD_STATION_TRUCK : PR_BUILD_STATION_BUS]);
01734   StationID est = INVALID_STATION;
01735   ret = CheckFlatLandRoadStop(roadstop_area, flags, is_drive_through ? 5 << ddir : 1 << ddir, is_drive_through, type, DiagDirToAxis(ddir), &est, rts);
01736   if (ret.Failed()) return ret;
01737   cost.AddCost(ret);
01738 
01739   Station *st = NULL;
01740   ret = FindJoiningRoadStop(est, station_to_join, HasBit(p2, 5), roadstop_area, &st);
01741   if (ret.Failed()) return ret;
01742 
01743   /* Find a deleted station close to us */
01744   if (st == NULL && reuse) st = GetClosestDeletedStation(tile);
01745 
01746   /* Check if this number of road stops can be allocated. */
01747   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);
01748 
01749   if (st != NULL) {
01750     if (st->owner != _current_company) {
01751       return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_STATION);
01752     }
01753 
01754     CommandCost ret = st->rect.BeforeAddRect(roadstop_area.tile, roadstop_area.w, roadstop_area.h, StationRect::ADD_TEST);
01755     if (ret.Failed()) return ret;
01756   } else {
01757     /* allocate and initialize new station */
01758     if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
01759 
01760     if (flags & DC_EXEC) {
01761       st = new Station(tile);
01762 
01763       st->town = ClosestTownFromTile(tile, UINT_MAX);
01764       st->string_id = GenerateStationName(st, tile, STATIONNAMING_ROAD);
01765 
01766       if (Company::IsValidID(_current_company)) {
01767         SetBit(st->town->have_ratings, _current_company);
01768       }
01769     }
01770   }
01771 
01772   if (flags & DC_EXEC) {
01773     /* Check every tile in the area. */
01774     TILE_AREA_LOOP(cur_tile, roadstop_area) {
01775       RoadTypes cur_rts = GetRoadTypes(cur_tile);
01776       Owner road_owner = HasBit(cur_rts, ROADTYPE_ROAD) ? GetRoadOwner(cur_tile, ROADTYPE_ROAD) : _current_company;
01777       Owner tram_owner = HasBit(cur_rts, ROADTYPE_TRAM) ? GetRoadOwner(cur_tile, ROADTYPE_TRAM) : _current_company;
01778 
01779       if (IsTileType(cur_tile, MP_STATION) && IsRoadStop(cur_tile)) {
01780         RemoveRoadStop(cur_tile, flags);
01781       }
01782 
01783       RoadStop *road_stop = new RoadStop(cur_tile);
01784       /* Insert into linked list of RoadStops. */
01785       RoadStop **currstop = FindRoadStopSpot(type, st);
01786       *currstop = road_stop;
01787 
01788       if (type) {
01789         st->truck_station.Add(cur_tile);
01790       } else {
01791         st->bus_station.Add(cur_tile);
01792       }
01793 
01794       /* Initialize an empty station. */
01795       st->AddFacility((type) ? FACIL_TRUCK_STOP : FACIL_BUS_STOP, cur_tile);
01796 
01797       st->rect.BeforeAddTile(cur_tile, StationRect::ADD_TRY);
01798 
01799       RoadStopType rs_type = type ? ROADSTOP_TRUCK : ROADSTOP_BUS;
01800       if (is_drive_through) {
01801         /* Update company infrastructure counts. If the current tile is a normal
01802          * road tile, count only the new road bits needed to get a full diagonal road. */
01803         RoadType rt;
01804         FOR_EACH_SET_ROADTYPE(rt, cur_rts | rts) {
01805           Company *c = Company::GetIfValid(rt == ROADTYPE_ROAD ? road_owner : tram_owner);
01806           if (c != NULL) {
01807             c->infrastructure.road[rt] += 2 - (IsNormalRoadTile(cur_tile) && HasBit(cur_rts, rt) ? CountBits(GetRoadBits(cur_tile, rt)) : 0);
01808             DirtyCompanyInfrastructureWindows(c->index);
01809           }
01810         }
01811 
01812         MakeDriveThroughRoadStop(cur_tile, st->owner, road_owner, tram_owner, st->index, rs_type, rts | cur_rts, DiagDirToAxis(ddir));
01813         road_stop->MakeDriveThrough();
01814       } else {
01815         /* Non-drive-through stop never overbuild and always count as two road bits. */
01816         Company::Get(st->owner)->infrastructure.road[FIND_FIRST_BIT(rts)] += 2;
01817         MakeRoadStop(cur_tile, st->owner, st->index, rs_type, rts, ddir);
01818       }
01819       Company::Get(st->owner)->infrastructure.station++;
01820       DirtyCompanyInfrastructureWindows(st->owner);
01821 
01822       MarkTileDirtyByTile(cur_tile);
01823     }
01824   }
01825 
01826   if (st != NULL) {
01827     st->UpdateVirtCoord();
01828     UpdateStationAcceptance(st, false);
01829     st->RecomputeIndustriesNear();
01830     InvalidateWindowData(WC_SELECT_STATION, 0, 0);
01831     InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
01832     SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_ROADVEHS);
01833   }
01834   return cost;
01835 }
01836 
01837 
01838 static Vehicle *ClearRoadStopStatusEnum(Vehicle *v, void *)
01839 {
01840   if (v->type == VEH_ROAD) {
01841     /* Okay... we are a road vehicle on a drive through road stop.
01842      * But that road stop has just been removed, so we need to make
01843      * sure we are in a valid state... however, vehicles can also
01844      * turn on road stop tiles, so only clear the 'road stop' state
01845      * bits and only when the state was 'in road stop', otherwise
01846      * we'll end up clearing the turn around bits. */
01847     RoadVehicle *rv = RoadVehicle::From(v);
01848     if (HasBit(rv->state, RVS_IN_DT_ROAD_STOP)) rv->state &= RVSB_ROAD_STOP_TRACKDIR_MASK;
01849   }
01850 
01851   return NULL;
01852 }
01853 
01854 
01861 static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags)
01862 {
01863   Station *st = Station::GetByTile(tile);
01864 
01865   if (_current_company != OWNER_WATER) {
01866     CommandCost ret = CheckOwnership(st->owner);
01867     if (ret.Failed()) return ret;
01868   }
01869 
01870   bool is_truck = IsTruckStop(tile);
01871 
01872   RoadStop **primary_stop;
01873   RoadStop *cur_stop;
01874   if (is_truck) { // truck stop
01875     primary_stop = &st->truck_stops;
01876     cur_stop = RoadStop::GetByTile(tile, ROADSTOP_TRUCK);
01877   } else {
01878     primary_stop = &st->bus_stops;
01879     cur_stop = RoadStop::GetByTile(tile, ROADSTOP_BUS);
01880   }
01881 
01882   assert(cur_stop != NULL);
01883 
01884   /* don't do the check for drive-through road stops when company bankrupts */
01885   if (IsDriveThroughStopTile(tile) && (flags & DC_BANKRUPT)) {
01886     /* remove the 'going through road stop' status from all vehicles on that tile */
01887     if (flags & DC_EXEC) FindVehicleOnPos(tile, NULL, &ClearRoadStopStatusEnum);
01888   } else {
01889     CommandCost ret = EnsureNoVehicleOnGround(tile);
01890     if (ret.Failed()) return ret;
01891   }
01892 
01893   if (flags & DC_EXEC) {
01894     if (*primary_stop == cur_stop) {
01895       /* removed the first stop in the list */
01896       *primary_stop = cur_stop->next;
01897       /* removed the only stop? */
01898       if (*primary_stop == NULL) {
01899         st->facilities &= (is_truck ? ~FACIL_TRUCK_STOP : ~FACIL_BUS_STOP);
01900       }
01901     } else {
01902       /* tell the predecessor in the list to skip this stop */
01903       RoadStop *pred = *primary_stop;
01904       while (pred->next != cur_stop) pred = pred->next;
01905       pred->next = cur_stop->next;
01906     }
01907 
01908     /* Update company infrastructure counts. */
01909     RoadType rt;
01910     FOR_EACH_SET_ROADTYPE(rt, GetRoadTypes(tile)) {
01911       Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
01912       if (c != NULL) {
01913         c->infrastructure.road[rt] -= 2;
01914         DirtyCompanyInfrastructureWindows(c->index);
01915       }
01916     }
01917     Company::Get(st->owner)->infrastructure.station--;
01918 
01919     if (IsDriveThroughStopTile(tile)) {
01920       /* Clears the tile for us */
01921       cur_stop->ClearDriveThrough();
01922     } else {
01923       DoClearSquare(tile);
01924     }
01925 
01926     SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_ROADVEHS);
01927     delete cur_stop;
01928 
01929     /* Make sure no vehicle is going to the old roadstop */
01930     RoadVehicle *v;
01931     FOR_ALL_ROADVEHICLES(v) {
01932       if (v->First() == v && v->current_order.IsType(OT_GOTO_STATION) &&
01933           v->dest_tile == tile) {
01934         v->dest_tile = v->GetOrderStationLocation(st->index);
01935       }
01936     }
01937 
01938     st->rect.AfterRemoveTile(st, tile);
01939 
01940     st->UpdateVirtCoord();
01941     st->RecomputeIndustriesNear();
01942     DeleteStationIfEmpty(st);
01943 
01944     /* Update the tile area of the truck/bus stop */
01945     if (is_truck) {
01946       st->truck_station.Clear();
01947       for (const RoadStop *rs = st->truck_stops; rs != NULL; rs = rs->next) st->truck_station.Add(rs->xy);
01948     } else {
01949       st->bus_station.Clear();
01950       for (const RoadStop *rs = st->bus_stops; rs != NULL; rs = rs->next) st->bus_station.Add(rs->xy);
01951     }
01952   }
01953 
01954   return CommandCost(EXPENSES_CONSTRUCTION, _price[is_truck ? PR_CLEAR_STATION_TRUCK : PR_CLEAR_STATION_BUS]);
01955 }
01956 
01967 CommandCost CmdRemoveRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01968 {
01969   uint8 width = (uint8)GB(p1, 0, 8);
01970   uint8 height = (uint8)GB(p1, 8, 8);
01971 
01972   /* Check for incorrect width / height. */
01973   if (width == 0 || height == 0) return CMD_ERROR;
01974   /* Check if the first tile and the last tile are valid */
01975   if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, height - 1) == INVALID_TILE) return CMD_ERROR;
01976 
01977   TileArea roadstop_area(tile, width, height);
01978 
01979   int quantity = 0;
01980   CommandCost cost(EXPENSES_CONSTRUCTION);
01981   TILE_AREA_LOOP(cur_tile, roadstop_area) {
01982     /* Make sure the specified tile is a road stop of the correct type */
01983     if (!IsTileType(cur_tile, MP_STATION) || !IsRoadStop(cur_tile) || (uint32)GetRoadStopType(cur_tile) != GB(p2, 0, 1)) continue;
01984 
01985     /* Save the stop info before it is removed */
01986     bool is_drive_through = IsDriveThroughStopTile(cur_tile);
01987     RoadTypes rts = GetRoadTypes(cur_tile);
01988     RoadBits road_bits = IsDriveThroughStopTile(cur_tile) ?
01989         ((GetRoadStopDir(cur_tile) == DIAGDIR_NE) ? ROAD_X : ROAD_Y) :
01990         DiagDirToRoadBits(GetRoadStopDir(cur_tile));
01991 
01992     Owner road_owner = GetRoadOwner(cur_tile, ROADTYPE_ROAD);
01993     Owner tram_owner = GetRoadOwner(cur_tile, ROADTYPE_TRAM);
01994     CommandCost ret = RemoveRoadStop(cur_tile, flags);
01995     if (ret.Failed()) return ret;
01996     cost.AddCost(ret);
01997 
01998     quantity++;
01999     /* If the stop was a drive-through stop replace the road */
02000     if ((flags & DC_EXEC) && is_drive_through) {
02001       MakeRoadNormal(cur_tile, road_bits, rts, ClosestTownFromTile(cur_tile, UINT_MAX)->index,
02002           road_owner, tram_owner);
02003 
02004       /* Update company infrastructure counts. */
02005       RoadType rt;
02006       FOR_EACH_SET_ROADTYPE(rt, rts) {
02007         Company *c = Company::GetIfValid(GetRoadOwner(cur_tile, rt));
02008         if (c != NULL) {
02009           c->infrastructure.road[rt] += CountBits(road_bits);
02010           DirtyCompanyInfrastructureWindows(c->index);
02011         }
02012       }
02013     }
02014   }
02015 
02016   if (quantity == 0) return_cmd_error(STR_ERROR_THERE_IS_NO_STATION);
02017 
02018   return cost;
02019 }
02020 
02027 static uint GetMinimalAirportDistanceToTile(TileIterator &it, TileIndex town_tile)
02028 {
02029   uint mindist = UINT_MAX;
02030 
02031   for (TileIndex cur_tile = it; cur_tile != INVALID_TILE; cur_tile = ++it) {
02032     mindist = min(mindist, DistanceManhattan(town_tile, cur_tile));
02033   }
02034 
02035   return mindist;
02036 }
02037 
02047 uint8 GetAirportNoiseLevelForTown(const AirportSpec *as, TileIterator &it, TileIndex town_tile)
02048 {
02049   /* 0 cannot be accounted, and 1 is the lowest that can be reduced from town.
02050    * So no need to go any further*/
02051   if (as->noise_level < 2) return as->noise_level;
02052 
02053   uint distance = GetMinimalAirportDistanceToTile(it, town_tile);
02054 
02055   /* The steps for measuring noise reduction are based on the "magical" (and arbitrary) 8 base distance
02056    * adding the town_council_tolerance 4 times, as a way to graduate, depending of the tolerance.
02057    * Basically, it says that the less tolerant a town is, the bigger the distance before
02058    * an actual decrease can be granted */
02059   uint8 town_tolerance_distance = 8 + (_settings_game.difficulty.town_council_tolerance * 4);
02060 
02061   /* now, we want to have the distance segmented using the distance judged bareable by town
02062    * This will give us the coefficient of reduction the distance provides. */
02063   uint noise_reduction = distance / town_tolerance_distance;
02064 
02065   /* If the noise reduction equals the airport noise itself, don't give it for free.
02066    * Otherwise, simply reduce the airport's level. */
02067   return noise_reduction >= as->noise_level ? 1 : as->noise_level - noise_reduction;
02068 }
02069 
02077 Town *AirportGetNearestTown(const AirportSpec *as, const TileIterator &it)
02078 {
02079   Town *t, *nearest = NULL;
02080   uint add = as->size_x + as->size_y - 2; // GetMinimalAirportDistanceToTile can differ from DistanceManhattan by this much
02081   uint mindist = UINT_MAX - add; // prevent overflow
02082   FOR_ALL_TOWNS(t) {
02083     if (DistanceManhattan(t->xy, it) < mindist + add) { // avoid calling GetMinimalAirportDistanceToTile too often
02084       TileIterator *copy = it.Clone();
02085       uint dist = GetMinimalAirportDistanceToTile(*copy, t->xy);
02086       delete copy;
02087       if (dist < mindist) {
02088         nearest = t;
02089         mindist = dist;
02090       }
02091     }
02092   }
02093 
02094   return nearest;
02095 }
02096 
02097 
02099 void UpdateAirportsNoise()
02100 {
02101   Town *t;
02102   const Station *st;
02103 
02104   FOR_ALL_TOWNS(t) t->noise_reached = 0;
02105 
02106   FOR_ALL_STATIONS(st) {
02107     if (st->airport.tile != INVALID_TILE && st->airport.type != AT_OILRIG) {
02108       const AirportSpec *as = st->airport.GetSpec();
02109       AirportTileIterator it(st);
02110       Town *nearest = AirportGetNearestTown(as, it);
02111       nearest->noise_reached += GetAirportNoiseLevelForTown(as, it, nearest->xy);
02112     }
02113   }
02114 }
02115 
02129 CommandCost CmdBuildAirport(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02130 {
02131   StationID station_to_join = GB(p2, 16, 16);
02132   bool reuse = (station_to_join != NEW_STATION);
02133   if (!reuse) station_to_join = INVALID_STATION;
02134   bool distant_join = (station_to_join != INVALID_STATION);
02135   byte airport_type = GB(p1, 0, 8);
02136   byte layout = GB(p1, 8, 8);
02137 
02138   if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
02139 
02140   if (airport_type >= NUM_AIRPORTS) return CMD_ERROR;
02141 
02142   CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
02143   if (ret.Failed()) return ret;
02144 
02145   /* Check if a valid, buildable airport was chosen for construction */
02146   const AirportSpec *as = AirportSpec::Get(airport_type);
02147   if (!as->IsAvailable() || layout >= as->num_table) return CMD_ERROR;
02148 
02149   Direction rotation = as->rotation[layout];
02150   Town *t = ClosestTownFromTile(tile, UINT_MAX);
02151   int w = as->size_x;
02152   int h = as->size_y;
02153   if (rotation == DIR_E || rotation == DIR_W) Swap(w, h);
02154 
02155   if (w > _settings_game.station.station_spread || h > _settings_game.station.station_spread) {
02156     return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
02157   }
02158 
02159   CommandCost cost = CheckFlatLand(TileArea(tile, w, h), flags);
02160   if (cost.Failed()) return cost;
02161 
02162   /* The noise level is the noise from the airport and reduce it to account for the distance to the town center. */
02163   AirportTileTableIterator iter(as->table[layout], tile);
02164   Town *nearest = AirportGetNearestTown(as, iter);
02165   uint newnoise_level = GetAirportNoiseLevelForTown(as, iter, nearest->xy);
02166 
02167   /* Check if local auth would allow a new airport */
02168   StringID authority_refuse_message = STR_NULL;
02169 
02170   if (_settings_game.economy.station_noise_level) {
02171     /* do not allow to build a new airport if this raise the town noise over the maximum allowed by town */
02172     if ((nearest->noise_reached + newnoise_level) > nearest->MaxTownNoise()) {
02173       authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_NOISE;
02174     }
02175   } else {
02176     uint num = 0;
02177     const Station *st;
02178     FOR_ALL_STATIONS(st) {
02179       if (st->town == t && (st->facilities & FACIL_AIRPORT) && st->airport.type != AT_OILRIG) num++;
02180     }
02181     if (num >= 2) {
02182       authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_AIRPORT;
02183     }
02184   }
02185 
02186   if (authority_refuse_message != STR_NULL) {
02187     SetDParam(0, t->index);
02188     return_cmd_error(authority_refuse_message);
02189   }
02190 
02191   Station *st = NULL;
02192   ret = FindJoiningStation(INVALID_STATION, station_to_join, HasBit(p2, 0), TileArea(tile, w, h), &st);
02193   if (ret.Failed()) return ret;
02194 
02195   /* Distant join */
02196   if (st == NULL && distant_join) st = Station::GetIfValid(station_to_join);
02197 
02198   /* Find a deleted station close to us */
02199   if (st == NULL && reuse) st = GetClosestDeletedStation(tile);
02200 
02201   if (st != NULL) {
02202     if (st->owner != _current_company) {
02203       return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_STATION);
02204     }
02205 
02206     CommandCost ret = st->rect.BeforeAddRect(tile, w, h, StationRect::ADD_TEST);
02207     if (ret.Failed()) return ret;
02208 
02209     if (st->airport.tile != INVALID_TILE) {
02210       return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_AIRPORT);
02211     }
02212   } else {
02213     /* allocate and initialize new station */
02214     if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
02215 
02216     if (flags & DC_EXEC) {
02217       st = new Station(tile);
02218 
02219       st->town = t;
02220       st->string_id = GenerateStationName(st, tile, !(GetAirport(airport_type)->flags & AirportFTAClass::AIRPLANES) ? STATIONNAMING_HELIPORT : STATIONNAMING_AIRPORT);
02221 
02222       if (Company::IsValidID(_current_company)) {
02223         SetBit(st->town->have_ratings, _current_company);
02224       }
02225     }
02226   }
02227 
02228   for (AirportTileTableIterator iter(as->table[layout], tile); iter != INVALID_TILE; ++iter) {
02229     cost.AddCost(_price[PR_BUILD_STATION_AIRPORT]);
02230   }
02231 
02232   if (flags & DC_EXEC) {
02233     /* Always add the noise, so there will be no need to recalculate when option toggles */
02234     nearest->noise_reached += newnoise_level;
02235 
02236     st->AddFacility(FACIL_AIRPORT, tile);
02237     st->airport.type = airport_type;
02238     st->airport.layout = layout;
02239     st->airport.flags = 0;
02240     st->airport.rotation = rotation;
02241 
02242     st->rect.BeforeAddRect(tile, w, h, StationRect::ADD_TRY);
02243 
02244     for (AirportTileTableIterator iter(as->table[layout], tile); iter != INVALID_TILE; ++iter) {
02245       MakeAirport(iter, st->owner, st->index, iter.GetStationGfx(), WATER_CLASS_INVALID);
02246       SetStationTileRandomBits(iter, GB(Random(), 0, 4));
02247       st->airport.Add(iter);
02248 
02249       if (AirportTileSpec::Get(GetTranslatedAirportTileID(iter.GetStationGfx()))->animation.status != ANIM_STATUS_NO_ANIMATION) AddAnimatedTile(iter);
02250     }
02251 
02252     /* Only call the animation trigger after all tiles have been built */
02253     for (AirportTileTableIterator iter(as->table[layout], tile); iter != INVALID_TILE; ++iter) {
02254       AirportTileAnimationTrigger(st, iter, AAT_BUILT);
02255     }
02256 
02257     UpdateAirplanesOnNewStation(st);
02258 
02259     Company::Get(st->owner)->infrastructure.airport++;
02260     DirtyCompanyInfrastructureWindows(st->owner);
02261 
02262     st->UpdateVirtCoord();
02263     UpdateStationAcceptance(st, false);
02264     st->RecomputeIndustriesNear();
02265     InvalidateWindowData(WC_SELECT_STATION, 0, 0);
02266     InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
02267     SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_PLANES);
02268 
02269     if (_settings_game.economy.station_noise_level) {
02270       SetWindowDirty(WC_TOWN_VIEW, st->town->index);
02271     }
02272   }
02273 
02274   return cost;
02275 }
02276 
02283 static CommandCost RemoveAirport(TileIndex tile, DoCommandFlag flags)
02284 {
02285   Station *st = Station::GetByTile(tile);
02286 
02287   if (_current_company != OWNER_WATER) {
02288     CommandCost ret = CheckOwnership(st->owner);
02289     if (ret.Failed()) return ret;
02290   }
02291 
02292   tile = st->airport.tile;
02293 
02294   CommandCost cost(EXPENSES_CONSTRUCTION);
02295 
02296   const Aircraft *a;
02297   FOR_ALL_AIRCRAFT(a) {
02298     if (!a->IsNormalAircraft()) continue;
02299     if (a->targetairport == st->index && a->state != FLYING) return CMD_ERROR;
02300   }
02301 
02302   if (flags & DC_EXEC) {
02303     const AirportSpec *as = st->airport.GetSpec();
02304     /* The noise level is the noise from the airport and reduce it to account for the distance to the town center.
02305      * And as for construction, always remove it, even if the setting is not set, in order to avoid the
02306      * need of recalculation */
02307     AirportTileIterator it(st);
02308     Town *nearest = AirportGetNearestTown(as, it);
02309     nearest->noise_reached -= GetAirportNoiseLevelForTown(as, it, nearest->xy);
02310   }
02311 
02312   TILE_AREA_LOOP(tile_cur, st->airport) {
02313     if (!st->TileBelongsToAirport(tile_cur)) continue;
02314 
02315     CommandCost ret = EnsureNoVehicleOnGround(tile_cur);
02316     if (ret.Failed()) return ret;
02317 
02318     cost.AddCost(_price[PR_CLEAR_STATION_AIRPORT]);
02319 
02320     if (flags & DC_EXEC) {
02321       if (IsHangarTile(tile_cur)) OrderBackup::Reset(tile_cur, false);
02322       DeleteAnimatedTile(tile_cur);
02323       DoClearSquare(tile_cur);
02324       DeleteNewGRFInspectWindow(GSF_AIRPORTTILES, tile_cur);
02325     }
02326   }
02327 
02328   if (flags & DC_EXEC) {
02329     /* Clear the persistent storage. */
02330     delete st->airport.psa;
02331 
02332     for (uint i = 0; i < st->airport.GetNumHangars(); ++i) {
02333       DeleteWindowById(
02334         WC_VEHICLE_DEPOT, st->airport.GetHangarTile(i)
02335       );
02336     }
02337 
02338     st->rect.AfterRemoveRect(st, st->airport);
02339 
02340     st->airport.Clear();
02341     st->facilities &= ~FACIL_AIRPORT;
02342 
02343     SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_PLANES);
02344 
02345     if (_settings_game.economy.station_noise_level) {
02346       SetWindowDirty(WC_TOWN_VIEW, st->town->index);
02347     }
02348 
02349     Company::Get(st->owner)->infrastructure.airport--;
02350     DirtyCompanyInfrastructureWindows(st->owner);
02351 
02352     st->UpdateVirtCoord();
02353     st->RecomputeIndustriesNear();
02354     DeleteStationIfEmpty(st);
02355     DeleteNewGRFInspectWindow(GSF_AIRPORTS, st->index);
02356   }
02357 
02358   return cost;
02359 }
02360 
02367 bool HasStationInUse(StationID station, bool include_company, CompanyID company)
02368 {
02369   const Vehicle *v;
02370   FOR_ALL_VEHICLES(v) {
02371     if ((v->owner == company) == include_company) {
02372       const Order *order;
02373       FOR_VEHICLE_ORDERS(v, order) {
02374         if ((order->IsType(OT_GOTO_STATION) || order->IsType(OT_GOTO_WAYPOINT)) && order->GetDestination() == station) {
02375           return true;
02376         }
02377       }
02378     }
02379   }
02380   return false;
02381 }
02382 
02383 static const TileIndexDiffC _dock_tileoffs_chkaround[] = {
02384   {-1,  0},
02385   { 0,  0},
02386   { 0,  0},
02387   { 0, -1}
02388 };
02389 static const byte _dock_w_chk[4] = { 2, 1, 2, 1 };
02390 static const byte _dock_h_chk[4] = { 1, 2, 1, 2 };
02391 
02401 CommandCost CmdBuildDock(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02402 {
02403   StationID station_to_join = GB(p2, 16, 16);
02404   bool reuse = (station_to_join != NEW_STATION);
02405   if (!reuse) station_to_join = INVALID_STATION;
02406   bool distant_join = (station_to_join != INVALID_STATION);
02407 
02408   if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
02409 
02410   DiagDirection direction = GetInclinedSlopeDirection(GetTileSlope(tile));
02411   if (direction == INVALID_DIAGDIR) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
02412   direction = ReverseDiagDir(direction);
02413 
02414   /* Docks cannot be placed on rapids */
02415   if (HasTileWaterGround(tile)) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
02416 
02417   CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
02418   if (ret.Failed()) return ret;
02419 
02420   if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
02421 
02422   ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
02423   if (ret.Failed()) return ret;
02424 
02425   TileIndex tile_cur = tile + TileOffsByDiagDir(direction);
02426 
02427   if (!IsTileType(tile_cur, MP_WATER) || GetTileSlope(tile_cur) != SLOPE_FLAT) {
02428     return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
02429   }
02430 
02431   if (MayHaveBridgeAbove(tile_cur) && IsBridgeAbove(tile_cur)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
02432 
02433   /* Get the water class of the water tile before it is cleared.*/
02434   WaterClass wc = GetWaterClass(tile_cur);
02435 
02436   ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
02437   if (ret.Failed()) return ret;
02438 
02439   tile_cur += TileOffsByDiagDir(direction);
02440   if (!IsTileType(tile_cur, MP_WATER) || GetTileSlope(tile_cur) != SLOPE_FLAT) {
02441     return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
02442   }
02443 
02444   /* middle */
02445   Station *st = NULL;
02446   ret = FindJoiningStation(INVALID_STATION, station_to_join, HasBit(p1, 0),
02447       TileArea(tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
02448           _dock_w_chk[direction], _dock_h_chk[direction]), &st);
02449   if (ret.Failed()) return ret;
02450 
02451   /* Distant join */
02452   if (st == NULL && distant_join) st = Station::GetIfValid(station_to_join);
02453 
02454   /* Find a deleted station close to us */
02455   if (st == NULL && reuse) st = GetClosestDeletedStation(tile);
02456 
02457   if (st != NULL) {
02458     if (st->owner != _current_company) {
02459       return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_STATION);
02460     }
02461 
02462     CommandCost ret = st->rect.BeforeAddRect(
02463         tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
02464         _dock_w_chk[direction], _dock_h_chk[direction], StationRect::ADD_TEST);
02465     if (ret.Failed()) return ret;
02466 
02467     if (st->dock_tile != INVALID_TILE) return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_DOCK);
02468   } else {
02469     /* allocate and initialize new station */
02470     if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
02471 
02472     if (flags & DC_EXEC) {
02473       st = new Station(tile);
02474 
02475       st->town = ClosestTownFromTile(tile, UINT_MAX);
02476       st->string_id = GenerateStationName(st, tile, STATIONNAMING_DOCK);
02477 
02478       if (Company::IsValidID(_current_company)) {
02479         SetBit(st->town->have_ratings, _current_company);
02480       }
02481     }
02482   }
02483 
02484   if (flags & DC_EXEC) {
02485     st->dock_tile = tile;
02486     st->AddFacility(FACIL_DOCK, tile);
02487 
02488     st->rect.BeforeAddRect(
02489         tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
02490         _dock_w_chk[direction], _dock_h_chk[direction], StationRect::ADD_TRY);
02491 
02492     /* If the water part of the dock is on a canal, update infrastructure counts.
02493      * This is needed as we've unconditionally cleared that tile before. */
02494     if (wc == WATER_CLASS_CANAL) {
02495       Company::Get(st->owner)->infrastructure.water++;
02496     }
02497     Company::Get(st->owner)->infrastructure.station += 2;
02498     DirtyCompanyInfrastructureWindows(st->owner);
02499 
02500     MakeDock(tile, st->owner, st->index, direction, wc);
02501 
02502     st->UpdateVirtCoord();
02503     UpdateStationAcceptance(st, false);
02504     st->RecomputeIndustriesNear();
02505     InvalidateWindowData(WC_SELECT_STATION, 0, 0);
02506     InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
02507     SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_SHIPS);
02508   }
02509 
02510   return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_STATION_DOCK]);
02511 }
02512 
02519 static CommandCost RemoveDock(TileIndex tile, DoCommandFlag flags)
02520 {
02521   Station *st = Station::GetByTile(tile);
02522   CommandCost ret = CheckOwnership(st->owner);
02523   if (ret.Failed()) return ret;
02524 
02525   TileIndex docking_location = TILE_ADD(st->dock_tile, ToTileIndexDiff(GetDockOffset(st->dock_tile)));
02526 
02527   TileIndex tile1 = st->dock_tile;
02528   TileIndex tile2 = tile1 + TileOffsByDiagDir(GetDockDirection(tile1));
02529 
02530   ret = EnsureNoVehicleOnGround(tile1);
02531   if (ret.Succeeded()) ret = EnsureNoVehicleOnGround(tile2);
02532   if (ret.Failed()) return ret;
02533 
02534   if (flags & DC_EXEC) {
02535     DoClearSquare(tile1);
02536     MarkTileDirtyByTile(tile1);
02537     MakeWaterKeepingClass(tile2, st->owner);
02538 
02539     st->rect.AfterRemoveTile(st, tile1);
02540     st->rect.AfterRemoveTile(st, tile2);
02541 
02542     st->dock_tile = INVALID_TILE;
02543     st->facilities &= ~FACIL_DOCK;
02544 
02545     Company::Get(st->owner)->infrastructure.station -= 2;
02546     DirtyCompanyInfrastructureWindows(st->owner);
02547 
02548     SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_SHIPS);
02549     st->UpdateVirtCoord();
02550     st->RecomputeIndustriesNear();
02551     DeleteStationIfEmpty(st);
02552 
02553     /* All ships that were going to our station, can't go to it anymore.
02554      * Just clear the order, then automatically the next appropriate order
02555      * will be selected and in case of no appropriate order it will just
02556      * wander around the world. */
02557     Ship *s;
02558     FOR_ALL_SHIPS(s) {
02559       if (s->current_order.IsType(OT_LOADING) && s->tile == docking_location) {
02560         s->LeaveStation();
02561       }
02562 
02563       if (s->dest_tile == docking_location) {
02564         s->dest_tile = 0;
02565         s->current_order.Free();
02566       }
02567     }
02568   }
02569 
02570   return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_STATION_DOCK]);
02571 }
02572 
02573 #include "table/station_land.h"
02574 
02575 const DrawTileSprites *GetStationTileLayout(StationType st, byte gfx)
02576 {
02577   return &_station_display_datas[st][gfx];
02578 }
02579 
02580 static void DrawTile_Station(TileInfo *ti)
02581 {
02582   const NewGRFSpriteLayout *layout = NULL;
02583   DrawTileSprites tmp_rail_layout;
02584   const DrawTileSprites *t = NULL;
02585   RoadTypes roadtypes;
02586   int32 total_offset;
02587   const RailtypeInfo *rti = NULL;
02588   uint32 relocation = 0;
02589   uint32 ground_relocation = 0;
02590   BaseStation *st = NULL;
02591   const StationSpec *statspec = NULL;
02592   uint tile_layout = 0;
02593 
02594   if (HasStationRail(ti->tile)) {
02595     rti = GetRailTypeInfo(GetRailType(ti->tile));
02596     roadtypes = ROADTYPES_NONE;
02597     total_offset = rti->GetRailtypeSpriteOffset();
02598 
02599     if (IsCustomStationSpecIndex(ti->tile)) {
02600       /* look for customization */
02601       st = BaseStation::GetByTile(ti->tile);
02602       statspec = st->speclist[GetCustomStationSpecIndex(ti->tile)].spec;
02603 
02604       if (statspec != NULL) {
02605         tile_layout = GetStationGfx(ti->tile);
02606 
02607         if (HasBit(statspec->callback_mask, CBM_STATION_SPRITE_LAYOUT)) {
02608           uint16 callback = GetStationCallback(CBID_STATION_SPRITE_LAYOUT, 0, 0, statspec, st, ti->tile);
02609           if (callback != CALLBACK_FAILED) tile_layout = (callback & ~1) + GetRailStationAxis(ti->tile);
02610         }
02611 
02612         /* Ensure the chosen tile layout is valid for this custom station */
02613         if (statspec->renderdata != NULL) {
02614           layout = &statspec->renderdata[tile_layout < statspec->tiles ? tile_layout : (uint)GetRailStationAxis(ti->tile)];
02615           if (!layout->NeedsPreprocessing()) {
02616             t = layout;
02617             layout = NULL;
02618           }
02619         }
02620       }
02621     }
02622   } else {
02623     roadtypes = IsRoadStop(ti->tile) ? GetRoadTypes(ti->tile) : ROADTYPES_NONE;
02624     total_offset = 0;
02625   }
02626 
02627   StationGfx gfx = GetStationGfx(ti->tile);
02628   if (IsAirport(ti->tile)) {
02629     gfx = GetAirportGfx(ti->tile);
02630     if (gfx >= NEW_AIRPORTTILE_OFFSET) {
02631       const AirportTileSpec *ats = AirportTileSpec::Get(gfx);
02632       if (ats->grf_prop.spritegroup[0] != NULL && DrawNewAirportTile(ti, Station::GetByTile(ti->tile), gfx, ats)) {
02633         return;
02634       }
02635       /* No sprite group (or no valid one) found, meaning no graphics associated.
02636        * Use the substitute one instead */
02637       assert(ats->grf_prop.subst_id != INVALID_AIRPORTTILE);
02638       gfx = ats->grf_prop.subst_id;
02639     }
02640     switch (gfx) {
02641       case APT_RADAR_GRASS_FENCE_SW:
02642         t = &_station_display_datas_airport_radar_grass_fence_sw[GetAnimationFrame(ti->tile)];
02643         break;
02644       case APT_GRASS_FENCE_NE_FLAG:
02645         t = &_station_display_datas_airport_flag_grass_fence_ne[GetAnimationFrame(ti->tile)];
02646         break;
02647       case APT_RADAR_FENCE_SW:
02648         t = &_station_display_datas_airport_radar_fence_sw[GetAnimationFrame(ti->tile)];
02649         break;
02650       case APT_RADAR_FENCE_NE:
02651         t = &_station_display_datas_airport_radar_fence_ne[GetAnimationFrame(ti->tile)];
02652         break;
02653       case APT_GRASS_FENCE_NE_FLAG_2:
02654         t = &_station_display_datas_airport_flag_grass_fence_ne_2[GetAnimationFrame(ti->tile)];
02655         break;
02656     }
02657   }
02658 
02659   Owner owner = GetTileOwner(ti->tile);
02660 
02661   PaletteID palette;
02662   if (Company::IsValidID(owner)) {
02663     palette = COMPANY_SPRITE_COLOUR(owner);
02664   } else {
02665     /* Some stations are not owner by a company, namely oil rigs */
02666     palette = PALETTE_TO_GREY;
02667   }
02668 
02669   if (layout == NULL && (t == NULL || t->seq == NULL)) t = GetStationTileLayout(GetStationType(ti->tile), gfx);
02670 
02671   /* don't show foundation for docks */
02672   if (ti->tileh != SLOPE_FLAT && !IsDock(ti->tile)) {
02673     if (statspec != NULL && HasBit(statspec->flags, SSF_CUSTOM_FOUNDATIONS)) {
02674       /* Station has custom foundations.
02675        * Check whether the foundation continues beyond the tile's upper sides. */
02676       uint edge_info = 0;
02677       int z;
02678       Slope slope = GetFoundationPixelSlope(ti->tile, &z);
02679       if (!HasFoundationNW(ti->tile, slope, z)) SetBit(edge_info, 0);
02680       if (!HasFoundationNE(ti->tile, slope, z)) SetBit(edge_info, 1);
02681       SpriteID image = GetCustomStationFoundationRelocation(statspec, st, ti->tile, tile_layout, edge_info);
02682 
02683       if (HasBit(statspec->flags, SSF_EXTENDED_FOUNDATIONS)) {
02684         /* Station provides extended foundations. */
02685 
02686         static const uint8 foundation_parts[] = {
02687           0, 0, 0, 0, // Invalid,  Invalid,   Invalid,   SLOPE_SW
02688           0, 1, 2, 3, // Invalid,  SLOPE_EW,  SLOPE_SE,  SLOPE_WSE
02689           0, 4, 5, 6, // Invalid,  SLOPE_NW,  SLOPE_NS,  SLOPE_NWS
02690           7, 8, 9     // SLOPE_NE, SLOPE_ENW, SLOPE_SEN
02691         };
02692 
02693         AddSortableSpriteToDraw(image + foundation_parts[ti->tileh], PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
02694       } else {
02695         /* Draw simple foundations, built up from 8 possible foundation sprites. */
02696 
02697         /* Each set bit represents one of the eight composite sprites to be drawn.
02698          * 'Invalid' entries will not drawn but are included for completeness. */
02699         static const uint8 composite_foundation_parts[] = {
02700           /* Invalid  (00000000), Invalid   (11010001), Invalid   (11100100), SLOPE_SW  (11100000) */
02701              0x00,                0xD1,                 0xE4,                 0xE0,
02702           /* Invalid  (11001010), SLOPE_EW  (11001001), SLOPE_SE  (11000100), SLOPE_WSE (11000000) */
02703              0xCA,                0xC9,                 0xC4,                 0xC0,
02704           /* Invalid  (11010010), SLOPE_NW  (10010001), SLOPE_NS  (11100100), SLOPE_NWS (10100000) */
02705              0xD2,                0x91,                 0xE4,                 0xA0,
02706           /* SLOPE_NE (01001010), SLOPE_ENW (00001001), SLOPE_SEN (01000100) */
02707              0x4A,                0x09,                 0x44
02708         };
02709 
02710         uint8 parts = composite_foundation_parts[ti->tileh];
02711 
02712         /* If foundations continue beyond the tile's upper sides then
02713          * mask out the last two pieces. */
02714         if (HasBit(edge_info, 0)) ClrBit(parts, 6);
02715         if (HasBit(edge_info, 1)) ClrBit(parts, 7);
02716 
02717         if (parts == 0) {
02718           /* We always have to draw at least one sprite to make sure there is a boundingbox and a sprite with the
02719            * correct offset for the childsprites.
02720            * So, draw the (completely empty) sprite of the default foundations. */
02721           goto draw_default_foundation;
02722         }
02723 
02724         StartSpriteCombine();
02725         for (int i = 0; i < 8; i++) {
02726           if (HasBit(parts, i)) {
02727             AddSortableSpriteToDraw(image + i, PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
02728           }
02729         }
02730         EndSpriteCombine();
02731       }
02732 
02733       OffsetGroundSprite(31, 1);
02734       ti->z += ApplyPixelFoundationToSlope(FOUNDATION_LEVELED, &ti->tileh);
02735     } else {
02736 draw_default_foundation:
02737       DrawFoundation(ti, FOUNDATION_LEVELED);
02738     }
02739   }
02740 
02741   if (IsBuoy(ti->tile)) {
02742     DrawWaterClassGround(ti);
02743     SpriteID sprite = GetCanalSprite(CF_BUOY, ti->tile);
02744     if (sprite != 0) total_offset = sprite - SPR_IMG_BUOY;
02745   } else if (IsDock(ti->tile) || (IsOilRig(ti->tile) && IsTileOnWater(ti->tile))) {
02746     if (ti->tileh == SLOPE_FLAT) {
02747       DrawWaterClassGround(ti);
02748     } else {
02749       assert(IsDock(ti->tile));
02750       TileIndex water_tile = ti->tile + TileOffsByDiagDir(GetDockDirection(ti->tile));
02751       WaterClass wc = GetWaterClass(water_tile);
02752       if (wc == WATER_CLASS_SEA) {
02753         DrawShoreTile(ti->tileh);
02754       } else {
02755         DrawClearLandTile(ti, 3);
02756       }
02757     }
02758   } else {
02759     if (layout != NULL) {
02760       /* Sprite layout which needs preprocessing */
02761       bool separate_ground = HasBit(statspec->flags, SSF_SEPARATE_GROUND);
02762       uint32 var10_values = layout->PrepareLayout(total_offset, rti->fallback_railtype, 0, 0, separate_ground);
02763       uint8 var10;
02764       FOR_EACH_SET_BIT(var10, var10_values) {
02765         uint32 var10_relocation = GetCustomStationRelocation(statspec, st, ti->tile, var10);
02766         layout->ProcessRegisters(var10, var10_relocation, separate_ground);
02767       }
02768       tmp_rail_layout.seq = layout->GetLayout(&tmp_rail_layout.ground);
02769       t = &tmp_rail_layout;
02770       total_offset = 0;
02771     } else if (statspec != NULL) {
02772       /* Simple sprite layout */
02773       ground_relocation = relocation = GetCustomStationRelocation(statspec, st, ti->tile, 0);
02774       if (HasBit(statspec->flags, SSF_SEPARATE_GROUND)) {
02775         ground_relocation = GetCustomStationRelocation(statspec, st, ti->tile, 1);
02776       }
02777       ground_relocation += rti->fallback_railtype;
02778     }
02779 
02780     SpriteID image = t->ground.sprite;
02781     PaletteID pal  = t->ground.pal;
02782     if (rti != NULL && rti->UsesOverlay() && (image == SPR_RAIL_TRACK_X || image == SPR_RAIL_TRACK_Y)) {
02783       SpriteID ground = GetCustomRailSprite(rti, ti->tile, RTSG_GROUND);
02784       DrawGroundSprite(SPR_FLAT_GRASS_TILE, PAL_NONE);
02785       DrawGroundSprite(ground + (image == SPR_RAIL_TRACK_X ? RTO_X : RTO_Y), PAL_NONE);
02786 
02787       if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationReservation(ti->tile)) {
02788         SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
02789         DrawGroundSprite(overlay + (image == SPR_RAIL_TRACK_X ? RTO_X : RTO_Y), PALETTE_CRASH);
02790       }
02791     } else {
02792       image += HasBit(image, SPRITE_MODIFIER_CUSTOM_SPRITE) ? ground_relocation : total_offset;
02793       if (HasBit(pal, SPRITE_MODIFIER_CUSTOM_SPRITE)) pal += ground_relocation;
02794       DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, palette));
02795 
02796       /* PBS debugging, draw reserved tracks darker */
02797       if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationRail(ti->tile) && HasStationReservation(ti->tile)) {
02798         const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
02799         DrawGroundSprite(GetRailStationAxis(ti->tile) == AXIS_X ? rti->base_sprites.single_x : rti->base_sprites.single_y, PALETTE_CRASH);
02800       }
02801     }
02802   }
02803 
02804   if (HasStationRail(ti->tile) && HasCatenaryDrawn(GetRailType(ti->tile)) && IsStationTileElectrifiable(ti->tile)) DrawCatenary(ti);
02805 
02806   if (HasBit(roadtypes, ROADTYPE_TRAM)) {
02807     Axis axis = GetRoadStopDir(ti->tile) == DIAGDIR_NE ? AXIS_X : AXIS_Y;
02808     DrawGroundSprite((HasBit(roadtypes, ROADTYPE_ROAD) ? SPR_TRAMWAY_OVERLAY : SPR_TRAMWAY_TRAM) + (axis ^ 1), PAL_NONE);
02809     DrawTramCatenary(ti, axis == AXIS_X ? ROAD_X : ROAD_Y);
02810   }
02811 
02812   if (IsRailWaypoint(ti->tile)) {
02813     /* Don't offset the waypoint graphics; they're always the same. */
02814     total_offset = 0;
02815   }
02816 
02817   DrawRailTileSeq(ti, t, TO_BUILDINGS, total_offset, relocation, palette);
02818 }
02819 
02820 void StationPickerDrawSprite(int x, int y, StationType st, RailType railtype, RoadType roadtype, int image)
02821 {
02822   int32 total_offset = 0;
02823   PaletteID pal = COMPANY_SPRITE_COLOUR(_local_company);
02824   const DrawTileSprites *t = GetStationTileLayout(st, image);
02825   const RailtypeInfo *rti = NULL;
02826 
02827   if (railtype != INVALID_RAILTYPE) {
02828     rti = GetRailTypeInfo(railtype);
02829     total_offset = rti->GetRailtypeSpriteOffset();
02830   }
02831 
02832   SpriteID img = t->ground.sprite;
02833   if ((img == SPR_RAIL_TRACK_X || img == SPR_RAIL_TRACK_Y) && rti->UsesOverlay()) {
02834     SpriteID ground = GetCustomRailSprite(rti, INVALID_TILE, RTSG_GROUND);
02835     DrawSprite(SPR_FLAT_GRASS_TILE, PAL_NONE, x, y);
02836     DrawSprite(ground + (img == SPR_RAIL_TRACK_X ? RTO_X : RTO_Y), PAL_NONE, x, y);
02837   } else {
02838     DrawSprite(img + total_offset, HasBit(img, PALETTE_MODIFIER_COLOUR) ? pal : PAL_NONE, x, y);
02839   }
02840 
02841   if (roadtype == ROADTYPE_TRAM) {
02842     DrawSprite(SPR_TRAMWAY_TRAM + (t->ground.sprite == SPR_ROAD_PAVED_STRAIGHT_X ? 1 : 0), PAL_NONE, x, y);
02843   }
02844 
02845   /* Default waypoint has no railtype specific sprites */
02846   DrawRailTileSeqInGUI(x, y, t, st == STATION_WAYPOINT ? 0 : total_offset, 0, pal);
02847 }
02848 
02849 static int GetSlopePixelZ_Station(TileIndex tile, uint x, uint y)
02850 {
02851   return GetTileMaxPixelZ(tile);
02852 }
02853 
02854 static Foundation GetFoundation_Station(TileIndex tile, Slope tileh)
02855 {
02856   return FlatteningFoundation(tileh);
02857 }
02858 
02859 static void GetTileDesc_Station(TileIndex tile, TileDesc *td)
02860 {
02861   td->owner[0] = GetTileOwner(tile);
02862   if (IsDriveThroughStopTile(tile)) {
02863     Owner road_owner = INVALID_OWNER;
02864     Owner tram_owner = INVALID_OWNER;
02865     RoadTypes rts = GetRoadTypes(tile);
02866     if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
02867     if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
02868 
02869     /* Is there a mix of owners? */
02870     if ((tram_owner != INVALID_OWNER && tram_owner != td->owner[0]) ||
02871         (road_owner != INVALID_OWNER && road_owner != td->owner[0])) {
02872       uint i = 1;
02873       if (road_owner != INVALID_OWNER) {
02874         td->owner_type[i] = STR_LAND_AREA_INFORMATION_ROAD_OWNER;
02875         td->owner[i] = road_owner;
02876         i++;
02877       }
02878       if (tram_owner != INVALID_OWNER) {
02879         td->owner_type[i] = STR_LAND_AREA_INFORMATION_TRAM_OWNER;
02880         td->owner[i] = tram_owner;
02881       }
02882     }
02883   }
02884   td->build_date = BaseStation::GetByTile(tile)->build_date;
02885 
02886   if (HasStationTileRail(tile)) {
02887     const StationSpec *spec = GetStationSpec(tile);
02888 
02889     if (spec != NULL) {
02890       td->station_class = StationClass::GetName(spec->cls_id);
02891       td->station_name  = spec->name;
02892 
02893       if (spec->grf_prop.grffile != NULL) {
02894         const GRFConfig *gc = GetGRFConfig(spec->grf_prop.grffile->grfid);
02895         td->grf = gc->GetName();
02896       }
02897     }
02898 
02899     const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(tile));
02900     td->rail_speed = rti->max_speed;
02901   }
02902 
02903   if (IsAirport(tile)) {
02904     const AirportSpec *as = Station::GetByTile(tile)->airport.GetSpec();
02905     td->airport_class = AirportClass::GetName(as->cls_id);
02906     td->airport_name = as->name;
02907 
02908     const AirportTileSpec *ats = AirportTileSpec::GetByTile(tile);
02909     td->airport_tile_name = ats->name;
02910 
02911     if (as->grf_prop.grffile != NULL) {
02912       const GRFConfig *gc = GetGRFConfig(as->grf_prop.grffile->grfid);
02913       td->grf = gc->GetName();
02914     } else if (ats->grf_prop.grffile != NULL) {
02915       const GRFConfig *gc = GetGRFConfig(ats->grf_prop.grffile->grfid);
02916       td->grf = gc->GetName();
02917     }
02918   }
02919 
02920   StringID str;
02921   switch (GetStationType(tile)) {
02922     default: NOT_REACHED();
02923     case STATION_RAIL:     str = STR_LAI_STATION_DESCRIPTION_RAILROAD_STATION; break;
02924     case STATION_AIRPORT:
02925       str = (IsHangar(tile) ? STR_LAI_STATION_DESCRIPTION_AIRCRAFT_HANGAR : STR_LAI_STATION_DESCRIPTION_AIRPORT);
02926       break;
02927     case STATION_TRUCK:    str = STR_LAI_STATION_DESCRIPTION_TRUCK_LOADING_AREA; break;
02928     case STATION_BUS:      str = STR_LAI_STATION_DESCRIPTION_BUS_STATION; break;
02929     case STATION_OILRIG:   str = STR_INDUSTRY_NAME_OIL_RIG; break;
02930     case STATION_DOCK:     str = STR_LAI_STATION_DESCRIPTION_SHIP_DOCK; break;
02931     case STATION_BUOY:     str = STR_LAI_STATION_DESCRIPTION_BUOY; break;
02932     case STATION_WAYPOINT: str = STR_LAI_STATION_DESCRIPTION_WAYPOINT; break;
02933   }
02934   td->str = str;
02935 }
02936 
02937 
02938 static TrackStatus GetTileTrackStatus_Station(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
02939 {
02940   TrackBits trackbits = TRACK_BIT_NONE;
02941 
02942   switch (mode) {
02943     case TRANSPORT_RAIL:
02944       if (HasStationRail(tile) && !IsStationTileBlocked(tile)) {
02945         trackbits = TrackToTrackBits(GetRailStationTrack(tile));
02946       }
02947       break;
02948 
02949     case TRANSPORT_WATER:
02950       /* buoy is coded as a station, it is always on open water */
02951       if (IsBuoy(tile)) {
02952         trackbits = TRACK_BIT_ALL;
02953         /* remove tracks that connect NE map edge */
02954         if (TileX(tile) == 0) trackbits &= ~(TRACK_BIT_X | TRACK_BIT_UPPER | TRACK_BIT_RIGHT);
02955         /* remove tracks that connect NW map edge */
02956         if (TileY(tile) == 0) trackbits &= ~(TRACK_BIT_Y | TRACK_BIT_LEFT | TRACK_BIT_UPPER);
02957       }
02958       break;
02959 
02960     case TRANSPORT_ROAD:
02961       if ((GetRoadTypes(tile) & sub_mode) != 0 && IsRoadStop(tile)) {
02962         DiagDirection dir = GetRoadStopDir(tile);
02963         Axis axis = DiagDirToAxis(dir);
02964 
02965         if (side != INVALID_DIAGDIR) {
02966           if (axis != DiagDirToAxis(side) || (IsStandardRoadStopTile(tile) && dir != side)) break;
02967         }
02968 
02969         trackbits = AxisToTrackBits(axis);
02970       }
02971       break;
02972 
02973     default:
02974       break;
02975   }
02976 
02977   return CombineTrackStatus(TrackBitsToTrackdirBits(trackbits), TRACKDIR_BIT_NONE);
02978 }
02979 
02980 
02981 static void TileLoop_Station(TileIndex tile)
02982 {
02983   /* FIXME -- GetTileTrackStatus_Station -> animated stationtiles
02984    * hardcoded.....not good */
02985   switch (GetStationType(tile)) {
02986     case STATION_AIRPORT:
02987       AirportTileAnimationTrigger(Station::GetByTile(tile), tile, AAT_TILELOOP);
02988       break;
02989 
02990     case STATION_DOCK:
02991       if (GetTileSlope(tile) != SLOPE_FLAT) break; // only handle water part
02992       /* FALL THROUGH */
02993     case STATION_OILRIG: //(station part)
02994     case STATION_BUOY:
02995       TileLoop_Water(tile);
02996       break;
02997 
02998     default: break;
02999   }
03000 }
03001 
03002 
03003 static void AnimateTile_Station(TileIndex tile)
03004 {
03005   if (HasStationRail(tile)) {
03006     AnimateStationTile(tile);
03007     return;
03008   }
03009 
03010   if (IsAirport(tile)) {
03011     AnimateAirportTile(tile);
03012   }
03013 }
03014 
03015 
03016 static bool ClickTile_Station(TileIndex tile)
03017 {
03018   const BaseStation *bst = BaseStation::GetByTile(tile);
03019 
03020   if (bst->facilities & FACIL_WAYPOINT) {
03021     ShowWaypointWindow(Waypoint::From(bst));
03022   } else if (IsHangar(tile)) {
03023     const Station *st = Station::From(bst);
03024     ShowDepotWindow(st->airport.GetHangarTile(st->airport.GetHangarNum(tile)), VEH_AIRCRAFT);
03025   } else {
03026     ShowStationViewWindow(bst->index);
03027   }
03028   return true;
03029 }
03030 
03031 static VehicleEnterTileStatus VehicleEnter_Station(Vehicle *v, TileIndex tile, int x, int y)
03032 {
03033   if (v->type == VEH_TRAIN) {
03034     StationID station_id = GetStationIndex(tile);
03035     if (!v->current_order.ShouldStopAtStation(v, station_id)) return VETSB_CONTINUE;
03036     if (!IsRailStation(tile) || !v->IsFrontEngine()) return VETSB_CONTINUE;
03037 
03038     int station_ahead;
03039     int station_length;
03040     int stop = GetTrainStopLocation(station_id, tile, Train::From(v), &station_ahead, &station_length);
03041 
03042     /* Stop whenever that amount of station ahead + the distance from the
03043      * begin of the platform to the stop location is longer than the length
03044      * of the platform. Station ahead 'includes' the current tile where the
03045      * vehicle is on, so we need to substract that. */
03046     if (!IsInsideBS(stop + station_ahead, station_length, TILE_SIZE)) return VETSB_CONTINUE;
03047 
03048     DiagDirection dir = DirToDiagDir(v->direction);
03049 
03050     x &= 0xF;
03051     y &= 0xF;
03052 
03053     if (DiagDirToAxis(dir) != AXIS_X) Swap(x, y);
03054     if (y == TILE_SIZE / 2) {
03055       if (dir != DIAGDIR_SE && dir != DIAGDIR_SW) x = TILE_SIZE - 1 - x;
03056       stop &= TILE_SIZE - 1;
03057 
03058       if (x == stop) return VETSB_ENTERED_STATION | (VehicleEnterTileStatus)(station_id << VETS_STATION_ID_OFFSET); // enter station
03059       if (x < stop) {
03060         uint16 spd;
03061 
03062         v->vehstatus |= VS_TRAIN_SLOWING;
03063         spd = max(0, (stop - x) * 20 - 15);
03064         if (spd < v->cur_speed) v->cur_speed = spd;
03065       }
03066     }
03067   } else if (v->type == VEH_ROAD) {
03068     RoadVehicle *rv = RoadVehicle::From(v);
03069     if (rv->state < RVSB_IN_ROAD_STOP && !IsReversingRoadTrackdir((Trackdir)rv->state) && rv->frame == 0) {
03070       if (IsRoadStop(tile) && rv->IsFrontEngine()) {
03071         /* Attempt to allocate a parking bay in a road stop */
03072         return RoadStop::GetByTile(tile, GetRoadStopType(tile))->Enter(rv) ? VETSB_CONTINUE : VETSB_CANNOT_ENTER;
03073       }
03074     }
03075   }
03076 
03077   return VETSB_CONTINUE;
03078 }
03079 
03084 void TriggerWatchedCargoCallbacks(Station *st)
03085 {
03086   /* Collect cargoes accepted since the last big tick. */
03087   uint cargoes = 0;
03088   for (CargoID cid = 0; cid < NUM_CARGO; cid++) {
03089     if (HasBit(st->goods[cid].acceptance_pickup, GoodsEntry::GES_ACCEPTED_BIGTICK)) SetBit(cargoes, cid);
03090   }
03091 
03092   /* Anything to do? */
03093   if (cargoes == 0) return;
03094 
03095   /* Loop over all houses in the catchment. */
03096   Rect r = st->GetCatchmentRect();
03097   TileArea ta(TileXY(r.left, r.top), TileXY(r.right, r.bottom));
03098   TILE_AREA_LOOP(tile, ta) {
03099     if (IsTileType(tile, MP_HOUSE)) {
03100       WatchedCargoCallback(tile, cargoes);
03101     }
03102   }
03103 }
03104 
03111 static bool StationHandleBigTick(BaseStation *st)
03112 {
03113   if (!st->IsInUse()) {
03114     if (++st->delete_ctr >= 8) delete st;
03115     return false;
03116   }
03117 
03118   if (Station::IsExpected(st)) {
03119     TriggerWatchedCargoCallbacks(Station::From(st));
03120 
03121     for (CargoID i = 0; i < NUM_CARGO; i++) {
03122       ClrBit(Station::From(st)->goods[i].acceptance_pickup, GoodsEntry::GES_ACCEPTED_BIGTICK);
03123     }
03124   }
03125 
03126 
03127   if ((st->facilities & FACIL_WAYPOINT) == 0) UpdateStationAcceptance(Station::From(st), true);
03128 
03129   return true;
03130 }
03131 
03132 static inline void byte_inc_sat(byte *p)
03133 {
03134   byte b = *p + 1;
03135   if (b != 0) *p = b;
03136 }
03137 
03138 static void UpdateStationRating(Station *st)
03139 {
03140   bool waiting_changed = false;
03141 
03142   byte_inc_sat(&st->time_since_load);
03143   byte_inc_sat(&st->time_since_unload);
03144 
03145   const CargoSpec *cs;
03146   FOR_ALL_CARGOSPECS(cs) {
03147     GoodsEntry *ge = &st->goods[cs->Index()];
03148     /* Slowly increase the rating back to his original level in the case we
03149      *  didn't deliver cargo yet to this station. This happens when a bribe
03150      *  failed while you didn't moved that cargo yet to a station. */
03151     if (!HasBit(ge->acceptance_pickup, GoodsEntry::GES_PICKUP) && ge->rating < INITIAL_STATION_RATING) {
03152       ge->rating++;
03153     }
03154 
03155     /* Only change the rating if we are moving this cargo */
03156     if (HasBit(ge->acceptance_pickup, GoodsEntry::GES_PICKUP)) {
03157       byte_inc_sat(&ge->days_since_pickup);
03158 
03159       bool skip = false;
03160       int rating = 0;
03161       uint waiting = ge->cargo.Count();
03162 
03163       /* num_dests is at least 1 if there is any cargo as
03164        * INVALID_STATION is also a destination.
03165        */
03166       uint num_dests = (uint)ge->cargo.Packets()->MapSize();
03167 
03168       /* Average amount of cargo per next hop, but prefer solitary stations
03169        * with only one or two next hops. They are allowed to have more
03170        * cargo waiting per next hop.
03171        * With manual cargo distribution waiting_avg = waiting / 2 as then
03172        * INVALID_STATION is the only destination.
03173        */
03174       uint waiting_avg = waiting / (num_dests + 1);
03175 
03176       if (HasBit(cs->callback_mask, CBM_CARGO_STATION_RATING_CALC)) {
03177         /* Perform custom station rating. If it succeeds the speed, days in transit and
03178          * waiting cargo ratings must not be executed. */
03179 
03180         /* NewGRFs expect last speed to be 0xFF when no vehicle has arrived yet. */
03181         uint last_speed = ge->last_speed;
03182         if (last_speed == 0) last_speed = 0xFF;
03183 
03184         uint32 var18 = min(ge->days_since_pickup, 0xFF) | (min(ge->max_waiting_cargo, 0xFFFF) << 8) | (min(last_speed, 0xFF) << 24);
03185         /* Convert to the 'old' vehicle types */
03186         uint32 var10 = (st->last_vehicle_type == VEH_INVALID) ? 0x0 : (st->last_vehicle_type + 0x10);
03187         uint16 callback = GetCargoCallback(CBID_CARGO_STATION_RATING_CALC, var10, var18, cs);
03188         if (callback != CALLBACK_FAILED) {
03189           skip = true;
03190           rating = GB(callback, 0, 14);
03191 
03192           /* Simulate a 15 bit signed value */
03193           if (HasBit(callback, 14)) rating -= 0x4000;
03194         }
03195       }
03196 
03197       if (!skip) {
03198         int b = ge->last_speed - 85;
03199         if (b >= 0) rating += b >> 2;
03200 
03201         byte days = ge->days_since_pickup;
03202         if (st->last_vehicle_type == VEH_SHIP) days >>= 2;
03203         (days > 21) ||
03204         (rating += 25, days > 12) ||
03205         (rating += 25, days > 6) ||
03206         (rating += 45, days > 3) ||
03207         (rating += 35, true);
03208 
03209         (rating -= 90, ge->max_waiting_cargo > 1500) ||
03210         (rating += 55, ge->max_waiting_cargo > 1000) ||
03211         (rating += 35, ge->max_waiting_cargo > 600) ||
03212         (rating += 10, ge->max_waiting_cargo > 300) ||
03213         (rating += 20, ge->max_waiting_cargo > 100) ||
03214         (rating += 10, true);
03215       }
03216 
03217       if (Company::IsValidID(st->owner) && HasBit(st->town->statues, st->owner)) rating += 26;
03218 
03219       byte age = ge->last_age;
03220       (age >= 3) ||
03221       (rating += 10, age >= 2) ||
03222       (rating += 10, age >= 1) ||
03223       (rating += 13, true);
03224 
03225       {
03226         int or_ = ge->rating; // old rating
03227 
03228         /* only modify rating in steps of -2, -1, 0, 1 or 2 */
03229         ge->rating = rating = or_ + Clamp(Clamp(rating, 0, 255) - or_, -2, 2);
03230 
03231         /* if rating is <= 64 and more than 100 items waiting on average per destination,
03232          * remove some random amount of goods from the station */
03233         if (rating <= 64 && waiting_avg >= 100) {
03234           int dec = Random() & 0x1F;
03235           if (waiting_avg < 200) dec &= 7;
03236           waiting -= (dec + 1) * num_dests;
03237           waiting_changed = true;
03238         }
03239 
03240         /* if rating is <= 127 and there are any items waiting, maybe remove some goods. */
03241         if (rating <= 127 && waiting != 0) {
03242           uint32 r = Random();
03243           if (rating <= (int)GB(r, 0, 7)) {
03244             /* Need to have int, otherwise it will just overflow etc. */
03245             waiting = max((int)waiting - (int)((GB(r, 8, 2) - 1) * num_dests), 0);
03246             waiting_changed = true;
03247           }
03248         }
03249 
03250         /* At some point we really must cap the cargo. Previously this
03251          * was a strict 4095, but now we'll have a less strict, but
03252          * increasingly agressive truncation of the amount of cargo. */
03253         static const uint WAITING_CARGO_THRESHOLD  = 1 << 12;
03254         static const uint WAITING_CARGO_CUT_FACTOR = 1 <<  6;
03255         static const uint MAX_WAITING_CARGO        = 1 << 15;
03256 
03257         if (waiting > WAITING_CARGO_THRESHOLD) {
03258           uint difference = waiting - WAITING_CARGO_THRESHOLD;
03259           waiting -= (difference / WAITING_CARGO_CUT_FACTOR);
03260 
03261           waiting = min(waiting, MAX_WAITING_CARGO);
03262           waiting_changed = true;
03263         }
03264 
03265         if (waiting_changed) {
03266           /* feed back the exact own waiting cargo at this station for the
03267            * next rating calculation.
03268            */
03269           ge->max_waiting_cargo = 0;
03270 
03271           /* If truncating also punish the source stations' ratings to
03272            * decrease the flow of incoming cargo. */
03273 
03274           StationCargoAmountMap waiting_per_source;
03275           ge->cargo.CountAndTruncate(waiting, waiting_per_source);
03276           for (StationCargoAmountMap::iterator i(waiting_per_source.begin()); i != waiting_per_source.end(); ++i) {
03277             Station *source_station = Station::GetIfValid(i->first);
03278             if (source_station == NULL) continue;
03279 
03280             GoodsEntry &source_ge = source_station->goods[cs->Index()];
03281             source_ge.max_waiting_cargo = max(source_ge.max_waiting_cargo, i->second);
03282           }
03283         } else {
03284           /* if the average number per next hop is low, be more forgiving. */
03285           ge->max_waiting_cargo = waiting_avg;
03286         }
03287       }
03288     }
03289   }
03290 
03291   StationID index = st->index;
03292   if (waiting_changed) {
03293     SetWindowDirty(WC_STATION_VIEW, index); // update whole window
03294   } else {
03295     SetWindowWidgetDirty(WC_STATION_VIEW, index, WID_SV_ACCEPT_RATING_LIST); // update only ratings list
03296   }
03297 }
03298 
03305 void DeleteStaleFlows(StationID at, CargoID c_id, StationID to)
03306 {
03307   FlowStatMap &flows = Station::Get(at)->goods[c_id].flows;
03308   for (FlowStatMap::iterator f_it = flows.begin(); f_it != flows.end();) {
03309     FlowStat &s_flows = f_it->second;
03310     s_flows.EraseShare(to);
03311     if (s_flows.GetShares()->empty()) {
03312       flows.erase(f_it++);
03313     } else {
03314       ++f_it;
03315     }
03316   }
03317 }
03318 
03325 uint GetMovingAverageLength(const Station *from, const Station *to)
03326 {
03327   return LinkStat::MIN_AVERAGE_LENGTH + (DistanceManhattan(from->xy, to->xy) >> 2);
03328 }
03329 
03333 void Station::RunAverages()
03334 {
03335   for (int goods_index = 0; goods_index < NUM_CARGO; ++goods_index) {
03336     LinkStatMap &links = this->goods[goods_index].link_stats;
03337     for (LinkStatMap::iterator i = links.begin(); i != links.end();) {
03338       StationID id = i->first;
03339       if (Station::IsValidID(id)) {
03340         i->second.Decrease();
03341         if (i->second.IsValid()) {
03342           ++i;
03343         } else {
03344           DeleteStaleFlows(this->index, goods_index, id);
03345           this->goods[goods_index].cargo.RerouteStalePackets(id);
03346           links.erase(i++);
03347         }
03348       } else {
03349         this->goods[goods_index].cargo.RerouteStalePackets(id);
03350         links.erase(i++);
03351       }
03352     }
03353 
03354     if (_settings_game.linkgraph.GetDistributionType(goods_index) == DT_MANUAL) {
03355       this->goods[goods_index].flows.clear();
03356     }
03357   }
03358 }
03359 
03368 void IncreaseStats(Station *st, CargoID cargo, StationID next_station_id, uint capacity, uint usage)
03369 {
03370   LinkStatMap &stats = st->goods[cargo].link_stats;
03371   LinkStatMap::iterator i = stats.find(next_station_id);
03372   if (i == stats.end()) {
03373     assert(st->index != next_station_id);
03374     stats.insert(std::make_pair(next_station_id, LinkStat(
03375         GetMovingAverageLength(st,
03376         Station::Get(next_station_id)), capacity,
03377         usage == UINT_MAX ? 0 : usage)));
03378   } else {
03379     if (usage == UINT_MAX) {
03380       i->second.Refresh(capacity);
03381     } else {
03382       assert(capacity >= usage);
03383       i->second.Increase(capacity, usage);
03384     }
03385     assert(i->second.IsValid());
03386   }
03387 }
03388 
03395 void IncreaseStats(Station *st, const Vehicle *front, StationID next_station_id)
03396 {
03397   for (const Vehicle *v = front; v != NULL; v = v->Next()) {
03398     if (v->refit_cap > 0) {
03399       IncreaseStats(st, v->cargo_type, next_station_id, v->refit_cap, v->cargo.Count());
03400     }
03401   }
03402 }
03403 
03404 /* called for every station each tick */
03405 static void StationHandleSmallTick(BaseStation *st)
03406 {
03407   if ((st->facilities & FACIL_WAYPOINT) != 0 || !st->IsInUse()) return;
03408 
03409   byte b = st->delete_ctr + 1;
03410   if (b >= STATION_RATING_TICKS) b = 0;
03411   st->delete_ctr = b;
03412 
03413   if (b == 0) UpdateStationRating(Station::From(st));
03414 }
03415 
03416 void OnTick_Station()
03417 {
03418   if (_game_mode == GM_EDITOR) return;
03419 
03420   RunAverages<Station>();
03421 
03422   BaseStation *st;
03423   FOR_ALL_BASE_STATIONS(st) {
03424     StationHandleSmallTick(st);
03425 
03426     /* Run STATION_ACCEPTANCE_TICKS = 250 tick interval trigger for station animation.
03427      * Station index is included so that triggers are not all done
03428      * at the same time. */
03429     if ((_tick_counter + st->index) % STATION_ACCEPTANCE_TICKS == 0) {
03430       /* Stop processing this station if it was deleted */
03431       if (!StationHandleBigTick(st)) continue;
03432       TriggerStationAnimation(st, st->xy, SAT_250_TICKS);
03433       if (Station::IsExpected(st)) AirportAnimationTrigger(Station::From(st), AAT_STATION_250_TICKS);
03434     }
03435   }
03436 }
03437 
03439 void StationMonthlyLoop()
03440 {
03441   Station *st;
03442 
03443   FOR_ALL_STATIONS(st) {
03444     for (CargoID i = 0; i < NUM_CARGO; i++) {
03445       GoodsEntry *ge = &st->goods[i];
03446       SB(ge->acceptance_pickup, GoodsEntry::GES_LAST_MONTH, 1, GB(ge->acceptance_pickup, GoodsEntry::GES_CURRENT_MONTH, 1));
03447       ClrBit(ge->acceptance_pickup, GoodsEntry::GES_CURRENT_MONTH);
03448       ge->supply = ge->supply_new;
03449       ge->supply_new = 0;
03450     }
03451   }
03452 }
03453 
03454 
03455 void ModifyStationRatingAround(TileIndex tile, Owner owner, int amount, uint radius)
03456 {
03457   Station *st;
03458 
03459   FOR_ALL_STATIONS(st) {
03460     if (st->owner == owner &&
03461         DistanceManhattan(tile, st->xy) <= radius) {
03462       for (CargoID i = 0; i < NUM_CARGO; i++) {
03463         GoodsEntry *ge = &st->goods[i];
03464 
03465         if (ge->acceptance_pickup != 0) {
03466           ge->rating = Clamp(ge->rating + amount, 0, 255);
03467         }
03468       }
03469     }
03470   }
03471 }
03472 
03473 static uint UpdateStationWaiting(Station *st, CargoID type, uint amount, SourceType source_type, SourceID source_id)
03474 {
03475   /* We can't allocate a CargoPacket? Then don't do anything
03476    * at all; i.e. just discard the incoming cargo. */
03477   if (!CargoPacket::CanAllocateItem()) return 0;
03478 
03479   GoodsEntry &ge = st->goods[type];
03480   amount += ge.amount_fract;
03481   ge.amount_fract = GB(amount, 0, 8);
03482 
03483   amount >>= 8;
03484   /* No new "real" cargo item yet. */
03485   if (amount == 0) return 0;
03486 
03487   StationID next = ge.GetVia(st->index);
03488 
03489   ge.cargo.Append(next, new CargoPacket(st->index, st->xy, amount, source_type, source_id));
03490   ge.supply_new += amount;
03491 
03492   if (!HasBit(ge.acceptance_pickup, GoodsEntry::GES_PICKUP)) {
03493     InvalidateWindowData(WC_STATION_LIST, st->index);
03494     SetBit(ge.acceptance_pickup, GoodsEntry::GES_PICKUP);
03495   }
03496 
03497   TriggerStationAnimation(st, st->xy, SAT_NEW_CARGO, type);
03498   AirportAnimationTrigger(st, AAT_STATION_NEW_CARGO, type);
03499 
03500   SetWindowDirty(WC_STATION_VIEW, st->index);
03501   st->MarkTilesDirty(true);
03502   return amount;
03503 }
03504 
03505 static bool IsUniqueStationName(const char *name)
03506 {
03507   const Station *st;
03508 
03509   FOR_ALL_STATIONS(st) {
03510     if (st->name != NULL && strcmp(st->name, name) == 0) return false;
03511   }
03512 
03513   return true;
03514 }
03515 
03525 CommandCost CmdRenameStation(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
03526 {
03527   Station *st = Station::GetIfValid(p1);
03528   if (st == NULL) return CMD_ERROR;
03529 
03530   CommandCost ret = CheckOwnership(st->owner);
03531   if (ret.Failed()) return ret;
03532 
03533   bool reset = StrEmpty(text);
03534 
03535   if (!reset) {
03536     if (Utf8StringLength(text) >= MAX_LENGTH_STATION_NAME_CHARS) return CMD_ERROR;
03537     if (!IsUniqueStationName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
03538   }
03539 
03540   if (flags & DC_EXEC) {
03541     free(st->name);
03542     st->name = reset ? NULL : strdup(text);
03543 
03544     st->UpdateVirtCoord();
03545     InvalidateWindowData(WC_STATION_LIST, st->owner, 1);
03546   }
03547 
03548   return CommandCost();
03549 }
03550 
03557 void FindStationsAroundTiles(const TileArea &location, StationList *stations)
03558 {
03559   /* area to search = producer plus station catchment radius */
03560   uint max_rad = (_settings_game.station.modified_catchment ? MAX_CATCHMENT : CA_UNMODIFIED);
03561 
03562   uint x = TileX(location.tile);
03563   uint y = TileY(location.tile);
03564 
03565   uint min_x = (x > max_rad) ? x - max_rad : 0;
03566   uint max_x = x + location.w + max_rad;
03567   uint min_y = (y > max_rad) ? y - max_rad : 0;
03568   uint max_y = y + location.h + max_rad;
03569 
03570   if (min_x == 0 && _settings_game.construction.freeform_edges) min_x = 1;
03571   if (min_y == 0 && _settings_game.construction.freeform_edges) min_y = 1;
03572   if (max_x >= MapSizeX()) max_x = MapSizeX() - 1;
03573   if (max_y >= MapSizeY()) max_y = MapSizeY() - 1;
03574 
03575   for (uint cy = min_y; cy < max_y; cy++) {
03576     for (uint cx = min_x; cx < max_x; cx++) {
03577       TileIndex cur_tile = TileXY(cx, cy);
03578       if (!IsTileType(cur_tile, MP_STATION)) continue;
03579 
03580       Station *st = Station::GetByTile(cur_tile);
03581       /* st can be NULL in case of waypoints */
03582       if (st == NULL) continue;
03583 
03584       if (_settings_game.station.modified_catchment) {
03585         int rad = st->GetCatchmentRadius();
03586         int rad_x = cx - x;
03587         int rad_y = cy - y;
03588 
03589         if (rad_x < -rad || rad_x >= rad + location.w) continue;
03590         if (rad_y < -rad || rad_y >= rad + location.h) continue;
03591       }
03592 
03593       /* Insert the station in the set. This will fail if it has
03594        * already been added.
03595        */
03596       stations->Include(st);
03597     }
03598   }
03599 }
03600 
03605 const StationList *StationFinder::GetStations()
03606 {
03607   if (this->tile != INVALID_TILE) {
03608     FindStationsAroundTiles(*this, &this->stations);
03609     this->tile = INVALID_TILE;
03610   }
03611   return &this->stations;
03612 }
03613 
03614 uint MoveGoodsToStation(CargoID type, uint amount, SourceType source_type, SourceID source_id, const StationList *all_stations)
03615 {
03616   /* Return if nothing to do. Also the rounding below fails for 0. */
03617   if (amount == 0) return 0;
03618 
03619   Station *st1 = NULL;   // Station with best rating
03620   Station *st2 = NULL;   // Second best station
03621   uint best_rating1 = 0; // rating of st1
03622   uint best_rating2 = 0; // rating of st2
03623 
03624   for (Station * const *st_iter = all_stations->Begin(); st_iter != all_stations->End(); ++st_iter) {
03625     Station *st = *st_iter;
03626 
03627     /* Is the station reserved exclusively for somebody else? */
03628     if (st->town->exclusive_counter > 0 && st->town->exclusivity != st->owner) continue;
03629 
03630     if (st->goods[type].rating == 0) continue; // Lowest possible rating, better not to give cargo anymore
03631 
03632     if (_settings_game.order.selectgoods && st->goods[type].last_speed == 0) continue; // Selectively servicing stations, and not this one
03633 
03634     if (IsCargoInClass(type, CC_PASSENGERS)) {
03635       if (st->facilities == FACIL_TRUCK_STOP) continue; // passengers are never served by just a truck stop
03636     } else {
03637       if (st->facilities == FACIL_BUS_STOP) continue; // non-passengers are never served by just a bus stop
03638     }
03639 
03640     /* This station can be used, add it to st1/st2 */
03641     if (st1 == NULL || st->goods[type].rating >= best_rating1) {
03642       st2 = st1; best_rating2 = best_rating1; st1 = st; best_rating1 = st->goods[type].rating;
03643     } else if (st2 == NULL || st->goods[type].rating >= best_rating2) {
03644       st2 = st; best_rating2 = st->goods[type].rating;
03645     }
03646   }
03647 
03648   /* no stations around at all? */
03649   if (st1 == NULL) return 0;
03650 
03651   /* From now we'll calculate with fractal cargo amounts.
03652    * First determine how much cargo we really have. */
03653   amount *= best_rating1 + 1;
03654 
03655   if (st2 == NULL) {
03656     /* only one station around */
03657     return UpdateStationWaiting(st1, type, amount, source_type, source_id);
03658   }
03659 
03660   /* several stations around, the best two (highest rating) are in st1 and st2 */
03661   assert(st1 != NULL);
03662   assert(st2 != NULL);
03663   assert(best_rating1 != 0 || best_rating2 != 0);
03664 
03665   /* Then determine the amount the worst station gets. We do it this way as the
03666    * best should get a bonus, which in this case is the rounding difference from
03667    * this calculation. In reality that will mean the bonus will be pretty low.
03668    * Nevertheless, the best station should always get the most cargo regardless
03669    * of rounding issues. */
03670   uint worst_cargo = amount * best_rating2 / (best_rating1 + best_rating2);
03671   assert(worst_cargo <= (amount - worst_cargo));
03672 
03673   /* And then send the cargo to the stations! */
03674   uint moved = UpdateStationWaiting(st1, type, amount - worst_cargo, source_type, source_id);
03675   /* These two UpdateStationWaiting's can't be in the statement as then the order
03676    * of execution would be undefined and that could cause desyncs with callbacks. */
03677   return moved + UpdateStationWaiting(st2, type, worst_cargo, source_type, source_id);
03678 }
03679 
03680 void BuildOilRig(TileIndex tile)
03681 {
03682   if (!Station::CanAllocateItem()) {
03683     DEBUG(misc, 0, "Can't allocate station for oilrig at 0x%X, reverting to oilrig only", tile);
03684     return;
03685   }
03686 
03687   Station *st = new Station(tile);
03688   st->town = ClosestTownFromTile(tile, UINT_MAX);
03689 
03690   st->string_id = GenerateStationName(st, tile, STATIONNAMING_OILRIG);
03691 
03692   assert(IsTileType(tile, MP_INDUSTRY));
03693   DeleteAnimatedTile(tile);
03694   MakeOilrig(tile, st->index, GetWaterClass(tile));
03695 
03696   st->owner = OWNER_NONE;
03697   st->airport.type = AT_OILRIG;
03698   st->airport.Add(tile);
03699   st->dock_tile = tile;
03700   st->facilities = FACIL_AIRPORT | FACIL_DOCK;
03701   st->build_date = _date;
03702 
03703   st->rect.BeforeAddTile(tile, StationRect::ADD_FORCE);
03704 
03705   for (CargoID j = 0; j < NUM_CARGO; j++) {
03706     st->goods[j].acceptance_pickup = 0;
03707     st->goods[j].days_since_pickup = 255;
03708     st->goods[j].rating = INITIAL_STATION_RATING;
03709     st->goods[j].last_speed = 0;
03710     st->goods[j].last_age = 255;
03711   }
03712 
03713   st->UpdateVirtCoord();
03714   UpdateStationAcceptance(st, false);
03715   st->RecomputeIndustriesNear();
03716 }
03717 
03718 void DeleteOilRig(TileIndex tile)
03719 {
03720   Station *st = Station::GetByTile(tile);
03721 
03722   MakeWaterKeepingClass(tile, OWNER_NONE);
03723 
03724   st->dock_tile = INVALID_TILE;
03725   st->airport.Clear();
03726   st->facilities &= ~(FACIL_AIRPORT | FACIL_DOCK);
03727   st->airport.flags = 0;
03728 
03729   st->rect.AfterRemoveTile(st, tile);
03730 
03731   st->UpdateVirtCoord();
03732   st->RecomputeIndustriesNear();
03733   if (!st->IsInUse()) delete st;
03734 }
03735 
03736 static void ChangeTileOwner_Station(TileIndex tile, Owner old_owner, Owner new_owner)
03737 {
03738   if (IsRoadStopTile(tile)) {
03739     for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
03740       /* Update all roadtypes, no matter if they are present */
03741       if (GetRoadOwner(tile, rt) == old_owner) {
03742         if (HasTileRoadType(tile, rt)) {
03743           /* A drive-through road-stop has always two road bits. No need to dirty windows here, we'll redraw the whole screen anyway. */
03744           Company::Get(old_owner)->infrastructure.road[rt] -= 2;
03745           if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.road[rt] += 2;
03746         }
03747         SetRoadOwner(tile, rt, new_owner == INVALID_OWNER ? OWNER_NONE : new_owner);
03748       }
03749     }
03750   }
03751 
03752   if (!IsTileOwner(tile, old_owner)) return;
03753 
03754   if (new_owner != INVALID_OWNER) {
03755     /* Update company infrastructure counts. Only do it here
03756      * if the new owner is valid as otherwise the clear
03757      * command will do it for us. No need to dirty windows
03758      * here, we'll redraw the whole screen anyway.*/
03759     Company *old_company = Company::Get(old_owner);
03760     Company *new_company = Company::Get(new_owner);
03761 
03762     /* Update counts for underlying infrastructure. */
03763     switch (GetStationType(tile)) {
03764       case STATION_RAIL:
03765       case STATION_WAYPOINT:
03766         if (!IsStationTileBlocked(tile)) {
03767           old_company->infrastructure.rail[GetRailType(tile)]--;
03768           new_company->infrastructure.rail[GetRailType(tile)]++;
03769         }
03770         break;
03771 
03772       case STATION_BUS:
03773       case STATION_TRUCK:
03774         /* Road stops were already handled above. */
03775         break;
03776 
03777       case STATION_BUOY:
03778       case STATION_DOCK:
03779         if (GetWaterClass(tile) == WATER_CLASS_CANAL) {
03780           old_company->infrastructure.water--;
03781           new_company->infrastructure.water++;
03782         }
03783         break;
03784 
03785       default:
03786         break;
03787     }
03788 
03789     /* Update station tile count. */
03790     if (!IsBuoy(tile) && !IsAirport(tile)) {
03791       old_company->infrastructure.station--;
03792       new_company->infrastructure.station++;
03793     }
03794 
03795     /* for buoys, owner of tile is owner of water, st->owner == OWNER_NONE */
03796     SetTileOwner(tile, new_owner);
03797     InvalidateWindowClassesData(WC_STATION_LIST, 0);
03798   } else {
03799     if (IsDriveThroughStopTile(tile)) {
03800       /* Remove the drive-through road stop */
03801       DoCommand(tile, 1 | 1 << 8, (GetStationType(tile) == STATION_TRUCK) ? ROADSTOP_TRUCK : ROADSTOP_BUS, DC_EXEC | DC_BANKRUPT, CMD_REMOVE_ROAD_STOP);
03802       assert(IsTileType(tile, MP_ROAD));
03803       /* Change owner of tile and all roadtypes */
03804       ChangeTileOwner(tile, old_owner, new_owner);
03805     } else {
03806       DoCommand(tile, 0, 0, DC_EXEC | DC_BANKRUPT, CMD_LANDSCAPE_CLEAR);
03807       /* Set tile owner of water under (now removed) buoy and dock to OWNER_NONE.
03808        * Update owner of buoy if it was not removed (was in orders).
03809        * Do not update when owned by OWNER_WATER (sea and rivers). */
03810       if ((IsTileType(tile, MP_WATER) || IsBuoyTile(tile)) && IsTileOwner(tile, old_owner)) SetTileOwner(tile, OWNER_NONE);
03811     }
03812   }
03813 }
03814 
03823 static bool CanRemoveRoadWithStop(TileIndex tile, DoCommandFlag flags)
03824 {
03825   /* Yeah... water can always remove stops, right? */
03826   if (_current_company == OWNER_WATER) return true;
03827 
03828   RoadTypes rts = GetRoadTypes(tile);
03829   if (HasBit(rts, ROADTYPE_TRAM)) {
03830     Owner tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
03831     if (tram_owner != OWNER_NONE && CheckOwnership(tram_owner).Failed()) return false;
03832   }
03833   if (HasBit(rts, ROADTYPE_ROAD)) {
03834     Owner road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
03835     if (road_owner != OWNER_TOWN) {
03836       if (road_owner != OWNER_NONE && CheckOwnership(road_owner).Failed()) return false;
03837     } else {
03838       if (CheckAllowRemoveRoad(tile, GetAnyRoadBits(tile, ROADTYPE_ROAD), OWNER_TOWN, ROADTYPE_ROAD, flags).Failed()) return false;
03839     }
03840   }
03841 
03842   return true;
03843 }
03844 
03851 CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags)
03852 {
03853   if (flags & DC_AUTO) {
03854     switch (GetStationType(tile)) {
03855       default: break;
03856       case STATION_RAIL:     return_cmd_error(STR_ERROR_MUST_DEMOLISH_RAILROAD);
03857       case STATION_WAYPOINT: return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
03858       case STATION_AIRPORT:  return_cmd_error(STR_ERROR_MUST_DEMOLISH_AIRPORT_FIRST);
03859       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);
03860       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);
03861       case STATION_BUOY:     return_cmd_error(STR_ERROR_BUOY_IN_THE_WAY);
03862       case STATION_DOCK:     return_cmd_error(STR_ERROR_MUST_DEMOLISH_DOCK_FIRST);
03863       case STATION_OILRIG:
03864         SetDParam(1, STR_INDUSTRY_NAME_OIL_RIG);
03865         return_cmd_error(STR_ERROR_GENERIC_OBJECT_IN_THE_WAY);
03866     }
03867   }
03868 
03869   switch (GetStationType(tile)) {
03870     case STATION_RAIL:     return RemoveRailStation(tile, flags);
03871     case STATION_WAYPOINT: return RemoveRailWaypoint(tile, flags);
03872     case STATION_AIRPORT:  return RemoveAirport(tile, flags);
03873     case STATION_TRUCK:
03874       if (IsDriveThroughStopTile(tile) && !CanRemoveRoadWithStop(tile, flags)) {
03875         return_cmd_error(STR_ERROR_MUST_DEMOLISH_TRUCK_STATION_FIRST);
03876       }
03877       return RemoveRoadStop(tile, flags);
03878     case STATION_BUS:
03879       if (IsDriveThroughStopTile(tile) && !CanRemoveRoadWithStop(tile, flags)) {
03880         return_cmd_error(STR_ERROR_MUST_DEMOLISH_BUS_STATION_FIRST);
03881       }
03882       return RemoveRoadStop(tile, flags);
03883     case STATION_BUOY:     return RemoveBuoy(tile, flags);
03884     case STATION_DOCK:     return RemoveDock(tile, flags);
03885     default: break;
03886   }
03887 
03888   return CMD_ERROR;
03889 }
03890 
03891 static CommandCost TerraformTile_Station(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
03892 {
03893   if (_settings_game.construction.build_on_slopes && AutoslopeEnabled()) {
03894     /* TODO: If you implement newgrf callback 149 'land slope check', you have to decide what to do with it here.
03895      *       TTDP does not call it.
03896      */
03897     if (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new)) {
03898       switch (GetStationType(tile)) {
03899         case STATION_WAYPOINT:
03900         case STATION_RAIL: {
03901           DiagDirection direction = AxisToDiagDir(GetRailStationAxis(tile));
03902           if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
03903           if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
03904           return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
03905         }
03906 
03907         case STATION_AIRPORT:
03908           return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
03909 
03910         case STATION_TRUCK:
03911         case STATION_BUS: {
03912           DiagDirection direction = GetRoadStopDir(tile);
03913           if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
03914           if (IsDriveThroughStopTile(tile)) {
03915             if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
03916           }
03917           return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
03918         }
03919 
03920         default: break;
03921       }
03922     }
03923   }
03924   return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
03925 }
03926 
03932 uint FlowStat::GetShare(StationID st) const
03933 {
03934   uint32 prev = 0;
03935   for (SharesMap::const_iterator it = this->shares.begin(); it != this->shares.end(); ++it) {
03936     if (it->second == st) {
03937       return it->first - prev;
03938     } else {
03939       prev = it->first;
03940     }
03941   }
03942   return 0;
03943 }
03944 
03950 StationID FlowStat::GetVia(StationID excluded) const
03951 {
03952   assert(!this->shares.empty());
03953   uint max = (--this->shares.end())->first - 1;
03954   SharesMap::const_iterator it = this->shares.upper_bound(RandomRange(max));
03955   assert(it != this->shares.end());
03956   if (it->second != excluded) {
03957     return it->second;
03958   } else {
03959     uint end = it->first;
03960     if (end - 1 == max) return INVALID_STATION; // only one station in the map
03961     uint begin = (it == this->shares.begin() ? 0 : (--it)->first);
03962     uint rand = RandomRange(max - (end - begin));
03963     if (rand < begin) {
03964       return this->shares.upper_bound(rand)->second;
03965     } else {
03966       return this->shares.upper_bound(rand + (end - begin))->second;
03967     }
03968   }
03969 }
03970 
03975 void FlowStat::EraseShare(StationID st)
03976 {
03977   uint32 removed_shares = 0;
03978   uint32 last_share = 0;
03979   SharesMap new_shares;
03980   for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
03981     if (it->second == st) {
03982       removed_shares += it->first - last_share;
03983     } else {
03984       new_shares[it->first - removed_shares] = it->second;
03985     }
03986     last_share = it->first;
03987   }
03988   this->shares.swap(new_shares);
03989   for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
03990     assert(it->second != st);
03991   }
03992 }
03993 
03999 uint GoodsEntry::GetSumFlowVia(StationID via) const
04000 {
04001   uint ret = 0;
04002   for (FlowStatMap::const_iterator i = this->flows.begin(); i != this->flows.end(); ++i) {
04003     ret += i->second.GetShare(via);
04004   }
04005   return ret;
04006 }
04007 
04008 extern const TileTypeProcs _tile_type_station_procs = {
04009   DrawTile_Station,           // draw_tile_proc
04010   GetSlopePixelZ_Station,     // get_slope_z_proc
04011   ClearTile_Station,          // clear_tile_proc
04012   NULL,                       // add_accepted_cargo_proc
04013   GetTileDesc_Station,        // get_tile_desc_proc
04014   GetTileTrackStatus_Station, // get_tile_track_status_proc
04015   ClickTile_Station,          // click_tile_proc
04016   AnimateTile_Station,        // animate_tile_proc
04017   TileLoop_Station,           // tile_loop_proc
04018   ChangeTileOwner_Station,    // change_tile_owner_proc
04019   NULL,                       // add_produced_cargo_proc
04020   VehicleEnter_Station,       // vehicle_enter_tile_proc
04021   GetFoundation_Station,      // get_foundation_proc
04022   TerraformTile_Station,      // terraform_tile_proc
04023 };