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