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 
00071 Station::~Station()
00072 {
00073   if (CleaningPool()) {
00074     for (CargoID c = 0; c < NUM_CARGO; c++) {
00075       this->goods[c].cargo.OnCleanPool();
00076     }
00077     return;
00078   }
00079 
00080   while (!this->loading_vehicles.empty()) {
00081     this->loading_vehicles.front()->LeaveStation();
00082   }
00083 
00084   Aircraft *a;
00085   FOR_ALL_AIRCRAFT(a) {
00086     if (!a->IsNormalAircraft()) continue;
00087     if (a->targetairport == this->index) a->targetairport = INVALID_STATION;
00088   }
00089 
00090   Vehicle *v;
00091   FOR_ALL_VEHICLES(v) {
00092     /* Forget about this station if this station is removed */
00093     if (v->last_station_visited == this->index) {
00094       v->last_station_visited = INVALID_STATION;
00095     }
00096   }
00097 
00098   /* Clear the persistent storage. */
00099   delete this->airport.psa;
00100 
00101   if (this->owner == OWNER_NONE) {
00102     /* Invalidate all in case of oil rigs. */
00103     InvalidateWindowClassesData(WC_STATION_LIST, 0);
00104   } else {
00105     InvalidateWindowData(WC_STATION_LIST, this->owner, 0);
00106   }
00107 
00108   DeleteWindowById(WC_STATION_VIEW, index);
00109 
00110   /* Now delete all orders that go to the station */
00111   RemoveOrderFromAllVehicles(OT_GOTO_STATION, this->index);
00112 
00113   /* Remove all news items */
00114   DeleteStationNews(this->index);
00115 
00116   for (CargoID c = 0; c < NUM_CARGO; c++) {
00117     this->goods[c].cargo.Truncate(0);
00118   }
00119 
00120   CargoPacket::InvalidateAllFrom(this->index);
00121 }
00122 
00123 
00129 void BaseStation::PostDestructor(size_t index)
00130 {
00131   InvalidateWindowData(WC_SELECT_STATION, 0, 0);
00132 }
00133 
00139 RoadStop *Station::GetPrimaryRoadStop(const RoadVehicle *v) const
00140 {
00141   RoadStop *rs = this->GetPrimaryRoadStop(v->IsBus() ? ROADSTOP_BUS : ROADSTOP_TRUCK);
00142 
00143   for (; rs != NULL; rs = rs->next) {
00144     /* The vehicle cannot go to this roadstop (different roadtype) */
00145     if ((GetRoadTypes(rs->xy) & v->compatible_roadtypes) == ROADTYPES_NONE) continue;
00146     /* The vehicle is articulated and can therefor not go the a standard road stop */
00147     if (IsStandardRoadStopTile(rs->xy) && v->HasArticulatedPart()) continue;
00148 
00149     /* The vehicle can actually go to this road stop. So, return it! */
00150     break;
00151   }
00152 
00153   return rs;
00154 }
00155 
00160 void Station::AddFacility(StationFacility new_facility_bit, TileIndex facil_xy)
00161 {
00162   if (this->facilities == FACIL_NONE) {
00163     this->xy = facil_xy;
00164     this->random_bits = Random();
00165   }
00166   this->facilities |= new_facility_bit;
00167   this->owner = _current_company;
00168   this->build_date = _date;
00169 }
00170 
00176 void Station::MarkTilesDirty(bool cargo_change) const
00177 {
00178   TileIndex tile = this->train_station.tile;
00179   int w, h;
00180 
00181   if (tile == INVALID_TILE) return;
00182 
00183   /* cargo_change is set if we're refreshing the tiles due to cargo moving
00184    * around. */
00185   if (cargo_change) {
00186     /* Don't waste time updating if there are no custom station graphics
00187      * that might change. Even if there are custom graphics, they might
00188      * not change. Unfortunately we have no way of telling. */
00189     if (this->num_specs == 0) return;
00190   }
00191 
00192   for (h = 0; h < train_station.h; h++) {
00193     for (w = 0; w < train_station.w; w++) {
00194       if (this->TileBelongsToRailStation(tile)) {
00195         MarkTileDirtyByTile(tile);
00196       }
00197       tile += TileDiffXY(1, 0);
00198     }
00199     tile += TileDiffXY(-w, 1);
00200   }
00201 }
00202 
00203 /* virtual */ uint Station::GetPlatformLength(TileIndex tile) const
00204 {
00205   assert(this->TileBelongsToRailStation(tile));
00206 
00207   TileIndexDiff delta = (GetRailStationAxis(tile) == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
00208 
00209   TileIndex t = tile;
00210   uint len = 0;
00211   do {
00212     t -= delta;
00213     len++;
00214   } while (IsCompatibleTrainStationTile(t, tile));
00215 
00216   t = tile;
00217   do {
00218     t += delta;
00219     len++;
00220   } while (IsCompatibleTrainStationTile(t, tile));
00221 
00222   return len - 1;
00223 }
00224 
00225 /* virtual */ uint Station::GetPlatformLength(TileIndex tile, DiagDirection dir) const
00226 {
00227   TileIndex start_tile = tile;
00228   uint length = 0;
00229   assert(IsRailStationTile(tile));
00230   assert(dir < DIAGDIR_END);
00231 
00232   do {
00233     length++;
00234     tile += TileOffsByDiagDir(dir);
00235   } while (IsCompatibleTrainStationTile(tile, start_tile));
00236 
00237   return length;
00238 }
00239 
00244 uint Station::GetCatchmentRadius() const
00245 {
00246   uint ret = CA_NONE;
00247 
00248   if (_settings_game.station.modified_catchment) {
00249     if (this->bus_stops          != NULL)         ret = max<uint>(ret, CA_BUS);
00250     if (this->truck_stops        != NULL)         ret = max<uint>(ret, CA_TRUCK);
00251     if (this->train_station.tile != INVALID_TILE) ret = max<uint>(ret, CA_TRAIN);
00252     if (this->dock_tile          != INVALID_TILE) ret = max<uint>(ret, CA_DOCK);
00253     if (this->airport.tile       != INVALID_TILE) ret = max<uint>(ret, this->airport.GetSpec()->catchment);
00254   } else {
00255     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) {
00256       ret = CA_UNMODIFIED;
00257     }
00258   }
00259 
00260   return ret;
00261 }
00262 
00267 Rect Station::GetCatchmentRect() const
00268 {
00269   assert(!this->rect.IsEmpty());
00270 
00271   /* Compute acceptance rectangle */
00272   int catchment_radius = this->GetCatchmentRadius();
00273 
00274   Rect ret = {
00275     max<int>(this->rect.left   - catchment_radius, 0),
00276     max<int>(this->rect.top    - catchment_radius, 0),
00277     min<int>(this->rect.right  + catchment_radius, MapMaxX()),
00278     min<int>(this->rect.bottom + catchment_radius, MapMaxY())
00279   };
00280 
00281   return ret;
00282 }
00283 
00285 struct RectAndIndustryVector {
00286   Rect rect;                       
00287   IndustryVector *industries_near; 
00288 };
00289 
00298 static bool FindIndustryToDeliver(TileIndex ind_tile, void *user_data)
00299 {
00300   /* Only process industry tiles */
00301   if (!IsTileType(ind_tile, MP_INDUSTRY)) return false;
00302 
00303   RectAndIndustryVector *riv = (RectAndIndustryVector *)user_data;
00304   Industry *ind = Industry::GetByTile(ind_tile);
00305 
00306   /* Don't check further if this industry is already in the list */
00307   if (riv->industries_near->Contains(ind)) return false;
00308 
00309   /* Only process tiles in the station acceptance rectangle */
00310   int x = TileX(ind_tile);
00311   int y = TileY(ind_tile);
00312   if (x < riv->rect.left || x > riv->rect.right || y < riv->rect.top || y > riv->rect.bottom) return false;
00313 
00314   /* Include only industries that can accept cargo */
00315   uint cargo_index;
00316   for (cargo_index = 0; cargo_index < lengthof(ind->accepts_cargo); cargo_index++) {
00317     if (ind->accepts_cargo[cargo_index] != CT_INVALID) break;
00318   }
00319   if (cargo_index >= lengthof(ind->accepts_cargo)) return false;
00320 
00321   *riv->industries_near->Append() = ind;
00322 
00323   return false;
00324 }
00325 
00330 void Station::RecomputeIndustriesNear()
00331 {
00332   this->industries_near.Clear();
00333   if (this->rect.IsEmpty()) return;
00334 
00335   RectAndIndustryVector riv = {
00336     this->GetCatchmentRect(),
00337     &this->industries_near
00338   };
00339 
00340   /* Compute maximum extent of acceptance rectangle wrt. station sign */
00341   TileIndex start_tile = this->xy;
00342   uint max_radius = max(
00343     max(DistanceManhattan(start_tile, TileXY(riv.rect.left,  riv.rect.top)), DistanceManhattan(start_tile, TileXY(riv.rect.left,  riv.rect.bottom))),
00344     max(DistanceManhattan(start_tile, TileXY(riv.rect.right, riv.rect.top)), DistanceManhattan(start_tile, TileXY(riv.rect.right, riv.rect.bottom)))
00345   );
00346 
00347   CircularTileSearch(&start_tile, 2 * max_radius + 1, &FindIndustryToDeliver, &riv);
00348 }
00349 
00353 /* static */ void Station::RecomputeIndustriesNearForAll()
00354 {
00355   Station *st;
00356   FOR_ALL_STATIONS(st) st->RecomputeIndustriesNear();
00357 }
00358 
00359 /************************************************************************/
00360 /*                     StationRect implementation                       */
00361 /************************************************************************/
00362 
00363 StationRect::StationRect()
00364 {
00365   this->MakeEmpty();
00366 }
00367 
00368 void StationRect::MakeEmpty()
00369 {
00370   this->left = this->top = this->right = this->bottom = 0;
00371 }
00372 
00382 bool StationRect::PtInExtendedRect(int x, int y, int distance) const
00383 {
00384   return this->left - distance <= x && x <= this->right + distance &&
00385       this->top - distance <= y && y <= this->bottom + distance;
00386 }
00387 
00388 bool StationRect::IsEmpty() const
00389 {
00390   return this->left == 0 || this->left > this->right || this->top > this->bottom;
00391 }
00392 
00393 CommandCost StationRect::BeforeAddTile(TileIndex tile, StationRectMode mode)
00394 {
00395   int x = TileX(tile);
00396   int y = TileY(tile);
00397   if (this->IsEmpty()) {
00398     /* we are adding the first station tile */
00399     if (mode != ADD_TEST) {
00400       this->left = this->right = x;
00401       this->top = this->bottom = y;
00402     }
00403   } else if (!this->PtInExtendedRect(x, y)) {
00404     /* current rect is not empty and new point is outside this rect
00405      * make new spread-out rectangle */
00406     Rect new_rect = {min(x, this->left), min(y, this->top), max(x, this->right), max(y, this->bottom)};
00407 
00408     /* check new rect dimensions against preset max */
00409     int w = new_rect.right - new_rect.left + 1;
00410     int h = new_rect.bottom - new_rect.top + 1;
00411     if (mode != ADD_FORCE && (w > _settings_game.station.station_spread || h > _settings_game.station.station_spread)) {
00412       assert(mode != ADD_TRY);
00413       return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
00414     }
00415 
00416     /* spread-out ok, return true */
00417     if (mode != ADD_TEST) {
00418       /* we should update the station rect */
00419       *this = new_rect;
00420     }
00421   } else {
00422     ; // new point is inside the rect, we don't need to do anything
00423   }
00424   return CommandCost();
00425 }
00426 
00427 CommandCost StationRect::BeforeAddRect(TileIndex tile, int w, int h, StationRectMode mode)
00428 {
00429   if (mode == ADD_FORCE || (w <= _settings_game.station.station_spread && h <= _settings_game.station.station_spread)) {
00430     /* Important when the old rect is completely inside the new rect, resp. the old one was empty. */
00431     CommandCost ret = this->BeforeAddTile(tile, mode);
00432     if (ret.Succeeded()) ret = this->BeforeAddTile(TILE_ADDXY(tile, w - 1, h - 1), mode);
00433     return ret;
00434   }
00435   return CommandCost();
00436 }
00437 
00447 /* static */ bool StationRect::ScanForStationTiles(StationID st_id, int left_a, int top_a, int right_a, int bottom_a)
00448 {
00449   TileArea ta(TileXY(left_a, top_a), TileXY(right_a, bottom_a));
00450   TILE_AREA_LOOP(tile, ta) {
00451     if (IsTileType(tile, MP_STATION) && GetStationIndex(tile) == st_id) return true;
00452   }
00453 
00454   return false;
00455 }
00456 
00457 bool StationRect::AfterRemoveTile(BaseStation *st, TileIndex tile)
00458 {
00459   int x = TileX(tile);
00460   int y = TileY(tile);
00461 
00462   /* look if removed tile was on the bounding rect edge
00463    * and try to reduce the rect by this edge
00464    * do it until we have empty rect or nothing to do */
00465   for (;;) {
00466     /* check if removed tile is on rect edge */
00467     bool left_edge = (x == this->left);
00468     bool right_edge = (x == this->right);
00469     bool top_edge = (y == this->top);
00470     bool bottom_edge = (y == this->bottom);
00471 
00472     /* can we reduce the rect in either direction? */
00473     bool reduce_x = ((left_edge || right_edge) && !ScanForStationTiles(st->index, x, this->top, x, this->bottom));
00474     bool reduce_y = ((top_edge || bottom_edge) && !ScanForStationTiles(st->index, this->left, y, this->right, y));
00475     if (!(reduce_x || reduce_y)) break; // nothing to do (can't reduce)
00476 
00477     if (reduce_x) {
00478       /* reduce horizontally */
00479       if (left_edge) {
00480         /* move left edge right */
00481         this->left = x = x + 1;
00482       } else {
00483         /* move right edge left */
00484         this->right = x = x - 1;
00485       }
00486     }
00487     if (reduce_y) {
00488       /* reduce vertically */
00489       if (top_edge) {
00490         /* move top edge down */
00491         this->top = y = y + 1;
00492       } else {
00493         /* move bottom edge up */
00494         this->bottom = y = y - 1;
00495       }
00496     }
00497 
00498     if (left > right || top > bottom) {
00499       /* can't continue, if the remaining rectangle is empty */
00500       this->MakeEmpty();
00501       return true; // empty remaining rect
00502     }
00503   }
00504   return false; // non-empty remaining rect
00505 }
00506 
00507 bool StationRect::AfterRemoveRect(BaseStation *st, TileArea ta)
00508 {
00509   assert(this->PtInExtendedRect(TileX(ta.tile), TileY(ta.tile)));
00510   assert(this->PtInExtendedRect(TileX(ta.tile) + ta.w - 1, TileY(ta.tile) + ta.h - 1));
00511 
00512   bool empty = this->AfterRemoveTile(st, ta.tile);
00513   if (ta.w != 1 || ta.h != 1) empty = empty || this->AfterRemoveTile(st, TILE_ADDXY(ta.tile, ta.w - 1, ta.h - 1));
00514   return empty;
00515 }
00516 
00517 StationRect& StationRect::operator = (const Rect &src)
00518 {
00519   this->left = src.left;
00520   this->top = src.top;
00521   this->right = src.right;
00522   this->bottom = src.bottom;
00523   return *this;
00524 }
00525 
00531 Money AirportMaintenanceCost(Owner owner)
00532 {
00533   Money total_cost = 0;
00534 
00535   const Station *st;
00536   FOR_ALL_STATIONS(st) {
00537     if (st->owner == owner && (st->facilities & FACIL_AIRPORT)) {
00538       total_cost += _price[PR_INFRASTRUCTURE_AIRPORT] * st->airport.GetSpec()->maintenance_cost;
00539     }
00540   }
00541   /* 3 bits fraction for the maintenance cost factor. */
00542   return total_cost >> 3;
00543 }