station.cpp

Go to the documentation of this file.
00001 /* $Id: station.cpp 25890 2013-10-20 13:47:11Z fonsinchen $ */
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 "date_func.h"
00018 #include "command_func.h"
00019 #include "news_func.h"
00020 #include "aircraft.h"
00021 #include "vehiclelist.h"
00022 #include "core/pool_func.hpp"
00023 #include "station_base.h"
00024 #include "roadstop_base.h"
00025 #include "industry.h"
00026 #include "core/random_func.hpp"
00027 #include "linkgraph/linkgraph.h"
00028 #include "linkgraph/linkgraphschedule.h"
00029 
00030 #include "table/strings.h"
00031 
00033 StationPool _station_pool("Station");
00034 INSTANTIATE_POOL_METHODS(Station)
00035 
00036 typedef StationIDStack::SmallStackPool StationIDStackPool;
00037 template<> StationIDStackPool StationIDStack::_pool("StationIDStack");
00038 INSTANTIATE_POOL_METHODS(StationIDStack)
00039 
00040 BaseStation::~BaseStation()
00041 {
00042   free(this->name);
00043   free(this->speclist);
00044 
00045   if (CleaningPool()) return;
00046 
00047   Owner owner = this->owner;
00048   if (!Company::IsValidID(owner)) owner = _local_company;
00049   if (!Company::IsValidID(owner)) return; // Spectators
00050   DeleteWindowById(WC_TRAINS_LIST,   VehicleListIdentifier(VL_STATION_LIST, VEH_TRAIN,    owner, this->index).Pack());
00051   DeleteWindowById(WC_ROADVEH_LIST,  VehicleListIdentifier(VL_STATION_LIST, VEH_ROAD,     owner, this->index).Pack());
00052   DeleteWindowById(WC_SHIPS_LIST,    VehicleListIdentifier(VL_STATION_LIST, VEH_SHIP,     owner, this->index).Pack());
00053   DeleteWindowById(WC_AIRCRAFT_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_AIRCRAFT, owner, this->index).Pack());
00054 
00055   this->sign.MarkDirty();
00056 }
00057 
00058 Station::Station(TileIndex tile) :
00059   SpecializedStation<Station, false>(tile),
00060   bus_station(INVALID_TILE, 0, 0),
00061   truck_station(INVALID_TILE, 0, 0),
00062   dock_tile(INVALID_TILE),
00063   indtype(IT_INVALID),
00064   time_since_load(255),
00065   time_since_unload(255),
00066   last_vehicle_type(VEH_INVALID)
00067 {
00068   /* this->random_bits is set in Station::AddFacility() */
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   for (CargoID c = 0; c < NUM_CARGO; ++c) {
00098     LinkGraph *lg = LinkGraph::GetIfValid(this->goods[c].link_graph);
00099     if (lg == NULL) continue;
00100 
00101     for (NodeID node = 0; node < lg->Size(); ++node) {
00102       if ((*lg)[node][this->goods[c].node].LastUpdate() != INVALID_DATE) {
00103         Station *st = Station::Get((*lg)[node].Station());
00104         st->goods[c].flows.DeleteFlows(this->index);
00105         RerouteCargo(st, c, this->index, st->index);
00106       }
00107     }
00108     lg->RemoveNode(this->goods[c].node);
00109     if (lg->Size() == 0) {
00110       LinkGraphSchedule::Instance()->Unqueue(lg);
00111       delete lg;
00112     }
00113   }
00114 
00115   Vehicle *v;
00116   FOR_ALL_VEHICLES(v) {
00117     /* Forget about this station if this station is removed */
00118     if (v->last_station_visited == this->index) {
00119       v->last_station_visited = INVALID_STATION;
00120     }
00121     if (v->last_loading_station == this->index) {
00122       v->last_loading_station = INVALID_STATION;
00123     }
00124   }
00125 
00126   /* Clear the persistent storage. */
00127   delete this->airport.psa;
00128 
00129   if (this->owner == OWNER_NONE) {
00130     /* Invalidate all in case of oil rigs. */
00131     InvalidateWindowClassesData(WC_STATION_LIST, 0);
00132   } else {
00133     InvalidateWindowData(WC_STATION_LIST, this->owner, 0);
00134   }
00135 
00136   DeleteWindowById(WC_STATION_VIEW, index);
00137 
00138   /* Now delete all orders that go to the station */
00139   RemoveOrderFromAllVehicles(OT_GOTO_STATION, this->index);
00140 
00141   /* Remove all news items */
00142   DeleteStationNews(this->index);
00143 
00144   for (CargoID c = 0; c < NUM_CARGO; c++) {
00145     this->goods[c].cargo.Truncate();
00146   }
00147 
00148   CargoPacket::InvalidateAllFrom(this->index);
00149 }
00150 
00151 
00157 void BaseStation::PostDestructor(size_t index)
00158 {
00159   InvalidateWindowData(WC_SELECT_STATION, 0, 0);
00160 }
00161 
00167 RoadStop *Station::GetPrimaryRoadStop(const RoadVehicle *v) const
00168 {
00169   RoadStop *rs = this->GetPrimaryRoadStop(v->IsBus() ? ROADSTOP_BUS : ROADSTOP_TRUCK);
00170 
00171   for (; rs != NULL; rs = rs->next) {
00172     /* The vehicle cannot go to this roadstop (different roadtype) */
00173     if ((GetRoadTypes(rs->xy) & v->compatible_roadtypes) == ROADTYPES_NONE) continue;
00174     /* The vehicle is articulated and can therefore not go to a standard road stop. */
00175     if (IsStandardRoadStopTile(rs->xy) && v->HasArticulatedPart()) continue;
00176 
00177     /* The vehicle can actually go to this road stop. So, return it! */
00178     break;
00179   }
00180 
00181   return rs;
00182 }
00183 
00188 void Station::AddFacility(StationFacility new_facility_bit, TileIndex facil_xy)
00189 {
00190   if (this->facilities == FACIL_NONE) {
00191     this->xy = facil_xy;
00192     this->random_bits = Random();
00193   }
00194   this->facilities |= new_facility_bit;
00195   this->owner = _current_company;
00196   this->build_date = _date;
00197 }
00198 
00204 void Station::MarkTilesDirty(bool cargo_change) const
00205 {
00206   TileIndex tile = this->train_station.tile;
00207   int w, h;
00208 
00209   if (tile == INVALID_TILE) return;
00210 
00211   /* cargo_change is set if we're refreshing the tiles due to cargo moving
00212    * around. */
00213   if (cargo_change) {
00214     /* Don't waste time updating if there are no custom station graphics
00215      * that might change. Even if there are custom graphics, they might
00216      * not change. Unfortunately we have no way of telling. */
00217     if (this->num_specs == 0) return;
00218   }
00219 
00220   for (h = 0; h < train_station.h; h++) {
00221     for (w = 0; w < train_station.w; w++) {
00222       if (this->TileBelongsToRailStation(tile)) {
00223         MarkTileDirtyByTile(tile);
00224       }
00225       tile += TileDiffXY(1, 0);
00226     }
00227     tile += TileDiffXY(-w, 1);
00228   }
00229 }
00230 
00231 /* virtual */ uint Station::GetPlatformLength(TileIndex tile) const
00232 {
00233   assert(this->TileBelongsToRailStation(tile));
00234 
00235   TileIndexDiff delta = (GetRailStationAxis(tile) == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
00236 
00237   TileIndex t = tile;
00238   uint len = 0;
00239   do {
00240     t -= delta;
00241     len++;
00242   } while (IsCompatibleTrainStationTile(t, tile));
00243 
00244   t = tile;
00245   do {
00246     t += delta;
00247     len++;
00248   } while (IsCompatibleTrainStationTile(t, tile));
00249 
00250   return len - 1;
00251 }
00252 
00253 /* virtual */ uint Station::GetPlatformLength(TileIndex tile, DiagDirection dir) const
00254 {
00255   TileIndex start_tile = tile;
00256   uint length = 0;
00257   assert(IsRailStationTile(tile));
00258   assert(dir < DIAGDIR_END);
00259 
00260   do {
00261     length++;
00262     tile += TileOffsByDiagDir(dir);
00263   } while (IsCompatibleTrainStationTile(tile, start_tile));
00264 
00265   return length;
00266 }
00267 
00272 uint Station::GetCatchmentRadius() const
00273 {
00274   uint ret = CA_NONE;
00275 
00276   if (_settings_game.station.modified_catchment) {
00277     if (this->bus_stops          != NULL)         ret = max<uint>(ret, CA_BUS);
00278     if (this->truck_stops        != NULL)         ret = max<uint>(ret, CA_TRUCK);
00279     if (this->train_station.tile != INVALID_TILE) ret = max<uint>(ret, CA_TRAIN);
00280     if (this->dock_tile          != INVALID_TILE) ret = max<uint>(ret, CA_DOCK);
00281     if (this->airport.tile       != INVALID_TILE) ret = max<uint>(ret, this->airport.GetSpec()->catchment);
00282   } else {
00283     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) {
00284       ret = CA_UNMODIFIED;
00285     }
00286   }
00287 
00288   return ret;
00289 }
00290 
00295 Rect Station::GetCatchmentRect() const
00296 {
00297   assert(!this->rect.IsEmpty());
00298 
00299   /* Compute acceptance rectangle */
00300   int catchment_radius = this->GetCatchmentRadius();
00301 
00302   Rect ret = {
00303     max<int>(this->rect.left   - catchment_radius, 0),
00304     max<int>(this->rect.top    - catchment_radius, 0),
00305     min<int>(this->rect.right  + catchment_radius, MapMaxX()),
00306     min<int>(this->rect.bottom + catchment_radius, MapMaxY())
00307   };
00308 
00309   return ret;
00310 }
00311 
00313 struct RectAndIndustryVector {
00314   Rect rect;                       
00315   IndustryVector *industries_near; 
00316 };
00317 
00326 static bool FindIndustryToDeliver(TileIndex ind_tile, void *user_data)
00327 {
00328   /* Only process industry tiles */
00329   if (!IsTileType(ind_tile, MP_INDUSTRY)) return false;
00330 
00331   RectAndIndustryVector *riv = (RectAndIndustryVector *)user_data;
00332   Industry *ind = Industry::GetByTile(ind_tile);
00333 
00334   /* Don't check further if this industry is already in the list */
00335   if (riv->industries_near->Contains(ind)) return false;
00336 
00337   /* Only process tiles in the station acceptance rectangle */
00338   int x = TileX(ind_tile);
00339   int y = TileY(ind_tile);
00340   if (x < riv->rect.left || x > riv->rect.right || y < riv->rect.top || y > riv->rect.bottom) return false;
00341 
00342   /* Include only industries that can accept cargo */
00343   uint cargo_index;
00344   for (cargo_index = 0; cargo_index < lengthof(ind->accepts_cargo); cargo_index++) {
00345     if (ind->accepts_cargo[cargo_index] != CT_INVALID) break;
00346   }
00347   if (cargo_index >= lengthof(ind->accepts_cargo)) return false;
00348 
00349   *riv->industries_near->Append() = ind;
00350 
00351   return false;
00352 }
00353 
00358 void Station::RecomputeIndustriesNear()
00359 {
00360   this->industries_near.Clear();
00361   if (this->rect.IsEmpty()) return;
00362 
00363   RectAndIndustryVector riv = {
00364     this->GetCatchmentRect(),
00365     &this->industries_near
00366   };
00367 
00368   /* Compute maximum extent of acceptance rectangle wrt. station sign */
00369   TileIndex start_tile = this->xy;
00370   uint max_radius = max(
00371     max(DistanceManhattan(start_tile, TileXY(riv.rect.left,  riv.rect.top)), DistanceManhattan(start_tile, TileXY(riv.rect.left,  riv.rect.bottom))),
00372     max(DistanceManhattan(start_tile, TileXY(riv.rect.right, riv.rect.top)), DistanceManhattan(start_tile, TileXY(riv.rect.right, riv.rect.bottom)))
00373   );
00374 
00375   CircularTileSearch(&start_tile, 2 * max_radius + 1, &FindIndustryToDeliver, &riv);
00376 }
00377 
00381 /* static */ void Station::RecomputeIndustriesNearForAll()
00382 {
00383   Station *st;
00384   FOR_ALL_STATIONS(st) st->RecomputeIndustriesNear();
00385 }
00386 
00387 /************************************************************************/
00388 /*                     StationRect implementation                       */
00389 /************************************************************************/
00390 
00391 StationRect::StationRect()
00392 {
00393   this->MakeEmpty();
00394 }
00395 
00396 void StationRect::MakeEmpty()
00397 {
00398   this->left = this->top = this->right = this->bottom = 0;
00399 }
00400 
00410 bool StationRect::PtInExtendedRect(int x, int y, int distance) const
00411 {
00412   return this->left - distance <= x && x <= this->right + distance &&
00413       this->top - distance <= y && y <= this->bottom + distance;
00414 }
00415 
00416 bool StationRect::IsEmpty() const
00417 {
00418   return this->left == 0 || this->left > this->right || this->top > this->bottom;
00419 }
00420 
00421 CommandCost StationRect::BeforeAddTile(TileIndex tile, StationRectMode mode)
00422 {
00423   int x = TileX(tile);
00424   int y = TileY(tile);
00425   if (this->IsEmpty()) {
00426     /* we are adding the first station tile */
00427     if (mode != ADD_TEST) {
00428       this->left = this->right = x;
00429       this->top = this->bottom = y;
00430     }
00431   } else if (!this->PtInExtendedRect(x, y)) {
00432     /* current rect is not empty and new point is outside this rect
00433      * make new spread-out rectangle */
00434     Rect new_rect = {min(x, this->left), min(y, this->top), max(x, this->right), max(y, this->bottom)};
00435 
00436     /* check new rect dimensions against preset max */
00437     int w = new_rect.right - new_rect.left + 1;
00438     int h = new_rect.bottom - new_rect.top + 1;
00439     if (mode != ADD_FORCE && (w > _settings_game.station.station_spread || h > _settings_game.station.station_spread)) {
00440       assert(mode != ADD_TRY);
00441       return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
00442     }
00443 
00444     /* spread-out ok, return true */
00445     if (mode != ADD_TEST) {
00446       /* we should update the station rect */
00447       *this = new_rect;
00448     }
00449   } else {
00450     ; // new point is inside the rect, we don't need to do anything
00451   }
00452   return CommandCost();
00453 }
00454 
00455 CommandCost StationRect::BeforeAddRect(TileIndex tile, int w, int h, StationRectMode mode)
00456 {
00457   if (mode == ADD_FORCE || (w <= _settings_game.station.station_spread && h <= _settings_game.station.station_spread)) {
00458     /* Important when the old rect is completely inside the new rect, resp. the old one was empty. */
00459     CommandCost ret = this->BeforeAddTile(tile, mode);
00460     if (ret.Succeeded()) ret = this->BeforeAddTile(TILE_ADDXY(tile, w - 1, h - 1), mode);
00461     return ret;
00462   }
00463   return CommandCost();
00464 }
00465 
00475 /* static */ bool StationRect::ScanForStationTiles(StationID st_id, int left_a, int top_a, int right_a, int bottom_a)
00476 {
00477   TileArea ta(TileXY(left_a, top_a), TileXY(right_a, bottom_a));
00478   TILE_AREA_LOOP(tile, ta) {
00479     if (IsTileType(tile, MP_STATION) && GetStationIndex(tile) == st_id) return true;
00480   }
00481 
00482   return false;
00483 }
00484 
00485 bool StationRect::AfterRemoveTile(BaseStation *st, TileIndex tile)
00486 {
00487   int x = TileX(tile);
00488   int y = TileY(tile);
00489 
00490   /* look if removed tile was on the bounding rect edge
00491    * and try to reduce the rect by this edge
00492    * do it until we have empty rect or nothing to do */
00493   for (;;) {
00494     /* check if removed tile is on rect edge */
00495     bool left_edge = (x == this->left);
00496     bool right_edge = (x == this->right);
00497     bool top_edge = (y == this->top);
00498     bool bottom_edge = (y == this->bottom);
00499 
00500     /* can we reduce the rect in either direction? */
00501     bool reduce_x = ((left_edge || right_edge) && !ScanForStationTiles(st->index, x, this->top, x, this->bottom));
00502     bool reduce_y = ((top_edge || bottom_edge) && !ScanForStationTiles(st->index, this->left, y, this->right, y));
00503     if (!(reduce_x || reduce_y)) break; // nothing to do (can't reduce)
00504 
00505     if (reduce_x) {
00506       /* reduce horizontally */
00507       if (left_edge) {
00508         /* move left edge right */
00509         this->left = x = x + 1;
00510       } else {
00511         /* move right edge left */
00512         this->right = x = x - 1;
00513       }
00514     }
00515     if (reduce_y) {
00516       /* reduce vertically */
00517       if (top_edge) {
00518         /* move top edge down */
00519         this->top = y = y + 1;
00520       } else {
00521         /* move bottom edge up */
00522         this->bottom = y = y - 1;
00523       }
00524     }
00525 
00526     if (left > right || top > bottom) {
00527       /* can't continue, if the remaining rectangle is empty */
00528       this->MakeEmpty();
00529       return true; // empty remaining rect
00530     }
00531   }
00532   return false; // non-empty remaining rect
00533 }
00534 
00535 bool StationRect::AfterRemoveRect(BaseStation *st, TileArea ta)
00536 {
00537   assert(this->PtInExtendedRect(TileX(ta.tile), TileY(ta.tile)));
00538   assert(this->PtInExtendedRect(TileX(ta.tile) + ta.w - 1, TileY(ta.tile) + ta.h - 1));
00539 
00540   bool empty = this->AfterRemoveTile(st, ta.tile);
00541   if (ta.w != 1 || ta.h != 1) empty = empty || this->AfterRemoveTile(st, TILE_ADDXY(ta.tile, ta.w - 1, ta.h - 1));
00542   return empty;
00543 }
00544 
00545 StationRect& StationRect::operator = (const Rect &src)
00546 {
00547   this->left = src.left;
00548   this->top = src.top;
00549   this->right = src.right;
00550   this->bottom = src.bottom;
00551   return *this;
00552 }
00553 
00559 Money AirportMaintenanceCost(Owner owner)
00560 {
00561   Money total_cost = 0;
00562 
00563   const Station *st;
00564   FOR_ALL_STATIONS(st) {
00565     if (st->owner == owner && (st->facilities & FACIL_AIRPORT)) {
00566       total_cost += _price[PR_INFRASTRUCTURE_AIRPORT] * st->airport.GetSpec()->maintenance_cost;
00567     }
00568   }
00569   /* 3 bits fraction for the maintenance cost factor. */
00570   return total_cost >> 3;
00571 }