Fix #8316: Make sort industries by production and transported with a cargo filter...
[openttd-github.git] / src / linkgraph / refresh.cpp
blob430e2907276ae3a69bd9b8c1125e18f78bab6f11
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 */
8 /** @file refresh.h Definition of link refreshing utility. */
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"
18 #include "../safeguards.h"
20 /**
21 * Refresh all links the given vehicle will visit.
22 * @param v Vehicle to refresh links for.
23 * @param allow_merge If the refresher is allowed to merge or extend link graphs.
24 * @param is_full_loading If the vehicle is full loading.
26 /* static */ void LinkRefresher::Run(Vehicle *v, bool allow_merge, bool is_full_loading)
28 /* If there are no orders we can't predict anything.*/
29 if (v->orders.list == nullptr) return;
31 /* Make sure the first order is a useful order. */
32 const Order *first = v->orders.list->GetNextDecisionNode(v->GetOrder(v->cur_implicit_order_index), 0);
33 if (first == nullptr) return;
35 HopSet seen_hops;
36 LinkRefresher refresher(v, &seen_hops, allow_merge, is_full_loading);
38 refresher.RefreshLinks(first, first, v->last_loading_station != INVALID_STATION ? 1 << HAS_CARGO : 0);
41 /**
42 * Comparison operator to allow hops to be used in a std::set.
43 * @param other Other hop to be compared with.
44 * @return If this hop is "smaller" than the other (defined by from, to and cargo in this order).
46 bool LinkRefresher::Hop::operator<(const Hop &other) const
48 if (this->from < other.from) {
49 return true;
50 } else if (this->from > other.from) {
51 return false;
53 if (this->to < other.to) {
54 return true;
55 } else if (this->to > other.to) {
56 return false;
58 return this->cargo < other.cargo;
61 /**
62 * Constructor for link refreshing algorithm.
63 * @param vehicle Vehicle to refresh links for.
64 * @param seen_hops Set of hops already seen. This is shared between this
65 * refresher and all its children.
66 * @param allow_merge If the refresher is allowed to merge or extend link graphs.
67 * @param is_full_loading If the vehicle is full loading.
69 LinkRefresher::LinkRefresher(Vehicle *vehicle, HopSet *seen_hops, bool allow_merge, bool is_full_loading) :
70 vehicle(vehicle), seen_hops(seen_hops), cargo(CT_INVALID), allow_merge(allow_merge),
71 is_full_loading(is_full_loading)
73 memset(this->capacities, 0, sizeof(this->capacities));
75 /* Assemble list of capacities and set last loading stations to 0. */
76 for (Vehicle *v = this->vehicle; v != nullptr; v = v->Next()) {
77 this->refit_capacities.push_back(RefitDesc(v->cargo_type, v->cargo_cap, v->refit_cap));
78 if (v->refit_cap > 0) {
79 assert(v->cargo_type < NUM_CARGO);
80 this->capacities[v->cargo_type] += v->refit_cap;
85 /**
86 * Handle refit orders by updating capacities and refit_capacities.
87 * @param refit_cargo Cargo to refit to.
88 * @return True if any vehicle was refit; false if none was.
90 bool LinkRefresher::HandleRefit(CargoID refit_cargo)
92 this->cargo = refit_cargo;
93 RefitList::iterator refit_it = this->refit_capacities.begin();
94 bool any_refit = false;
95 for (Vehicle *v = this->vehicle; v != nullptr; v = v->Next()) {
96 const Engine *e = Engine::Get(v->engine_type);
97 if (!HasBit(e->info.refit_mask, this->cargo)) {
98 ++refit_it;
99 continue;
101 any_refit = true;
103 /* Back up the vehicle's cargo type */
104 CargoID temp_cid = v->cargo_type;
105 byte temp_subtype = v->cargo_subtype;
106 v->cargo_type = this->cargo;
107 v->cargo_subtype = GetBestFittingSubType(v, v, this->cargo);
109 uint16 mail_capacity = 0;
110 uint amount = e->DetermineCapacity(v, &mail_capacity);
112 /* Restore the original cargo type */
113 v->cargo_type = temp_cid;
114 v->cargo_subtype = temp_subtype;
116 /* Skip on next refit. */
117 if (this->cargo != refit_it->cargo && refit_it->remaining > 0) {
118 this->capacities[refit_it->cargo] -= refit_it->remaining;
119 refit_it->remaining = 0;
120 } else if (amount < refit_it->remaining) {
121 this->capacities[refit_it->cargo] -= refit_it->remaining - amount;
122 refit_it->remaining = amount;
124 refit_it->capacity = amount;
125 refit_it->cargo = this->cargo;
127 ++refit_it;
129 /* Special case for aircraft with mail. */
130 if (v->type == VEH_AIRCRAFT) {
131 if (mail_capacity < refit_it->remaining) {
132 this->capacities[refit_it->cargo] -= refit_it->remaining - mail_capacity;
133 refit_it->remaining = mail_capacity;
135 refit_it->capacity = mail_capacity;
136 break; // aircraft have only one vehicle
139 return any_refit;
143 * Restore capacities and refit_capacities as vehicle might have been able to load now.
145 void LinkRefresher::ResetRefit()
147 for (RefitList::iterator it(this->refit_capacities.begin()); it != this->refit_capacities.end(); ++it) {
148 if (it->remaining == it->capacity) continue;
149 this->capacities[it->cargo] += it->capacity - it->remaining;
150 it->remaining = it->capacity;
155 * Predict the next order the vehicle will execute and resolve conditionals by
156 * recursion and return next non-conditional order in list.
157 * @param cur Current order being evaluated.
158 * @param next Next order to be evaluated.
159 * @param flags RefreshFlags to give hints about the previous link and state carried over from that.
160 * @param num_hops Number of hops already taken by recursive calls to this method.
161 * @return new next Order.
163 const Order *LinkRefresher::PredictNextOrder(const Order *cur, const Order *next, uint8 flags, uint num_hops)
165 /* next is good if it's either nullptr (then the caller will stop the
166 * evaluation) or if it's not conditional and the caller allows it to be
167 * chosen (by setting USE_NEXT). */
168 while (next != nullptr && (!HasBit(flags, USE_NEXT) || next->IsType(OT_CONDITIONAL))) {
170 /* After the first step any further non-conditional order is good,
171 * regardless of previous USE_NEXT settings. The case of cur and next or
172 * their respective stations being equal is handled elsewhere. */
173 SetBit(flags, USE_NEXT);
175 if (next->IsType(OT_CONDITIONAL)) {
176 const Order *skip_to = this->vehicle->orders.list->GetNextDecisionNode(
177 this->vehicle->orders.list->GetOrderAt(next->GetConditionSkipToOrder()), num_hops);
178 if (skip_to != nullptr && num_hops < this->vehicle->orders.list->GetNumOrders()) {
179 /* Make copies of capacity tracking lists. There is potential
180 * for optimization here: If the vehicle never refits we don't
181 * need to copy anything. Also, if we've seen the branched link
182 * before we don't need to branch at all. */
183 LinkRefresher branch(*this);
184 branch.RefreshLinks(cur, skip_to, flags, num_hops + 1);
188 /* Reassign next with the following stop. This can be a station or a
189 * depot.*/
190 next = this->vehicle->orders.list->GetNextDecisionNode(
191 this->vehicle->orders.list->GetNext(next), num_hops++);
193 return next;
197 * Refresh link stats for the given pair of orders.
198 * @param cur Last stop where the consist could interact with cargo.
199 * @param next Next order to be processed.
201 void LinkRefresher::RefreshStats(const Order *cur, const Order *next)
203 StationID next_station = next->GetDestination();
204 Station *st = Station::GetIfValid(cur->GetDestination());
205 if (st != nullptr && next_station != INVALID_STATION && next_station != st->index) {
206 for (CargoID c = 0; c < NUM_CARGO; c++) {
207 /* Refresh the link and give it a minimum capacity. */
209 uint cargo_quantity = this->capacities[c];
210 if (cargo_quantity == 0) continue;
212 /* If not allowed to merge link graphs, make sure the stations are
213 * already in the same link graph. */
214 if (!this->allow_merge && st->goods[c].link_graph != Station::Get(next_station)->goods[c].link_graph) {
215 continue;
218 /* A link is at least partly restricted if a vehicle can't load at its source. */
219 EdgeUpdateMode restricted_mode = (cur->GetLoadType() & OLFB_NO_LOAD) == 0 ?
220 EUM_UNRESTRICTED : EUM_RESTRICTED;
222 /* If the vehicle is currently full loading, increase the capacities at the station
223 * where it is loading by an estimate of what it would have transported if it wasn't
224 * loading. Don't do that if the vehicle has been waiting for longer than the entire
225 * order list is supposed to take, though. If that is the case the total duration is
226 * probably far off and we'd greatly overestimate the capacity by increasing.*/
227 if (this->is_full_loading && this->vehicle->orders.list != nullptr &&
228 st->index == vehicle->last_station_visited &&
229 this->vehicle->orders.list->GetTotalDuration() >
230 (Ticks)this->vehicle->current_order_time) {
231 uint effective_capacity = cargo_quantity * this->vehicle->load_unload_ticks;
232 if (effective_capacity > (uint)this->vehicle->orders.list->GetTotalDuration()) {
233 IncreaseStats(st, c, next_station, effective_capacity /
234 this->vehicle->orders.list->GetTotalDuration(), 0,
235 EUM_INCREASE | restricted_mode);
236 } else if (RandomRange(this->vehicle->orders.list->GetTotalDuration()) < effective_capacity) {
237 IncreaseStats(st, c, next_station, 1, 0, EUM_INCREASE | restricted_mode);
238 } else {
239 IncreaseStats(st, c, next_station, cargo_quantity, 0, EUM_REFRESH | restricted_mode);
241 } else {
242 IncreaseStats(st, c, next_station, cargo_quantity, 0, EUM_REFRESH | restricted_mode);
249 * Iterate over orders starting at \a cur and \a next and refresh links
250 * associated with them. \a cur and \a next can be equal. If they're not they
251 * must be "neighbours" in their order list, which means \a next must be directly
252 * reachable from \a cur without passing any further OT_GOTO_STATION or
253 * OT_IMPLICIT orders in between.
254 * @param cur Current order being evaluated.
255 * @param next Next order to be checked.
256 * @param flags RefreshFlags to give hints about the previous link and state carried over from that.
257 * @param num_hops Number of hops already taken by recursive calls to this method.
259 void LinkRefresher::RefreshLinks(const Order *cur, const Order *next, uint8 flags, uint num_hops)
261 while (next != nullptr) {
263 if ((next->IsType(OT_GOTO_DEPOT) || next->IsType(OT_GOTO_STATION)) && next->IsRefit()) {
264 SetBit(flags, WAS_REFIT);
265 if (!next->IsAutoRefit()) {
266 this->HandleRefit(next->GetRefitCargo());
267 } else if (!HasBit(flags, IN_AUTOREFIT)) {
268 SetBit(flags, IN_AUTOREFIT);
269 LinkRefresher backup(*this);
270 for (CargoID c = 0; c != NUM_CARGO; ++c) {
271 if (CargoSpec::Get(c)->IsValid() && this->HandleRefit(c)) {
272 this->RefreshLinks(cur, next, flags, num_hops);
273 *this = backup;
279 /* Only reset the refit capacities if the "previous" next is a station,
280 * meaning that either the vehicle was refit at the previous station or
281 * it wasn't at all refit during the current hop. */
282 if (HasBit(flags, WAS_REFIT) && (next->IsType(OT_GOTO_STATION) || next->IsType(OT_IMPLICIT))) {
283 SetBit(flags, RESET_REFIT);
284 } else {
285 ClrBit(flags, RESET_REFIT);
288 next = this->PredictNextOrder(cur, next, flags, num_hops);
289 if (next == nullptr) break;
290 Hop hop(cur->index, next->index, this->cargo);
291 if (this->seen_hops->find(hop) != this->seen_hops->end()) {
292 break;
293 } else {
294 this->seen_hops->insert(hop);
297 /* Don't use the same order again, but choose a new one in the next round. */
298 ClrBit(flags, USE_NEXT);
300 /* Skip resetting and link refreshing if next order won't do anything with cargo. */
301 if (!next->IsType(OT_GOTO_STATION) && !next->IsType(OT_IMPLICIT)) continue;
303 if (HasBit(flags, RESET_REFIT)) {
304 this->ResetRefit();
305 ClrBit(flags, RESET_REFIT);
306 ClrBit(flags, WAS_REFIT);
309 if (cur->IsType(OT_GOTO_STATION) || cur->IsType(OT_IMPLICIT)) {
310 if (cur->CanLeaveWithCargo(HasBit(flags, HAS_CARGO))) {
311 SetBit(flags, HAS_CARGO);
312 this->RefreshStats(cur, next);
313 } else {
314 ClrBit(flags, HAS_CARGO);
318 /* "cur" is only assigned here if the stop is a station so that
319 * whenever stats are to be increased two stations can be found. */
320 cur = next;