# station_cmd.cpp

Go to the documentation of this file.

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