(svn r27763) -Update from Eints:
[openttd.git] / src / station_base.h
blobaf4d206ba043091bf6458d6813b26a78e1199ccc
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * 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/>.
8 */
10 /** @file station_base.h Base classes/functions for stations. */
12 #ifndef STATION_BASE_H
13 #define STATION_BASE_H
15 #include "core/random_func.hpp"
16 #include "base_station_base.h"
17 #include "newgrf_airport.h"
18 #include "cargopacket.h"
19 #include "industry_type.h"
20 #include "linkgraph/linkgraph_type.h"
21 #include "newgrf_storage.h"
22 #include <map>
24 typedef Pool<BaseStation, StationID, 32, 64000> StationPool;
25 extern StationPool _station_pool;
27 static const byte INITIAL_STATION_RATING = 175;
29 /**
30 * Flow statistics telling how much flow should be sent along a link. This is
31 * done by creating "flow shares" and using std::map's upper_bound() method to
32 * look them up with a random number. A flow share is the difference between a
33 * key in a map and the previous key. So one key in the map doesn't actually
34 * mean anything by itself.
36 class FlowStat {
37 public:
38 typedef std::map<uint32, StationID> SharesMap;
40 static const SharesMap empty_sharesmap;
42 /**
43 * Invalid constructor. This can't be called as a FlowStat must not be
44 * empty. However, the constructor must be defined and reachable for
45 * FlwoStat to be used in a std::map.
47 inline FlowStat() {NOT_REACHED();}
49 /**
50 * Create a FlowStat with an initial entry.
51 * @param st Station the initial entry refers to.
52 * @param flow Amount of flow for the initial entry.
53 * @param restricted If the flow to be added is restricted.
55 inline FlowStat(StationID st, uint flow, bool restricted = false)
57 assert(flow > 0);
58 this->shares[flow] = st;
59 this->unrestricted = restricted ? 0 : flow;
62 /**
63 * Add some flow to the end of the shares map. Only do that if you know
64 * that the station isn't in the map yet. Anything else may lead to
65 * inconsistencies.
66 * @param st Remote station.
67 * @param flow Amount of flow to be added.
68 * @param restricted If the flow to be added is restricted.
70 inline void AppendShare(StationID st, uint flow, bool restricted = false)
72 assert(flow > 0);
73 this->shares[(--this->shares.end())->first + flow] = st;
74 if (!restricted) this->unrestricted += flow;
77 uint GetShare(StationID st) const;
79 void ChangeShare(StationID st, int flow);
81 void RestrictShare(StationID st);
83 void ReleaseShare(StationID st);
85 void ScaleToMonthly(uint runtime);
87 /**
88 * Get the actual shares as a const pointer so that they can be iterated
89 * over.
90 * @return Actual shares.
92 inline const SharesMap *GetShares() const { return &this->shares; }
94 /**
95 * Return total amount of unrestricted shares.
96 * @return Amount of unrestricted shares.
98 inline uint GetUnrestricted() const { return this->unrestricted; }
101 * Swap the shares maps, and thus the content of this FlowStat with the
102 * other one.
103 * @param other FlowStat to swap with.
105 inline void SwapShares(FlowStat &other)
107 this->shares.swap(other.shares);
108 Swap(this->unrestricted, other.unrestricted);
112 * Get a station a package can be routed to. This done by drawing a
113 * random number between 0 and sum_shares and then looking that up in
114 * the map with lower_bound. So each share gets selected with a
115 * probability dependent on its flow. Do include restricted flows here.
116 * @param is_restricted Output if a restricted flow was chosen.
117 * @return A station ID from the shares map.
119 inline StationID GetViaWithRestricted(bool &is_restricted) const
121 assert(!this->shares.empty());
122 uint rand = RandomRange((--this->shares.end())->first);
123 is_restricted = rand >= this->unrestricted;
124 return this->shares.upper_bound(rand)->second;
128 * Get a station a package can be routed to. This done by drawing a
129 * random number between 0 and sum_shares and then looking that up in
130 * the map with lower_bound. So each share gets selected with a
131 * probability dependent on its flow. Don't include restricted flows.
132 * @return A station ID from the shares map.
134 inline StationID GetVia() const
136 assert(!this->shares.empty());
137 return this->unrestricted > 0 ?
138 this->shares.upper_bound(RandomRange(this->unrestricted))->second :
139 INVALID_STATION;
142 StationID GetVia(StationID excluded, StationID excluded2 = INVALID_STATION) const;
144 void Invalidate();
146 private:
147 SharesMap shares; ///< Shares of flow to be sent via specified station (or consumed locally).
148 uint unrestricted; ///< Limit for unrestricted shares.
151 /** Flow descriptions by origin stations. */
152 class FlowStatMap : public std::map<StationID, FlowStat> {
153 public:
154 uint GetFlow() const;
155 uint GetFlowVia(StationID via) const;
156 uint GetFlowFrom(StationID from) const;
157 uint GetFlowFromVia(StationID from, StationID via) const;
159 void AddFlow(StationID origin, StationID via, uint amount);
160 void PassOnFlow(StationID origin, StationID via, uint amount);
161 StationIDStack DeleteFlows(StationID via);
162 void RestrictFlows(StationID via);
163 void ReleaseFlows(StationID via);
164 void FinalizeLocalConsumption(StationID self);
168 * Stores station stats for a single cargo.
170 struct GoodsEntry {
171 /** Status of this cargo for the station. */
172 enum GoodsEntryStatus {
174 * Set when the station accepts the cargo currently for final deliveries.
175 * It is updated every STATION_ACCEPTANCE_TICKS ticks by checking surrounding tiles for acceptance >= 8/8.
177 GES_ACCEPTANCE,
180 * This indicates whether a cargo has a rating at the station.
181 * Set when cargo was ever waiting at the station.
182 * It is set when cargo supplied by surrounding tiles is moved to the station, or when
183 * arriving vehicles unload/transfer cargo without it being a final delivery.
185 * This flag is cleared after 255 * STATION_RATING_TICKS of not having seen a pickup.
187 GES_RATING,
190 * Set when a vehicle ever delivered cargo to the station for final delivery.
191 * This flag is never cleared.
193 GES_EVER_ACCEPTED,
196 * Set when cargo was delivered for final delivery last month.
197 * This flag is set to the value of GES_CURRENT_MONTH at the start of each month.
199 GES_LAST_MONTH,
202 * Set when cargo was delivered for final delivery this month.
203 * This flag is reset on the beginning of every month.
205 GES_CURRENT_MONTH,
208 * Set when cargo was delivered for final delivery during the current STATION_ACCEPTANCE_TICKS interval.
209 * This flag is reset every STATION_ACCEPTANCE_TICKS ticks.
211 GES_ACCEPTED_BIGTICK,
214 GoodsEntry() :
215 status(0),
216 time_since_pickup(255),
217 rating(INITIAL_STATION_RATING),
218 last_speed(0),
219 last_age(255),
220 amount_fract(0),
221 link_graph(INVALID_LINK_GRAPH),
222 node(INVALID_NODE),
223 max_waiting_cargo(0)
226 byte status; ///< Status of this cargo, see #GoodsEntryStatus.
229 * Number of rating-intervals (up to 255) since the last vehicle tried to load this cargo.
230 * The unit used is STATION_RATING_TICKS.
231 * This does not imply there was any cargo to load.
233 byte time_since_pickup;
235 byte rating; ///< %Station rating for this cargo.
238 * Maximum speed (up to 255) of the last vehicle that tried to load this cargo.
239 * This does not imply there was any cargo to load.
240 * The unit used is a special vehicle-specific speed unit for station ratings.
241 * - Trains: km-ish/h
242 * - RV: km-ish/h
243 * - Ships: 0.5 * km-ish/h
244 * - Aircraft: 8 * mph
246 byte last_speed;
249 * Age in years (up to 255) of the last vehicle that tried to load this cargo.
250 * This does not imply there was any cargo to load.
252 byte last_age;
254 byte amount_fract; ///< Fractional part of the amount in the cargo list
255 StationCargoList cargo; ///< The cargo packets of cargo waiting in this station
257 LinkGraphID link_graph; ///< Link graph this station belongs to.
258 NodeID node; ///< ID of node in link graph referring to this goods entry.
259 FlowStatMap flows; ///< Planned flows through this station.
260 uint max_waiting_cargo; ///< Max cargo from this station waiting at any station.
263 * Reports whether a vehicle has ever tried to load the cargo at this station.
264 * This does not imply that there was cargo available for loading. Refer to GES_RATING for that.
265 * @return true if vehicle tried to load.
267 bool HasVehicleEverTriedLoading() const { return this->last_speed != 0; }
270 * Does this cargo have a rating at this station?
271 * @return true if the cargo has a rating, i.e. cargo has been moved to the station.
273 inline bool HasRating() const
275 return HasBit(this->status, GES_RATING);
279 * Get the best next hop for a cargo packet from station source.
280 * @param source Source of the packet.
281 * @return The chosen next hop or INVALID_STATION if none was found.
283 inline StationID GetVia(StationID source) const
285 FlowStatMap::const_iterator flow_it(this->flows.find(source));
286 return flow_it != this->flows.end() ? flow_it->second.GetVia() : INVALID_STATION;
290 * Get the best next hop for a cargo packet from station source, optionally
291 * excluding one or two stations.
292 * @param source Source of the packet.
293 * @param excluded If this station would be chosen choose the second best one instead.
294 * @param excluded2 Second station to be excluded, if != INVALID_STATION.
295 * @return The chosen next hop or INVALID_STATION if none was found.
297 inline StationID GetVia(StationID source, StationID excluded, StationID excluded2 = INVALID_STATION) const
299 FlowStatMap::const_iterator flow_it(this->flows.find(source));
300 return flow_it != this->flows.end() ? flow_it->second.GetVia(excluded, excluded2) : INVALID_STATION;
304 /** All airport-related information. Only valid if tile != INVALID_TILE. */
305 struct Airport : public TileArea {
306 Airport() : TileArea(INVALID_TILE, 0, 0) {}
308 uint64 flags; ///< stores which blocks on the airport are taken. was 16 bit earlier on, then 32
309 byte type; ///< Type of this airport, @see AirportTypes
310 byte layout; ///< Airport layout number.
311 DirectionByte rotation; ///< How this airport is rotated.
313 PersistentStorage *psa; ///< Persistent storage for NewGRF airports.
316 * Get the AirportSpec that from the airport type of this airport. If there
317 * is no airport (\c tile == INVALID_TILE) then return the dummy AirportSpec.
318 * @return The AirportSpec for this airport.
320 const AirportSpec *GetSpec() const
322 if (this->tile == INVALID_TILE) return &AirportSpec::dummy;
323 return AirportSpec::Get(this->type);
327 * Get the finite-state machine for this airport or the finite-state machine
328 * for the dummy airport in case this isn't an airport.
329 * @pre this->type < NEW_AIRPORT_OFFSET.
330 * @return The state machine for this airport.
332 const AirportFTAClass *GetFTA() const
334 return this->GetSpec()->fsm;
337 /** Check if this airport has at least one hangar. */
338 inline bool HasHangar() const
340 return this->GetSpec()->nof_depots > 0;
344 * Add the tileoffset to the base tile of this airport but rotate it first.
345 * The base tile is the northernmost tile of this airport. This function
346 * helps to make sure that getting the tile of a hangar works even for
347 * rotated airport layouts without requiring a rotated array of hangar tiles.
348 * @param tidc The tilediff to add to the airport tile.
349 * @return The tile of this airport plus the rotated offset.
351 inline TileIndex GetRotatedTileFromOffset(TileIndexDiffC tidc) const
353 const AirportSpec *as = this->GetSpec();
354 switch (this->rotation) {
355 case DIR_N: return this->tile + ToTileIndexDiff(tidc);
357 case DIR_E: return this->tile + TileDiffXY(tidc.y, as->size_x - 1 - tidc.x);
359 case DIR_S: return this->tile + TileDiffXY(as->size_x - 1 - tidc.x, as->size_y - 1 - tidc.y);
361 case DIR_W: return this->tile + TileDiffXY(as->size_y - 1 - tidc.y, tidc.x);
363 default: NOT_REACHED();
368 * Get the first tile of the given hangar.
369 * @param hangar_num The hangar to get the location of.
370 * @pre hangar_num < GetNumHangars().
371 * @return A tile with the given hangar.
373 inline TileIndex GetHangarTile(uint hangar_num) const
375 const AirportSpec *as = this->GetSpec();
376 for (uint i = 0; i < as->nof_depots; i++) {
377 if (as->depot_table[i].hangar_num == hangar_num) {
378 return this->GetRotatedTileFromOffset(as->depot_table[i].ti);
381 NOT_REACHED();
385 * Get the exit direction of the hangar at a specific tile.
386 * @param tile The tile to query.
387 * @pre IsHangarTile(tile).
388 * @return The exit direction of the hangar, taking airport rotation into account.
390 inline Direction GetHangarExitDirection(TileIndex tile) const
392 const AirportSpec *as = this->GetSpec();
393 const HangarTileTable *htt = GetHangarDataByTile(tile);
394 return ChangeDir(htt->dir, DirDifference(this->rotation, as->rotation[0]));
398 * Get the hangar number of the hangar at a specific tile.
399 * @param tile The tile to query.
400 * @pre IsHangarTile(tile).
401 * @return The hangar number of the hangar at the given tile.
403 inline uint GetHangarNum(TileIndex tile) const
405 const HangarTileTable *htt = GetHangarDataByTile(tile);
406 return htt->hangar_num;
409 /** Get the number of hangars on this airport. */
410 inline uint GetNumHangars() const
412 uint num = 0;
413 uint counted = 0;
414 const AirportSpec *as = this->GetSpec();
415 for (uint i = 0; i < as->nof_depots; i++) {
416 if (!HasBit(counted, as->depot_table[i].hangar_num)) {
417 num++;
418 SetBit(counted, as->depot_table[i].hangar_num);
421 return num;
424 private:
426 * Retrieve hangar information of a hangar at a given tile.
427 * @param tile %Tile containing the hangar.
428 * @return The requested hangar information.
429 * @pre The \a tile must be at a hangar tile at an airport.
431 inline const HangarTileTable *GetHangarDataByTile(TileIndex tile) const
433 const AirportSpec *as = this->GetSpec();
434 for (uint i = 0; i < as->nof_depots; i++) {
435 if (this->GetRotatedTileFromOffset(as->depot_table[i].ti) == tile) {
436 return as->depot_table + i;
439 NOT_REACHED();
443 typedef SmallVector<Industry *, 2> IndustryVector;
445 /** Station data structure */
446 struct Station FINAL : SpecializedStation<Station, false> {
447 public:
448 RoadStop *GetPrimaryRoadStop(RoadStopType type) const
450 return type == ROADSTOP_BUS ? bus_stops : truck_stops;
453 RoadStop *GetPrimaryRoadStop(const struct RoadVehicle *v) const;
455 RoadStop *bus_stops; ///< All the road stops
456 TileArea bus_station; ///< Tile area the bus 'station' part covers
457 RoadStop *truck_stops; ///< All the truck stops
458 TileArea truck_station; ///< Tile area the truck 'station' part covers
460 Airport airport; ///< Tile area the airport covers
461 TileIndex dock_tile; ///< The location of the dock
463 IndustryType indtype; ///< Industry type to get the name from
465 StationHadVehicleOfTypeByte had_vehicle_of_type;
467 byte time_since_load;
468 byte time_since_unload;
470 byte last_vehicle_type;
471 std::list<Vehicle *> loading_vehicles;
472 GoodsEntry goods[NUM_CARGO]; ///< Goods at this station
473 uint32 always_accepted; ///< Bitmask of always accepted cargo types (by houses, HQs, industry tiles when industry doesn't accept cargo)
475 IndustryVector industries_near; ///< Cached list of industries near the station that can accept cargo, @see DeliverGoodsToIndustry()
477 Station(TileIndex tile = INVALID_TILE);
478 ~Station();
480 void AddFacility(StationFacility new_facility_bit, TileIndex facil_xy);
482 void MarkTilesDirty(bool cargo_change) const;
484 void UpdateVirtCoord();
486 /* virtual */ uint GetPlatformLength(TileIndex tile, DiagDirection dir) const;
487 /* virtual */ uint GetPlatformLength(TileIndex tile) const;
488 void RecomputeIndustriesNear();
489 static void RecomputeIndustriesNearForAll();
491 uint GetCatchmentRadius() const;
492 Rect GetCatchmentRect() const;
494 /* virtual */ inline bool TileBelongsToRailStation(TileIndex tile) const
496 return IsRailStationTile(tile) && GetStationIndex(tile) == this->index;
499 inline bool TileBelongsToAirport(TileIndex tile) const
501 return IsAirportTile(tile) && GetStationIndex(tile) == this->index;
504 /* virtual */ uint32 GetNewGRFVariable(const ResolverObject &object, byte variable, byte parameter, bool *available) const;
506 /* virtual */ void GetTileArea(TileArea *ta, StationType type) const;
509 #define FOR_ALL_STATIONS(var) FOR_ALL_BASE_STATIONS_OF_TYPE(Station, var)
511 /** Iterator to iterate over all tiles belonging to an airport. */
512 class AirportTileIterator : public OrthogonalTileIterator {
513 private:
514 const Station *st; ///< The station the airport is a part of.
516 public:
518 * Construct the iterator.
519 * @param ta Area, i.e. begin point and width/height of to-be-iterated area.
521 AirportTileIterator(const Station *st) : OrthogonalTileIterator(st->airport), st(st)
523 if (!st->TileBelongsToAirport(this->tile)) ++(*this);
526 inline TileIterator& operator ++()
528 (*this).OrthogonalTileIterator::operator++();
529 while (this->tile != INVALID_TILE && !st->TileBelongsToAirport(this->tile)) {
530 (*this).OrthogonalTileIterator::operator++();
532 return *this;
535 virtual TileIterator *Clone() const
537 return new AirportTileIterator(*this);
541 #endif /* STATION_BASE_H */