station_cmd.cpp

Go to the documentation of this file.
00001 /* $Id: station_cmd.cpp 22448 2011-05-13 17:57:07Z rubidium $ */
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 "roadveh.h"
00022 #include "industry.h"
00023 #include "newgrf_cargo.h"
00024 #include "newgrf_debug.h"
00025 #include "newgrf_station.h"
00026 #include "pathfinder/yapf/yapf_cache.h"
00027 #include "road_internal.h" /* For drawing catenary/checking road removal */
00028 #include "autoslope.h"
00029 #include "water.h"
00030 #include "station_gui.h"
00031 #include "strings_func.h"
00032 #include "clear_func.h"
00033 #include "window_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 "table/airporttile_ids.h"
00049 #include "newgrf_airporttiles.h"
00050 #include "order_backup.h"
00051 
00052 #include "table/strings.h"
00053 
00060 bool IsHangar(TileIndex t)
00061 {
00062   assert(IsTileType(t, MP_STATION));
00063 
00064   /* If the tile isn't an airport there's no chance it's a hangar. */
00065   if (!IsAirport(t)) return false;
00066 
00067   const Station *st = Station::GetByTile(t);
00068   const AirportSpec *as = st->airport.GetSpec();
00069 
00070   for (uint i = 0; i < as->nof_depots; i++) {
00071     if (st->airport.GetHangarTile(i) == t) return true;
00072   }
00073 
00074   return false;
00075 }
00076 
00084 template <class T>
00085 CommandCost GetStationAround(TileArea ta, StationID closest_station, T **st)
00086 {
00087   ta.tile -= TileDiffXY(1, 1);
00088   ta.w    += 2;
00089   ta.h    += 2;
00090 
00091   /* check around to see if there's any stations there */
00092   TILE_AREA_LOOP(tile_cur, ta) {
00093     if (IsTileType(tile_cur, MP_STATION)) {
00094       StationID t = GetStationIndex(tile_cur);
00095       if (!T::IsValidID(t)) continue;
00096 
00097       if (closest_station == INVALID_STATION) {
00098         closest_station = t;
00099       } else if (closest_station != t) {
00100         return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
00101       }
00102     }
00103   }
00104   *st = (closest_station == INVALID_STATION) ? NULL : T::Get(closest_station);
00105   return CommandCost();
00106 }
00107 
00113 typedef bool (*CMSAMatcher)(TileIndex tile);
00114 
00121 static int CountMapSquareAround(TileIndex tile, CMSAMatcher cmp)
00122 {
00123   int num = 0;
00124 
00125   for (int dx = -3; dx <= 3; dx++) {
00126     for (int dy = -3; dy <= 3; dy++) {
00127       TileIndex t = TileAddWrap(tile, dx, dy);
00128       if (t != INVALID_TILE && cmp(t)) num++;
00129     }
00130   }
00131 
00132   return num;
00133 }
00134 
00140 static bool CMSAMine(TileIndex tile)
00141 {
00142   /* No industry */
00143   if (!IsTileType(tile, MP_INDUSTRY)) return false;
00144 
00145   const Industry *ind = Industry::GetByTile(tile);
00146 
00147   /* No extractive industry */
00148   if ((GetIndustrySpec(ind->type)->life_type & INDUSTRYLIFE_EXTRACTIVE) == 0) return false;
00149 
00150   for (uint i = 0; i < lengthof(ind->produced_cargo); i++) {
00151     /* The industry extracts something non-liquid, i.e. no oil or plastic, so it is a mine.
00152      * Also the production of passengers and mail is ignored. */
00153     if (ind->produced_cargo[i] != CT_INVALID &&
00154         (CargoSpec::Get(ind->produced_cargo[i])->classes & (CC_LIQUID | CC_PASSENGERS | CC_MAIL)) == 0) {
00155       return true;
00156     }
00157   }
00158 
00159   return false;
00160 }
00161 
00167 static bool CMSAWater(TileIndex tile)
00168 {
00169   return IsTileType(tile, MP_WATER) && IsWater(tile);
00170 }
00171 
00177 static bool CMSATree(TileIndex tile)
00178 {
00179   return IsTileType(tile, MP_TREES);
00180 }
00181 
00187 static bool CMSAForest(TileIndex tile)
00188 {
00189   /* No industry */
00190   if (!IsTileType(tile, MP_INDUSTRY)) return false;
00191 
00192   const Industry *ind = Industry::GetByTile(tile);
00193 
00194   /* No extractive industry */
00195   if ((GetIndustrySpec(ind->type)->life_type & INDUSTRYLIFE_ORGANIC) == 0) return false;
00196 
00197   for (uint i = 0; i < lengthof(ind->produced_cargo); i++) {
00198     /* The industry produces wood. */
00199     if (ind->produced_cargo[i] != CT_INVALID && CargoSpec::Get(ind->produced_cargo[i])->label == 'WOOD') return true;
00200   }
00201 
00202   return false;
00203 }
00204 
00205 #define M(x) ((x) - STR_SV_STNAME)
00206 
00207 enum StationNaming {
00208   STATIONNAMING_RAIL,
00209   STATIONNAMING_ROAD,
00210   STATIONNAMING_AIRPORT,
00211   STATIONNAMING_OILRIG,
00212   STATIONNAMING_DOCK,
00213   STATIONNAMING_HELIPORT,
00214 };
00215 
00217 struct StationNameInformation {
00218   uint32 free_names; 
00219   bool *indtypes;    
00220 };
00221 
00230 static bool FindNearIndustryName(TileIndex tile, void *user_data)
00231 {
00232   /* All already found industry types */
00233   StationNameInformation *sni = (StationNameInformation*)user_data;
00234   if (!IsTileType(tile, MP_INDUSTRY)) return false;
00235 
00236   /* If the station name is undefined it means that it doesn't name a station */
00237   IndustryType indtype = GetIndustryType(tile);
00238   if (GetIndustrySpec(indtype)->station_name == STR_UNDEFINED) return false;
00239 
00240   /* In all cases if an industry that provides a name is found two of
00241    * the standard names will be disabled. */
00242   sni->free_names &= ~(1 << M(STR_SV_STNAME_OILFIELD) | 1 << M(STR_SV_STNAME_MINES));
00243   return !sni->indtypes[indtype];
00244 }
00245 
00246 static StringID GenerateStationName(Station *st, TileIndex tile, StationNaming name_class)
00247 {
00248   static const uint32 _gen_station_name_bits[] = {
00249     0,                                       // STATIONNAMING_RAIL
00250     0,                                       // STATIONNAMING_ROAD
00251     1U << M(STR_SV_STNAME_AIRPORT),          // STATIONNAMING_AIRPORT
00252     1U << M(STR_SV_STNAME_OILFIELD),         // STATIONNAMING_OILRIG
00253     1U << M(STR_SV_STNAME_DOCKS),            // STATIONNAMING_DOCK
00254     1U << M(STR_SV_STNAME_HELIPORT),         // STATIONNAMING_HELIPORT
00255   };
00256 
00257   const Town *t = st->town;
00258   uint32 free_names = UINT32_MAX;
00259 
00260   bool indtypes[NUM_INDUSTRYTYPES];
00261   memset(indtypes, 0, sizeof(indtypes));
00262 
00263   const Station *s;
00264   FOR_ALL_STATIONS(s) {
00265     if (s != st && s->town == t) {
00266       if (s->indtype != IT_INVALID) {
00267         indtypes[s->indtype] = true;
00268         continue;
00269       }
00270       uint str = M(s->string_id);
00271       if (str <= 0x20) {
00272         if (str == M(STR_SV_STNAME_FOREST)) {
00273           str = M(STR_SV_STNAME_WOODS);
00274         }
00275         ClrBit(free_names, str);
00276       }
00277     }
00278   }
00279 
00280   TileIndex indtile = tile;
00281   StationNameInformation sni = { free_names, indtypes };
00282   if (CircularTileSearch(&indtile, 7, FindNearIndustryName, &sni)) {
00283     /* An industry has been found nearby */
00284     IndustryType indtype = GetIndustryType(indtile);
00285     const IndustrySpec *indsp = GetIndustrySpec(indtype);
00286     /* STR_NULL means it only disables oil rig/mines */
00287     if (indsp->station_name != STR_NULL) {
00288       st->indtype = indtype;
00289       return STR_SV_STNAME_FALLBACK;
00290     }
00291   }
00292 
00293   /* Oil rigs/mines name could be marked not free by looking for a near by industry. */
00294   free_names = sni.free_names;
00295 
00296   /* check default names */
00297   uint32 tmp = free_names & _gen_station_name_bits[name_class];
00298   if (tmp != 0) return STR_SV_STNAME + FindFirstBit(tmp);
00299 
00300   /* check mine? */
00301   if (HasBit(free_names, M(STR_SV_STNAME_MINES))) {
00302     if (CountMapSquareAround(tile, CMSAMine) >= 2) {
00303       return STR_SV_STNAME_MINES;
00304     }
00305   }
00306 
00307   /* check close enough to town to get central as name? */
00308   if (DistanceMax(tile, t->xy) < 8) {
00309     if (HasBit(free_names, M(STR_SV_STNAME))) return STR_SV_STNAME;
00310 
00311     if (HasBit(free_names, M(STR_SV_STNAME_CENTRAL))) return STR_SV_STNAME_CENTRAL;
00312   }
00313 
00314   /* Check lakeside */
00315   if (HasBit(free_names, M(STR_SV_STNAME_LAKESIDE)) &&
00316       DistanceFromEdge(tile) < 20 &&
00317       CountMapSquareAround(tile, CMSAWater) >= 5) {
00318     return STR_SV_STNAME_LAKESIDE;
00319   }
00320 
00321   /* Check woods */
00322   if (HasBit(free_names, M(STR_SV_STNAME_WOODS)) && (
00323         CountMapSquareAround(tile, CMSATree) >= 8 ||
00324         CountMapSquareAround(tile, CMSAForest) >= 2)
00325       ) {
00326     return _settings_game.game_creation.landscape == LT_TROPIC ? STR_SV_STNAME_FOREST : STR_SV_STNAME_WOODS;
00327   }
00328 
00329   /* check elevation compared to town */
00330   uint z = GetTileZ(tile);
00331   uint z2 = GetTileZ(t->xy);
00332   if (z < z2) {
00333     if (HasBit(free_names, M(STR_SV_STNAME_VALLEY))) return STR_SV_STNAME_VALLEY;
00334   } else if (z > z2) {
00335     if (HasBit(free_names, M(STR_SV_STNAME_HEIGHTS))) return STR_SV_STNAME_HEIGHTS;
00336   }
00337 
00338   /* check direction compared to town */
00339   static const int8 _direction_and_table[] = {
00340     ~( (1 << M(STR_SV_STNAME_WEST))  | (1 << M(STR_SV_STNAME_EAST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
00341     ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
00342     ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_EAST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
00343     ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_EAST)) ),
00344   };
00345 
00346   free_names &= _direction_and_table[
00347     (TileX(tile) < TileX(t->xy)) +
00348     (TileY(tile) < TileY(t->xy)) * 2];
00349 
00350   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));
00351   return (tmp == 0) ? STR_SV_STNAME_FALLBACK : (STR_SV_STNAME + FindFirstBit(tmp));
00352 }
00353 #undef M
00354 
00360 static Station *GetClosestDeletedStation(TileIndex tile)
00361 {
00362   uint threshold = 8;
00363   Station *best_station = NULL;
00364   Station *st;
00365 
00366   FOR_ALL_STATIONS(st) {
00367     if (!st->IsInUse() && st->owner == _current_company) {
00368       uint cur_dist = DistanceManhattan(tile, st->xy);
00369 
00370       if (cur_dist < threshold) {
00371         threshold = cur_dist;
00372         best_station = st;
00373       }
00374     }
00375   }
00376 
00377   return best_station;
00378 }
00379 
00380 
00381 void Station::GetTileArea(TileArea *ta, StationType type) const
00382 {
00383   switch (type) {
00384     case STATION_RAIL:
00385       *ta = this->train_station;
00386       return;
00387 
00388     case STATION_AIRPORT:
00389       *ta = this->airport;
00390       return;
00391 
00392     case STATION_TRUCK:
00393       *ta = this->truck_station;
00394       return;
00395 
00396     case STATION_BUS:
00397       *ta = this->bus_station;
00398       return;
00399 
00400     case STATION_DOCK:
00401     case STATION_OILRIG:
00402       ta->tile = this->dock_tile;
00403       break;
00404 
00405     default: NOT_REACHED();
00406   }
00407 
00408   ta->w = 1;
00409   ta->h = 1;
00410 }
00411 
00415 void Station::UpdateVirtCoord()
00416 {
00417   Point pt = RemapCoords2(TileX(this->xy) * TILE_SIZE, TileY(this->xy) * TILE_SIZE);
00418 
00419   pt.y -= 32;
00420   if ((this->facilities & FACIL_AIRPORT) && this->airport.type == AT_OILRIG) pt.y -= 16;
00421 
00422   SetDParam(0, this->index);
00423   SetDParam(1, this->facilities);
00424   this->sign.UpdatePosition(pt.x, pt.y, STR_VIEWPORT_STATION);
00425 
00426   SetWindowDirty(WC_STATION_VIEW, this->index);
00427 }
00428 
00430 void UpdateAllStationVirtCoords()
00431 {
00432   BaseStation *st;
00433 
00434   FOR_ALL_BASE_STATIONS(st) {
00435     st->UpdateVirtCoord();
00436   }
00437 }
00438 
00444 static uint GetAcceptanceMask(const Station *st)
00445 {
00446   uint mask = 0;
00447 
00448   for (CargoID i = 0; i < NUM_CARGO; i++) {
00449     if (HasBit(st->goods[i].acceptance_pickup, GoodsEntry::ACCEPTANCE)) mask |= 1 << i;
00450   }
00451   return mask;
00452 }
00453 
00458 static void ShowRejectOrAcceptNews(const Station *st, uint num_items, CargoID *cargo, StringID msg)
00459 {
00460   for (uint i = 0; i < num_items; i++) {
00461     SetDParam(i + 1, CargoSpec::Get(cargo[i])->name);
00462   }
00463 
00464   SetDParam(0, st->index);
00465   AddNewsItem(msg, NS_ACCEPTANCE, NR_STATION, st->index);
00466 }
00467 
00475 CargoArray GetProductionAroundTiles(TileIndex tile, int w, int h, int rad)
00476 {
00477   CargoArray produced;
00478 
00479   int x = TileX(tile);
00480   int y = TileY(tile);
00481 
00482   /* expand the region by rad tiles on each side
00483    * while making sure that we remain inside the board. */
00484   int x2 = min(x + w + rad, MapSizeX());
00485   int x1 = max(x - rad, 0);
00486 
00487   int y2 = min(y + h + rad, MapSizeY());
00488   int y1 = max(y - rad, 0);
00489 
00490   assert(x1 < x2);
00491   assert(y1 < y2);
00492   assert(w > 0);
00493   assert(h > 0);
00494 
00495   TileArea ta(TileXY(x1, y1), TileXY(x2 - 1, y2 - 1));
00496 
00497   /* Loop over all tiles to get the produced cargo of
00498    * everything except industries */
00499   TILE_AREA_LOOP(tile, ta) AddProducedCargo(tile, produced);
00500 
00501   /* Loop over the industries. They produce cargo for
00502    * anything that is within 'rad' from their bounding
00503    * box. As such if you have e.g. a oil well the tile
00504    * area loop might not hit an industry tile while
00505    * the industry would produce cargo for the station.
00506    */
00507   const Industry *i;
00508   FOR_ALL_INDUSTRIES(i) {
00509     if (!ta.Intersects(i->location)) continue;
00510 
00511     for (uint j = 0; j < lengthof(i->produced_cargo); j++) {
00512       CargoID cargo = i->produced_cargo[j];
00513       if (cargo != CT_INVALID) produced[cargo]++;
00514     }
00515   }
00516 
00517   return produced;
00518 }
00519 
00528 CargoArray GetAcceptanceAroundTiles(TileIndex tile, int w, int h, int rad, uint32 *always_accepted)
00529 {
00530   CargoArray acceptance;
00531   if (always_accepted != NULL) *always_accepted = 0;
00532 
00533   int x = TileX(tile);
00534   int y = TileY(tile);
00535 
00536   /* expand the region by rad tiles on each side
00537    * while making sure that we remain inside the board. */
00538   int x2 = min(x + w + rad, MapSizeX());
00539   int y2 = min(y + h + rad, MapSizeY());
00540   int x1 = max(x - rad, 0);
00541   int y1 = max(y - rad, 0);
00542 
00543   assert(x1 < x2);
00544   assert(y1 < y2);
00545   assert(w > 0);
00546   assert(h > 0);
00547 
00548   for (int yc = y1; yc != y2; yc++) {
00549     for (int xc = x1; xc != x2; xc++) {
00550       TileIndex tile = TileXY(xc, yc);
00551       AddAcceptedCargo(tile, acceptance, always_accepted);
00552     }
00553   }
00554 
00555   return acceptance;
00556 }
00557 
00563 void UpdateStationAcceptance(Station *st, bool show_msg)
00564 {
00565   /* old accepted goods types */
00566   uint old_acc = GetAcceptanceMask(st);
00567 
00568   /* And retrieve the acceptance. */
00569   CargoArray acceptance;
00570   if (!st->rect.IsEmpty()) {
00571     acceptance = GetAcceptanceAroundTiles(
00572       TileXY(st->rect.left, st->rect.top),
00573       st->rect.right  - st->rect.left + 1,
00574       st->rect.bottom - st->rect.top  + 1,
00575       st->GetCatchmentRadius(),
00576       &st->always_accepted
00577     );
00578   }
00579 
00580   /* Adjust in case our station only accepts fewer kinds of goods */
00581   for (CargoID i = 0; i < NUM_CARGO; i++) {
00582     uint amt = min(acceptance[i], 15);
00583 
00584     /* Make sure the station can accept the goods type. */
00585     bool is_passengers = IsCargoInClass(i, CC_PASSENGERS);
00586     if ((!is_passengers && !(st->facilities & ~FACIL_BUS_STOP)) ||
00587         (is_passengers && !(st->facilities & ~FACIL_TRUCK_STOP))) {
00588       amt = 0;
00589     }
00590 
00591     SB(st->goods[i].acceptance_pickup, GoodsEntry::ACCEPTANCE, 1, amt >= 8);
00592   }
00593 
00594   /* Only show a message in case the acceptance was actually changed. */
00595   uint new_acc = GetAcceptanceMask(st);
00596   if (old_acc == new_acc) return;
00597 
00598   /* show a message to report that the acceptance was changed? */
00599   if (show_msg && st->owner == _local_company && st->IsInUse()) {
00600     /* List of accept and reject strings for different number of
00601      * cargo types */
00602     static const StringID accept_msg[] = {
00603       STR_NEWS_STATION_NOW_ACCEPTS_CARGO,
00604       STR_NEWS_STATION_NOW_ACCEPTS_CARGO_AND_CARGO,
00605     };
00606     static const StringID reject_msg[] = {
00607       STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO,
00608       STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO_OR_CARGO,
00609     };
00610 
00611     /* Array of accepted and rejected cargo types */
00612     CargoID accepts[2] = { CT_INVALID, CT_INVALID };
00613     CargoID rejects[2] = { CT_INVALID, CT_INVALID };
00614     uint num_acc = 0;
00615     uint num_rej = 0;
00616 
00617     /* Test each cargo type to see if its acceptange has changed */
00618     for (CargoID i = 0; i < NUM_CARGO; i++) {
00619       if (HasBit(new_acc, i)) {
00620         if (!HasBit(old_acc, i) && num_acc < lengthof(accepts)) {
00621           /* New cargo is accepted */
00622           accepts[num_acc++] = i;
00623         }
00624       } else {
00625         if (HasBit(old_acc, i) && num_rej < lengthof(rejects)) {
00626           /* Old cargo is no longer accepted */
00627           rejects[num_rej++] = i;
00628         }
00629       }
00630     }
00631 
00632     /* Show news message if there are any changes */
00633     if (num_acc > 0) ShowRejectOrAcceptNews(st, num_acc, accepts, accept_msg[num_acc - 1]);
00634     if (num_rej > 0) ShowRejectOrAcceptNews(st, num_rej, rejects, reject_msg[num_rej - 1]);
00635   }
00636 
00637   /* redraw the station view since acceptance changed */
00638   SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_ACCEPTLIST);
00639 }
00640 
00641 static void UpdateStationSignCoord(BaseStation *st)
00642 {
00643   const StationRect *r = &st->rect;
00644 
00645   if (r->IsEmpty()) return; // no tiles belong to this station
00646 
00647   /* clamp sign coord to be inside the station rect */
00648   st->xy = TileXY(ClampU(TileX(st->xy), r->left, r->right), ClampU(TileY(st->xy), r->top, r->bottom));
00649   st->UpdateVirtCoord();
00650 }
00651 
00658 static void DeleteStationIfEmpty(BaseStation *st)
00659 {
00660   if (!st->IsInUse()) {
00661     st->delete_ctr = 0;
00662     InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
00663   }
00664   /* station remains but it probably lost some parts - station sign should stay in the station boundaries */
00665   UpdateStationSignCoord(st);
00666 }
00667 
00668 CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags);
00669 
00678 CommandCost CheckBuildableTile(TileIndex tile, uint invalid_dirs, int &allowed_z, bool check_bridge = true)
00679 {
00680   if (check_bridge && MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) {
00681     return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
00682   }
00683 
00684   CommandCost ret = EnsureNoVehicleOnGround(tile);
00685   if (ret.Failed()) return ret;
00686 
00687   uint z;
00688   Slope tileh = GetTileSlope(tile, &z);
00689 
00690   /* Prohibit building if
00691    *   1) The tile is "steep" (i.e. stretches two height levels).
00692    *   2) The tile is non-flat and the build_on_slopes switch is disabled.
00693    */
00694   if (IsSteepSlope(tileh) ||
00695       ((!_settings_game.construction.build_on_slopes) && tileh != SLOPE_FLAT)) {
00696     return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
00697   }
00698 
00699   CommandCost cost(EXPENSES_CONSTRUCTION);
00700   int flat_z = z;
00701   if (tileh != SLOPE_FLAT) {
00702     /* Forbid building if the tile faces a slope in a invalid direction. */
00703     if ((HasBit(invalid_dirs, DIAGDIR_NE) && !(tileh & SLOPE_NE)) ||
00704         (HasBit(invalid_dirs, DIAGDIR_SE) && !(tileh & SLOPE_SE)) ||
00705         (HasBit(invalid_dirs, DIAGDIR_SW) && !(tileh & SLOPE_SW)) ||
00706         (HasBit(invalid_dirs, DIAGDIR_NW) && !(tileh & SLOPE_NW))) {
00707       return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
00708     }
00709     cost.AddCost(_price[PR_BUILD_FOUNDATION]);
00710     flat_z += TILE_HEIGHT;
00711   }
00712 
00713   /* The level of this tile must be equal to allowed_z. */
00714   if (allowed_z < 0) {
00715     /* First tile. */
00716     allowed_z = flat_z;
00717   } else if (allowed_z != flat_z) {
00718     return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
00719   }
00720 
00721   return cost;
00722 }
00723 
00730 CommandCost CheckFlatLand(TileArea tile_area, DoCommandFlag flags)
00731 {
00732   CommandCost cost(EXPENSES_CONSTRUCTION);
00733   int allowed_z = -1;
00734 
00735   TILE_AREA_LOOP(tile_cur, tile_area) {
00736     CommandCost ret = CheckBuildableTile(tile_cur, 0, allowed_z);
00737     if (ret.Failed()) return ret;
00738     cost.AddCost(ret);
00739 
00740     ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00741     if (ret.Failed()) return ret;
00742     cost.AddCost(ret);
00743   }
00744 
00745   return cost;
00746 }
00747 
00758 static CommandCost CheckFlatLandRailStation(TileArea tile_area, DoCommandFlag flags, uint invalid_dirs, StationID *station, RailType rt, SmallVector<Train *, 4> &affected_vehicles)
00759 {
00760   CommandCost cost(EXPENSES_CONSTRUCTION);
00761   int allowed_z = -1;
00762 
00763   TILE_AREA_LOOP(tile_cur, tile_area) {
00764     CommandCost ret = CheckBuildableTile(tile_cur, invalid_dirs, allowed_z);
00765     if (ret.Failed()) return ret;
00766     cost.AddCost(ret);
00767 
00768     /* if station is set, then we have special handling to allow building on top of already existing stations.
00769      * so station points to INVALID_STATION if we can build on any station.
00770      * Or it points to a station if we're only allowed to build on exactly that station. */
00771     if (station != NULL && IsTileType(tile_cur, MP_STATION)) {
00772       if (!IsRailStation(tile_cur)) {
00773         return ClearTile_Station(tile_cur, DC_AUTO); // get error message
00774       } else {
00775         StationID st = GetStationIndex(tile_cur);
00776         if (*station == INVALID_STATION) {
00777           *station = st;
00778         } else if (*station != st) {
00779           return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
00780         }
00781       }
00782     } else {
00783       /* Rail type is only valid when building a railway station; if station to
00784        * build isn't a rail station it's INVALID_RAILTYPE. */
00785       if (rt != INVALID_RAILTYPE &&
00786           IsPlainRailTile(tile_cur) && !HasSignals(tile_cur) &&
00787           HasPowerOnRail(GetRailType(tile_cur), rt)) {
00788         /* Allow overbuilding if the tile:
00789          *  - has rail, but no signals
00790          *  - it has exactly one track
00791          *  - the track is in line with the station
00792          *  - the current rail type has power on the to-be-built type (e.g. convert normal rail to el rail)
00793          */
00794         TrackBits tracks = GetTrackBits(tile_cur);
00795         Track track = RemoveFirstTrack(&tracks);
00796         Track expected_track = HasBit(invalid_dirs, DIAGDIR_NE) ? TRACK_X : TRACK_Y;
00797 
00798         if (tracks == TRACK_BIT_NONE && track == expected_track) {
00799           /* Check for trains having a reservation for this tile. */
00800           if (HasBit(GetRailReservationTrackBits(tile_cur), track)) {
00801             Train *v = GetTrainForReservation(tile_cur, track);
00802             if (v != NULL) {
00803               *affected_vehicles.Append() = v;
00804             }
00805           }
00806           CommandCost ret = DoCommand(tile_cur, 0, track, flags, CMD_REMOVE_SINGLE_RAIL);
00807           if (ret.Failed()) return ret;
00808           cost.AddCost(ret);
00809           /* With flags & ~DC_EXEC CmdLandscapeClear would fail since the rail still exists */
00810           continue;
00811         }
00812       }
00813       ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00814       if (ret.Failed()) return ret;
00815       cost.AddCost(ret);
00816     }
00817   }
00818 
00819   return cost;
00820 }
00821 
00834 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)
00835 {
00836   CommandCost cost(EXPENSES_CONSTRUCTION);
00837   int allowed_z = -1;
00838 
00839   TILE_AREA_LOOP(cur_tile, tile_area) {
00840     CommandCost ret = CheckBuildableTile(cur_tile, invalid_dirs, allowed_z);
00841     if (ret.Failed()) return ret;
00842     cost.AddCost(ret);
00843 
00844     /* If station is set, then we have special handling to allow building on top of already existing stations.
00845      * Station points to INVALID_STATION if we can build on any station.
00846      * Or it points to a station if we're only allowed to build on exactly that station. */
00847     if (station != NULL && IsTileType(cur_tile, MP_STATION)) {
00848       if (!IsRoadStop(cur_tile)) {
00849         return ClearTile_Station(cur_tile, DC_AUTO); // Get error message.
00850       } else {
00851         if (is_truck_stop != IsTruckStop(cur_tile) ||
00852             is_drive_through != IsDriveThroughStopTile(cur_tile)) {
00853           return ClearTile_Station(cur_tile, DC_AUTO); // Get error message.
00854         }
00855         /* Drive-through station in the wrong direction. */
00856         if (is_drive_through && IsDriveThroughStopTile(cur_tile) && DiagDirToAxis(GetRoadStopDir(cur_tile)) != axis){
00857           return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
00858         }
00859         StationID st = GetStationIndex(cur_tile);
00860         if (*station == INVALID_STATION) {
00861           *station = st;
00862         } else if (*station != st) {
00863           return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
00864         }
00865       }
00866     } else {
00867       bool build_over_road = is_drive_through && IsNormalRoadTile(cur_tile);
00868       /* Road bits in the wrong direction. */
00869       RoadBits rb = IsNormalRoadTile(cur_tile) ? GetAllRoadBits(cur_tile) : ROAD_NONE;
00870       if (build_over_road && (rb & (axis == AXIS_X ? ROAD_Y : ROAD_X)) != 0) {
00871         /* Someone was pedantic and *NEEDED* three fracking different error messages. */
00872         switch (CountBits(rb)) {
00873           case 1:
00874             return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
00875 
00876           case 2:
00877             if (rb == ROAD_X || rb == ROAD_Y) return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
00878             return_cmd_error(STR_ERROR_DRIVE_THROUGH_CORNER);
00879 
00880           default: // 3 or 4
00881             return_cmd_error(STR_ERROR_DRIVE_THROUGH_JUNCTION);
00882         }
00883       }
00884 
00885       RoadTypes cur_rts = IsNormalRoadTile(cur_tile) ? GetRoadTypes(cur_tile) : ROADTYPES_NONE;
00886       uint num_roadbits = 0;
00887       if (build_over_road) {
00888         /* There is a road, check if we can build road+tram stop over it. */
00889         if (HasBit(cur_rts, ROADTYPE_ROAD)) {
00890           Owner road_owner = GetRoadOwner(cur_tile, ROADTYPE_ROAD);
00891           if (road_owner == OWNER_TOWN) {
00892             if (!_settings_game.construction.road_stop_on_town_road) return_cmd_error(STR_ERROR_DRIVE_THROUGH_ON_TOWN_ROAD);
00893           } else if (!_settings_game.construction.road_stop_on_competitor_road && road_owner != OWNER_NONE) {
00894             CommandCost ret = CheckOwnership(road_owner);
00895             if (ret.Failed()) return ret;
00896           }
00897           num_roadbits += CountBits(GetRoadBits(cur_tile, ROADTYPE_ROAD));
00898         }
00899 
00900         /* There is a tram, check if we can build road+tram stop over it. */
00901         if (HasBit(cur_rts, ROADTYPE_TRAM)) {
00902           Owner tram_owner = GetRoadOwner(cur_tile, ROADTYPE_TRAM);
00903           if (!_settings_game.construction.road_stop_on_competitor_road && tram_owner != OWNER_NONE) {
00904             CommandCost ret = CheckOwnership(tram_owner);
00905             if (ret.Failed()) return ret;
00906           }
00907           num_roadbits += CountBits(GetRoadBits(cur_tile, ROADTYPE_TRAM));
00908         }
00909 
00910         /* Take into account existing roadbits. */
00911         rts |= cur_rts;
00912       } else {
00913         ret = DoCommand(cur_tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00914         if (ret.Failed()) return ret;
00915         cost.AddCost(ret);
00916       }
00917 
00918       uint roadbits_to_build = CountBits(rts) * 2 - num_roadbits;
00919       cost.AddCost(_price[PR_BUILD_ROAD] * roadbits_to_build);
00920     }
00921   }
00922 
00923   return cost;
00924 }
00925 
00933 CommandCost CanExpandRailStation(const BaseStation *st, TileArea &new_ta, Axis axis)
00934 {
00935   TileArea cur_ta = st->train_station;
00936 
00937   /* determine new size of train station region.. */
00938   int x = min(TileX(cur_ta.tile), TileX(new_ta.tile));
00939   int y = min(TileY(cur_ta.tile), TileY(new_ta.tile));
00940   new_ta.w = max(TileX(cur_ta.tile) + cur_ta.w, TileX(new_ta.tile) + new_ta.w) - x;
00941   new_ta.h = max(TileY(cur_ta.tile) + cur_ta.h, TileY(new_ta.tile) + new_ta.h) - y;
00942   new_ta.tile = TileXY(x, y);
00943 
00944   /* make sure the final size is not too big. */
00945   if (new_ta.w > _settings_game.station.station_spread || new_ta.h > _settings_game.station.station_spread) {
00946     return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
00947   }
00948 
00949   return CommandCost();
00950 }
00951 
00952 static inline byte *CreateSingle(byte *layout, int n)
00953 {
00954   int i = n;
00955   do *layout++ = 0; while (--i);
00956   layout[((n - 1) >> 1) - n] = 2;
00957   return layout;
00958 }
00959 
00960 static inline byte *CreateMulti(byte *layout, int n, byte b)
00961 {
00962   int i = n;
00963   do *layout++ = b; while (--i);
00964   if (n > 4) {
00965     layout[0 - n] = 0;
00966     layout[n - 1 - n] = 0;
00967   }
00968   return layout;
00969 }
00970 
00971 void GetStationLayout(byte *layout, int numtracks, int plat_len, const StationSpec *statspec)
00972 {
00973   if (statspec != NULL && statspec->lengths >= plat_len &&
00974       statspec->platforms[plat_len - 1] >= numtracks &&
00975       statspec->layouts[plat_len - 1][numtracks - 1]) {
00976     /* Custom layout defined, follow it. */
00977     memcpy(layout, statspec->layouts[plat_len - 1][numtracks - 1],
00978       plat_len * numtracks);
00979     return;
00980   }
00981 
00982   if (plat_len == 1) {
00983     CreateSingle(layout, numtracks);
00984   } else {
00985     if (numtracks & 1) layout = CreateSingle(layout, plat_len);
00986     numtracks >>= 1;
00987 
00988     while (--numtracks >= 0) {
00989       layout = CreateMulti(layout, plat_len, 4);
00990       layout = CreateMulti(layout, plat_len, 6);
00991     }
00992   }
00993 }
00994 
01006 template <class T, StringID error_message>
01007 CommandCost FindJoiningBaseStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, T **st)
01008 {
01009   assert(*st == NULL);
01010   bool check_surrounding = true;
01011 
01012   if (_settings_game.station.adjacent_stations) {
01013     if (existing_station != INVALID_STATION) {
01014       if (adjacent && existing_station != station_to_join) {
01015         /* You can't build an adjacent station over the top of one that
01016          * already exists. */
01017         return_cmd_error(error_message);
01018       } else {
01019         /* Extend the current station, and don't check whether it will
01020          * be near any other stations. */
01021         *st = T::GetIfValid(existing_station);
01022         check_surrounding = (*st == NULL);
01023       }
01024     } else {
01025       /* There's no station here. Don't check the tiles surrounding this
01026        * one if the company wanted to build an adjacent station. */
01027       if (adjacent) check_surrounding = false;
01028     }
01029   }
01030 
01031   if (check_surrounding) {
01032     /* Make sure there are no similar stations around us. */
01033     CommandCost ret = GetStationAround(ta, existing_station, st);
01034     if (ret.Failed()) return ret;
01035   }
01036 
01037   /* Distant join */
01038   if (*st == NULL && station_to_join != INVALID_STATION) *st = T::GetIfValid(station_to_join);
01039 
01040   return CommandCost();
01041 }
01042 
01052 static CommandCost FindJoiningStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
01053 {
01054   return FindJoiningBaseStation<Station, STR_ERROR_MUST_REMOVE_RAILWAY_STATION_FIRST>(existing_station, station_to_join, adjacent, ta, st);
01055 }
01056 
01066 CommandCost FindJoiningWaypoint(StationID existing_waypoint, StationID waypoint_to_join, bool adjacent, TileArea ta, Waypoint **wp)
01067 {
01068   return FindJoiningBaseStation<Waypoint, STR_ERROR_MUST_REMOVE_RAILWAYPOINT_FIRST>(existing_waypoint, waypoint_to_join, adjacent, ta, wp);
01069 }
01070 
01088 CommandCost CmdBuildRailStation(TileIndex tile_org, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01089 {
01090   /* Unpack parameters */
01091   RailType rt    = Extract<RailType, 0, 4>(p1);
01092   Axis axis      = Extract<Axis, 4, 1>(p1);
01093   byte numtracks = GB(p1,  8, 8);
01094   byte plat_len  = GB(p1, 16, 8);
01095   bool adjacent  = HasBit(p1, 24);
01096 
01097   StationClassID spec_class = Extract<StationClassID, 0, 8>(p2);
01098   byte spec_index           = GB(p2, 8, 8);
01099   StationID station_to_join = GB(p2, 16, 16);
01100 
01101   /* Does the authority allow this? */
01102   CommandCost ret = CheckIfAuthorityAllowsNewStation(tile_org, flags);
01103   if (ret.Failed()) return ret;
01104 
01105   if (!ValParamRailtype(rt)) return CMD_ERROR;
01106 
01107   /* Check if the given station class is valid */
01108   if ((uint)spec_class >= StationClass::GetCount() || spec_class == STAT_CLASS_WAYP) return CMD_ERROR;
01109   if (spec_index >= StationClass::GetCount(spec_class)) return CMD_ERROR;
01110   if (plat_len == 0 || numtracks == 0) return CMD_ERROR;
01111 
01112   int w_org, h_org;
01113   if (axis == AXIS_X) {
01114     w_org = plat_len;
01115     h_org = numtracks;
01116   } else {
01117     h_org = plat_len;
01118     w_org = numtracks;
01119   }
01120 
01121   bool reuse = (station_to_join != NEW_STATION);
01122   if (!reuse) station_to_join = INVALID_STATION;
01123   bool distant_join = (station_to_join != INVALID_STATION);
01124 
01125   if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
01126 
01127   if (h_org > _settings_game.station.station_spread || w_org > _settings_game.station.station_spread) return CMD_ERROR;
01128 
01129   /* these values are those that will be stored in train_tile and station_platforms */
01130   TileArea new_location(tile_org, w_org, h_org);
01131 
01132   /* Make sure the area below consists of clear tiles. (OR tiles belonging to a certain rail station) */
01133   StationID est = INVALID_STATION;
01134   SmallVector<Train *, 4> affected_vehicles;
01135   /* Clear the land below the station. */
01136   CommandCost cost = CheckFlatLandRailStation(TileArea(tile_org, w_org, h_org), flags, 5 << axis, &est, rt, affected_vehicles);
01137   if (cost.Failed()) return cost;
01138   /* Add construction expenses. */
01139   cost.AddCost((numtracks * _price[PR_BUILD_STATION_RAIL] + _price[PR_BUILD_STATION_RAIL_LENGTH]) * plat_len);
01140   cost.AddCost(numtracks * plat_len * RailBuildCost(rt));
01141 
01142   Station *st = NULL;
01143   ret = FindJoiningStation(est, station_to_join, adjacent, new_location, &st);
01144   if (ret.Failed()) return ret;
01145 
01146   /* See if there is a deleted station close to us. */
01147   if (st == NULL && reuse) st = GetClosestDeletedStation(tile_org);
01148 
01149   if (st != NULL) {
01150     /* Reuse an existing station. */
01151     if (st->owner != _current_company) return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_STATION);
01152 
01153     if (st->train_station.tile != INVALID_TILE) {
01154       CommandCost ret = CanExpandRailStation(st, new_location, axis);
01155       if (ret.Failed()) return ret;
01156     }
01157 
01158     /* XXX can't we pack this in the "else" part of the if above? */
01159     CommandCost ret = st->rect.BeforeAddRect(tile_org, w_org, h_org, StationRect::ADD_TEST);
01160     if (ret.Failed()) return ret;
01161   } else {
01162     /* allocate and initialize new station */
01163     if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
01164 
01165     if (flags & DC_EXEC) {
01166       st = new Station(tile_org);
01167 
01168       st->town = ClosestTownFromTile(tile_org, UINT_MAX);
01169       st->string_id = GenerateStationName(st, tile_org, STATIONNAMING_RAIL);
01170 
01171       if (Company::IsValidID(_current_company)) {
01172         SetBit(st->town->have_ratings, _current_company);
01173       }
01174     }
01175   }
01176 
01177   /* Check if we can allocate a custom stationspec to this station */
01178   const StationSpec *statspec = StationClass::Get(spec_class, spec_index);
01179   int specindex = AllocateSpecToStation(statspec, st, (flags & DC_EXEC) != 0);
01180   if (specindex == -1) return_cmd_error(STR_ERROR_TOO_MANY_STATION_SPECS);
01181 
01182   if (statspec != NULL) {
01183     /* Perform NewStation checks */
01184 
01185     /* Check if the station size is permitted */
01186     if (HasBit(statspec->disallowed_platforms, numtracks - 1) || HasBit(statspec->disallowed_lengths, plat_len - 1)) {
01187       return CMD_ERROR;
01188     }
01189 
01190     /* Check if the station is buildable */
01191     if (HasBit(statspec->callback_mask, CBM_STATION_AVAIL) && GB(GetStationCallback(CBID_STATION_AVAILABILITY, 0, 0, statspec, NULL, INVALID_TILE), 0, 8) == 0) {
01192       return CMD_ERROR;
01193     }
01194   }
01195 
01196   if (flags & DC_EXEC) {
01197     TileIndexDiff tile_delta;
01198     byte *layout_ptr;
01199     byte numtracks_orig;
01200     Track track;
01201 
01202     st->train_station = new_location;
01203     st->AddFacility(FACIL_TRAIN, new_location.tile);
01204 
01205     st->rect.BeforeAddRect(tile_org, w_org, h_org, StationRect::ADD_TRY);
01206 
01207     if (statspec != NULL) {
01208       /* Include this station spec's animation trigger bitmask
01209        * in the station's cached copy. */
01210       st->cached_anim_triggers |= statspec->animation.triggers;
01211     }
01212 
01213     tile_delta = (axis == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
01214     track = AxisToTrack(axis);
01215 
01216     layout_ptr = AllocaM(byte, numtracks * plat_len);
01217     GetStationLayout(layout_ptr, numtracks, plat_len, statspec);
01218 
01219     numtracks_orig = numtracks;
01220 
01221     do {
01222       TileIndex tile = tile_org;
01223       int w = plat_len;
01224       do {
01225         byte layout = *layout_ptr++;
01226         if (IsRailStationTile(tile) && HasStationReservation(tile)) {
01227           /* Check for trains having a reservation for this tile. */
01228           Train *v = GetTrainForReservation(tile, AxisToTrack(GetRailStationAxis(tile)));
01229           if (v != NULL) {
01230             FreeTrainTrackReservation(v);
01231             *affected_vehicles.Append() = v;
01232             if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), false);
01233             for (; v->Next() != NULL; v = v->Next()) { }
01234             if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), false);
01235           }
01236         }
01237 
01238         /* Remove animation if overbuilding */
01239         DeleteAnimatedTile(tile);
01240         byte old_specindex = HasStationTileRail(tile) ? GetCustomStationSpecIndex(tile) : 0;
01241         MakeRailStation(tile, st->owner, st->index, axis, layout & ~1, rt);
01242         /* Free the spec if we overbuild something */
01243         DeallocateSpecFromStation(st, old_specindex);
01244 
01245         SetCustomStationSpecIndex(tile, specindex);
01246         SetStationTileRandomBits(tile, GB(Random(), 0, 4));
01247         SetAnimationFrame(tile, 0);
01248 
01249         if (statspec != NULL) {
01250           /* Use a fixed axis for GetPlatformInfo as our platforms / numtracks are always the right way around */
01251           uint32 platinfo = GetPlatformInfo(AXIS_X, 0, plat_len, numtracks_orig, plat_len - w, numtracks_orig - numtracks, false);
01252 
01253           /* As the station is not yet completely finished, the station does not yet exist. */
01254           uint16 callback = GetStationCallback(CBID_STATION_TILE_LAYOUT, platinfo, 0, statspec, NULL, tile);
01255           if (callback != CALLBACK_FAILED && callback < 8) SetStationGfx(tile, (callback & ~1) + axis);
01256 
01257           /* Trigger station animation -- after building? */
01258           TriggerStationAnimation(st, tile, SAT_BUILT);
01259         }
01260 
01261         tile += tile_delta;
01262       } while (--w);
01263       AddTrackToSignalBuffer(tile_org, track, _current_company);
01264       YapfNotifyTrackLayoutChange(tile_org, track);
01265       tile_org += tile_delta ^ TileDiffXY(1, 1); // perpendicular to tile_delta
01266     } while (--numtracks);
01267 
01268     for (uint i = 0; i < affected_vehicles.Length(); ++i) {
01269       /* Restore reservations of trains. */
01270       Train *v = affected_vehicles[i];
01271       if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
01272       TryPathReserve(v, true, true);
01273       for (; v->Next() != NULL; v = v->Next()) { }
01274       if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), true);
01275     }
01276 
01277     st->MarkTilesDirty(false);
01278     st->UpdateVirtCoord();
01279     UpdateStationAcceptance(st, false);
01280     st->RecomputeIndustriesNear();
01281     InvalidateWindowData(WC_SELECT_STATION, 0, 0);
01282     InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
01283     SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_TRAINS);
01284   }
01285 
01286   return cost;
01287 }
01288 
01289 static void MakeRailStationAreaSmaller(BaseStation *st)
01290 {
01291   TileArea ta = st->train_station;
01292 
01293 restart:
01294 
01295   /* too small? */
01296   if (ta.w != 0 && ta.h != 0) {
01297     /* check the left side, x = constant, y changes */
01298     for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(0, i));) {
01299       /* the left side is unused? */
01300       if (++i == ta.h) {
01301         ta.tile += TileDiffXY(1, 0);
01302         ta.w--;
01303         goto restart;
01304       }
01305     }
01306 
01307     /* check the right side, x = constant, y changes */
01308     for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(ta.w - 1, i));) {
01309       /* the right side is unused? */
01310       if (++i == ta.h) {
01311         ta.w--;
01312         goto restart;
01313       }
01314     }
01315 
01316     /* check the upper side, y = constant, x changes */
01317     for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(i, 0));) {
01318       /* the left side is unused? */
01319       if (++i == ta.w) {
01320         ta.tile += TileDiffXY(0, 1);
01321         ta.h--;
01322         goto restart;
01323       }
01324     }
01325 
01326     /* check the lower side, y = constant, x changes */
01327     for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(i, ta.h - 1));) {
01328       /* the left side is unused? */
01329       if (++i == ta.w) {
01330         ta.h--;
01331         goto restart;
01332       }
01333     }
01334   } else {
01335     ta.Clear();
01336   }
01337 
01338   st->train_station = ta;
01339 }
01340 
01351 template <class T>
01352 CommandCost RemoveFromRailBaseStation(TileArea ta, SmallVector<T *, 4> &affected_stations, DoCommandFlag flags, Money removal_cost, bool keep_rail)
01353 {
01354   /* Count of the number of tiles removed */
01355   int quantity = 0;
01356   CommandCost total_cost(EXPENSES_CONSTRUCTION);
01357 
01358   /* Do the action for every tile into the area */
01359   TILE_AREA_LOOP(tile, ta) {
01360     /* Make sure the specified tile is a rail station */
01361     if (!HasStationTileRail(tile)) continue;
01362 
01363     /* If there is a vehicle on ground, do not allow to remove (flood) the tile */
01364     CommandCost ret = EnsureNoVehicleOnGround(tile);
01365     if (ret.Failed()) continue;
01366 
01367     /* Check ownership of station */
01368     T *st = T::GetByTile(tile);
01369     if (st == NULL) continue;
01370 
01371     if (_current_company != OWNER_WATER) {
01372       CommandCost ret = CheckOwnership(st->owner);
01373       if (ret.Failed()) continue;
01374     }
01375 
01376     /* If we reached here, the tile is valid so increase the quantity of tiles we will remove */
01377     quantity++;
01378 
01379     if (keep_rail || IsStationTileBlocked(tile)) {
01380       /* Don't refund the 'steel' of the track when we keep the
01381        *  rail, or when the tile didn't have any rail at all. */
01382       total_cost.AddCost(-_price[PR_CLEAR_RAIL]);
01383     }
01384 
01385     if (flags & DC_EXEC) {
01386       /* read variables before the station tile is removed */
01387       uint specindex = GetCustomStationSpecIndex(tile);
01388       Track track = GetRailStationTrack(tile);
01389       Owner owner = GetTileOwner(tile);
01390       RailType rt = GetRailType(tile);
01391       Train *v = NULL;
01392 
01393       if (HasStationReservation(tile)) {
01394         v = GetTrainForReservation(tile, track);
01395         if (v != NULL) {
01396           /* Free train reservation. */
01397           FreeTrainTrackReservation(v);
01398           if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), false);
01399           Vehicle *temp = v;
01400           for (; temp->Next() != NULL; temp = temp->Next()) { }
01401           if (IsRailStationTile(temp->tile)) SetRailStationPlatformReservation(temp->tile, TrackdirToExitdir(ReverseTrackdir(temp->GetVehicleTrackdir())), false);
01402         }
01403       }
01404 
01405       bool build_rail = keep_rail && !IsStationTileBlocked(tile);
01406 
01407       DoClearSquare(tile);
01408       DeleteNewGRFInspectWindow(GSF_STATIONS, tile);
01409       if (build_rail) MakeRailNormal(tile, owner, TrackToTrackBits(track), rt);
01410 
01411       st->rect.AfterRemoveTile(st, tile);
01412       AddTrackToSignalBuffer(tile, track, owner);
01413       YapfNotifyTrackLayoutChange(tile, track);
01414 
01415       DeallocateSpecFromStation(st, specindex);
01416 
01417       affected_stations.Include(st);
01418 
01419       if (v != NULL) {
01420         /* Restore station reservation. */
01421         if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
01422         TryPathReserve(v, true, true);
01423         for (; v->Next() != NULL; v = v->Next()) { }
01424         if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), true);
01425       }
01426     }
01427   }
01428 
01429   if (quantity == 0) return_cmd_error(STR_ERROR_THERE_IS_NO_STATION);
01430 
01431   for (T **stp = affected_stations.Begin(); stp != affected_stations.End(); stp++) {
01432     T *st = *stp;
01433 
01434     /* now we need to make the "spanned" area of the railway station smaller
01435      * if we deleted something at the edges.
01436      * we also need to adjust train_tile. */
01437     MakeRailStationAreaSmaller(st);
01438     UpdateStationSignCoord(st);
01439 
01440     /* if we deleted the whole station, delete the train facility. */
01441     if (st->train_station.tile == INVALID_TILE) {
01442       st->facilities &= ~FACIL_TRAIN;
01443       SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_TRAINS);
01444       st->UpdateVirtCoord();
01445       DeleteStationIfEmpty(st);
01446     }
01447   }
01448 
01449   total_cost.AddCost(quantity * removal_cost);
01450   return total_cost;
01451 }
01452 
01464 CommandCost CmdRemoveFromRailStation(TileIndex start, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01465 {
01466   TileIndex end = p1 == 0 ? start : p1;
01467   if (start >= MapSize() || end >= MapSize()) return CMD_ERROR;
01468 
01469   TileArea ta(start, end);
01470   SmallVector<Station *, 4> affected_stations;
01471 
01472   CommandCost ret = RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_STATION_RAIL], HasBit(p2, 0));
01473   if (ret.Failed()) return ret;
01474 
01475   /* Do all station specific functions here. */
01476   for (Station **stp = affected_stations.Begin(); stp != affected_stations.End(); stp++) {
01477     Station *st = *stp;
01478 
01479     if (st->train_station.tile == INVALID_TILE) SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_TRAINS);
01480     st->MarkTilesDirty(false);
01481     st->RecomputeIndustriesNear();
01482   }
01483 
01484   /* Now apply the rail cost to the number that we deleted */
01485   return ret;
01486 }
01487 
01499 CommandCost CmdRemoveFromRailWaypoint(TileIndex start, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01500 {
01501   TileIndex end = p1 == 0 ? start : p1;
01502   if (start >= MapSize() || end >= MapSize()) return CMD_ERROR;
01503 
01504   TileArea ta(start, end);
01505   SmallVector<Waypoint *, 4> affected_stations;
01506 
01507   return RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_WAYPOINT_RAIL], HasBit(p2, 0));
01508 }
01509 
01510 
01518 template <class T>
01519 CommandCost RemoveRailStation(T *st, DoCommandFlag flags)
01520 {
01521   /* Current company owns the station? */
01522   if (_current_company != OWNER_WATER) {
01523     CommandCost ret = CheckOwnership(st->owner);
01524     if (ret.Failed()) return ret;
01525   }
01526 
01527   /* determine width and height of platforms */
01528   TileArea ta = st->train_station;
01529 
01530   assert(ta.w != 0 && ta.h != 0);
01531 
01532   CommandCost cost(EXPENSES_CONSTRUCTION);
01533   /* clear all areas of the station */
01534   TILE_AREA_LOOP(tile, ta) {
01535     /* only remove tiles that are actually train station tiles */
01536     if (!st->TileBelongsToRailStation(tile)) continue;
01537 
01538     CommandCost ret = EnsureNoVehicleOnGround(tile);
01539     if (ret.Failed()) return ret;
01540 
01541     cost.AddCost(_price[PR_CLEAR_STATION_RAIL]);
01542     if (flags & DC_EXEC) {
01543       /* read variables before the station tile is removed */
01544       Track track = GetRailStationTrack(tile);
01545       Owner owner = GetTileOwner(tile); // _current_company can be OWNER_WATER
01546       Train *v = NULL;
01547       if (HasStationReservation(tile)) {
01548         v = GetTrainForReservation(tile, track);
01549         if (v != NULL) FreeTrainTrackReservation(v);
01550       }
01551       DoClearSquare(tile);
01552       DeleteNewGRFInspectWindow(GSF_STATIONS, tile);
01553       AddTrackToSignalBuffer(tile, track, owner);
01554       YapfNotifyTrackLayoutChange(tile, track);
01555       if (v != NULL) TryPathReserve(v, true);
01556     }
01557   }
01558 
01559   if (flags & DC_EXEC) {
01560     st->rect.AfterRemoveRect(st, st->train_station);
01561 
01562     st->train_station.Clear();
01563 
01564     st->facilities &= ~FACIL_TRAIN;
01565 
01566     free(st->speclist);
01567     st->num_specs = 0;
01568     st->speclist  = NULL;
01569     st->cached_anim_triggers = 0;
01570 
01571     SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_TRAINS);
01572     st->UpdateVirtCoord();
01573     DeleteStationIfEmpty(st);
01574   }
01575 
01576   return cost;
01577 }
01578 
01585 static CommandCost RemoveRailStation(TileIndex tile, DoCommandFlag flags)
01586 {
01587   /* if there is flooding, remove platforms tile by tile */
01588   if (_current_company == OWNER_WATER) {
01589     return DoCommand(tile, 0, 0, DC_EXEC, CMD_REMOVE_FROM_RAIL_STATION);
01590   }
01591 
01592   Station *st = Station::GetByTile(tile);
01593   CommandCost cost = RemoveRailStation(st, flags);
01594 
01595   if (flags & DC_EXEC) st->RecomputeIndustriesNear();
01596 
01597   return cost;
01598 }
01599 
01606 static CommandCost RemoveRailWaypoint(TileIndex tile, DoCommandFlag flags)
01607 {
01608   /* if there is flooding, remove waypoints tile by tile */
01609   if (_current_company == OWNER_WATER) {
01610     return DoCommand(tile, 0, 0, DC_EXEC, CMD_REMOVE_FROM_RAIL_WAYPOINT);
01611   }
01612 
01613   return RemoveRailStation(Waypoint::GetByTile(tile), flags);
01614 }
01615 
01616 
01622 static RoadStop **FindRoadStopSpot(bool truck_station, Station *st)
01623 {
01624   RoadStop **primary_stop = (truck_station) ? &st->truck_stops : &st->bus_stops;
01625 
01626   if (*primary_stop == NULL) {
01627     /* we have no roadstop of the type yet, so write a "primary stop" */
01628     return primary_stop;
01629   } else {
01630     /* there are stops already, so append to the end of the list */
01631     RoadStop *stop = *primary_stop;
01632     while (stop->next != NULL) stop = stop->next;
01633     return &stop->next;
01634   }
01635 }
01636 
01637 static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags);
01638 
01648 static CommandCost FindJoiningRoadStop(StationID existing_stop, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
01649 {
01650   return FindJoiningBaseStation<Station, STR_ERROR_MUST_REMOVE_ROAD_STOP_FIRST>(existing_stop, station_to_join, adjacent, ta, st);
01651 }
01652 
01668 CommandCost CmdBuildRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01669 {
01670   bool type = HasBit(p2, 0);
01671   bool is_drive_through = HasBit(p2, 1);
01672   RoadTypes rts = Extract<RoadTypes, 2, 2>(p2);
01673   StationID station_to_join = GB(p2, 16, 16);
01674   bool reuse = (station_to_join != NEW_STATION);
01675   if (!reuse) station_to_join = INVALID_STATION;
01676   bool distant_join = (station_to_join != INVALID_STATION);
01677 
01678   uint8 width = (uint8)GB(p1, 0, 8);
01679   uint8 lenght = (uint8)GB(p1, 8, 8);
01680 
01681   /* Check if the requested road stop is too big */
01682   if (width > _settings_game.station.station_spread || lenght > _settings_game.station.station_spread) return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
01683   /* Check for incorrect width / lenght. */
01684   if (width == 0 || lenght == 0) return CMD_ERROR;
01685   /* Check if the first tile and the last tile are valid */
01686   if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, lenght - 1) == INVALID_TILE) return CMD_ERROR;
01687 
01688   TileArea roadstop_area(tile, width, lenght);
01689 
01690   if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
01691 
01692   if (!HasExactlyOneBit(rts) || !HasRoadTypesAvail(_current_company, rts)) return CMD_ERROR;
01693 
01694   /* Trams only have drive through stops */
01695   if (!is_drive_through && HasBit(rts, ROADTYPE_TRAM)) return CMD_ERROR;
01696 
01697   DiagDirection ddir = Extract<DiagDirection, 6, 2>(p2);
01698 
01699   /* Safeguard the parameters. */
01700   if (!IsValidDiagDirection(ddir)) return CMD_ERROR;
01701   /* If it is a drive-through stop, check for valid axis. */
01702   if (is_drive_through && !IsValidAxis((Axis)ddir)) return CMD_ERROR;
01703 
01704   CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
01705   if (ret.Failed()) return ret;
01706 
01707   /* Total road stop cost. */
01708   CommandCost cost(EXPENSES_CONSTRUCTION, roadstop_area.w * roadstop_area.h * _price[type ? PR_BUILD_STATION_TRUCK : PR_BUILD_STATION_BUS]);
01709   StationID est = INVALID_STATION;
01710   ret = CheckFlatLandRoadStop(roadstop_area, flags, is_drive_through ? 5 << ddir : 1 << ddir, is_drive_through, type, DiagDirToAxis(ddir), &est, rts);
01711   if (ret.Failed()) return ret;
01712   cost.AddCost(ret);
01713 
01714   Station *st = NULL;
01715   ret = FindJoiningRoadStop(est, station_to_join, HasBit(p2, 5), roadstop_area, &st);
01716   if (ret.Failed()) return ret;
01717 
01718   /* Find a deleted station close to us */
01719   if (st == NULL && reuse) st = GetClosestDeletedStation(tile);
01720 
01721   /* Check if this number of road stops can be allocated. */
01722   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);
01723 
01724   if (st != NULL) {
01725     if (st->owner != _current_company) {
01726       return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_STATION);
01727     }
01728 
01729     CommandCost ret = st->rect.BeforeAddRect(roadstop_area.tile, roadstop_area.w, roadstop_area.h, StationRect::ADD_TEST);
01730     if (ret.Failed()) return ret;
01731   } else {
01732     /* allocate and initialize new station */
01733     if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
01734 
01735     if (flags & DC_EXEC) {
01736       st = new Station(tile);
01737 
01738       st->town = ClosestTownFromTile(tile, UINT_MAX);
01739       st->string_id = GenerateStationName(st, tile, STATIONNAMING_ROAD);
01740 
01741       if (Company::IsValidID(_current_company)) {
01742         SetBit(st->town->have_ratings, _current_company);
01743       }
01744     }
01745   }
01746 
01747   if (flags & DC_EXEC) {
01748     /* Check every tile in the area. */
01749     TILE_AREA_LOOP(cur_tile, roadstop_area) {
01750       RoadTypes cur_rts = GetRoadTypes(cur_tile);
01751       Owner road_owner = HasBit(cur_rts, ROADTYPE_ROAD) ? GetRoadOwner(cur_tile, ROADTYPE_ROAD) : _current_company;
01752       Owner tram_owner = HasBit(cur_rts, ROADTYPE_TRAM) ? GetRoadOwner(cur_tile, ROADTYPE_TRAM) : _current_company;
01753 
01754       if (IsTileType(cur_tile, MP_STATION) && IsRoadStop(cur_tile)) {
01755         RemoveRoadStop(cur_tile, flags);
01756       }
01757 
01758       RoadStop *road_stop = new RoadStop(cur_tile);
01759       /* Insert into linked list of RoadStops. */
01760       RoadStop **currstop = FindRoadStopSpot(type, st);
01761       *currstop = road_stop;
01762 
01763       if (type) {
01764         st->truck_station.Add(cur_tile);
01765       } else {
01766         st->bus_station.Add(cur_tile);
01767       }
01768 
01769       /* Initialize an empty station. */
01770       st->AddFacility((type) ? FACIL_TRUCK_STOP : FACIL_BUS_STOP, cur_tile);
01771 
01772       st->rect.BeforeAddTile(cur_tile, StationRect::ADD_TRY);
01773 
01774       RoadStopType rs_type = type ? ROADSTOP_TRUCK : ROADSTOP_BUS;
01775       if (is_drive_through) {
01776         MakeDriveThroughRoadStop(cur_tile, st->owner, road_owner, tram_owner, st->index, rs_type, rts | cur_rts, DiagDirToAxis(ddir));
01777         road_stop->MakeDriveThrough();
01778       } else {
01779         MakeRoadStop(cur_tile, st->owner, st->index, rs_type, rts, ddir);
01780       }
01781 
01782       MarkTileDirtyByTile(cur_tile);
01783     }
01784   }
01785 
01786   if (st != NULL) {
01787     st->UpdateVirtCoord();
01788     UpdateStationAcceptance(st, false);
01789     st->RecomputeIndustriesNear();
01790     InvalidateWindowData(WC_SELECT_STATION, 0, 0);
01791     InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
01792     SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_ROADVEHS);
01793   }
01794   return cost;
01795 }
01796 
01797 
01798 static Vehicle *ClearRoadStopStatusEnum(Vehicle *v, void *)
01799 {
01800   if (v->type == VEH_ROAD) {
01801     /* Okay... we are a road vehicle on a drive through road stop.
01802      * But that road stop has just been removed, so we need to make
01803      * sure we are in a valid state... however, vehicles can also
01804      * turn on road stop tiles, so only clear the 'road stop' state
01805      * bits and only when the state was 'in road stop', otherwise
01806      * we'll end up clearing the turn around bits. */
01807     RoadVehicle *rv = RoadVehicle::From(v);
01808     if (HasBit(rv->state, RVS_IN_DT_ROAD_STOP)) rv->state &= RVSB_ROAD_STOP_TRACKDIR_MASK;
01809   }
01810 
01811   return NULL;
01812 }
01813 
01814 
01821 static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags)
01822 {
01823   Station *st = Station::GetByTile(tile);
01824 
01825   if (_current_company != OWNER_WATER) {
01826     CommandCost ret = CheckOwnership(st->owner);
01827     if (ret.Failed()) return ret;
01828   }
01829 
01830   bool is_truck = IsTruckStop(tile);
01831 
01832   RoadStop **primary_stop;
01833   RoadStop *cur_stop;
01834   if (is_truck) { // truck stop
01835     primary_stop = &st->truck_stops;
01836     cur_stop = RoadStop::GetByTile(tile, ROADSTOP_TRUCK);
01837   } else {
01838     primary_stop = &st->bus_stops;
01839     cur_stop = RoadStop::GetByTile(tile, ROADSTOP_BUS);
01840   }
01841 
01842   assert(cur_stop != NULL);
01843 
01844   /* don't do the check for drive-through road stops when company bankrupts */
01845   if (IsDriveThroughStopTile(tile) && (flags & DC_BANKRUPT)) {
01846     /* remove the 'going through road stop' status from all vehicles on that tile */
01847     if (flags & DC_EXEC) FindVehicleOnPos(tile, NULL, &ClearRoadStopStatusEnum);
01848   } else {
01849     CommandCost ret = EnsureNoVehicleOnGround(tile);
01850     if (ret.Failed()) return ret;
01851   }
01852 
01853   if (flags & DC_EXEC) {
01854     if (*primary_stop == cur_stop) {
01855       /* removed the first stop in the list */
01856       *primary_stop = cur_stop->next;
01857       /* removed the only stop? */
01858       if (*primary_stop == NULL) {
01859         st->facilities &= (is_truck ? ~FACIL_TRUCK_STOP : ~FACIL_BUS_STOP);
01860       }
01861     } else {
01862       /* tell the predecessor in the list to skip this stop */
01863       RoadStop *pred = *primary_stop;
01864       while (pred->next != cur_stop) pred = pred->next;
01865       pred->next = cur_stop->next;
01866     }
01867 
01868     if (IsDriveThroughStopTile(tile)) {
01869       /* Clears the tile for us */
01870       cur_stop->ClearDriveThrough();
01871     } else {
01872       DoClearSquare(tile);
01873     }
01874 
01875     SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_ROADVEHS);
01876     delete cur_stop;
01877 
01878     /* Make sure no vehicle is going to the old roadstop */
01879     RoadVehicle *v;
01880     FOR_ALL_ROADVEHICLES(v) {
01881       if (v->First() == v && v->current_order.IsType(OT_GOTO_STATION) &&
01882           v->dest_tile == tile) {
01883         v->dest_tile = v->GetOrderStationLocation(st->index);
01884       }
01885     }
01886 
01887     st->rect.AfterRemoveTile(st, tile);
01888 
01889     st->UpdateVirtCoord();
01890     st->RecomputeIndustriesNear();
01891     DeleteStationIfEmpty(st);
01892 
01893     /* Update the tile area of the truck/bus stop */
01894     if (is_truck) {
01895       st->truck_station.Clear();
01896       for (const RoadStop *rs = st->truck_stops; rs != NULL; rs = rs->next) st->truck_station.Add(rs->xy);
01897     } else {
01898       st->bus_station.Clear();
01899       for (const RoadStop *rs = st->bus_stops; rs != NULL; rs = rs->next) st->bus_station.Add(rs->xy);
01900     }
01901   }
01902 
01903   return CommandCost(EXPENSES_CONSTRUCTION, _price[is_truck ? PR_CLEAR_STATION_TRUCK : PR_CLEAR_STATION_BUS]);
01904 }
01905 
01916 CommandCost CmdRemoveRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01917 {
01918   uint8 width = (uint8)GB(p1, 0, 8);
01919   uint8 height = (uint8)GB(p1, 8, 8);
01920 
01921   /* Check for incorrect width / height. */
01922   if (width == 0 || height == 0) return CMD_ERROR;
01923   /* Check if the first tile and the last tile are valid */
01924   if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, height - 1) == INVALID_TILE) return CMD_ERROR;
01925 
01926   TileArea roadstop_area(tile, width, height);
01927 
01928   int quantity = 0;
01929   CommandCost cost(EXPENSES_CONSTRUCTION);
01930   TILE_AREA_LOOP(cur_tile, roadstop_area) {
01931     /* Make sure the specified tile is a road stop of the correct type */
01932     if (!IsTileType(cur_tile, MP_STATION) || !IsRoadStop(cur_tile) || (uint32)GetRoadStopType(cur_tile) != GB(p2, 0, 1)) continue;
01933 
01934     /* Save the stop info before it is removed */
01935     bool is_drive_through = IsDriveThroughStopTile(cur_tile);
01936     RoadTypes rts = GetRoadTypes(cur_tile);
01937     RoadBits road_bits = IsDriveThroughStopTile(cur_tile) ?
01938         ((GetRoadStopDir(cur_tile) == DIAGDIR_NE) ? ROAD_X : ROAD_Y) :
01939         DiagDirToRoadBits(GetRoadStopDir(cur_tile));
01940 
01941     Owner road_owner = GetRoadOwner(cur_tile, ROADTYPE_ROAD);
01942     Owner tram_owner = GetRoadOwner(cur_tile, ROADTYPE_TRAM);
01943     CommandCost ret = RemoveRoadStop(cur_tile, flags);
01944     if (ret.Failed()) return ret;
01945     cost.AddCost(ret);
01946 
01947     quantity++;
01948     /* If the stop was a drive-through stop replace the road */
01949     if ((flags & DC_EXEC) && is_drive_through) {
01950       MakeRoadNormal(cur_tile, road_bits, rts, ClosestTownFromTile(cur_tile, UINT_MAX)->index,
01951           road_owner, tram_owner);
01952     }
01953   }
01954 
01955   if (quantity == 0) return_cmd_error(STR_ERROR_THERE_IS_NO_STATION);
01956 
01957   return cost;
01958 }
01959 
01967 static uint GetMinimalAirportDistanceToTile(const AirportSpec *as, TileIndex town_tile, TileIndex airport_tile)
01968 {
01969   uint ttx = TileX(town_tile); // X, Y of town
01970   uint tty = TileY(town_tile);
01971 
01972   uint atx = TileX(airport_tile); // X, Y of northern airport corner
01973   uint aty = TileY(airport_tile);
01974 
01975   uint btx = TileX(airport_tile) + as->size_x - 1; // X, Y of southern corner
01976   uint bty = TileY(airport_tile) + as->size_y - 1;
01977 
01978   /* if ttx < atx, dx = atx - ttx
01979    * if atx <= ttx <= btx, dx = 0
01980    * else, dx = ttx - btx (similiar for dy) */
01981   uint dx = ttx < atx ? atx - ttx : (ttx <= btx ? 0 : ttx - btx);
01982   uint dy = tty < aty ? aty - tty : (tty <= bty ? 0 : tty - bty);
01983 
01984   return dx + dy;
01985 }
01986 
01996 uint8 GetAirportNoiseLevelForTown(const AirportSpec *as, TileIndex town_tile, TileIndex tile)
01997 {
01998   /* 0 cannot be accounted, and 1 is the lowest that can be reduced from town.
01999    * So no need to go any further*/
02000   if (as->noise_level < 2) return as->noise_level;
02001 
02002   uint distance = GetMinimalAirportDistanceToTile(as, town_tile, tile);
02003 
02004   /* The steps for measuring noise reduction are based on the "magical" (and arbitrary) 8 base distance
02005    * adding the town_council_tolerance 4 times, as a way to graduate, depending of the tolerance.
02006    * Basically, it says that the less tolerant a town is, the bigger the distance before
02007    * an actual decrease can be granted */
02008   uint8 town_tolerance_distance = 8 + (_settings_game.difficulty.town_council_tolerance * 4);
02009 
02010   /* now, we want to have the distance segmented using the distance judged bareable by town
02011    * This will give us the coefficient of reduction the distance provides. */
02012   uint noise_reduction = distance / town_tolerance_distance;
02013 
02014   /* If the noise reduction equals the airport noise itself, don't give it for free.
02015    * Otherwise, simply reduce the airport's level. */
02016   return noise_reduction >= as->noise_level ? 1 : as->noise_level - noise_reduction;
02017 }
02018 
02026 Town *AirportGetNearestTown(const AirportSpec *as, TileIndex airport_tile)
02027 {
02028   Town *t, *nearest = NULL;
02029   uint add = as->size_x + as->size_y - 2; // GetMinimalAirportDistanceToTile can differ from DistanceManhattan by this much
02030   uint mindist = UINT_MAX - add; // prevent overflow
02031   FOR_ALL_TOWNS(t) {
02032     if (DistanceManhattan(t->xy, airport_tile) < mindist + add) { // avoid calling GetMinimalAirportDistanceToTile too often
02033       uint dist = GetMinimalAirportDistanceToTile(as, t->xy, airport_tile);
02034       if (dist < mindist) {
02035         nearest = t;
02036         mindist = dist;
02037       }
02038     }
02039   }
02040 
02041   return nearest;
02042 }
02043 
02044 
02046 void UpdateAirportsNoise()
02047 {
02048   Town *t;
02049   const Station *st;
02050 
02051   FOR_ALL_TOWNS(t) t->noise_reached = 0;
02052 
02053   FOR_ALL_STATIONS(st) {
02054     if (st->airport.tile != INVALID_TILE) {
02055       const AirportSpec *as = st->airport.GetSpec();
02056       Town *nearest = AirportGetNearestTown(as, st->airport.tile);
02057       nearest->noise_reached += GetAirportNoiseLevelForTown(as, nearest->xy, st->airport.tile);
02058     }
02059   }
02060 }
02061 
02075 CommandCost CmdBuildAirport(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02076 {
02077   StationID station_to_join = GB(p2, 16, 16);
02078   bool reuse = (station_to_join != NEW_STATION);
02079   if (!reuse) station_to_join = INVALID_STATION;
02080   bool distant_join = (station_to_join != INVALID_STATION);
02081   byte airport_type = GB(p1, 0, 8);
02082   byte layout = GB(p1, 8, 8);
02083 
02084   if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
02085 
02086   if (airport_type >= NUM_AIRPORTS) return CMD_ERROR;
02087 
02088   CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
02089   if (ret.Failed()) return ret;
02090 
02091   /* Check if a valid, buildable airport was chosen for construction */
02092   const AirportSpec *as = AirportSpec::Get(airport_type);
02093   if (!as->IsAvailable() || layout >= as->num_table) return CMD_ERROR;
02094 
02095   Direction rotation = as->rotation[layout];
02096   Town *t = ClosestTownFromTile(tile, UINT_MAX);
02097   int w = as->size_x;
02098   int h = as->size_y;
02099   if (rotation == DIR_E || rotation == DIR_W) Swap(w, h);
02100 
02101   if (w > _settings_game.station.station_spread || h > _settings_game.station.station_spread) {
02102     return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
02103   }
02104 
02105   CommandCost cost = CheckFlatLand(TileArea(tile, w, h), flags);
02106   if (cost.Failed()) return cost;
02107 
02108   /* The noise level is the noise from the airport and reduce it to account for the distance to the town center. */
02109   Town *nearest = AirportGetNearestTown(as, tile);
02110   uint newnoise_level = GetAirportNoiseLevelForTown(as, nearest->xy, tile);
02111 
02112   /* Check if local auth would allow a new airport */
02113   StringID authority_refuse_message = STR_NULL;
02114 
02115   if (_settings_game.economy.station_noise_level) {
02116     /* do not allow to build a new airport if this raise the town noise over the maximum allowed by town */
02117     if ((nearest->noise_reached + newnoise_level) > nearest->MaxTownNoise()) {
02118       authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_NOISE;
02119     }
02120   } else {
02121     uint num = 0;
02122     const Station *st;
02123     FOR_ALL_STATIONS(st) {
02124       if (st->town == t && (st->facilities & FACIL_AIRPORT) && st->airport.type != AT_OILRIG) num++;
02125     }
02126     if (num >= 2) {
02127       authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_AIRPORT;
02128     }
02129   }
02130 
02131   if (authority_refuse_message != STR_NULL) {
02132     SetDParam(0, t->index);
02133     return_cmd_error(authority_refuse_message);
02134   }
02135 
02136   Station *st = NULL;
02137   ret = FindJoiningStation(INVALID_STATION, station_to_join, HasBit(p2, 0), TileArea(tile, w, h), &st);
02138   if (ret.Failed()) return ret;
02139 
02140   /* Distant join */
02141   if (st == NULL && distant_join) st = Station::GetIfValid(station_to_join);
02142 
02143   /* Find a deleted station close to us */
02144   if (st == NULL && reuse) st = GetClosestDeletedStation(tile);
02145 
02146   if (st != NULL) {
02147     if (st->owner != _current_company) {
02148       return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_STATION);
02149     }
02150 
02151     CommandCost ret = st->rect.BeforeAddRect(tile, w, h, StationRect::ADD_TEST);
02152     if (ret.Failed()) return ret;
02153 
02154     if (st->airport.tile != INVALID_TILE) {
02155       return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_AIRPORT);
02156     }
02157   } else {
02158     /* allocate and initialize new station */
02159     if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
02160 
02161     if (flags & DC_EXEC) {
02162       st = new Station(tile);
02163 
02164       st->town = t;
02165       st->string_id = GenerateStationName(st, tile, !(GetAirport(airport_type)->flags & AirportFTAClass::AIRPLANES) ? STATIONNAMING_HELIPORT : STATIONNAMING_AIRPORT);
02166 
02167       if (Company::IsValidID(_current_company)) {
02168         SetBit(st->town->have_ratings, _current_company);
02169       }
02170     }
02171   }
02172 
02173   const AirportTileTable *it = as->table[layout];
02174   do {
02175     cost.AddCost(_price[PR_BUILD_STATION_AIRPORT]);
02176   } while ((++it)->ti.x != -0x80);
02177 
02178   if (flags & DC_EXEC) {
02179     /* Always add the noise, so there will be no need to recalculate when option toggles */
02180     nearest->noise_reached += newnoise_level;
02181 
02182     st->AddFacility(FACIL_AIRPORT, tile);
02183     st->airport.type = airport_type;
02184     st->airport.layout = layout;
02185     st->airport.flags = 0;
02186     st->airport.rotation = rotation;
02187 
02188     st->rect.BeforeAddRect(tile, w, h, StationRect::ADD_TRY);
02189 
02190     it = as->table[layout];
02191     do {
02192       TileIndex cur_tile = tile + ToTileIndexDiff(it->ti);
02193       MakeAirport(cur_tile, st->owner, st->index, it->gfx, WATER_CLASS_INVALID);
02194       SetStationTileRandomBits(cur_tile, GB(Random(), 0, 4));
02195       st->airport.Add(cur_tile);
02196 
02197       if (AirportTileSpec::Get(GetTranslatedAirportTileID(it->gfx))->animation.status != ANIM_STATUS_NO_ANIMATION) AddAnimatedTile(cur_tile);
02198     } while ((++it)->ti.x != -0x80);
02199 
02200     /* Only call the animation trigger after all tiles have been built */
02201     it = as->table[layout];
02202     do {
02203       TileIndex cur_tile = tile + ToTileIndexDiff(it->ti);
02204       AirportTileAnimationTrigger(st, cur_tile, AAT_BUILT);
02205     } while ((++it)->ti.x != -0x80);
02206 
02207     UpdateAirplanesOnNewStation(st);
02208 
02209     st->UpdateVirtCoord();
02210     UpdateStationAcceptance(st, false);
02211     st->RecomputeIndustriesNear();
02212     InvalidateWindowData(WC_SELECT_STATION, 0, 0);
02213     InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
02214     SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_PLANES);
02215 
02216     if (_settings_game.economy.station_noise_level) {
02217       SetWindowDirty(WC_TOWN_VIEW, st->town->index);
02218     }
02219   }
02220 
02221   return cost;
02222 }
02223 
02230 static CommandCost RemoveAirport(TileIndex tile, DoCommandFlag flags)
02231 {
02232   Station *st = Station::GetByTile(tile);
02233 
02234   if (_current_company != OWNER_WATER) {
02235     CommandCost ret = CheckOwnership(st->owner);
02236     if (ret.Failed()) return ret;
02237   }
02238 
02239   tile = st->airport.tile;
02240 
02241   CommandCost cost(EXPENSES_CONSTRUCTION);
02242 
02243   const Aircraft *a;
02244   FOR_ALL_AIRCRAFT(a) {
02245     if (!a->IsNormalAircraft()) continue;
02246     if (a->targetairport == st->index && a->state != FLYING) return CMD_ERROR;
02247   }
02248 
02249   TILE_AREA_LOOP(tile_cur, st->airport) {
02250     if (!st->TileBelongsToAirport(tile_cur)) continue;
02251 
02252     CommandCost ret = EnsureNoVehicleOnGround(tile_cur);
02253     if (ret.Failed()) return ret;
02254 
02255     cost.AddCost(_price[PR_CLEAR_STATION_AIRPORT]);
02256 
02257     if (flags & DC_EXEC) {
02258       if (IsHangarTile(tile_cur)) OrderBackup::Reset(tile_cur, false);
02259       DeleteAnimatedTile(tile_cur);
02260       DoClearSquare(tile_cur);
02261       DeleteNewGRFInspectWindow(GSF_AIRPORTTILES, tile_cur);
02262     }
02263   }
02264 
02265   if (flags & DC_EXEC) {
02266     const AirportSpec *as = st->airport.GetSpec();
02267     for (uint i = 0; i < st->airport.GetNumHangars(); ++i) {
02268       DeleteWindowById(
02269         WC_VEHICLE_DEPOT, st->airport.GetHangarTile(i)
02270       );
02271     }
02272 
02273     /* The noise level is the noise from the airport and reduce it to account for the distance to the town center.
02274      * And as for construction, always remove it, even if the setting is not set, in order to avoid the
02275      * need of recalculation */
02276     Town *nearest = AirportGetNearestTown(as, tile);
02277     nearest->noise_reached -= GetAirportNoiseLevelForTown(as, nearest->xy, tile);
02278 
02279     st->rect.AfterRemoveRect(st, st->airport);
02280 
02281     st->airport.Clear();
02282     st->facilities &= ~FACIL_AIRPORT;
02283 
02284     SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_PLANES);
02285 
02286     if (_settings_game.economy.station_noise_level) {
02287       SetWindowDirty(WC_TOWN_VIEW, st->town->index);
02288     }
02289 
02290     st->UpdateVirtCoord();
02291     st->RecomputeIndustriesNear();
02292     DeleteStationIfEmpty(st);
02293     DeleteNewGRFInspectWindow(GSF_AIRPORTS, st->index);
02294   }
02295 
02296   return cost;
02297 }
02298 
02305 bool HasStationInUse(StationID station, bool include_company, CompanyID company)
02306 {
02307   const Vehicle *v;
02308   FOR_ALL_VEHICLES(v) {
02309     if ((v->owner == company) == include_company) {
02310       const Order *order;
02311       FOR_VEHICLE_ORDERS(v, order) {
02312         if ((order->IsType(OT_GOTO_STATION) || order->IsType(OT_GOTO_WAYPOINT)) && order->GetDestination() == station) {
02313           return true;
02314         }
02315       }
02316     }
02317   }
02318   return false;
02319 }
02320 
02321 static const TileIndexDiffC _dock_tileoffs_chkaround[] = {
02322   {-1,  0},
02323   { 0,  0},
02324   { 0,  0},
02325   { 0, -1}
02326 };
02327 static const byte _dock_w_chk[4] = { 2, 1, 2, 1 };
02328 static const byte _dock_h_chk[4] = { 1, 2, 1, 2 };
02329 
02339 CommandCost CmdBuildDock(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02340 {
02341   StationID station_to_join = GB(p2, 16, 16);
02342   bool reuse = (station_to_join != NEW_STATION);
02343   if (!reuse) station_to_join = INVALID_STATION;
02344   bool distant_join = (station_to_join != INVALID_STATION);
02345 
02346   if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
02347 
02348   DiagDirection direction = GetInclinedSlopeDirection(GetTileSlope(tile, NULL));
02349   if (direction == INVALID_DIAGDIR) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
02350   direction = ReverseDiagDir(direction);
02351 
02352   /* Docks cannot be placed on rapids */
02353   if (HasTileWaterGround(tile)) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
02354 
02355   CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
02356   if (ret.Failed()) return ret;
02357 
02358   if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
02359 
02360   ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
02361   if (ret.Failed()) return ret;
02362 
02363   TileIndex tile_cur = tile + TileOffsByDiagDir(direction);
02364 
02365   if (!IsTileType(tile_cur, MP_WATER) || GetTileSlope(tile_cur, NULL) != SLOPE_FLAT) {
02366     return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
02367   }
02368 
02369   if (MayHaveBridgeAbove(tile_cur) && IsBridgeAbove(tile_cur)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
02370 
02371   /* Get the water class of the water tile before it is cleared.*/
02372   WaterClass wc = GetWaterClass(tile_cur);
02373 
02374   ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
02375   if (ret.Failed()) return ret;
02376 
02377   tile_cur += TileOffsByDiagDir(direction);
02378   if (!IsTileType(tile_cur, MP_WATER) || GetTileSlope(tile_cur, NULL) != SLOPE_FLAT) {
02379     return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
02380   }
02381 
02382   /* middle */
02383   Station *st = NULL;
02384   ret = FindJoiningStation(INVALID_STATION, station_to_join, HasBit(p1, 0),
02385       TileArea(tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
02386           _dock_w_chk[direction], _dock_h_chk[direction]), &st);
02387   if (ret.Failed()) return ret;
02388 
02389   /* Distant join */
02390   if (st == NULL && distant_join) st = Station::GetIfValid(station_to_join);
02391 
02392   /* Find a deleted station close to us */
02393   if (st == NULL && reuse) st = GetClosestDeletedStation(tile);
02394 
02395   if (st != NULL) {
02396     if (st->owner != _current_company) {
02397       return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_STATION);
02398     }
02399 
02400     CommandCost ret = st->rect.BeforeAddRect(
02401         tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
02402         _dock_w_chk[direction], _dock_h_chk[direction], StationRect::ADD_TEST);
02403     if (ret.Failed()) return ret;
02404 
02405     if (st->dock_tile != INVALID_TILE) return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_DOCK);
02406   } else {
02407     /* allocate and initialize new station */
02408     if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
02409 
02410     if (flags & DC_EXEC) {
02411       st = new Station(tile);
02412 
02413       st->town = ClosestTownFromTile(tile, UINT_MAX);
02414       st->string_id = GenerateStationName(st, tile, STATIONNAMING_DOCK);
02415 
02416       if (Company::IsValidID(_current_company)) {
02417         SetBit(st->town->have_ratings, _current_company);
02418       }
02419     }
02420   }
02421 
02422   if (flags & DC_EXEC) {
02423     st->dock_tile = tile;
02424     st->AddFacility(FACIL_DOCK, tile);
02425 
02426     st->rect.BeforeAddRect(
02427         tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
02428         _dock_w_chk[direction], _dock_h_chk[direction], StationRect::ADD_TRY);
02429 
02430     MakeDock(tile, st->owner, st->index, direction, wc);
02431 
02432     st->UpdateVirtCoord();
02433     UpdateStationAcceptance(st, false);
02434     st->RecomputeIndustriesNear();
02435     InvalidateWindowData(WC_SELECT_STATION, 0, 0);
02436     InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
02437     SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_SHIPS);
02438   }
02439 
02440   return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_STATION_DOCK]);
02441 }
02442 
02449 static CommandCost RemoveDock(TileIndex tile, DoCommandFlag flags)
02450 {
02451   Station *st = Station::GetByTile(tile);
02452   CommandCost ret = CheckOwnership(st->owner);
02453   if (ret.Failed()) return ret;
02454 
02455   TileIndex tile1 = st->dock_tile;
02456   TileIndex tile2 = tile1 + TileOffsByDiagDir(GetDockDirection(tile1));
02457 
02458   ret = EnsureNoVehicleOnGround(tile1);
02459   if (ret.Succeeded()) ret = EnsureNoVehicleOnGround(tile2);
02460   if (ret.Failed()) return ret;
02461 
02462   if (flags & DC_EXEC) {
02463     DoClearSquare(tile1);
02464     MarkTileDirtyByTile(tile1);
02465     MakeWaterKeepingClass(tile2, st->owner);
02466 
02467     st->rect.AfterRemoveTile(st, tile1);
02468     st->rect.AfterRemoveTile(st, tile2);
02469 
02470     st->dock_tile = INVALID_TILE;
02471     st->facilities &= ~FACIL_DOCK;
02472 
02473     SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_SHIPS);
02474     st->UpdateVirtCoord();
02475     st->RecomputeIndustriesNear();
02476     DeleteStationIfEmpty(st);
02477   }
02478 
02479   return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_STATION_DOCK]);
02480 }
02481 
02482 #include "table/station_land.h"
02483 
02484 const DrawTileSprites *GetStationTileLayout(StationType st, byte gfx)
02485 {
02486   return &_station_display_datas[st][gfx];
02487 }
02488 
02489 static void DrawTile_Station(TileInfo *ti)
02490 {
02491   const DrawTileSprites *t = NULL;
02492   RoadTypes roadtypes;
02493   int32 total_offset;
02494   int32 custom_ground_offset;
02495   const RailtypeInfo *rti = NULL;
02496   uint32 relocation = 0;
02497   const BaseStation *st = NULL;
02498   const StationSpec *statspec = NULL;
02499 
02500   if (HasStationRail(ti->tile)) {
02501     rti = GetRailTypeInfo(GetRailType(ti->tile));
02502     roadtypes = ROADTYPES_NONE;
02503     total_offset = rti->GetRailtypeSpriteOffset();
02504     custom_ground_offset = rti->fallback_railtype;
02505 
02506     if (IsCustomStationSpecIndex(ti->tile)) {
02507       /* look for customization */
02508       st = BaseStation::GetByTile(ti->tile);
02509       statspec = st->speclist[GetCustomStationSpecIndex(ti->tile)].spec;
02510 
02511       if (statspec != NULL) {
02512         uint tile = GetStationGfx(ti->tile);
02513 
02514         relocation = GetCustomStationRelocation(statspec, st, ti->tile);
02515 
02516         if (HasBit(statspec->callback_mask, CBM_STATION_SPRITE_LAYOUT)) {
02517           uint16 callback = GetStationCallback(CBID_STATION_SPRITE_LAYOUT, 0, 0, statspec, st, ti->tile);
02518           if (callback != CALLBACK_FAILED) tile = (callback & ~1) + GetRailStationAxis(ti->tile);
02519         }
02520 
02521         /* Ensure the chosen tile layout is valid for this custom station */
02522         if (statspec->renderdata != NULL) {
02523           t = &statspec->renderdata[tile < statspec->tiles ? tile : (uint)GetRailStationAxis(ti->tile)];
02524         }
02525       }
02526     }
02527   } else {
02528     roadtypes = IsRoadStop(ti->tile) ? GetRoadTypes(ti->tile) : ROADTYPES_NONE;
02529     total_offset = 0;
02530     custom_ground_offset = 0;
02531   }
02532 
02533   if (IsAirport(ti->tile)) {
02534     StationGfx gfx = GetAirportGfx(ti->tile);
02535     if (gfx >= NEW_AIRPORTTILE_OFFSET) {
02536       const AirportTileSpec *ats = AirportTileSpec::Get(gfx);
02537       if (ats->grf_prop.spritegroup[0] != NULL && DrawNewAirportTile(ti, Station::GetByTile(ti->tile), gfx, ats)) {
02538         return;
02539       }
02540       /* No sprite group (or no valid one) found, meaning no graphics associated.
02541        * Use the substitute one instead */
02542       assert(ats->grf_prop.subst_id != INVALID_AIRPORTTILE);
02543       gfx = ats->grf_prop.subst_id;
02544     }
02545     switch (gfx) {
02546       case APT_RADAR_GRASS_FENCE_SW:
02547         t = &_station_display_datas_airport_radar_grass_fence_sw[GetAnimationFrame(ti->tile)];
02548         break;
02549       case APT_GRASS_FENCE_NE_FLAG:
02550         t = &_station_display_datas_airport_flag_grass_fence_ne[GetAnimationFrame(ti->tile)];
02551         break;
02552       case APT_RADAR_FENCE_SW:
02553         t = &_station_display_datas_airport_radar_fence_sw[GetAnimationFrame(ti->tile)];
02554         break;
02555       case APT_RADAR_FENCE_NE:
02556         t = &_station_display_datas_airport_radar_fence_ne[GetAnimationFrame(ti->tile)];
02557         break;
02558       case APT_GRASS_FENCE_NE_FLAG_2:
02559         t = &_station_display_datas_airport_flag_grass_fence_ne_2[GetAnimationFrame(ti->tile)];
02560         break;
02561     }
02562   }
02563 
02564   Owner owner = GetTileOwner(ti->tile);
02565 
02566   PaletteID palette;
02567   if (Company::IsValidID(owner)) {
02568     palette = COMPANY_SPRITE_COLOUR(owner);
02569   } else {
02570     /* Some stations are not owner by a company, namely oil rigs */
02571     palette = PALETTE_TO_GREY;
02572   }
02573 
02574   if (t == NULL || t->seq == NULL) t = GetStationTileLayout(GetStationType(ti->tile), GetStationGfx(ti->tile));
02575 
02576   /* don't show foundation for docks */
02577   if (ti->tileh != SLOPE_FLAT && !IsDock(ti->tile)) {
02578     if (statspec != NULL && HasBit(statspec->flags, SSF_CUSTOM_FOUNDATIONS)) {
02579       /* Station has custom foundations. */
02580       SpriteID image = GetCustomStationFoundationRelocation(statspec, st, ti->tile);
02581 
02582       if (HasBit(statspec->flags, SSF_EXTENDED_FOUNDATIONS)) {
02583         /* Station provides extended foundations. */
02584 
02585         static const uint8 foundation_parts[] = {
02586           0, 0, 0, 0, // Invalid,  Invalid,   Invalid,   SLOPE_SW
02587           0, 1, 2, 3, // Invalid,  SLOPE_EW,  SLOPE_SE,  SLOPE_WSE
02588           0, 4, 5, 6, // Invalid,  SLOPE_NW,  SLOPE_NS,  SLOPE_NWS
02589           7, 8, 9     // SLOPE_NE, SLOPE_ENW, SLOPE_SEN
02590         };
02591 
02592         AddSortableSpriteToDraw(image + foundation_parts[ti->tileh], PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
02593       } else {
02594         /* Draw simple foundations, built up from 8 possible foundation sprites. */
02595 
02596         /* Each set bit represents one of the eight composite sprites to be drawn.
02597          * 'Invalid' entries will not drawn but are included for completeness. */
02598         static const uint8 composite_foundation_parts[] = {
02599           /* Invalid  (00000000), Invalid   (11010001), Invalid   (11100100), SLOPE_SW  (11100000) */
02600              0x00,                0xD1,                 0xE4,                 0xE0,
02601           /* Invalid  (11001010), SLOPE_EW  (11001001), SLOPE_SE  (11000100), SLOPE_WSE (11000000) */
02602              0xCA,                0xC9,                 0xC4,                 0xC0,
02603           /* Invalid  (11010010), SLOPE_NW  (10010001), SLOPE_NS  (11100100), SLOPE_NWS (10100000) */
02604              0xD2,                0x91,                 0xE4,                 0xA0,
02605           /* SLOPE_NE (01001010), SLOPE_ENW (00001001), SLOPE_SEN (01000100) */
02606              0x4A,                0x09,                 0x44
02607         };
02608 
02609         uint8 parts = composite_foundation_parts[ti->tileh];
02610 
02611         /* If foundations continue beyond the tile's upper sides then
02612          * mask out the last two pieces. */
02613         uint z;
02614         Slope slope = GetFoundationSlope(ti->tile, &z);
02615         if (!HasFoundationNW(ti->tile, slope, z)) ClrBit(parts, 6);
02616         if (!HasFoundationNE(ti->tile, slope, z)) ClrBit(parts, 7);
02617 
02618         if (parts == 0) {
02619           /* We always have to draw at least one sprite to make sure there is a boundingbox and a sprite with the
02620            * correct offset for the childsprites.
02621            * So, draw the (completely empty) sprite of the default foundations. */
02622           goto draw_default_foundation;
02623         }
02624 
02625         StartSpriteCombine();
02626         for (int i = 0; i < 8; i++) {
02627           if (HasBit(parts, i)) {
02628             AddSortableSpriteToDraw(image + i, PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
02629           }
02630         }
02631         EndSpriteCombine();
02632       }
02633 
02634       OffsetGroundSprite(31, 1);
02635       ti->z += ApplyFoundationToSlope(FOUNDATION_LEVELED, &ti->tileh);
02636     } else {
02637 draw_default_foundation:
02638       DrawFoundation(ti, FOUNDATION_LEVELED);
02639     }
02640   }
02641 
02642   if (IsBuoy(ti->tile) || IsDock(ti->tile) || (IsOilRig(ti->tile) && IsTileOnWater(ti->tile))) {
02643     if (ti->tileh == SLOPE_FLAT) {
02644       DrawWaterClassGround(ti);
02645     } else {
02646       assert(IsDock(ti->tile));
02647       TileIndex water_tile = ti->tile + TileOffsByDiagDir(GetDockDirection(ti->tile));
02648       WaterClass wc = GetWaterClass(water_tile);
02649       if (wc == WATER_CLASS_SEA) {
02650         DrawShoreTile(ti->tileh);
02651       } else {
02652         DrawClearLandTile(ti, 3);
02653       }
02654     }
02655   } else {
02656     SpriteID image = t->ground.sprite;
02657     PaletteID pal  = t->ground.pal;
02658     if (rti != NULL && rti->UsesOverlay() && (image == SPR_RAIL_TRACK_X || image == SPR_RAIL_TRACK_Y)) {
02659       SpriteID ground = GetCustomRailSprite(rti, ti->tile, RTSG_GROUND);
02660       DrawGroundSprite(SPR_FLAT_GRASS_TILE, PAL_NONE);
02661       DrawGroundSprite(ground + (image == SPR_RAIL_TRACK_X ? RTO_X : RTO_Y), PAL_NONE);
02662 
02663       if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationReservation(ti->tile)) {
02664         SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
02665         DrawGroundSprite(overlay + (image == SPR_RAIL_TRACK_X ? RTO_X : RTO_Y), PALETTE_CRASH);
02666       }
02667     } else {
02668       if (HasBit(image, SPRITE_MODIFIER_CUSTOM_SPRITE)) {
02669         image += GetCustomStationGroundRelocation(statspec, st, ti->tile);
02670         image += custom_ground_offset;
02671       } else {
02672         image += total_offset;
02673       }
02674       DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, palette));
02675 
02676       /* PBS debugging, draw reserved tracks darker */
02677       if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationRail(ti->tile) && HasStationReservation(ti->tile)) {
02678         const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
02679         DrawGroundSprite(GetRailStationAxis(ti->tile) == AXIS_X ? rti->base_sprites.single_x : rti->base_sprites.single_y, PALETTE_CRASH);
02680       }
02681     }
02682   }
02683 
02684   if (HasStationRail(ti->tile) && HasCatenaryDrawn(GetRailType(ti->tile)) && IsStationTileElectrifiable(ti->tile)) DrawCatenary(ti);
02685 
02686   if (HasBit(roadtypes, ROADTYPE_TRAM)) {
02687     Axis axis = GetRoadStopDir(ti->tile) == DIAGDIR_NE ? AXIS_X : AXIS_Y;
02688     DrawGroundSprite((HasBit(roadtypes, ROADTYPE_ROAD) ? SPR_TRAMWAY_OVERLAY : SPR_TRAMWAY_TRAM) + (axis ^ 1), PAL_NONE);
02689     DrawTramCatenary(ti, axis == AXIS_X ? ROAD_X : ROAD_Y);
02690   }
02691 
02692   if (IsRailWaypoint(ti->tile)) {
02693     /* Don't offset the waypoint graphics; they're always the same. */
02694     total_offset = 0;
02695   }
02696 
02697   DrawRailTileSeq(ti, t, TO_BUILDINGS, total_offset, relocation, palette);
02698 }
02699 
02700 void StationPickerDrawSprite(int x, int y, StationType st, RailType railtype, RoadType roadtype, int image)
02701 {
02702   int32 total_offset = 0;
02703   PaletteID pal = COMPANY_SPRITE_COLOUR(_local_company);
02704   const DrawTileSprites *t = GetStationTileLayout(st, image);
02705   const RailtypeInfo *rti = NULL;
02706 
02707   if (railtype != INVALID_RAILTYPE) {
02708     rti = GetRailTypeInfo(railtype);
02709     total_offset = rti->GetRailtypeSpriteOffset();
02710   }
02711 
02712   SpriteID img = t->ground.sprite;
02713   if ((img == SPR_RAIL_TRACK_X || img == SPR_RAIL_TRACK_Y) && rti->UsesOverlay()) {
02714     SpriteID ground = GetCustomRailSprite(rti, INVALID_TILE, RTSG_GROUND);
02715     DrawSprite(SPR_FLAT_GRASS_TILE, PAL_NONE, x, y);
02716     DrawSprite(ground + (img == SPR_RAIL_TRACK_X ? RTO_X : RTO_Y), PAL_NONE, x, y);
02717   } else {
02718     DrawSprite(img + total_offset, HasBit(img, PALETTE_MODIFIER_COLOUR) ? pal : PAL_NONE, x, y);
02719   }
02720 
02721   if (roadtype == ROADTYPE_TRAM) {
02722     DrawSprite(SPR_TRAMWAY_TRAM + (t->ground.sprite == SPR_ROAD_PAVED_STRAIGHT_X ? 1 : 0), PAL_NONE, x, y);
02723   }
02724 
02725   /* Default waypoint has no railtype specific sprites */
02726   DrawRailTileSeqInGUI(x, y, t, st == STATION_WAYPOINT ? 0 : total_offset, 0, pal);
02727 }
02728 
02729 static uint GetSlopeZ_Station(TileIndex tile, uint x, uint y)
02730 {
02731   return GetTileMaxZ(tile);
02732 }
02733 
02734 static Foundation GetFoundation_Station(TileIndex tile, Slope tileh)
02735 {
02736   return FlatteningFoundation(tileh);
02737 }
02738 
02739 static void GetTileDesc_Station(TileIndex tile, TileDesc *td)
02740 {
02741   td->owner[0] = GetTileOwner(tile);
02742   if (IsDriveThroughStopTile(tile)) {
02743     Owner road_owner = INVALID_OWNER;
02744     Owner tram_owner = INVALID_OWNER;
02745     RoadTypes rts = GetRoadTypes(tile);
02746     if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
02747     if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
02748 
02749     /* Is there a mix of owners? */
02750     if ((tram_owner != INVALID_OWNER && tram_owner != td->owner[0]) ||
02751         (road_owner != INVALID_OWNER && road_owner != td->owner[0])) {
02752       uint i = 1;
02753       if (road_owner != INVALID_OWNER) {
02754         td->owner_type[i] = STR_LAND_AREA_INFORMATION_ROAD_OWNER;
02755         td->owner[i] = road_owner;
02756         i++;
02757       }
02758       if (tram_owner != INVALID_OWNER) {
02759         td->owner_type[i] = STR_LAND_AREA_INFORMATION_TRAM_OWNER;
02760         td->owner[i] = tram_owner;
02761       }
02762     }
02763   }
02764   td->build_date = BaseStation::GetByTile(tile)->build_date;
02765 
02766   if (HasStationTileRail(tile)) {
02767     const StationSpec *spec = GetStationSpec(tile);
02768 
02769     if (spec != NULL) {
02770       td->station_class = StationClass::GetName(spec->cls_id);
02771       td->station_name  = spec->name;
02772 
02773       if (spec->grf_prop.grffile != NULL) {
02774         const GRFConfig *gc = GetGRFConfig(spec->grf_prop.grffile->grfid);
02775         td->grf = gc->GetName();
02776       }
02777     }
02778 
02779     const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(tile));
02780     td->rail_speed = rti->max_speed;
02781   }
02782 
02783   if (IsAirport(tile)) {
02784     const AirportSpec *as = Station::GetByTile(tile)->airport.GetSpec();
02785     td->airport_class = AirportClass::GetName(as->cls_id);
02786     td->airport_name = as->name;
02787 
02788     const AirportTileSpec *ats = AirportTileSpec::GetByTile(tile);
02789     td->airport_tile_name = ats->name;
02790 
02791     if (as->grf_prop.grffile != NULL) {
02792       const GRFConfig *gc = GetGRFConfig(as->grf_prop.grffile->grfid);
02793       td->grf = gc->GetName();
02794     } else if (ats->grf_prop.grffile != NULL) {
02795       const GRFConfig *gc = GetGRFConfig(ats->grf_prop.grffile->grfid);
02796       td->grf = gc->GetName();
02797     }
02798   }
02799 
02800   StringID str;
02801   switch (GetStationType(tile)) {
02802     default: NOT_REACHED();
02803     case STATION_RAIL:     str = STR_LAI_STATION_DESCRIPTION_RAILROAD_STATION; break;
02804     case STATION_AIRPORT:
02805       str = (IsHangar(tile) ? STR_LAI_STATION_DESCRIPTION_AIRCRAFT_HANGAR : STR_LAI_STATION_DESCRIPTION_AIRPORT);
02806       break;
02807     case STATION_TRUCK:    str = STR_LAI_STATION_DESCRIPTION_TRUCK_LOADING_AREA; break;
02808     case STATION_BUS:      str = STR_LAI_STATION_DESCRIPTION_BUS_STATION; break;
02809     case STATION_OILRIG:   str = STR_INDUSTRY_NAME_OIL_RIG; break;
02810     case STATION_DOCK:     str = STR_LAI_STATION_DESCRIPTION_SHIP_DOCK; break;
02811     case STATION_BUOY:     str = STR_LAI_STATION_DESCRIPTION_BUOY; break;
02812     case STATION_WAYPOINT: str = STR_LAI_STATION_DESCRIPTION_WAYPOINT; break;
02813   }
02814   td->str = str;
02815 }
02816 
02817 
02818 static TrackStatus GetTileTrackStatus_Station(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
02819 {
02820   TrackBits trackbits = TRACK_BIT_NONE;
02821 
02822   switch (mode) {
02823     case TRANSPORT_RAIL:
02824       if (HasStationRail(tile) && !IsStationTileBlocked(tile)) {
02825         trackbits = TrackToTrackBits(GetRailStationTrack(tile));
02826       }
02827       break;
02828 
02829     case TRANSPORT_WATER:
02830       /* buoy is coded as a station, it is always on open water */
02831       if (IsBuoy(tile)) {
02832         trackbits = TRACK_BIT_ALL;
02833         /* remove tracks that connect NE map edge */
02834         if (TileX(tile) == 0) trackbits &= ~(TRACK_BIT_X | TRACK_BIT_UPPER | TRACK_BIT_RIGHT);
02835         /* remove tracks that connect NW map edge */
02836         if (TileY(tile) == 0) trackbits &= ~(TRACK_BIT_Y | TRACK_BIT_LEFT | TRACK_BIT_UPPER);
02837       }
02838       break;
02839 
02840     case TRANSPORT_ROAD:
02841       if ((GetRoadTypes(tile) & sub_mode) != 0 && IsRoadStop(tile)) {
02842         DiagDirection dir = GetRoadStopDir(tile);
02843         Axis axis = DiagDirToAxis(dir);
02844 
02845         if (side != INVALID_DIAGDIR) {
02846           if (axis != DiagDirToAxis(side) || (IsStandardRoadStopTile(tile) && dir != side)) break;
02847         }
02848 
02849         trackbits = AxisToTrackBits(axis);
02850       }
02851       break;
02852 
02853     default:
02854       break;
02855   }
02856 
02857   return CombineTrackStatus(TrackBitsToTrackdirBits(trackbits), TRACKDIR_BIT_NONE);
02858 }
02859 
02860 
02861 static void TileLoop_Station(TileIndex tile)
02862 {
02863   /* FIXME -- GetTileTrackStatus_Station -> animated stationtiles
02864    * hardcoded.....not good */
02865   switch (GetStationType(tile)) {
02866     case STATION_AIRPORT:
02867       AirportTileAnimationTrigger(Station::GetByTile(tile), tile, AAT_TILELOOP);
02868       break;
02869 
02870     case STATION_DOCK:
02871       if (GetTileSlope(tile, NULL) != SLOPE_FLAT) break; // only handle water part
02872       /* FALL THROUGH */
02873     case STATION_OILRIG: //(station part)
02874     case STATION_BUOY:
02875       TileLoop_Water(tile);
02876       break;
02877 
02878     default: break;
02879   }
02880 }
02881 
02882 
02883 static void AnimateTile_Station(TileIndex tile)
02884 {
02885   if (HasStationRail(tile)) {
02886     AnimateStationTile(tile);
02887     return;
02888   }
02889 
02890   if (IsAirport(tile)) {
02891     AnimateAirportTile(tile);
02892   }
02893 }
02894 
02895 
02896 static bool ClickTile_Station(TileIndex tile)
02897 {
02898   const BaseStation *bst = BaseStation::GetByTile(tile);
02899 
02900   if (bst->facilities & FACIL_WAYPOINT) {
02901     ShowWaypointWindow(Waypoint::From(bst));
02902   } else if (IsHangar(tile)) {
02903     const Station *st = Station::From(bst);
02904     ShowDepotWindow(st->airport.GetHangarTile(st->airport.GetHangarNum(tile)), VEH_AIRCRAFT);
02905   } else {
02906     ShowStationViewWindow(bst->index);
02907   }
02908   return true;
02909 }
02910 
02911 static VehicleEnterTileStatus VehicleEnter_Station(Vehicle *v, TileIndex tile, int x, int y)
02912 {
02913   if (v->type == VEH_TRAIN) {
02914     StationID station_id = GetStationIndex(tile);
02915     if (!v->current_order.ShouldStopAtStation(v, station_id)) return VETSB_CONTINUE;
02916     if (!IsRailStation(tile) || !v->IsFrontEngine()) return VETSB_CONTINUE;
02917 
02918     int station_ahead;
02919     int station_length;
02920     int stop = GetTrainStopLocation(station_id, tile, Train::From(v), &station_ahead, &station_length);
02921 
02922     /* Stop whenever that amount of station ahead + the distance from the
02923      * begin of the platform to the stop location is longer than the length
02924      * of the platform. Station ahead 'includes' the current tile where the
02925      * vehicle is on, so we need to substract that. */
02926     if (!IsInsideBS(stop + station_ahead, station_length, TILE_SIZE)) return VETSB_CONTINUE;
02927 
02928     DiagDirection dir = DirToDiagDir(v->direction);
02929 
02930     x &= 0xF;
02931     y &= 0xF;
02932 
02933     if (DiagDirToAxis(dir) != AXIS_X) Swap(x, y);
02934     if (y == TILE_SIZE / 2) {
02935       if (dir != DIAGDIR_SE && dir != DIAGDIR_SW) x = TILE_SIZE - 1 - x;
02936       stop &= TILE_SIZE - 1;
02937 
02938       if (x == stop) return VETSB_ENTERED_STATION | (VehicleEnterTileStatus)(station_id << VETS_STATION_ID_OFFSET); // enter station
02939       if (x < stop) {
02940         uint16 spd;
02941 
02942         v->vehstatus |= VS_TRAIN_SLOWING;
02943         spd = max(0, (stop - x) * 20 - 15);
02944         if (spd < v->cur_speed) v->cur_speed = spd;
02945       }
02946     }
02947   } else if (v->type == VEH_ROAD) {
02948     RoadVehicle *rv = RoadVehicle::From(v);
02949     if (rv->state < RVSB_IN_ROAD_STOP && !IsReversingRoadTrackdir((Trackdir)rv->state) && rv->frame == 0) {
02950       if (IsRoadStop(tile) && rv->IsFrontEngine()) {
02951         /* Attempt to allocate a parking bay in a road stop */
02952         return RoadStop::GetByTile(tile, GetRoadStopType(tile))->Enter(rv) ? VETSB_CONTINUE : VETSB_CANNOT_ENTER;
02953       }
02954     }
02955   }
02956 
02957   return VETSB_CONTINUE;
02958 }
02959 
02966 static bool StationHandleBigTick(BaseStation *st)
02967 {
02968   if (!st->IsInUse() && ++st->delete_ctr >= 8) {
02969     delete st;
02970     return false;
02971   }
02972 
02973   if ((st->facilities & FACIL_WAYPOINT) == 0) UpdateStationAcceptance(Station::From(st), true);
02974 
02975   return true;
02976 }
02977 
02978 static inline void byte_inc_sat(byte *p)
02979 {
02980   byte b = *p + 1;
02981   if (b != 0) *p = b;
02982 }
02983 
02984 static void UpdateStationRating(Station *st)
02985 {
02986   bool waiting_changed = false;
02987 
02988   byte_inc_sat(&st->time_since_load);
02989   byte_inc_sat(&st->time_since_unload);
02990 
02991   const CargoSpec *cs;
02992   FOR_ALL_CARGOSPECS(cs) {
02993     GoodsEntry *ge = &st->goods[cs->Index()];
02994     /* Slowly increase the rating back to his original level in the case we
02995      *  didn't deliver cargo yet to this station. This happens when a bribe
02996      *  failed while you didn't moved that cargo yet to a station. */
02997     if (!HasBit(ge->acceptance_pickup, GoodsEntry::PICKUP) && ge->rating < INITIAL_STATION_RATING) {
02998       ge->rating++;
02999     }
03000 
03001     /* Only change the rating if we are moving this cargo */
03002     if (HasBit(ge->acceptance_pickup, GoodsEntry::PICKUP)) {
03003       byte_inc_sat(&ge->days_since_pickup);
03004 
03005       bool skip = false;
03006       int rating = 0;
03007       uint waiting = ge->cargo.Count();
03008 
03009       if (HasBit(cs->callback_mask, CBM_CARGO_STATION_RATING_CALC)) {
03010         /* Perform custom station rating. If it succeeds the speed, days in transit and
03011          * waiting cargo ratings must not be executed. */
03012 
03013         /* NewGRFs expect last speed to be 0xFF when no vehicle has arrived yet. */
03014         uint last_speed = ge->last_speed;
03015         if (last_speed == 0) last_speed = 0xFF;
03016 
03017         uint32 var18 = min(ge->days_since_pickup, 0xFF) | (min(waiting, 0xFFFF) << 8) | (min(last_speed, 0xFF) << 24);
03018         /* Convert to the 'old' vehicle types */
03019         uint32 var10 = (st->last_vehicle_type == VEH_INVALID) ? 0x0 : (st->last_vehicle_type + 0x10);
03020         uint16 callback = GetCargoCallback(CBID_CARGO_STATION_RATING_CALC, var10, var18, cs);
03021         if (callback != CALLBACK_FAILED) {
03022           skip = true;
03023           rating = GB(callback, 0, 14);
03024 
03025           /* Simulate a 15 bit signed value */
03026           if (HasBit(callback, 14)) rating -= 0x4000;
03027         }
03028       }
03029 
03030       if (!skip) {
03031         int b = ge->last_speed - 85;
03032         if (b >= 0) rating += b >> 2;
03033 
03034         byte days = ge->days_since_pickup;
03035         if (st->last_vehicle_type == VEH_SHIP) days >>= 2;
03036         (days > 21) ||
03037         (rating += 25, days > 12) ||
03038         (rating += 25, days > 6) ||
03039         (rating += 45, days > 3) ||
03040         (rating += 35, true);
03041 
03042         (rating -= 90, waiting > 1500) ||
03043         (rating += 55, waiting > 1000) ||
03044         (rating += 35, waiting > 600) ||
03045         (rating += 10, waiting > 300) ||
03046         (rating += 20, waiting > 100) ||
03047         (rating += 10, true);
03048       }
03049 
03050       if (Company::IsValidID(st->owner) && HasBit(st->town->statues, st->owner)) rating += 26;
03051 
03052       byte age = ge->last_age;
03053       (age >= 3) ||
03054       (rating += 10, age >= 2) ||
03055       (rating += 10, age >= 1) ||
03056       (rating += 13, true);
03057 
03058       {
03059         int or_ = ge->rating; // old rating
03060 
03061         /* only modify rating in steps of -2, -1, 0, 1 or 2 */
03062         ge->rating = rating = or_ + Clamp(Clamp(rating, 0, 255) - or_, -2, 2);
03063 
03064         /* if rating is <= 64 and more than 200 items waiting,
03065          * remove some random amount of goods from the station */
03066         if (rating <= 64 && waiting >= 200) {
03067           int dec = Random() & 0x1F;
03068           if (waiting < 400) dec &= 7;
03069           waiting -= dec + 1;
03070           waiting_changed = true;
03071         }
03072 
03073         /* if rating is <= 127 and there are any items waiting, maybe remove some goods. */
03074         if (rating <= 127 && waiting != 0) {
03075           uint32 r = Random();
03076           if (rating <= (int)GB(r, 0, 7)) {
03077             /* Need to have int, otherwise it will just overflow etc. */
03078             waiting = max((int)waiting - (int)GB(r, 8, 2) - 1, 0);
03079             waiting_changed = true;
03080           }
03081         }
03082 
03083         /* At some point we really must cap the cargo. Previously this
03084          * was a strict 4095, but now we'll have a less strict, but
03085          * increasingly agressive truncation of the amount of cargo. */
03086         static const uint WAITING_CARGO_THRESHOLD  = 1 << 12;
03087         static const uint WAITING_CARGO_CUT_FACTOR = 1 <<  6;
03088         static const uint MAX_WAITING_CARGO        = 1 << 15;
03089 
03090         if (waiting > WAITING_CARGO_THRESHOLD) {
03091           uint difference = waiting - WAITING_CARGO_THRESHOLD;
03092           waiting -= (difference / WAITING_CARGO_CUT_FACTOR);
03093 
03094           waiting = min(waiting, MAX_WAITING_CARGO);
03095           waiting_changed = true;
03096         }
03097 
03098         if (waiting_changed) ge->cargo.Truncate(waiting);
03099       }
03100     }
03101   }
03102 
03103   StationID index = st->index;
03104   if (waiting_changed) {
03105     SetWindowDirty(WC_STATION_VIEW, index); // update whole window
03106   } else {
03107     SetWindowWidgetDirty(WC_STATION_VIEW, index, SVW_RATINGLIST); // update only ratings list
03108   }
03109 }
03110 
03111 /* called for every station each tick */
03112 static void StationHandleSmallTick(BaseStation *st)
03113 {
03114   if ((st->facilities & FACIL_WAYPOINT) != 0 || !st->IsInUse()) return;
03115 
03116   byte b = st->delete_ctr + 1;
03117   if (b >= 185) b = 0;
03118   st->delete_ctr = b;
03119 
03120   if (b == 0) UpdateStationRating(Station::From(st));
03121 }
03122 
03123 void OnTick_Station()
03124 {
03125   if (_game_mode == GM_EDITOR) return;
03126 
03127   BaseStation *st;
03128   FOR_ALL_BASE_STATIONS(st) {
03129     StationHandleSmallTick(st);
03130 
03131     /* Run 250 tick interval trigger for station animation.
03132      * Station index is included so that triggers are not all done
03133      * at the same time. */
03134     if ((_tick_counter + st->index) % 250 == 0) {
03135       /* Stop processing this station if it was deleted */
03136       if (!StationHandleBigTick(st)) continue;
03137       TriggerStationAnimation(st, st->xy, SAT_250_TICKS);
03138       if (Station::IsExpected(st)) AirportAnimationTrigger(Station::From(st), AAT_STATION_250_TICKS);
03139     }
03140   }
03141 }
03142 
03143 void StationMonthlyLoop()
03144 {
03145   /* not used */
03146 }
03147 
03148 
03149 void ModifyStationRatingAround(TileIndex tile, Owner owner, int amount, uint radius)
03150 {
03151   Station *st;
03152 
03153   FOR_ALL_STATIONS(st) {
03154     if (st->owner == owner &&
03155         DistanceManhattan(tile, st->xy) <= radius) {
03156       for (CargoID i = 0; i < NUM_CARGO; i++) {
03157         GoodsEntry *ge = &st->goods[i];
03158 
03159         if (ge->acceptance_pickup != 0) {
03160           ge->rating = Clamp(ge->rating + amount, 0, 255);
03161         }
03162       }
03163     }
03164   }
03165 }
03166 
03167 static uint UpdateStationWaiting(Station *st, CargoID type, uint amount, SourceType source_type, SourceID source_id)
03168 {
03169   /* We can't allocate a CargoPacket? Then don't do anything
03170    * at all; i.e. just discard the incoming cargo. */
03171   if (!CargoPacket::CanAllocateItem()) return 0;
03172 
03173   GoodsEntry &ge = st->goods[type];
03174   amount += ge.amount_fract;
03175   ge.amount_fract = GB(amount, 0, 8);
03176 
03177   amount >>= 8;
03178   /* No new "real" cargo item yet. */
03179   if (amount == 0) return 0;
03180 
03181   ge.cargo.Append(new CargoPacket(st->index, st->xy, amount, source_type, source_id));
03182 
03183   if (!HasBit(ge.acceptance_pickup, GoodsEntry::PICKUP)) {
03184     InvalidateWindowData(WC_STATION_LIST, st->index);
03185     SetBit(ge.acceptance_pickup, GoodsEntry::PICKUP);
03186   }
03187 
03188   TriggerStationAnimation(st, st->xy, SAT_NEW_CARGO, type);
03189   AirportAnimationTrigger(st, AAT_STATION_NEW_CARGO, type);
03190 
03191   SetWindowDirty(WC_STATION_VIEW, st->index);
03192   st->MarkTilesDirty(true);
03193   return amount;
03194 }
03195 
03196 static bool IsUniqueStationName(const char *name)
03197 {
03198   const Station *st;
03199 
03200   FOR_ALL_STATIONS(st) {
03201     if (st->name != NULL && strcmp(st->name, name) == 0) return false;
03202   }
03203 
03204   return true;
03205 }
03206 
03216 CommandCost CmdRenameStation(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
03217 {
03218   Station *st = Station::GetIfValid(p1);
03219   if (st == NULL) return CMD_ERROR;
03220 
03221   CommandCost ret = CheckOwnership(st->owner);
03222   if (ret.Failed()) return ret;
03223 
03224   bool reset = StrEmpty(text);
03225 
03226   if (!reset) {
03227     if (Utf8StringLength(text) >= MAX_LENGTH_STATION_NAME_CHARS) return CMD_ERROR;
03228     if (!IsUniqueStationName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
03229   }
03230 
03231   if (flags & DC_EXEC) {
03232     free(st->name);
03233     st->name = reset ? NULL : strdup(text);
03234 
03235     st->UpdateVirtCoord();
03236     InvalidateWindowData(WC_STATION_LIST, st->owner, 1);
03237   }
03238 
03239   return CommandCost();
03240 }
03241 
03248 void FindStationsAroundTiles(const TileArea &location, StationList *stations)
03249 {
03250   /* area to search = producer plus station catchment radius */
03251   int max_rad = (_settings_game.station.modified_catchment ? MAX_CATCHMENT : CA_UNMODIFIED);
03252 
03253   for (int dy = -max_rad; dy < location.h + max_rad; dy++) {
03254     for (int dx = -max_rad; dx < location.w + max_rad; dx++) {
03255       TileIndex cur_tile = TileAddWrap(location.tile, dx, dy);
03256       if (cur_tile == INVALID_TILE || !IsTileType(cur_tile, MP_STATION)) continue;
03257 
03258       Station *st = Station::GetByTile(cur_tile);
03259       if (st == NULL) continue;
03260 
03261       if (_settings_game.station.modified_catchment) {
03262         int rad = st->GetCatchmentRadius();
03263         if (dx < -rad || dx >= rad + location.w || dy < -rad || dy >= rad + location.h) continue;
03264       }
03265 
03266       /* Insert the station in the set. This will fail if it has
03267        * already been added.
03268        */
03269       stations->Include(st);
03270     }
03271   }
03272 }
03273 
03278 const StationList *StationFinder::GetStations()
03279 {
03280   if (this->tile != INVALID_TILE) {
03281     FindStationsAroundTiles(*this, &this->stations);
03282     this->tile = INVALID_TILE;
03283   }
03284   return &this->stations;
03285 }
03286 
03287 uint MoveGoodsToStation(CargoID type, uint amount, SourceType source_type, SourceID source_id, const StationList *all_stations)
03288 {
03289   /* Return if nothing to do. Also the rounding below fails for 0. */
03290   if (amount == 0) return 0;
03291 
03292   Station *st1 = NULL;   // Station with best rating
03293   Station *st2 = NULL;   // Second best station
03294   uint best_rating1 = 0; // rating of st1
03295   uint best_rating2 = 0; // rating of st2
03296 
03297   for (Station * const *st_iter = all_stations->Begin(); st_iter != all_stations->End(); ++st_iter) {
03298     Station *st = *st_iter;
03299 
03300     /* Is the station reserved exclusively for somebody else? */
03301     if (st->town->exclusive_counter > 0 && st->town->exclusivity != st->owner) continue;
03302 
03303     if (st->goods[type].rating == 0) continue; // Lowest possible rating, better not to give cargo anymore
03304 
03305     if (_settings_game.order.selectgoods && st->goods[type].last_speed == 0) continue; // Selectively servicing stations, and not this one
03306 
03307     if (IsCargoInClass(type, CC_PASSENGERS)) {
03308       if (st->facilities == FACIL_TRUCK_STOP) continue; // passengers are never served by just a truck stop
03309     } else {
03310       if (st->facilities == FACIL_BUS_STOP) continue; // non-passengers are never served by just a bus stop
03311     }
03312 
03313     /* This station can be used, add it to st1/st2 */
03314     if (st1 == NULL || st->goods[type].rating >= best_rating1) {
03315       st2 = st1; best_rating2 = best_rating1; st1 = st; best_rating1 = st->goods[type].rating;
03316     } else if (st2 == NULL || st->goods[type].rating >= best_rating2) {
03317       st2 = st; best_rating2 = st->goods[type].rating;
03318     }
03319   }
03320 
03321   /* no stations around at all? */
03322   if (st1 == NULL) return 0;
03323 
03324   /* From now we'll calculate with fractal cargo amounts.
03325    * First determine how much cargo we really have. */
03326   amount *= best_rating1 + 1;
03327 
03328   if (st2 == NULL) {
03329     /* only one station around */
03330     return UpdateStationWaiting(st1, type, amount, source_type, source_id);
03331   }
03332 
03333   /* several stations around, the best two (highest rating) are in st1 and st2 */
03334   assert(st1 != NULL);
03335   assert(st2 != NULL);
03336   assert(best_rating1 != 0 || best_rating2 != 0);
03337 
03338   /* Then determine the amount the worst station gets. We do it this way as the
03339    * best should get a bonus, which in this case is the rounding difference from
03340    * this calculation. In reality that will mean the bonus will be pretty low.
03341    * Nevertheless, the best station should always get the most cargo regardless
03342    * of rounding issues. */
03343   uint worst_cargo = amount * best_rating2 / (best_rating1 + best_rating2);
03344   assert(worst_cargo <= (amount - worst_cargo));
03345 
03346   /* And then send the cargo to the stations! */
03347   uint moved = UpdateStationWaiting(st1, type, amount - worst_cargo, source_type, source_id);
03348   /* These two UpdateStationWaiting's can't be in the statement as then the order
03349    * of execution would be undefined and that could cause desyncs with callbacks. */
03350   return moved + UpdateStationWaiting(st2, type, worst_cargo, source_type, source_id);
03351 }
03352 
03353 void BuildOilRig(TileIndex tile)
03354 {
03355   if (!Station::CanAllocateItem()) {
03356     DEBUG(misc, 0, "Can't allocate station for oilrig at 0x%X, reverting to oilrig only", tile);
03357     return;
03358   }
03359 
03360   Station *st = new Station(tile);
03361   st->town = ClosestTownFromTile(tile, UINT_MAX);
03362 
03363   st->string_id = GenerateStationName(st, tile, STATIONNAMING_OILRIG);
03364 
03365   assert(IsTileType(tile, MP_INDUSTRY));
03366   DeleteAnimatedTile(tile);
03367   MakeOilrig(tile, st->index, GetWaterClass(tile));
03368 
03369   st->owner = OWNER_NONE;
03370   st->airport.type = AT_OILRIG;
03371   st->airport.Add(tile);
03372   st->dock_tile = tile;
03373   st->facilities = FACIL_AIRPORT | FACIL_DOCK;
03374   st->build_date = _date;
03375 
03376   st->rect.BeforeAddTile(tile, StationRect::ADD_FORCE);
03377 
03378   for (CargoID j = 0; j < NUM_CARGO; j++) {
03379     st->goods[j].acceptance_pickup = 0;
03380     st->goods[j].days_since_pickup = 255;
03381     st->goods[j].rating = INITIAL_STATION_RATING;
03382     st->goods[j].last_speed = 0;
03383     st->goods[j].last_age = 255;
03384   }
03385 
03386   st->UpdateVirtCoord();
03387   UpdateStationAcceptance(st, false);
03388   st->RecomputeIndustriesNear();
03389 }
03390 
03391 void DeleteOilRig(TileIndex tile)
03392 {
03393   Station *st = Station::GetByTile(tile);
03394 
03395   MakeWaterKeepingClass(tile, OWNER_NONE);
03396 
03397   st->dock_tile = INVALID_TILE;
03398   st->airport.Clear();
03399   st->facilities &= ~(FACIL_AIRPORT | FACIL_DOCK);
03400   st->airport.flags = 0;
03401 
03402   st->rect.AfterRemoveTile(st, tile);
03403 
03404   st->UpdateVirtCoord();
03405   st->RecomputeIndustriesNear();
03406   if (!st->IsInUse()) delete st;
03407 }
03408 
03409 static void ChangeTileOwner_Station(TileIndex tile, Owner old_owner, Owner new_owner)
03410 {
03411   if (IsDriveThroughStopTile(tile)) {
03412     for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
03413       /* Update all roadtypes, no matter if they are present */
03414       if (GetRoadOwner(tile, rt) == old_owner) {
03415         SetRoadOwner(tile, rt, new_owner == INVALID_OWNER ? OWNER_NONE : new_owner);
03416       }
03417     }
03418   }
03419 
03420   if (!IsTileOwner(tile, old_owner)) return;
03421 
03422   if (new_owner != INVALID_OWNER) {
03423     /* for buoys, owner of tile is owner of water, st->owner == OWNER_NONE */
03424     SetTileOwner(tile, new_owner);
03425     InvalidateWindowClassesData(WC_STATION_LIST, 0);
03426   } else {
03427     if (IsDriveThroughStopTile(tile)) {
03428       /* Remove the drive-through road stop */
03429       DoCommand(tile, 1 | 1 << 8, (GetStationType(tile) == STATION_TRUCK) ? ROADSTOP_TRUCK : ROADSTOP_BUS, DC_EXEC | DC_BANKRUPT, CMD_REMOVE_ROAD_STOP);
03430       assert(IsTileType(tile, MP_ROAD));
03431       /* Change owner of tile and all roadtypes */
03432       ChangeTileOwner(tile, old_owner, new_owner);
03433     } else {
03434       DoCommand(tile, 0, 0, DC_EXEC | DC_BANKRUPT, CMD_LANDSCAPE_CLEAR);
03435       /* Set tile owner of water under (now removed) buoy and dock to OWNER_NONE.
03436        * Update owner of buoy if it was not removed (was in orders).
03437        * Do not update when owned by OWNER_WATER (sea and rivers). */
03438       if ((IsTileType(tile, MP_WATER) || IsBuoyTile(tile)) && IsTileOwner(tile, old_owner)) SetTileOwner(tile, OWNER_NONE);
03439     }
03440   }
03441 }
03442 
03451 static bool CanRemoveRoadWithStop(TileIndex tile, DoCommandFlag flags)
03452 {
03453   /* Yeah... water can always remove stops, right? */
03454   if (_current_company == OWNER_WATER) return true;
03455 
03456   RoadTypes rts = GetRoadTypes(tile);
03457   if (HasBit(rts, ROADTYPE_TRAM)) {
03458     Owner tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
03459     if (tram_owner != OWNER_NONE && CheckOwnership(tram_owner).Failed()) return false;
03460   }
03461   if (HasBit(rts, ROADTYPE_ROAD)) {
03462     Owner road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
03463     if (road_owner != OWNER_TOWN) {
03464       if (road_owner != OWNER_NONE && CheckOwnership(road_owner).Failed()) return false;
03465     } else {
03466       if (CheckAllowRemoveRoad(tile, GetAnyRoadBits(tile, ROADTYPE_ROAD), OWNER_TOWN, ROADTYPE_ROAD, flags).Failed()) return false;
03467     }
03468   }
03469 
03470   return true;
03471 }
03472 
03473 CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags)
03474 {
03475   if (flags & DC_AUTO) {
03476     switch (GetStationType(tile)) {
03477       default: break;
03478       case STATION_RAIL:     return_cmd_error(STR_ERROR_MUST_DEMOLISH_RAILROAD);
03479       case STATION_WAYPOINT: return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
03480       case STATION_AIRPORT:  return_cmd_error(STR_ERROR_MUST_DEMOLISH_AIRPORT_FIRST);
03481       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);
03482       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);
03483       case STATION_BUOY:     return_cmd_error(STR_ERROR_BUOY_IN_THE_WAY);
03484       case STATION_DOCK:     return_cmd_error(STR_ERROR_MUST_DEMOLISH_DOCK_FIRST);
03485       case STATION_OILRIG:
03486         SetDParam(1, STR_INDUSTRY_NAME_OIL_RIG);
03487         return_cmd_error(STR_ERROR_GENERIC_OBJECT_IN_THE_WAY);
03488     }
03489   }
03490 
03491   switch (GetStationType(tile)) {
03492     case STATION_RAIL:     return RemoveRailStation(tile, flags);
03493     case STATION_WAYPOINT: return RemoveRailWaypoint(tile, flags);
03494     case STATION_AIRPORT:  return RemoveAirport(tile, flags);
03495     case STATION_TRUCK:
03496       if (IsDriveThroughStopTile(tile) && !CanRemoveRoadWithStop(tile, flags)) {
03497         return_cmd_error(STR_ERROR_MUST_DEMOLISH_TRUCK_STATION_FIRST);
03498       }
03499       return RemoveRoadStop(tile, flags);
03500     case STATION_BUS:
03501       if (IsDriveThroughStopTile(tile) && !CanRemoveRoadWithStop(tile, flags)) {
03502         return_cmd_error(STR_ERROR_MUST_DEMOLISH_BUS_STATION_FIRST);
03503       }
03504       return RemoveRoadStop(tile, flags);
03505     case STATION_BUOY:     return RemoveBuoy(tile, flags);
03506     case STATION_DOCK:     return RemoveDock(tile, flags);
03507     default: break;
03508   }
03509 
03510   return CMD_ERROR;
03511 }
03512 
03513 static CommandCost TerraformTile_Station(TileIndex tile, DoCommandFlag flags, uint z_new, Slope tileh_new)
03514 {
03515   if (_settings_game.construction.build_on_slopes && AutoslopeEnabled()) {
03516     /* TODO: If you implement newgrf callback 149 'land slope check', you have to decide what to do with it here.
03517      *       TTDP does not call it.
03518      */
03519     if (!IsSteepSlope(tileh_new) && (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new))) {
03520       switch (GetStationType(tile)) {
03521         case STATION_WAYPOINT:
03522         case STATION_RAIL: {
03523           DiagDirection direction = AxisToDiagDir(GetRailStationAxis(tile));
03524           if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
03525           if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
03526           return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
03527         }
03528 
03529         case STATION_AIRPORT:
03530           return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
03531 
03532         case STATION_TRUCK:
03533         case STATION_BUS: {
03534           DiagDirection direction = GetRoadStopDir(tile);
03535           if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
03536           if (IsDriveThroughStopTile(tile)) {
03537             if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
03538           }
03539           return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
03540         }
03541 
03542         default: break;
03543       }
03544     }
03545   }
03546   return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
03547 }
03548 
03549 
03550 extern const TileTypeProcs _tile_type_station_procs = {
03551   DrawTile_Station,           // draw_tile_proc
03552   GetSlopeZ_Station,          // get_slope_z_proc
03553   ClearTile_Station,          // clear_tile_proc
03554   NULL,                       // add_accepted_cargo_proc
03555   GetTileDesc_Station,        // get_tile_desc_proc
03556   GetTileTrackStatus_Station, // get_tile_track_status_proc
03557   ClickTile_Station,          // click_tile_proc
03558   AnimateTile_Station,        // animate_tile_proc
03559   TileLoop_Station,           // tile_loop_clear
03560   ChangeTileOwner_Station,    // change_tile_owner_clear
03561   NULL,                       // add_produced_cargo_proc
03562   VehicleEnter_Station,       // vehicle_enter_tile_proc
03563   GetFoundation_Station,      // get_foundation_proc
03564   TerraformTile_Station,      // terraform_tile_proc
03565 };

Generated on Sun May 15 19:20:15 2011 for OpenTTD by  doxygen 1.6.1