# station_cmd.cpp

Go to the documentation of this file.

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