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 "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 
00163 void Station::MarkTilesDirty(bool cargo_change) const
00164 {
00165   TileIndex tile = this->train_station.tile;
00166   int w, h;
00167 
00168   if (tile == INVALID_TILE) return;
00169 
00170   /* cargo_change is set if we're refreshing the tiles due to cargo moving
00171    * around. */
00172   if (cargo_change) {
00173     /* Don't waste time updating if there are no custom station graphics
00174      * that might change. Even if there are custom graphics, they might
00175      * not change. Unfortunately we have no way of telling. */
00176     if (this->num_specs == 0) return;
00177   }
00178 
00179   for (h = 0; h < train_station.h; h++) {
00180     for (w = 0; w < train_station.w; w++) {
00181       if (this->TileBelongsToRailStation(tile)) {
00182         MarkTileDirtyByTile(tile);
00183       }
00184       tile += TileDiffXY(1, 0);
00185     }
00186     tile += TileDiffXY(-w, 1);
00187   }
00188 }
00189 
00190 /* virtual */ uint Station::GetPlatformLength(TileIndex tile) const
00191 {
00192   assert(this->TileBelongsToRailStation(tile));
00193 
00194   TileIndexDiff delta = (GetRailStationAxis(tile) == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
00195 
00196   TileIndex t = tile;
00197   uint len = 0;
00198   do {
00199     t -= delta;
00200     len++;
00201   } while (IsCompatibleTrainStationTile(t, tile));
00202 
00203   t = tile;
00204   do {
00205     t += delta;
00206     len++;
00207   } while (IsCompatibleTrainStationTile(t, tile));
00208 
00209   return len - 1;
00210 }
00211 
00212 /* virtual */ uint Station::GetPlatformLength(TileIndex tile, DiagDirection dir) const
00213 {
00214   TileIndex start_tile = tile;
00215   uint length = 0;
00216   assert(IsRailStationTile(tile));
00217   assert(dir < DIAGDIR_END);
00218 
00219   do {
00220     length++;
00221     tile += TileOffsByDiagDir(dir);
00222   } while (IsCompatibleTrainStationTile(tile, start_tile));
00223 
00224   return length;
00225 }
00226 
00231 uint Station::GetCatchmentRadius() const
00232 {
00233   uint ret = CA_NONE;
00234 
00235   if (_settings_game.station.modified_catchment) {
00236     if (this->bus_stops          != NULL)         ret = max<uint>(ret, CA_BUS);
00237     if (this->truck_stops        != NULL)         ret = max<uint>(ret, CA_TRUCK);
00238     if (this->train_station.tile != INVALID_TILE) ret = max<uint>(ret, CA_TRAIN);
00239     if (this->dock_tile          != INVALID_TILE) ret = max<uint>(ret, CA_DOCK);
00240     if (this->airport.tile       != INVALID_TILE) ret = max<uint>(ret, this->airport.GetSpec()->catchment);
00241   } else {
00242     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) {
00243       ret = CA_UNMODIFIED;
00244     }
00245   }
00246 
00247   return ret;
00248 }
00249 
00254 Rect Station::GetCatchmentRect() const
00255 {
00256   assert(!this->rect.IsEmpty());
00257 
00258   /* Compute acceptance rectangle */
00259   int catchment_radius = this->GetCatchmentRadius();
00260 
00261   Rect ret = {
00262     max<int>(this->rect.left   - catchment_radius, 0),
00263     max<int>(this->rect.top    - catchment_radius, 0),
00264     min<int>(this->rect.right  + catchment_radius, MapMaxX()),
00265     min<int>(this->rect.bottom + catchment_radius, MapMaxY())
00266   };
00267 
00268   return ret;
00269 }
00270 
00272 struct RectAndIndustryVector {
00273   Rect rect;
00274   IndustryVector *industries_near;
00275 };
00276 
00285 static bool FindIndustryToDeliver(TileIndex ind_tile, void *user_data)
00286 {
00287   /* Only process industry tiles */
00288   if (!IsTileType(ind_tile, MP_INDUSTRY)) return false;
00289 
00290   RectAndIndustryVector *riv = (RectAndIndustryVector *)user_data;
00291   Industry *ind = Industry::GetByTile(ind_tile);
00292 
00293   /* Don't check further if this industry is already in the list */
00294   if (riv->industries_near->Contains(ind)) return false;
00295 
00296   /* Only process tiles in the station acceptance rectangle */
00297   int x = TileX(ind_tile);
00298   int y = TileY(ind_tile);
00299   if (x < riv->rect.left || x > riv->rect.right || y < riv->rect.top || y > riv->rect.bottom) return false;
00300 
00301   /* Include only industries that can accept cargo */
00302   uint cargo_index;
00303   for (cargo_index = 0; cargo_index < lengthof(ind->accepts_cargo); cargo_index++) {
00304     if (ind->accepts_cargo[cargo_index] != CT_INVALID) break;
00305   }
00306   if (cargo_index >= lengthof(ind->accepts_cargo)) return false;
00307 
00308   *riv->industries_near->Append() = ind;
00309 
00310   return false;
00311 }
00312 
00317 void Station::RecomputeIndustriesNear()
00318 {
00319   this->industries_near.Clear();
00320   if (this->rect.IsEmpty()) return;
00321 
00322   RectAndIndustryVector riv = {
00323     this->GetCatchmentRect(),
00324     &this->industries_near
00325   };
00326 
00327   /* Compute maximum extent of acceptance rectangle wrt. station sign */
00328   TileIndex start_tile = this->xy;
00329   uint max_radius = max(
00330     max(DistanceManhattan(start_tile, TileXY(riv.rect.left,  riv.rect.top)), DistanceManhattan(start_tile, TileXY(riv.rect.left,  riv.rect.bottom))),
00331     max(DistanceManhattan(start_tile, TileXY(riv.rect.right, riv.rect.top)), DistanceManhattan(start_tile, TileXY(riv.rect.right, riv.rect.bottom)))
00332   );
00333 
00334   CircularTileSearch(&start_tile, 2 * max_radius + 1, &FindIndustryToDeliver, &riv);
00335 }
00336 
00340 /* static */ void Station::RecomputeIndustriesNearForAll()
00341 {
00342   Station *st;
00343   FOR_ALL_STATIONS(st) st->RecomputeIndustriesNear();
00344 }
00345 
00346 /************************************************************************/
00347 /*                     StationRect implementation                       */
00348 /************************************************************************/
00349 
00350 StationRect::StationRect()
00351 {
00352   this->MakeEmpty();
00353 }
00354 
00355 void StationRect::MakeEmpty()
00356 {
00357   this->left = this->top = this->right = this->bottom = 0;
00358 }
00359 
00369 bool StationRect::PtInExtendedRect(int x, int y, int distance) const
00370 {
00371   return this->left - distance <= x && x <= this->right + distance &&
00372       this->top - distance <= y && y <= this->bottom + distance;
00373 }
00374 
00375 bool StationRect::IsEmpty() const
00376 {
00377   return this->left == 0 || this->left > this->right || this->top > this->bottom;
00378 }
00379 
00380 CommandCost StationRect::BeforeAddTile(TileIndex tile, StationRectMode mode)
00381 {
00382   int x = TileX(tile);
00383   int y = TileY(tile);
00384   if (this->IsEmpty()) {
00385     /* we are adding the first station tile */
00386     if (mode != ADD_TEST) {
00387       this->left = this->right = x;
00388       this->top = this->bottom = y;
00389     }
00390   } else if (!this->PtInExtendedRect(x, y)) {
00391     /* current rect is not empty and new point is outside this rect
00392      * make new spread-out rectangle */
00393     Rect new_rect = {min(x, this->left), min(y, this->top), max(x, this->right), max(y, this->bottom)};
00394 
00395     /* check new rect dimensions against preset max */
00396     int w = new_rect.right - new_rect.left + 1;
00397     int h = new_rect.bottom - new_rect.top + 1;
00398     if (mode != ADD_FORCE && (w > _settings_game.station.station_spread || h > _settings_game.station.station_spread)) {
00399       assert(mode != ADD_TRY);
00400       return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
00401     }
00402 
00403     /* spread-out ok, return true */
00404     if (mode != ADD_TEST) {
00405       /* we should update the station rect */
00406       *this = new_rect;
00407     }
00408   } else {
00409     ; // new point is inside the rect, we don't need to do anything
00410   }
00411   return CommandCost();
00412 }
00413 
00414 CommandCost StationRect::BeforeAddRect(TileIndex tile, int w, int h, StationRectMode mode)
00415 {
00416   if (mode == ADD_FORCE || (w <= _settings_game.station.station_spread && h <= _settings_game.station.station_spread)) {
00417     /* Important when the old rect is completely inside the new rect, resp. the old one was empty. */
00418     CommandCost ret = this->BeforeAddTile(tile, mode);
00419     if (ret.Succeeded()) ret = this->BeforeAddTile(TILE_ADDXY(tile, w - 1, h - 1), mode);
00420     return ret;
00421   }
00422   return CommandCost();
00423 }
00424 
00434 /* static */ bool StationRect::ScanForStationTiles(StationID st_id, int left_a, int top_a, int right_a, int bottom_a)
00435 {
00436   TileArea ta(TileXY(left_a, top_a), TileXY(right_a, bottom_a));
00437   TILE_AREA_LOOP(tile, ta) {
00438     if (IsTileType(tile, MP_STATION) && GetStationIndex(tile) == st_id) return true;
00439   }
00440 
00441   return false;
00442 }
00443 
00444 bool StationRect::AfterRemoveTile(BaseStation *st, TileIndex tile)
00445 {
00446   int x = TileX(tile);
00447   int y = TileY(tile);
00448 
00449   /* look if removed tile was on the bounding rect edge
00450    * and try to reduce the rect by this edge
00451    * do it until we have empty rect or nothing to do */
00452   for (;;) {
00453     /* check if removed tile is on rect edge */
00454     bool left_edge = (x == this->left);
00455     bool right_edge = (x == this->right);
00456     bool top_edge = (y == this->top);
00457     bool bottom_edge = (y == this->bottom);
00458 
00459     /* can we reduce the rect in either direction? */
00460     bool reduce_x = ((left_edge || right_edge) && !ScanForStationTiles(st->index, x, this->top, x, this->bottom));
00461     bool reduce_y = ((top_edge || bottom_edge) && !ScanForStationTiles(st->index, this->left, y, this->right, y));
00462     if (!(reduce_x || reduce_y)) break; // nothing to do (can't reduce)
00463 
00464     if (reduce_x) {
00465       /* reduce horizontally */
00466       if (left_edge) {
00467         /* move left edge right */
00468         this->left = x = x + 1;
00469       } else {
00470         /* move right edge left */
00471         this->right = x = x - 1;
00472       }
00473     }
00474     if (reduce_y) {
00475       /* reduce vertically */
00476       if (top_edge) {
00477         /* move top edge down */
00478         this->top = y = y + 1;
00479       } else {
00480         /* move bottom edge up */
00481         this->bottom = y = y - 1;
00482       }
00483     }
00484 
00485     if (left > right || top > bottom) {
00486       /* can't continue, if the remaining rectangle is empty */
00487       this->MakeEmpty();
00488       return true; // empty remaining rect
00489     }
00490   }
00491   return false; // non-empty remaining rect
00492 }
00493 
00494 bool StationRect::AfterRemoveRect(BaseStation *st, TileArea ta)
00495 {
00496   assert(this->PtInExtendedRect(TileX(ta.tile), TileY(ta.tile)));
00497   assert(this->PtInExtendedRect(TileX(ta.tile) + ta.w - 1, TileY(ta.tile) + ta.h - 1));
00498 
00499   bool empty = this->AfterRemoveTile(st, ta.tile);
00500   if (ta.w != 1 || ta.h != 1) empty = empty || this->AfterRemoveTile(st, TILE_ADDXY(ta.tile, ta.w - 1, ta.h - 1));
00501   return empty;
00502 }
00503 
00504 StationRect& StationRect::operator = (const Rect &src)
00505 {
00506   this->left = src.left;
00507   this->top = src.top;
00508   this->right = src.right;
00509   this->bottom = src.bottom;
00510   return *this;
00511 }
00512 
00513 
00514 void InitializeStations()
00515 {
00516   _station_pool.CleanPool();
00517 }

Generated on Sun Jan 23 01:49:09 2011 for OpenTTD by  doxygen 1.6.1