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, NT_ACCEPTANCE, NF_INCOLOUR | NF_SMALL, 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 
00642 static CommandCost BuildStationPart(Station **st, DoCommandFlag flags, bool reuse, TileArea area, StationNaming name_class)
00643 {
00644   /* Find a deleted station close to us */
00645   if (*st == NULL && reuse) *st = GetClosestDeletedStation(area.tile);
00646 
00647   if (*st != NULL) {
00648     if ((*st)->owner != _current_company) {
00649       return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_STATION);
00650     }
00651 
00652     CommandCost ret = (*st)->rect.BeforeAddRect(area.tile, area.w, area.h, StationRect::ADD_TEST);
00653     if (ret.Failed()) return ret;
00654   } else {
00655     /* allocate and initialize new station */
00656     if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
00657 
00658     if (flags & DC_EXEC) {
00659       *st = new Station(area.tile);
00660 
00661       (*st)->town = ClosestTownFromTile(area.tile, UINT_MAX);
00662       (*st)->string_id = GenerateStationName(*st, area.tile, name_class);
00663 
00664       if (Company::IsValidID(_current_company)) {
00665         SetBit((*st)->town->have_ratings, _current_company);
00666       }
00667     }
00668   }
00669   return CommandCost();
00670 }
00671 
00678 static void DeleteStationIfEmpty(BaseStation *st)
00679 {
00680   if (!st->IsInUse()) {
00681     st->delete_ctr = 0;
00682     InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
00683   }
00684   /* station remains but it probably lost some parts - station sign should stay in the station boundaries */
00685   UpdateStationSignCoord(st);
00686 }
00687 
00688 CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags);
00689 
00699 CommandCost CheckBuildableTile(TileIndex tile, uint invalid_dirs, int &allowed_z, bool allow_steep, bool check_bridge = true)
00700 {
00701   if (check_bridge && MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) {
00702     return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
00703   }
00704 
00705   CommandCost ret = EnsureNoVehicleOnGround(tile);
00706   if (ret.Failed()) return ret;
00707 
00708   int z;
00709   Slope tileh = GetTileSlope(tile, &z);
00710 
00711   /* Prohibit building if
00712    *   1) The tile is "steep" (i.e. stretches two height levels).
00713    *   2) The tile is non-flat and the build_on_slopes switch is disabled.
00714    */
00715   if ((!allow_steep && IsSteepSlope(tileh)) ||
00716       ((!_settings_game.construction.build_on_slopes) && tileh != SLOPE_FLAT)) {
00717     return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
00718   }
00719 
00720   CommandCost cost(EXPENSES_CONSTRUCTION);
00721   int flat_z = z + GetSlopeMaxZ(tileh);
00722   if (tileh != SLOPE_FLAT) {
00723     /* Forbid building if the tile faces a slope in a invalid direction. */
00724     for (DiagDirection dir = DIAGDIR_BEGIN; dir != DIAGDIR_END; dir++) {
00725       if (HasBit(invalid_dirs, dir) && !CanBuildDepotByTileh(dir, tileh)) {
00726         return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
00727       }
00728     }
00729     cost.AddCost(_price[PR_BUILD_FOUNDATION]);
00730   }
00731 
00732   /* The level of this tile must be equal to allowed_z. */
00733   if (allowed_z < 0) {
00734     /* First tile. */
00735     allowed_z = flat_z;
00736   } else if (allowed_z != flat_z) {
00737     return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
00738   }
00739 
00740   return cost;
00741 }
00742 
00749 CommandCost CheckFlatLand(TileArea tile_area, DoCommandFlag flags)
00750 {
00751   CommandCost cost(EXPENSES_CONSTRUCTION);
00752   int allowed_z = -1;
00753 
00754   TILE_AREA_LOOP(tile_cur, tile_area) {
00755     CommandCost ret = CheckBuildableTile(tile_cur, 0, allowed_z, true);
00756     if (ret.Failed()) return ret;
00757     cost.AddCost(ret);
00758 
00759     ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00760     if (ret.Failed()) return ret;
00761     cost.AddCost(ret);
00762   }
00763 
00764   return cost;
00765 }
00766 
00781 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)
00782 {
00783   CommandCost cost(EXPENSES_CONSTRUCTION);
00784   int allowed_z = -1;
00785   uint invalid_dirs = 5 << axis;
00786 
00787   const StationSpec *statspec = StationClass::Get(spec_class)->GetSpec(spec_index);
00788   bool slope_cb = statspec != NULL && HasBit(statspec->callback_mask, CBM_STATION_SLOPE_CHECK);
00789 
00790   TILE_AREA_LOOP(tile_cur, tile_area) {
00791     CommandCost ret = CheckBuildableTile(tile_cur, invalid_dirs, allowed_z, false);
00792     if (ret.Failed()) return ret;
00793     cost.AddCost(ret);
00794 
00795     if (slope_cb) {
00796       /* Do slope check if requested. */
00797       ret = PerformStationTileSlopeCheck(tile_area.tile, tile_cur, statspec, axis, plat_len, numtracks);
00798       if (ret.Failed()) return ret;
00799     }
00800 
00801     /* if station is set, then we have special handling to allow building on top of already existing stations.
00802      * so station points to INVALID_STATION if we can build on any station.
00803      * Or it points to a station if we're only allowed to build on exactly that station. */
00804     if (station != NULL && IsTileType(tile_cur, MP_STATION)) {
00805       if (!IsRailStation(tile_cur)) {
00806         return ClearTile_Station(tile_cur, DC_AUTO); // get error message
00807       } else {
00808         StationID st = GetStationIndex(tile_cur);
00809         if (*station == INVALID_STATION) {
00810           *station = st;
00811         } else if (*station != st) {
00812           return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
00813         }
00814       }
00815     } else {
00816       /* Rail type is only valid when building a railway station; if station to
00817        * build isn't a rail station it's INVALID_RAILTYPE. */
00818       if (rt != INVALID_RAILTYPE &&
00819           IsPlainRailTile(tile_cur) && !HasSignals(tile_cur) &&
00820           HasPowerOnRail(GetRailType(tile_cur), rt)) {
00821         /* Allow overbuilding if the tile:
00822          *  - has rail, but no signals
00823          *  - it has exactly one track
00824          *  - the track is in line with the station
00825          *  - the current rail type has power on the to-be-built type (e.g. convert normal rail to el rail)
00826          */
00827         TrackBits tracks = GetTrackBits(tile_cur);
00828         Track track = RemoveFirstTrack(&tracks);
00829         Track expected_track = HasBit(invalid_dirs, DIAGDIR_NE) ? TRACK_X : TRACK_Y;
00830 
00831         if (tracks == TRACK_BIT_NONE && track == expected_track) {
00832           /* Check for trains having a reservation for this tile. */
00833           if (HasBit(GetRailReservationTrackBits(tile_cur), track)) {
00834             Train *v = GetTrainForReservation(tile_cur, track);
00835             if (v != NULL) {
00836               *affected_vehicles.Append() = v;
00837             }
00838           }
00839           CommandCost ret = DoCommand(tile_cur, 0, track, flags, CMD_REMOVE_SINGLE_RAIL);
00840           if (ret.Failed()) return ret;
00841           cost.AddCost(ret);
00842           /* With flags & ~DC_EXEC CmdLandscapeClear would fail since the rail still exists */
00843           continue;
00844         }
00845       }
00846       ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00847       if (ret.Failed()) return ret;
00848       cost.AddCost(ret);
00849     }
00850   }
00851 
00852   return cost;
00853 }
00854 
00867 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)
00868 {
00869   CommandCost cost(EXPENSES_CONSTRUCTION);
00870   int allowed_z = -1;
00871 
00872   TILE_AREA_LOOP(cur_tile, tile_area) {
00873     CommandCost ret = CheckBuildableTile(cur_tile, invalid_dirs, allowed_z, !is_drive_through);
00874     if (ret.Failed()) return ret;
00875     cost.AddCost(ret);
00876 
00877     /* If station is set, then we have special handling to allow building on top of already existing stations.
00878      * Station points to INVALID_STATION if we can build on any station.
00879      * Or it points to a station if we're only allowed to build on exactly that station. */
00880     if (station != NULL && IsTileType(cur_tile, MP_STATION)) {
00881       if (!IsRoadStop(cur_tile)) {
00882         return ClearTile_Station(cur_tile, DC_AUTO); // Get error message.
00883       } else {
00884         if (is_truck_stop != IsTruckStop(cur_tile) ||
00885             is_drive_through != IsDriveThroughStopTile(cur_tile)) {
00886           return ClearTile_Station(cur_tile, DC_AUTO); // Get error message.
00887         }
00888         /* Drive-through station in the wrong direction. */
00889         if (is_drive_through && IsDriveThroughStopTile(cur_tile) && DiagDirToAxis(GetRoadStopDir(cur_tile)) != axis){
00890           return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
00891         }
00892         StationID st = GetStationIndex(cur_tile);
00893         if (*station == INVALID_STATION) {
00894           *station = st;
00895         } else if (*station != st) {
00896           return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
00897         }
00898       }
00899     } else {
00900       bool build_over_road = is_drive_through && IsNormalRoadTile(cur_tile);
00901       /* Road bits in the wrong direction. */
00902       RoadBits rb = IsNormalRoadTile(cur_tile) ? GetAllRoadBits(cur_tile) : ROAD_NONE;
00903       if (build_over_road && (rb & (axis == AXIS_X ? ROAD_Y : ROAD_X)) != 0) {
00904         /* Someone was pedantic and *NEEDED* three fracking different error messages. */
00905         switch (CountBits(rb)) {
00906           case 1:
00907             return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
00908 
00909           case 2:
00910             if (rb == ROAD_X || rb == ROAD_Y) return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
00911             return_cmd_error(STR_ERROR_DRIVE_THROUGH_CORNER);
00912 
00913           default: // 3 or 4
00914             return_cmd_error(STR_ERROR_DRIVE_THROUGH_JUNCTION);
00915         }
00916       }
00917 
00918       RoadTypes cur_rts = IsNormalRoadTile(cur_tile) ? GetRoadTypes(cur_tile) : ROADTYPES_NONE;
00919       uint num_roadbits = 0;
00920       if (build_over_road) {
00921         /* There is a road, check if we can build road+tram stop over it. */
00922         if (HasBit(cur_rts, ROADTYPE_ROAD)) {
00923           Owner road_owner = GetRoadOwner(cur_tile, ROADTYPE_ROAD);
00924           if (road_owner == OWNER_TOWN) {
00925             if (!_settings_game.construction.road_stop_on_town_road) return_cmd_error(STR_ERROR_DRIVE_THROUGH_ON_TOWN_ROAD);
00926           } else if (!_settings_game.construction.road_stop_on_competitor_road && road_owner != OWNER_NONE) {
00927             CommandCost ret = CheckOwnership(road_owner);
00928             if (ret.Failed()) return ret;
00929           }
00930           num_roadbits += CountBits(GetRoadBits(cur_tile, ROADTYPE_ROAD));
00931         }
00932 
00933         /* There is a tram, check if we can build road+tram stop over it. */
00934         if (HasBit(cur_rts, ROADTYPE_TRAM)) {
00935           Owner tram_owner = GetRoadOwner(cur_tile, ROADTYPE_TRAM);
00936           if (!_settings_game.construction.road_stop_on_competitor_road && tram_owner != OWNER_NONE) {
00937             CommandCost ret = CheckOwnership(tram_owner);
00938             if (ret.Failed()) return ret;
00939           }
00940           num_roadbits += CountBits(GetRoadBits(cur_tile, ROADTYPE_TRAM));
00941         }
00942 
00943         /* Take into account existing roadbits. */
00944         rts |= cur_rts;
00945       } else {
00946         ret = DoCommand(cur_tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00947         if (ret.Failed()) return ret;
00948         cost.AddCost(ret);
00949       }
00950 
00951       uint roadbits_to_build = CountBits(rts) * 2 - num_roadbits;
00952       cost.AddCost(_price[PR_BUILD_ROAD] * roadbits_to_build);
00953     }
00954   }
00955 
00956   return cost;
00957 }
00958 
00966 CommandCost CanExpandRailStation(const BaseStation *st, TileArea &new_ta, Axis axis)
00967 {
00968   TileArea cur_ta = st->train_station;
00969 
00970   /* determine new size of train station region.. */
00971   int x = min(TileX(cur_ta.tile), TileX(new_ta.tile));
00972   int y = min(TileY(cur_ta.tile), TileY(new_ta.tile));
00973   new_ta.w = max(TileX(cur_ta.tile) + cur_ta.w, TileX(new_ta.tile) + new_ta.w) - x;
00974   new_ta.h = max(TileY(cur_ta.tile) + cur_ta.h, TileY(new_ta.tile) + new_ta.h) - y;
00975   new_ta.tile = TileXY(x, y);
00976 
00977   /* make sure the final size is not too big. */
00978   if (new_ta.w > _settings_game.station.station_spread || new_ta.h > _settings_game.station.station_spread) {
00979     return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
00980   }
00981 
00982   return CommandCost();
00983 }
00984 
00985 static inline byte *CreateSingle(byte *layout, int n)
00986 {
00987   int i = n;
00988   do *layout++ = 0; while (--i);
00989   layout[((n - 1) >> 1) - n] = 2;
00990   return layout;
00991 }
00992 
00993 static inline byte *CreateMulti(byte *layout, int n, byte b)
00994 {
00995   int i = n;
00996   do *layout++ = b; while (--i);
00997   if (n > 4) {
00998     layout[0 - n] = 0;
00999     layout[n - 1 - n] = 0;
01000   }
01001   return layout;
01002 }
01003 
01011 void GetStationLayout(byte *layout, int numtracks, int plat_len, const StationSpec *statspec)
01012 {
01013   if (statspec != NULL && statspec->lengths >= plat_len &&
01014       statspec->platforms[plat_len - 1] >= numtracks &&
01015       statspec->layouts[plat_len - 1][numtracks - 1]) {
01016     /* Custom layout defined, follow it. */
01017     memcpy(layout, statspec->layouts[plat_len - 1][numtracks - 1],
01018       plat_len * numtracks);
01019     return;
01020   }
01021 
01022   if (plat_len == 1) {
01023     CreateSingle(layout, numtracks);
01024   } else {
01025     if (numtracks & 1) layout = CreateSingle(layout, plat_len);
01026     numtracks >>= 1;
01027 
01028     while (--numtracks >= 0) {
01029       layout = CreateMulti(layout, plat_len, 4);
01030       layout = CreateMulti(layout, plat_len, 6);
01031     }
01032   }
01033 }
01034 
01046 template <class T, StringID error_message>
01047 CommandCost FindJoiningBaseStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, T **st)
01048 {
01049   assert(*st == NULL);
01050   bool check_surrounding = true;
01051 
01052   if (_settings_game.station.adjacent_stations) {
01053     if (existing_station != INVALID_STATION) {
01054       if (adjacent && existing_station != station_to_join) {
01055         /* You can't build an adjacent station over the top of one that
01056          * already exists. */
01057         return_cmd_error(error_message);
01058       } else {
01059         /* Extend the current station, and don't check whether it will
01060          * be near any other stations. */
01061         *st = T::GetIfValid(existing_station);
01062         check_surrounding = (*st == NULL);
01063       }
01064     } else {
01065       /* There's no station here. Don't check the tiles surrounding this
01066        * one if the company wanted to build an adjacent station. */
01067       if (adjacent) check_surrounding = false;
01068     }
01069   }
01070 
01071   if (check_surrounding) {
01072     /* Make sure there are no similar stations around us. */
01073     CommandCost ret = GetStationAround(ta, existing_station, st);
01074     if (ret.Failed()) return ret;
01075   }
01076 
01077   /* Distant join */
01078   if (*st == NULL && station_to_join != INVALID_STATION) *st = T::GetIfValid(station_to_join);
01079 
01080   return CommandCost();
01081 }
01082 
01092 static CommandCost FindJoiningStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
01093 {
01094   return FindJoiningBaseStation<Station, STR_ERROR_MUST_REMOVE_RAILWAY_STATION_FIRST>(existing_station, station_to_join, adjacent, ta, st);
01095 }
01096 
01106 CommandCost FindJoiningWaypoint(StationID existing_waypoint, StationID waypoint_to_join, bool adjacent, TileArea ta, Waypoint **wp)
01107 {
01108   return FindJoiningBaseStation<Waypoint, STR_ERROR_MUST_REMOVE_RAILWAYPOINT_FIRST>(existing_waypoint, waypoint_to_join, adjacent, ta, wp);
01109 }
01110 
01128 CommandCost CmdBuildRailStation(TileIndex tile_org, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01129 {
01130   /* Unpack parameters */
01131   RailType rt    = Extract<RailType, 0, 4>(p1);
01132   Axis axis      = Extract<Axis, 4, 1>(p1);
01133   byte numtracks = GB(p1,  8, 8);
01134   byte plat_len  = GB(p1, 16, 8);
01135   bool adjacent  = HasBit(p1, 24);
01136 
01137   StationClassID spec_class = Extract<StationClassID, 0, 8>(p2);
01138   byte spec_index           = GB(p2, 8, 8);
01139   StationID station_to_join = GB(p2, 16, 16);
01140 
01141   /* Does the authority allow this? */
01142   CommandCost ret = CheckIfAuthorityAllowsNewStation(tile_org, flags);
01143   if (ret.Failed()) return ret;
01144 
01145   if (!ValParamRailtype(rt)) return CMD_ERROR;
01146 
01147   /* Check if the given station class is valid */
01148   if ((uint)spec_class >= StationClass::GetClassCount() || spec_class == STAT_CLASS_WAYP) return CMD_ERROR;
01149   if (spec_index >= StationClass::Get(spec_class)->GetSpecCount()) return CMD_ERROR;
01150   if (plat_len == 0 || numtracks == 0) return CMD_ERROR;
01151 
01152   int w_org, h_org;
01153   if (axis == AXIS_X) {
01154     w_org = plat_len;
01155     h_org = numtracks;
01156   } else {
01157     h_org = plat_len;
01158     w_org = numtracks;
01159   }
01160 
01161   bool reuse = (station_to_join != NEW_STATION);
01162   if (!reuse) station_to_join = INVALID_STATION;
01163   bool distant_join = (station_to_join != INVALID_STATION);
01164 
01165   if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
01166 
01167   if (h_org > _settings_game.station.station_spread || w_org > _settings_game.station.station_spread) return CMD_ERROR;
01168 
01169   /* these values are those that will be stored in train_tile and station_platforms */
01170   TileArea new_location(tile_org, w_org, h_org);
01171 
01172   /* Make sure the area below consists of clear tiles. (OR tiles belonging to a certain rail station) */
01173   StationID est = INVALID_STATION;
01174   SmallVector<Train *, 4> affected_vehicles;
01175   /* Clear the land below the station. */
01176   CommandCost cost = CheckFlatLandRailStation(new_location, flags, axis, &est, rt, affected_vehicles, spec_class, spec_index, plat_len, numtracks);
01177   if (cost.Failed()) return cost;
01178   /* Add construction expenses. */
01179   cost.AddCost((numtracks * _price[PR_BUILD_STATION_RAIL] + _price[PR_BUILD_STATION_RAIL_LENGTH]) * plat_len);
01180   cost.AddCost(numtracks * plat_len * RailBuildCost(rt));
01181 
01182   Station *st = NULL;
01183   ret = FindJoiningStation(est, station_to_join, adjacent, new_location, &st);
01184   if (ret.Failed()) return ret;
01185 
01186   ret = BuildStationPart(&st, flags, reuse, new_location, STATIONNAMING_RAIL);
01187   if (ret.Failed()) return ret;
01188 
01189   if (st != NULL && st->train_station.tile != INVALID_TILE) {
01190     CommandCost ret = CanExpandRailStation(st, new_location, axis);
01191     if (ret.Failed()) return ret;
01192   }
01193 
01194   /* Check if we can allocate a custom stationspec to this station */
01195   const StationSpec *statspec = StationClass::Get(spec_class)->GetSpec(spec_index);
01196   int specindex = AllocateSpecToStation(statspec, st, (flags & DC_EXEC) != 0);
01197   if (specindex == -1) return_cmd_error(STR_ERROR_TOO_MANY_STATION_SPECS);
01198 
01199   if (statspec != NULL) {
01200     /* Perform NewStation checks */
01201 
01202     /* Check if the station size is permitted */
01203     if (HasBit(statspec->disallowed_platforms, numtracks - 1) || HasBit(statspec->disallowed_lengths, plat_len - 1)) {
01204       return CMD_ERROR;
01205     }
01206 
01207     /* Check if the station is buildable */
01208     if (HasBit(statspec->callback_mask, CBM_STATION_AVAIL)) {
01209       uint16 cb_res = GetStationCallback(CBID_STATION_AVAILABILITY, 0, 0, statspec, NULL, INVALID_TILE);
01210       if (cb_res != CALLBACK_FAILED && !Convert8bitBooleanCallback(statspec->grf_prop.grffile, CBID_STATION_AVAILABILITY, cb_res)) return CMD_ERROR;
01211     }
01212   }
01213 
01214   if (flags & DC_EXEC) {
01215     TileIndexDiff tile_delta;
01216     byte *layout_ptr;
01217     byte numtracks_orig;
01218     Track track;
01219 
01220     st->train_station = new_location;
01221     st->AddFacility(FACIL_TRAIN, new_location.tile);
01222 
01223     st->rect.BeforeAddRect(tile_org, w_org, h_org, StationRect::ADD_TRY);
01224 
01225     if (statspec != NULL) {
01226       /* Include this station spec's animation trigger bitmask
01227        * in the station's cached copy. */
01228       st->cached_anim_triggers |= statspec->animation.triggers;
01229     }
01230 
01231     tile_delta = (axis == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
01232     track = AxisToTrack(axis);
01233 
01234     layout_ptr = AllocaM(byte, numtracks * plat_len);
01235     GetStationLayout(layout_ptr, numtracks, plat_len, statspec);
01236 
01237     numtracks_orig = numtracks;
01238 
01239     Company *c = Company::Get(st->owner);
01240     do {
01241       TileIndex tile = tile_org;
01242       int w = plat_len;
01243       do {
01244         byte layout = *layout_ptr++;
01245         if (IsRailStationTile(tile) && HasStationReservation(tile)) {
01246           /* Check for trains having a reservation for this tile. */
01247           Train *v = GetTrainForReservation(tile, AxisToTrack(GetRailStationAxis(tile)));
01248           if (v != NULL) {
01249             FreeTrainTrackReservation(v);
01250             *affected_vehicles.Append() = v;
01251             if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), false);
01252             for (; v->Next() != NULL; v = v->Next()) { }
01253             if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), false);
01254           }
01255         }
01256 
01257         /* Railtype can change when overbuilding. */
01258         if (IsRailStationTile(tile)) {
01259           if (!IsStationTileBlocked(tile)) c->infrastructure.rail[GetRailType(tile)]--;
01260           c->infrastructure.station--;
01261         }
01262 
01263         /* Remove animation if overbuilding */
01264         DeleteAnimatedTile(tile);
01265         byte old_specindex = HasStationTileRail(tile) ? GetCustomStationSpecIndex(tile) : 0;
01266         MakeRailStation(tile, st->owner, st->index, axis, layout & ~1, rt);
01267         /* Free the spec if we overbuild something */
01268         DeallocateSpecFromStation(st, old_specindex);
01269 
01270         SetCustomStationSpecIndex(tile, specindex);
01271         SetStationTileRandomBits(tile, GB(Random(), 0, 4));
01272         SetAnimationFrame(tile, 0);
01273 
01274         if (!IsStationTileBlocked(tile)) c->infrastructure.rail[rt]++;
01275         c->infrastructure.station++;
01276 
01277         if (statspec != NULL) {
01278           /* Use a fixed axis for GetPlatformInfo as our platforms / numtracks are always the right way around */
01279           uint32 platinfo = GetPlatformInfo(AXIS_X, 0, plat_len, numtracks_orig, plat_len - w, numtracks_orig - numtracks, false);
01280 
01281           /* As the station is not yet completely finished, the station does not yet exist. */
01282           uint16 callback = GetStationCallback(CBID_STATION_TILE_LAYOUT, platinfo, 0, statspec, NULL, tile);
01283           if (callback != CALLBACK_FAILED) {
01284             if (callback < 8) {
01285               SetStationGfx(tile, (callback & ~1) + axis);
01286             } else {
01287               ErrorUnknownCallbackResult(statspec->grf_prop.grffile->grfid, CBID_STATION_TILE_LAYOUT, callback);
01288             }
01289           }
01290 
01291           /* Trigger station animation -- after building? */
01292           TriggerStationAnimation(st, tile, SAT_BUILT);
01293         }
01294 
01295         tile += tile_delta;
01296       } while (--w);
01297       AddTrackToSignalBuffer(tile_org, track, _current_company);
01298       YapfNotifyTrackLayoutChange(tile_org, track);
01299       tile_org += tile_delta ^ TileDiffXY(1, 1); // perpendicular to tile_delta
01300     } while (--numtracks);
01301 
01302     for (uint i = 0; i < affected_vehicles.Length(); ++i) {
01303       /* Restore reservations of trains. */
01304       Train *v = affected_vehicles[i];
01305       if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
01306       TryPathReserve(v, true, true);
01307       for (; v->Next() != NULL; v = v->Next()) { }
01308       if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), true);
01309     }
01310 
01311     st->MarkTilesDirty(false);
01312     st->UpdateVirtCoord();
01313     UpdateStationAcceptance(st, false);
01314     st->RecomputeIndustriesNear();
01315     InvalidateWindowData(WC_SELECT_STATION, 0, 0);
01316     InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
01317     SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
01318     DirtyCompanyInfrastructureWindows(st->owner);
01319   }
01320 
01321   return cost;
01322 }
01323 
01324 static void MakeRailStationAreaSmaller(BaseStation *st)
01325 {
01326   TileArea ta = st->train_station;
01327 
01328 restart:
01329 
01330   /* too small? */
01331   if (ta.w != 0 && ta.h != 0) {
01332     /* check the left side, x = constant, y changes */
01333     for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(0, i));) {
01334       /* the left side is unused? */
01335       if (++i == ta.h) {
01336         ta.tile += TileDiffXY(1, 0);
01337         ta.w--;
01338         goto restart;
01339       }
01340     }
01341 
01342     /* check the right side, x = constant, y changes */
01343     for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(ta.w - 1, i));) {
01344       /* the right side is unused? */
01345       if (++i == ta.h) {
01346         ta.w--;
01347         goto restart;
01348       }
01349     }
01350 
01351     /* check the upper side, y = constant, x changes */
01352     for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(i, 0));) {
01353       /* the left side is unused? */
01354       if (++i == ta.w) {
01355         ta.tile += TileDiffXY(0, 1);
01356         ta.h--;
01357         goto restart;
01358       }
01359     }
01360 
01361     /* check the lower side, y = constant, x changes */
01362     for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(i, ta.h - 1));) {
01363       /* the left side is unused? */
01364       if (++i == ta.w) {
01365         ta.h--;
01366         goto restart;
01367       }
01368     }
01369   } else {
01370     ta.Clear();
01371   }
01372 
01373   st->train_station = ta;
01374 }
01375 
01386 template <class T>
01387 CommandCost RemoveFromRailBaseStation(TileArea ta, SmallVector<T *, 4> &affected_stations, DoCommandFlag flags, Money removal_cost, bool keep_rail)
01388 {
01389   /* Count of the number of tiles removed */
01390   int quantity = 0;
01391   CommandCost total_cost(EXPENSES_CONSTRUCTION);
01392 
01393   /* Do the action for every tile into the area */
01394   TILE_AREA_LOOP(tile, ta) {
01395     /* Make sure the specified tile is a rail station */
01396     if (!HasStationTileRail(tile)) continue;
01397 
01398     /* If there is a vehicle on ground, do not allow to remove (flood) the tile */
01399     CommandCost ret = EnsureNoVehicleOnGround(tile);
01400     if (ret.Failed()) continue;
01401 
01402     /* Check ownership of station */
01403     T *st = T::GetByTile(tile);
01404     if (st == NULL) continue;
01405 
01406     if (_current_company != OWNER_WATER) {
01407       CommandCost ret = CheckOwnership(st->owner);
01408       if (ret.Failed()) continue;
01409     }
01410 
01411     /* If we reached here, the tile is valid so increase the quantity of tiles we will remove */
01412     quantity++;
01413 
01414     if (keep_rail || IsStationTileBlocked(tile)) {
01415       /* Don't refund the 'steel' of the track when we keep the
01416        *  rail, or when the tile didn't have any rail at all. */
01417       total_cost.AddCost(-_price[PR_CLEAR_RAIL]);
01418     }
01419 
01420     if (flags & DC_EXEC) {
01421       /* read variables before the station tile is removed */
01422       uint specindex = GetCustomStationSpecIndex(tile);
01423       Track track = GetRailStationTrack(tile);
01424       Owner owner = GetTileOwner(tile);
01425       RailType rt = GetRailType(tile);
01426       Train *v = NULL;
01427 
01428       if (HasStationReservation(tile)) {
01429         v = GetTrainForReservation(tile, track);
01430         if (v != NULL) {
01431           /* Free train reservation. */
01432           FreeTrainTrackReservation(v);
01433           if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), false);
01434           Vehicle *temp = v;
01435           for (; temp->Next() != NULL; temp = temp->Next()) { }
01436           if (IsRailStationTile(temp->tile)) SetRailStationPlatformReservation(temp->tile, TrackdirToExitdir(ReverseTrackdir(temp->GetVehicleTrackdir())), false);
01437         }
01438       }
01439 
01440       bool build_rail = keep_rail && !IsStationTileBlocked(tile);
01441       if (!build_rail && !IsStationTileBlocked(tile)) Company::Get(owner)->infrastructure.rail[rt]--;
01442 
01443       DoClearSquare(tile);
01444       DeleteNewGRFInspectWindow(GSF_STATIONS, tile);
01445       if (build_rail) MakeRailNormal(tile, owner, TrackToTrackBits(track), rt);
01446       Company::Get(owner)->infrastructure.station--;
01447       DirtyCompanyInfrastructureWindows(owner);
01448 
01449       st->rect.AfterRemoveTile(st, tile);
01450       AddTrackToSignalBuffer(tile, track, owner);
01451       YapfNotifyTrackLayoutChange(tile, track);
01452 
01453       DeallocateSpecFromStation(st, specindex);
01454 
01455       affected_stations.Include(st);
01456 
01457       if (v != NULL) {
01458         /* Restore station reservation. */
01459         if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
01460         TryPathReserve(v, true, true);
01461         for (; v->Next() != NULL; v = v->Next()) { }
01462         if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), true);
01463       }
01464     }
01465   }
01466 
01467   if (quantity == 0) return_cmd_error(STR_ERROR_THERE_IS_NO_STATION);
01468 
01469   for (T **stp = affected_stations.Begin(); stp != affected_stations.End(); stp++) {
01470     T *st = *stp;
01471 
01472     /* now we need to make the "spanned" area of the railway station smaller
01473      * if we deleted something at the edges.
01474      * we also need to adjust train_tile. */
01475     MakeRailStationAreaSmaller(st);
01476     UpdateStationSignCoord(st);
01477 
01478     /* if we deleted the whole station, delete the train facility. */
01479     if (st->train_station.tile == INVALID_TILE) {
01480       st->facilities &= ~FACIL_TRAIN;
01481       SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
01482       st->UpdateVirtCoord();
01483       DeleteStationIfEmpty(st);
01484     }
01485   }
01486 
01487   total_cost.AddCost(quantity * removal_cost);
01488   return total_cost;
01489 }
01490 
01502 CommandCost CmdRemoveFromRailStation(TileIndex start, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01503 {
01504   TileIndex end = p1 == 0 ? start : p1;
01505   if (start >= MapSize() || end >= MapSize()) return CMD_ERROR;
01506 
01507   TileArea ta(start, end);
01508   SmallVector<Station *, 4> affected_stations;
01509 
01510   CommandCost ret = RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_STATION_RAIL], HasBit(p2, 0));
01511   if (ret.Failed()) return ret;
01512 
01513   /* Do all station specific functions here. */
01514   for (Station **stp = affected_stations.Begin(); stp != affected_stations.End(); stp++) {
01515     Station *st = *stp;
01516 
01517     if (st->train_station.tile == INVALID_TILE) SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
01518     st->MarkTilesDirty(false);
01519     st->RecomputeIndustriesNear();
01520   }
01521 
01522   /* Now apply the rail cost to the number that we deleted */
01523   return ret;
01524 }
01525 
01537 CommandCost CmdRemoveFromRailWaypoint(TileIndex start, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01538 {
01539   TileIndex end = p1 == 0 ? start : p1;
01540   if (start >= MapSize() || end >= MapSize()) return CMD_ERROR;
01541 
01542   TileArea ta(start, end);
01543   SmallVector<Waypoint *, 4> affected_stations;
01544 
01545   return RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_WAYPOINT_RAIL], HasBit(p2, 0));
01546 }
01547 
01548 
01556 template <class T>
01557 CommandCost RemoveRailStation(T *st, DoCommandFlag flags)
01558 {
01559   /* Current company owns the station? */
01560   if (_current_company != OWNER_WATER) {
01561     CommandCost ret = CheckOwnership(st->owner);
01562     if (ret.Failed()) return ret;
01563   }
01564 
01565   /* determine width and height of platforms */
01566   TileArea ta = st->train_station;
01567 
01568   assert(ta.w != 0 && ta.h != 0);
01569 
01570   CommandCost cost(EXPENSES_CONSTRUCTION);
01571   /* clear all areas of the station */
01572   TILE_AREA_LOOP(tile, ta) {
01573     /* only remove tiles that are actually train station tiles */
01574     if (!st->TileBelongsToRailStation(tile)) continue;
01575 
01576     CommandCost ret = EnsureNoVehicleOnGround(tile);
01577     if (ret.Failed()) return ret;
01578 
01579     cost.AddCost(_price[PR_CLEAR_STATION_RAIL]);
01580     if (flags & DC_EXEC) {
01581       /* read variables before the station tile is removed */
01582       Track track = GetRailStationTrack(tile);
01583       Owner owner = GetTileOwner(tile); // _current_company can be OWNER_WATER
01584       Train *v = NULL;
01585       if (HasStationReservation(tile)) {
01586         v = GetTrainForReservation(tile, track);
01587         if (v != NULL) FreeTrainTrackReservation(v);
01588       }
01589       if (!IsStationTileBlocked(tile)) Company::Get(owner)->infrastructure.rail[GetRailType(tile)]--;
01590       Company::Get(owner)->infrastructure.station--;
01591       DoClearSquare(tile);
01592       DeleteNewGRFInspectWindow(GSF_STATIONS, tile);
01593       AddTrackToSignalBuffer(tile, track, owner);
01594       YapfNotifyTrackLayoutChange(tile, track);
01595       if (v != NULL) TryPathReserve(v, true);
01596     }
01597   }
01598 
01599   if (flags & DC_EXEC) {
01600     st->rect.AfterRemoveRect(st, st->train_station);
01601 
01602     st->train_station.Clear();
01603 
01604     st->facilities &= ~FACIL_TRAIN;
01605 
01606     free(st->speclist);
01607     st->num_specs = 0;
01608     st->speclist  = NULL;
01609     st->cached_anim_triggers = 0;
01610 
01611     DirtyCompanyInfrastructureWindows(st->owner);
01612     SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
01613     st->UpdateVirtCoord();
01614     DeleteStationIfEmpty(st);
01615   }
01616 
01617   return cost;
01618 }
01619 
01626 static CommandCost RemoveRailStation(TileIndex tile, DoCommandFlag flags)
01627 {
01628   /* if there is flooding, remove platforms tile by tile */
01629   if (_current_company == OWNER_WATER) {
01630     return DoCommand(tile, 0, 0, DC_EXEC, CMD_REMOVE_FROM_RAIL_STATION);
01631   }
01632 
01633   Station *st = Station::GetByTile(tile);
01634   CommandCost cost = RemoveRailStation(st, flags);
01635 
01636   if (flags & DC_EXEC) st->RecomputeIndustriesNear();
01637 
01638   return cost;
01639 }
01640 
01647 static CommandCost RemoveRailWaypoint(TileIndex tile, DoCommandFlag flags)
01648 {
01649   /* if there is flooding, remove waypoints tile by tile */
01650   if (_current_company == OWNER_WATER) {
01651     return DoCommand(tile, 0, 0, DC_EXEC, CMD_REMOVE_FROM_RAIL_WAYPOINT);
01652   }
01653 
01654   return RemoveRailStation(Waypoint::GetByTile(tile), flags);
01655 }
01656 
01657 
01663 static RoadStop **FindRoadStopSpot(bool truck_station, Station *st)
01664 {
01665   RoadStop **primary_stop = (truck_station) ? &st->truck_stops : &st->bus_stops;
01666 
01667   if (*primary_stop == NULL) {
01668     /* we have no roadstop of the type yet, so write a "primary stop" */
01669     return primary_stop;
01670   } else {
01671     /* there are stops already, so append to the end of the list */
01672     RoadStop *stop = *primary_stop;
01673     while (stop->next != NULL) stop = stop->next;
01674     return &stop->next;
01675   }
01676 }
01677 
01678 static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags);
01679 
01689 static CommandCost FindJoiningRoadStop(StationID existing_stop, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
01690 {
01691   return FindJoiningBaseStation<Station, STR_ERROR_MUST_REMOVE_ROAD_STOP_FIRST>(existing_stop, station_to_join, adjacent, ta, st);
01692 }
01693 
01709 CommandCost CmdBuildRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01710 {
01711   bool type = HasBit(p2, 0);
01712   bool is_drive_through = HasBit(p2, 1);
01713   RoadTypes rts = Extract<RoadTypes, 2, 2>(p2);
01714   StationID station_to_join = GB(p2, 16, 16);
01715   bool reuse = (station_to_join != NEW_STATION);
01716   if (!reuse) station_to_join = INVALID_STATION;
01717   bool distant_join = (station_to_join != INVALID_STATION);
01718 
01719   uint8 width = (uint8)GB(p1, 0, 8);
01720   uint8 lenght = (uint8)GB(p1, 8, 8);
01721 
01722   /* Check if the requested road stop is too big */
01723   if (width > _settings_game.station.station_spread || lenght > _settings_game.station.station_spread) return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
01724   /* Check for incorrect width / length. */
01725   if (width == 0 || lenght == 0) return CMD_ERROR;
01726   /* Check if the first tile and the last tile are valid */
01727   if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, lenght - 1) == INVALID_TILE) return CMD_ERROR;
01728 
01729   TileArea roadstop_area(tile, width, lenght);
01730 
01731   if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
01732 
01733   if (!HasExactlyOneBit(rts) || !HasRoadTypesAvail(_current_company, rts)) return CMD_ERROR;
01734 
01735   /* Trams only have drive through stops */
01736   if (!is_drive_through && HasBit(rts, ROADTYPE_TRAM)) return CMD_ERROR;
01737 
01738   DiagDirection ddir = Extract<DiagDirection, 6, 2>(p2);
01739 
01740   /* Safeguard the parameters. */
01741   if (!IsValidDiagDirection(ddir)) return CMD_ERROR;
01742   /* If it is a drive-through stop, check for valid axis. */
01743   if (is_drive_through && !IsValidAxis((Axis)ddir)) return CMD_ERROR;
01744 
01745   CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
01746   if (ret.Failed()) return ret;
01747 
01748   /* Total road stop cost. */
01749   CommandCost cost(EXPENSES_CONSTRUCTION, roadstop_area.w * roadstop_area.h * _price[type ? PR_BUILD_STATION_TRUCK : PR_BUILD_STATION_BUS]);
01750   StationID est = INVALID_STATION;
01751   ret = CheckFlatLandRoadStop(roadstop_area, flags, is_drive_through ? 5 << ddir : 1 << ddir, is_drive_through, type, DiagDirToAxis(ddir), &est, rts);
01752   if (ret.Failed()) return ret;
01753   cost.AddCost(ret);
01754 
01755   Station *st = NULL;
01756   ret = FindJoiningRoadStop(est, station_to_join, HasBit(p2, 5), roadstop_area, &st);
01757   if (ret.Failed()) return ret;
01758 
01759   /* Check if this number of road stops can be allocated. */
01760   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);
01761 
01762   ret = BuildStationPart(&st, flags, reuse, roadstop_area, STATIONNAMING_ROAD);
01763   if (ret.Failed()) return ret;
01764 
01765   if (flags & DC_EXEC) {
01766     /* Check every tile in the area. */
01767     TILE_AREA_LOOP(cur_tile, roadstop_area) {
01768       RoadTypes cur_rts = GetRoadTypes(cur_tile);
01769       Owner road_owner = HasBit(cur_rts, ROADTYPE_ROAD) ? GetRoadOwner(cur_tile, ROADTYPE_ROAD) : _current_company;
01770       Owner tram_owner = HasBit(cur_rts, ROADTYPE_TRAM) ? GetRoadOwner(cur_tile, ROADTYPE_TRAM) : _current_company;
01771 
01772       if (IsTileType(cur_tile, MP_STATION) && IsRoadStop(cur_tile)) {
01773         RemoveRoadStop(cur_tile, flags);
01774       }
01775 
01776       RoadStop *road_stop = new RoadStop(cur_tile);
01777       /* Insert into linked list of RoadStops. */
01778       RoadStop **currstop = FindRoadStopSpot(type, st);
01779       *currstop = road_stop;
01780 
01781       if (type) {
01782         st->truck_station.Add(cur_tile);
01783       } else {
01784         st->bus_station.Add(cur_tile);
01785       }
01786 
01787       /* Initialize an empty station. */
01788       st->AddFacility((type) ? FACIL_TRUCK_STOP : FACIL_BUS_STOP, cur_tile);
01789 
01790       st->rect.BeforeAddTile(cur_tile, StationRect::ADD_TRY);
01791 
01792       RoadStopType rs_type = type ? ROADSTOP_TRUCK : ROADSTOP_BUS;
01793       if (is_drive_through) {
01794         /* Update company infrastructure counts. If the current tile is a normal
01795          * road tile, count only the new road bits needed to get a full diagonal road. */
01796         RoadType rt;
01797         FOR_EACH_SET_ROADTYPE(rt, cur_rts | rts) {
01798           Company *c = Company::GetIfValid(rt == ROADTYPE_ROAD ? road_owner : tram_owner);
01799           if (c != NULL) {
01800             c->infrastructure.road[rt] += 2 - (IsNormalRoadTile(cur_tile) && HasBit(cur_rts, rt) ? CountBits(GetRoadBits(cur_tile, rt)) : 0);
01801             DirtyCompanyInfrastructureWindows(c->index);
01802           }
01803         }
01804 
01805         MakeDriveThroughRoadStop(cur_tile, st->owner, road_owner, tram_owner, st->index, rs_type, rts | cur_rts, DiagDirToAxis(ddir));
01806         road_stop->MakeDriveThrough();
01807       } else {
01808         /* Non-drive-through stop never overbuild and always count as two road bits. */
01809         Company::Get(st->owner)->infrastructure.road[FIND_FIRST_BIT(rts)] += 2;
01810         MakeRoadStop(cur_tile, st->owner, st->index, rs_type, rts, ddir);
01811       }
01812       Company::Get(st->owner)->infrastructure.station++;
01813       DirtyCompanyInfrastructureWindows(st->owner);
01814 
01815       MarkTileDirtyByTile(cur_tile);
01816     }
01817   }
01818 
01819   if (st != NULL) {
01820     st->UpdateVirtCoord();
01821     UpdateStationAcceptance(st, false);
01822     st->RecomputeIndustriesNear();
01823     InvalidateWindowData(WC_SELECT_STATION, 0, 0);
01824     InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
01825     SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_ROADVEHS);
01826   }
01827   return cost;
01828 }
01829 
01830 
01831 static Vehicle *ClearRoadStopStatusEnum(Vehicle *v, void *)
01832 {
01833   if (v->type == VEH_ROAD) {
01834     /* Okay... we are a road vehicle on a drive through road stop.
01835      * But that road stop has just been removed, so we need to make
01836      * sure we are in a valid state... however, vehicles can also
01837      * turn on road stop tiles, so only clear the 'road stop' state
01838      * bits and only when the state was 'in road stop', otherwise
01839      * we'll end up clearing the turn around bits. */
01840     RoadVehicle *rv = RoadVehicle::From(v);
01841     if (HasBit(rv->state, RVS_IN_DT_ROAD_STOP)) rv->state &= RVSB_ROAD_STOP_TRACKDIR_MASK;
01842   }
01843 
01844   return NULL;
01845 }
01846 
01847 
01854 static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags)
01855 {
01856   Station *st = Station::GetByTile(tile);
01857 
01858   if (_current_company != OWNER_WATER) {
01859     CommandCost ret = CheckOwnership(st->owner);
01860     if (ret.Failed()) return ret;
01861   }
01862 
01863   bool is_truck = IsTruckStop(tile);
01864 
01865   RoadStop **primary_stop;
01866   RoadStop *cur_stop;
01867   if (is_truck) { // truck stop
01868     primary_stop = &st->truck_stops;
01869     cur_stop = RoadStop::GetByTile(tile, ROADSTOP_TRUCK);
01870   } else {
01871     primary_stop = &st->bus_stops;
01872     cur_stop = RoadStop::GetByTile(tile, ROADSTOP_BUS);
01873   }
01874 
01875   assert(cur_stop != NULL);
01876 
01877   /* don't do the check for drive-through road stops when company bankrupts */
01878   if (IsDriveThroughStopTile(tile) && (flags & DC_BANKRUPT)) {
01879     /* remove the 'going through road stop' status from all vehicles on that tile */
01880     if (flags & DC_EXEC) FindVehicleOnPos(tile, NULL, &ClearRoadStopStatusEnum);
01881   } else {
01882     CommandCost ret = EnsureNoVehicleOnGround(tile);
01883     if (ret.Failed()) return ret;
01884   }
01885 
01886   if (flags & DC_EXEC) {
01887     if (*primary_stop == cur_stop) {
01888       /* removed the first stop in the list */
01889       *primary_stop = cur_stop->next;
01890       /* removed the only stop? */
01891       if (*primary_stop == NULL) {
01892         st->facilities &= (is_truck ? ~FACIL_TRUCK_STOP : ~FACIL_BUS_STOP);
01893       }
01894     } else {
01895       /* tell the predecessor in the list to skip this stop */
01896       RoadStop *pred = *primary_stop;
01897       while (pred->next != cur_stop) pred = pred->next;
01898       pred->next = cur_stop->next;
01899     }
01900 
01901     /* Update company infrastructure counts. */
01902     RoadType rt;
01903     FOR_EACH_SET_ROADTYPE(rt, GetRoadTypes(tile)) {
01904       Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
01905       if (c != NULL) {
01906         c->infrastructure.road[rt] -= 2;
01907         DirtyCompanyInfrastructureWindows(c->index);
01908       }
01909     }
01910     Company::Get(st->owner)->infrastructure.station--;
01911 
01912     if (IsDriveThroughStopTile(tile)) {
01913       /* Clears the tile for us */
01914       cur_stop->ClearDriveThrough();
01915     } else {
01916       DoClearSquare(tile);
01917     }
01918 
01919     SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_ROADVEHS);
01920     delete cur_stop;
01921 
01922     /* Make sure no vehicle is going to the old roadstop */
01923     RoadVehicle *v;
01924     FOR_ALL_ROADVEHICLES(v) {
01925       if (v->First() == v && v->current_order.IsType(OT_GOTO_STATION) &&
01926           v->dest_tile == tile) {
01927         v->dest_tile = v->GetOrderStationLocation(st->index);
01928       }
01929     }
01930 
01931     st->rect.AfterRemoveTile(st, tile);
01932 
01933     st->UpdateVirtCoord();
01934     st->RecomputeIndustriesNear();
01935     DeleteStationIfEmpty(st);
01936 
01937     /* Update the tile area of the truck/bus stop */
01938     if (is_truck) {
01939       st->truck_station.Clear();
01940       for (const RoadStop *rs = st->truck_stops; rs != NULL; rs = rs->next) st->truck_station.Add(rs->xy);
01941     } else {
01942       st->bus_station.Clear();
01943       for (const RoadStop *rs = st->bus_stops; rs != NULL; rs = rs->next) st->bus_station.Add(rs->xy);
01944     }
01945   }
01946 
01947   return CommandCost(EXPENSES_CONSTRUCTION, _price[is_truck ? PR_CLEAR_STATION_TRUCK : PR_CLEAR_STATION_BUS]);
01948 }
01949 
01960 CommandCost CmdRemoveRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01961 {
01962   uint8 width = (uint8)GB(p1, 0, 8);
01963   uint8 height = (uint8)GB(p1, 8, 8);
01964 
01965   /* Check for incorrect width / height. */
01966   if (width == 0 || height == 0) return CMD_ERROR;
01967   /* Check if the first tile and the last tile are valid */
01968   if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, height - 1) == INVALID_TILE) return CMD_ERROR;
01969 
01970   TileArea roadstop_area(tile, width, height);
01971 
01972   int quantity = 0;
01973   CommandCost cost(EXPENSES_CONSTRUCTION);
01974   TILE_AREA_LOOP(cur_tile, roadstop_area) {
01975     /* Make sure the specified tile is a road stop of the correct type */
01976     if (!IsTileType(cur_tile, MP_STATION) || !IsRoadStop(cur_tile) || (uint32)GetRoadStopType(cur_tile) != GB(p2, 0, 1)) continue;
01977 
01978     /* Save the stop info before it is removed */
01979     bool is_drive_through = IsDriveThroughStopTile(cur_tile);
01980     RoadTypes rts = GetRoadTypes(cur_tile);
01981     RoadBits road_bits = IsDriveThroughStopTile(cur_tile) ?
01982         ((GetRoadStopDir(cur_tile) == DIAGDIR_NE) ? ROAD_X : ROAD_Y) :
01983         DiagDirToRoadBits(GetRoadStopDir(cur_tile));
01984 
01985     Owner road_owner = GetRoadOwner(cur_tile, ROADTYPE_ROAD);
01986     Owner tram_owner = GetRoadOwner(cur_tile, ROADTYPE_TRAM);
01987     CommandCost ret = RemoveRoadStop(cur_tile, flags);
01988     if (ret.Failed()) return ret;
01989     cost.AddCost(ret);
01990 
01991     quantity++;
01992     /* If the stop was a drive-through stop replace the road */
01993     if ((flags & DC_EXEC) && is_drive_through) {
01994       MakeRoadNormal(cur_tile, road_bits, rts, ClosestTownFromTile(cur_tile, UINT_MAX)->index,
01995           road_owner, tram_owner);
01996 
01997       /* Update company infrastructure counts. */
01998       RoadType rt;
01999       FOR_EACH_SET_ROADTYPE(rt, rts) {
02000         Company *c = Company::GetIfValid(GetRoadOwner(cur_tile, rt));
02001         if (c != NULL) {
02002           c->infrastructure.road[rt] += CountBits(road_bits);
02003           DirtyCompanyInfrastructureWindows(c->index);
02004         }
02005       }
02006     }
02007   }
02008 
02009   if (quantity == 0) return_cmd_error(STR_ERROR_THERE_IS_NO_STATION);
02010 
02011   return cost;
02012 }
02013 
02020 static uint GetMinimalAirportDistanceToTile(TileIterator &it, TileIndex town_tile)
02021 {
02022   uint mindist = UINT_MAX;
02023 
02024   for (TileIndex cur_tile = it; cur_tile != INVALID_TILE; cur_tile = ++it) {
02025     mindist = min(mindist, DistanceManhattan(town_tile, cur_tile));
02026   }
02027 
02028   return mindist;
02029 }
02030 
02040 uint8 GetAirportNoiseLevelForTown(const AirportSpec *as, TileIterator &it, TileIndex town_tile)
02041 {
02042   /* 0 cannot be accounted, and 1 is the lowest that can be reduced from town.
02043    * So no need to go any further*/
02044   if (as->noise_level < 2) return as->noise_level;
02045 
02046   uint distance = GetMinimalAirportDistanceToTile(it, town_tile);
02047 
02048   /* The steps for measuring noise reduction are based on the "magical" (and arbitrary) 8 base distance
02049    * adding the town_council_tolerance 4 times, as a way to graduate, depending of the tolerance.
02050    * Basically, it says that the less tolerant a town is, the bigger the distance before
02051    * an actual decrease can be granted */
02052   uint8 town_tolerance_distance = 8 + (_settings_game.difficulty.town_council_tolerance * 4);
02053 
02054   /* now, we want to have the distance segmented using the distance judged bareable by town
02055    * This will give us the coefficient of reduction the distance provides. */
02056   uint noise_reduction = distance / town_tolerance_distance;
02057 
02058   /* If the noise reduction equals the airport noise itself, don't give it for free.
02059    * Otherwise, simply reduce the airport's level. */
02060   return noise_reduction >= as->noise_level ? 1 : as->noise_level - noise_reduction;
02061 }
02062 
02070 Town *AirportGetNearestTown(const AirportSpec *as, const TileIterator &it)
02071 {
02072   Town *t, *nearest = NULL;
02073   uint add = as->size_x + as->size_y - 2; // GetMinimalAirportDistanceToTile can differ from DistanceManhattan by this much
02074   uint mindist = UINT_MAX - add; // prevent overflow
02075   FOR_ALL_TOWNS(t) {
02076     if (DistanceManhattan(t->xy, it) < mindist + add) { // avoid calling GetMinimalAirportDistanceToTile too often
02077       TileIterator *copy = it.Clone();
02078       uint dist = GetMinimalAirportDistanceToTile(*copy, t->xy);
02079       delete copy;
02080       if (dist < mindist) {
02081         nearest = t;
02082         mindist = dist;
02083       }
02084     }
02085   }
02086 
02087   return nearest;
02088 }
02089 
02090 
02092 void UpdateAirportsNoise()
02093 {
02094   Town *t;
02095   const Station *st;
02096 
02097   FOR_ALL_TOWNS(t) t->noise_reached = 0;
02098 
02099   FOR_ALL_STATIONS(st) {
02100     if (st->airport.tile != INVALID_TILE && st->airport.type != AT_OILRIG) {
02101       const AirportSpec *as = st->airport.GetSpec();
02102       AirportTileIterator it(st);
02103       Town *nearest = AirportGetNearestTown(as, it);
02104       nearest->noise_reached += GetAirportNoiseLevelForTown(as, it, nearest->xy);
02105     }
02106   }
02107 }
02108 
02122 CommandCost CmdBuildAirport(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02123 {
02124   StationID station_to_join = GB(p2, 16, 16);
02125   bool reuse = (station_to_join != NEW_STATION);
02126   if (!reuse) station_to_join = INVALID_STATION;
02127   bool distant_join = (station_to_join != INVALID_STATION);
02128   byte airport_type = GB(p1, 0, 8);
02129   byte layout = GB(p1, 8, 8);
02130 
02131   if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
02132 
02133   if (airport_type >= NUM_AIRPORTS) return CMD_ERROR;
02134 
02135   CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
02136   if (ret.Failed()) return ret;
02137 
02138   /* Check if a valid, buildable airport was chosen for construction */
02139   const AirportSpec *as = AirportSpec::Get(airport_type);
02140   if (!as->IsAvailable() || layout >= as->num_table) return CMD_ERROR;
02141 
02142   Direction rotation = as->rotation[layout];
02143   int w = as->size_x;
02144   int h = as->size_y;
02145   if (rotation == DIR_E || rotation == DIR_W) Swap(w, h);
02146   TileArea airport_area = TileArea(tile, w, h);
02147 
02148   if (w > _settings_game.station.station_spread || h > _settings_game.station.station_spread) {
02149     return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
02150   }
02151 
02152   CommandCost cost = CheckFlatLand(airport_area, flags);
02153   if (cost.Failed()) return cost;
02154 
02155   /* The noise level is the noise from the airport and reduce it to account for the distance to the town center. */
02156   AirportTileTableIterator iter(as->table[layout], tile);
02157   Town *nearest = AirportGetNearestTown(as, iter);
02158   uint newnoise_level = GetAirportNoiseLevelForTown(as, iter, nearest->xy);
02159 
02160   /* Check if local auth would allow a new airport */
02161   StringID authority_refuse_message = STR_NULL;
02162   Town *authority_refuse_town = NULL;
02163 
02164   if (_settings_game.economy.station_noise_level) {
02165     /* do not allow to build a new airport if this raise the town noise over the maximum allowed by town */
02166     if ((nearest->noise_reached + newnoise_level) > nearest->MaxTownNoise()) {
02167       authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_NOISE;
02168       authority_refuse_town = nearest;
02169     }
02170   } else {
02171     Town *t = ClosestTownFromTile(tile, UINT_MAX);
02172     uint num = 0;
02173     const Station *st;
02174     FOR_ALL_STATIONS(st) {
02175       if (st->town == t && (st->facilities & FACIL_AIRPORT) && st->airport.type != AT_OILRIG) num++;
02176     }
02177     if (num >= 2) {
02178       authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_AIRPORT;
02179       authority_refuse_town = t;
02180     }
02181   }
02182 
02183   if (authority_refuse_message != STR_NULL) {
02184     SetDParam(0, authority_refuse_town->index);
02185     return_cmd_error(authority_refuse_message);
02186   }
02187 
02188   Station *st = NULL;
02189   ret = FindJoiningStation(INVALID_STATION, station_to_join, HasBit(p2, 0), airport_area, &st);
02190   if (ret.Failed()) return ret;
02191 
02192   /* Distant join */
02193   if (st == NULL && distant_join) st = Station::GetIfValid(station_to_join);
02194 
02195   ret = BuildStationPart(&st, flags, reuse, airport_area, (GetAirport(airport_type)->flags & AirportFTAClass::AIRPLANES) ? STATIONNAMING_AIRPORT : STATIONNAMING_HELIPORT);
02196   if (ret.Failed()) return ret;
02197 
02198   if (st != NULL && st->airport.tile != INVALID_TILE) {
02199     return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_AIRPORT);
02200   }
02201 
02202   for (AirportTileTableIterator iter(as->table[layout], tile); iter != INVALID_TILE; ++iter) {
02203     cost.AddCost(_price[PR_BUILD_STATION_AIRPORT]);
02204   }
02205 
02206   if (flags & DC_EXEC) {
02207     /* Always add the noise, so there will be no need to recalculate when option toggles */
02208     nearest->noise_reached += newnoise_level;
02209 
02210     st->AddFacility(FACIL_AIRPORT, tile);
02211     st->airport.type = airport_type;
02212     st->airport.layout = layout;
02213     st->airport.flags = 0;
02214     st->airport.rotation = rotation;
02215 
02216     st->rect.BeforeAddRect(tile, w, h, StationRect::ADD_TRY);
02217 
02218     for (AirportTileTableIterator iter(as->table[layout], tile); iter != INVALID_TILE; ++iter) {
02219       MakeAirport(iter, st->owner, st->index, iter.GetStationGfx(), WATER_CLASS_INVALID);
02220       SetStationTileRandomBits(iter, GB(Random(), 0, 4));
02221       st->airport.Add(iter);
02222 
02223       if (AirportTileSpec::Get(GetTranslatedAirportTileID(iter.GetStationGfx()))->animation.status != ANIM_STATUS_NO_ANIMATION) AddAnimatedTile(iter);
02224     }
02225 
02226     /* Only call the animation trigger after all tiles have been built */
02227     for (AirportTileTableIterator iter(as->table[layout], tile); iter != INVALID_TILE; ++iter) {
02228       AirportTileAnimationTrigger(st, iter, AAT_BUILT);
02229     }
02230 
02231     UpdateAirplanesOnNewStation(st);
02232 
02233     Company::Get(st->owner)->infrastructure.airport++;
02234     DirtyCompanyInfrastructureWindows(st->owner);
02235 
02236     st->UpdateVirtCoord();
02237     UpdateStationAcceptance(st, false);
02238     st->RecomputeIndustriesNear();
02239     InvalidateWindowData(WC_SELECT_STATION, 0, 0);
02240     InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
02241     InvalidateWindowData(WC_STATION_VIEW, st->index, -1);
02242 
02243     if (_settings_game.economy.station_noise_level) {
02244       SetWindowDirty(WC_TOWN_VIEW, st->town->index);
02245     }
02246   }
02247 
02248   return cost;
02249 }
02250 
02257 static CommandCost RemoveAirport(TileIndex tile, DoCommandFlag flags)
02258 {
02259   Station *st = Station::GetByTile(tile);
02260 
02261   if (_current_company != OWNER_WATER) {
02262     CommandCost ret = CheckOwnership(st->owner);
02263     if (ret.Failed()) return ret;
02264   }
02265 
02266   tile = st->airport.tile;
02267 
02268   CommandCost cost(EXPENSES_CONSTRUCTION);
02269 
02270   const Aircraft *a;
02271   FOR_ALL_AIRCRAFT(a) {
02272     if (!a->IsNormalAircraft()) continue;
02273     if (a->targetairport == st->index && a->state != FLYING) return CMD_ERROR;
02274   }
02275 
02276   if (flags & DC_EXEC) {
02277     const AirportSpec *as = st->airport.GetSpec();
02278     /* The noise level is the noise from the airport and reduce it to account for the distance to the town center.
02279      * And as for construction, always remove it, even if the setting is not set, in order to avoid the
02280      * need of recalculation */
02281     AirportTileIterator it(st);
02282     Town *nearest = AirportGetNearestTown(as, it);
02283     nearest->noise_reached -= GetAirportNoiseLevelForTown(as, it, nearest->xy);
02284   }
02285 
02286   TILE_AREA_LOOP(tile_cur, st->airport) {
02287     if (!st->TileBelongsToAirport(tile_cur)) continue;
02288 
02289     CommandCost ret = EnsureNoVehicleOnGround(tile_cur);
02290     if (ret.Failed()) return ret;
02291 
02292     cost.AddCost(_price[PR_CLEAR_STATION_AIRPORT]);
02293 
02294     if (flags & DC_EXEC) {
02295       if (IsHangarTile(tile_cur)) OrderBackup::Reset(tile_cur, false);
02296       DeleteAnimatedTile(tile_cur);
02297       DoClearSquare(tile_cur);
02298       DeleteNewGRFInspectWindow(GSF_AIRPORTTILES, tile_cur);
02299     }
02300   }
02301 
02302   if (flags & DC_EXEC) {
02303     /* Clear the persistent storage. */
02304     delete st->airport.psa;
02305 
02306     for (uint i = 0; i < st->airport.GetNumHangars(); ++i) {
02307       DeleteWindowById(
02308         WC_VEHICLE_DEPOT, st->airport.GetHangarTile(i)
02309       );
02310     }
02311 
02312     st->rect.AfterRemoveRect(st, st->airport);
02313 
02314     st->airport.Clear();
02315     st->facilities &= ~FACIL_AIRPORT;
02316 
02317     InvalidateWindowData(WC_STATION_VIEW, st->index, -1);
02318 
02319     if (_settings_game.economy.station_noise_level) {
02320       SetWindowDirty(WC_TOWN_VIEW, st->town->index);
02321     }
02322 
02323     Company::Get(st->owner)->infrastructure.airport--;
02324     DirtyCompanyInfrastructureWindows(st->owner);
02325 
02326     st->UpdateVirtCoord();
02327     st->RecomputeIndustriesNear();
02328     DeleteStationIfEmpty(st);
02329     DeleteNewGRFInspectWindow(GSF_AIRPORTS, st->index);
02330   }
02331 
02332   return cost;
02333 }
02334 
02344 CommandCost CmdOpenCloseAirport(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02345 {
02346   if (!Station::IsValidID(p1)) return CMD_ERROR;
02347   Station *st = Station::Get(p1);
02348 
02349   if (!(st->facilities & FACIL_AIRPORT)) return CMD_ERROR;
02350 
02351   CommandCost ret = CheckOwnership(st->owner);
02352   if (ret.Failed()) return ret;
02353 
02354   if (flags & DC_EXEC) {
02355     st->airport.flags ^= AIRPORT_CLOSED_block;
02356     SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_CLOSE_AIRPORT);
02357   }
02358   return CommandCost();
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   TileArea dock_area = TileArea(tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
02445       _dock_w_chk[direction], _dock_h_chk[direction]);
02446 
02447   /* middle */
02448   Station *st = NULL;
02449   ret = FindJoiningStation(INVALID_STATION, station_to_join, HasBit(p1, 0), dock_area, &st);
02450   if (ret.Failed()) return ret;
02451 
02452   /* Distant join */
02453   if (st == NULL && distant_join) st = Station::GetIfValid(station_to_join);
02454 
02455   ret = BuildStationPart(&st, flags, reuse, dock_area, STATIONNAMING_DOCK);
02456   if (ret.Failed()) return ret;
02457 
02458   if (st != NULL && st->dock_tile != INVALID_TILE) return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_DOCK);
02459 
02460   if (flags & DC_EXEC) {
02461     st->dock_tile = tile;
02462     st->AddFacility(FACIL_DOCK, tile);
02463 
02464     st->rect.BeforeAddRect(dock_area.tile, dock_area.w, dock_area.h, StationRect::ADD_TRY);
02465 
02466     /* If the water part of the dock is on a canal, update infrastructure counts.
02467      * This is needed as we've unconditionally cleared that tile before. */
02468     if (wc == WATER_CLASS_CANAL) {
02469       Company::Get(st->owner)->infrastructure.water++;
02470     }
02471     Company::Get(st->owner)->infrastructure.station += 2;
02472     DirtyCompanyInfrastructureWindows(st->owner);
02473 
02474     MakeDock(tile, st->owner, st->index, direction, wc);
02475 
02476     st->UpdateVirtCoord();
02477     UpdateStationAcceptance(st, false);
02478     st->RecomputeIndustriesNear();
02479     InvalidateWindowData(WC_SELECT_STATION, 0, 0);
02480     InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
02481     SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_SHIPS);
02482   }
02483 
02484   return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_STATION_DOCK]);
02485 }
02486 
02493 static CommandCost RemoveDock(TileIndex tile, DoCommandFlag flags)
02494 {
02495   Station *st = Station::GetByTile(tile);
02496   CommandCost ret = CheckOwnership(st->owner);
02497   if (ret.Failed()) return ret;
02498 
02499   TileIndex docking_location = TILE_ADD(st->dock_tile, ToTileIndexDiff(GetDockOffset(st->dock_tile)));
02500 
02501   TileIndex tile1 = st->dock_tile;
02502   TileIndex tile2 = tile1 + TileOffsByDiagDir(GetDockDirection(tile1));
02503 
02504   ret = EnsureNoVehicleOnGround(tile1);
02505   if (ret.Succeeded()) ret = EnsureNoVehicleOnGround(tile2);
02506   if (ret.Failed()) return ret;
02507 
02508   if (flags & DC_EXEC) {
02509     DoClearSquare(tile1);
02510     MarkTileDirtyByTile(tile1);
02511     MakeWaterKeepingClass(tile2, st->owner);
02512 
02513     st->rect.AfterRemoveTile(st, tile1);
02514     st->rect.AfterRemoveTile(st, tile2);
02515 
02516     st->dock_tile = INVALID_TILE;
02517     st->facilities &= ~FACIL_DOCK;
02518 
02519     Company::Get(st->owner)->infrastructure.station -= 2;
02520     DirtyCompanyInfrastructureWindows(st->owner);
02521 
02522     SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_SHIPS);
02523     st->UpdateVirtCoord();
02524     st->RecomputeIndustriesNear();
02525     DeleteStationIfEmpty(st);
02526 
02527     /* All ships that were going to our station, can't go to it anymore.
02528      * Just clear the order, then automatically the next appropriate order
02529      * will be selected and in case of no appropriate order it will just
02530      * wander around the world. */
02531     Ship *s;
02532     FOR_ALL_SHIPS(s) {
02533       if (s->current_order.IsType(OT_LOADING) && s->tile == docking_location) {
02534         s->LeaveStation();
02535       }
02536 
02537       if (s->dest_tile == docking_location) {
02538         s->dest_tile = 0;
02539         s->current_order.Free();
02540       }
02541     }
02542   }
02543 
02544   return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_STATION_DOCK]);
02545 }
02546 
02547 #include "table/station_land.h"
02548 
02549 const DrawTileSprites *GetStationTileLayout(StationType st, byte gfx)
02550 {
02551   return &_station_display_datas[st][gfx];
02552 }
02553 
02554 static void DrawTile_Station(TileInfo *ti)
02555 {
02556   const NewGRFSpriteLayout *layout = NULL;
02557   DrawTileSprites tmp_rail_layout;
02558   const DrawTileSprites *t = NULL;
02559   RoadTypes roadtypes;
02560   int32 total_offset;
02561   const RailtypeInfo *rti = NULL;
02562   uint32 relocation = 0;
02563   uint32 ground_relocation = 0;
02564   BaseStation *st = NULL;
02565   const StationSpec *statspec = NULL;
02566   uint tile_layout = 0;
02567 
02568   if (HasStationRail(ti->tile)) {
02569     rti = GetRailTypeInfo(GetRailType(ti->tile));
02570     roadtypes = ROADTYPES_NONE;
02571     total_offset = rti->GetRailtypeSpriteOffset();
02572 
02573     if (IsCustomStationSpecIndex(ti->tile)) {
02574       /* look for customization */
02575       st = BaseStation::GetByTile(ti->tile);
02576       statspec = st->speclist[GetCustomStationSpecIndex(ti->tile)].spec;
02577 
02578       if (statspec != NULL) {
02579         tile_layout = GetStationGfx(ti->tile);
02580 
02581         if (HasBit(statspec->callback_mask, CBM_STATION_SPRITE_LAYOUT)) {
02582           uint16 callback = GetStationCallback(CBID_STATION_SPRITE_LAYOUT, 0, 0, statspec, st, ti->tile);
02583           if (callback != CALLBACK_FAILED) tile_layout = (callback & ~1) + GetRailStationAxis(ti->tile);
02584         }
02585 
02586         /* Ensure the chosen tile layout is valid for this custom station */
02587         if (statspec->renderdata != NULL) {
02588           layout = &statspec->renderdata[tile_layout < statspec->tiles ? tile_layout : (uint)GetRailStationAxis(ti->tile)];
02589           if (!layout->NeedsPreprocessing()) {
02590             t = layout;
02591             layout = NULL;
02592           }
02593         }
02594       }
02595     }
02596   } else {
02597     roadtypes = IsRoadStop(ti->tile) ? GetRoadTypes(ti->tile) : ROADTYPES_NONE;
02598     total_offset = 0;
02599   }
02600 
02601   StationGfx gfx = GetStationGfx(ti->tile);
02602   if (IsAirport(ti->tile)) {
02603     gfx = GetAirportGfx(ti->tile);
02604     if (gfx >= NEW_AIRPORTTILE_OFFSET) {
02605       const AirportTileSpec *ats = AirportTileSpec::Get(gfx);
02606       if (ats->grf_prop.spritegroup[0] != NULL && DrawNewAirportTile(ti, Station::GetByTile(ti->tile), gfx, ats)) {
02607         return;
02608       }
02609       /* No sprite group (or no valid one) found, meaning no graphics associated.
02610        * Use the substitute one instead */
02611       assert(ats->grf_prop.subst_id != INVALID_AIRPORTTILE);
02612       gfx = ats->grf_prop.subst_id;
02613     }
02614     switch (gfx) {
02615       case APT_RADAR_GRASS_FENCE_SW:
02616         t = &_station_display_datas_airport_radar_grass_fence_sw[GetAnimationFrame(ti->tile)];
02617         break;
02618       case APT_GRASS_FENCE_NE_FLAG:
02619         t = &_station_display_datas_airport_flag_grass_fence_ne[GetAnimationFrame(ti->tile)];
02620         break;
02621       case APT_RADAR_FENCE_SW:
02622         t = &_station_display_datas_airport_radar_fence_sw[GetAnimationFrame(ti->tile)];
02623         break;
02624       case APT_RADAR_FENCE_NE:
02625         t = &_station_display_datas_airport_radar_fence_ne[GetAnimationFrame(ti->tile)];
02626         break;
02627       case APT_GRASS_FENCE_NE_FLAG_2:
02628         t = &_station_display_datas_airport_flag_grass_fence_ne_2[GetAnimationFrame(ti->tile)];
02629         break;
02630     }
02631   }
02632 
02633   Owner owner = GetTileOwner(ti->tile);
02634 
02635   PaletteID palette;
02636   if (Company::IsValidID(owner)) {
02637     palette = COMPANY_SPRITE_COLOUR(owner);
02638   } else {
02639     /* Some stations are not owner by a company, namely oil rigs */
02640     palette = PALETTE_TO_GREY;
02641   }
02642 
02643   if (layout == NULL && (t == NULL || t->seq == NULL)) t = GetStationTileLayout(GetStationType(ti->tile), gfx);
02644 
02645   /* don't show foundation for docks */
02646   if (ti->tileh != SLOPE_FLAT && !IsDock(ti->tile)) {
02647     if (statspec != NULL && HasBit(statspec->flags, SSF_CUSTOM_FOUNDATIONS)) {
02648       /* Station has custom foundations.
02649        * Check whether the foundation continues beyond the tile's upper sides. */
02650       uint edge_info = 0;
02651       int z;
02652       Slope slope = GetFoundationPixelSlope(ti->tile, &z);
02653       if (!HasFoundationNW(ti->tile, slope, z)) SetBit(edge_info, 0);
02654       if (!HasFoundationNE(ti->tile, slope, z)) SetBit(edge_info, 1);
02655       SpriteID image = GetCustomStationFoundationRelocation(statspec, st, ti->tile, tile_layout, edge_info);
02656 
02657       if (HasBit(statspec->flags, SSF_EXTENDED_FOUNDATIONS)) {
02658         /* Station provides extended foundations. */
02659 
02660         static const uint8 foundation_parts[] = {
02661           0, 0, 0, 0, // Invalid,  Invalid,   Invalid,   SLOPE_SW
02662           0, 1, 2, 3, // Invalid,  SLOPE_EW,  SLOPE_SE,  SLOPE_WSE
02663           0, 4, 5, 6, // Invalid,  SLOPE_NW,  SLOPE_NS,  SLOPE_NWS
02664           7, 8, 9     // SLOPE_NE, SLOPE_ENW, SLOPE_SEN
02665         };
02666 
02667         AddSortableSpriteToDraw(image + foundation_parts[ti->tileh], PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
02668       } else {
02669         /* Draw simple foundations, built up from 8 possible foundation sprites. */
02670 
02671         /* Each set bit represents one of the eight composite sprites to be drawn.
02672          * 'Invalid' entries will not drawn but are included for completeness. */
02673         static const uint8 composite_foundation_parts[] = {
02674           /* Invalid  (00000000), Invalid   (11010001), Invalid   (11100100), SLOPE_SW  (11100000) */
02675              0x00,                0xD1,                 0xE4,                 0xE0,
02676           /* Invalid  (11001010), SLOPE_EW  (11001001), SLOPE_SE  (11000100), SLOPE_WSE (11000000) */
02677              0xCA,                0xC9,                 0xC4,                 0xC0,
02678           /* Invalid  (11010010), SLOPE_NW  (10010001), SLOPE_NS  (11100100), SLOPE_NWS (10100000) */
02679              0xD2,                0x91,                 0xE4,                 0xA0,
02680           /* SLOPE_NE (01001010), SLOPE_ENW (00001001), SLOPE_SEN (01000100) */
02681              0x4A,                0x09,                 0x44
02682         };
02683 
02684         uint8 parts = composite_foundation_parts[ti->tileh];
02685 
02686         /* If foundations continue beyond the tile's upper sides then
02687          * mask out the last two pieces. */
02688         if (HasBit(edge_info, 0)) ClrBit(parts, 6);
02689         if (HasBit(edge_info, 1)) ClrBit(parts, 7);
02690 
02691         if (parts == 0) {
02692           /* We always have to draw at least one sprite to make sure there is a boundingbox and a sprite with the
02693            * correct offset for the childsprites.
02694            * So, draw the (completely empty) sprite of the default foundations. */
02695           goto draw_default_foundation;
02696         }
02697 
02698         StartSpriteCombine();
02699         for (int i = 0; i < 8; i++) {
02700           if (HasBit(parts, i)) {
02701             AddSortableSpriteToDraw(image + i, PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
02702           }
02703         }
02704         EndSpriteCombine();
02705       }
02706 
02707       OffsetGroundSprite(31, 1);
02708       ti->z += ApplyPixelFoundationToSlope(FOUNDATION_LEVELED, &ti->tileh);
02709     } else {
02710 draw_default_foundation:
02711       DrawFoundation(ti, FOUNDATION_LEVELED);
02712     }
02713   }
02714 
02715   if (IsBuoy(ti->tile)) {
02716     DrawWaterClassGround(ti);
02717     SpriteID sprite = GetCanalSprite(CF_BUOY, ti->tile);
02718     if (sprite != 0) total_offset = sprite - SPR_IMG_BUOY;
02719   } else if (IsDock(ti->tile) || (IsOilRig(ti->tile) && IsTileOnWater(ti->tile))) {
02720     if (ti->tileh == SLOPE_FLAT) {
02721       DrawWaterClassGround(ti);
02722     } else {
02723       assert(IsDock(ti->tile));
02724       TileIndex water_tile = ti->tile + TileOffsByDiagDir(GetDockDirection(ti->tile));
02725       WaterClass wc = GetWaterClass(water_tile);
02726       if (wc == WATER_CLASS_SEA) {
02727         DrawShoreTile(ti->tileh);
02728       } else {
02729         DrawClearLandTile(ti, 3);
02730       }
02731     }
02732   } else {
02733     if (layout != NULL) {
02734       /* Sprite layout which needs preprocessing */
02735       bool separate_ground = HasBit(statspec->flags, SSF_SEPARATE_GROUND);
02736       uint32 var10_values = layout->PrepareLayout(total_offset, rti->fallback_railtype, 0, 0, separate_ground);
02737       uint8 var10;
02738       FOR_EACH_SET_BIT(var10, var10_values) {
02739         uint32 var10_relocation = GetCustomStationRelocation(statspec, st, ti->tile, var10);
02740         layout->ProcessRegisters(var10, var10_relocation, separate_ground);
02741       }
02742       tmp_rail_layout.seq = layout->GetLayout(&tmp_rail_layout.ground);
02743       t = &tmp_rail_layout;
02744       total_offset = 0;
02745     } else if (statspec != NULL) {
02746       /* Simple sprite layout */
02747       ground_relocation = relocation = GetCustomStationRelocation(statspec, st, ti->tile, 0);
02748       if (HasBit(statspec->flags, SSF_SEPARATE_GROUND)) {
02749         ground_relocation = GetCustomStationRelocation(statspec, st, ti->tile, 1);
02750       }
02751       ground_relocation += rti->fallback_railtype;
02752     }
02753 
02754     SpriteID image = t->ground.sprite;
02755     PaletteID pal  = t->ground.pal;
02756     if (rti != NULL && rti->UsesOverlay() && (image == SPR_RAIL_TRACK_X || image == SPR_RAIL_TRACK_Y)) {
02757       SpriteID ground = GetCustomRailSprite(rti, ti->tile, RTSG_GROUND);
02758       DrawGroundSprite(SPR_FLAT_GRASS_TILE, PAL_NONE);
02759       DrawGroundSprite(ground + (image == SPR_RAIL_TRACK_X ? RTO_X : RTO_Y), PAL_NONE);
02760 
02761       if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationReservation(ti->tile)) {
02762         SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
02763         DrawGroundSprite(overlay + (image == SPR_RAIL_TRACK_X ? RTO_X : RTO_Y), PALETTE_CRASH);
02764       }
02765     } else {
02766       image += HasBit(image, SPRITE_MODIFIER_CUSTOM_SPRITE) ? ground_relocation : total_offset;
02767       if (HasBit(pal, SPRITE_MODIFIER_CUSTOM_SPRITE)) pal += ground_relocation;
02768       DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, palette));
02769 
02770       /* PBS debugging, draw reserved tracks darker */
02771       if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationRail(ti->tile) && HasStationReservation(ti->tile)) {
02772         const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
02773         DrawGroundSprite(GetRailStationAxis(ti->tile) == AXIS_X ? rti->base_sprites.single_x : rti->base_sprites.single_y, PALETTE_CRASH);
02774       }
02775     }
02776   }
02777 
02778   if (HasStationRail(ti->tile) && HasCatenaryDrawn(GetRailType(ti->tile))) DrawCatenary(ti);
02779 
02780   if (HasBit(roadtypes, ROADTYPE_TRAM)) {
02781     Axis axis = GetRoadStopDir(ti->tile) == DIAGDIR_NE ? AXIS_X : AXIS_Y;
02782     DrawGroundSprite((HasBit(roadtypes, ROADTYPE_ROAD) ? SPR_TRAMWAY_OVERLAY : SPR_TRAMWAY_TRAM) + (axis ^ 1), PAL_NONE);
02783     DrawTramCatenary(ti, axis == AXIS_X ? ROAD_X : ROAD_Y);
02784   }
02785 
02786   if (IsRailWaypoint(ti->tile)) {
02787     /* Don't offset the waypoint graphics; they're always the same. */
02788     total_offset = 0;
02789   }
02790 
02791   DrawRailTileSeq(ti, t, TO_BUILDINGS, total_offset, relocation, palette);
02792 }
02793 
02794 void StationPickerDrawSprite(int x, int y, StationType st, RailType railtype, RoadType roadtype, int image)
02795 {
02796   int32 total_offset = 0;
02797   PaletteID pal = COMPANY_SPRITE_COLOUR(_local_company);
02798   const DrawTileSprites *t = GetStationTileLayout(st, image);
02799   const RailtypeInfo *rti = NULL;
02800 
02801   if (railtype != INVALID_RAILTYPE) {
02802     rti = GetRailTypeInfo(railtype);
02803     total_offset = rti->GetRailtypeSpriteOffset();
02804   }
02805 
02806   SpriteID img = t->ground.sprite;
02807   if ((img == SPR_RAIL_TRACK_X || img == SPR_RAIL_TRACK_Y) && rti->UsesOverlay()) {
02808     SpriteID ground = GetCustomRailSprite(rti, INVALID_TILE, RTSG_GROUND);
02809     DrawSprite(SPR_FLAT_GRASS_TILE, PAL_NONE, x, y);
02810     DrawSprite(ground + (img == SPR_RAIL_TRACK_X ? RTO_X : RTO_Y), PAL_NONE, x, y);
02811   } else {
02812     DrawSprite(img + total_offset, HasBit(img, PALETTE_MODIFIER_COLOUR) ? pal : PAL_NONE, x, y);
02813   }
02814 
02815   if (roadtype == ROADTYPE_TRAM) {
02816     DrawSprite(SPR_TRAMWAY_TRAM + (t->ground.sprite == SPR_ROAD_PAVED_STRAIGHT_X ? 1 : 0), PAL_NONE, x, y);
02817   }
02818 
02819   /* Default waypoint has no railtype specific sprites */
02820   DrawRailTileSeqInGUI(x, y, t, st == STATION_WAYPOINT ? 0 : total_offset, 0, pal);
02821 }
02822 
02823 static int GetSlopePixelZ_Station(TileIndex tile, uint x, uint y)
02824 {
02825   return GetTileMaxPixelZ(tile);
02826 }
02827 
02828 static Foundation GetFoundation_Station(TileIndex tile, Slope tileh)
02829 {
02830   return FlatteningFoundation(tileh);
02831 }
02832 
02833 static void GetTileDesc_Station(TileIndex tile, TileDesc *td)
02834 {
02835   td->owner[0] = GetTileOwner(tile);
02836   if (IsDriveThroughStopTile(tile)) {
02837     Owner road_owner = INVALID_OWNER;
02838     Owner tram_owner = INVALID_OWNER;
02839     RoadTypes rts = GetRoadTypes(tile);
02840     if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
02841     if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
02842 
02843     /* Is there a mix of owners? */
02844     if ((tram_owner != INVALID_OWNER && tram_owner != td->owner[0]) ||
02845         (road_owner != INVALID_OWNER && road_owner != td->owner[0])) {
02846       uint i = 1;
02847       if (road_owner != INVALID_OWNER) {
02848         td->owner_type[i] = STR_LAND_AREA_INFORMATION_ROAD_OWNER;
02849         td->owner[i] = road_owner;
02850         i++;
02851       }
02852       if (tram_owner != INVALID_OWNER) {
02853         td->owner_type[i] = STR_LAND_AREA_INFORMATION_TRAM_OWNER;
02854         td->owner[i] = tram_owner;
02855       }
02856     }
02857   }
02858   td->build_date = BaseStation::GetByTile(tile)->build_date;
02859 
02860   if (HasStationTileRail(tile)) {
02861     const StationSpec *spec = GetStationSpec(tile);
02862 
02863     if (spec != NULL) {
02864       td->station_class = StationClass::Get(spec->cls_id)->name;
02865       td->station_name  = spec->name;
02866 
02867       if (spec->grf_prop.grffile != NULL) {
02868         const GRFConfig *gc = GetGRFConfig(spec->grf_prop.grffile->grfid);
02869         td->grf = gc->GetName();
02870       }
02871     }
02872 
02873     const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(tile));
02874     td->rail_speed = rti->max_speed;
02875   }
02876 
02877   if (IsAirport(tile)) {
02878     const AirportSpec *as = Station::GetByTile(tile)->airport.GetSpec();
02879     td->airport_class = AirportClass::Get(as->cls_id)->name;
02880     td->airport_name = as->name;
02881 
02882     const AirportTileSpec *ats = AirportTileSpec::GetByTile(tile);
02883     td->airport_tile_name = ats->name;
02884 
02885     if (as->grf_prop.grffile != NULL) {
02886       const GRFConfig *gc = GetGRFConfig(as->grf_prop.grffile->grfid);
02887       td->grf = gc->GetName();
02888     } else if (ats->grf_prop.grffile != NULL) {
02889       const GRFConfig *gc = GetGRFConfig(ats->grf_prop.grffile->grfid);
02890       td->grf = gc->GetName();
02891     }
02892   }
02893 
02894   StringID str;
02895   switch (GetStationType(tile)) {
02896     default: NOT_REACHED();
02897     case STATION_RAIL:     str = STR_LAI_STATION_DESCRIPTION_RAILROAD_STATION; break;
02898     case STATION_AIRPORT:
02899       str = (IsHangar(tile) ? STR_LAI_STATION_DESCRIPTION_AIRCRAFT_HANGAR : STR_LAI_STATION_DESCRIPTION_AIRPORT);
02900       break;
02901     case STATION_TRUCK:    str = STR_LAI_STATION_DESCRIPTION_TRUCK_LOADING_AREA; break;
02902     case STATION_BUS:      str = STR_LAI_STATION_DESCRIPTION_BUS_STATION; break;
02903     case STATION_OILRIG:   str = STR_INDUSTRY_NAME_OIL_RIG; break;
02904     case STATION_DOCK:     str = STR_LAI_STATION_DESCRIPTION_SHIP_DOCK; break;
02905     case STATION_BUOY:     str = STR_LAI_STATION_DESCRIPTION_BUOY; break;
02906     case STATION_WAYPOINT: str = STR_LAI_STATION_DESCRIPTION_WAYPOINT; break;
02907   }
02908   td->str = str;
02909 }
02910 
02911 
02912 static TrackStatus GetTileTrackStatus_Station(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
02913 {
02914   TrackBits trackbits = TRACK_BIT_NONE;
02915 
02916   switch (mode) {
02917     case TRANSPORT_RAIL:
02918       if (HasStationRail(tile) && !IsStationTileBlocked(tile)) {
02919         trackbits = TrackToTrackBits(GetRailStationTrack(tile));
02920       }
02921       break;
02922 
02923     case TRANSPORT_WATER:
02924       /* buoy is coded as a station, it is always on open water */
02925       if (IsBuoy(tile)) {
02926         trackbits = TRACK_BIT_ALL;
02927         /* remove tracks that connect NE map edge */
02928         if (TileX(tile) == 0) trackbits &= ~(TRACK_BIT_X | TRACK_BIT_UPPER | TRACK_BIT_RIGHT);
02929         /* remove tracks that connect NW map edge */
02930         if (TileY(tile) == 0) trackbits &= ~(TRACK_BIT_Y | TRACK_BIT_LEFT | TRACK_BIT_UPPER);
02931       }
02932       break;
02933 
02934     case TRANSPORT_ROAD:
02935       if ((GetRoadTypes(tile) & sub_mode) != 0 && IsRoadStop(tile)) {
02936         DiagDirection dir = GetRoadStopDir(tile);
02937         Axis axis = DiagDirToAxis(dir);
02938 
02939         if (side != INVALID_DIAGDIR) {
02940           if (axis != DiagDirToAxis(side) || (IsStandardRoadStopTile(tile) && dir != side)) break;
02941         }
02942 
02943         trackbits = AxisToTrackBits(axis);
02944       }
02945       break;
02946 
02947     default:
02948       break;
02949   }
02950 
02951   return CombineTrackStatus(TrackBitsToTrackdirBits(trackbits), TRACKDIR_BIT_NONE);
02952 }
02953 
02954 
02955 static void TileLoop_Station(TileIndex tile)
02956 {
02957   /* FIXME -- GetTileTrackStatus_Station -> animated stationtiles
02958    * hardcoded.....not good */
02959   switch (GetStationType(tile)) {
02960     case STATION_AIRPORT:
02961       AirportTileAnimationTrigger(Station::GetByTile(tile), tile, AAT_TILELOOP);
02962       break;
02963 
02964     case STATION_DOCK:
02965       if (GetTileSlope(tile) != SLOPE_FLAT) break; // only handle water part
02966       /* FALL THROUGH */
02967     case STATION_OILRIG: //(station part)
02968     case STATION_BUOY:
02969       TileLoop_Water(tile);
02970       break;
02971 
02972     default: break;
02973   }
02974 }
02975 
02976 
02977 static void AnimateTile_Station(TileIndex tile)
02978 {
02979   if (HasStationRail(tile)) {
02980     AnimateStationTile(tile);
02981     return;
02982   }
02983 
02984   if (IsAirport(tile)) {
02985     AnimateAirportTile(tile);
02986   }
02987 }
02988 
02989 
02990 static bool ClickTile_Station(TileIndex tile)
02991 {
02992   const BaseStation *bst = BaseStation::GetByTile(tile);
02993 
02994   if (bst->facilities & FACIL_WAYPOINT) {
02995     ShowWaypointWindow(Waypoint::From(bst));
02996   } else if (IsHangar(tile)) {
02997     const Station *st = Station::From(bst);
02998     ShowDepotWindow(st->airport.GetHangarTile(st->airport.GetHangarNum(tile)), VEH_AIRCRAFT);
02999   } else {
03000     ShowStationViewWindow(bst->index);
03001   }
03002   return true;
03003 }
03004 
03005 static VehicleEnterTileStatus VehicleEnter_Station(Vehicle *v, TileIndex tile, int x, int y)
03006 {
03007   if (v->type == VEH_TRAIN) {
03008     StationID station_id = GetStationIndex(tile);
03009     if (!v->current_order.ShouldStopAtStation(v, station_id)) return VETSB_CONTINUE;
03010     if (!IsRailStation(tile) || !v->IsFrontEngine()) return VETSB_CONTINUE;
03011 
03012     int station_ahead;
03013     int station_length;
03014     int stop = GetTrainStopLocation(station_id, tile, Train::From(v), &station_ahead, &station_length);
03015 
03016     /* Stop whenever that amount of station ahead + the distance from the
03017      * begin of the platform to the stop location is longer than the length
03018      * of the platform. Station ahead 'includes' the current tile where the
03019      * vehicle is on, so we need to substract that. */
03020     if (!IsInsideBS(stop + station_ahead, station_length, TILE_SIZE)) return VETSB_CONTINUE;
03021 
03022     DiagDirection dir = DirToDiagDir(v->direction);
03023 
03024     x &= 0xF;
03025     y &= 0xF;
03026 
03027     if (DiagDirToAxis(dir) != AXIS_X) Swap(x, y);
03028     if (y == TILE_SIZE / 2) {
03029       if (dir != DIAGDIR_SE && dir != DIAGDIR_SW) x = TILE_SIZE - 1 - x;
03030       stop &= TILE_SIZE - 1;
03031 
03032       if (x == stop) return VETSB_ENTERED_STATION | (VehicleEnterTileStatus)(station_id << VETS_STATION_ID_OFFSET); // enter station
03033       if (x < stop) {
03034         uint16 spd;
03035 
03036         v->vehstatus |= VS_TRAIN_SLOWING;
03037         spd = max(0, (stop - x) * 20 - 15);
03038         if (spd < v->cur_speed) v->cur_speed = spd;
03039       }
03040     }
03041   } else if (v->type == VEH_ROAD) {
03042     RoadVehicle *rv = RoadVehicle::From(v);
03043     if (rv->state < RVSB_IN_ROAD_STOP && !IsReversingRoadTrackdir((Trackdir)rv->state) && rv->frame == 0) {
03044       if (IsRoadStop(tile) && rv->IsFrontEngine()) {
03045         /* Attempt to allocate a parking bay in a road stop */
03046         return RoadStop::GetByTile(tile, GetRoadStopType(tile))->Enter(rv) ? VETSB_CONTINUE : VETSB_CANNOT_ENTER;
03047       }
03048     }
03049   }
03050 
03051   return VETSB_CONTINUE;
03052 }
03053 
03058 void TriggerWatchedCargoCallbacks(Station *st)
03059 {
03060   /* Collect cargoes accepted since the last big tick. */
03061   uint cargoes = 0;
03062   for (CargoID cid = 0; cid < NUM_CARGO; cid++) {
03063     if (HasBit(st->goods[cid].acceptance_pickup, GoodsEntry::GES_ACCEPTED_BIGTICK)) SetBit(cargoes, cid);
03064   }
03065 
03066   /* Anything to do? */
03067   if (cargoes == 0) return;
03068 
03069   /* Loop over all houses in the catchment. */
03070   Rect r = st->GetCatchmentRect();
03071   TileArea ta(TileXY(r.left, r.top), TileXY(r.right, r.bottom));
03072   TILE_AREA_LOOP(tile, ta) {
03073     if (IsTileType(tile, MP_HOUSE)) {
03074       WatchedCargoCallback(tile, cargoes);
03075     }
03076   }
03077 }
03078 
03085 static bool StationHandleBigTick(BaseStation *st)
03086 {
03087   if (!st->IsInUse()) {
03088     if (++st->delete_ctr >= 8) delete st;
03089     return false;
03090   }
03091 
03092   if (Station::IsExpected(st)) {
03093     TriggerWatchedCargoCallbacks(Station::From(st));
03094 
03095     for (CargoID i = 0; i < NUM_CARGO; i++) {
03096       ClrBit(Station::From(st)->goods[i].acceptance_pickup, GoodsEntry::GES_ACCEPTED_BIGTICK);
03097     }
03098   }
03099 
03100 
03101   if ((st->facilities & FACIL_WAYPOINT) == 0) UpdateStationAcceptance(Station::From(st), true);
03102 
03103   return true;
03104 }
03105 
03106 static inline void byte_inc_sat(byte *p)
03107 {
03108   byte b = *p + 1;
03109   if (b != 0) *p = b;
03110 }
03111 
03112 static void UpdateStationRating(Station *st)
03113 {
03114   bool waiting_changed = false;
03115 
03116   byte_inc_sat(&st->time_since_load);
03117   byte_inc_sat(&st->time_since_unload);
03118 
03119   const CargoSpec *cs;
03120   FOR_ALL_CARGOSPECS(cs) {
03121     GoodsEntry *ge = &st->goods[cs->Index()];
03122     /* Slowly increase the rating back to his original level in the case we
03123      *  didn't deliver cargo yet to this station. This happens when a bribe
03124      *  failed while you didn't moved that cargo yet to a station. */
03125     if (!HasBit(ge->acceptance_pickup, GoodsEntry::GES_PICKUP) && ge->rating < INITIAL_STATION_RATING) {
03126       ge->rating++;
03127     }
03128 
03129     /* Only change the rating if we are moving this cargo */
03130     if (HasBit(ge->acceptance_pickup, GoodsEntry::GES_PICKUP)) {
03131       byte_inc_sat(&ge->days_since_pickup);
03132 
03133       bool skip = false;
03134       int rating = 0;
03135       uint waiting = ge->cargo.Count();
03136 
03137       /* num_dests is at least 1 if there is any cargo as
03138        * INVALID_STATION is also a destination.
03139        */
03140       uint num_dests = (uint)ge->cargo.Packets()->MapSize();
03141 
03142       /* Average amount of cargo per next hop, but prefer solitary stations
03143        * with only one or two next hops. They are allowed to have more
03144        * cargo waiting per next hop.
03145        * With manual cargo distribution waiting_avg = waiting / 2 as then
03146        * INVALID_STATION is the only destination.
03147        */
03148       uint waiting_avg = waiting / (num_dests + 1);
03149 
03150       if (HasBit(cs->callback_mask, CBM_CARGO_STATION_RATING_CALC)) {
03151         /* Perform custom station rating. If it succeeds the speed, days in transit and
03152          * waiting cargo ratings must not be executed. */
03153 
03154         /* NewGRFs expect last speed to be 0xFF when no vehicle has arrived yet. */
03155         uint last_speed = ge->last_speed;
03156         if (last_speed == 0) last_speed = 0xFF;
03157 
03158         uint32 var18 = min(ge->days_since_pickup, 0xFF) | (min(ge->max_waiting_cargo, 0xFFFF) << 8) | (min(last_speed, 0xFF) << 24);
03159         /* Convert to the 'old' vehicle types */
03160         uint32 var10 = (st->last_vehicle_type == VEH_INVALID) ? 0x0 : (st->last_vehicle_type + 0x10);
03161         uint16 callback = GetCargoCallback(CBID_CARGO_STATION_RATING_CALC, var10, var18, cs);
03162         if (callback != CALLBACK_FAILED) {
03163           skip = true;
03164           rating = GB(callback, 0, 14);
03165 
03166           /* Simulate a 15 bit signed value */
03167           if (HasBit(callback, 14)) rating -= 0x4000;
03168         }
03169       }
03170 
03171       if (!skip) {
03172         int b = ge->last_speed - 85;
03173         if (b >= 0) rating += b >> 2;
03174 
03175         byte days = ge->days_since_pickup;
03176         if (st->last_vehicle_type == VEH_SHIP) days >>= 2;
03177         (days > 21) ||
03178         (rating += 25, days > 12) ||
03179         (rating += 25, days > 6) ||
03180         (rating += 45, days > 3) ||
03181         (rating += 35, true);
03182 
03183         (rating -= 90, ge->max_waiting_cargo > 1500) ||
03184         (rating += 55, ge->max_waiting_cargo > 1000) ||
03185         (rating += 35, ge->max_waiting_cargo > 600) ||
03186         (rating += 10, ge->max_waiting_cargo > 300) ||
03187         (rating += 20, ge->max_waiting_cargo > 100) ||
03188         (rating += 10, true);
03189       }
03190 
03191       if (Company::IsValidID(st->owner) && HasBit(st->town->statues, st->owner)) rating += 26;
03192 
03193       byte age = ge->last_age;
03194       (age >= 3) ||
03195       (rating += 10, age >= 2) ||
03196       (rating += 10, age >= 1) ||
03197       (rating += 13, true);
03198 
03199       {
03200         int or_ = ge->rating; // old rating
03201 
03202         /* only modify rating in steps of -2, -1, 0, 1 or 2 */
03203         ge->rating = rating = or_ + Clamp(Clamp(rating, 0, 255) - or_, -2, 2);
03204 
03205         /* if rating is <= 64 and more than 100 items waiting on average per destination,
03206          * remove some random amount of goods from the station */
03207         if (rating <= 64 && waiting_avg >= 100) {
03208           int dec = Random() & 0x1F;
03209           if (waiting_avg < 200) dec &= 7;
03210           waiting -= (dec + 1) * num_dests;
03211           waiting_changed = true;
03212         }
03213 
03214         /* if rating is <= 127 and there are any items waiting, maybe remove some goods. */
03215         if (rating <= 127 && waiting != 0) {
03216           uint32 r = Random();
03217           if (rating <= (int)GB(r, 0, 7)) {
03218             /* Need to have int, otherwise it will just overflow etc. */
03219             waiting = max((int)waiting - (int)((GB(r, 8, 2) - 1) * num_dests), 0);
03220             waiting_changed = true;
03221           }
03222         }
03223 
03224         /* At some point we really must cap the cargo. Previously this
03225          * was a strict 4095, but now we'll have a less strict, but
03226          * increasingly agressive truncation of the amount of cargo. */
03227         static const uint WAITING_CARGO_THRESHOLD  = 1 << 12;
03228         static const uint WAITING_CARGO_CUT_FACTOR = 1 <<  6;
03229         static const uint MAX_WAITING_CARGO        = 1 << 15;
03230 
03231         if (waiting > WAITING_CARGO_THRESHOLD) {
03232           uint difference = waiting - WAITING_CARGO_THRESHOLD;
03233           waiting -= (difference / WAITING_CARGO_CUT_FACTOR);
03234 
03235           waiting = min(waiting, MAX_WAITING_CARGO);
03236           waiting_changed = true;
03237         }
03238 
03239         if (waiting_changed) {
03240           /* feed back the exact own waiting cargo at this station for the
03241            * next rating calculation.
03242            */
03243           ge->max_waiting_cargo = 0;
03244 
03245           /* If truncating also punish the source stations' ratings to
03246            * decrease the flow of incoming cargo. */
03247 
03248           StationCargoAmountMap waiting_per_source;
03249           ge->cargo.CountAndTruncate(waiting, waiting_per_source);
03250           for (StationCargoAmountMap::iterator i(waiting_per_source.begin()); i != waiting_per_source.end(); ++i) {
03251             Station *source_station = Station::GetIfValid(i->first);
03252             if (source_station == NULL) continue;
03253 
03254             GoodsEntry &source_ge = source_station->goods[cs->Index()];
03255             source_ge.max_waiting_cargo = max(source_ge.max_waiting_cargo, i->second);
03256           }
03257         } else {
03258           /* if the average number per next hop is low, be more forgiving. */
03259           ge->max_waiting_cargo = waiting_avg;
03260         }
03261       }
03262     }
03263   }
03264 
03265   StationID index = st->index;
03266   if (waiting_changed) {
03267     SetWindowDirty(WC_STATION_VIEW, index); // update whole window
03268   } else {
03269     SetWindowWidgetDirty(WC_STATION_VIEW, index, WID_SV_ACCEPT_RATING_LIST); // update only ratings list
03270   }
03271 }
03272 
03279 void DeleteStaleFlows(StationID at, CargoID c_id, StationID to)
03280 {
03281   FlowStatMap &flows = Station::Get(at)->goods[c_id].flows;
03282   for (FlowStatMap::iterator f_it = flows.begin(); f_it != flows.end();) {
03283     FlowStat &s_flows = f_it->second;
03284     s_flows.EraseShare(to);
03285     if (s_flows.GetShares()->empty()) {
03286       flows.erase(f_it++);
03287     } else {
03288       ++f_it;
03289     }
03290   }
03291 }
03292 
03299 uint GetMovingAverageLength(const Station *from, const Station *to)
03300 {
03301   return LinkStat::MIN_AVERAGE_LENGTH + (DistanceManhattan(from->xy, to->xy) >> 2);
03302 }
03303 
03307 void Station::RunAverages()
03308 {
03309   for (int goods_index = 0; goods_index < NUM_CARGO; ++goods_index) {
03310     LinkStatMap &links = this->goods[goods_index].link_stats;
03311     for (LinkStatMap::iterator i = links.begin(); i != links.end();) {
03312       StationID id = i->first;
03313       if (Station::IsValidID(id)) {
03314         i->second.Decrease();
03315         if (i->second.IsValid()) {
03316           ++i;
03317         } else {
03318           DeleteStaleFlows(this->index, goods_index, id);
03319           this->goods[goods_index].cargo.RerouteStalePackets(id);
03320           links.erase(i++);
03321         }
03322       } else {
03323         this->goods[goods_index].cargo.RerouteStalePackets(id);
03324         links.erase(i++);
03325       }
03326     }
03327 
03328     if (_settings_game.linkgraph.GetDistributionType(goods_index) == DT_MANUAL) {
03329       this->goods[goods_index].flows.clear();
03330     }
03331   }
03332 }
03333 
03342 void IncreaseStats(Station *st, CargoID cargo, StationID next_station_id, uint capacity, uint usage)
03343 {
03344   LinkStatMap &stats = st->goods[cargo].link_stats;
03345   LinkStatMap::iterator i = stats.find(next_station_id);
03346   if (i == stats.end()) {
03347     assert(st->index != next_station_id);
03348     stats.insert(std::make_pair(next_station_id, LinkStat(
03349         GetMovingAverageLength(st,
03350         Station::Get(next_station_id)), capacity,
03351         usage == UINT_MAX ? 0 : usage)));
03352   } else {
03353     if (usage == UINT_MAX) {
03354       i->second.Refresh(capacity);
03355     } else {
03356       assert(capacity >= usage);
03357       i->second.Increase(capacity, usage);
03358     }
03359     assert(i->second.IsValid());
03360   }
03361 }
03362 
03369 void IncreaseStats(Station *st, const Vehicle *front, StationID next_station_id)
03370 {
03371   for (const Vehicle *v = front; v != NULL; v = v->Next()) {
03372     if (v->refit_cap > 0) {
03373       IncreaseStats(st, v->cargo_type, next_station_id, v->refit_cap, v->cargo.Count());
03374     }
03375   }
03376 }
03377 
03378 /* called for every station each tick */
03379 static void StationHandleSmallTick(BaseStation *st)
03380 {
03381   if ((st->facilities & FACIL_WAYPOINT) != 0 || !st->IsInUse()) return;
03382 
03383   byte b = st->delete_ctr + 1;
03384   if (b >= STATION_RATING_TICKS) b = 0;
03385   st->delete_ctr = b;
03386 
03387   if (b == 0) UpdateStationRating(Station::From(st));
03388 }
03389 
03390 void OnTick_Station()
03391 {
03392   if (_game_mode == GM_EDITOR) return;
03393 
03394   RunAverages<Station>();
03395 
03396   BaseStation *st;
03397   FOR_ALL_BASE_STATIONS(st) {
03398     StationHandleSmallTick(st);
03399 
03400     /* Run STATION_ACCEPTANCE_TICKS = 250 tick interval trigger for station animation.
03401      * Station index is included so that triggers are not all done
03402      * at the same time. */
03403     if ((_tick_counter + st->index) % STATION_ACCEPTANCE_TICKS == 0) {
03404       /* Stop processing this station if it was deleted */
03405       if (!StationHandleBigTick(st)) continue;
03406       TriggerStationAnimation(st, st->xy, SAT_250_TICKS);
03407       if (Station::IsExpected(st)) AirportAnimationTrigger(Station::From(st), AAT_STATION_250_TICKS);
03408     }
03409   }
03410 }
03411 
03413 void StationMonthlyLoop()
03414 {
03415   Station *st;
03416 
03417   FOR_ALL_STATIONS(st) {
03418     for (CargoID i = 0; i < NUM_CARGO; i++) {
03419       GoodsEntry *ge = &st->goods[i];
03420       SB(ge->acceptance_pickup, GoodsEntry::GES_LAST_MONTH, 1, GB(ge->acceptance_pickup, GoodsEntry::GES_CURRENT_MONTH, 1));
03421       ClrBit(ge->acceptance_pickup, GoodsEntry::GES_CURRENT_MONTH);
03422       ge->supply = ge->supply_new;
03423       ge->supply_new = 0;
03424     }
03425   }
03426 }
03427 
03428 
03429 void ModifyStationRatingAround(TileIndex tile, Owner owner, int amount, uint radius)
03430 {
03431   Station *st;
03432 
03433   FOR_ALL_STATIONS(st) {
03434     if (st->owner == owner &&
03435         DistanceManhattan(tile, st->xy) <= radius) {
03436       for (CargoID i = 0; i < NUM_CARGO; i++) {
03437         GoodsEntry *ge = &st->goods[i];
03438 
03439         if (ge->acceptance_pickup != 0) {
03440           ge->rating = Clamp(ge->rating + amount, 0, 255);
03441         }
03442       }
03443     }
03444   }
03445 }
03446 
03447 static uint UpdateStationWaiting(Station *st, CargoID type, uint amount, SourceType source_type, SourceID source_id)
03448 {
03449   /* We can't allocate a CargoPacket? Then don't do anything
03450    * at all; i.e. just discard the incoming cargo. */
03451   if (!CargoPacket::CanAllocateItem()) return 0;
03452 
03453   GoodsEntry &ge = st->goods[type];
03454   amount += ge.amount_fract;
03455   ge.amount_fract = GB(amount, 0, 8);
03456 
03457   amount >>= 8;
03458   /* No new "real" cargo item yet. */
03459   if (amount == 0) return 0;
03460 
03461   StationID next = ge.GetVia(st->index);
03462 
03463   ge.cargo.Append(next, new CargoPacket(st->index, st->xy, amount, source_type, source_id));
03464   ge.supply_new += amount;
03465 
03466   if (!HasBit(ge.acceptance_pickup, GoodsEntry::GES_PICKUP)) {
03467     InvalidateWindowData(WC_STATION_LIST, st->index);
03468     SetBit(ge.acceptance_pickup, GoodsEntry::GES_PICKUP);
03469   }
03470 
03471   TriggerStationAnimation(st, st->xy, SAT_NEW_CARGO, type);
03472   AirportAnimationTrigger(st, AAT_STATION_NEW_CARGO, type);
03473 
03474   SetWindowDirty(WC_STATION_VIEW, st->index);
03475   st->MarkTilesDirty(true);
03476   return amount;
03477 }
03478 
03479 static bool IsUniqueStationName(const char *name)
03480 {
03481   const Station *st;
03482 
03483   FOR_ALL_STATIONS(st) {
03484     if (st->name != NULL && strcmp(st->name, name) == 0) return false;
03485   }
03486 
03487   return true;
03488 }
03489 
03499 CommandCost CmdRenameStation(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
03500 {
03501   Station *st = Station::GetIfValid(p1);
03502   if (st == NULL) return CMD_ERROR;
03503 
03504   CommandCost ret = CheckOwnership(st->owner);
03505   if (ret.Failed()) return ret;
03506 
03507   bool reset = StrEmpty(text);
03508 
03509   if (!reset) {
03510     if (Utf8StringLength(text) >= MAX_LENGTH_STATION_NAME_CHARS) return CMD_ERROR;
03511     if (!IsUniqueStationName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
03512   }
03513 
03514   if (flags & DC_EXEC) {
03515     free(st->name);
03516     st->name = reset ? NULL : strdup(text);
03517 
03518     st->UpdateVirtCoord();
03519     InvalidateWindowData(WC_STATION_LIST, st->owner, 1);
03520   }
03521 
03522   return CommandCost();
03523 }
03524 
03531 void FindStationsAroundTiles(const TileArea &location, StationList *stations)
03532 {
03533   /* area to search = producer plus station catchment radius */
03534   uint max_rad = (_settings_game.station.modified_catchment ? MAX_CATCHMENT : CA_UNMODIFIED);
03535 
03536   uint x = TileX(location.tile);
03537   uint y = TileY(location.tile);
03538 
03539   uint min_x = (x > max_rad) ? x - max_rad : 0;
03540   uint max_x = x + location.w + max_rad;
03541   uint min_y = (y > max_rad) ? y - max_rad : 0;
03542   uint max_y = y + location.h + max_rad;
03543 
03544   if (min_x == 0 && _settings_game.construction.freeform_edges) min_x = 1;
03545   if (min_y == 0 && _settings_game.construction.freeform_edges) min_y = 1;
03546   if (max_x >= MapSizeX()) max_x = MapSizeX() - 1;
03547   if (max_y >= MapSizeY()) max_y = MapSizeY() - 1;
03548 
03549   for (uint cy = min_y; cy < max_y; cy++) {
03550     for (uint cx = min_x; cx < max_x; cx++) {
03551       TileIndex cur_tile = TileXY(cx, cy);
03552       if (!IsTileType(cur_tile, MP_STATION)) continue;
03553 
03554       Station *st = Station::GetByTile(cur_tile);
03555       /* st can be NULL in case of waypoints */
03556       if (st == NULL) continue;
03557 
03558       if (_settings_game.station.modified_catchment) {
03559         int rad = st->GetCatchmentRadius();
03560         int rad_x = cx - x;
03561         int rad_y = cy - y;
03562 
03563         if (rad_x < -rad || rad_x >= rad + location.w) continue;
03564         if (rad_y < -rad || rad_y >= rad + location.h) continue;
03565       }
03566 
03567       /* Insert the station in the set. This will fail if it has
03568        * already been added.
03569        */
03570       stations->Include(st);
03571     }
03572   }
03573 }
03574 
03579 const StationList *StationFinder::GetStations()
03580 {
03581   if (this->tile != INVALID_TILE) {
03582     FindStationsAroundTiles(*this, &this->stations);
03583     this->tile = INVALID_TILE;
03584   }
03585   return &this->stations;
03586 }
03587 
03588 uint MoveGoodsToStation(CargoID type, uint amount, SourceType source_type, SourceID source_id, const StationList *all_stations)
03589 {
03590   /* Return if nothing to do. Also the rounding below fails for 0. */
03591   if (amount == 0) return 0;
03592 
03593   Station *st1 = NULL;   // Station with best rating
03594   Station *st2 = NULL;   // Second best station
03595   uint best_rating1 = 0; // rating of st1
03596   uint best_rating2 = 0; // rating of st2
03597 
03598   for (Station * const *st_iter = all_stations->Begin(); st_iter != all_stations->End(); ++st_iter) {
03599     Station *st = *st_iter;
03600 
03601     /* Is the station reserved exclusively for somebody else? */
03602     if (st->town->exclusive_counter > 0 && st->town->exclusivity != st->owner) continue;
03603 
03604     if (st->goods[type].rating == 0) continue; // Lowest possible rating, better not to give cargo anymore
03605 
03606     if (_settings_game.order.selectgoods && st->goods[type].last_speed == 0) continue; // Selectively servicing stations, and not this one
03607 
03608     if (IsCargoInClass(type, CC_PASSENGERS)) {
03609       if (st->facilities == FACIL_TRUCK_STOP) continue; // passengers are never served by just a truck stop
03610     } else {
03611       if (st->facilities == FACIL_BUS_STOP) continue; // non-passengers are never served by just a bus stop
03612     }
03613 
03614     /* This station can be used, add it to st1/st2 */
03615     if (st1 == NULL || st->goods[type].rating >= best_rating1) {
03616       st2 = st1; best_rating2 = best_rating1; st1 = st; best_rating1 = st->goods[type].rating;
03617     } else if (st2 == NULL || st->goods[type].rating >= best_rating2) {
03618       st2 = st; best_rating2 = st->goods[type].rating;
03619     }
03620   }
03621 
03622   /* no stations around at all? */
03623   if (st1 == NULL) return 0;
03624 
03625   /* From now we'll calculate with fractal cargo amounts.
03626    * First determine how much cargo we really have. */
03627   amount *= best_rating1 + 1;
03628 
03629   if (st2 == NULL) {
03630     /* only one station around */
03631     return UpdateStationWaiting(st1, type, amount, source_type, source_id);
03632   }
03633 
03634   /* several stations around, the best two (highest rating) are in st1 and st2 */
03635   assert(st1 != NULL);
03636   assert(st2 != NULL);
03637   assert(best_rating1 != 0 || best_rating2 != 0);
03638 
03639   /* Then determine the amount the worst station gets. We do it this way as the
03640    * best should get a bonus, which in this case is the rounding difference from
03641    * this calculation. In reality that will mean the bonus will be pretty low.
03642    * Nevertheless, the best station should always get the most cargo regardless
03643    * of rounding issues. */
03644   uint worst_cargo = amount * best_rating2 / (best_rating1 + best_rating2);
03645   assert(worst_cargo <= (amount - worst_cargo));
03646 
03647   /* And then send the cargo to the stations! */
03648   uint moved = UpdateStationWaiting(st1, type, amount - worst_cargo, source_type, source_id);
03649   /* These two UpdateStationWaiting's can't be in the statement as then the order
03650    * of execution would be undefined and that could cause desyncs with callbacks. */
03651   return moved + UpdateStationWaiting(st2, type, worst_cargo, source_type, source_id);
03652 }
03653 
03654 void BuildOilRig(TileIndex tile)
03655 {
03656   if (!Station::CanAllocateItem()) {
03657     DEBUG(misc, 0, "Can't allocate station for oilrig at 0x%X, reverting to oilrig only", tile);
03658     return;
03659   }
03660 
03661   Station *st = new Station(tile);
03662   st->town = ClosestTownFromTile(tile, UINT_MAX);
03663 
03664   st->string_id = GenerateStationName(st, tile, STATIONNAMING_OILRIG);
03665 
03666   assert(IsTileType(tile, MP_INDUSTRY));
03667   DeleteAnimatedTile(tile);
03668   MakeOilrig(tile, st->index, GetWaterClass(tile));
03669 
03670   st->owner = OWNER_NONE;
03671   st->airport.type = AT_OILRIG;
03672   st->airport.Add(tile);
03673   st->dock_tile = tile;
03674   st->facilities = FACIL_AIRPORT | FACIL_DOCK;
03675   st->build_date = _date;
03676 
03677   st->rect.BeforeAddTile(tile, StationRect::ADD_FORCE);
03678 
03679   for (CargoID j = 0; j < NUM_CARGO; j++) {
03680     st->goods[j].acceptance_pickup = 0;
03681     st->goods[j].days_since_pickup = 255;
03682     st->goods[j].rating = INITIAL_STATION_RATING;
03683     st->goods[j].last_speed = 0;
03684     st->goods[j].last_age = 255;
03685   }
03686 
03687   st->UpdateVirtCoord();
03688   UpdateStationAcceptance(st, false);
03689   st->RecomputeIndustriesNear();
03690 }
03691 
03692 void DeleteOilRig(TileIndex tile)
03693 {
03694   Station *st = Station::GetByTile(tile);
03695 
03696   MakeWaterKeepingClass(tile, OWNER_NONE);
03697 
03698   st->dock_tile = INVALID_TILE;
03699   st->airport.Clear();
03700   st->facilities &= ~(FACIL_AIRPORT | FACIL_DOCK);
03701   st->airport.flags = 0;
03702 
03703   st->rect.AfterRemoveTile(st, tile);
03704 
03705   st->UpdateVirtCoord();
03706   st->RecomputeIndustriesNear();
03707   if (!st->IsInUse()) delete st;
03708 }
03709 
03710 static void ChangeTileOwner_Station(TileIndex tile, Owner old_owner, Owner new_owner)
03711 {
03712   if (IsRoadStopTile(tile)) {
03713     for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
03714       /* Update all roadtypes, no matter if they are present */
03715       if (GetRoadOwner(tile, rt) == old_owner) {
03716         if (HasTileRoadType(tile, rt)) {
03717           /* A drive-through road-stop has always two road bits. No need to dirty windows here, we'll redraw the whole screen anyway. */
03718           Company::Get(old_owner)->infrastructure.road[rt] -= 2;
03719           if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.road[rt] += 2;
03720         }
03721         SetRoadOwner(tile, rt, new_owner == INVALID_OWNER ? OWNER_NONE : new_owner);
03722       }
03723     }
03724   }
03725 
03726   if (!IsTileOwner(tile, old_owner)) return;
03727 
03728   if (new_owner != INVALID_OWNER) {
03729     /* Update company infrastructure counts. Only do it here
03730      * if the new owner is valid as otherwise the clear
03731      * command will do it for us. No need to dirty windows
03732      * here, we'll redraw the whole screen anyway.*/
03733     Company *old_company = Company::Get(old_owner);
03734     Company *new_company = Company::Get(new_owner);
03735 
03736     /* Update counts for underlying infrastructure. */
03737     switch (GetStationType(tile)) {
03738       case STATION_RAIL:
03739       case STATION_WAYPOINT:
03740         if (!IsStationTileBlocked(tile)) {
03741           old_company->infrastructure.rail[GetRailType(tile)]--;
03742           new_company->infrastructure.rail[GetRailType(tile)]++;
03743         }
03744         break;
03745 
03746       case STATION_BUS:
03747       case STATION_TRUCK:
03748         /* Road stops were already handled above. */
03749         break;
03750 
03751       case STATION_BUOY:
03752       case STATION_DOCK:
03753         if (GetWaterClass(tile) == WATER_CLASS_CANAL) {
03754           old_company->infrastructure.water--;
03755           new_company->infrastructure.water++;
03756         }
03757         break;
03758 
03759       default:
03760         break;
03761     }
03762 
03763     /* Update station tile count. */
03764     if (!IsBuoy(tile) && !IsAirport(tile)) {
03765       old_company->infrastructure.station--;
03766       new_company->infrastructure.station++;
03767     }
03768 
03769     /* for buoys, owner of tile is owner of water, st->owner == OWNER_NONE */
03770     SetTileOwner(tile, new_owner);
03771     InvalidateWindowClassesData(WC_STATION_LIST, 0);
03772   } else {
03773     if (IsDriveThroughStopTile(tile)) {
03774       /* Remove the drive-through road stop */
03775       DoCommand(tile, 1 | 1 << 8, (GetStationType(tile) == STATION_TRUCK) ? ROADSTOP_TRUCK : ROADSTOP_BUS, DC_EXEC | DC_BANKRUPT, CMD_REMOVE_ROAD_STOP);
03776       assert(IsTileType(tile, MP_ROAD));
03777       /* Change owner of tile and all roadtypes */
03778       ChangeTileOwner(tile, old_owner, new_owner);
03779     } else {
03780       DoCommand(tile, 0, 0, DC_EXEC | DC_BANKRUPT, CMD_LANDSCAPE_CLEAR);
03781       /* Set tile owner of water under (now removed) buoy and dock to OWNER_NONE.
03782        * Update owner of buoy if it was not removed (was in orders).
03783        * Do not update when owned by OWNER_WATER (sea and rivers). */
03784       if ((IsTileType(tile, MP_WATER) || IsBuoyTile(tile)) && IsTileOwner(tile, old_owner)) SetTileOwner(tile, OWNER_NONE);
03785     }
03786   }
03787 }
03788 
03797 static bool CanRemoveRoadWithStop(TileIndex tile, DoCommandFlag flags)
03798 {
03799   /* Yeah... water can always remove stops, right? */
03800   if (_current_company == OWNER_WATER) return true;
03801 
03802   RoadTypes rts = GetRoadTypes(tile);
03803   if (HasBit(rts, ROADTYPE_TRAM)) {
03804     Owner tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
03805     if (tram_owner != OWNER_NONE && CheckOwnership(tram_owner).Failed()) return false;
03806   }
03807   if (HasBit(rts, ROADTYPE_ROAD)) {
03808     Owner road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
03809     if (road_owner != OWNER_TOWN) {
03810       if (road_owner != OWNER_NONE && CheckOwnership(road_owner).Failed()) return false;
03811     } else {
03812       if (CheckAllowRemoveRoad(tile, GetAnyRoadBits(tile, ROADTYPE_ROAD), OWNER_TOWN, ROADTYPE_ROAD, flags).Failed()) return false;
03813     }
03814   }
03815 
03816   return true;
03817 }
03818 
03825 CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags)
03826 {
03827   if (flags & DC_AUTO) {
03828     switch (GetStationType(tile)) {
03829       default: break;
03830       case STATION_RAIL:     return_cmd_error(STR_ERROR_MUST_DEMOLISH_RAILROAD);
03831       case STATION_WAYPOINT: return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
03832       case STATION_AIRPORT:  return_cmd_error(STR_ERROR_MUST_DEMOLISH_AIRPORT_FIRST);
03833       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);
03834       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);
03835       case STATION_BUOY:     return_cmd_error(STR_ERROR_BUOY_IN_THE_WAY);
03836       case STATION_DOCK:     return_cmd_error(STR_ERROR_MUST_DEMOLISH_DOCK_FIRST);
03837       case STATION_OILRIG:
03838         SetDParam(1, STR_INDUSTRY_NAME_OIL_RIG);
03839         return_cmd_error(STR_ERROR_GENERIC_OBJECT_IN_THE_WAY);
03840     }
03841   }
03842 
03843   switch (GetStationType(tile)) {
03844     case STATION_RAIL:     return RemoveRailStation(tile, flags);
03845     case STATION_WAYPOINT: return RemoveRailWaypoint(tile, flags);
03846     case STATION_AIRPORT:  return RemoveAirport(tile, flags);
03847     case STATION_TRUCK:
03848       if (IsDriveThroughStopTile(tile) && !CanRemoveRoadWithStop(tile, flags)) {
03849         return_cmd_error(STR_ERROR_MUST_DEMOLISH_TRUCK_STATION_FIRST);
03850       }
03851       return RemoveRoadStop(tile, flags);
03852     case STATION_BUS:
03853       if (IsDriveThroughStopTile(tile) && !CanRemoveRoadWithStop(tile, flags)) {
03854         return_cmd_error(STR_ERROR_MUST_DEMOLISH_BUS_STATION_FIRST);
03855       }
03856       return RemoveRoadStop(tile, flags);
03857     case STATION_BUOY:     return RemoveBuoy(tile, flags);
03858     case STATION_DOCK:     return RemoveDock(tile, flags);
03859     default: break;
03860   }
03861 
03862   return CMD_ERROR;
03863 }
03864 
03865 static CommandCost TerraformTile_Station(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
03866 {
03867   if (_settings_game.construction.build_on_slopes && AutoslopeEnabled()) {
03868     /* TODO: If you implement newgrf callback 149 'land slope check', you have to decide what to do with it here.
03869      *       TTDP does not call it.
03870      */
03871     if (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new)) {
03872       switch (GetStationType(tile)) {
03873         case STATION_WAYPOINT:
03874         case STATION_RAIL: {
03875           DiagDirection direction = AxisToDiagDir(GetRailStationAxis(tile));
03876           if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
03877           if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
03878           return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
03879         }
03880 
03881         case STATION_AIRPORT:
03882           return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
03883 
03884         case STATION_TRUCK:
03885         case STATION_BUS: {
03886           DiagDirection direction = GetRoadStopDir(tile);
03887           if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
03888           if (IsDriveThroughStopTile(tile)) {
03889             if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
03890           }
03891           return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
03892         }
03893 
03894         default: break;
03895       }
03896     }
03897   }
03898   return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
03899 }
03900 
03906 uint FlowStat::GetShare(StationID st) const
03907 {
03908   uint32 prev = 0;
03909   for (SharesMap::const_iterator it = this->shares.begin(); it != this->shares.end(); ++it) {
03910     if (it->second == st) {
03911       return it->first - prev;
03912     } else {
03913       prev = it->first;
03914     }
03915   }
03916   return 0;
03917 }
03918 
03924 StationID FlowStat::GetVia(StationID excluded) const
03925 {
03926   assert(!this->shares.empty());
03927   uint max = (--this->shares.end())->first - 1;
03928   SharesMap::const_iterator it = this->shares.upper_bound(RandomRange(max));
03929   assert(it != this->shares.end());
03930   if (it->second != excluded) {
03931     return it->second;
03932   } else {
03933     uint end = it->first;
03934     if (end - 1 == max) return INVALID_STATION; // only one station in the map
03935     uint begin = (it == this->shares.begin() ? 0 : (--it)->first);
03936     uint rand = RandomRange(max - (end - begin));
03937     if (rand < begin) {
03938       return this->shares.upper_bound(rand)->second;
03939     } else {
03940       return this->shares.upper_bound(rand + (end - begin))->second;
03941     }
03942   }
03943 }
03944 
03949 void FlowStat::EraseShare(StationID st)
03950 {
03951   uint32 removed_shares = 0;
03952   uint32 last_share = 0;
03953   SharesMap new_shares;
03954   for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
03955     if (it->second == st) {
03956       removed_shares += it->first - last_share;
03957     } else {
03958       new_shares[it->first - removed_shares] = it->second;
03959     }
03960     last_share = it->first;
03961   }
03962   this->shares.swap(new_shares);
03963   for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
03964     assert(it->second != st);
03965   }
03966 }
03967 
03973 uint GoodsEntry::GetSumFlowVia(StationID via) const
03974 {
03975   uint ret = 0;
03976   for (FlowStatMap::const_iterator i = this->flows.begin(); i != this->flows.end(); ++i) {
03977     ret += i->second.GetShare(via);
03978   }
03979   return ret;
03980 }
03981 
03982 extern const TileTypeProcs _tile_type_station_procs = {
03983   DrawTile_Station,           // draw_tile_proc
03984   GetSlopePixelZ_Station,     // get_slope_z_proc
03985   ClearTile_Station,          // clear_tile_proc
03986   NULL,                       // add_accepted_cargo_proc
03987   GetTileDesc_Station,        // get_tile_desc_proc
03988   GetTileTrackStatus_Station, // get_tile_track_status_proc
03989   ClickTile_Station,          // click_tile_proc
03990   AnimateTile_Station,        // animate_tile_proc
03991   TileLoop_Station,           // tile_loop_proc
03992   ChangeTileOwner_Station,    // change_tile_owner_proc
03993   NULL,                       // add_produced_cargo_proc
03994   VehicleEnter_Station,       // vehicle_enter_tile_proc
03995   GetFoundation_Station,      // get_foundation_proc
03996   TerraformTile_Station,      // terraform_tile_proc
03997 };