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/>.
10 /** @file order_cmd.cpp Handling of orders. */
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"
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"
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
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. */
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);
70 * @note ONLY use on "current_order" vehicle orders!
74 this->type
= OT_NOTHING
;
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
;
89 this->dest
= destination
;
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
;
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);
137 this->jump_counter
+= percent
;
142 * Makes this order a Leave Station order.
144 void Order::MakeLeaveStation()
146 this->type
= OT_LEAVESTATION
;
151 * Makes this order a Dummy order.
153 void Order::MakeDummy()
155 this->type
= OT_DUMMY
;
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
;
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;
244 if (!(this->GetDepotOrderType() & ODTFB_PART_OF_ORDERS
)) SetBit(order
, 6);
246 order
|= GB(this->GetDestination(), 0, 8) << 8;
249 if (this->GetLoadType() & OLFB_FULL_LOAD
) SetBit(order
, 6);
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
;
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
);
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
);
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
);
319 this->DeAllocExtraInfo();
323 void Order::AllocExtraInfo()
326 this->extra
.reset(new OrderExtraInfo());
330 void Order::DeAllocExtraInfo()
335 void CargoStationIDStackSet::FillNextStoppingStation(const Vehicle
*v
, const OrderList
*o
, const Order
*first
, uint hops
)
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
;
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
)
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
) {
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
)
389 for (Order
*o
= this->first
; o
!= nullptr; o
= next
) {
394 if (keep_orderlist
) {
395 this->first
= nullptr;
396 this->num_orders
= 0;
397 this->num_manual_orders
= 0;
398 this->timetable_duration
= 0;
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) {
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
;
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.
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
);
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
);
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);
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
;
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());
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
;
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
;
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
;
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;
619 to_remove
= this->first
;
620 this->first
= to_remove
->next
;
622 Order
*prev
= GetOrderAt(index
- 1);
623 to_remove
= prev
->next
;
624 prev
->next
= to_remove
->next
;
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());
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;
646 /* Take the moving order out of the pointer-chain */
648 moving_one
= this->first
;
649 this->first
= moving_one
->next
;
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 */
658 moving_one
->next
= this->first
;
659 this->first
= moving_one
;
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;
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
699 for (const Vehicle
*v_shared
= v
->PreviousShared(); v_shared
!= nullptr; v_shared
= v_shared
->PreviousShared()) 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;
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
) {
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;
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 const int num_running_vehicles
= this->GetNumRunningVehicles();
791 assert(num_running_vehicles
> 0);
793 this->current_separation
= this->GetTimetableTotalDuration() / num_running_vehicles
;
798 assert(this->num_sep_vehicles
> 0);
799 this->current_separation
= this->GetTimetableTotalDuration() / this->num_sep_vehicles
;
803 // separation is set manually -> nothing to do
806 case TTS_MODE_BUFFERED_AUTO
: {
807 int num_running_vehicles
= this->GetNumRunningVehicles();
808 assert(num_running_vehicles
> 0);
810 if (num_running_vehicles
> 1)
811 num_running_vehicles
--;
813 this->current_separation
= this->GetTimetableTotalDuration() / num_running_vehicles
;
824 * Returns the delay setting required for correct separation and increases the separation counter by 1.
825 * @return the delay setting required for correct separation. */
826 Ticks
OrderList::SeparateVehicle()
828 if (!this->is_separation_valid
|| this->current_sep_mode
== TTS_MODE_OFF
)
829 return INVALID_TICKS
;
831 UpdateSeparationTime();
833 Ticks result
= GetCurrentTickCount() - (this->separation_counter
* this->current_separation
+ this->last_timetable_init
);
834 this->IncreaseSeparationCounter();
835 if (this->separation_counter
== UINT16_MAX
) {
836 this->MarkSeparationInvalid();
843 * Returns the current separation settings.
844 * @return the current separation settings.
846 TTSepSettings
OrderList::GetSepSettings()
848 TTSepSettings result
;
850 result
.mode
= this->current_sep_mode
;
851 result
.sep_ticks
= GetSepTime();
853 // Depending on the operation mode return either the user setting or the true amount of vehicles running the timetable.
854 result
.num_veh
= (result
.mode
== TTS_MODE_MAN_N
) ? this->num_sep_vehicles
: GetNumVehicles();
859 * Sets new separation settings.
860 * @param mode Contains the operation mode that is to be used for separation.
861 * @param parameter Depending on the operation mode this contains either the number of vehicles (#TTS_MODE_MAN_N)
862 * or the time between vehicles in ticks (#TTS_MODE_MAN_T). For other modes, this is undefined.
864 void OrderList::SetSepSettings(TTSepMode mode
, uint32 parameter
)
866 this->current_sep_mode
= mode
;
868 switch (this->current_sep_mode
)
871 assert(parameter
> 0);
872 this->current_separation
= this->GetTimetableTotalDuration() / parameter
;
873 this->num_sep_vehicles
= parameter
;
877 this->current_separation
= parameter
;
878 assert(this->current_separation
> 0);
879 this->num_sep_vehicles
= this->GetTimetableTotalDuration() / this->current_separation
;
883 case TTS_MODE_BUFFERED_AUTO
:
893 this->is_separation_valid
= false;
898 * Checks whether the order goes to a station or not, i.e. whether the
899 * destination is a station
900 * @param v the vehicle to check for
901 * @param o the order to check
902 * @return true if the destination is a station
904 static inline bool OrderGoesToStation(const Vehicle
*v
, const Order
*o
)
906 return o
->IsType(OT_GOTO_STATION
) ||
907 (v
->type
== VEH_AIRCRAFT
&& o
->IsType(OT_GOTO_DEPOT
) && !(o
->GetDepotActionType() & ODATFB_NEAREST_DEPOT
));
911 * Delete all news items regarding defective orders about a vehicle
912 * This could kill still valid warnings (for example about void order when just
913 * another order gets added), but assume the company will notice the problems,
914 * when (s)he's changing the orders.
916 void DeleteOrderWarnings(const Vehicle
*v
)
918 DeleteVehicleNews(v
->index
, STR_NEWS_VEHICLE_HAS_TOO_FEW_ORDERS
);
919 DeleteVehicleNews(v
->index
, STR_NEWS_VEHICLE_HAS_VOID_ORDER
);
920 DeleteVehicleNews(v
->index
, STR_NEWS_VEHICLE_HAS_DUPLICATE_ENTRY
);
921 DeleteVehicleNews(v
->index
, STR_NEWS_VEHICLE_HAS_INVALID_ENTRY
);
922 DeleteVehicleNews(v
->index
, STR_NEWS_PLANE_USES_TOO_SHORT_RUNWAY
);
926 * Returns a tile somewhat representing the order destination (not suitable for pathfinding).
927 * @param v The vehicle to get the location for.
928 * @param airport Get the airport tile and not the station location for aircraft.
929 * @return destination of order, or INVALID_TILE if none.
931 TileIndex
Order::GetLocation(const Vehicle
*v
, bool airport
) const
933 switch (this->GetType()) {
934 case OT_GOTO_WAYPOINT
:
935 case OT_GOTO_STATION
:
937 if (airport
&& v
->type
== VEH_AIRCRAFT
) return Station::Get(this->GetDestination())->airport
.tile
;
938 return BaseStation::Get(this->GetDestination())->xy
;
941 if ((this->GetDepotActionType() & ODATFB_NEAREST_DEPOT
) != 0) return INVALID_TILE
;
942 return (v
->type
== VEH_AIRCRAFT
) ? Station::Get(this->GetDestination())->xy
: Depot::Get(this->GetDestination())->xy
;
950 * Get the distance between two orders of a vehicle. Conditional orders are resolved
951 * and the bigger distance of the two order branches is returned.
952 * @param prev Origin order.
953 * @param cur Destination order.
954 * @param v The vehicle to get the distance for.
955 * @param conditional_depth Internal param for resolving conditional orders.
956 * @return Maximum distance between the two orders.
958 uint
GetOrderDistance(const Order
*prev
, const Order
*cur
, const Vehicle
*v
, int conditional_depth
)
960 if (cur
->IsType(OT_CONDITIONAL
)) {
961 if (conditional_depth
> v
->GetNumOrders()) return 0;
965 int dist1
= GetOrderDistance(prev
, v
->GetOrder(cur
->GetConditionSkipToOrder()), v
, conditional_depth
);
966 int dist2
= GetOrderDistance(prev
, cur
->next
== nullptr ? v
->GetFirstOrder() : cur
->next
, v
, conditional_depth
);
967 return max(dist1
, dist2
);
970 TileIndex prev_tile
= prev
->GetLocation(v
, true);
971 TileIndex cur_tile
= cur
->GetLocation(v
, true);
972 if (prev_tile
== INVALID_TILE
|| cur_tile
== INVALID_TILE
) return 0;
973 return v
->type
== VEH_AIRCRAFT
? DistanceSquare(prev_tile
, cur_tile
) : DistanceManhattan(prev_tile
, cur_tile
);
977 * Add an order to the orderlist of a vehicle.
979 * @param flags operation to perform
980 * @param p1 various bitstuffed elements
981 * - p1 = (bit 0 - 19) - ID of the vehicle
982 * - p1 = (bit 24 - 31) - the selected order (if any). If the last order is given,
983 * the order will be inserted before that one
984 * the maximum vehicle order id is 254.
985 * @param p2 packed order to insert
987 * @return the cost of this operation or an error
989 CommandCost
CmdInsertOrder(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
991 VehicleID veh
= GB(p1
, 0, 20);
992 VehicleOrderID sel_ord
= GB(p1
, 20, 8);
995 Vehicle
*v
= Vehicle::GetIfValid(veh
);
996 if (v
== nullptr || !v
->IsPrimaryVehicle()) return CommandError();
998 CommandCost ret
= CheckOwnership(v
->owner
);
999 if (ret
.Failed()) return ret
;
1001 /* Check if the inserted order is to the correct destination (owner, type),
1002 * and has the correct flags if any */
1003 switch (new_order
.GetType()) {
1004 case OT_GOTO_STATION
: {
1005 const Station
*st
= Station::GetIfValid(new_order
.GetDestination());
1006 if (st
== nullptr) return CommandError();
1008 if (st
->owner
!= OWNER_NONE
) {
1009 CommandCost ret
= CheckOwnership(st
->owner
);
1010 if (ret
.Failed()) return ret
;
1013 if (!CanVehicleUseStation(v
, st
)) return CommandError(STR_ERROR_CAN_T_ADD_ORDER
);
1014 for (Vehicle
*u
= v
->FirstShared(); u
!= nullptr; u
= u
->NextShared()) {
1015 if (!CanVehicleUseStation(u
, st
)) return CommandError(STR_ERROR_CAN_T_ADD_ORDER_SHARED
);
1018 /* Non stop only allowed for ground vehicles. */
1019 if (new_order
.GetNonStopType() != ONSF_STOP_EVERYWHERE
&& !v
->IsGroundVehicle()) return CommandError();
1021 /* Filter invalid load/unload types. */
1022 switch (new_order
.GetLoadType()) {
1023 case OLF_LOAD_IF_POSSIBLE
: case OLFB_FULL_LOAD
: case OLF_FULL_LOAD_ANY
: case OLFB_NO_LOAD
: break;
1024 default: return CommandError();
1026 switch (new_order
.GetUnloadType()) {
1027 case OUF_UNLOAD_IF_POSSIBLE
: case OUFB_UNLOAD
: case OUFB_TRANSFER
: case OUFB_NO_UNLOAD
: break;
1028 default: return CommandError();
1031 /* Filter invalid stop locations */
1032 switch (new_order
.GetStopLocation()) {
1033 case OSL_PLATFORM_NEAR_END
:
1034 case OSL_PLATFORM_MIDDLE
:
1035 if (v
->type
!= VEH_TRAIN
) return CommandError();
1038 case OSL_PLATFORM_FAR_END
:
1042 return CommandError();
1048 case OT_GOTO_DEPOT
: {
1049 if ((new_order
.GetDepotActionType() & ODATFB_NEAREST_DEPOT
) == 0) {
1050 if (v
->type
== VEH_AIRCRAFT
) {
1051 const Station
*st
= Station::GetIfValid(new_order
.GetDestination());
1053 if (st
== nullptr) return CommandError();
1055 CommandCost ret
= CheckOwnership(st
->owner
);
1056 if (ret
.Failed()) return ret
;
1058 if (!CanVehicleUseStation(v
, st
) || !st
->airport
.HasHangar()) {
1059 return CommandError();
1062 const Depot
*dp
= Depot::GetIfValid(new_order
.GetDestination());
1064 if (dp
== nullptr) return CommandError();
1066 CommandCost ret
= CheckOwnership(GetTileOwner(dp
->xy
));
1067 if (ret
.Failed()) return ret
;
1071 if (!IsRailDepotTile(dp
->xy
)) return CommandError();
1075 if (!IsRoadDepotTile(dp
->xy
)) return CommandError();
1079 if (!IsShipDepotTile(dp
->xy
)) return CommandError();
1082 default: return CommandError();
1087 if (new_order
.GetNonStopType() != ONSF_STOP_EVERYWHERE
&& !v
->IsGroundVehicle()) return CommandError();
1088 if (new_order
.GetDepotOrderType() & ~(ODTFB_PART_OF_ORDERS
| ((new_order
.GetDepotOrderType() & ODTFB_PART_OF_ORDERS
) != 0 ? ODTFB_SERVICE
: 0))) return CommandError();
1089 if (new_order
.GetDepotActionType() & ~(ODATFB_HALT
| ODATFB_NEAREST_DEPOT
)) return CommandError();
1090 if ((new_order
.GetDepotOrderType() & ODTFB_SERVICE
) && (new_order
.GetDepotActionType() & ODATFB_HALT
)) return CommandError();
1094 case OT_GOTO_WAYPOINT
: {
1095 const Waypoint
*wp
= Waypoint::GetIfValid(new_order
.GetDestination());
1096 if (wp
== nullptr) return CommandError();
1099 default: return CommandError();
1102 if (!(wp
->facilities
& FACIL_TRAIN
)) return CommandError(STR_ERROR_CAN_T_ADD_ORDER
);
1104 CommandCost ret
= CheckOwnership(wp
->owner
);
1105 if (ret
.Failed()) return ret
;
1110 if (!(wp
->facilities
& FACIL_DOCK
)) return CommandError(STR_ERROR_CAN_T_ADD_ORDER
);
1111 if (wp
->owner
!= OWNER_NONE
) {
1112 CommandCost ret
= CheckOwnership(wp
->owner
);
1113 if (ret
.Failed()) return ret
;
1118 /* Order flags can be any of the following for waypoints:
1120 * non-stop orders (if any) are only valid for trains */
1121 if (new_order
.GetNonStopType() != ONSF_STOP_EVERYWHERE
&& v
->type
!= VEH_TRAIN
) return CommandError();
1125 case OT_CONDITIONAL
: {
1126 VehicleOrderID skip_to
= new_order
.GetConditionSkipToOrder();
1127 if (skip_to
!= 0 && skip_to
>= v
->GetNumOrders()) return CommandError(); // Always allow jumping to the first (even when there is no order).
1128 if (new_order
.GetConditionVariable() >= OCV_END
) return CommandError();
1130 OrderConditionComparator occ
= new_order
.GetConditionComparator();
1131 if (occ
>= OCC_END
) return CommandError();
1132 switch (new_order
.GetConditionVariable()) {
1133 case OCV_SLOT_OCCUPANCY
: {
1134 TraceRestrictSlotID slot
= new_order
.GetXData();
1135 if (slot
!= INVALID_TRACE_RESTRICT_SLOT_ID
&& !TraceRestrictSlot::IsValidID(slot
)) return CommandError();
1136 if (occ
!= OCC_IS_TRUE
&& occ
!= OCC_IS_FALSE
) return CommandError();
1139 case OCV_CARGO_WAITING
:
1140 case OCV_CARGO_ACCEPTANCE
:
1141 if (!CargoSpec::Get(new_order
.GetConditionValue())->IsValid()) return CommandError();
1144 case OCV_REQUIRES_SERVICE
:
1145 if (occ
!= OCC_IS_TRUE
&& occ
!= OCC_IS_FALSE
) return CommandError();
1148 case OCV_UNCONDITIONALLY
:
1149 if (occ
!= OCC_EQUALS
) return CommandError();
1150 if (new_order
.GetConditionValue() != 0) return CommandError();
1153 case OCV_FREE_PLATFORMS
:
1154 if (v
->type
!= VEH_TRAIN
) return CommandError();
1155 if (occ
== OCC_IS_TRUE
|| occ
== OCC_IS_FALSE
) return CommandError();
1159 if (occ
!= OCC_EQUALS
) return CommandError();
1162 case OCV_LOAD_PERCENTAGE
:
1163 case OCV_RELIABILITY
:
1164 if (new_order
.GetConditionValue() > 100) return CommandError();
1168 if (occ
== OCC_IS_TRUE
|| occ
== OCC_IS_FALSE
) return CommandError();
1174 default: return CommandError();
1177 if (sel_ord
> v
->GetNumOrders()) return CommandError();
1179 if (v
->GetNumOrders() >= MAX_VEH_ORDER_ID
) return CommandError(STR_ERROR_TOO_MANY_ORDERS
);
1180 if (!Order::CanAllocateItem()) return CommandError(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS
);
1181 if (!v
->HasOrdersList() && !OrderList::CanAllocateItem()) return CommandError(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS
);
1183 if (v
->type
== VEH_SHIP
&& _settings_game
.pf
.pathfinder_for_ships
!= VPF_NPF
) {
1184 /* Make sure the new destination is not too far away from the previous */
1185 const Order
*prev
= nullptr;
1188 /* Find the last goto station or depot order before the insert location.
1189 * If the order is to be inserted at the beginning of the order list this
1190 * finds the last order in the list. */
1192 FOR_VEHICLE_ORDERS(v
, o
) {
1193 switch (o
->GetType()) {
1194 case OT_GOTO_STATION
:
1196 case OT_GOTO_WAYPOINT
:
1202 if (++n
== sel_ord
&& prev
!= nullptr) break;
1204 if (prev
!= nullptr) {
1206 if (new_order
.IsType(OT_CONDITIONAL
)) {
1207 /* The order is not yet inserted, so we have to do the first iteration here. */
1208 dist
= GetOrderDistance(prev
, v
->GetOrder(new_order
.GetConditionSkipToOrder()), v
);
1210 dist
= GetOrderDistance(prev
, &new_order
, v
);
1214 return CommandError(STR_ERROR_TOO_FAR_FROM_PREVIOUS_DESTINATION
);
1219 if (flags
& DC_EXEC
) {
1220 Order
*new_o
= new Order();
1221 new_o
->AssignOrder(new_order
);
1222 InsertOrder(v
, new_o
, sel_ord
);
1223 CheckMarkDirtyFocusedRoutePaths(v
);
1226 return CommandCost();
1230 * Insert a new order but skip the validation.
1231 * @param v The vehicle to insert the order to.
1232 * @param new_o The new order.
1233 * @param sel_ord The position the order should be inserted at.
1235 void InsertOrder(Vehicle
*v
, Order
*new_o
, VehicleOrderID sel_ord
)
1237 /* Create new order and link in list */
1238 if (!v
->HasOrdersList()) {
1239 v
->SetOrdersList(new OrderList(new_o
, v
));
1241 v
->InsertOrderAt(new_o
, sel_ord
);
1244 Vehicle
*u
= v
->FirstShared();
1245 DeleteOrderWarnings(u
);
1246 for (; u
!= nullptr; u
= u
->NextShared()) {
1247 assert(v
->IsSharingOrdersWith(u
));
1249 /* If there is added an order before the current one, we need
1250 * to update the selected order. We do not change implicit/real order indices though.
1251 * If the new order is between the current implicit order and real order, the implicit order will
1252 * later skip the inserted order. */
1253 if (sel_ord
<= u
->cur_real_order_index
) {
1254 uint cur
= u
->cur_real_order_index
+ 1;
1255 /* Check if we don't go out of bound */
1256 if (cur
< u
->GetNumOrders()) {
1257 u
->cur_real_order_index
= cur
;
1260 if (sel_ord
== u
->cur_implicit_order_index
&& u
->IsGroundVehicle()) {
1261 /* We are inserting an order just before the current implicit order.
1262 * We do not know whether we will reach current implicit or the newly inserted order first.
1263 * So, disable creation of implicit orders until we are on track again. */
1264 uint16
&gv_flags
= u
->GetGroundVehicleFlags();
1265 SetBit(gv_flags
, GVF_SUPPRESS_IMPLICIT_ORDERS
);
1267 if (sel_ord
<= u
->cur_implicit_order_index
) {
1268 uint cur
= u
->cur_implicit_order_index
+ 1;
1269 /* Check if we don't go out of bound */
1270 if (cur
< u
->GetNumOrders()) {
1271 u
->cur_implicit_order_index
= cur
;
1274 if (u
->cur_timetable_order_index
!= INVALID_VEH_ORDER_ID
&& sel_ord
<= u
->cur_timetable_order_index
) {
1275 uint cur
= u
->cur_timetable_order_index
+ 1;
1276 /* Check if we don't go out of bound */
1277 if (cur
< u
->GetNumOrders()) {
1278 u
->cur_timetable_order_index
= cur
;
1281 /* Update any possible open window of the vehicle */
1282 InvalidateVehicleOrder(u
, INVALID_VEH_ORDER_ID
| (sel_ord
<< 8));
1285 /* As we insert an order, the order to skip to will be 'wrong'. */
1286 VehicleOrderID cur_order_id
= 0;
1288 FOR_VEHICLE_ORDERS(v
, order
) {
1289 if (order
->IsType(OT_CONDITIONAL
)) {
1290 VehicleOrderID order_id
= order
->GetConditionSkipToOrder();
1291 if (order_id
>= sel_ord
) {
1292 order
->SetConditionSkipToOrder(order_id
+ 1);
1294 if (order_id
== cur_order_id
) {
1295 order
->SetConditionSkipToOrder((order_id
+ 1) % v
->GetNumOrders());
1301 /* Make sure to rebuild the whole list */
1302 InvalidateWindowClassesData(GetWindowClassForVehicleType(v
->type
), 0);
1306 * Declone an order-list
1307 * @param *dst delete the orders of this vehicle
1308 * @param flags execution flags
1310 static CommandCost
DecloneOrder(Vehicle
*dst
, DoCommandFlag flags
)
1312 if (flags
& DC_EXEC
) {
1313 dst
->DeleteVehicleOrders();
1314 InvalidateVehicleOrder(dst
, VIWD_REMOVE_ALL_ORDERS
);
1315 InvalidateWindowClassesData(GetWindowClassForVehicleType(dst
->type
), 0);
1316 CheckMarkDirtyFocusedRoutePaths(dst
);
1318 return CommandCost();
1322 * Get the first cargoID that points to a valid cargo (usually 0)
1324 static CargoID
GetFirstValidCargo()
1326 for (CargoID i
= 0; i
< NUM_CARGO
; i
++) {
1327 if (CargoSpec::Get(i
)->IsValid()) return i
;
1329 /* No cargoes defined -> 'Houston, we have a problem!' */
1331 /* Return something to avoid compiler warning */
1336 * Get the first valid TraceRestrictSlot. Or INVALID_TRACE_RESTRICT_SLOT_ID if no slots are defined.
1338 static TraceRestrictSlotID
GetFirstValidTraceRestrictSlot()
1340 const TraceRestrictSlot
* slot
;
1341 FOR_ALL_TRACE_RESTRICT_SLOTS(slot
)
1343 // Stupid way to get the first valid slot but there is no "GetFirstValidSlot()".
1347 return INVALID_TRACE_RESTRICT_SLOT_ID
;
1351 * Delete an order from the orderlist of a vehicle.
1352 * @param tile unused
1353 * @param flags operation to perform
1354 * @param p1 the ID of the vehicle
1355 * @param p2 the order to delete (max 255)
1356 * @param text unused
1357 * @return the cost of this operation or an error
1359 CommandCost
CmdDeleteOrder(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1361 VehicleID veh_id
= GB(p1
, 0, 20);
1362 VehicleOrderID sel_ord
= GB(p2
, 0, 8);
1364 Vehicle
*v
= Vehicle::GetIfValid(veh_id
);
1366 if (v
== nullptr || !v
->IsPrimaryVehicle()) return CommandError();
1368 CommandCost ret
= CheckOwnership(v
->owner
);
1369 if (ret
.Failed()) return ret
;
1371 /* If we did not select an order, we maybe want to de-clone the orders */
1372 if (sel_ord
>= v
->GetNumOrders()) return DecloneOrder(v
, flags
);
1374 if (v
->GetOrder(sel_ord
) == nullptr) return CommandError();
1376 if (flags
& DC_EXEC
) {
1377 DeleteOrder(v
, sel_ord
);
1378 CheckMarkDirtyFocusedRoutePaths(v
);
1380 return CommandCost();
1384 * Cancel the current loading order of the vehicle as the order was deleted.
1385 * @param v the vehicle
1387 void CancelLoadingDueToDeletedOrder(Vehicle
*v
)
1389 assert(v
->current_order
.IsType(OT_LOADING
));
1390 /* NON-stop flag is misused to see if a train is in a station that is
1391 * on his order list or not */
1392 v
->current_order
.SetNonStopType(ONSF_STOP_EVERYWHERE
);
1393 /* When full loading, "cancel" that order so the vehicle doesn't
1394 * stay indefinitely at this station anymore. */
1395 if (v
->current_order
.GetLoadType() & OLFB_FULL_LOAD
) v
->current_order
.SetLoadType(OLF_LOAD_IF_POSSIBLE
);
1399 * Delete an order but skip the parameter validation.
1400 * @param v The vehicle to delete the order from.
1401 * @param sel_ord The id of the order to be deleted.
1403 void DeleteOrder(Vehicle
*v
, VehicleOrderID sel_ord
)
1405 v
->DeleteOrderAt(sel_ord
);
1407 Vehicle
*u
= v
->FirstShared();
1408 DeleteOrderWarnings(u
);
1409 for (; u
!= nullptr; u
= u
->NextShared()) {
1410 assert(v
->IsSharingOrdersWith(u
));
1412 if (sel_ord
== u
->cur_real_order_index
&& u
->current_order
.IsType(OT_LOADING
)) {
1413 CancelLoadingDueToDeletedOrder(u
);
1416 if (sel_ord
< u
->cur_real_order_index
) {
1417 u
->cur_real_order_index
--;
1418 } else if (sel_ord
== u
->cur_real_order_index
) {
1419 u
->UpdateRealOrderIndex();
1422 if (sel_ord
< u
->cur_implicit_order_index
) {
1423 u
->cur_implicit_order_index
--;
1424 } else if (sel_ord
== u
->cur_implicit_order_index
) {
1425 /* Make sure the index is valid */
1426 if (u
->cur_implicit_order_index
>= u
->GetNumOrders()) u
->cur_implicit_order_index
= 0;
1428 /* Skip non-implicit orders for the implicit-order-index (e.g. if the current implicit order was deleted */
1429 while (u
->cur_implicit_order_index
!= u
->cur_real_order_index
&& !u
->GetOrder(u
->cur_implicit_order_index
)->IsType(OT_IMPLICIT
)) {
1430 u
->cur_implicit_order_index
++;
1431 if (u
->cur_implicit_order_index
>= u
->GetNumOrders()) u
->cur_implicit_order_index
= 0;
1435 if (u
->cur_timetable_order_index
!= INVALID_VEH_ORDER_ID
) {
1436 if (sel_ord
< u
->cur_timetable_order_index
) {
1437 u
->cur_timetable_order_index
--;
1438 } else if (sel_ord
== u
->cur_timetable_order_index
) {
1439 u
->cur_timetable_order_index
= INVALID_VEH_ORDER_ID
;
1443 /* Update any possible open window of the vehicle */
1444 InvalidateVehicleOrder(u
, sel_ord
| (INVALID_VEH_ORDER_ID
<< 8));
1447 /* As we delete an order, the order to skip to will be 'wrong'. */
1448 VehicleOrderID cur_order_id
= 0;
1449 Order
*order
= nullptr;
1450 FOR_VEHICLE_ORDERS(v
, order
) {
1451 if (order
->IsType(OT_CONDITIONAL
)) {
1452 VehicleOrderID order_id
= order
->GetConditionSkipToOrder();
1453 if (order_id
>= sel_ord
) {
1454 order_id
= max(order_id
- 1, 0);
1456 if (order_id
== cur_order_id
) {
1457 order_id
= (order_id
+ 1) % v
->GetNumOrders();
1459 order
->SetConditionSkipToOrder(order_id
);
1464 InvalidateWindowClassesData(GetWindowClassForVehicleType(v
->type
), 0);
1465 CheckMarkDirtyFocusedRoutePaths(v
);
1469 * Goto order of order-list.
1470 * @param tile unused
1471 * @param flags operation to perform
1472 * @param p1 The ID of the vehicle which order is skipped
1473 * @param p2 the selected order to which we want to skip
1474 * @param text unused
1475 * @return the cost of this operation or an error
1477 CommandCost
CmdSkipToOrder(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1479 VehicleID veh_id
= GB(p1
, 0, 20);
1480 VehicleOrderID sel_ord
= GB(p2
, 0, 8);
1482 Vehicle
*v
= Vehicle::GetIfValid(veh_id
);
1484 if (v
== nullptr || !v
->IsPrimaryVehicle() || sel_ord
== v
->cur_implicit_order_index
|| sel_ord
>= v
->GetNumOrders() || v
->GetNumOrders() < 2) return CommandError();
1486 CommandCost ret
= CheckOwnership(v
->owner
);
1487 if (ret
.Failed()) return ret
;
1489 if (flags
& DC_EXEC
) {
1490 if (v
->current_order
.IsType(OT_LOADING
)) v
->LeaveStation();
1491 if (v
->current_order
.IsType(OT_WAITING
)) v
->HandleWaiting(true);
1493 v
->cur_implicit_order_index
= v
->cur_real_order_index
= sel_ord
;
1494 v
->UpdateRealOrderIndex();
1495 v
->cur_timetable_order_index
= INVALID_VEH_ORDER_ID
;
1497 InvalidateVehicleOrder(v
, VIWD_MODIFY_ORDERS
);
1500 /* We have an aircraft/ship, they have a mini-schedule, so update them all */
1501 if (v
->type
== VEH_AIRCRAFT
) SetWindowClassesDirty(WC_AIRCRAFT_LIST
);
1502 if (v
->type
== VEH_SHIP
) SetWindowClassesDirty(WC_SHIPS_LIST
);
1504 return CommandCost();
1508 * Move an order inside the orderlist
1509 * @param tile unused
1510 * @param flags operation to perform
1511 * @param p1 the ID of the vehicle
1512 * @param p2 order to move and target
1513 * bit 0-15 : the order to move
1514 * bit 16-31 : the target order
1515 * @param text unused
1516 * @return the cost of this operation or an error
1517 * @note The target order will move one place down in the orderlist
1518 * if you move the order upwards else it'll move it one place down
1520 CommandCost
CmdMoveOrder(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1522 VehicleID veh
= GB(p1
, 0, 20);
1523 VehicleOrderID moving_order
= GB(p2
, 0, 16);
1524 VehicleOrderID target_order
= GB(p2
, 16, 16);
1526 Vehicle
*v
= Vehicle::GetIfValid(veh
);
1527 if (v
== nullptr || !v
->IsPrimaryVehicle()) return CommandError();
1529 CommandCost ret
= CheckOwnership(v
->owner
);
1530 if (ret
.Failed()) return ret
;
1532 /* Don't make senseless movements */
1533 if (moving_order
>= v
->GetNumOrders() || target_order
>= v
->GetNumOrders() ||
1534 moving_order
== target_order
|| v
->GetNumOrders() <= 1) return CommandError();
1536 Order
*moving_one
= v
->GetOrder(moving_order
);
1537 /* Don't move an empty order */
1538 if (moving_one
== nullptr) return CommandError();
1540 if (flags
& DC_EXEC
) {
1541 v
->MoveOrder(moving_order
, target_order
);
1543 /* Update shared list */
1544 Vehicle
*u
= v
->FirstShared();
1546 DeleteOrderWarnings(u
);
1548 for (; u
!= nullptr; u
= u
->NextShared()) {
1549 /* Update the current order.
1550 * There are multiple ways to move orders, which result in cur_implicit_order_index
1551 * and cur_real_order_index to not longer make any sense. E.g. moving another
1552 * real order between them.
1554 * Basically one could choose to preserve either of them, but not both.
1555 * While both ways are suitable in this or that case from a human point of view, neither
1556 * of them makes really sense.
1557 * However, from an AI point of view, preserving cur_real_order_index is the most
1558 * predictable and transparent behaviour.
1560 * With that decision it basically does not matter what we do to cur_implicit_order_index.
1561 * If we change orders between the implicit- and real-index, the implicit orders are mostly likely
1562 * completely out-dated anyway. So, keep it simple and just keep cur_implicit_order_index as well.
1563 * The worst which can happen is that a lot of implicit orders are removed when reaching current_order.
1565 if (u
->cur_real_order_index
== moving_order
) {
1566 u
->cur_real_order_index
= target_order
;
1567 } else if (u
->cur_real_order_index
> moving_order
&& u
->cur_real_order_index
<= target_order
) {
1568 u
->cur_real_order_index
--;
1569 } else if (u
->cur_real_order_index
< moving_order
&& u
->cur_real_order_index
>= target_order
) {
1570 u
->cur_real_order_index
++;
1573 if (u
->cur_implicit_order_index
== moving_order
) {
1574 u
->cur_implicit_order_index
= target_order
;
1575 } else if (u
->cur_implicit_order_index
> moving_order
&& u
->cur_implicit_order_index
<= target_order
) {
1576 u
->cur_implicit_order_index
--;
1577 } else if (u
->cur_implicit_order_index
< moving_order
&& u
->cur_implicit_order_index
>= target_order
) {
1578 u
->cur_implicit_order_index
++;
1581 u
->cur_timetable_order_index
= INVALID_VEH_ORDER_ID
;
1583 assert(v
->IsSharingOrdersWith(u
));
1585 /* Update any possible open window of the vehicle */
1586 InvalidateVehicleOrder(u
, moving_order
| (target_order
<< 8));
1589 /* As we move an order, the order to skip to will be 'wrong'. */
1591 FOR_VEHICLE_ORDERS(v
, order
) {
1592 if (order
->IsType(OT_CONDITIONAL
)) {
1593 VehicleOrderID order_id
= order
->GetConditionSkipToOrder();
1594 if (order_id
== moving_order
) {
1595 order_id
= target_order
;
1596 } else if (order_id
> moving_order
&& order_id
<= target_order
) {
1598 } else if (order_id
< moving_order
&& order_id
>= target_order
) {
1601 order
->SetConditionSkipToOrder(order_id
);
1605 /* Make sure to rebuild the whole list */
1606 InvalidateWindowClassesData(GetWindowClassForVehicleType(v
->type
), 0);
1609 return CommandCost();
1613 * Modify an order in the orderlist of a vehicle.
1614 * @param tile unused
1615 * @param flags operation to perform
1616 * @param p1 various bitstuffed elements
1617 * - p1 = (bit 0 - 19) - ID of the vehicle
1618 * - p1 = (bit 20 - 27) - the selected order (if any). If the last order is given,
1619 * the order will be inserted before that one
1620 * the maximum vehicle order id is 254.
1621 * @param p2 various bitstuffed elements
1622 * - p2 = (bit 0 - 3) - what data to modify (@see ModifyOrderFlags)
1623 * - p2 = (bit 4 - 19) - the data to modify
1624 * - p2 = (bit 20 - 27) - a CargoID for cargo type orders (MOF_CARGO_TYPE_UNLOAD or MOF_CARGO_TYPE_LOAD)
1625 * @param text unused
1626 * @return the cost of this operation or an error
1628 CommandCost
CmdModifyOrder(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1630 VehicleOrderID sel_ord
= GB(p1
, 20, 8);
1631 VehicleID veh
= GB(p1
, 0, 20);
1632 ModifyOrderFlags mof
= Extract
<ModifyOrderFlags
, 0, 4>(p2
);
1633 uint16 data
= GB(p2
, 4, 16);
1634 CargoID cargo_id
= (mof
== MOF_CARGO_TYPE_UNLOAD
|| mof
== MOF_CARGO_TYPE_LOAD
) ? (CargoID
)GB(p2
, 20, 8) : (CargoID
)CT_INVALID
;
1636 if (mof
>= MOF_END
) return CommandError();
1638 Vehicle
*v
= Vehicle::GetIfValid(veh
);
1639 if (v
== nullptr || !v
->IsPrimaryVehicle()) return CommandError();
1641 CommandCost ret
= CheckOwnership(v
->owner
);
1642 if (ret
.Failed()) return ret
;
1644 /* Is it a valid order? */
1645 if (sel_ord
>= v
->GetNumOrders()) return CommandError();
1647 Order
*order
= v
->GetOrder(sel_ord
);
1648 switch (order
->GetType()) {
1649 case OT_GOTO_STATION
:
1650 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();
1654 if (mof
!= MOF_NON_STOP
&& mof
!= MOF_DEPOT_ACTION
) return CommandError();
1657 case OT_GOTO_WAYPOINT
:
1658 if (mof
!= MOF_NON_STOP
&& mof
!= MOF_WAYPOINT_FLAGS
) return CommandError();
1661 case OT_CONDITIONAL
:
1662 if (mof
!= MOF_COND_VARIABLE
&& mof
!= MOF_COND_COMPARATOR
&& mof
!= MOF_COND_VALUE
&& mof
!= MOF_COND_DESTINATION
) return CommandError();
1666 return CommandError();
1670 default: NOT_REACHED();
1673 if (!v
->IsGroundVehicle()) return CommandError();
1674 if (data
>= ONSF_END
) return CommandError();
1675 if (data
== order
->GetNonStopType()) return CommandError();
1678 case MOF_STOP_LOCATION
:
1679 if (v
->type
!= VEH_TRAIN
) return CommandError();
1680 if (data
>= OSL_END
) return CommandError();
1683 case MOF_CARGO_TYPE_UNLOAD
:
1684 if (cargo_id
>= NUM_CARGO
) return CommandError();
1685 if (data
== OUFB_CARGO_TYPE_UNLOAD
) return CommandError();
1688 if (order
->GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION
) return CommandError();
1689 if ((data
& ~(OUFB_UNLOAD
| OUFB_TRANSFER
| OUFB_NO_UNLOAD
| OUFB_CARGO_TYPE_UNLOAD
)) != 0) return CommandError();
1690 /* Unload and no-unload are mutual exclusive and so are transfer and no unload. */
1691 if (data
!= 0 && (data
& OUFB_CARGO_TYPE_UNLOAD
) == 0 && ((data
& (OUFB_UNLOAD
| OUFB_TRANSFER
)) != 0) == ((data
& OUFB_NO_UNLOAD
) != 0)) return CommandError();
1692 /* Cargo-type-unload exclude all the other flags. */
1693 if ((data
& OUFB_CARGO_TYPE_UNLOAD
) != 0 && data
!= OUFB_CARGO_TYPE_UNLOAD
) return CommandError();
1694 if (data
== order
->GetUnloadType()) return CommandError();
1697 case MOF_CARGO_TYPE_LOAD
:
1698 if (cargo_id
>= NUM_CARGO
) return CommandError();
1699 if (data
== OLFB_CARGO_TYPE_LOAD
|| data
== OLF_FULL_LOAD_ANY
) return CommandError();
1702 if (order
->GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION
) return CommandError();
1703 if ((data
> OLFB_NO_LOAD
&& data
!= OLFB_CARGO_TYPE_LOAD
) || data
== 1) return CommandError();
1704 if (data
== order
->GetLoadType()) return CommandError();
1707 case MOF_DEPOT_ACTION
:
1708 if (data
>= DA_END
) return CommandError();
1711 case MOF_COND_VARIABLE
:
1712 if (data
== OCV_FREE_PLATFORMS
&& v
->type
!= VEH_TRAIN
) return CommandError();
1713 if (data
>= OCV_END
) return CommandError();
1716 case MOF_COND_COMPARATOR
:
1717 if (data
>= OCC_END
) return CommandError();
1718 switch (order
->GetConditionVariable()) {
1719 case OCV_UNCONDITIONALLY
:
1721 return CommandError();
1723 case OCV_REQUIRES_SERVICE
:
1724 case OCV_CARGO_ACCEPTANCE
:
1725 case OCV_CARGO_WAITING
:
1726 case OCV_SLOT_OCCUPANCY
:
1727 if (data
!= OCC_IS_TRUE
&& data
!= OCC_IS_FALSE
) return CommandError();
1731 if (data
== OCC_IS_TRUE
|| data
== OCC_IS_FALSE
) return CommandError();
1736 case MOF_COND_VALUE
:
1737 switch (order
->GetConditionVariable()) {
1738 case OCV_UNCONDITIONALLY
:
1739 case OCV_REQUIRES_SERVICE
:
1740 return CommandError();
1742 case OCV_LOAD_PERCENTAGE
:
1743 case OCV_RELIABILITY
:
1745 if (data
> 100) return CommandError();
1748 case OCV_SLOT_OCCUPANCY
:
1749 if (data
!= INVALID_TRACE_RESTRICT_SLOT_ID
&& !TraceRestrictSlot::IsValidID(data
)) return CommandError();
1752 case OCV_CARGO_ACCEPTANCE
:
1753 case OCV_CARGO_WAITING
:
1754 if (!(data
< NUM_CARGO
&& CargoSpec::Get(data
)->IsValid())) return CommandError();
1758 if (data
> 2047) return CommandError();
1763 case MOF_COND_DESTINATION
:
1764 if (data
>= v
->GetNumOrders()) return CommandError();
1767 case MOF_WAYPOINT_FLAGS
:
1768 if (data
!= (data
& OWF_REVERSE
)) return CommandError();
1772 if (flags
& DC_EXEC
) {
1775 order
->SetNonStopType((OrderNonStopFlags
)data
);
1776 if (data
& ONSF_NO_STOP_AT_DESTINATION_STATION
) {
1777 order
->SetRefit(CT_NO_REFIT
);
1778 order
->SetLoadType(OLF_LOAD_IF_POSSIBLE
);
1779 order
->SetUnloadType(OUF_UNLOAD_IF_POSSIBLE
);
1783 case MOF_STOP_LOCATION
:
1784 order
->SetStopLocation((OrderStopLocation
)data
);
1788 order
->SetUnloadType((OrderUnloadFlags
)data
);
1791 case MOF_CARGO_TYPE_UNLOAD
:
1792 order
->SetUnloadType((OrderUnloadFlags
)data
, cargo_id
);
1796 order
->SetLoadType((OrderLoadFlags
)data
);
1797 if (data
& OLFB_NO_LOAD
) order
->SetRefit(CT_NO_REFIT
);
1800 case MOF_CARGO_TYPE_LOAD
:
1801 order
->SetLoadType((OrderLoadFlags
)data
, cargo_id
);
1804 case MOF_DEPOT_ACTION
: {
1807 order
->SetDepotOrderType((OrderDepotTypeFlags
)(order
->GetDepotOrderType() & ~ODTFB_SERVICE
));
1808 order
->SetDepotActionType((OrderDepotActionFlags
)(order
->GetDepotActionType() & ~ODATFB_HALT
));
1812 order
->SetDepotOrderType((OrderDepotTypeFlags
)(order
->GetDepotOrderType() | ODTFB_SERVICE
));
1813 order
->SetDepotActionType((OrderDepotActionFlags
)(order
->GetDepotActionType() & ~ODATFB_HALT
));
1814 order
->SetRefit(CT_NO_REFIT
);
1818 order
->SetDepotOrderType((OrderDepotTypeFlags
)(order
->GetDepotOrderType() & ~ODTFB_SERVICE
));
1819 order
->SetDepotActionType((OrderDepotActionFlags
)(order
->GetDepotActionType() | ODATFB_HALT
));
1820 order
->SetRefit(CT_NO_REFIT
);
1829 case MOF_COND_VARIABLE
: {
1830 /* Check whether old conditional variable had a cargo as value */
1831 bool old_var_was_cargo
= (order
->GetConditionVariable() == OCV_CARGO_ACCEPTANCE
|| order
->GetConditionVariable() == OCV_CARGO_WAITING
);
1832 bool old_var_was_slot
= (order
->GetConditionVariable() == OCV_SLOT_OCCUPANCY
);
1833 order
->SetConditionVariable((OrderConditionVariable
)data
);
1835 OrderConditionComparator occ
= order
->GetConditionComparator();
1836 switch (order
->GetConditionVariable()) {
1837 case OCV_UNCONDITIONALLY
:
1838 order
->SetConditionComparator(OCC_EQUALS
);
1839 order
->SetConditionValue(0);
1842 case OCV_SLOT_OCCUPANCY
:
1843 if (!old_var_was_slot
) order
->GetXDataRef() = INVALID_TRACE_RESTRICT_SLOT_ID
;
1844 if (occ
!= OCC_IS_TRUE
&& occ
!= OCC_IS_FALSE
) order
->SetConditionComparator(OCC_IS_TRUE
);
1847 case OCV_CARGO_ACCEPTANCE
:
1848 case OCV_CARGO_WAITING
:
1849 if (!old_var_was_cargo
) order
->SetConditionValue((uint16
) GetFirstValidCargo());
1850 if (occ
!= OCC_IS_TRUE
&& occ
!= OCC_IS_FALSE
) order
->SetConditionComparator(OCC_IS_TRUE
);
1853 case OCV_REQUIRES_SERVICE
:
1854 if (old_var_was_cargo
|| old_var_was_slot
) order
->SetConditionValue(0);
1855 if (occ
!= OCC_IS_TRUE
&& occ
!= OCC_IS_FALSE
) order
->SetConditionComparator(OCC_IS_TRUE
);
1856 order
->SetConditionValue(0);
1860 order
->SetConditionComparator(OCC_EQUALS
);
1863 case OCV_LOAD_PERCENTAGE
:
1864 case OCV_RELIABILITY
:
1865 if (order
->GetConditionValue() > 100) order
->SetConditionValue(100);
1869 if (old_var_was_cargo
|| old_var_was_slot
) order
->SetConditionValue(0);
1870 if (occ
== OCC_IS_TRUE
|| occ
== OCC_IS_FALSE
) order
->SetConditionComparator(OCC_EQUALS
);
1876 case MOF_COND_COMPARATOR
:
1877 order
->SetConditionComparator((OrderConditionComparator
)data
);
1880 case MOF_COND_VALUE
:
1881 switch (order
->GetConditionVariable()) {
1882 case OCV_SLOT_OCCUPANCY
:
1883 order
->GetXDataRef() = data
;
1887 order
->SetConditionValue(data
);
1892 case MOF_COND_DESTINATION
:
1893 order
->SetConditionSkipToOrder(data
);
1896 case MOF_WAYPOINT_FLAGS
:
1897 order
->SetWaypointFlags((OrderWaypointFlags
)data
);
1900 default: NOT_REACHED();
1903 /* Update the windows and full load flags, also for vehicles that share the same order list */
1904 Vehicle
*u
= v
->FirstShared();
1905 DeleteOrderWarnings(u
);
1906 for (; u
!= nullptr; u
= u
->NextShared()) {
1907 /* Toggle u->current_order "Full load" flag if it changed.
1908 * However, as the same flag is used for depot orders, check
1909 * whether we are not going to a depot as there are three
1910 * cases where the full load flag can be active and only
1911 * one case where the flag is used for depot orders. In the
1912 * other cases for the OrderTypeByte the flags are not used,
1913 * so do not care and those orders should not be active
1914 * when this function is called.
1916 if (sel_ord
== u
->cur_real_order_index
&&
1917 (u
->current_order
.IsType(OT_GOTO_STATION
) || u
->current_order
.IsType(OT_LOADING
)) &&
1918 u
->current_order
.GetLoadType() != order
->GetLoadType()) {
1919 u
->current_order
.SetLoadType(order
->GetLoadType());
1921 InvalidateVehicleOrder(u
, VIWD_MODIFY_ORDERS
);
1923 CheckMarkDirtyFocusedRoutePaths(v
);
1926 return CommandCost();
1930 * Check if an aircraft has enough range for an order list.
1931 * @param v_new Aircraft to check.
1932 * @param v_order Vehicle currently holding the order list.
1933 * @param first First order in the source order list.
1934 * @return True if the aircraft has enough range for the orders, false otherwise.
1936 static bool CheckAircraftOrderDistance(const Aircraft
*v_new
, const Vehicle
*v_order
, const Order
*first
)
1938 if (first
== nullptr || v_new
->acache
.cached_max_range
== 0) return true;
1940 /* Iterate over all orders to check the distance between all
1941 * 'goto' orders and their respective next order (of any type). */
1942 for (const Order
*o
= first
; o
!= nullptr; o
= o
->next
) {
1943 switch (o
->GetType()) {
1944 case OT_GOTO_STATION
:
1946 case OT_GOTO_WAYPOINT
:
1947 /* If we don't have a next order, we've reached the end and must check the first order instead. */
1948 if (GetOrderDistance(o
, o
->next
!= nullptr ? o
->next
: first
, v_order
) > v_new
->acache
.cached_max_range_sqr
) return false;
1959 * Clone/share/copy an order-list of another vehicle.
1960 * @param tile unused
1961 * @param flags operation to perform
1962 * @param p1 various bitstuffed elements
1963 * - p1 = (bit 0-19) - destination vehicle to clone orders to
1964 * - p1 = (bit 30-31) - action to perform
1965 * @param p2 source vehicle to clone orders from, if any (none for CO_UNSHARE)
1966 * @param text unused
1967 * @return the cost of this operation or an error
1969 CommandCost
CmdCloneOrder(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1971 VehicleID veh_src
= GB(p2
, 0, 20);
1972 VehicleID veh_dst
= GB(p1
, 0, 20);
1974 Vehicle
*dst
= Vehicle::GetIfValid(veh_dst
);
1975 if (dst
== nullptr || !dst
->IsPrimaryVehicle()) return CommandError();
1977 CommandCost ret
= CheckOwnership(dst
->owner
);
1978 if (ret
.Failed()) return ret
;
1980 switch (GB(p1
, 30, 2)) {
1982 Vehicle
*src
= Vehicle::GetIfValid(veh_src
);
1985 if (src
== nullptr || !src
->IsPrimaryVehicle() || dst
->type
!= src
->type
|| dst
== src
) return CommandError();
1987 CommandCost ret
= CheckOwnership(src
->owner
);
1988 if (ret
.Failed()) return ret
;
1990 /* Trucks can't share orders with busses (and visa versa) */
1991 if (src
->type
== VEH_ROAD
&& RoadVehicle::From(src
)->IsBus() != RoadVehicle::From(dst
)->IsBus()) {
1992 return CommandError();
1995 /* Is the vehicle already in the shared list? */
1996 if (src
->FirstShared() == dst
->FirstShared()) return CommandError();
2000 FOR_VEHICLE_ORDERS(src
, order
) {
2001 if (!OrderGoesToStation(dst
, order
)) continue;
2003 /* Allow copying unreachable destinations if they were already unreachable for the source.
2004 * This is basically to allow cloning / autorenewing / autoreplacing vehicles, while the stations
2005 * are temporarily invalid due to reconstruction. */
2006 const Station
*st
= Station::Get(order
->GetDestination());
2007 if (CanVehicleUseStation(src
, st
) && !CanVehicleUseStation(dst
, st
)) {
2008 return CommandError(STR_ERROR_CAN_T_COPY_SHARE_ORDER
);
2012 /* Check for aircraft range limits. */
2013 if (dst
->type
== VEH_AIRCRAFT
&& !CheckAircraftOrderDistance(Aircraft::From(dst
), src
, src
->GetFirstOrder())) {
2014 return CommandError(STR_ERROR_AIRCRAFT_NOT_ENOUGH_RANGE
);
2017 if (!src
->HasOrdersList() && !OrderList::CanAllocateItem()) {
2018 return CommandError(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS
);
2021 if (flags
& DC_EXEC
) {
2022 /* If the destination vehicle had a OrderList, destroy it.
2023 * We only reset the order indices, if the new orders are obviously different.
2024 * (We mainly do this to keep the order indices valid and in range.) */
2025 dst
->DeleteVehicleOrders(false, dst
->GetNumOrders() != src
->GetNumOrders());
2027 dst
->ShareOrdersWith(src
);
2029 /* Link this vehicle in the shared-list */
2030 dst
->AddToShared(src
);
2032 /* Set automation bit if target has it. */
2033 if (HasBit(src
->vehicle_flags
, VF_AUTOMATE_TIMETABLE
)) {
2034 SetBit(dst
->vehicle_flags
, VF_AUTOMATE_TIMETABLE
);
2037 ClrBit(dst
->vehicle_flags
, VF_AUTOMATE_TIMETABLE
);
2040 if (HasBit(src
->vehicle_flags
, VF_AUTOMATE_PRES_WAIT_TIME
)) {
2041 SetBit(dst
->vehicle_flags
, VF_AUTOMATE_PRES_WAIT_TIME
);
2044 ClrBit(dst
->vehicle_flags
, VF_AUTOMATE_PRES_WAIT_TIME
);
2047 InvalidateVehicleOrder(dst
, VIWD_REMOVE_ALL_ORDERS
);
2048 InvalidateVehicleOrder(src
, VIWD_MODIFY_ORDERS
);
2050 InvalidateWindowClassesData(GetWindowClassForVehicleType(dst
->type
), 0);
2051 CheckMarkDirtyFocusedRoutePaths(dst
);
2057 Vehicle
*src
= Vehicle::GetIfValid(veh_src
);
2060 if (src
== nullptr || !src
->IsPrimaryVehicle() || dst
->type
!= src
->type
|| dst
== src
) return CommandError();
2062 CommandCost ret
= CheckOwnership(src
->owner
);
2063 if (ret
.Failed()) return ret
;
2065 /* Trucks can't copy all the orders from busses (and visa versa),
2066 * and neither can helicopters and aircraft. */
2068 FOR_VEHICLE_ORDERS(src
, order
) {
2069 if (OrderGoesToStation(dst
, order
) &&
2070 !CanVehicleUseStation(dst
, Station::Get(order
->GetDestination()))) {
2071 return CommandError(STR_ERROR_CAN_T_COPY_SHARE_ORDER
);
2075 /* Check for aircraft range limits. */
2076 if (dst
->type
== VEH_AIRCRAFT
&& !CheckAircraftOrderDistance(Aircraft::From(dst
), src
, src
->GetFirstOrder())) {
2077 return CommandError(STR_ERROR_AIRCRAFT_NOT_ENOUGH_RANGE
);
2080 /* make sure there are orders available */
2081 if (!Order::CanAllocateItem(src
->GetNumOrders()) || !OrderList::CanAllocateItem()) {
2082 return CommandError(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS
);
2085 if (flags
& DC_EXEC
) {
2087 Order
*first
= nullptr;
2090 /* If the destination vehicle had an order list, destroy the chain but keep the OrderList.
2091 * We only reset the order indices, if the new orders are obviously different.
2092 * (We mainly do this to keep the order indices valid and in range.) */
2093 dst
->DeleteVehicleOrders(true, dst
->GetNumOrders() != src
->GetNumOrders());
2096 FOR_VEHICLE_ORDERS(src
, order
) {
2097 *order_dst
= new Order();
2098 (*order_dst
)->AssignOrder(*order
);
2099 order_dst
= &(*order_dst
)->next
;
2101 if (!dst
->HasOrdersList()) {
2102 dst
->SetOrdersList(new OrderList(first
, dst
));
2104 assert(dst
->GetFirstOrder() == nullptr);
2105 assert(!dst
->HasSharedOrdersList());
2106 dst
->DeleteAndReplaceOrdersList(new OrderList(first
, dst
));
2109 /* Set automation bit if target has it. */
2110 if (HasBit(src
->vehicle_flags
, VF_AUTOMATE_TIMETABLE
)) {
2111 SetBit(dst
->vehicle_flags
, VF_AUTOMATE_TIMETABLE
);
2114 ClrBit(dst
->vehicle_flags
, VF_AUTOMATE_TIMETABLE
);
2117 if (HasBit(src
->vehicle_flags
, VF_AUTOMATE_PRES_WAIT_TIME
)) {
2118 SetBit(dst
->vehicle_flags
, VF_AUTOMATE_PRES_WAIT_TIME
);
2121 ClrBit(dst
->vehicle_flags
, VF_AUTOMATE_PRES_WAIT_TIME
);
2124 InvalidateVehicleOrder(dst
, VIWD_REMOVE_ALL_ORDERS
);
2126 InvalidateWindowClassesData(GetWindowClassForVehicleType(dst
->type
), 0);
2127 CheckMarkDirtyFocusedRoutePaths(dst
);
2132 case CO_UNSHARE
: return DecloneOrder(dst
, flags
);
2133 default: return CommandError();
2136 return CommandCost();
2140 * Add/remove refit orders from an order
2141 * @param tile Not used
2142 * @param flags operation to perform
2143 * @param p1 VehicleIndex of the vehicle having the order
2146 * - bit 16-23 number of order to modify
2147 * @param text unused
2148 * @return the cost of this operation or an error
2150 CommandCost
CmdOrderRefit(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
2152 VehicleID veh
= GB(p1
, 0, 20);
2153 VehicleOrderID order_number
= GB(p2
, 16, 8);
2154 CargoID cargo
= GB(p2
, 0, 8);
2156 if (cargo
>= NUM_CARGO
&& cargo
!= CT_NO_REFIT
&& cargo
!= CT_AUTO_REFIT
) return CommandError();
2158 const Vehicle
*v
= Vehicle::GetIfValid(veh
);
2159 if (v
== nullptr || !v
->IsPrimaryVehicle()) return CommandError();
2161 CommandCost ret
= CheckOwnership(v
->owner
);
2162 if (ret
.Failed()) return ret
;
2164 Order
*order
= v
->GetOrder(order_number
);
2165 if (order
== nullptr) return CommandError();
2167 /* Automatic refit cargo is only supported for goto station orders. */
2168 if (cargo
== CT_AUTO_REFIT
&& !order
->IsType(OT_GOTO_STATION
)) return CommandError();
2170 if (order
->GetLoadType() & OLFB_NO_LOAD
) return CommandError();
2172 if (flags
& DC_EXEC
) {
2173 order
->SetRefit(cargo
);
2175 /* Make the depot order an 'always go' order. */
2176 if (cargo
!= CT_NO_REFIT
&& order
->IsType(OT_GOTO_DEPOT
)) {
2177 order
->SetDepotOrderType((OrderDepotTypeFlags
)(order
->GetDepotOrderType() & ~ODTFB_SERVICE
));
2178 order
->SetDepotActionType((OrderDepotActionFlags
)(order
->GetDepotActionType() & ~ODATFB_HALT
));
2181 for (Vehicle
*u
= v
->FirstShared(); u
!= nullptr; u
= u
->NextShared()) {
2182 /* Update any possible open window of the vehicle */
2183 InvalidateVehicleOrder(u
, VIWD_MODIFY_ORDERS
);
2185 /* If the vehicle already got the current depot set as current order, then update current order as well */
2186 if (u
->cur_real_order_index
== order_number
&& (u
->current_order
.GetDepotOrderType() & ODTFB_PART_OF_ORDERS
)) {
2187 u
->current_order
.SetRefit(cargo
);
2190 CheckMarkDirtyFocusedRoutePaths(v
);
2193 return CommandCost();
2199 * Check the orders of a vehicle, to see if there are invalid orders and stuff
2202 void CheckOrders(const Vehicle
*v
)
2204 /* Does the user wants us to check things? */
2205 if (_settings_client
.gui
.order_review_system
== 0) return;
2207 /* Do nothing for crashed vehicles */
2208 if (v
->vehstatus
& VS_CRASHED
) return;
2210 /* Do nothing for stopped vehicles if setting is '1' */
2211 if (_settings_client
.gui
.order_review_system
== 1 && (v
->vehstatus
& VS_STOPPED
)) return;
2213 /* do nothing we we're not the first vehicle in a share-chain */
2214 if (v
->FirstShared() != v
) return;
2216 /* Only check every 20 days, so that we don't flood the message log */
2217 /* The check is skipped entirely in case the current vehicle is virtual (a.k.a a 'template train') */
2218 if (v
->owner
== _local_company
&& v
->day_counter
% 20 == 0 && !HasBit(v
->subtype
, GVSF_VIRTUAL
) ) {
2220 StringID message
= INVALID_STRING_ID
;
2222 /* Check the order list */
2225 FOR_VEHICLE_ORDERS(v
, order
) {
2227 if (order
->IsType(OT_DUMMY
)) {
2228 message
= STR_NEWS_VEHICLE_HAS_VOID_ORDER
;
2231 /* Does station have a load-bay for this vehicle? */
2232 if (order
->IsType(OT_GOTO_STATION
)) {
2233 const Station
*st
= Station::Get(order
->GetDestination());
2236 if (!CanVehicleUseStation(v
, st
)) {
2237 message
= STR_NEWS_VEHICLE_HAS_INVALID_ENTRY
;
2238 } else if (v
->type
== VEH_AIRCRAFT
&&
2239 (AircraftVehInfo(v
->engine_type
)->subtype
& AIR_FAST
) &&
2240 (st
->airport
.GetFTA()->flags
& AirportFTAClass::SHORT_STRIP
) &&
2241 _settings_game
.vehicle
.plane_crashes
!= 0 &&
2242 !_cheats
.no_jetcrash
.value
&&
2243 message
== INVALID_STRING_ID
) {
2244 message
= STR_NEWS_PLANE_USES_TOO_SHORT_RUNWAY
;
2249 /* Check if the last and the first order are the same */
2250 if (v
->GetNumOrders() > 1) {
2251 const Order
*last
= v
->GetLastOrder();
2253 if (v
->GetFirstOrder()->Equals(*last
)) {
2254 message
= STR_NEWS_VEHICLE_HAS_DUPLICATE_ENTRY
;
2258 /* Do we only have 1 station in our order list? */
2259 if (n_st
< 2 && message
== INVALID_STRING_ID
) message
= STR_NEWS_VEHICLE_HAS_TOO_FEW_ORDERS
;
2262 v
->DebugCheckSanity();
2265 /* We don't have a problem */
2266 if (message
== INVALID_STRING_ID
) return;
2268 SetDParam(0, v
->index
);
2269 AddVehicleAdviceNewsItem(message
, v
->index
);
2274 * Removes an order from all vehicles. Triggers when, say, a station is removed.
2275 * @param type The type of the order (OT_GOTO_[STATION|DEPOT|WAYPOINT]).
2276 * @param destination The destination. Can be a StationID, DepotID or WaypointID.
2278 void RemoveOrderFromAllVehicles(OrderType type
, DestinationID destination
)
2282 /* Aircraft have StationIDs for depot orders and never use DepotIDs
2283 * This fact is handled specially below
2286 /* Go through all vehicles */
2287 FOR_ALL_VEHICLES(v
) {
2290 order
= &v
->current_order
;
2291 if ((v
->type
== VEH_AIRCRAFT
&& order
->IsType(OT_GOTO_DEPOT
) ? OT_GOTO_STATION
: order
->GetType()) == type
&&
2292 v
->current_order
.GetDestination() == destination
) {
2294 SetWindowDirty(WC_VEHICLE_VIEW
, v
->index
);
2297 /* Clear the order from the order-list */
2299 FOR_VEHICLE_ORDERS(v
, order
) {
2303 OrderType ot
= order
->GetType();
2304 if (ot
== OT_GOTO_DEPOT
&& (order
->GetDepotActionType() & ODATFB_NEAREST_DEPOT
) != 0) continue;
2305 if (ot
== OT_IMPLICIT
|| (v
->type
== VEH_AIRCRAFT
&& ot
== OT_GOTO_DEPOT
)) ot
= OT_GOTO_STATION
;
2306 if (ot
== type
&& order
->GetDestination() == destination
) {
2307 /* We want to clear implicit orders, but we don't want to make them
2308 * dummy orders. They should just vanish. Also check the actual order
2309 * type as ot is currently OT_GOTO_STATION. */
2310 if (order
->IsType(OT_IMPLICIT
)) {
2311 order
= order
->next
; // DeleteOrder() invalidates current order
2313 if (order
!= nullptr) goto restart
;
2317 /* Clear wait time */
2318 v
->UpdateTotalDuration(-order
->GetWaitTime());
2319 if (order
->IsWaitTimetabled()) {
2320 v
->UpdateTimetableDuration(-order
->GetTimetabledWait());
2321 order
->SetWaitTimetabled(false);
2323 order
->SetWaitTime(0);
2325 /* Clear order, preserving travel time */
2326 bool travel_timetabled
= order
->IsTravelTimetabled();
2328 order
->SetTravelTimetabled(travel_timetabled
);
2330 for (const Vehicle
*w
= v
->FirstShared(); w
!= nullptr; w
= w
->NextShared()) {
2331 /* In GUI, simulate by removing the order and adding it back */
2332 InvalidateVehicleOrder(w
, id
| (INVALID_VEH_ORDER_ID
<< 8));
2333 InvalidateVehicleOrder(w
, (INVALID_VEH_ORDER_ID
<< 8) | id
);
2339 OrderBackup::RemoveOrder(type
, destination
);
2343 * Checks if a vehicle has a depot in its order list.
2344 * @return True iff at least one order is a depot order.
2346 bool Vehicle::HasDepotOrder() const
2350 FOR_VEHICLE_ORDERS(this, order
) {
2351 if (order
->IsType(OT_GOTO_DEPOT
)) return true;
2358 * Clamp the service interval to the correct min/max. The actual min/max values
2359 * depend on whether it's in percent or days.
2360 * @param interval proposed service interval
2361 * @param company_id the owner of the vehicle
2362 * @return Clamped service interval
2364 uint16
GetServiceIntervalClamped(uint interval
, bool ispercent
)
2366 return ispercent
? Clamp(interval
, MIN_SERVINT_PERCENT
, MAX_SERVINT_PERCENT
) : Clamp(interval
, MIN_SERVINT_DAYS
, MAX_SERVINT_DAYS
);
2371 * Check if a vehicle has any valid orders
2373 * @return false if there are no valid orders
2374 * @note Conditional orders are not considered valid destination orders
2377 static bool CheckForValidOrders(const Vehicle
*v
)
2381 FOR_VEHICLE_ORDERS(v
, order
) {
2382 switch (order
->GetType()) {
2383 case OT_GOTO_STATION
:
2385 case OT_GOTO_WAYPOINT
:
2397 * Compare the variable and value based on the given comparator.
2399 static bool OrderConditionCompare(OrderConditionComparator occ
, int variable
, int value
)
2402 case OCC_EQUALS
: return variable
== value
;
2403 case OCC_NOT_EQUALS
: return variable
!= value
;
2404 case OCC_LESS_THAN
: return variable
< value
;
2405 case OCC_LESS_EQUALS
: return variable
<= value
;
2406 case OCC_MORE_THAN
: return variable
> value
;
2407 case OCC_MORE_EQUALS
: return variable
>= value
;
2408 case OCC_IS_TRUE
: return variable
!= 0;
2409 case OCC_IS_FALSE
: return variable
== 0;
2410 default: NOT_REACHED();
2414 /* Get the number of free (train) platforms in a station.
2415 * @param st_id The StationID of the station.
2416 * @return The number of free train platforms.
2418 static uint16
GetFreeStationPlatforms(StationID st_id
)
2420 assert(Station::IsValidID(st_id
));
2421 const Station
*st
= Station::Get(st_id
);
2422 if (!(st
->facilities
& FACIL_TRAIN
)) return 0;
2426 TILE_AREA_LOOP(t1
, st
->train_station
) {
2427 if (st
->TileBelongsToRailStation(t1
)) {
2428 /* We only proceed if this tile is a track tile and the north(-east/-west) end of the platform */
2429 if (IsCompatibleTrainStationTile(t1
+ TileOffsByDiagDir(GetRailStationAxis(t1
) == AXIS_X
? DIAGDIR_NE
: DIAGDIR_NW
), t1
) || IsStationTileBlocked(t1
)) continue;
2433 if (GetStationReservationTrackBits(t2
)) {
2437 t2
+= TileOffsByDiagDir(GetRailStationAxis(t1
) == AXIS_X
? DIAGDIR_SW
: DIAGDIR_SE
);
2438 } while (IsCompatibleTrainStationTile(t2
, t1
));
2439 if (is_free
) counter
++;
2445 /** Gets the next 'real' station in the order list
2446 * @param v the vehicle in question
2447 * @param order the current (conditional) order
2448 * @return the StationID of the next valid station in the order list, or INVALID_STATION if there is none.
2450 static StationID
GetNextRealStation(const Vehicle
*v
, const Order
*order
, int conditional_depth
= 0)
2452 if (order
->IsType(OT_GOTO_STATION
)) {
2453 if (Station::IsValidID(order
->GetDestination())) return order
->GetDestination();
2455 //nothing conditional about this
2456 if (conditional_depth
> v
->GetNumOrders()) return INVALID_STATION
;
2457 return GetNextRealStation(v
, (order
->next
!= nullptr) ? order
->next
: v
->GetFirstOrder(), ++conditional_depth
);
2461 * Process a conditional order and determine the next order.
2462 * @param order the order the vehicle currently has
2463 * @param v the vehicle to update
2464 * @return index of next order to jump to, or INVALID_VEH_ORDER_ID to use the next order
2466 VehicleOrderID
ProcessConditionalOrder(const Order
*order
, const Vehicle
*v
)
2468 if (order
->GetType() != OT_CONDITIONAL
) return INVALID_VEH_ORDER_ID
;
2470 bool skip_order
= false;
2471 OrderConditionComparator occ
= order
->GetConditionComparator();
2472 uint16 value
= order
->GetConditionValue();
2473 bool has_manual_depot_order
= (HasBit(v
->vehicle_flags
, VF_SHOULD_GOTO_DEPOT
) || HasBit(v
->vehicle_flags
, VF_SHOULD_SERVICE_AT_DEPOT
));
2475 // OrderConditionCompare ignores the last parameter for occ == OCC_IS_TRUE or occ == OCC_IS_FALSE.
2476 switch (order
->GetConditionVariable()) {
2477 case OCV_LOAD_PERCENTAGE
: skip_order
= OrderConditionCompare(occ
, CalcPercentVehicleFilled(v
, nullptr), value
); break;
2478 case OCV_RELIABILITY
: skip_order
= OrderConditionCompare(occ
, ToPercent16(v
->reliability
), value
); break;
2479 case OCV_MAX_SPEED
: skip_order
= OrderConditionCompare(occ
, v
->GetDisplayMaxSpeed() * 10 / 16, value
); break;
2480 case OCV_AGE
: skip_order
= OrderConditionCompare(occ
, v
->age
/ DAYS_IN_LEAP_YEAR
, value
); break;
2481 case OCV_REQUIRES_SERVICE
: skip_order
= OrderConditionCompare(occ
, has_manual_depot_order
|| v
->NeedsServicing(), value
); break;
2482 case OCV_UNCONDITIONALLY
: skip_order
= true; break;
2483 case OCV_CARGO_WAITING
: {
2484 StationID next_station
= GetNextRealStation(v
, order
);
2485 if (Station::IsValidID(next_station
)) skip_order
= OrderConditionCompare(occ
, Station::Get(next_station
)->goods
[value
].cargo
.AvailableCount() > 0, value
);
2488 case OCV_CARGO_ACCEPTANCE
: {
2489 StationID next_station
= GetNextRealStation(v
, order
);
2490 if (Station::IsValidID(next_station
)) skip_order
= OrderConditionCompare(occ
, HasBit(Station::Get(next_station
)->goods
[value
].status
, GoodsEntry::GES_ACCEPTANCE
), value
);
2493 case OCV_SLOT_OCCUPANCY
: {
2494 const TraceRestrictSlot
* slot
= TraceRestrictSlot::GetIfValid(order
->GetXData());
2495 if (slot
!= nullptr) skip_order
= OrderConditionCompare(occ
, slot
->occupants
.size() >= slot
->max_occupancy
, value
);
2498 case OCV_FREE_PLATFORMS
: {
2499 StationID next_station
= GetNextRealStation(v
, order
);
2500 if (Station::IsValidID(next_station
)) skip_order
= OrderConditionCompare(occ
, GetFreeStationPlatforms(next_station
), value
);
2504 /* get a non-const reference to the current order */
2505 Order
*ord
= (Order
*)order
;
2506 skip_order
= ord
->UpdateJumpCounter((byte
)value
);
2509 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;
2510 default: NOT_REACHED();
2513 return skip_order
? order
->GetConditionSkipToOrder() : (VehicleOrderID
)INVALID_VEH_ORDER_ID
;
2517 * Update the vehicle's destination tile from an order.
2518 * @param order the order the vehicle currently has
2519 * @param v the vehicle to update
2520 * @param conditional_depth the depth (amount of steps) to go with conditional orders. This to prevent infinite loops.
2521 * @param pbs_look_ahead Whether we are forecasting orders for pbs reservations in advance. If true, the order indices must not be modified.
2523 bool UpdateOrderDest(Vehicle
*v
, const Order
*order
, int conditional_depth
, bool pbs_look_ahead
)
2525 if (conditional_depth
> v
->GetNumOrders()) {
2526 v
->current_order
.Free();
2531 bool has_manual_depot_order
= (HasBit(v
->vehicle_flags
, VF_SHOULD_GOTO_DEPOT
) || HasBit(v
->vehicle_flags
, VF_SHOULD_SERVICE_AT_DEPOT
));
2533 switch (order
->GetType()) {
2534 case OT_GOTO_STATION
:
2535 v
->dest_tile
= v
->GetOrderStationLocation(order
->GetDestination());
2539 if ((order
->GetDepotOrderType() & ODTFB_SERVICE
) && !(v
->NeedsServicing() || has_manual_depot_order
)) {
2540 assert(!pbs_look_ahead
);
2541 UpdateVehicleTimetable(v
, true);
2542 v
->IncrementRealOrderIndex();
2546 if (v
->current_order
.GetDepotActionType() & ODATFB_NEAREST_DEPOT
) {
2547 /* We need to search for the nearest depot (hangar). */
2549 DestinationID destination
;
2552 if (v
->FindClosestDepot(&location
, &destination
, &reverse
)) {
2553 /* PBS reservations cannot reverse */
2554 if (pbs_look_ahead
&& reverse
) return false;
2556 v
->dest_tile
= location
;
2557 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());
2559 /* If there is no depot in front, reverse automatically (trains only) */
2560 if (v
->type
== VEH_TRAIN
&& reverse
) DoCommand(v
->tile
, v
->index
, 0, DC_EXEC
, CMD_REVERSE_TRAIN_DIRECTION
);
2562 if (v
->type
== VEH_AIRCRAFT
) {
2563 Aircraft
*a
= Aircraft::From(v
);
2564 if (a
->state
== FLYING
&& a
->targetairport
!= destination
) {
2565 /* The aircraft is now heading for a different hangar than the next in the orders */
2566 extern void AircraftNextAirportPos_and_Order(Aircraft
*a
);
2567 AircraftNextAirportPos_and_Order(a
);
2573 /* If there is no depot, we cannot help PBS either. */
2574 if (pbs_look_ahead
) return false;
2576 UpdateVehicleTimetable(v
, true);
2577 v
->IncrementRealOrderIndex();
2579 if (v
->type
!= VEH_AIRCRAFT
) {
2580 v
->dest_tile
= Depot::Get(order
->GetDestination())->xy
;
2586 case OT_GOTO_WAYPOINT
:
2587 v
->dest_tile
= Waypoint::Get(order
->GetDestination())->xy
;
2590 case OT_CONDITIONAL
: {
2591 assert(!pbs_look_ahead
);
2592 VehicleOrderID next_order
= ProcessConditionalOrder(order
, v
);
2593 if (next_order
!= INVALID_VEH_ORDER_ID
) {
2594 /* Jump to next_order. cur_implicit_order_index becomes exactly that order,
2595 * cur_real_order_index might come after next_order. */
2596 UpdateVehicleTimetable(v
, false);
2597 v
->cur_implicit_order_index
= v
->cur_real_order_index
= next_order
;
2598 v
->UpdateRealOrderIndex();
2599 v
->cur_timetable_order_index
= v
->GetIndexOfOrder(order
);
2601 /* Disable creation of implicit orders.
2602 * When inserting them we do not know that we would have to make the conditional orders point to them. */
2603 if (v
->IsGroundVehicle()) {
2604 uint16
&gv_flags
= v
->GetGroundVehicleFlags();
2605 SetBit(gv_flags
, GVF_SUPPRESS_IMPLICIT_ORDERS
);
2608 v
->cur_timetable_order_index
= INVALID_VEH_ORDER_ID
;
2609 UpdateVehicleTimetable(v
, true);
2610 v
->IncrementRealOrderIndex();
2620 assert(v
->cur_implicit_order_index
< v
->GetNumOrders());
2621 assert(v
->cur_real_order_index
< v
->GetNumOrders());
2623 /* Get the current order */
2624 order
= v
->GetOrder(v
->cur_real_order_index
);
2625 if (order
!= nullptr && order
->IsType(OT_IMPLICIT
)) {
2626 assert(v
->GetNumManualOrders() == 0);
2630 if (order
== nullptr) {
2631 v
->current_order
.Free();
2636 v
->current_order
= *order
;
2637 return UpdateOrderDest(v
, order
, conditional_depth
+ 1, pbs_look_ahead
);
2641 * Handle the orders of a vehicle and determine the next place
2642 * to go to if needed.
2643 * @param v the vehicle to do this for.
2644 * @return true *if* the vehicle is eligible for reversing
2645 * (basically only when leaving a station).
2647 bool ProcessOrders(Vehicle
*v
)
2649 // Check if we have an illegal manual depot order. Could happen if we deleted the depot order from the orders list after sending
2650 // the vehicle to the depot.
2651 if (HasBit(v
->vehicle_flags
, VF_SHOULD_GOTO_DEPOT
) || HasBit(v
->vehicle_flags
, VF_SHOULD_SERVICE_AT_DEPOT
)) {
2652 int next_depot_index
= -1;
2654 for (int i
= 0; i
< v
->GetNumOrders(); ++i
) {
2655 Order
* order
= v
->GetOrder(i
);
2657 bool isRegularOrder
= (order
->GetDepotOrderType() & ODTFB_PART_OF_ORDERS
) != 0;
2658 bool isDepotOrder
= order
->GetType() == OT_GOTO_DEPOT
;
2660 if (isRegularOrder
&& isDepotOrder
) {
2661 if (i
>= v
->cur_implicit_order_index
) {
2662 next_depot_index
= i
;
2665 else if (next_depot_index
< 0) {
2666 next_depot_index
= i
;
2671 if (next_depot_index
== -1) {
2672 ClrBit(v
->vehicle_flags
, VF_SHOULD_GOTO_DEPOT
);
2673 ClrBit(v
->vehicle_flags
, VF_SHOULD_SERVICE_AT_DEPOT
);
2677 switch (v
->current_order
.GetType()) {
2679 // Check whether the vehicle was manually ordered to go to the depot on its order list.
2680 // If so mark the current depot order as manual, now that we are processing it.
2681 if (HasBit(v
->vehicle_flags
, VF_SHOULD_GOTO_DEPOT
) || HasBit(v
->vehicle_flags
, VF_SHOULD_SERVICE_AT_DEPOT
)) {
2682 v
->current_order
.SetDepotOrderType(ODTF_MANUAL
);
2683 v
->current_order
.SetDepotActionType(HasBit(v
->vehicle_flags
, VF_SHOULD_SERVICE_AT_DEPOT
) ? ODATF_SERVICE_ONLY
: ODATFB_HALT
);
2686 /* Let a depot order in the order list interrupt. */
2687 if (!(v
->current_order
.GetDepotOrderType() & ODTFB_PART_OF_ORDERS
)) return false;
2697 case OT_LEAVESTATION
:
2698 if (v
->type
!= VEH_AIRCRAFT
) return false;
2705 * Reversing because of order change is allowed only just after leaving a
2706 * station (and the difficulty setting to allowed, of course)
2707 * this can be detected because only after OT_LEAVESTATION, current_order
2708 * will be reset to nothing. (That also happens if no order, but in that case
2709 * it won't hit the point in code where may_reverse is checked)
2711 bool may_reverse
= v
->current_order
.IsType(OT_NOTHING
);
2713 /* Check if we've reached a 'via' destination. */
2714 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
)) &&
2715 IsTileType(v
->tile
, MP_STATION
) &&
2716 v
->current_order
.GetDestination() == GetStationIndex(v
->tile
)) {
2717 v
->DeleteUnreachedImplicitOrders();
2718 /* We set the last visited station here because we do not want
2719 * the train to stop at this 'via' station if the next order
2720 * is a no-non-stop order; in that case not setting the last
2721 * visited station will cause the vehicle to still stop. */
2722 v
->last_station_visited
= v
->current_order
.GetDestination();
2723 UpdateVehicleTimetable(v
, true);
2724 v
->IncrementImplicitOrderIndex();
2727 /* Get the current order */
2728 assert(v
->cur_implicit_order_index
== 0 || v
->cur_implicit_order_index
< v
->GetNumOrders());
2729 v
->UpdateRealOrderIndex();
2731 const Order
*order
= v
->GetOrder(v
->cur_real_order_index
);
2732 if (order
!= nullptr && order
->IsType(OT_IMPLICIT
)) {
2733 assert(v
->GetNumManualOrders() == 0);
2737 /* If no order, do nothing. */
2738 if (order
== nullptr || (v
->type
== VEH_AIRCRAFT
&& !CheckForValidOrders(v
))) {
2739 if (v
->type
== VEH_AIRCRAFT
) {
2740 /* Aircraft do something vastly different here, so handle separately */
2741 extern void HandleMissingAircraftOrders(Aircraft
*v
);
2742 HandleMissingAircraftOrders(Aircraft::From(v
));
2746 v
->current_order
.Free();
2751 /* If it is unchanged, keep it. */
2752 if (order
->Equals(v
->current_order
) && (v
->type
== VEH_AIRCRAFT
|| v
->dest_tile
!= 0) &&
2753 (v
->type
!= VEH_SHIP
|| !order
->IsType(OT_GOTO_STATION
) || Station::Get(order
->GetDestination())->HasFacilities(FACIL_DOCK
))) {
2757 /* Otherwise set it, and determine the destination tile. */
2758 v
->current_order
= *order
;
2760 InvalidateVehicleOrder(v
, VIWD_MODIFY_ORDERS
);
2771 SetWindowClassesDirty(GetWindowClassForVehicleType(v
->type
));
2775 return UpdateOrderDest(v
, order
) && may_reverse
;
2779 * Check whether the given vehicle should stop at the given station
2780 * based on this order and the non-stop settings.
2781 * @param v the vehicle that might be stopping.
2782 * @param station the station to stop at.
2783 * @return true if the vehicle should stop.
2785 bool Order::ShouldStopAtStation(const Vehicle
*v
, StationID station
) const
2787 bool is_dest_station
= this->IsType(OT_GOTO_STATION
) && this->dest
== station
;
2789 return (!this->IsType(OT_GOTO_DEPOT
) || (this->GetDepotOrderType() & ODTFB_PART_OF_ORDERS
) != 0) &&
2790 v
->last_station_visited
!= station
&& // Do stop only when we've not just been there
2791 /* Finally do stop when there is no non-stop flag set for this type of station. */
2792 !(this->GetNonStopType() & (is_dest_station
? ONSF_NO_STOP_AT_DESTINATION_STATION
: ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS
));
2796 * A vehicle can leave the current station with cargo if:
2797 * 1. it can load cargo here OR
2798 * 2a. it could leave the last station with cargo AND
2799 * 2b. it doesn't have to unload all cargo here.
2801 bool Order::CanLeaveWithCargo(bool has_cargo
, CargoID cargo
) const
2803 return (this->GetCargoLoadType(cargo
) & OLFB_NO_LOAD
) == 0 || (has_cargo
&&
2804 (this->GetCargoUnloadType(cargo
) & (OUFB_UNLOAD
| OUFB_TRANSFER
)) == 0);