OpenTTD Source 15.0-beta2
refresh.cpp
1/*
2 * This file is part of OpenTTD.
3 * 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.
4 * 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.
5 * 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/>.
6 */
7
10#include "../stdafx.h"
11#include "../core/bitmath_func.hpp"
12#include "../station_func.h"
13#include "../engine_base.h"
14#include "../vehicle_func.h"
15#include "refresh.h"
16#include "linkgraph.h"
17
18#include "../safeguards.h"
19
26/* static */ void LinkRefresher::Run(Vehicle *v, bool allow_merge, bool is_full_loading)
27{
28 /* If there are no orders we can't predict anything.*/
29 if (v->orders == nullptr) return;
30
31 /* Make sure the first order is a useful order. */
33 if (first == nullptr) return;
34
35 HopSet seen_hops;
37
38 refresher.RefreshLinks(first, first, v->last_loading_station != StationID::Invalid() ? RefreshFlags{RefreshFlag::HasCargo} : RefreshFlags{});
39}
40
49LinkRefresher::LinkRefresher(Vehicle *vehicle, HopSet *seen_hops, bool allow_merge, bool is_full_loading) :
50 vehicle(vehicle), seen_hops(seen_hops), cargo(INVALID_CARGO), allow_merge(allow_merge),
51 is_full_loading(is_full_loading)
52{
53 /* Assemble list of capacities and set last loading stations to 0. */
54 for (Vehicle *v = this->vehicle; v != nullptr; v = v->Next()) {
55 this->refit_capacities.push_back(RefitDesc(v->cargo_type, v->cargo_cap, v->refit_cap));
56 if (v->refit_cap > 0) {
57 assert(v->cargo_type < NUM_CARGO);
58 this->capacities[v->cargo_type] += v->refit_cap;
59 }
60 }
61}
62
69{
70 this->cargo = refit_cargo;
71 RefitList::iterator refit_it = this->refit_capacities.begin();
72 bool any_refit = false;
73 for (Vehicle *v = this->vehicle; v != nullptr; v = v->Next()) {
74 const Engine *e = Engine::Get(v->engine_type);
75 if (!HasBit(e->info.refit_mask, this->cargo)) {
76 ++refit_it;
77 continue;
78 }
79 any_refit = true;
80
81 /* Back up the vehicle's cargo type */
82 CargoType temp_cargo_type = v->cargo_type;
83 uint8_t temp_subtype = v->cargo_subtype;
84 v->cargo_type = this->cargo;
85 v->cargo_subtype = GetBestFittingSubType(v, v, this->cargo);
86
87 uint16_t mail_capacity = 0;
88 uint amount = e->DetermineCapacity(v, &mail_capacity);
89
90 /* Restore the original cargo type */
91 v->cargo_type = temp_cargo_type;
92 v->cargo_subtype = temp_subtype;
93
94 /* Skip on next refit. */
95 if (this->cargo != refit_it->cargo && refit_it->remaining > 0) {
96 this->capacities[refit_it->cargo] -= refit_it->remaining;
97 refit_it->remaining = 0;
98 } else if (amount < refit_it->remaining) {
99 this->capacities[refit_it->cargo] -= refit_it->remaining - amount;
100 refit_it->remaining = amount;
101 }
102 refit_it->capacity = amount;
103 refit_it->cargo = this->cargo;
104
105 ++refit_it;
106
107 /* Special case for aircraft with mail. */
108 if (v->type == VEH_AIRCRAFT) {
109 if (mail_capacity < refit_it->remaining) {
110 this->capacities[refit_it->cargo] -= refit_it->remaining - mail_capacity;
111 refit_it->remaining = mail_capacity;
112 }
113 refit_it->capacity = mail_capacity;
114 break; // aircraft have only one vehicle
115 }
116 }
117 return any_refit;
118}
119
124{
125 for (auto &it : this->refit_capacities) {
126 if (it.remaining == it.capacity) continue;
127 this->capacities[it.cargo] += it.capacity - it.remaining;
128 it.remaining = it.capacity;
129 }
130}
131
141const Order *LinkRefresher::PredictNextOrder(const Order *cur, const Order *next, RefreshFlags flags, uint num_hops)
142{
143 /* next is good if it's either nullptr (then the caller will stop the
144 * evaluation) or if it's not conditional and the caller allows it to be
145 * chosen (by setting RefreshFlag::UseNext). */
146 while (next != nullptr && (!flags.Test(RefreshFlag::UseNext) || next->IsType(OT_CONDITIONAL))) {
147
148 /* After the first step any further non-conditional order is good,
149 * regardless of previous RefreshFlag::UseNext settings. The case of cur and next or
150 * their respective stations being equal is handled elsewhere. */
152
153 if (next->IsType(OT_CONDITIONAL)) {
154 const Order *skip_to = this->vehicle->orders->GetNextDecisionNode(
155 this->vehicle->orders->GetOrderAt(next->GetConditionSkipToOrder()), num_hops);
156 if (skip_to != nullptr && num_hops < this->vehicle->orders->GetNumOrders()) {
157 /* Make copies of capacity tracking lists. There is potential
158 * for optimization here: If the vehicle never refits we don't
159 * need to copy anything. Also, if we've seen the branched link
160 * before we don't need to branch at all. */
161 LinkRefresher branch(*this);
162 branch.RefreshLinks(cur, skip_to, flags, num_hops + 1);
163 }
164 }
165
166 /* Reassign next with the following stop. This can be a station or a
167 * depot.*/
168 next = this->vehicle->orders->GetNextDecisionNode(
169 this->vehicle->orders->GetNext(next), num_hops++);
170 }
171 return next;
172}
173
179void LinkRefresher::RefreshStats(const Order *cur, const Order *next)
180{
181 StationID next_station = next->GetDestination().ToStationID();
182 Station *st = Station::GetIfValid(cur->GetDestination().ToStationID());
183 if (st != nullptr && next_station != StationID::Invalid() && next_station != st->index) {
184 Station *st_to = Station::Get(next_station);
185 for (CargoType cargo = 0; cargo < NUM_CARGO; ++cargo) {
186 /* Refresh the link and give it a minimum capacity. */
187
188 uint cargo_quantity = this->capacities[cargo];
189 if (cargo_quantity == 0) continue;
190
191 if (this->vehicle->GetDisplayMaxSpeed() == 0) continue;
192
193 /* If not allowed to merge link graphs, make sure the stations are
194 * already in the same link graph. */
195 if (!this->allow_merge && st->goods[cargo].link_graph != st_to->goods[cargo].link_graph) {
196 continue;
197 }
198
199 /* A link is at least partly restricted if a vehicle can't load at its source. */
200 EdgeUpdateMode restricted_mode = (cur->GetLoadType() & OLFB_NO_LOAD) == 0 ?
202 /* This estimates the travel time of the link as the time needed
203 * to travel between the stations at half the max speed of the consist.
204 * The result is in tiles/tick (= 2048 km-ish/h). */
205 uint32_t time_estimate = DistanceManhattan(st->xy, st_to->xy) * 4096U / this->vehicle->GetDisplayMaxSpeed();
206
207 /* If the vehicle is currently full loading, increase the capacities at the station
208 * where it is loading by an estimate of what it would have transported if it wasn't
209 * loading. Don't do that if the vehicle has been waiting for longer than the entire
210 * order list is supposed to take, though. If that is the case the total duration is
211 * probably far off and we'd greatly overestimate the capacity by increasing.*/
212 if (this->is_full_loading && this->vehicle->orders != nullptr &&
214 this->vehicle->orders->GetTotalDuration() > this->vehicle->current_order_time) {
215 uint effective_capacity = cargo_quantity * this->vehicle->load_unload_ticks;
216 if (effective_capacity > (uint)this->vehicle->orders->GetTotalDuration()) {
217 IncreaseStats(st, cargo, next_station, effective_capacity /
218 this->vehicle->orders->GetTotalDuration(), 0, 0,
219 {EdgeUpdateMode::Increase, restricted_mode});
220 } else if (RandomRange(this->vehicle->orders->GetTotalDuration()) < effective_capacity) {
221 IncreaseStats(st, cargo, next_station, 1, 0, 0, {EdgeUpdateMode::Increase, restricted_mode});
222 } else {
223 IncreaseStats(st, cargo, next_station, cargo_quantity, 0, time_estimate, {EdgeUpdateMode::Refresh, restricted_mode});
224 }
225 } else {
226 IncreaseStats(st, cargo, next_station, cargo_quantity, 0, time_estimate, {EdgeUpdateMode::Refresh, restricted_mode});
227 }
228 }
229 }
230}
231
243void LinkRefresher::RefreshLinks(const Order *cur, const Order *next, RefreshFlags flags, uint num_hops)
244{
245 while (next != nullptr) {
246
247 if ((next->IsType(OT_GOTO_DEPOT) || next->IsType(OT_GOTO_STATION)) && next->IsRefit()) {
249 if (!next->IsAutoRefit()) {
250 this->HandleRefit(next->GetRefitCargo());
251 } else if (!flags.Test(RefreshFlag::InAutorefit)) {
253 LinkRefresher backup(*this);
254 for (CargoType cargo = 0; cargo != NUM_CARGO; ++cargo) {
255 if (CargoSpec::Get(cargo)->IsValid() && this->HandleRefit(cargo)) {
256 this->RefreshLinks(cur, next, flags, num_hops);
257 *this = backup;
258 }
259 }
260 }
261 }
262
263 /* Only reset the refit capacities if the "previous" next is a station,
264 * meaning that either the vehicle was refit at the previous station or
265 * it wasn't at all refit during the current hop. */
266 if (flags.Test(RefreshFlag::WasRefit) && (next->IsType(OT_GOTO_STATION) || next->IsType(OT_IMPLICIT))) {
268 } else {
270 }
271
272 next = this->PredictNextOrder(cur, next, flags, num_hops);
273 if (next == nullptr) break;
274 Hop hop(cur->index, next->index, this->cargo);
275 if (this->seen_hops->find(hop) != this->seen_hops->end()) {
276 break;
277 } else {
278 this->seen_hops->insert(hop);
279 }
280
281 /* Don't use the same order again, but choose a new one in the next round. */
283
284 /* Skip resetting and link refreshing if next order won't do anything with cargo. */
285 if (!next->IsType(OT_GOTO_STATION) && !next->IsType(OT_IMPLICIT)) continue;
286
287 if (flags.Test(RefreshFlag::ResetRefit)) {
288 this->ResetRefit();
290 }
291
292 if (cur->IsType(OT_GOTO_STATION) || cur->IsType(OT_IMPLICIT)) {
295 this->RefreshStats(cur, next);
296 } else {
298 }
299 }
300
301 /* "cur" is only assigned here if the stop is a station so that
302 * whenever stats are to be increased two stations can be found. */
303 cur = next;
304 }
305}
debug_inline constexpr bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
uint8_t CargoType
Cargo slots to indicate a cargo type within a game.
Definition cargo_type.h:23
static const CargoType NUM_CARGO
Maximum number of cargo types in a game.
Definition cargo_type.h:75
constexpr bool Test(Tvalue_type value) const
Test if the value-th bit is set.
constexpr Timpl & Set()
Set all bits.
constexpr Timpl & Reset(Tvalue_type value)
Reset the value-th bit.
Enum-as-bit-set wrapper.
Utility to refresh links a consist will visit.
Definition refresh.h:19
bool allow_merge
If the refresher is allowed to merge or extend link graphs.
Definition refresh.h:88
void ResetRefit()
Restore capacities and refit_capacities as vehicle might have been able to load now.
Definition refresh.cpp:123
bool HandleRefit(CargoType refit_cargo)
Handle refit orders by updating capacities and refit_capacities.
Definition refresh.cpp:68
void RefreshLinks(const Order *cur, const Order *next, RefreshFlags flags, uint num_hops=0)
Iterate over orders starting at cur and next and refresh links associated with them.
Definition refresh.cpp:243
Vehicle * vehicle
Vehicle for which the links should be refreshed.
Definition refresh.h:83
@ UseNext
There was a conditional jump. Try to use the given next order when looking for a new one.
@ ResetRefit
Consist had a chance to load since the last refit and the refit capacities can be reset.
@ WasRefit
Consist was refit since the last stop where it could interact with cargo.
@ HasCargo
Consist could leave the last stop where it could interact with cargo carrying cargo (i....
@ InAutorefit
Currently doing an autorefit loop. Ignore the first autorefit order.
RefitList refit_capacities
Current state of capacity remaining from previous refits versus overall capacity per vehicle in the c...
Definition refresh.h:85
LinkRefresher(Vehicle *v, HopSet *seen_hops, bool allow_merge, bool is_full_loading)
Constructor for link refreshing algorithm.
Definition refresh.cpp:49
const Order * PredictNextOrder(const Order *cur, const Order *next, RefreshFlags flags, uint num_hops=0)
Predict the next order the vehicle will execute and resolve conditionals by recursion and return next...
Definition refresh.cpp:141
CargoType cargo
Cargo given in last refit order.
Definition refresh.h:87
CargoArray capacities
Current added capacities per cargo type in the consist.
Definition refresh.h:84
HopSet * seen_hops
Hops already seen. If the same hop is seen twice we stop the algorithm. This is shared between all Re...
Definition refresh.h:86
bool is_full_loading
If the vehicle is full loading.
Definition refresh.h:89
static void Run(Vehicle *v, bool allow_merge=true, bool is_full_loading=false)
Refresh all links the given vehicle will visit.
Definition refresh.cpp:26
void RefreshStats(const Order *cur, const Order *next)
Refresh link stats for the given pair of orders.
Definition refresh.cpp:179
Declaration of link graph classes used for cargo distribution.
EdgeUpdateMode
Special modes for updating links.
@ Refresh
Refresh capacity.
@ Unrestricted
Use unrestricted link.
@ Increase
Increase capacity.
@ Restricted
Use restricted link.
uint DistanceManhattan(TileIndex t0, TileIndex t1)
Gets the Manhattan distance between the two given tiles.
Definition map.cpp:142
@ OLFB_NO_LOAD
Do not load anything.
Definition order_type.h:82
uint32_t RandomRange(uint32_t limit, const std::source_location location=std::source_location::current())
Pick a random number between 0 and limit - 1, inclusive.
Definition of link refreshing utility.
void IncreaseStats(Station *st, CargoType cargo, StationID next_station_id, uint capacity, uint usage, uint32_t time, EdgeUpdateModes modes)
Increase capacity for a link stat given by station cargo and next hop.
VehicleOrderID cur_implicit_order_index
The index to the current implicit order.
TileIndex xy
Base tile of the station.
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo type.
Definition cargotype.h:137
uint DetermineCapacity(const Vehicle *v, uint16_t *mail_capacity=nullptr) const
Determines capacity of a given vehicle from scratch.
Definition engine.cpp:201
A hop the refresh algorithm might evaluate.
Definition refresh.h:58
Simulated cargo type and capacity for prediction of future links.
Definition refresh.h:41
const Order * GetNextDecisionNode(const Order *next, uint hops) const
Get the next order which will make the given vehicle stop at a station or refit at a depot or evaluat...
Order * GetOrderAt(int index) const
Get a certain order of the order chain.
const Order * GetNext(const Order *curr) const
Get the order after the given one or the first one, if the given one is the last one.
Definition order_base.h:310
VehicleOrderID GetNumOrders() const
Get number of orders in the order list.
Definition order_base.h:316
TimerGameTick::Ticks GetTotalDuration() const
Gets the known duration of the vehicles orders, timetabled or not.
Definition order_base.h:377
DestinationID GetDestination() const
Gets the destination of this order.
Definition order_base.h:103
bool IsType(OrderType type) const
Check whether this order is of the given type.
Definition order_base.h:70
VehicleOrderID GetConditionSkipToOrder() const
Get the order to skip to.
Definition order_base.h:152
CargoType GetRefitCargo() const
Get the cargo to to refit to.
Definition order_base.h:131
OrderLoadFlags GetLoadType() const
How must the consist be loaded?
Definition order_base.h:136
bool CanLeaveWithCargo(bool has_cargo) const
A vehicle can leave the current station with cargo if:
bool IsAutoRefit() const
Is this order a auto-refit order.
Definition order_base.h:124
bool IsRefit() const
Is this order a refit order.
Definition order_base.h:117
static Titem * Get(auto index)
Returns Titem with given index.
Tindex index
Index of this pool item.
static Station * Get(auto index)
Gets station with given index.
static Station * GetIfValid(auto index)
Returns station if the index is a valid index for this station type.
Station data structure.
std::array< GoodsEntry, NUM_CARGO > goods
Goods at this station.
Vehicle data structure.
Order * GetOrder(int index) const
Returns order 'index' of a vehicle or nullptr when it doesn't exists.
StationID last_loading_station
Last station the vehicle has stopped at and could possibly leave from with any cargo loaded.
virtual int GetDisplayMaxSpeed() const
Gets the maximum speed in km-ish/h that can be sent into string parameters for string processing.
Vehicle * Next() const
Get the next vehicle of this vehicle.
OrderList * orders
Pointer to the order list for this vehicle.
uint16_t load_unload_ticks
Ticks to wait before starting next cycle.
StationID last_station_visited
The last station we stopped at.
uint8_t GetBestFittingSubType(Vehicle *v_from, Vehicle *v_for, CargoType dest_cargo_type)
Get the best fitting subtype when 'cloning'/'replacing' v_from with v_for.
@ VEH_AIRCRAFT
Aircraft vehicle type.