station.cpp

Go to the documentation of this file.
00001 /* $Id: station.cpp 21483 2010-12-12 17:36:34Z 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 "company_func.h"
00014 #include "company_base.h"
00015 #include "roadveh.h"
00016 #include "functions.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 
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()) return;
00074 
00075   while (!this->loading_vehicles.empty()) {
00076     this->loading_vehicles.front()->LeaveStation();
00077   }
00078 
00079   Aircraft *a;
00080   FOR_ALL_AIRCRAFT(a) {
00081     if (!a->IsNormalAircraft()) continue;
00082     if (a->targetairport == this->index) a->targetairport = INVALID_STATION;
00083   }
00084 
00085   Vehicle *v;
00086   FOR_ALL_VEHICLES(v) {
00087     /* Forget about this station if this station is removed */
00088     if (v->last_station_visited == this->index) {
00089       v->last_station_visited = INVALID_STATION;
00090     }
00091   }
00092 
00093   InvalidateWindowData(WC_STATION_LIST, this->owner, 0);
00094 
00095   DeleteWindowById(WC_STATION_VIEW, index);
00096 
00097   /* Now delete all orders that go to the station */
00098   RemoveOrderFromAllVehicles(OT_GOTO_STATION, this->index);
00099 
00100   /* Remove all news items */
00101   DeleteStationNews(this->index);
00102 
00103   for (CargoID c = 0; c < NUM_CARGO; c++) {
00104     this->goods[c].cargo.Truncate(0);
00105   }
00106 
00107   CargoPacket::InvalidateAllFrom(this->index);
00108 }
00109 
00110 
00116 void BaseStation::PostDestructor(size_t index)
00117 {
00118   InvalidateWindowData(WC_SELECT_STATION, 0, 0);
00119 }
00120 
00126 RoadStop *Station::GetPrimaryRoadStop(const RoadVehicle *v) const
00127 {
00128   RoadStop *rs = this->GetPrimaryRoadStop(v->IsBus() ? ROADSTOP_BUS : ROADSTOP_TRUCK);
00129 
00130   for (; rs != NULL; rs = rs->next) {
00131     /* The vehicle cannot go to this roadstop (different roadtype) */
00132     if ((GetRoadTypes(rs->xy) & v->compatible_roadtypes) == ROADTYPES_NONE) continue;
00133     /* The vehicle is articulated and can therefor not go the a standard road stop */
00134     if (IsStandardRoadStopTile(rs->xy) && v->HasArticulatedPart()) continue;
00135 
00136     /* The vehicle can actually go to this road stop. So, return it! */
00137     break;
00138   }
00139 
00140   return rs;
00141 }
00142 
00147 void Station::AddFacility(StationFacility new_facility_bit, TileIndex facil_xy)
00148 {
00149   if (this->facilities == FACIL_NONE) {
00150     this->xy = facil_xy;
00151     this->random_bits = Random();
00152   }
00153   this->facilities |= new_facility_bit;
00154   this->owner = _current_company;
00155   this->build_date = _date;
00156 }
00157 
00158 void Station::MarkTilesDirty(bool cargo_change) const
00159 {
00160   TileIndex tile = this->train_station.tile;
00161   int w, h;
00162 
00163   if (tile == INVALID_TILE) return;
00164 
00165   /* cargo_change is set if we're refreshing the tiles due to cargo moving
00166    * around. */
00167   if (cargo_change) {
00168     /* Don't waste time updating if there are no custom station graphics
00169      * that might change. Even if there are custom graphics, they might
00170      * not change. Unfortunately we have no way of telling. */
00171     if (this->num_specs == 0) return;
00172   }
00173 
00174   for (h = 0; h < train_station.h; h++) {
00175     for (w = 0; w < train_station.w; w++) {
00176       if (this->TileBelongsToRailStation(tile)) {
00177         MarkTileDirtyByTile(tile);
00178       }
00179       tile += TileDiffXY(1, 0);
00180     }
00181     tile += TileDiffXY(-w, 1);
00182   }
00183 }
00184 
00185 /* virtual */ uint Station::GetPlatformLength(TileIndex tile) const
00186 {
00187   assert(this->TileBelongsToRailStation(tile));
00188 
00189   TileIndexDiff delta = (GetRailStationAxis(tile) == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
00190 
00191   TileIndex t = tile;
00192   uint len = 0;
00193   do {
00194     t -= delta;
00195     len++;
00196   } while (IsCompatibleTrainStationTile(t, tile));
00197 
00198   t = tile;
00199   do {
00200     t += delta;
00201     len++;
00202   } while (IsCompatibleTrainStationTile(t, tile));
00203 
00204   return len - 1;
00205 }
00206 
00207 /* virtual */ uint Station::GetPlatformLength(TileIndex tile, DiagDirection dir) const
00208 {
00209   TileIndex start_tile = tile;
00210   uint length = 0;
00211   assert(IsRailStationTile(tile));
00212   assert(dir < DIAGDIR_END);
00213 
00214   do {
00215     length++;
00216     tile += TileOffsByDiagDir(dir);
00217   } while (IsCompatibleTrainStationTile(tile, start_tile));
00218 
00219   return length;
00220 }
00221 
00226 uint Station::GetCatchmentRadius() const
00227 {
00228   uint ret = CA_NONE;
00229 
00230   if (_settings_game.station.modified_catchment) {
00231     if (this->bus_stops          != NULL)         ret = max<uint>(ret, CA_BUS);
00232     if (this->truck_stops        != NULL)         ret = max<uint>(ret, CA_TRUCK);
00233     if (this->train_station.tile != INVALID_TILE) ret = max<uint>(ret, CA_TRAIN);
00234     if (this->dock_tile          != INVALID_TILE) ret = max<uint>(ret, CA_DOCK);
00235     if (this->airport.tile       != INVALID_TILE) ret = max<uint>(ret, this->airport.GetSpec()->catchment);
00236   } else {
00237     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) {
00238       ret = CA_UNMODIFIED;
00239     }
00240   }
00241 
00242   return ret;
00243 }
00244 
00249 Rect Station::GetCatchmentRect() const
00250 {
00251   assert(!this->rect.IsEmpty());
00252 
00253   /* Compute acceptance rectangle */
00254   int catchment_radius = this->GetCatchmentRadius();
00255 
00256   Rect ret = {
00257     max<int>(this->rect.left   - catchment_radius, 0),
00258     max<int>(this->rect.top    - catchment_radius, 0),
00259     min<int>(this->rect.right  + catchment_radius, MapMaxX()),
00260     min<int>(this->rect.bottom + catchment_radius, MapMaxY())
00261   };
00262 
00263   return ret;
00264 }
00265 
00267 struct RectAndIndustryVector {
00268   Rect rect;
00269   IndustryVector *industries_near;
00270 };
00271 
00280 static bool FindIndustryToDeliver(TileIndex ind_tile, void *user_data)
00281 {
00282   /* Only process industry tiles */
00283   if (!IsTileType(ind_tile, MP_INDUSTRY)) return false;
00284 
00285   RectAndIndustryVector *riv = (RectAndIndustryVector *)user_data;
00286   Industry *ind = Industry::GetByTile(ind_tile);
00287 
00288   /* Don't check further if this industry is already in the list */
00289   if (riv->industries_near->Contains(ind)) return false;
00290 
00291   /* Only process tiles in the station acceptance rectangle */
00292   int x = TileX(ind_tile);
00293   int y = TileY(ind_tile);
00294   if (x < riv->rect.left || x > riv->rect.right || y < riv->rect.top || y > riv->rect.bottom) return false;
00295 
00296   /* Include only industries that can accept cargo */
00297   uint cargo_index;
00298   for (cargo_index = 0; cargo_index < lengthof(ind->accepts_cargo); cargo_index++) {
00299     if (ind->accepts_cargo[cargo_index] != CT_INVALID) break;
00300   }
00301   if (cargo_index >= lengthof(ind->accepts_cargo)) return false;
00302 
00303   *riv->industries_near->Append() = ind;
00304 
00305   return false;
00306 }
00307 
00312 void Station::RecomputeIndustriesNear()
00313 {
00314   this->industries_near.Clear();
00315   if (this->rect.IsEmpty()) return;
00316 
00317   RectAndIndustryVector riv = {
00318     this->GetCatchmentRect(),
00319     &this->industries_near
00320   };
00321 
00322   /* Compute maximum extent of acceptance rectangle wrt. station sign */
00323   TileIndex start_tile = this->xy;
00324   uint max_radius = max(
00325     max(DistanceManhattan(start_tile, TileXY(riv.rect.left,  riv.rect.top)), DistanceManhattan(start_tile, TileXY(riv.rect.left,  riv.rect.bottom))),
00326     max(DistanceManhattan(start_tile, TileXY(riv.rect.right, riv.rect.top)), DistanceManhattan(start_tile, TileXY(riv.rect.right, riv.rect.bottom)))
00327   );
00328 
00329   CircularTileSearch(&start_tile, 2 * max_radius + 1, &FindIndustryToDeliver, &riv);
00330 }
00331 
00335 /* static */ void Station::RecomputeIndustriesNearForAll()
00336 {
00337   Station *st;
00338   FOR_ALL_STATIONS(st) st->RecomputeIndustriesNear();
00339 }
00340 
00341 /************************************************************************/
00342 /*                     StationRect implementation                       */
00343 /************************************************************************/
00344 
00345 StationRect::StationRect()
00346 {
00347   this->MakeEmpty();
00348 }
00349 
00350 void StationRect::MakeEmpty()
00351 {
00352   this->left = this->top = this->right = this->bottom = 0;
00353 }
00354 
00364 bool StationRect::PtInExtendedRect(int x, int y, int distance) const
00365 {
00366   return this->left - distance <= x && x <= this->right + distance &&
00367       this->top - distance <= y && y <= this->bottom + distance;
00368 }
00369 
00370 bool StationRect::IsEmpty() const
00371 {
00372   return this->left == 0 || this->left > this->right || this->top > this->bottom;
00373 }
00374 
00375 CommandCost StationRect::BeforeAddTile(TileIndex tile, StationRectMode mode)
00376 {
00377   int x = TileX(tile);
00378   int y = TileY(tile);
00379   if (this->IsEmpty()) {
00380     /* we are adding the first station tile */
00381     if (mode != ADD_TEST) {
00382       this->left = this->right = x;
00383       this->top = this->bottom = y;
00384     }
00385   } else if (!this->PtInExtendedRect(x, y)) {
00386     /* current rect is not empty and new point is outside this rect
00387      * make new spread-out rectangle */
00388     Rect new_rect = {min(x, this->left), min(y, this->top), max(x, this->right), max(y, this->bottom)};
00389 
00390     /* check new rect dimensions against preset max */
00391     int w = new_rect.right - new_rect.left + 1;
00392     int h = new_rect.bottom - new_rect.top + 1;
00393     if (mode != ADD_FORCE && (w > _settings_game.station.station_spread || h > _settings_game.station.station_spread)) {
00394       assert(mode != ADD_TRY);
00395       return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
00396     }
00397 
00398     /* spread-out ok, return true */
00399     if (mode != ADD_TEST) {
00400       /* we should update the station rect */
00401       *this = new_rect;
00402     }
00403   } else {
00404     ; // new point is inside the rect, we don't need to do anything
00405   }
00406   return CommandCost();
00407 }
00408 
00409 CommandCost StationRect::BeforeAddRect(TileIndex tile, int w, int h, StationRectMode mode)
00410 {
00411   if (mode == ADD_FORCE || (w <= _settings_game.station.station_spread && h <= _settings_game.station.station_spread)) {
00412     /* Important when the old rect is completely inside the new rect, resp. the old one was empty. */
00413     CommandCost ret = this->BeforeAddTile(tile, mode);
00414     if (ret.Succeeded()) ret = this->BeforeAddTile(TILE_ADDXY(tile, w - 1, h - 1), mode);
00415     return ret;
00416   }
00417   return CommandCost();
00418 }
00419 
00429 /* static */ bool StationRect::ScanForStationTiles(StationID st_id, int left_a, int top_a, int right_a, int bottom_a)
00430 {
00431   TileArea ta(TileXY(left_a, top_a), TileXY(right_a, bottom_a));
00432   TILE_AREA_LOOP(tile, ta) {
00433     if (IsTileType(tile, MP_STATION) && GetStationIndex(tile) == st_id) return true;
00434   }
00435 
00436   return false;
00437 }
00438 
00439 bool StationRect::AfterRemoveTile(BaseStation *st, TileIndex tile)
00440 {
00441   int x = TileX(tile);
00442   int y = TileY(tile);
00443 
00444   /* look if removed tile was on the bounding rect edge
00445    * and try to reduce the rect by this edge
00446    * do it until we have empty rect or nothing to do */
00447   for (;;) {
00448     /* check if removed tile is on rect edge */
00449     bool left_edge = (x == this->left);
00450     bool right_edge = (x == this->right);
00451     bool top_edge = (y == this->top);
00452     bool bottom_edge = (y == this->bottom);
00453 
00454     /* can we reduce the rect in either direction? */
00455     bool reduce_x = ((left_edge || right_edge) && !ScanForStationTiles(st->index, x, this->top, x, this->bottom));
00456     bool reduce_y = ((top_edge || bottom_edge) && !ScanForStationTiles(st->index, this->left, y, this->right, y));
00457     if (!(reduce_x || reduce_y)) break; // nothing to do (can't reduce)
00458 
00459     if (reduce_x) {
00460       /* reduce horizontally */
00461       if (left_edge) {
00462         /* move left edge right */
00463         this->left = x = x + 1;
00464       } else {
00465         /* move right edge left */
00466         this->right = x = x - 1;
00467       }
00468     }
00469     if (reduce_y) {
00470       /* reduce vertically */
00471       if (top_edge) {
00472         /* move top edge down */
00473         this->top = y = y + 1;
00474       } else {
00475         /* move bottom edge up */
00476         this->bottom = y = y - 1;
00477       }
00478     }
00479 
00480     if (left > right || top > bottom) {
00481       /* can't continue, if the remaining rectangle is empty */
00482       this->MakeEmpty();
00483       return true; // empty remaining rect
00484     }
00485   }
00486   return false; // non-empty remaining rect
00487 }
00488 
00489 bool StationRect::AfterRemoveRect(BaseStation *st, TileArea ta)
00490 {
00491   assert(this->PtInExtendedRect(TileX(ta.tile), TileY(ta.tile)));
00492   assert(this->PtInExtendedRect(TileX(ta.tile) + ta.w - 1, TileY(ta.tile) + ta.h - 1));
00493 
00494   bool empty = this->AfterRemoveTile(st, ta.tile);
00495   if (ta.w != 1 || ta.h != 1) empty = empty || this->AfterRemoveTile(st, TILE_ADDXY(ta.tile, ta.w - 1, ta.h - 1));
00496   return empty;
00497 }
00498 
00499 StationRect& StationRect::operator = (const Rect &src)
00500 {
00501   this->left = src.left;
00502   this->top = src.top;
00503   this->right = src.right;
00504   this->bottom = src.bottom;
00505   return *this;
00506 }
00507 
00508 
00509 void InitializeStations()
00510 {
00511   _station_pool.CleanPool();
00512 }

Generated on Sun Jan 9 16:02:01 2011 for OpenTTD by  doxygen 1.6.1