Fix crash when setting separation mode for vehicles with no orders list.
[openttd-joker.git] / src / order_cmd.cpp
bloba8ad54a119c9a60d2fda955466789c818914906c
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 order_cmd.cpp Handling of orders. */
12 #include "stdafx.h"
13 #include "debug.h"
14 #include "cmd_helper.h"
15 #include "command_func.h"
16 #include "company_func.h"
17 #include "news_func.h"
18 #include "strings_func.h"
19 #include "timetable.h"
20 #include "station_base.h"
21 #include "station_map.h"
22 #include "station_func.h"
23 #include "map_func.h"
24 #include "cargotype.h"
25 #include "vehicle_func.h"
26 #include "depot_base.h"
27 #include "core/bitmath_func.hpp"
28 #include "core/pool_func.hpp"
29 #include "core/random_func.hpp"
30 #include "aircraft.h"
31 #include "roadveh.h"
32 #include "station_base.h"
33 #include "waypoint_base.h"
34 #include "company_base.h"
35 #include "order_backup.h"
36 #include "cheat_type.h"
37 #include "viewport_func.h"
38 #include "tracerestrict.h"
40 #include "table/strings.h"
42 #include "safeguards.h"
44 /* DestinationID must be at least as large as every these below, because it can
45 * be any of them
47 assert_compile(sizeof(DestinationID) >= sizeof(DepotID));
48 assert_compile(sizeof(DestinationID) >= sizeof(StationID));
50 OrderPool _order_pool("Order");
51 INSTANTIATE_POOL_METHODS(Order)
52 OrderListPool _orderlist_pool("OrderList");
53 INSTANTIATE_POOL_METHODS(OrderList)
55 /** Clean everything up. */
56 Order::~Order()
58 if (CleaningPool()) return;
60 /* We can visit oil rigs and buoys that are not our own. They will be shown in
61 * the list of stations. So, we need to invalidate that window if needed. */
62 if (this->IsType(OT_GOTO_STATION) || this->IsType(OT_GOTO_WAYPOINT)) {
63 BaseStation *bs = BaseStation::GetIfValid(this->GetDestination());
64 if (bs != nullptr && bs->owner == OWNER_NONE) InvalidateWindowClassesData(WC_STATION_LIST, 0);
68 /**
69 * 'Free' the order
70 * @note ONLY use on "current_order" vehicle orders!
72 void Order::Free()
74 this->type = OT_NOTHING;
75 this->flags = 0;
76 this->dest = 0;
77 this->next = nullptr;
78 DeAllocExtraInfo();
81 /**
82 * Makes this order a Go To Station order.
83 * @param destination the station to go to.
85 void Order::MakeGoToStation(StationID destination)
87 this->type = OT_GOTO_STATION;
88 this->flags = 0;
89 this->dest = destination;
92 /**
93 * Makes this order a Go To Depot order.
94 * @param destination the depot to go to.
95 * @param order is this order a 'default' order, or an overridden vehicle order?
96 * @param non_stop_type how to get to the depot?
97 * @param action what to do in the depot?
98 * @param cargo the cargo type to change to.
100 void Order::MakeGoToDepot(DepotID destination, OrderDepotTypeFlags order, OrderNonStopFlags non_stop_type, OrderDepotActionFlags action, CargoID cargo)
102 this->type = OT_GOTO_DEPOT;
103 this->SetDepotOrderType(order);
104 this->SetDepotActionType(action);
105 this->SetNonStopType(non_stop_type);
106 this->dest = destination;
107 this->SetRefit(cargo);
111 * Makes this order a Go To Waypoint order.
112 * @param destination the waypoint to go to.
114 void Order::MakeGoToWaypoint(StationID destination)
116 this->type = OT_GOTO_WAYPOINT;
117 this->flags = 0;
118 this->dest = destination;
122 * Makes this order a Loading order.
123 * @param ordered is this an ordered stop?
125 void Order::MakeLoading(bool ordered)
127 this->type = OT_LOADING;
128 if (!ordered) this->flags = 0;
131 bool Order::UpdateJumpCounter(byte percent)
133 if(this->jump_counter >= 0) {
134 this->jump_counter += (percent - 100);
135 return true;
137 this->jump_counter += percent;
138 return false;
142 * Makes this order a Leave Station order.
144 void Order::MakeLeaveStation()
146 this->type = OT_LEAVESTATION;
147 this->flags = 0;
151 * Makes this order a Dummy order.
153 void Order::MakeDummy()
155 this->type = OT_DUMMY;
156 this->flags = 0;
160 * Makes this order an conditional order.
161 * @param order the order to jump to.
163 void Order::MakeConditional(VehicleOrderID order)
165 this->type = OT_CONDITIONAL;
166 this->flags = order;
167 this->dest = 0;
171 * Makes this order an implicit order.
172 * @param destination the station to go to.
174 void Order::MakeImplicit(StationID destination)
176 this->type = OT_IMPLICIT;
177 this->dest = destination;
180 void Order::MakeWaiting()
182 this->type = OT_WAITING;
186 * Make this depot/station order also a refit order.
187 * @param cargo the cargo type to change to.
188 * @pre IsType(OT_GOTO_DEPOT) || IsType(OT_GOTO_STATION).
190 void Order::SetRefit(CargoID cargo)
192 this->refit_cargo = cargo;
196 * Does this order have the same type, flags and destination?
197 * @param other the second order to compare to.
198 * @return true if the type, flags and destination match.
200 bool Order::Equals(const Order &other) const
202 /* In case of go to nearest depot orders we need "only" compare the flags
203 * with the other and not the nearest depot order bit or the actual
204 * destination because those get clear/filled in during the order
205 * evaluation. If we do not do this the order will continuously be seen as
206 * a different order and it will try to find a "nearest depot" every tick. */
207 if ((this->IsType(OT_GOTO_DEPOT) && this->type == other.type) &&
208 ((this->GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0 ||
209 (other.GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0)) {
210 return this->GetDepotOrderType() == other.GetDepotOrderType() &&
211 (this->GetDepotActionType() & ~ODATFB_NEAREST_DEPOT) == (other.GetDepotActionType() & ~ODATFB_NEAREST_DEPOT);
214 return this->type == other.type && this->flags == other.flags && this->dest == other.dest;
218 * Pack this order into a 32 bits integer, or actually only
219 * the type, flags and destination.
220 * @return the packed representation.
221 * @note unpacking is done in the constructor.
223 uint32 Order::Pack() const
225 return this->dest << 16 | this->flags << 8 | this->type;
229 * Pack this order into a 16 bits integer as close to the TTD
230 * representation as possible.
231 * @return the TTD-like packed representation.
233 uint16 Order::MapOldOrder() const
235 uint16 order = this->GetType();
236 switch (this->type) {
237 case OT_GOTO_STATION:
238 if (this->GetUnloadType() & OUFB_UNLOAD) SetBit(order, 5);
239 if (this->GetLoadType() & OLFB_FULL_LOAD) SetBit(order, 6);
240 if (this->GetNonStopType() & ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS) SetBit(order, 7);
241 order |= GB(this->GetDestination(), 0, 8) << 8;
242 break;
243 case OT_GOTO_DEPOT:
244 if (!(this->GetDepotOrderType() & ODTFB_PART_OF_ORDERS)) SetBit(order, 6);
245 SetBit(order, 7);
246 order |= GB(this->GetDestination(), 0, 8) << 8;
247 break;
248 case OT_LOADING:
249 if (this->GetLoadType() & OLFB_FULL_LOAD) SetBit(order, 6);
250 break;
252 return order;
256 * Create an order based on a packed representation of that order.
257 * @param packed the packed representation.
259 Order::Order(uint32 packed)
261 this->type = (OrderType)GB(packed, 0, 8);
262 this->flags = GB(packed, 8, 8);
263 this->dest = GB(packed, 16, 16);
264 this->extra = nullptr;
265 this->next = nullptr;
266 this->refit_cargo = CT_NO_REFIT;
267 this->wait_time = 0;
268 this->travel_time = 0;
269 this->jump_counter = 0;
270 this->max_speed = UINT16_MAX;
275 * Updates the widgets of a vehicle which contains the order-data
278 void InvalidateVehicleOrder(const Vehicle *v, int data)
280 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
282 if (data != 0) {
283 /* Calls SetDirty() too */
284 InvalidateWindowData(WC_VEHICLE_ORDERS, v->index, data);
285 InvalidateWindowData(WC_VEHICLE_TIMETABLE, v->index, data);
286 InvalidateWindowData(WC_VEHICLE_TRIP_HISTORY, v->index, data);
287 return;
290 SetWindowDirty(WC_VEHICLE_ORDERS, v->index);
291 SetWindowDirty(WC_VEHICLE_TIMETABLE, v->index);
292 SetWindowDirty(WC_VEHICLE_TRIP_HISTORY, v->index);
297 * Assign data to an order (from another order)
298 * This function makes sure that the index is maintained correctly
299 * @param other the data to copy (except next pointer).
302 void Order::AssignOrder(const Order &other)
304 this->type = other.type;
305 this->flags = other.flags;
306 this->dest = other.dest;
308 this->refit_cargo = other.refit_cargo;
310 this->wait_time = other.wait_time;
311 this->jump_counter = other.jump_counter;
312 this->travel_time = other.travel_time;
313 this->max_speed = other.max_speed;
315 if ((this->GetUnloadType() == OUFB_CARGO_TYPE_UNLOAD || this->GetLoadType() == OLFB_CARGO_TYPE_LOAD) && other.extra != nullptr) {
316 this->AllocExtraInfo();
317 *(this->extra) = *(other.extra);
318 } else {
319 this->DeAllocExtraInfo();
323 void Order::AllocExtraInfo()
325 if (!this->extra) {
326 this->extra.reset(new OrderExtraInfo());
330 void Order::DeAllocExtraInfo()
332 this->extra.reset();
335 void CargoStationIDStackSet::FillNextStoppingStation(const Vehicle *v, const OrderList *o, const Order *first, uint hops)
337 this->more.clear();
338 this->first = o->GetNextStoppingStation(v, ~0, first, hops);
339 if (this->first.cargo_mask != (uint32) ~0) {
340 uint32 have_cargoes = this->first.cargo_mask;
341 do {
342 this->more.push_back(o->GetNextStoppingStation(v, ~have_cargoes, first, hops));
343 have_cargoes |= this->more.back().cargo_mask;
344 } while (have_cargoes != (uint32) ~0);
349 * Recomputes everything.
350 * @param chain first order in the chain
351 * @param v one of vehicle that is using this orderlist
353 void OrderList::Initialize(Order *chain, Vehicle *v)
355 this->first = chain;
356 this->first_shared = v;
358 this->num_orders = 0;
359 this->num_manual_orders = 0;
360 this->num_vehicles = 1;
361 this->timetable_duration = 0;
362 this->total_duration = 0;
364 for (Order *o = this->first; o != nullptr; o = o->next) {
365 ++this->num_orders;
366 if (!o->IsType(OT_IMPLICIT)) ++this->num_manual_orders;
367 if (!o->IsType(OT_CONDITIONAL)) {
368 this->timetable_duration += o->GetTimetabledWait() + o->GetTimetabledTravel();
369 this->total_duration += o->GetWaitTime() + o->GetTravelTime();
373 for (Vehicle *u = this->first_shared->PreviousShared(); u != nullptr; u = u->PreviousShared()) {
374 ++this->num_vehicles;
375 this->first_shared = u;
378 for (const Vehicle *u = v->NextShared(); u != nullptr; u = u->NextShared()) ++this->num_vehicles;
382 * Free a complete order chain.
383 * @param keep_orderlist If this is true only delete the orders, otherwise also delete the OrderList.
384 * @note do not use on "current_order" vehicle orders!
386 void OrderList::FreeChain(bool keep_orderlist)
388 Order *next;
389 for (Order *o = this->first; o != nullptr; o = next) {
390 next = o->next;
391 delete o;
394 if (keep_orderlist) {
395 this->first = nullptr;
396 this->num_orders = 0;
397 this->num_manual_orders = 0;
398 this->timetable_duration = 0;
399 } else {
400 delete this;
405 * Get a certain order of the order chain.
406 * @param index zero-based index of the order within the chain.
407 * @return the order at position index.
409 Order *OrderList::GetOrderAt(int index) const
411 if (index < 0) return nullptr;
413 Order *order = this->first;
415 while (order != nullptr && index-- > 0) {
416 order = order->next;
418 return order;
422 * Get the index of an order of the order chain, or INVALID_VEH_ORDER_ID.
423 * @param order order to get the index of.
424 * @return the position index of the given order, or INVALID_VEH_ORDER_ID.
426 VehicleOrderID OrderList::GetIndexOfOrder(const Order *order) const
428 VehicleOrderID index = 0;
429 const Order *o = this->first;
430 while (o != nullptr) {
431 if (o == order) return index;
432 index++;
433 o = o->next;
436 return INVALID_VEH_ORDER_ID;
440 * Get the next order which will make the given vehicle stop at a station
441 * or refit at a depot or evaluate a non-trivial condition.
442 * @param next The order to start looking at.
443 * @param hops The number of orders we have already looked at.
444 * @param cargo_mask The bit set of cargoes that the we are looking at, this may be reduced to indicate the set of cargoes that the result is valid for.
445 * @return Either of
446 * \li a station order
447 * \li a refitting depot order
448 * \li a non-trivial conditional order
449 * \li nullptr if the vehicle won't stop anymore.
451 const Order *OrderList::GetNextDecisionNode(const Order *next, uint hops, uint32 &cargo_mask) const
453 assert(cargo_mask != 0);
455 if (hops > this->GetNumOrders() || next == nullptr) return nullptr;
457 if (next->IsType(OT_CONDITIONAL)) {
458 if (next->GetConditionVariable() != OCV_UNCONDITIONALLY) return next;
460 /* We can evaluate trivial conditions right away. They're conceptually
461 * the same as regular order progression. */
462 return this->GetNextDecisionNode(
463 this->GetOrderAt(next->GetConditionSkipToOrder()),
464 hops + 1, cargo_mask);
467 if (next->IsType(OT_GOTO_DEPOT)) {
468 if (next->GetDepotActionType() & ODATFB_HALT) return nullptr;
469 if (next->IsRefit()) return next;
473 bool can_load_or_unload = false;
474 if ((next->IsType(OT_GOTO_STATION) || next->IsType(OT_IMPLICIT)) &&
475 (next->GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION) == 0) {
476 if (next->GetUnloadType() == OUFB_CARGO_TYPE_UNLOAD || next->GetLoadType() == OLFB_CARGO_TYPE_LOAD) {
477 /* This is a cargo-specific load/unload order.
478 * If the first cargo is both a no-load and no-unload order, skip it.
479 * Drop cargoes which don't match the first one. */
480 can_load_or_unload = CargoMaskValueFilter<bool>(cargo_mask, [&](CargoID cargo) {
481 return ((next->GetCargoLoadType(cargo) & OLFB_NO_LOAD) == 0 || (next->GetCargoUnloadType(cargo) & OUFB_NO_UNLOAD) == 0);
483 } else if ((next->GetLoadType() & OLFB_NO_LOAD) == 0 || (next->GetUnloadType() & OUFB_NO_UNLOAD) == 0) {
484 can_load_or_unload = true;
488 if (!can_load_or_unload) {
489 return this->GetNextDecisionNode(this->GetNext(next), hops + 1, cargo_mask);
492 return next;
496 * Recursively determine the next deterministic station to stop at.
497 * @param v The vehicle we're looking at.
498 * @param uint32 cargo_mask Bit-set of the cargo IDs of interest.
499 * @param first Order to start searching at or nullptr to start at cur_implicit_order_index + 1.
500 * @param hops Number of orders we have already looked at.
501 * @return A CargoMaskedStationIDStack of the cargo mask the result is valid for, and the next stoppping station or INVALID_STATION.
502 * @pre The vehicle is currently loading and v->last_station_visited is meaningful.
503 * @note This function may draw a random number. Don't use it from the GUI.
505 CargoMaskedStationIDStack OrderList::GetNextStoppingStation(const Vehicle *v, uint32 cargo_mask, const Order *first, uint hops) const
507 assert(cargo_mask != 0);
509 const Order *next = first;
510 if (first == nullptr) {
511 next = this->GetOrderAt(v->cur_implicit_order_index);
512 if (next == nullptr) {
513 next = this->GetFirstOrder();
514 if (next == nullptr) return CargoMaskedStationIDStack(cargo_mask, INVALID_STATION);
515 } else {
516 /* GetNext never returns nullptr if there is a valid station in the list.
517 * As the given "next" is already valid and a station in the list, we
518 * don't have to check for nullptr here. */
519 next = this->GetNext(next);
520 assert(next != nullptr);
524 do {
525 next = this->GetNextDecisionNode(next, ++hops, cargo_mask);
527 /* Resolve possibly nested conditionals by estimation. */
528 while (next != nullptr && next->IsType(OT_CONDITIONAL)) {
529 /* We return both options of conditional orders. */
530 const Order *skip_to = this->GetNextDecisionNode(
531 this->GetOrderAt(next->GetConditionSkipToOrder()), hops, cargo_mask);
532 const Order *advance = this->GetNextDecisionNode(
533 this->GetNext(next), hops, cargo_mask);
534 if (advance == nullptr || advance == first || skip_to == advance) {
535 next = (skip_to == first) ? nullptr : skip_to;
536 } else if (skip_to == nullptr || skip_to == first) {
537 next = (advance == first) ? nullptr : advance;
538 } else {
539 CargoMaskedStationIDStack st1 = this->GetNextStoppingStation(v, cargo_mask, skip_to, hops);
540 cargo_mask &= st1.cargo_mask;
541 CargoMaskedStationIDStack st2 = this->GetNextStoppingStation(v, cargo_mask, advance, hops);
542 st1.cargo_mask &= st2.cargo_mask;
543 while (!st2.station.IsEmpty()) st1.station.Push(st2.station.Pop());
544 return st1;
546 ++hops;
549 if (next == nullptr) return CargoMaskedStationIDStack(cargo_mask, INVALID_STATION);
551 /* Don't return a next stop if the vehicle has to unload everything. */
552 if ((next->IsType(OT_GOTO_STATION) || next->IsType(OT_IMPLICIT)) &&
553 next->GetDestination() == v->last_station_visited) {
554 /* This is a cargo-specific load/unload order.
555 * Don't return a next stop if first cargo has transfer or unload set.
556 * Drop cargoes which don't match the first one. */
557 bool invalid = CargoMaskValueFilter<bool>(cargo_mask, [&](CargoID cargo) {
558 return ((next->GetCargoUnloadType(cargo) & (OUFB_TRANSFER | OUFB_UNLOAD)) != 0);
560 if (invalid) return CargoMaskedStationIDStack(cargo_mask, INVALID_STATION);
562 } while (next->IsType(OT_GOTO_DEPOT) || next->GetDestination() == v->last_station_visited);
564 return CargoMaskedStationIDStack(cargo_mask, next->GetDestination());
568 * Insert a new order into the order chain.
569 * @param new_order is the order to insert into the chain.
570 * @param index is the position where the order is supposed to be inserted.
572 void OrderList::InsertOrderAt(Order *new_order, int index)
574 if (this->first == nullptr) {
575 this->first = new_order;
576 } else {
577 if (index == 0) {
578 /* Insert as first or only order */
579 new_order->next = this->first;
580 this->first = new_order;
581 } else if (index >= this->num_orders) {
582 /* index is after the last order, add it to the end */
583 this->GetLastOrder()->next = new_order;
584 } else {
585 /* Put the new order in between */
586 Order *order = this->GetOrderAt(index - 1);
587 new_order->next = order->next;
588 order->next = new_order;
591 ++this->num_orders;
592 if (!new_order->IsType(OT_IMPLICIT)) ++this->num_manual_orders;
593 if (!new_order->IsType(OT_CONDITIONAL)) {
594 this->timetable_duration += new_order->GetTimetabledWait() + new_order->GetTimetabledTravel();
595 this->total_duration += new_order->GetWaitTime() + new_order->GetTravelTime();
598 /* We can visit oil rigs and buoys that are not our own. They will be shown in
599 * the list of stations. So, we need to invalidate that window if needed. */
600 if (new_order->IsType(OT_GOTO_STATION) || new_order->IsType(OT_GOTO_WAYPOINT)) {
601 BaseStation *bs = BaseStation::Get(new_order->GetDestination());
602 if (bs->owner == OWNER_NONE) InvalidateWindowClassesData(WC_STATION_LIST, 0);
609 * Remove an order from the order list and delete it.
610 * @param index is the position of the order which is to be deleted.
612 void OrderList::DeleteOrderAt(int index)
614 if (index >= this->num_orders) return;
616 Order *to_remove;
618 if (index == 0) {
619 to_remove = this->first;
620 this->first = to_remove->next;
621 } else {
622 Order *prev = GetOrderAt(index - 1);
623 to_remove = prev->next;
624 prev->next = to_remove->next;
626 --this->num_orders;
627 if (!to_remove->IsType(OT_IMPLICIT)) --this->num_manual_orders;
628 if (!to_remove->IsType(OT_CONDITIONAL)) {
629 this->timetable_duration -= (to_remove->GetTimetabledWait() + to_remove->GetTimetabledTravel());
630 this->total_duration -= (to_remove->GetWaitTime() + to_remove->GetTravelTime());
632 delete to_remove;
636 * Move an order to another position within the order list.
637 * @param from is the zero-based position of the order to move.
638 * @param to is the zero-based position where the order is moved to.
640 void OrderList::MoveOrder(int from, int to)
642 if (from >= this->num_orders || to >= this->num_orders || from == to) return;
644 Order *moving_one;
646 /* Take the moving order out of the pointer-chain */
647 if (from == 0) {
648 moving_one = this->first;
649 this->first = moving_one->next;
650 } else {
651 Order *one_before = GetOrderAt(from - 1);
652 moving_one = one_before->next;
653 one_before->next = moving_one->next;
656 /* Insert the moving_order again in the pointer-chain */
657 if (to == 0) {
658 moving_one->next = this->first;
659 this->first = moving_one;
660 } else {
661 Order *one_before = GetOrderAt(to - 1);
662 moving_one->next = one_before->next;
663 one_before->next = moving_one;
668 * Removes the vehicle from the shared order list.
669 * @note This is supposed to be called when the vehicle is still in the chain
670 * @param v vehicle to remove from the list
672 void OrderList::RemoveVehicle(Vehicle *v)
674 --this->num_vehicles;
675 if (v == this->first_shared) this->first_shared = v->NextShared();
679 * Checks whether a vehicle is part of the shared vehicle chain.
680 * @param v is the vehicle to search in the shared vehicle chain.
682 bool OrderList::IsVehicleInSharedOrdersList(const Vehicle *v) const
684 for (const Vehicle *v_shared = this->first_shared; v_shared != nullptr; v_shared = v_shared->NextShared()) {
685 if (v_shared == v) return true;
688 return false;
692 * Gets the position of the given vehicle within the shared order vehicle list.
693 * @param v is the vehicle of which to get the position
694 * @return position of v within the shared vehicle chain.
696 int OrderList::GetPositionInSharedOrderList(const Vehicle *v) const
698 int count = 0;
699 for (const Vehicle *v_shared = v->PreviousShared(); v_shared != nullptr; v_shared = v_shared->PreviousShared()) count++;
700 return count;
704 * Checks whether all orders of the list have a filled timetable.
705 * @return whether all orders have a filled timetable.
707 bool OrderList::IsCompleteTimetable() const
709 for (Order *o = this->first; o != nullptr; o = o->next) {
710 /* Implicit orders are, by definition, not timetabled. */
711 if (o->IsType(OT_IMPLICIT)) continue;
712 if (!o->IsCompletelyTimetabled()) return false;
714 return true;
718 * Checks for internal consistency of order list. Triggers assertion if something is wrong.
720 void OrderList::DebugCheckSanity() const
722 VehicleOrderID check_num_orders = 0;
723 VehicleOrderID check_num_manual_orders = 0;
724 uint check_num_vehicles = 0;
725 Ticks check_timetable_duration = 0;
726 Ticks check_total_duration = 0;
728 DEBUG(misc, 6, "Checking OrderList %hu for sanity...", this->index);
730 for (const Order *o = this->first; o != nullptr; o = o->next) {
731 ++check_num_orders;
732 if (!o->IsType(OT_IMPLICIT)) ++check_num_manual_orders;
733 if (!o->IsType(OT_CONDITIONAL)) {
734 check_timetable_duration += o->GetTimetabledWait() + o->GetTimetabledTravel();
735 check_total_duration += o->GetWaitTime() + o->GetTravelTime();
738 assert(this->num_orders == check_num_orders);
739 assert(this->num_manual_orders == check_num_manual_orders);
740 assert(this->timetable_duration == check_timetable_duration);
741 assert(this->total_duration == check_total_duration);
743 for (const Vehicle *v = this->first_shared; v != nullptr; v = v->NextShared()) {
744 ++check_num_vehicles;
745 assert(v->HasSpecificOrderList(this));
747 assert(this->num_vehicles == check_num_vehicles);
748 DEBUG(misc, 6, "... detected %u orders (%u manual), %u vehicles, %i timetabled, %i total",
749 (uint)this->num_orders, (uint)this->num_manual_orders,
750 this->num_vehicles, this->timetable_duration, this->total_duration);
753 /** Returns the number of running (i.e. not stopped) vehicles in the shared orders list. */
754 int OrderList::GetNumRunningVehicles()
756 int num_running_vehicles = 0;
758 for (const Vehicle *v = this->first_shared; v != nullptr; v = v->NextShared()) {
759 if (!(v->vehstatus & (VS_STOPPED | VS_CRASHED)) || v->current_order.IsType(OT_WAITING)) {
760 num_running_vehicles++;
764 return num_running_vehicles;
767 /** (Re-)Initializes Separation if necessary and possible. */
768 void OrderList::InitializeSeparation()
770 // Check whether separation can be used at all
771 if (!this->IsCompleteTimetable() || this->current_sep_mode == TTS_MODE_OFF) {
772 this->is_separation_valid = false;
773 return;
776 // Save current tick count as reference for future timetable start dates and reset the separation counter.
777 this->last_timetable_init = GetCurrentTickCount();
778 this->separation_counter = 0;
780 this->UpdateSeparationTime();
782 this->is_separation_valid = true;
785 void OrderList::UpdateSeparationTime()
787 // Calculate separation amount depending on mode of operation.
788 switch (current_sep_mode) {
789 case TTS_MODE_AUTO: {
790 int num_running_vehicles = this->GetNumRunningVehicles();
791 assert(num_running_vehicles > 0);
793 this->current_separation = this->GetTimetableTotalDuration() / num_running_vehicles;
794 break;
797 case TTS_MODE_MAN_N:
798 this->current_separation = this->GetTimetableTotalDuration() / this->num_sep_vehicles;
799 break;
801 case TTS_MODE_MAN_T:
802 // separation is set manually -> nothing to do
803 break;
805 case TTS_MODE_BUFFERED_AUTO: {
806 int num_running_vehicles = this->GetNumRunningVehicles();
807 assert(num_running_vehicles > 0);
809 if (num_running_vehicles > 1)
810 num_running_vehicles--;
812 this->current_separation = this->GetTimetableTotalDuration() / num_running_vehicles;
813 break;
816 default:
817 NOT_REACHED();
818 break;
823 * Returns the delay setting required for correct separation and increases the separation counter by 1.
824 * @return the delay setting required for correct separation. */
825 Ticks OrderList::SeparateVehicle()
827 if (!this->is_separation_valid || this->current_sep_mode == TTS_MODE_OFF)
828 return INVALID_TICKS;
830 UpdateSeparationTime();
832 Ticks result = GetCurrentTickCount() - (this->separation_counter * this->current_separation + this->last_timetable_init);
833 this->IncreaseSeparationCounter();
834 if (this->separation_counter == UINT16_MAX) {
835 this->MarkSeparationInvalid();
838 return result;
842 * Returns the current separation settings.
843 * @return the current separation settings.
845 TTSepSettings OrderList::GetSepSettings()
847 TTSepSettings result;
849 result.mode = this->current_sep_mode;
850 result.sep_ticks = GetSepTime();
852 // Depending on the operation mode return either the user setting or the true amount of vehicles running the timetable.
853 result.num_veh = (result.mode == TTS_MODE_MAN_N) ? this->num_sep_vehicles : GetNumVehicles();
854 return result;
858 * Prepares command to set new separation settings.
859 * @param s Contains the new settings to be used for separation.
860 * @todo Clean this up (e.g. via union type)
862 void OrderList::SetSepSettings(TTSepSettings s)
864 uint32 p2 = GB<uint32>(s.mode, 0, 3);
865 AB<uint32, uint>(p2, 3, 29, (s.mode == TTS_MODE_MAN_N) ? s.num_veh : s.sep_ticks);
866 DoCommandP(0, this->first_shared->index, p2, CMD_REINIT_SEPARATION);
870 * Sets new separation settings.
871 * @param mode Contains the operation mode that is to be used for separation.
872 * @param parameter Depending on the operation mode this contains either the number of vehicles (#TTS_MODE_MAN_N)
873 * or the time between vehicles in ticks (#TTS_MODE_MAN_T). For other modes, this is undefined.
875 void OrderList::SetSepSettings(TTSepMode mode, uint32 parameter)
877 this->current_sep_mode = mode;
879 switch (this->current_sep_mode)
881 case TTS_MODE_MAN_N:
882 this->current_separation = this->GetTimetableTotalDuration() / parameter;
883 this->num_sep_vehicles = parameter;
884 break;
886 case TTS_MODE_MAN_T:
887 this->current_separation = parameter;
888 this->num_sep_vehicles = this->GetTimetableTotalDuration() / this->current_separation;
889 break;
891 case TTS_MODE_AUTO:
892 case TTS_MODE_BUFFERED_AUTO:
893 case TTS_MODE_OFF:
894 /* nothing to do */
895 break;
897 default:
898 NOT_REACHED();
899 break;
902 this->is_separation_valid = false;
907 * Checks whether the order goes to a station or not, i.e. whether the
908 * destination is a station
909 * @param v the vehicle to check for
910 * @param o the order to check
911 * @return true if the destination is a station
913 static inline bool OrderGoesToStation(const Vehicle *v, const Order *o)
915 return o->IsType(OT_GOTO_STATION) ||
916 (v->type == VEH_AIRCRAFT && o->IsType(OT_GOTO_DEPOT) && !(o->GetDepotActionType() & ODATFB_NEAREST_DEPOT));
920 * Delete all news items regarding defective orders about a vehicle
921 * This could kill still valid warnings (for example about void order when just
922 * another order gets added), but assume the company will notice the problems,
923 * when (s)he's changing the orders.
925 void DeleteOrderWarnings(const Vehicle *v)
927 DeleteVehicleNews(v->index, STR_NEWS_VEHICLE_HAS_TOO_FEW_ORDERS);
928 DeleteVehicleNews(v->index, STR_NEWS_VEHICLE_HAS_VOID_ORDER);
929 DeleteVehicleNews(v->index, STR_NEWS_VEHICLE_HAS_DUPLICATE_ENTRY);
930 DeleteVehicleNews(v->index, STR_NEWS_VEHICLE_HAS_INVALID_ENTRY);
931 DeleteVehicleNews(v->index, STR_NEWS_PLANE_USES_TOO_SHORT_RUNWAY);
935 * Returns a tile somewhat representing the order destination (not suitable for pathfinding).
936 * @param v The vehicle to get the location for.
937 * @param airport Get the airport tile and not the station location for aircraft.
938 * @return destination of order, or INVALID_TILE if none.
940 TileIndex Order::GetLocation(const Vehicle *v, bool airport) const
942 switch (this->GetType()) {
943 case OT_GOTO_WAYPOINT:
944 case OT_GOTO_STATION:
945 case OT_IMPLICIT:
946 if (airport && v->type == VEH_AIRCRAFT) return Station::Get(this->GetDestination())->airport.tile;
947 return BaseStation::Get(this->GetDestination())->xy;
949 case OT_GOTO_DEPOT:
950 if ((this->GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0) return INVALID_TILE;
951 return (v->type == VEH_AIRCRAFT) ? Station::Get(this->GetDestination())->xy : Depot::Get(this->GetDestination())->xy;
953 default:
954 return INVALID_TILE;
959 * Get the distance between two orders of a vehicle. Conditional orders are resolved
960 * and the bigger distance of the two order branches is returned.
961 * @param prev Origin order.
962 * @param cur Destination order.
963 * @param v The vehicle to get the distance for.
964 * @param conditional_depth Internal param for resolving conditional orders.
965 * @return Maximum distance between the two orders.
967 uint GetOrderDistance(const Order *prev, const Order *cur, const Vehicle *v, int conditional_depth)
969 if (cur->IsType(OT_CONDITIONAL)) {
970 if (conditional_depth > v->GetNumOrders()) return 0;
972 conditional_depth++;
974 int dist1 = GetOrderDistance(prev, v->GetOrder(cur->GetConditionSkipToOrder()), v, conditional_depth);
975 int dist2 = GetOrderDistance(prev, cur->next == nullptr ? v->GetFirstOrder() : cur->next, v, conditional_depth);
976 return max(dist1, dist2);
979 TileIndex prev_tile = prev->GetLocation(v, true);
980 TileIndex cur_tile = cur->GetLocation(v, true);
981 if (prev_tile == INVALID_TILE || cur_tile == INVALID_TILE) return 0;
982 return v->type == VEH_AIRCRAFT ? DistanceSquare(prev_tile, cur_tile) : DistanceManhattan(prev_tile, cur_tile);
986 * Add an order to the orderlist of a vehicle.
987 * @param tile unused
988 * @param flags operation to perform
989 * @param p1 various bitstuffed elements
990 * - p1 = (bit 0 - 19) - ID of the vehicle
991 * - p1 = (bit 24 - 31) - the selected order (if any). If the last order is given,
992 * the order will be inserted before that one
993 * the maximum vehicle order id is 254.
994 * @param p2 packed order to insert
995 * @param text unused
996 * @return the cost of this operation or an error
998 CommandCost CmdInsertOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1000 VehicleID veh = GB(p1, 0, 20);
1001 VehicleOrderID sel_ord = GB(p1, 20, 8);
1002 Order new_order(p2);
1004 Vehicle *v = Vehicle::GetIfValid(veh);
1005 if (v == nullptr || !v->IsPrimaryVehicle()) return CommandError();
1007 CommandCost ret = CheckOwnership(v->owner);
1008 if (ret.Failed()) return ret;
1010 /* Check if the inserted order is to the correct destination (owner, type),
1011 * and has the correct flags if any */
1012 switch (new_order.GetType()) {
1013 case OT_GOTO_STATION: {
1014 const Station *st = Station::GetIfValid(new_order.GetDestination());
1015 if (st == nullptr) return CommandError();
1017 if (st->owner != OWNER_NONE) {
1018 CommandCost ret = CheckOwnership(st->owner);
1019 if (ret.Failed()) return ret;
1022 if (!CanVehicleUseStation(v, st)) return CommandError(STR_ERROR_CAN_T_ADD_ORDER);
1023 for (Vehicle *u = v->FirstShared(); u != nullptr; u = u->NextShared()) {
1024 if (!CanVehicleUseStation(u, st)) return CommandError(STR_ERROR_CAN_T_ADD_ORDER_SHARED);
1027 /* Non stop only allowed for ground vehicles. */
1028 if (new_order.GetNonStopType() != ONSF_STOP_EVERYWHERE && !v->IsGroundVehicle()) return CommandError();
1030 /* Filter invalid load/unload types. */
1031 switch (new_order.GetLoadType()) {
1032 case OLF_LOAD_IF_POSSIBLE: case OLFB_FULL_LOAD: case OLF_FULL_LOAD_ANY: case OLFB_NO_LOAD: break;
1033 default: return CommandError();
1035 switch (new_order.GetUnloadType()) {
1036 case OUF_UNLOAD_IF_POSSIBLE: case OUFB_UNLOAD: case OUFB_TRANSFER: case OUFB_NO_UNLOAD: break;
1037 default: return CommandError();
1040 /* Filter invalid stop locations */
1041 switch (new_order.GetStopLocation()) {
1042 case OSL_PLATFORM_NEAR_END:
1043 case OSL_PLATFORM_MIDDLE:
1044 if (v->type != VEH_TRAIN) return CommandError();
1045 FALLTHROUGH;
1047 case OSL_PLATFORM_FAR_END:
1048 break;
1050 default:
1051 return CommandError();
1054 break;
1057 case OT_GOTO_DEPOT: {
1058 if ((new_order.GetDepotActionType() & ODATFB_NEAREST_DEPOT) == 0) {
1059 if (v->type == VEH_AIRCRAFT) {
1060 const Station *st = Station::GetIfValid(new_order.GetDestination());
1062 if (st == nullptr) return CommandError();
1064 CommandCost ret = CheckOwnership(st->owner);
1065 if (ret.Failed()) return ret;
1067 if (!CanVehicleUseStation(v, st) || !st->airport.HasHangar()) {
1068 return CommandError();
1070 } else {
1071 const Depot *dp = Depot::GetIfValid(new_order.GetDestination());
1073 if (dp == nullptr) return CommandError();
1075 CommandCost ret = CheckOwnership(GetTileOwner(dp->xy));
1076 if (ret.Failed()) return ret;
1078 switch (v->type) {
1079 case VEH_TRAIN:
1080 if (!IsRailDepotTile(dp->xy)) return CommandError();
1081 break;
1083 case VEH_ROAD:
1084 if (!IsRoadDepotTile(dp->xy)) return CommandError();
1085 break;
1087 case VEH_SHIP:
1088 if (!IsShipDepotTile(dp->xy)) return CommandError();
1089 break;
1091 default: return CommandError();
1096 if (new_order.GetNonStopType() != ONSF_STOP_EVERYWHERE && !v->IsGroundVehicle()) return CommandError();
1097 if (new_order.GetDepotOrderType() & ~(ODTFB_PART_OF_ORDERS | ((new_order.GetDepotOrderType() & ODTFB_PART_OF_ORDERS) != 0 ? ODTFB_SERVICE : 0))) return CommandError();
1098 if (new_order.GetDepotActionType() & ~(ODATFB_HALT | ODATFB_NEAREST_DEPOT)) return CommandError();
1099 if ((new_order.GetDepotOrderType() & ODTFB_SERVICE) && (new_order.GetDepotActionType() & ODATFB_HALT)) return CommandError();
1100 break;
1103 case OT_GOTO_WAYPOINT: {
1104 const Waypoint *wp = Waypoint::GetIfValid(new_order.GetDestination());
1105 if (wp == nullptr) return CommandError();
1107 switch (v->type) {
1108 default: return CommandError();
1110 case VEH_TRAIN: {
1111 if (!(wp->facilities & FACIL_TRAIN)) return CommandError(STR_ERROR_CAN_T_ADD_ORDER);
1113 CommandCost ret = CheckOwnership(wp->owner);
1114 if (ret.Failed()) return ret;
1115 break;
1118 case VEH_SHIP:
1119 if (!(wp->facilities & FACIL_DOCK)) return CommandError(STR_ERROR_CAN_T_ADD_ORDER);
1120 if (wp->owner != OWNER_NONE) {
1121 CommandCost ret = CheckOwnership(wp->owner);
1122 if (ret.Failed()) return ret;
1124 break;
1127 /* Order flags can be any of the following for waypoints:
1128 * [non-stop]
1129 * non-stop orders (if any) are only valid for trains */
1130 if (new_order.GetNonStopType() != ONSF_STOP_EVERYWHERE && v->type != VEH_TRAIN) return CommandError();
1131 break;
1134 case OT_CONDITIONAL: {
1135 VehicleOrderID skip_to = new_order.GetConditionSkipToOrder();
1136 if (skip_to != 0 && skip_to >= v->GetNumOrders()) return CommandError(); // Always allow jumping to the first (even when there is no order).
1137 if (new_order.GetConditionVariable() >= OCV_END) return CommandError();
1139 OrderConditionComparator occ = new_order.GetConditionComparator();
1140 if (occ >= OCC_END) return CommandError();
1141 switch (new_order.GetConditionVariable()) {
1142 case OCV_SLOT_OCCUPANCY: {
1143 TraceRestrictSlotID slot = new_order.GetXData();
1144 if (slot != INVALID_TRACE_RESTRICT_SLOT_ID && !TraceRestrictSlot::IsValidID(slot)) return CommandError();
1145 if (occ != OCC_IS_TRUE && occ != OCC_IS_FALSE) return CommandError();
1146 break;
1148 case OCV_CARGO_WAITING:
1149 case OCV_CARGO_ACCEPTANCE:
1150 if (!CargoSpec::Get(new_order.GetConditionValue())->IsValid()) return CommandError();
1151 /* FALL THROUGH */
1153 case OCV_REQUIRES_SERVICE:
1154 if (occ != OCC_IS_TRUE && occ != OCC_IS_FALSE) return CommandError();
1155 break;
1157 case OCV_UNCONDITIONALLY:
1158 if (occ != OCC_EQUALS) return CommandError();
1159 if (new_order.GetConditionValue() != 0) return CommandError();
1160 break;
1162 case OCV_FREE_PLATFORMS:
1163 if (v->type != VEH_TRAIN) return CommandError();
1164 if (occ == OCC_IS_TRUE || occ == OCC_IS_FALSE) return CommandError();
1165 break;
1167 case OCV_PERCENT:
1168 if (occ != OCC_EQUALS) return CommandError();
1169 /* FALL THROUGH */
1171 case OCV_LOAD_PERCENTAGE:
1172 case OCV_RELIABILITY:
1173 if (new_order.GetConditionValue() > 100) return CommandError();
1174 FALLTHROUGH;
1176 default:
1177 if (occ == OCC_IS_TRUE || occ == OCC_IS_FALSE) return CommandError();
1178 break;
1180 break;
1183 default: return CommandError();
1186 if (sel_ord > v->GetNumOrders()) return CommandError();
1188 if (v->GetNumOrders() >= MAX_VEH_ORDER_ID) return CommandError(STR_ERROR_TOO_MANY_ORDERS);
1189 if (!Order::CanAllocateItem()) return CommandError(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
1190 if (!v->HasOrdersList() && !OrderList::CanAllocateItem()) return CommandError(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
1192 if (v->type == VEH_SHIP && _settings_game.pf.pathfinder_for_ships != VPF_NPF) {
1193 /* Make sure the new destination is not too far away from the previous */
1194 const Order *prev = nullptr;
1195 uint n = 0;
1197 /* Find the last goto station or depot order before the insert location.
1198 * If the order is to be inserted at the beginning of the order list this
1199 * finds the last order in the list. */
1200 const Order *o;
1201 FOR_VEHICLE_ORDERS(v, o) {
1202 switch (o->GetType()) {
1203 case OT_GOTO_STATION:
1204 case OT_GOTO_DEPOT:
1205 case OT_GOTO_WAYPOINT:
1206 prev = o;
1207 break;
1209 default: break;
1211 if (++n == sel_ord && prev != nullptr) break;
1213 if (prev != nullptr) {
1214 uint dist;
1215 if (new_order.IsType(OT_CONDITIONAL)) {
1216 /* The order is not yet inserted, so we have to do the first iteration here. */
1217 dist = GetOrderDistance(prev, v->GetOrder(new_order.GetConditionSkipToOrder()), v);
1218 } else {
1219 dist = GetOrderDistance(prev, &new_order, v);
1222 if (dist >= 130) {
1223 return CommandError(STR_ERROR_TOO_FAR_FROM_PREVIOUS_DESTINATION);
1228 if (flags & DC_EXEC) {
1229 Order *new_o = new Order();
1230 new_o->AssignOrder(new_order);
1231 InsertOrder(v, new_o, sel_ord);
1232 CheckMarkDirtyFocusedRoutePaths(v);
1235 return CommandCost();
1239 * Insert a new order but skip the validation.
1240 * @param v The vehicle to insert the order to.
1241 * @param new_o The new order.
1242 * @param sel_ord The position the order should be inserted at.
1244 void InsertOrder(Vehicle *v, Order *new_o, VehicleOrderID sel_ord)
1246 /* Create new order and link in list */
1247 if (!v->HasOrdersList()) {
1248 v->SetOrdersList(new OrderList(new_o, v));
1249 } else {
1250 v->InsertOrderAt(new_o, sel_ord);
1253 Vehicle *u = v->FirstShared();
1254 DeleteOrderWarnings(u);
1255 for (; u != nullptr; u = u->NextShared()) {
1256 assert(v->IsSharingOrdersWith(u));
1258 /* If there is added an order before the current one, we need
1259 * to update the selected order. We do not change implicit/real order indices though.
1260 * If the new order is between the current implicit order and real order, the implicit order will
1261 * later skip the inserted order. */
1262 if (sel_ord <= u->cur_real_order_index) {
1263 uint cur = u->cur_real_order_index + 1;
1264 /* Check if we don't go out of bound */
1265 if (cur < u->GetNumOrders()) {
1266 u->cur_real_order_index = cur;
1269 if (sel_ord == u->cur_implicit_order_index && u->IsGroundVehicle()) {
1270 /* We are inserting an order just before the current implicit order.
1271 * We do not know whether we will reach current implicit or the newly inserted order first.
1272 * So, disable creation of implicit orders until we are on track again. */
1273 uint16 &gv_flags = u->GetGroundVehicleFlags();
1274 SetBit(gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS);
1276 if (sel_ord <= u->cur_implicit_order_index) {
1277 uint cur = u->cur_implicit_order_index + 1;
1278 /* Check if we don't go out of bound */
1279 if (cur < u->GetNumOrders()) {
1280 u->cur_implicit_order_index = cur;
1283 if (u->cur_timetable_order_index != INVALID_VEH_ORDER_ID && sel_ord <= u->cur_timetable_order_index) {
1284 uint cur = u->cur_timetable_order_index + 1;
1285 /* Check if we don't go out of bound */
1286 if (cur < u->GetNumOrders()) {
1287 u->cur_timetable_order_index = cur;
1290 /* Update any possible open window of the vehicle */
1291 InvalidateVehicleOrder(u, INVALID_VEH_ORDER_ID | (sel_ord << 8));
1294 /* As we insert an order, the order to skip to will be 'wrong'. */
1295 VehicleOrderID cur_order_id = 0;
1296 Order *order;
1297 FOR_VEHICLE_ORDERS(v, order) {
1298 if (order->IsType(OT_CONDITIONAL)) {
1299 VehicleOrderID order_id = order->GetConditionSkipToOrder();
1300 if (order_id >= sel_ord) {
1301 order->SetConditionSkipToOrder(order_id + 1);
1303 if (order_id == cur_order_id) {
1304 order->SetConditionSkipToOrder((order_id + 1) % v->GetNumOrders());
1307 cur_order_id++;
1310 /* Make sure to rebuild the whole list */
1311 InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
1315 * Declone an order-list
1316 * @param *dst delete the orders of this vehicle
1317 * @param flags execution flags
1319 static CommandCost DecloneOrder(Vehicle *dst, DoCommandFlag flags)
1321 if (flags & DC_EXEC) {
1322 dst->DeleteVehicleOrders();
1323 InvalidateVehicleOrder(dst, VIWD_REMOVE_ALL_ORDERS);
1324 InvalidateWindowClassesData(GetWindowClassForVehicleType(dst->type), 0);
1325 CheckMarkDirtyFocusedRoutePaths(dst);
1327 return CommandCost();
1331 * Get the first cargoID that points to a valid cargo (usually 0)
1333 static CargoID GetFirstValidCargo()
1335 for (CargoID i = 0; i < NUM_CARGO; i++) {
1336 if (CargoSpec::Get(i)->IsValid()) return i;
1338 /* No cargoes defined -> 'Houston, we have a problem!' */
1339 assert(0);
1340 /* Return something to avoid compiler warning */
1341 return 0;
1345 * Get the first valid TraceRestrictSlot. Or INVALID_TRACE_RESTRICT_SLOT_ID if no slots are defined.
1347 static TraceRestrictSlotID GetFirstValidTraceRestrictSlot()
1349 const TraceRestrictSlot* slot;
1350 FOR_ALL_TRACE_RESTRICT_SLOTS(slot)
1352 // Stupid way to get the first valid slot but there is no "GetFirstValidSlot()".
1353 return slot->index;
1356 return INVALID_TRACE_RESTRICT_SLOT_ID;
1360 * Delete an order from the orderlist of a vehicle.
1361 * @param tile unused
1362 * @param flags operation to perform
1363 * @param p1 the ID of the vehicle
1364 * @param p2 the order to delete (max 255)
1365 * @param text unused
1366 * @return the cost of this operation or an error
1368 CommandCost CmdDeleteOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1370 VehicleID veh_id = GB(p1, 0, 20);
1371 VehicleOrderID sel_ord = GB(p2, 0, 8);
1373 Vehicle *v = Vehicle::GetIfValid(veh_id);
1375 if (v == nullptr || !v->IsPrimaryVehicle()) return CommandError();
1377 CommandCost ret = CheckOwnership(v->owner);
1378 if (ret.Failed()) return ret;
1380 /* If we did not select an order, we maybe want to de-clone the orders */
1381 if (sel_ord >= v->GetNumOrders()) return DecloneOrder(v, flags);
1383 if (v->GetOrder(sel_ord) == nullptr) return CommandError();
1385 if (flags & DC_EXEC) {
1386 DeleteOrder(v, sel_ord);
1387 CheckMarkDirtyFocusedRoutePaths(v);
1389 return CommandCost();
1393 * Cancel the current loading order of the vehicle as the order was deleted.
1394 * @param v the vehicle
1396 void CancelLoadingDueToDeletedOrder(Vehicle *v)
1398 assert(v->current_order.IsType(OT_LOADING));
1399 /* NON-stop flag is misused to see if a train is in a station that is
1400 * on his order list or not */
1401 v->current_order.SetNonStopType(ONSF_STOP_EVERYWHERE);
1402 /* When full loading, "cancel" that order so the vehicle doesn't
1403 * stay indefinitely at this station anymore. */
1404 if (v->current_order.GetLoadType() & OLFB_FULL_LOAD) v->current_order.SetLoadType(OLF_LOAD_IF_POSSIBLE);
1408 * Delete an order but skip the parameter validation.
1409 * @param v The vehicle to delete the order from.
1410 * @param sel_ord The id of the order to be deleted.
1412 void DeleteOrder(Vehicle *v, VehicleOrderID sel_ord)
1414 v->DeleteOrderAt(sel_ord);
1416 Vehicle *u = v->FirstShared();
1417 DeleteOrderWarnings(u);
1418 for (; u != nullptr; u = u->NextShared()) {
1419 assert(v->IsSharingOrdersWith(u));
1421 if (sel_ord == u->cur_real_order_index && u->current_order.IsType(OT_LOADING)) {
1422 CancelLoadingDueToDeletedOrder(u);
1425 if (sel_ord < u->cur_real_order_index) {
1426 u->cur_real_order_index--;
1427 } else if (sel_ord == u->cur_real_order_index) {
1428 u->UpdateRealOrderIndex();
1431 if (sel_ord < u->cur_implicit_order_index) {
1432 u->cur_implicit_order_index--;
1433 } else if (sel_ord == u->cur_implicit_order_index) {
1434 /* Make sure the index is valid */
1435 if (u->cur_implicit_order_index >= u->GetNumOrders()) u->cur_implicit_order_index = 0;
1437 /* Skip non-implicit orders for the implicit-order-index (e.g. if the current implicit order was deleted */
1438 while (u->cur_implicit_order_index != u->cur_real_order_index && !u->GetOrder(u->cur_implicit_order_index)->IsType(OT_IMPLICIT)) {
1439 u->cur_implicit_order_index++;
1440 if (u->cur_implicit_order_index >= u->GetNumOrders()) u->cur_implicit_order_index = 0;
1444 if (u->cur_timetable_order_index != INVALID_VEH_ORDER_ID) {
1445 if (sel_ord < u->cur_timetable_order_index) {
1446 u->cur_timetable_order_index--;
1447 } else if (sel_ord == u->cur_timetable_order_index) {
1448 u->cur_timetable_order_index = INVALID_VEH_ORDER_ID;
1452 /* Update any possible open window of the vehicle */
1453 InvalidateVehicleOrder(u, sel_ord | (INVALID_VEH_ORDER_ID << 8));
1456 /* As we delete an order, the order to skip to will be 'wrong'. */
1457 VehicleOrderID cur_order_id = 0;
1458 Order *order = nullptr;
1459 FOR_VEHICLE_ORDERS(v, order) {
1460 if (order->IsType(OT_CONDITIONAL)) {
1461 VehicleOrderID order_id = order->GetConditionSkipToOrder();
1462 if (order_id >= sel_ord) {
1463 order_id = max(order_id - 1, 0);
1465 if (order_id == cur_order_id) {
1466 order_id = (order_id + 1) % v->GetNumOrders();
1468 order->SetConditionSkipToOrder(order_id);
1470 cur_order_id++;
1473 InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
1474 CheckMarkDirtyFocusedRoutePaths(v);
1478 * Goto order of order-list.
1479 * @param tile unused
1480 * @param flags operation to perform
1481 * @param p1 The ID of the vehicle which order is skipped
1482 * @param p2 the selected order to which we want to skip
1483 * @param text unused
1484 * @return the cost of this operation or an error
1486 CommandCost CmdSkipToOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1488 VehicleID veh_id = GB(p1, 0, 20);
1489 VehicleOrderID sel_ord = GB(p2, 0, 8);
1491 Vehicle *v = Vehicle::GetIfValid(veh_id);
1493 if (v == nullptr || !v->IsPrimaryVehicle() || sel_ord == v->cur_implicit_order_index || sel_ord >= v->GetNumOrders() || v->GetNumOrders() < 2) return CommandError();
1495 CommandCost ret = CheckOwnership(v->owner);
1496 if (ret.Failed()) return ret;
1498 if (flags & DC_EXEC) {
1499 if (v->current_order.IsType(OT_LOADING)) v->LeaveStation();
1500 if (v->current_order.IsType(OT_WAITING)) v->HandleWaiting(true);
1502 v->cur_implicit_order_index = v->cur_real_order_index = sel_ord;
1503 v->UpdateRealOrderIndex();
1504 v->cur_timetable_order_index = INVALID_VEH_ORDER_ID;
1506 InvalidateVehicleOrder(v, VIWD_MODIFY_ORDERS);
1509 /* We have an aircraft/ship, they have a mini-schedule, so update them all */
1510 if (v->type == VEH_AIRCRAFT) SetWindowClassesDirty(WC_AIRCRAFT_LIST);
1511 if (v->type == VEH_SHIP) SetWindowClassesDirty(WC_SHIPS_LIST);
1513 return CommandCost();
1517 * Move an order inside the orderlist
1518 * @param tile unused
1519 * @param flags operation to perform
1520 * @param p1 the ID of the vehicle
1521 * @param p2 order to move and target
1522 * bit 0-15 : the order to move
1523 * bit 16-31 : the target order
1524 * @param text unused
1525 * @return the cost of this operation or an error
1526 * @note The target order will move one place down in the orderlist
1527 * if you move the order upwards else it'll move it one place down
1529 CommandCost CmdMoveOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1531 VehicleID veh = GB(p1, 0, 20);
1532 VehicleOrderID moving_order = GB(p2, 0, 16);
1533 VehicleOrderID target_order = GB(p2, 16, 16);
1535 Vehicle *v = Vehicle::GetIfValid(veh);
1536 if (v == nullptr || !v->IsPrimaryVehicle()) return CommandError();
1538 CommandCost ret = CheckOwnership(v->owner);
1539 if (ret.Failed()) return ret;
1541 /* Don't make senseless movements */
1542 if (moving_order >= v->GetNumOrders() || target_order >= v->GetNumOrders() ||
1543 moving_order == target_order || v->GetNumOrders() <= 1) return CommandError();
1545 Order *moving_one = v->GetOrder(moving_order);
1546 /* Don't move an empty order */
1547 if (moving_one == nullptr) return CommandError();
1549 if (flags & DC_EXEC) {
1550 v->MoveOrder(moving_order, target_order);
1552 /* Update shared list */
1553 Vehicle *u = v->FirstShared();
1555 DeleteOrderWarnings(u);
1557 for (; u != nullptr; u = u->NextShared()) {
1558 /* Update the current order.
1559 * There are multiple ways to move orders, which result in cur_implicit_order_index
1560 * and cur_real_order_index to not longer make any sense. E.g. moving another
1561 * real order between them.
1563 * Basically one could choose to preserve either of them, but not both.
1564 * While both ways are suitable in this or that case from a human point of view, neither
1565 * of them makes really sense.
1566 * However, from an AI point of view, preserving cur_real_order_index is the most
1567 * predictable and transparent behaviour.
1569 * With that decision it basically does not matter what we do to cur_implicit_order_index.
1570 * If we change orders between the implicit- and real-index, the implicit orders are mostly likely
1571 * completely out-dated anyway. So, keep it simple and just keep cur_implicit_order_index as well.
1572 * The worst which can happen is that a lot of implicit orders are removed when reaching current_order.
1574 if (u->cur_real_order_index == moving_order) {
1575 u->cur_real_order_index = target_order;
1576 } else if (u->cur_real_order_index > moving_order && u->cur_real_order_index <= target_order) {
1577 u->cur_real_order_index--;
1578 } else if (u->cur_real_order_index < moving_order && u->cur_real_order_index >= target_order) {
1579 u->cur_real_order_index++;
1582 if (u->cur_implicit_order_index == moving_order) {
1583 u->cur_implicit_order_index = target_order;
1584 } else if (u->cur_implicit_order_index > moving_order && u->cur_implicit_order_index <= target_order) {
1585 u->cur_implicit_order_index--;
1586 } else if (u->cur_implicit_order_index < moving_order && u->cur_implicit_order_index >= target_order) {
1587 u->cur_implicit_order_index++;
1590 u->cur_timetable_order_index = INVALID_VEH_ORDER_ID;
1592 assert(v->IsSharingOrdersWith(u));
1594 /* Update any possible open window of the vehicle */
1595 InvalidateVehicleOrder(u, moving_order | (target_order << 8));
1598 /* As we move an order, the order to skip to will be 'wrong'. */
1599 Order *order;
1600 FOR_VEHICLE_ORDERS(v, order) {
1601 if (order->IsType(OT_CONDITIONAL)) {
1602 VehicleOrderID order_id = order->GetConditionSkipToOrder();
1603 if (order_id == moving_order) {
1604 order_id = target_order;
1605 } else if (order_id > moving_order && order_id <= target_order) {
1606 order_id--;
1607 } else if (order_id < moving_order && order_id >= target_order) {
1608 order_id++;
1610 order->SetConditionSkipToOrder(order_id);
1614 /* Make sure to rebuild the whole list */
1615 InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
1618 return CommandCost();
1622 * Modify an order in the orderlist of a vehicle.
1623 * @param tile unused
1624 * @param flags operation to perform
1625 * @param p1 various bitstuffed elements
1626 * - p1 = (bit 0 - 19) - ID of the vehicle
1627 * - p1 = (bit 20 - 27) - the selected order (if any). If the last order is given,
1628 * the order will be inserted before that one
1629 * the maximum vehicle order id is 254.
1630 * @param p2 various bitstuffed elements
1631 * - p2 = (bit 0 - 3) - what data to modify (@see ModifyOrderFlags)
1632 * - p2 = (bit 4 - 19) - the data to modify
1633 * - p2 = (bit 20 - 27) - a CargoID for cargo type orders (MOF_CARGO_TYPE_UNLOAD or MOF_CARGO_TYPE_LOAD)
1634 * @param text unused
1635 * @return the cost of this operation or an error
1637 CommandCost CmdModifyOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1639 VehicleOrderID sel_ord = GB(p1, 20, 8);
1640 VehicleID veh = GB(p1, 0, 20);
1641 ModifyOrderFlags mof = Extract<ModifyOrderFlags, 0, 4>(p2);
1642 uint16 data = GB(p2, 4, 16);
1643 CargoID cargo_id = (mof == MOF_CARGO_TYPE_UNLOAD || mof == MOF_CARGO_TYPE_LOAD) ? (CargoID)GB(p2, 20, 8) : (CargoID)CT_INVALID;
1645 if (mof >= MOF_END) return CommandError();
1647 Vehicle *v = Vehicle::GetIfValid(veh);
1648 if (v == nullptr || !v->IsPrimaryVehicle()) return CommandError();
1650 CommandCost ret = CheckOwnership(v->owner);
1651 if (ret.Failed()) return ret;
1653 /* Is it a valid order? */
1654 if (sel_ord >= v->GetNumOrders()) return CommandError();
1656 Order *order = v->GetOrder(sel_ord);
1657 switch (order->GetType()) {
1658 case OT_GOTO_STATION:
1659 if (mof != MOF_NON_STOP && mof != MOF_STOP_LOCATION && mof != MOF_UNLOAD && mof != MOF_LOAD && mof != MOF_CARGO_TYPE_UNLOAD && mof != MOF_CARGO_TYPE_LOAD) return CommandError();
1660 break;
1662 case OT_GOTO_DEPOT:
1663 if (mof != MOF_NON_STOP && mof != MOF_DEPOT_ACTION) return CommandError();
1664 break;
1666 case OT_GOTO_WAYPOINT:
1667 if (mof != MOF_NON_STOP && mof != MOF_WAYPOINT_FLAGS) return CommandError();
1668 break;
1670 case OT_CONDITIONAL:
1671 if (mof != MOF_COND_VARIABLE && mof != MOF_COND_COMPARATOR && mof != MOF_COND_VALUE && mof != MOF_COND_DESTINATION) return CommandError();
1672 break;
1674 default:
1675 return CommandError();
1678 switch (mof) {
1679 default: NOT_REACHED();
1681 case MOF_NON_STOP:
1682 if (!v->IsGroundVehicle()) return CommandError();
1683 if (data >= ONSF_END) return CommandError();
1684 if (data == order->GetNonStopType()) return CommandError();
1685 break;
1687 case MOF_STOP_LOCATION:
1688 if (v->type != VEH_TRAIN) return CommandError();
1689 if (data >= OSL_END) return CommandError();
1690 break;
1692 case MOF_CARGO_TYPE_UNLOAD:
1693 if (cargo_id >= NUM_CARGO) return CommandError();
1694 if (data == OUFB_CARGO_TYPE_UNLOAD) return CommandError();
1695 /* FALL THROUGH */
1696 case MOF_UNLOAD:
1697 if (order->GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION) return CommandError();
1698 if ((data & ~(OUFB_UNLOAD | OUFB_TRANSFER | OUFB_NO_UNLOAD | OUFB_CARGO_TYPE_UNLOAD)) != 0) return CommandError();
1699 /* Unload and no-unload are mutual exclusive and so are transfer and no unload. */
1700 if (data != 0 && (data & OUFB_CARGO_TYPE_UNLOAD) == 0 && ((data & (OUFB_UNLOAD | OUFB_TRANSFER)) != 0) == ((data & OUFB_NO_UNLOAD) != 0)) return CommandError();
1701 /* Cargo-type-unload exclude all the other flags. */
1702 if ((data & OUFB_CARGO_TYPE_UNLOAD) != 0 && data != OUFB_CARGO_TYPE_UNLOAD) return CommandError();
1703 if (data == order->GetUnloadType()) return CommandError();
1704 break;
1706 case MOF_CARGO_TYPE_LOAD:
1707 if (cargo_id >= NUM_CARGO) return CommandError();
1708 if (data == OLFB_CARGO_TYPE_LOAD || data == OLF_FULL_LOAD_ANY) return CommandError();
1709 /* FALL THROUGH */
1710 case MOF_LOAD:
1711 if (order->GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION) return CommandError();
1712 if ((data > OLFB_NO_LOAD && data != OLFB_CARGO_TYPE_LOAD) || data == 1) return CommandError();
1713 if (data == order->GetLoadType()) return CommandError();
1714 break;
1716 case MOF_DEPOT_ACTION:
1717 if (data >= DA_END) return CommandError();
1718 break;
1720 case MOF_COND_VARIABLE:
1721 if (data == OCV_FREE_PLATFORMS && v->type != VEH_TRAIN) return CommandError();
1722 if (data >= OCV_END) return CommandError();
1723 break;
1725 case MOF_COND_COMPARATOR:
1726 if (data >= OCC_END) return CommandError();
1727 switch (order->GetConditionVariable()) {
1728 case OCV_UNCONDITIONALLY:
1729 case OCV_PERCENT:
1730 return CommandError();
1732 case OCV_REQUIRES_SERVICE:
1733 case OCV_CARGO_ACCEPTANCE:
1734 case OCV_CARGO_WAITING:
1735 case OCV_SLOT_OCCUPANCY:
1736 if (data != OCC_IS_TRUE && data != OCC_IS_FALSE) return CommandError();
1737 break;
1739 default:
1740 if (data == OCC_IS_TRUE || data == OCC_IS_FALSE) return CommandError();
1741 break;
1743 break;
1745 case MOF_COND_VALUE:
1746 switch (order->GetConditionVariable()) {
1747 case OCV_UNCONDITIONALLY:
1748 case OCV_REQUIRES_SERVICE:
1749 return CommandError();
1751 case OCV_LOAD_PERCENTAGE:
1752 case OCV_RELIABILITY:
1753 case OCV_PERCENT:
1754 if (data > 100) return CommandError();
1755 break;
1757 case OCV_SLOT_OCCUPANCY:
1758 if (data != INVALID_TRACE_RESTRICT_SLOT_ID && !TraceRestrictSlot::IsValidID(data)) return CommandError();
1759 break;
1761 case OCV_CARGO_ACCEPTANCE:
1762 case OCV_CARGO_WAITING:
1763 if (!(data < NUM_CARGO && CargoSpec::Get(data)->IsValid())) return CommandError();
1764 break;
1766 default:
1767 if (data > 2047) return CommandError();
1768 break;
1770 break;
1772 case MOF_COND_DESTINATION:
1773 if (data >= v->GetNumOrders()) return CommandError();
1774 break;
1776 case MOF_WAYPOINT_FLAGS:
1777 if (data != (data & OWF_REVERSE)) return CommandError();
1778 break;
1781 if (flags & DC_EXEC) {
1782 switch (mof) {
1783 case MOF_NON_STOP:
1784 order->SetNonStopType((OrderNonStopFlags)data);
1785 if (data & ONSF_NO_STOP_AT_DESTINATION_STATION) {
1786 order->SetRefit(CT_NO_REFIT);
1787 order->SetLoadType(OLF_LOAD_IF_POSSIBLE);
1788 order->SetUnloadType(OUF_UNLOAD_IF_POSSIBLE);
1790 break;
1792 case MOF_STOP_LOCATION:
1793 order->SetStopLocation((OrderStopLocation)data);
1794 break;
1796 case MOF_UNLOAD:
1797 order->SetUnloadType((OrderUnloadFlags)data);
1798 break;
1800 case MOF_CARGO_TYPE_UNLOAD:
1801 order->SetUnloadType((OrderUnloadFlags)data, cargo_id);
1802 break;
1804 case MOF_LOAD:
1805 order->SetLoadType((OrderLoadFlags)data);
1806 if (data & OLFB_NO_LOAD) order->SetRefit(CT_NO_REFIT);
1807 break;
1809 case MOF_CARGO_TYPE_LOAD:
1810 order->SetLoadType((OrderLoadFlags)data, cargo_id);
1811 break;
1813 case MOF_DEPOT_ACTION: {
1814 switch (data) {
1815 case DA_ALWAYS_GO:
1816 order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() & ~ODTFB_SERVICE));
1817 order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_HALT));
1818 break;
1820 case DA_SERVICE:
1821 order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() | ODTFB_SERVICE));
1822 order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_HALT));
1823 order->SetRefit(CT_NO_REFIT);
1824 break;
1826 case DA_STOP:
1827 order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() & ~ODTFB_SERVICE));
1828 order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() | ODATFB_HALT));
1829 order->SetRefit(CT_NO_REFIT);
1830 break;
1832 default:
1833 NOT_REACHED();
1835 break;
1838 case MOF_COND_VARIABLE: {
1839 /* Check whether old conditional variable had a cargo as value */
1840 bool old_var_was_cargo = (order->GetConditionVariable() == OCV_CARGO_ACCEPTANCE || order->GetConditionVariable() == OCV_CARGO_WAITING);
1841 bool old_var_was_slot = (order->GetConditionVariable() == OCV_SLOT_OCCUPANCY);
1842 order->SetConditionVariable((OrderConditionVariable)data);
1844 OrderConditionComparator occ = order->GetConditionComparator();
1845 switch (order->GetConditionVariable()) {
1846 case OCV_UNCONDITIONALLY:
1847 order->SetConditionComparator(OCC_EQUALS);
1848 order->SetConditionValue(0);
1849 break;
1851 case OCV_SLOT_OCCUPANCY:
1852 if (!old_var_was_slot) order->GetXDataRef() = INVALID_TRACE_RESTRICT_SLOT_ID;
1853 if (occ != OCC_IS_TRUE && occ != OCC_IS_FALSE) order->SetConditionComparator(OCC_IS_TRUE);
1854 break;
1856 case OCV_CARGO_ACCEPTANCE:
1857 case OCV_CARGO_WAITING:
1858 if (!old_var_was_cargo) order->SetConditionValue((uint16) GetFirstValidCargo());
1859 if (occ != OCC_IS_TRUE && occ != OCC_IS_FALSE) order->SetConditionComparator(OCC_IS_TRUE);
1860 break;
1862 case OCV_REQUIRES_SERVICE:
1863 if (old_var_was_cargo || old_var_was_slot) order->SetConditionValue(0);
1864 if (occ != OCC_IS_TRUE && occ != OCC_IS_FALSE) order->SetConditionComparator(OCC_IS_TRUE);
1865 order->SetConditionValue(0);
1866 break;
1868 case OCV_PERCENT:
1869 order->SetConditionComparator(OCC_EQUALS);
1870 /* FALL THROUGH */
1872 case OCV_LOAD_PERCENTAGE:
1873 case OCV_RELIABILITY:
1874 if (order->GetConditionValue() > 100) order->SetConditionValue(100);
1875 FALLTHROUGH;
1877 default:
1878 if (old_var_was_cargo || old_var_was_slot) order->SetConditionValue(0);
1879 if (occ == OCC_IS_TRUE || occ == OCC_IS_FALSE) order->SetConditionComparator(OCC_EQUALS);
1880 break;
1882 break;
1885 case MOF_COND_COMPARATOR:
1886 order->SetConditionComparator((OrderConditionComparator)data);
1887 break;
1889 case MOF_COND_VALUE:
1890 switch (order->GetConditionVariable()) {
1891 case OCV_SLOT_OCCUPANCY:
1892 order->GetXDataRef() = data;
1893 break;
1895 default:
1896 order->SetConditionValue(data);
1897 break;
1899 break;
1901 case MOF_COND_DESTINATION:
1902 order->SetConditionSkipToOrder(data);
1903 break;
1905 case MOF_WAYPOINT_FLAGS:
1906 order->SetWaypointFlags((OrderWaypointFlags)data);
1907 break;
1909 default: NOT_REACHED();
1912 /* Update the windows and full load flags, also for vehicles that share the same order list */
1913 Vehicle *u = v->FirstShared();
1914 DeleteOrderWarnings(u);
1915 for (; u != nullptr; u = u->NextShared()) {
1916 /* Toggle u->current_order "Full load" flag if it changed.
1917 * However, as the same flag is used for depot orders, check
1918 * whether we are not going to a depot as there are three
1919 * cases where the full load flag can be active and only
1920 * one case where the flag is used for depot orders. In the
1921 * other cases for the OrderTypeByte the flags are not used,
1922 * so do not care and those orders should not be active
1923 * when this function is called.
1925 if (sel_ord == u->cur_real_order_index &&
1926 (u->current_order.IsType(OT_GOTO_STATION) || u->current_order.IsType(OT_LOADING)) &&
1927 u->current_order.GetLoadType() != order->GetLoadType()) {
1928 u->current_order.SetLoadType(order->GetLoadType());
1930 InvalidateVehicleOrder(u, VIWD_MODIFY_ORDERS);
1932 CheckMarkDirtyFocusedRoutePaths(v);
1935 return CommandCost();
1939 * Check if an aircraft has enough range for an order list.
1940 * @param v_new Aircraft to check.
1941 * @param v_order Vehicle currently holding the order list.
1942 * @param first First order in the source order list.
1943 * @return True if the aircraft has enough range for the orders, false otherwise.
1945 static bool CheckAircraftOrderDistance(const Aircraft *v_new, const Vehicle *v_order, const Order *first)
1947 if (first == nullptr || v_new->acache.cached_max_range == 0) return true;
1949 /* Iterate over all orders to check the distance between all
1950 * 'goto' orders and their respective next order (of any type). */
1951 for (const Order *o = first; o != nullptr; o = o->next) {
1952 switch (o->GetType()) {
1953 case OT_GOTO_STATION:
1954 case OT_GOTO_DEPOT:
1955 case OT_GOTO_WAYPOINT:
1956 /* If we don't have a next order, we've reached the end and must check the first order instead. */
1957 if (GetOrderDistance(o, o->next != nullptr ? o->next : first, v_order) > v_new->acache.cached_max_range_sqr) return false;
1958 break;
1960 default: break;
1964 return true;
1968 * Clone/share/copy an order-list of another vehicle.
1969 * @param tile unused
1970 * @param flags operation to perform
1971 * @param p1 various bitstuffed elements
1972 * - p1 = (bit 0-19) - destination vehicle to clone orders to
1973 * - p1 = (bit 30-31) - action to perform
1974 * @param p2 source vehicle to clone orders from, if any (none for CO_UNSHARE)
1975 * @param text unused
1976 * @return the cost of this operation or an error
1978 CommandCost CmdCloneOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1980 VehicleID veh_src = GB(p2, 0, 20);
1981 VehicleID veh_dst = GB(p1, 0, 20);
1983 Vehicle *dst = Vehicle::GetIfValid(veh_dst);
1984 if (dst == nullptr || !dst->IsPrimaryVehicle()) return CommandError();
1986 CommandCost ret = CheckOwnership(dst->owner);
1987 if (ret.Failed()) return ret;
1989 switch (GB(p1, 30, 2)) {
1990 case CO_SHARE: {
1991 Vehicle *src = Vehicle::GetIfValid(veh_src);
1993 /* Sanity checks */
1994 if (src == nullptr || !src->IsPrimaryVehicle() || dst->type != src->type || dst == src) return CommandError();
1996 CommandCost ret = CheckOwnership(src->owner);
1997 if (ret.Failed()) return ret;
1999 /* Trucks can't share orders with busses (and visa versa) */
2000 if (src->type == VEH_ROAD && RoadVehicle::From(src)->IsBus() != RoadVehicle::From(dst)->IsBus()) {
2001 return CommandError();
2004 /* Is the vehicle already in the shared list? */
2005 if (src->FirstShared() == dst->FirstShared()) return CommandError();
2007 const Order *order;
2009 FOR_VEHICLE_ORDERS(src, order) {
2010 if (!OrderGoesToStation(dst, order)) continue;
2012 /* Allow copying unreachable destinations if they were already unreachable for the source.
2013 * This is basically to allow cloning / autorenewing / autoreplacing vehicles, while the stations
2014 * are temporarily invalid due to reconstruction. */
2015 const Station *st = Station::Get(order->GetDestination());
2016 if (CanVehicleUseStation(src, st) && !CanVehicleUseStation(dst, st)) {
2017 return CommandError(STR_ERROR_CAN_T_COPY_SHARE_ORDER);
2021 /* Check for aircraft range limits. */
2022 if (dst->type == VEH_AIRCRAFT && !CheckAircraftOrderDistance(Aircraft::From(dst), src, src->GetFirstOrder())) {
2023 return CommandError(STR_ERROR_AIRCRAFT_NOT_ENOUGH_RANGE);
2026 if (!src->HasOrdersList() && !OrderList::CanAllocateItem()) {
2027 return CommandError(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
2030 if (flags & DC_EXEC) {
2031 /* If the destination vehicle had a OrderList, destroy it.
2032 * We only reset the order indices, if the new orders are obviously different.
2033 * (We mainly do this to keep the order indices valid and in range.) */
2034 dst->DeleteVehicleOrders(false, dst->GetNumOrders() != src->GetNumOrders());
2036 dst->ShareOrdersWith(src);
2038 /* Link this vehicle in the shared-list */
2039 dst->AddToShared(src);
2041 /* Set automation bit if target has it. */
2042 if (HasBit(src->vehicle_flags, VF_AUTOMATE_TIMETABLE)) {
2043 SetBit(dst->vehicle_flags, VF_AUTOMATE_TIMETABLE);
2045 else {
2046 ClrBit(dst->vehicle_flags, VF_AUTOMATE_TIMETABLE);
2049 if (HasBit(src->vehicle_flags, VF_AUTOMATE_PRES_WAIT_TIME)) {
2050 SetBit(dst->vehicle_flags, VF_AUTOMATE_PRES_WAIT_TIME);
2052 else {
2053 ClrBit(dst->vehicle_flags, VF_AUTOMATE_PRES_WAIT_TIME);
2056 InvalidateVehicleOrder(dst, VIWD_REMOVE_ALL_ORDERS);
2057 InvalidateVehicleOrder(src, VIWD_MODIFY_ORDERS);
2059 InvalidateWindowClassesData(GetWindowClassForVehicleType(dst->type), 0);
2060 CheckMarkDirtyFocusedRoutePaths(dst);
2062 break;
2065 case CO_COPY: {
2066 Vehicle *src = Vehicle::GetIfValid(veh_src);
2068 /* Sanity checks */
2069 if (src == nullptr || !src->IsPrimaryVehicle() || dst->type != src->type || dst == src) return CommandError();
2071 CommandCost ret = CheckOwnership(src->owner);
2072 if (ret.Failed()) return ret;
2074 /* Trucks can't copy all the orders from busses (and visa versa),
2075 * and neither can helicopters and aircraft. */
2076 const Order *order;
2077 FOR_VEHICLE_ORDERS(src, order) {
2078 if (OrderGoesToStation(dst, order) &&
2079 !CanVehicleUseStation(dst, Station::Get(order->GetDestination()))) {
2080 return CommandError(STR_ERROR_CAN_T_COPY_SHARE_ORDER);
2084 /* Check for aircraft range limits. */
2085 if (dst->type == VEH_AIRCRAFT && !CheckAircraftOrderDistance(Aircraft::From(dst), src, src->GetFirstOrder())) {
2086 return CommandError(STR_ERROR_AIRCRAFT_NOT_ENOUGH_RANGE);
2089 /* make sure there are orders available */
2090 if (!Order::CanAllocateItem(src->GetNumOrders()) || !OrderList::CanAllocateItem()) {
2091 return CommandError(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
2094 if (flags & DC_EXEC) {
2095 const Order *order;
2096 Order *first = nullptr;
2097 Order **order_dst;
2099 /* If the destination vehicle had an order list, destroy the chain but keep the OrderList.
2100 * We only reset the order indices, if the new orders are obviously different.
2101 * (We mainly do this to keep the order indices valid and in range.) */
2102 dst->DeleteVehicleOrders(true, dst->GetNumOrders() != src->GetNumOrders());
2104 order_dst = &first;
2105 FOR_VEHICLE_ORDERS(src, order) {
2106 *order_dst = new Order();
2107 (*order_dst)->AssignOrder(*order);
2108 order_dst = &(*order_dst)->next;
2110 if (!dst->HasOrdersList()) {
2111 dst->SetOrdersList(new OrderList(first, dst));
2112 } else {
2113 assert(dst->GetFirstOrder() == nullptr);
2114 assert(!dst->HasSharedOrdersList());
2115 dst->DeleteAndReplaceOrdersList(new OrderList(first, dst));
2118 /* Set automation bit if target has it. */
2119 if (HasBit(src->vehicle_flags, VF_AUTOMATE_TIMETABLE)) {
2120 SetBit(dst->vehicle_flags, VF_AUTOMATE_TIMETABLE);
2122 else {
2123 ClrBit(dst->vehicle_flags, VF_AUTOMATE_TIMETABLE);
2126 if (HasBit(src->vehicle_flags, VF_AUTOMATE_PRES_WAIT_TIME)) {
2127 SetBit(dst->vehicle_flags, VF_AUTOMATE_PRES_WAIT_TIME);
2129 else {
2130 ClrBit(dst->vehicle_flags, VF_AUTOMATE_PRES_WAIT_TIME);
2133 InvalidateVehicleOrder(dst, VIWD_REMOVE_ALL_ORDERS);
2135 InvalidateWindowClassesData(GetWindowClassForVehicleType(dst->type), 0);
2136 CheckMarkDirtyFocusedRoutePaths(dst);
2138 break;
2141 case CO_UNSHARE: return DecloneOrder(dst, flags);
2142 default: return CommandError();
2145 return CommandCost();
2149 * Add/remove refit orders from an order
2150 * @param tile Not used
2151 * @param flags operation to perform
2152 * @param p1 VehicleIndex of the vehicle having the order
2153 * @param p2 bitmask
2154 * - bit 0-7 CargoID
2155 * - bit 16-23 number of order to modify
2156 * @param text unused
2157 * @return the cost of this operation or an error
2159 CommandCost CmdOrderRefit(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2161 VehicleID veh = GB(p1, 0, 20);
2162 VehicleOrderID order_number = GB(p2, 16, 8);
2163 CargoID cargo = GB(p2, 0, 8);
2165 if (cargo >= NUM_CARGO && cargo != CT_NO_REFIT && cargo != CT_AUTO_REFIT) return CommandError();
2167 const Vehicle *v = Vehicle::GetIfValid(veh);
2168 if (v == nullptr || !v->IsPrimaryVehicle()) return CommandError();
2170 CommandCost ret = CheckOwnership(v->owner);
2171 if (ret.Failed()) return ret;
2173 Order *order = v->GetOrder(order_number);
2174 if (order == nullptr) return CommandError();
2176 /* Automatic refit cargo is only supported for goto station orders. */
2177 if (cargo == CT_AUTO_REFIT && !order->IsType(OT_GOTO_STATION)) return CommandError();
2179 if (order->GetLoadType() & OLFB_NO_LOAD) return CommandError();
2181 if (flags & DC_EXEC) {
2182 order->SetRefit(cargo);
2184 /* Make the depot order an 'always go' order. */
2185 if (cargo != CT_NO_REFIT && order->IsType(OT_GOTO_DEPOT)) {
2186 order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() & ~ODTFB_SERVICE));
2187 order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_HALT));
2190 for (Vehicle *u = v->FirstShared(); u != nullptr; u = u->NextShared()) {
2191 /* Update any possible open window of the vehicle */
2192 InvalidateVehicleOrder(u, VIWD_MODIFY_ORDERS);
2194 /* If the vehicle already got the current depot set as current order, then update current order as well */
2195 if (u->cur_real_order_index == order_number && (u->current_order.GetDepotOrderType() & ODTFB_PART_OF_ORDERS)) {
2196 u->current_order.SetRefit(cargo);
2199 CheckMarkDirtyFocusedRoutePaths(v);
2202 return CommandCost();
2208 * Check the orders of a vehicle, to see if there are invalid orders and stuff
2211 void CheckOrders(const Vehicle *v)
2213 /* Does the user wants us to check things? */
2214 if (_settings_client.gui.order_review_system == 0) return;
2216 /* Do nothing for crashed vehicles */
2217 if (v->vehstatus & VS_CRASHED) return;
2219 /* Do nothing for stopped vehicles if setting is '1' */
2220 if (_settings_client.gui.order_review_system == 1 && (v->vehstatus & VS_STOPPED)) return;
2222 /* do nothing we we're not the first vehicle in a share-chain */
2223 if (v->FirstShared() != v) return;
2225 /* Only check every 20 days, so that we don't flood the message log */
2226 /* The check is skipped entirely in case the current vehicle is virtual (a.k.a a 'template train') */
2227 if (v->owner == _local_company && v->day_counter % 20 == 0 && !HasBit(v->subtype, GVSF_VIRTUAL) ) {
2228 const Order *order;
2229 StringID message = INVALID_STRING_ID;
2231 /* Check the order list */
2232 int n_st = 0;
2234 FOR_VEHICLE_ORDERS(v, order) {
2235 /* Dummy order? */
2236 if (order->IsType(OT_DUMMY)) {
2237 message = STR_NEWS_VEHICLE_HAS_VOID_ORDER;
2238 break;
2240 /* Does station have a load-bay for this vehicle? */
2241 if (order->IsType(OT_GOTO_STATION)) {
2242 const Station *st = Station::Get(order->GetDestination());
2244 n_st++;
2245 if (!CanVehicleUseStation(v, st)) {
2246 message = STR_NEWS_VEHICLE_HAS_INVALID_ENTRY;
2247 } else if (v->type == VEH_AIRCRAFT &&
2248 (AircraftVehInfo(v->engine_type)->subtype & AIR_FAST) &&
2249 (st->airport.GetFTA()->flags & AirportFTAClass::SHORT_STRIP) &&
2250 _settings_game.vehicle.plane_crashes != 0 &&
2251 !_cheats.no_jetcrash.value &&
2252 message == INVALID_STRING_ID) {
2253 message = STR_NEWS_PLANE_USES_TOO_SHORT_RUNWAY;
2258 /* Check if the last and the first order are the same */
2259 if (v->GetNumOrders() > 1) {
2260 const Order *last = v->GetLastOrder();
2262 if (v->GetFirstOrder()->Equals(*last)) {
2263 message = STR_NEWS_VEHICLE_HAS_DUPLICATE_ENTRY;
2267 /* Do we only have 1 station in our order list? */
2268 if (n_st < 2 && message == INVALID_STRING_ID) message = STR_NEWS_VEHICLE_HAS_TOO_FEW_ORDERS;
2270 #ifndef NDEBUG
2271 v->DebugCheckSanity();
2272 #endif
2274 /* We don't have a problem */
2275 if (message == INVALID_STRING_ID) return;
2277 SetDParam(0, v->index);
2278 AddVehicleAdviceNewsItem(message, v->index);
2283 * Removes an order from all vehicles. Triggers when, say, a station is removed.
2284 * @param type The type of the order (OT_GOTO_[STATION|DEPOT|WAYPOINT]).
2285 * @param destination The destination. Can be a StationID, DepotID or WaypointID.
2287 void RemoveOrderFromAllVehicles(OrderType type, DestinationID destination)
2289 Vehicle *v;
2291 /* Aircraft have StationIDs for depot orders and never use DepotIDs
2292 * This fact is handled specially below
2295 /* Go through all vehicles */
2296 FOR_ALL_VEHICLES(v) {
2297 Order *order;
2299 order = &v->current_order;
2300 if ((v->type == VEH_AIRCRAFT && order->IsType(OT_GOTO_DEPOT) ? OT_GOTO_STATION : order->GetType()) == type &&
2301 v->current_order.GetDestination() == destination) {
2302 order->MakeDummy();
2303 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
2306 /* Clear the order from the order-list */
2307 int id = -1;
2308 FOR_VEHICLE_ORDERS(v, order) {
2309 id++;
2310 restart:
2312 OrderType ot = order->GetType();
2313 if (ot == OT_GOTO_DEPOT && (order->GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0) continue;
2314 if (ot == OT_IMPLICIT || (v->type == VEH_AIRCRAFT && ot == OT_GOTO_DEPOT)) ot = OT_GOTO_STATION;
2315 if (ot == type && order->GetDestination() == destination) {
2316 /* We want to clear implicit orders, but we don't want to make them
2317 * dummy orders. They should just vanish. Also check the actual order
2318 * type as ot is currently OT_GOTO_STATION. */
2319 if (order->IsType(OT_IMPLICIT)) {
2320 order = order->next; // DeleteOrder() invalidates current order
2321 DeleteOrder(v, id);
2322 if (order != nullptr) goto restart;
2323 break;
2326 /* Clear wait time */
2327 v->UpdateTotalDuration(-order->GetWaitTime());
2328 if (order->IsWaitTimetabled()) {
2329 v->UpdateTimetableDuration(-order->GetTimetabledWait());
2330 order->SetWaitTimetabled(false);
2332 order->SetWaitTime(0);
2334 /* Clear order, preserving travel time */
2335 bool travel_timetabled = order->IsTravelTimetabled();
2336 order->MakeDummy();
2337 order->SetTravelTimetabled(travel_timetabled);
2339 for (const Vehicle *w = v->FirstShared(); w != nullptr; w = w->NextShared()) {
2340 /* In GUI, simulate by removing the order and adding it back */
2341 InvalidateVehicleOrder(w, id | (INVALID_VEH_ORDER_ID << 8));
2342 InvalidateVehicleOrder(w, (INVALID_VEH_ORDER_ID << 8) | id);
2348 OrderBackup::RemoveOrder(type, destination);
2352 * Checks if a vehicle has a depot in its order list.
2353 * @return True iff at least one order is a depot order.
2355 bool Vehicle::HasDepotOrder() const
2357 const Order *order;
2359 FOR_VEHICLE_ORDERS(this, order) {
2360 if (order->IsType(OT_GOTO_DEPOT)) return true;
2363 return false;
2367 * Clamp the service interval to the correct min/max. The actual min/max values
2368 * depend on whether it's in percent or days.
2369 * @param interval proposed service interval
2370 * @param company_id the owner of the vehicle
2371 * @return Clamped service interval
2373 uint16 GetServiceIntervalClamped(uint interval, bool ispercent)
2375 return ispercent ? Clamp(interval, MIN_SERVINT_PERCENT, MAX_SERVINT_PERCENT) : Clamp(interval, MIN_SERVINT_DAYS, MAX_SERVINT_DAYS);
2380 * Check if a vehicle has any valid orders
2382 * @return false if there are no valid orders
2383 * @note Conditional orders are not considered valid destination orders
2386 static bool CheckForValidOrders(const Vehicle *v)
2388 const Order *order;
2390 FOR_VEHICLE_ORDERS(v, order) {
2391 switch (order->GetType()) {
2392 case OT_GOTO_STATION:
2393 case OT_GOTO_DEPOT:
2394 case OT_GOTO_WAYPOINT:
2395 return true;
2397 default:
2398 break;
2402 return false;
2406 * Compare the variable and value based on the given comparator.
2408 static bool OrderConditionCompare(OrderConditionComparator occ, int variable, int value)
2410 switch (occ) {
2411 case OCC_EQUALS: return variable == value;
2412 case OCC_NOT_EQUALS: return variable != value;
2413 case OCC_LESS_THAN: return variable < value;
2414 case OCC_LESS_EQUALS: return variable <= value;
2415 case OCC_MORE_THAN: return variable > value;
2416 case OCC_MORE_EQUALS: return variable >= value;
2417 case OCC_IS_TRUE: return variable != 0;
2418 case OCC_IS_FALSE: return variable == 0;
2419 default: NOT_REACHED();
2423 /* Get the number of free (train) platforms in a station.
2424 * @param st_id The StationID of the station.
2425 * @return The number of free train platforms.
2427 static uint16 GetFreeStationPlatforms(StationID st_id)
2429 assert(Station::IsValidID(st_id));
2430 const Station *st = Station::Get(st_id);
2431 if (!(st->facilities & FACIL_TRAIN)) return 0;
2432 bool is_free;
2433 TileIndex t2;
2434 uint16 counter = 0;
2435 TILE_AREA_LOOP(t1, st->train_station) {
2436 if (st->TileBelongsToRailStation(t1)) {
2437 /* We only proceed if this tile is a track tile and the north(-east/-west) end of the platform */
2438 if (IsCompatibleTrainStationTile(t1 + TileOffsByDiagDir(GetRailStationAxis(t1) == AXIS_X ? DIAGDIR_NE : DIAGDIR_NW), t1) || IsStationTileBlocked(t1)) continue;
2439 is_free = true;
2440 t2 = t1;
2441 do {
2442 if (GetStationReservationTrackBits(t2)) {
2443 is_free = false;
2444 break;
2446 t2 += TileOffsByDiagDir(GetRailStationAxis(t1) == AXIS_X ? DIAGDIR_SW : DIAGDIR_SE);
2447 } while (IsCompatibleTrainStationTile(t2, t1));
2448 if (is_free) counter++;
2451 return counter;
2454 /** Gets the next 'real' station in the order list
2455 * @param v the vehicle in question
2456 * @param order the current (conditional) order
2457 * @return the StationID of the next valid station in the order list, or INVALID_STATION if there is none.
2459 static StationID GetNextRealStation(const Vehicle *v, const Order *order, int conditional_depth = 0)
2461 if (order->IsType(OT_GOTO_STATION)) {
2462 if (Station::IsValidID(order->GetDestination())) return order->GetDestination();
2464 //nothing conditional about this
2465 if (conditional_depth > v->GetNumOrders()) return INVALID_STATION;
2466 return GetNextRealStation(v, (order->next != nullptr) ? order->next : v->GetFirstOrder(), ++conditional_depth);
2470 * Process a conditional order and determine the next order.
2471 * @param order the order the vehicle currently has
2472 * @param v the vehicle to update
2473 * @return index of next order to jump to, or INVALID_VEH_ORDER_ID to use the next order
2475 VehicleOrderID ProcessConditionalOrder(const Order *order, const Vehicle *v)
2477 if (order->GetType() != OT_CONDITIONAL) return INVALID_VEH_ORDER_ID;
2479 bool skip_order = false;
2480 OrderConditionComparator occ = order->GetConditionComparator();
2481 uint16 value = order->GetConditionValue();
2482 bool has_manual_depot_order = (HasBit(v->vehicle_flags, VF_SHOULD_GOTO_DEPOT) || HasBit(v->vehicle_flags, VF_SHOULD_SERVICE_AT_DEPOT));
2484 // OrderConditionCompare ignores the last parameter for occ == OCC_IS_TRUE or occ == OCC_IS_FALSE.
2485 switch (order->GetConditionVariable()) {
2486 case OCV_LOAD_PERCENTAGE: skip_order = OrderConditionCompare(occ, CalcPercentVehicleFilled(v, nullptr), value); break;
2487 case OCV_RELIABILITY: skip_order = OrderConditionCompare(occ, ToPercent16(v->reliability), value); break;
2488 case OCV_MAX_SPEED: skip_order = OrderConditionCompare(occ, v->GetDisplayMaxSpeed() * 10 / 16, value); break;
2489 case OCV_AGE: skip_order = OrderConditionCompare(occ, v->age / DAYS_IN_LEAP_YEAR, value); break;
2490 case OCV_REQUIRES_SERVICE: skip_order = OrderConditionCompare(occ, has_manual_depot_order || v->NeedsServicing(), value); break;
2491 case OCV_UNCONDITIONALLY: skip_order = true; break;
2492 case OCV_CARGO_WAITING: {
2493 StationID next_station = GetNextRealStation(v, order);
2494 if (Station::IsValidID(next_station)) skip_order = OrderConditionCompare(occ, Station::Get(next_station)->goods[value].cargo.AvailableCount() > 0, value);
2495 break;
2497 case OCV_CARGO_ACCEPTANCE: {
2498 StationID next_station = GetNextRealStation(v, order);
2499 if (Station::IsValidID(next_station)) skip_order = OrderConditionCompare(occ, HasBit(Station::Get(next_station)->goods[value].status, GoodsEntry::GES_ACCEPTANCE), value);
2500 break;
2502 case OCV_SLOT_OCCUPANCY: {
2503 const TraceRestrictSlot* slot = TraceRestrictSlot::GetIfValid(order->GetXData());
2504 if (slot != nullptr) skip_order = OrderConditionCompare(occ, slot->occupants.size() >= slot->max_occupancy, value);
2505 break;
2507 case OCV_FREE_PLATFORMS: {
2508 StationID next_station = GetNextRealStation(v, order);
2509 if (Station::IsValidID(next_station)) skip_order = OrderConditionCompare(occ, GetFreeStationPlatforms(next_station), value);
2510 break;
2512 case OCV_PERCENT: {
2513 /* get a non-const reference to the current order */
2514 Order *ord = (Order *)order;
2515 skip_order = ord->UpdateJumpCounter((byte)value);
2516 break;
2518 case OCV_REMAINING_LIFETIME: skip_order = OrderConditionCompare(occ, max(v->max_age - v->age + DAYS_IN_LEAP_YEAR - 1, 0) / DAYS_IN_LEAP_YEAR, value); break;
2519 default: NOT_REACHED();
2522 return skip_order ? order->GetConditionSkipToOrder() : (VehicleOrderID)INVALID_VEH_ORDER_ID;
2526 * Update the vehicle's destination tile from an order.
2527 * @param order the order the vehicle currently has
2528 * @param v the vehicle to update
2529 * @param conditional_depth the depth (amount of steps) to go with conditional orders. This to prevent infinite loops.
2530 * @param pbs_look_ahead Whether we are forecasting orders for pbs reservations in advance. If true, the order indices must not be modified.
2532 bool UpdateOrderDest(Vehicle *v, const Order *order, int conditional_depth, bool pbs_look_ahead)
2534 if (conditional_depth > v->GetNumOrders()) {
2535 v->current_order.Free();
2536 v->dest_tile = 0;
2537 return false;
2540 bool has_manual_depot_order = (HasBit(v->vehicle_flags, VF_SHOULD_GOTO_DEPOT) || HasBit(v->vehicle_flags, VF_SHOULD_SERVICE_AT_DEPOT));
2542 switch (order->GetType()) {
2543 case OT_GOTO_STATION:
2544 v->dest_tile = v->GetOrderStationLocation(order->GetDestination());
2545 return true;
2547 case OT_GOTO_DEPOT:
2548 if ((order->GetDepotOrderType() & ODTFB_SERVICE) && !(v->NeedsServicing() || has_manual_depot_order)) {
2549 assert(!pbs_look_ahead);
2550 UpdateVehicleTimetable(v, true);
2551 v->IncrementRealOrderIndex();
2552 break;
2555 if (v->current_order.GetDepotActionType() & ODATFB_NEAREST_DEPOT) {
2556 /* We need to search for the nearest depot (hangar). */
2557 TileIndex location;
2558 DestinationID destination;
2559 bool reverse;
2561 if (v->FindClosestDepot(&location, &destination, &reverse)) {
2562 /* PBS reservations cannot reverse */
2563 if (pbs_look_ahead && reverse) return false;
2565 v->dest_tile = location;
2566 v->current_order.MakeGoToDepot(destination, v->current_order.GetDepotOrderType(), v->current_order.GetNonStopType(), (OrderDepotActionFlags)(v->current_order.GetDepotActionType() & ~ODATFB_NEAREST_DEPOT), v->current_order.GetRefitCargo());
2568 /* If there is no depot in front, reverse automatically (trains only) */
2569 if (v->type == VEH_TRAIN && reverse) DoCommand(v->tile, v->index, 0, DC_EXEC, CMD_REVERSE_TRAIN_DIRECTION);
2571 if (v->type == VEH_AIRCRAFT) {
2572 Aircraft *a = Aircraft::From(v);
2573 if (a->state == FLYING && a->targetairport != destination) {
2574 /* The aircraft is now heading for a different hangar than the next in the orders */
2575 extern void AircraftNextAirportPos_and_Order(Aircraft *a);
2576 AircraftNextAirportPos_and_Order(a);
2579 return true;
2582 /* If there is no depot, we cannot help PBS either. */
2583 if (pbs_look_ahead) return false;
2585 UpdateVehicleTimetable(v, true);
2586 v->IncrementRealOrderIndex();
2587 } else {
2588 if (v->type != VEH_AIRCRAFT) {
2589 v->dest_tile = Depot::Get(order->GetDestination())->xy;
2591 return true;
2593 break;
2595 case OT_GOTO_WAYPOINT:
2596 v->dest_tile = Waypoint::Get(order->GetDestination())->xy;
2597 return true;
2599 case OT_CONDITIONAL: {
2600 assert(!pbs_look_ahead);
2601 VehicleOrderID next_order = ProcessConditionalOrder(order, v);
2602 if (next_order != INVALID_VEH_ORDER_ID) {
2603 /* Jump to next_order. cur_implicit_order_index becomes exactly that order,
2604 * cur_real_order_index might come after next_order. */
2605 UpdateVehicleTimetable(v, false);
2606 v->cur_implicit_order_index = v->cur_real_order_index = next_order;
2607 v->UpdateRealOrderIndex();
2608 v->cur_timetable_order_index = v->GetIndexOfOrder(order);
2610 /* Disable creation of implicit orders.
2611 * When inserting them we do not know that we would have to make the conditional orders point to them. */
2612 if (v->IsGroundVehicle()) {
2613 uint16 &gv_flags = v->GetGroundVehicleFlags();
2614 SetBit(gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS);
2616 } else {
2617 v->cur_timetable_order_index = INVALID_VEH_ORDER_ID;
2618 UpdateVehicleTimetable(v, true);
2619 v->IncrementRealOrderIndex();
2621 break;
2624 default:
2625 v->dest_tile = 0;
2626 return false;
2629 assert(v->cur_implicit_order_index < v->GetNumOrders());
2630 assert(v->cur_real_order_index < v->GetNumOrders());
2632 /* Get the current order */
2633 order = v->GetOrder(v->cur_real_order_index);
2634 if (order != nullptr && order->IsType(OT_IMPLICIT)) {
2635 assert(v->GetNumManualOrders() == 0);
2636 order = nullptr;
2639 if (order == nullptr) {
2640 v->current_order.Free();
2641 v->dest_tile = 0;
2642 return false;
2645 v->current_order = *order;
2646 return UpdateOrderDest(v, order, conditional_depth + 1, pbs_look_ahead);
2650 * Handle the orders of a vehicle and determine the next place
2651 * to go to if needed.
2652 * @param v the vehicle to do this for.
2653 * @return true *if* the vehicle is eligible for reversing
2654 * (basically only when leaving a station).
2656 bool ProcessOrders(Vehicle *v)
2658 // Check if we have an illegal manual depot order. Could happen if we deleted the depot order from the orders list after sending
2659 // the vehicle to the depot.
2660 if (HasBit(v->vehicle_flags, VF_SHOULD_GOTO_DEPOT) || HasBit(v->vehicle_flags, VF_SHOULD_SERVICE_AT_DEPOT)) {
2661 int next_depot_index = -1;
2663 for (int i = 0; i < v->GetNumOrders(); ++i) {
2664 Order* order = v->GetOrder(i);
2666 bool isRegularOrder = (order->GetDepotOrderType() & ODTFB_PART_OF_ORDERS) != 0;
2667 bool isDepotOrder = order->GetType() == OT_GOTO_DEPOT;
2669 if (isRegularOrder && isDepotOrder) {
2670 if (i >= v->cur_implicit_order_index) {
2671 next_depot_index = i;
2672 break;
2674 else if (next_depot_index < 0) {
2675 next_depot_index = i;
2680 if (next_depot_index == -1) {
2681 ClrBit(v->vehicle_flags, VF_SHOULD_GOTO_DEPOT);
2682 ClrBit(v->vehicle_flags, VF_SHOULD_SERVICE_AT_DEPOT);
2686 switch (v->current_order.GetType()) {
2687 case OT_GOTO_DEPOT:
2688 // Check whether the vehicle was manually ordered to go to the depot on its order list.
2689 // If so mark the current depot order as manual, now that we are processing it.
2690 if (HasBit(v->vehicle_flags, VF_SHOULD_GOTO_DEPOT) || HasBit(v->vehicle_flags, VF_SHOULD_SERVICE_AT_DEPOT)) {
2691 v->current_order.SetDepotOrderType(ODTF_MANUAL);
2692 v->current_order.SetDepotActionType(HasBit(v->vehicle_flags, VF_SHOULD_SERVICE_AT_DEPOT) ? ODATF_SERVICE_ONLY : ODATFB_HALT);
2695 /* Let a depot order in the order list interrupt. */
2696 if (!(v->current_order.GetDepotOrderType() & ODTFB_PART_OF_ORDERS)) return false;
2698 break;
2700 case OT_LOADING:
2701 return false;
2703 case OT_WAITING:
2704 return false;
2706 case OT_LEAVESTATION:
2707 if (v->type != VEH_AIRCRAFT) return false;
2708 break;
2710 default: break;
2714 * Reversing because of order change is allowed only just after leaving a
2715 * station (and the difficulty setting to allowed, of course)
2716 * this can be detected because only after OT_LEAVESTATION, current_order
2717 * will be reset to nothing. (That also happens if no order, but in that case
2718 * it won't hit the point in code where may_reverse is checked)
2720 bool may_reverse = v->current_order.IsType(OT_NOTHING);
2722 /* Check if we've reached a 'via' destination. */
2723 if (((v->current_order.IsType(OT_GOTO_STATION) && (v->current_order.GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION)) || v->current_order.IsType(OT_GOTO_WAYPOINT)) &&
2724 IsTileType(v->tile, MP_STATION) &&
2725 v->current_order.GetDestination() == GetStationIndex(v->tile)) {
2726 v->DeleteUnreachedImplicitOrders();
2727 /* We set the last visited station here because we do not want
2728 * the train to stop at this 'via' station if the next order
2729 * is a no-non-stop order; in that case not setting the last
2730 * visited station will cause the vehicle to still stop. */
2731 v->last_station_visited = v->current_order.GetDestination();
2732 UpdateVehicleTimetable(v, true);
2733 v->IncrementImplicitOrderIndex();
2736 /* Get the current order */
2737 assert(v->cur_implicit_order_index == 0 || v->cur_implicit_order_index < v->GetNumOrders());
2738 v->UpdateRealOrderIndex();
2740 const Order *order = v->GetOrder(v->cur_real_order_index);
2741 if (order != nullptr && order->IsType(OT_IMPLICIT)) {
2742 assert(v->GetNumManualOrders() == 0);
2743 order = nullptr;
2746 /* If no order, do nothing. */
2747 if (order == nullptr || (v->type == VEH_AIRCRAFT && !CheckForValidOrders(v))) {
2748 if (v->type == VEH_AIRCRAFT) {
2749 /* Aircraft do something vastly different here, so handle separately */
2750 extern void HandleMissingAircraftOrders(Aircraft *v);
2751 HandleMissingAircraftOrders(Aircraft::From(v));
2752 return false;
2755 v->current_order.Free();
2756 v->dest_tile = 0;
2757 return false;
2760 /* If it is unchanged, keep it. */
2761 if (order->Equals(v->current_order) && (v->type == VEH_AIRCRAFT || v->dest_tile != 0) &&
2762 (v->type != VEH_SHIP || !order->IsType(OT_GOTO_STATION) || Station::Get(order->GetDestination())->HasFacilities(FACIL_DOCK))) {
2763 return false;
2766 /* Otherwise set it, and determine the destination tile. */
2767 v->current_order = *order;
2769 InvalidateVehicleOrder(v, VIWD_MODIFY_ORDERS);
2770 switch (v->type) {
2771 default:
2772 NOT_REACHED();
2774 case VEH_ROAD:
2775 case VEH_TRAIN:
2776 break;
2778 case VEH_AIRCRAFT:
2779 case VEH_SHIP:
2780 SetWindowClassesDirty(GetWindowClassForVehicleType(v->type));
2781 break;
2784 return UpdateOrderDest(v, order) && may_reverse;
2788 * Check whether the given vehicle should stop at the given station
2789 * based on this order and the non-stop settings.
2790 * @param v the vehicle that might be stopping.
2791 * @param station the station to stop at.
2792 * @return true if the vehicle should stop.
2794 bool Order::ShouldStopAtStation(const Vehicle *v, StationID station) const
2796 bool is_dest_station = this->IsType(OT_GOTO_STATION) && this->dest == station;
2798 return (!this->IsType(OT_GOTO_DEPOT) || (this->GetDepotOrderType() & ODTFB_PART_OF_ORDERS) != 0) &&
2799 v->last_station_visited != station && // Do stop only when we've not just been there
2800 /* Finally do stop when there is no non-stop flag set for this type of station. */
2801 !(this->GetNonStopType() & (is_dest_station ? ONSF_NO_STOP_AT_DESTINATION_STATION : ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS));
2805 * A vehicle can leave the current station with cargo if:
2806 * 1. it can load cargo here OR
2807 * 2a. it could leave the last station with cargo AND
2808 * 2b. it doesn't have to unload all cargo here.
2810 bool Order::CanLeaveWithCargo(bool has_cargo, CargoID cargo) const
2812 return (this->GetCargoLoadType(cargo) & OLFB_NO_LOAD) == 0 || (has_cargo &&
2813 (this->GetCargoUnloadType(cargo) & (OUFB_UNLOAD | OUFB_TRANSFER)) == 0);