station.cpp

Go to the documentation of this file.
00001 /* $Id$ */
00002 
00003 /*
00004  * This file is part of OpenTTD.
00005  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
00006  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
00007  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
00008  */
00009 
00012 #include "stdafx.h"
00013 #include "company_func.h"
00014 #include "company_base.h"
00015 #include "roadveh.h"
00016 #include "viewport_func.h"
00017 #include "window_func.h"
00018 #include "date_func.h"
00019 #include "command_func.h"
00020 #include "news_func.h"
00021 #include "aircraft.h"
00022 #include "vehiclelist.h"
00023 #include "core/pool_func.hpp"
00024 #include "station_base.h"
00025 #include "roadstop_base.h"
00026 #include "industry.h"
00027 #include "core/random_func.hpp"
00028 
00029 #include "table/strings.h"
00030 
00032 StationPool _station_pool("Station");
00033 INSTANTIATE_POOL_METHODS(Station)
00034 
00035 BaseStation::~BaseStation()
00036 {
00037   free(this->name);
00038   free(this->speclist);
00039 
00040   if (CleaningPool()) return;
00041 
00042   Owner owner = this->owner;
00043   if (!Company::IsValidID(owner)) owner = _local_company;
00044   if (!Company::IsValidID(owner)) return; // Spectators
00045   DeleteWindowById(WC_TRAINS_LIST,   VehicleListIdentifier(VL_STATION_LIST, VEH_TRAIN,    owner, this->index).Pack());
00046   DeleteWindowById(WC_ROADVEH_LIST,  VehicleListIdentifier(VL_STATION_LIST, VEH_ROAD,     owner, this->index).Pack());
00047   DeleteWindowById(WC_SHIPS_LIST,    VehicleListIdentifier(VL_STATION_LIST, VEH_SHIP,     owner, this->index).Pack());
00048   DeleteWindowById(WC_AIRCRAFT_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_AIRCRAFT, owner, this->index).Pack());
00049 
00050   this->sign.MarkDirty();
00051 }
00052 
00053 Station::Station(TileIndex tile) :
00054   SpecializedStation<Station, false>(tile),
00055   bus_station(INVALID_TILE, 0, 0),
00056   truck_station(INVALID_TILE, 0, 0),
00057   dock_tile(INVALID_TILE),
00058   indtype(IT_INVALID),
00059   time_since_load(255),
00060   time_since_unload(255),
00061   last_vehicle_type(VEH_INVALID)
00062 {
00063   /* this->random_bits is set in Station::AddFacility() */
00064 
00065   /* has to be done like this as we can't give arguments when constructing an array */
00066   for (CargoID i = 0; i < NUM_CARGO; ++i) {
00067     this->goods[i].cargo.AssignTo(this, i);
00068   }
00069 }
00070 
00078 Station::~Station()
00079 {
00080   if (CleaningPool()) {
00081     for (CargoID c = 0; c < NUM_CARGO; c++) {
00082       this->goods[c].cargo.OnCleanPool();
00083     }
00084     return;
00085   }
00086 
00087   while (!this->loading_vehicles.empty()) {
00088     this->loading_vehicles.front()->LeaveStation();
00089   }
00090 
00091   Aircraft *a;
00092   FOR_ALL_AIRCRAFT(a) {
00093     if (!a->IsNormalAircraft()) continue;
00094     if (a->targetairport == this->index) a->targetairport = INVALID_STATION;
00095   }
00096 
00097   Station *st;
00098   FOR_ALL_STATIONS(st) {
00099     for (CargoID c = 0; c < NUM_CARGO; ++c) {
00100       GoodsEntry &ge = st->goods[c];
00101       ge.link_stats.erase(this->index);
00102       DeleteStaleFlows(st->index, c, this->index);
00103       ge.cargo.RerouteStalePackets(this->index);
00104     }
00105   }
00106 
00107   Vehicle *v;
00108   FOR_ALL_VEHICLES(v) {
00109     /* Forget about this station if this station is removed */
00110     if (v->last_station_visited == this->index) {
00111       v->last_station_visited = INVALID_STATION;
00112     }
00113 
00114     if (v->last_loading_station == this->index) {
00115       v->last_loading_station = INVALID_STATION;
00116     }
00117   }
00118 
00119   InvalidateWindowData(WC_STATION_LIST, this->owner, 0);
00120 
00121   DeleteWindowById(WC_STATION_VIEW, index);
00122 
00123   /* Now delete all orders that go to the station */
00124   RemoveOrderFromAllVehicles(OT_GOTO_STATION, this->index);
00125 
00126   /* Remove all news items */
00127   DeleteStationNews(this->index);
00128 
00129   for (CargoID c = 0; c < NUM_CARGO; c++) {
00130     this->goods[c].cargo.Truncate(0);
00131   }
00132 
00133   CargoPacket::InvalidateAllFrom(this->index);
00134 }
00135 
00136 
00142 void BaseStation::PostDestructor(size_t index)
00143 {
00144   InvalidateWindowData(WC_SELECT_STATION, 0, 0);
00145 }
00146 
00152 RoadStop *Station::GetPrimaryRoadStop(const RoadVehicle *v) const
00153 {
00154   RoadStop *rs = this->GetPrimaryRoadStop(v->IsBus() ? ROADSTOP_BUS : ROADSTOP_TRUCK);
00155 
00156   for (; rs != NULL; rs = rs->next) {
00157     /* The vehicle cannot go to this roadstop (different roadtype) */
00158     if ((GetRoadTypes(rs->xy) & v->compatible_roadtypes) == ROADTYPES_NONE) continue;
00159     /* The vehicle is articulated and can therefor not go the a standard road stop */
00160     if (IsStandardRoadStopTile(rs->xy) && v->HasArticulatedPart()) continue;
00161 
00162     /* The vehicle can actually go to this road stop. So, return it! */
00163     break;
00164   }
00165 
00166   return rs;
00167 }
00168 
00173 void Station::AddFacility(StationFacility new_facility_bit, TileIndex facil_xy)
00174 {
00175   if (this->facilities == FACIL_NONE) {
00176     this->xy = facil_xy;
00177     this->random_bits = Random();
00178   }
00179   this->facilities |= new_facility_bit;
00180   this->owner = _current_company;
00181   this->build_date = _date;
00182 }
00183 
00189 void Station::MarkTilesDirty(bool cargo_change) const
00190 {
00191   TileIndex tile = this->train_station.tile;
00192   int w, h;
00193 
00194   if (tile == INVALID_TILE) return;
00195 
00196   /* cargo_change is set if we're refreshing the tiles due to cargo moving
00197    * around. */
00198   if (cargo_change) {
00199     /* Don't waste time updating if there are no custom station graphics
00200      * that might change. Even if there are custom graphics, they might
00201      * not change. Unfortunately we have no way of telling. */
00202     if (this->num_specs == 0) return;
00203   }
00204 
00205   for (h = 0; h < train_station.h; h++) {
00206     for (w = 0; w < train_station.w; w++) {
00207       if (this->TileBelongsToRailStation(tile)) {
00208         MarkTileDirtyByTile(tile);
00209       }
00210       tile += TileDiffXY(1, 0);
00211     }
00212     tile += TileDiffXY(-w, 1);
00213   }
00214 }
00215 
00216 /* virtual */ uint Station::GetPlatformLength(TileIndex tile) const
00217 {
00218   assert(this->TileBelongsToRailStation(tile));
00219 
00220   TileIndexDiff delta = (GetRailStationAxis(tile) == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
00221 
00222   TileIndex t = tile;
00223   uint len = 0;
00224   do {
00225     t -= delta;
00226     len++;
00227   } while (IsCompatibleTrainStationTile(t, tile));
00228 
00229   t = tile;
00230   do {
00231     t += delta;
00232     len++;
00233   } while (IsCompatibleTrainStationTile(t, tile));
00234 
00235   return len - 1;
00236 }
00237 
00238 /* virtual */ uint Station::GetPlatformLength(TileIndex tile, DiagDirection dir) const
00239 {
00240   TileIndex start_tile = tile;
00241   uint length = 0;
00242   assert(IsRailStationTile(tile));
00243   assert(dir < DIAGDIR_END);
00244 
00245   do {
00246     length++;
00247     tile += TileOffsByDiagDir(dir);
00248   } while (IsCompatibleTrainStationTile(tile, start_tile));
00249 
00250   return length;
00251 }
00252 
00257 uint Station::GetCatchmentRadius() const
00258 {
00259   uint ret = CA_NONE;
00260 
00261   if (_settings_game.station.modified_catchment) {
00262     if (this->bus_stops          != NULL)         ret = max<uint>(ret, CA_BUS);
00263     if (this->truck_stops        != NULL)         ret = max<uint>(ret, CA_TRUCK);
00264     if (this->train_station.tile != INVALID_TILE) ret = max<uint>(ret, CA_TRAIN);
00265     if (this->dock_tile          != INVALID_TILE) ret = max<uint>(ret, CA_DOCK);
00266     if (this->airport.tile       != INVALID_TILE) ret = max<uint>(ret, this->airport.GetSpec()->catchment);
00267   } else {
00268     if (this->bus_stops != NULL || this->truck_stops != NULL || this->train_station.tile != INVALID_TILE || this->dock_tile != INVALID_TILE || this->airport.tile != INVALID_TILE) {
00269       ret = CA_UNMODIFIED;
00270     }
00271   }
00272 
00273   return ret;
00274 }
00275 
00280 Rect Station::GetCatchmentRect() const
00281 {
00282   assert(!this->rect.IsEmpty());
00283 
00284   /* Compute acceptance rectangle */
00285   int catchment_radius = this->GetCatchmentRadius();
00286 
00287   Rect ret = {
00288     max<int>(this->rect.left   - catchment_radius, 0),
00289     max<int>(this->rect.top    - catchment_radius, 0),
00290     min<int>(this->rect.right  + catchment_radius, MapMaxX()),
00291     min<int>(this->rect.bottom + catchment_radius, MapMaxY())
00292   };
00293 
00294   return ret;
00295 }
00296 
00298 struct RectAndIndustryVector {
00299   Rect rect;                       
00300   IndustryVector *industries_near; 
00301 };
00302 
00311 static bool FindIndustryToDeliver(TileIndex ind_tile, void *user_data)
00312 {
00313   /* Only process industry tiles */
00314   if (!IsTileType(ind_tile, MP_INDUSTRY)) return false;
00315 
00316   RectAndIndustryVector *riv = (RectAndIndustryVector *)user_data;
00317   Industry *ind = Industry::GetByTile(ind_tile);
00318 
00319   /* Don't check further if this industry is already in the list */
00320   if (riv->industries_near->Contains(ind)) return false;
00321 
00322   /* Only process tiles in the station acceptance rectangle */
00323   int x = TileX(ind_tile);
00324   int y = TileY(ind_tile);
00325   if (x < riv->rect.left || x > riv->rect.right || y < riv->rect.top || y > riv->rect.bottom) return false;
00326 
00327   /* Include only industries that can accept cargo */
00328   uint cargo_index;
00329   for (cargo_index = 0; cargo_index < lengthof(ind->accepts_cargo); cargo_index++) {
00330     if (ind->accepts_cargo[cargo_index] != CT_INVALID) break;
00331   }
00332   if (cargo_index >= lengthof(ind->accepts_cargo)) return false;
00333 
00334   *riv->industries_near->Append() = ind;
00335 
00336   return false;
00337 }
00338 
00343 void Station::RecomputeIndustriesNear()
00344 {
00345   this->industries_near.Clear();
00346   if (this->rect.IsEmpty()) return;
00347 
00348   RectAndIndustryVector riv = {
00349     this->GetCatchmentRect(),
00350     &this->industries_near
00351   };
00352 
00353   /* Compute maximum extent of acceptance rectangle wrt. station sign */
00354   TileIndex start_tile = this->xy;
00355   uint max_radius = max(
00356     max(DistanceManhattan(start_tile, TileXY(riv.rect.left,  riv.rect.top)), DistanceManhattan(start_tile, TileXY(riv.rect.left,  riv.rect.bottom))),
00357     max(DistanceManhattan(start_tile, TileXY(riv.rect.right, riv.rect.top)), DistanceManhattan(start_tile, TileXY(riv.rect.right, riv.rect.bottom)))
00358   );
00359 
00360   CircularTileSearch(&start_tile, 2 * max_radius + 1, &FindIndustryToDeliver, &riv);
00361 }
00362 
00366 /* static */ void Station::RecomputeIndustriesNearForAll()
00367 {
00368   Station *st;
00369   FOR_ALL_STATIONS(st) st->RecomputeIndustriesNear();
00370 }
00371 
00372 /************************************************************************/
00373 /*                     StationRect implementation                       */
00374 /************************************************************************/
00375 
00376 StationRect::StationRect()
00377 {
00378   this->MakeEmpty();
00379 }
00380 
00381 void StationRect::MakeEmpty()
00382 {
00383   this->left = this->top = this->right = this->bottom = 0;
00384 }
00385 
00395 bool StationRect::PtInExtendedRect(int x, int y, int distance) const
00396 {
00397   return this->left - distance <= x && x <= this->right + distance &&
00398       this->top - distance <= y && y <= this->bottom + distance;
00399 }
00400 
00401 bool StationRect::IsEmpty() const
00402 {
00403   return this->left == 0 || this->left > this->right || this->top > this->bottom;
00404 }
00405 
00406 CommandCost StationRect::BeforeAddTile(TileIndex tile, StationRectMode mode)
00407 {
00408   int x = TileX(tile);
00409   int y = TileY(tile);
00410   if (this->IsEmpty()) {
00411     /* we are adding the first station tile */
00412     if (mode != ADD_TEST) {
00413       this->left = this->right = x;
00414       this->top = this->bottom = y;
00415     }
00416   } else if (!this->PtInExtendedRect(x, y)) {
00417     /* current rect is not empty and new point is outside this rect
00418      * make new spread-out rectangle */
00419     Rect new_rect = {min(x, this->left), min(y, this->top), max(x, this->right), max(y, this->bottom)};
00420 
00421     /* check new rect dimensions against preset max */
00422     int w = new_rect.right - new_rect.left + 1;
00423     int h = new_rect.bottom - new_rect.top + 1;
00424     if (mode != ADD_FORCE && (w > _settings_game.station.station_spread || h > _settings_game.station.station_spread)) {
00425       assert(mode != ADD_TRY);
00426       return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
00427     }
00428 
00429     /* spread-out ok, return true */
00430     if (mode != ADD_TEST) {
00431       /* we should update the station rect */
00432       *this = new_rect;
00433     }
00434   } else {
00435     ; // new point is inside the rect, we don't need to do anything
00436   }
00437   return CommandCost();
00438 }
00439 
00440 CommandCost StationRect::BeforeAddRect(TileIndex tile, int w, int h, StationRectMode mode)
00441 {
00442   if (mode == ADD_FORCE || (w <= _settings_game.station.station_spread && h <= _settings_game.station.station_spread)) {
00443     /* Important when the old rect is completely inside the new rect, resp. the old one was empty. */
00444     CommandCost ret = this->BeforeAddTile(tile, mode);
00445     if (ret.Succeeded()) ret = this->BeforeAddTile(TILE_ADDXY(tile, w - 1, h - 1), mode);
00446     return ret;
00447   }
00448   return CommandCost();
00449 }
00450 
00460 /* static */ bool StationRect::ScanForStationTiles(StationID st_id, int left_a, int top_a, int right_a, int bottom_a)
00461 {
00462   TileArea ta(TileXY(left_a, top_a), TileXY(right_a, bottom_a));
00463   TILE_AREA_LOOP(tile, ta) {
00464     if (IsTileType(tile, MP_STATION) && GetStationIndex(tile) == st_id) return true;
00465   }
00466 
00467   return false;
00468 }
00469 
00470 bool StationRect::AfterRemoveTile(BaseStation *st, TileIndex tile)
00471 {
00472   int x = TileX(tile);
00473   int y = TileY(tile);
00474 
00475   /* look if removed tile was on the bounding rect edge
00476    * and try to reduce the rect by this edge
00477    * do it until we have empty rect or nothing to do */
00478   for (;;) {
00479     /* check if removed tile is on rect edge */
00480     bool left_edge = (x == this->left);
00481     bool right_edge = (x == this->right);
00482     bool top_edge = (y == this->top);
00483     bool bottom_edge = (y == this->bottom);
00484 
00485     /* can we reduce the rect in either direction? */
00486     bool reduce_x = ((left_edge || right_edge) && !ScanForStationTiles(st->index, x, this->top, x, this->bottom));
00487     bool reduce_y = ((top_edge || bottom_edge) && !ScanForStationTiles(st->index, this->left, y, this->right, y));
00488     if (!(reduce_x || reduce_y)) break; // nothing to do (can't reduce)
00489 
00490     if (reduce_x) {
00491       /* reduce horizontally */
00492       if (left_edge) {
00493         /* move left edge right */
00494         this->left = x = x + 1;
00495       } else {
00496         /* move right edge left */
00497         this->right = x = x - 1;
00498       }
00499     }
00500     if (reduce_y) {
00501       /* reduce vertically */
00502       if (top_edge) {
00503         /* move top edge down */
00504         this->top = y = y + 1;
00505       } else {
00506         /* move bottom edge up */
00507         this->bottom = y = y - 1;
00508       }
00509     }
00510 
00511     if (left > right || top > bottom) {
00512       /* can't continue, if the remaining rectangle is empty */
00513       this->MakeEmpty();
00514       return true; // empty remaining rect
00515     }
00516   }
00517   return false; // non-empty remaining rect
00518 }
00519 
00520 bool StationRect::AfterRemoveRect(BaseStation *st, TileArea ta)
00521 {
00522   assert(this->PtInExtendedRect(TileX(ta.tile), TileY(ta.tile)));
00523   assert(this->PtInExtendedRect(TileX(ta.tile) + ta.w - 1, TileY(ta.tile) + ta.h - 1));
00524 
00525   bool empty = this->AfterRemoveTile(st, ta.tile);
00526   if (ta.w != 1 || ta.h != 1) empty = empty || this->AfterRemoveTile(st, TILE_ADDXY(ta.tile, ta.w - 1, ta.h - 1));
00527   return empty;
00528 }
00529 
00530 StationRect& StationRect::operator = (const Rect &src)
00531 {
00532   this->left = src.left;
00533   this->top = src.top;
00534   this->right = src.right;
00535   this->bottom = src.bottom;
00536   return *this;
00537 }
00538 
00544 Money AirportMaintenanceCost(Owner owner)
00545 {
00546   Money total_cost = 0;
00547 
00548   const Station *st;
00549   FOR_ALL_STATIONS(st) {
00550     if (st->owner == owner && (st->facilities & FACIL_AIRPORT)) {
00551       total_cost += _price[PR_INFRASTRUCTURE_AIRPORT] * st->airport.GetSpec()->maintenance_cost;
00552     }
00553   }
00554   /* 3 bits fraction for the maintenance cost factor. */
00555   return total_cost >> 3;
00556 }