Add ScriptStoryPageElementList to get the contents of a page
[openttd/fttd.git] / src / cargopacket.h
blob7d7e4598bd43858ad750f6638cd9f53cf2fc22e9
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 cargopacket.h Base class for cargo packets. */
12 #ifndef CARGOPACKET_H
13 #define CARGOPACKET_H
15 #include "core/pool_type.hpp"
16 #include "economy_type.h"
17 #include "station_type.h"
18 #include "order_type.h"
19 #include "cargo_type.h"
20 #include "vehicle_type.h"
21 #include "core/multimap.hpp"
22 #include "saveload/saveload_data.h"
23 #include <list>
25 /** Unique identifier for a single cargo packet. */
26 typedef uint32 CargoPacketID;
27 struct CargoPacket;
29 /** Type of the pool for cargo packets for a little over 16 million packets. */
30 typedef Pool<CargoPacket, CargoPacketID, 1024, 0xFFF000, PT_NORMAL, true, false> CargoPacketPool;
31 /** The actual pool with cargo packets. */
32 extern CargoPacketPool _cargopacket_pool;
34 struct GoodsEntry; // forward-declare for Stage() and RerouteStalePackets()
36 template <class Tinst, class Tcont> class CargoList;
37 class StationCargoList; // forward-declare, so we can use it in VehicleCargoList.
38 extern const struct SaveLoad *GetCargoPacketDesc();
40 typedef uint32 TileOrStationID;
42 /**
43 * Container for cargo from the same location and time.
45 struct CargoPacket : CargoPacketPool::PoolItem<&_cargopacket_pool> {
46 private:
47 Money feeder_share; ///< Value of feeder pickup to be paid for on delivery of cargo.
48 uint16 count; ///< The amount of cargo in this packet.
49 byte days_in_transit; ///< Amount of days this packet has been in transit.
50 SourceTypeByte source_type; ///< Type of \c source_id.
51 SourceID source_id; ///< Index of source, INVALID_SOURCE if unknown/invalid.
52 StationID source; ///< The station where the cargo came from first.
53 TileIndex source_xy; ///< The origin of the cargo (first station in feeder chain).
54 union {
55 TileOrStationID loaded_at_xy; ///< Location where this cargo has been loaded into the vehicle.
56 TileOrStationID next_station; ///< Station where the cargo wants to go next.
59 /** The CargoList caches, thus needs to know about it. */
60 template <class Tinst, class Tcont> friend class CargoList;
61 friend class VehicleCargoList;
62 friend class StationCargoList;
63 /** We want this to be saved, right? */
64 friend const struct SaveLoad *GetCargoPacketDesc();
65 public:
66 /** Maximum number of items in a single cargo packet. */
67 static const uint16 MAX_COUNT = UINT16_MAX;
69 CargoPacket();
70 CargoPacket(StationID source, TileIndex source_xy, uint16 count, SourceType source_type, SourceID source_id);
71 CargoPacket(uint16 count, byte days_in_transit, StationID source, TileIndex source_xy, TileIndex loaded_at_xy, Money feeder_share = 0, SourceType source_type = ST_INDUSTRY, SourceID source_id = INVALID_SOURCE);
73 /** Destroy the packet. */
74 ~CargoPacket() { }
76 CargoPacket *Split(uint new_size);
77 void Merge(CargoPacket *cp);
78 void Reduce(uint count);
80 /**
81 * Sets the tile where the packet was loaded last.
82 * @param load_place Tile where the packet was loaded last.
84 void SetLoadPlace(TileIndex load_place) { this->loaded_at_xy = load_place; }
86 /**
87 * Sets the station where the packet is supposed to go next.
88 * @param next_station Next station the packet should go to.
90 void SetNextStation(StationID next_station) { this->next_station = next_station; }
92 /**
93 * Adds some feeder share to the packet.
94 * @param new_share Feeder share to be added.
96 void AddFeederShare(Money new_share) { this->feeder_share += new_share; }
98 /**
99 * Gets the number of 'items' in this packet.
100 * @return Item count.
102 inline uint16 Count() const
104 return this->count;
108 * Gets the amount of money already paid to earlier vehicles in
109 * the feeder chain.
110 * @return Feeder share.
112 inline Money FeederShare() const
114 return this->feeder_share;
118 * Gets part of the amount of money already paid to earlier vehicles in
119 * the feeder chain.
120 * @param part Amount of cargo to get the share for.
121 * @return Feeder share for the given amount of cargo.
123 inline Money FeederShare(uint part) const
125 return this->feeder_share * part / static_cast<uint>(this->count);
129 * Gets the number of days this cargo has been in transit.
130 * This number isn't really in days, but in 2.5 days (CARGO_AGING_TICKS = 185 ticks) and
131 * it is capped at 255.
132 * @return Length this cargo has been in transit.
134 inline byte DaysInTransit() const
136 return this->days_in_transit;
140 * Gets the type of the cargo's source. industry, town or head quarter.
141 * @return Source type.
143 inline SourceType SourceSubsidyType() const
145 return this->source_type;
149 * Gets the ID of the cargo's source. An IndustryID, TownID or CompanyID.
150 * @return Source ID.
152 inline SourceID SourceSubsidyID() const
154 return this->source_id;
158 * Gets the ID of the station where the cargo was loaded for the first time.
159 * @return StationID.
161 inline SourceID SourceStation() const
163 return this->source;
167 * Gets the coordinates of the cargo's source station.
168 * @return Source station's coordinates.
170 inline TileIndex SourceStationXY() const
172 return this->source_xy;
176 * Gets the coordinates of the cargo's last loading station.
177 * @return Last loading station's coordinates.
179 inline TileIndex LoadedAtXY() const
181 return this->loaded_at_xy;
185 * Gets the ID of station the cargo wants to go next.
186 * @return Next station for this packets.
188 inline StationID NextStation() const
190 return this->next_station;
193 static void InvalidateAllFrom(SourceType src_type, SourceID src);
194 static void InvalidateAllFrom(StationID sid);
195 static void AfterLoad(const SavegameTypeVersion *stv);
199 * Iterate over all _valid_ cargo packets from the given start.
200 * @param var Variable used as "iterator".
201 * @param start Cargo packet ID of the first packet to iterate over.
203 #define FOR_ALL_CARGOPACKETS_FROM(var, start) FOR_ALL_ITEMS_FROM(CargoPacket, cargopacket_index, var, start)
206 * Iterate over all _valid_ cargo packets from the begin of the pool.
207 * @param var Variable used as "iterator".
209 #define FOR_ALL_CARGOPACKETS(var) FOR_ALL_CARGOPACKETS_FROM(var, 0)
212 * Simple collection class for a list of cargo packets.
213 * @tparam Tinst Actual instantiation of this cargo list.
215 template <class Tinst, class Tcont>
216 class CargoList {
217 public:
218 /** The iterator for our container. */
219 typedef typename Tcont::iterator Iterator;
220 /** The reverse iterator for our container. */
221 typedef typename Tcont::reverse_iterator ReverseIterator;
222 /** The const iterator for our container. */
223 typedef typename Tcont::const_iterator ConstIterator;
224 /** The const reverse iterator for our container. */
225 typedef typename Tcont::const_reverse_iterator ConstReverseIterator;
227 /** Kind of actions that could be done with packets on move. */
228 enum MoveToAction {
229 MTA_BEGIN = 0,
230 MTA_TRANSFER = 0, ///< Transfer the cargo to the station.
231 MTA_DELIVER, ///< Deliver the cargo to some town or industry.
232 MTA_KEEP, ///< Keep the cargo in the vehicle.
233 MTA_LOAD, ///< Load the cargo from the station.
234 MTA_END,
235 NUM_MOVE_TO_ACTION = MTA_END
238 protected:
239 uint count; ///< Cache for the number of cargo entities.
240 uint cargo_days_in_transit; ///< Cache for the sum of number of days in transit of each entity; comparable to man-hours.
242 Tcont packets; ///< The cargo packets in this list.
244 void AddToCache(const CargoPacket *cp);
246 void RemoveFromCache(const CargoPacket *cp, uint count);
248 static bool TryMerge(CargoPacket *cp, CargoPacket *icp);
250 public:
251 /** Create the cargo list. */
252 CargoList() {}
254 ~CargoList();
256 void OnCleanPool();
259 * Returns a pointer to the cargo packet list (so you can iterate over it etc).
260 * @return Pointer to the packet list.
262 inline const Tcont *Packets() const
264 return &this->packets;
268 * Returns average number of days in transit for a cargo entity.
269 * @return The before mentioned number.
271 inline uint DaysInTransit() const
273 return this->count == 0 ? 0 : this->cargo_days_in_transit / this->count;
276 void InvalidateCache();
279 typedef std::list<CargoPacket *> CargoPacketList;
282 * CargoList that is used for vehicles.
284 class VehicleCargoList : public CargoList<VehicleCargoList, CargoPacketList> {
285 protected:
286 /** The (direct) parent of this class. */
287 typedef CargoList<VehicleCargoList, CargoPacketList> Parent;
289 Money feeder_share; ///< Cache for the feeder share.
290 uint action_counts[NUM_MOVE_TO_ACTION]; ///< Counts of cargo to be transfered, delivered, kept and loaded.
292 template<class Taction>
293 void ShiftCargo(Taction action);
295 template<class Taction>
296 void PopCargo(Taction action);
299 * Assert that the designation counts add up.
301 inline void AssertCountConsistency() const
303 assert(this->action_counts[MTA_KEEP] +
304 this->action_counts[MTA_DELIVER] +
305 this->action_counts[MTA_TRANSFER] +
306 this->action_counts[MTA_LOAD] == this->count);
309 void AddToCache(const CargoPacket *cp);
310 void RemoveFromCache(const CargoPacket *cp, uint count);
312 void AddToMeta(const CargoPacket *cp, MoveToAction action);
313 void RemoveFromMeta(const CargoPacket *cp, MoveToAction action, uint count);
315 static MoveToAction ChooseAction(const CargoPacket *cp, StationID cargo_next,
316 StationID current_station, bool accepted, StationIDStack next_station);
318 public:
319 /** The station cargo list needs to control the unloading. */
320 friend class StationCargoList;
321 /** The super class ought to know what it's doing. */
322 friend class CargoList<VehicleCargoList, CargoPacketList>;
323 /** The vehicles have a cargo list (and we want that saved). */
324 friend const struct SaveLoad *GetVehicleDescription(VehicleType vt);
326 friend class CargoShift;
327 friend class CargoTransfer;
328 friend class CargoDelivery;
329 template<class Tsource>
330 friend class CargoRemoval;
331 friend class CargoReturn;
332 friend class VehicleCargoReroute;
335 * Returns source of the first cargo packet in this list.
336 * @return The before mentioned source.
338 inline StationID Source() const
340 return this->count == 0 ? INVALID_STATION : this->packets.front()->source;
344 * Returns total sum of the feeder share for all packets.
345 * @return The before mentioned number.
347 inline Money FeederShare() const
349 return this->feeder_share;
353 * Returns the amount of cargo designated for a given purpose.
354 * @param action Action the cargo is designated for.
355 * @return Amount of cargo designated for the given action.
357 inline uint ActionCount(MoveToAction action) const
359 return this->action_counts[action];
363 * Returns sum of cargo on board the vehicle (ie not only
364 * reserved).
365 * @return Cargo on board the vehicle.
367 inline uint StoredCount() const
369 return this->count - this->action_counts[MTA_LOAD];
373 * Returns sum of cargo, including reserved cargo.
374 * @return Sum of cargo.
376 inline uint TotalCount() const
378 return this->count;
382 * Returns sum of reserved cargo.
383 * @return Sum of reserved cargo.
385 inline uint ReservedCount() const
387 return this->action_counts[MTA_LOAD];
391 * Returns sum of cargo to be moved out of the vehicle at the current station.
392 * @return Cargo to be moved.
394 inline uint UnloadCount() const
396 return this->action_counts[MTA_TRANSFER] + this->action_counts[MTA_DELIVER];
400 * Returns the sum of cargo to be kept in the vehicle at the current station.
401 * @return Cargo to be kept or loaded.
403 inline uint RemainingCount() const
405 return this->action_counts[MTA_KEEP] + this->action_counts[MTA_LOAD];
408 void Append(CargoPacket *cp, MoveToAction action = MTA_KEEP);
410 void AgeCargo();
412 void InvalidateCache();
414 void SetTransferLoadPlace(TileIndex xy);
416 bool Stage(bool accepted, StationID current_station, StationIDStack next_station, uint8 order_flags, const GoodsEntry *ge, CargoPayment *payment);
419 * Marks all cargo in the vehicle as to be kept. This is mostly useful for
420 * loading old savegames. When loading is aborted the reserved cargo has
421 * to be returned first.
423 inline void KeepAll()
425 this->action_counts[MTA_DELIVER] = this->action_counts[MTA_TRANSFER] = this->action_counts[MTA_LOAD] = 0;
426 this->action_counts[MTA_KEEP] = this->count;
429 /* Methods for moving cargo around. First parameter is always maximum
430 * amount of cargo to be moved. Second parameter is destination (if
431 * applicable), return value is amount of cargo actually moved. */
433 uint Reassign(uint max_move, MoveToAction from, MoveToAction to);
434 uint Return(uint max_move, StationCargoList *dest, StationID next_station);
435 uint Unload(uint max_move, StationCargoList *dest, CargoPayment *payment);
436 uint Shift(uint max_move, VehicleCargoList *dest);
437 uint Truncate(uint max_move = UINT_MAX);
438 uint Reroute(uint max_move, VehicleCargoList *dest, StationID avoid, StationID avoid2, const GoodsEntry *ge);
441 * Are two the two CargoPackets mergeable in the context of
442 * a list of CargoPackets for a Vehicle?
443 * @param cp1 First CargoPacket.
444 * @param cp2 Second CargoPacket.
445 * @return True if they are mergeable.
447 static bool AreMergable(const CargoPacket *cp1, const CargoPacket *cp2)
449 return cp1->source_xy == cp2->source_xy &&
450 cp1->days_in_transit == cp2->days_in_transit &&
451 cp1->source_type == cp2->source_type &&
452 cp1->source_id == cp2->source_id &&
453 cp1->loaded_at_xy == cp2->loaded_at_xy;
457 typedef MultiMap<StationID, CargoPacket *> StationCargoPacketMap;
458 typedef std::map<StationID, uint> StationCargoAmountMap;
461 * CargoList that is used for stations.
463 class StationCargoList : public CargoList<StationCargoList, StationCargoPacketMap> {
464 protected:
465 /** The (direct) parent of this class. */
466 typedef CargoList<StationCargoList, StationCargoPacketMap> Parent;
468 uint reserved_count; ///< Amount of cargo being reserved for loading.
470 public:
471 /** The super class ought to know what it's doing. */
472 friend class CargoList<StationCargoList, StationCargoPacketMap>;
473 /** The stations, via GoodsEntry, have a CargoList. */
474 friend const struct SaveLoad *GetGoodsDesc();
476 friend class CargoLoad;
477 friend class CargoTransfer;
478 template<class Tsource>
479 friend class CargoRemoval;
480 friend class CargoReservation;
481 friend class CargoReturn;
482 friend class StationCargoReroute;
484 static void InvalidateAllFrom(SourceType src_type, SourceID src);
486 template<class Taction>
487 bool ShiftCargo(Taction &action, StationID next);
489 template<class Taction>
490 uint ShiftCargo(Taction action, StationIDStack next, bool include_invalid);
492 void Append(CargoPacket *cp, StationID next);
495 * Check for cargo headed for a specific station.
496 * @param next Station the cargo is headed for.
497 * @return If there is any cargo for that station.
499 inline bool HasCargoFor(StationIDStack next) const
501 while (!next.IsEmpty()) {
502 if (this->packets.find(next.Pop()) != this->packets.end()) return true;
504 /* Packets for INVALID_STTION can go anywhere. */
505 return this->packets.find(INVALID_STATION) != this->packets.end();
509 * Returns source of the first cargo packet in this list.
510 * @return The before mentioned source.
512 inline StationID Source() const
514 return this->count == 0 ? INVALID_STATION : this->packets.begin()->second.front()->source;
518 * Returns sum of cargo still available for loading at the sation.
519 * (i.e. not counting cargo which is already reserved for loading)
520 * @return Cargo on board the vehicle.
522 inline uint AvailableCount() const
524 return this->count;
528 * Returns sum of cargo reserved for loading onto vehicles.
529 * @return Cargo reserved for loading.
531 inline uint ReservedCount() const
533 return this->reserved_count;
537 * Returns total count of cargo at the station, including
538 * cargo which is already reserved for loading.
539 * @return Total cargo count.
541 inline uint TotalCount() const
543 return this->count + this->reserved_count;
546 /* Methods for moving cargo around. First parameter is always maximum
547 * amount of cargo to be moved. Second parameter is destination (if
548 * applicable), return value is amount of cargo actually moved. */
550 uint Reserve(uint max_move, VehicleCargoList *dest, TileIndex load_place, StationIDStack next);
551 uint Load(uint max_move, VehicleCargoList *dest, TileIndex load_place, StationIDStack next);
552 uint Truncate(uint max_move = UINT_MAX, StationCargoAmountMap *cargo_per_source = NULL);
553 uint Reroute(uint max_move, StationCargoList *dest, StationID avoid, StationID avoid2, const GoodsEntry *ge);
556 * Are two the two CargoPackets mergeable in the context of
557 * a list of CargoPackets for a Vehicle?
558 * @param cp1 First CargoPacket.
559 * @param cp2 Second CargoPacket.
560 * @return True if they are mergeable.
562 static bool AreMergable(const CargoPacket *cp1, const CargoPacket *cp2)
564 return cp1->source_xy == cp2->source_xy &&
565 cp1->days_in_transit == cp2->days_in_transit &&
566 cp1->source_type == cp2->source_type &&
567 cp1->source_id == cp2->source_id;
571 #endif /* CARGOPACKET_H */