2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 /** @file order_cmd.cpp Handling of orders. */
12 #include "command_func.h"
13 #include "company_func.h"
14 #include "news_func.h"
15 #include "strings_func.h"
16 #include "timetable.h"
17 #include "vehicle_func.h"
18 #include "depot_base.h"
19 #include "core/pool_func.hpp"
20 #include "core/random_func.hpp"
23 #include "station_base.h"
24 #include "waypoint_base.h"
25 #include "company_base.h"
26 #include "order_backup.h"
27 #include "cheat_type.h"
28 #include "order_cmd.h"
29 #include "train_cmd.h"
31 #include "table/strings.h"
33 #include "safeguards.h"
35 /* DestinationID must be at least as large as every these below, because it can
38 static_assert(sizeof(DestinationID
) >= sizeof(DepotID
));
39 static_assert(sizeof(DestinationID
) >= sizeof(StationID
));
41 OrderPool
_order_pool("Order");
42 INSTANTIATE_POOL_METHODS(Order
)
43 OrderListPool
_orderlist_pool("OrderList");
44 INSTANTIATE_POOL_METHODS(OrderList
)
46 /** Clean everything up. */
49 if (CleaningPool()) return;
51 /* We can visit oil rigs and buoys that are not our own. They will be shown in
52 * the list of stations. So, we need to invalidate that window if needed. */
53 if (this->IsType(OT_GOTO_STATION
) || this->IsType(OT_GOTO_WAYPOINT
)) {
54 BaseStation
*bs
= BaseStation::GetIfValid(this->GetDestination());
55 if (bs
!= nullptr && bs
->owner
== OWNER_NONE
) InvalidateWindowClassesData(WC_STATION_LIST
, 0);
61 * @note ONLY use on "current_order" vehicle orders!
65 this->type
= OT_NOTHING
;
72 * Makes this order a Go To Station order.
73 * @param destination the station to go to.
75 void Order::MakeGoToStation(StationID destination
)
77 this->type
= OT_GOTO_STATION
;
79 this->dest
= destination
;
83 * Makes this order a Go To Depot order.
84 * @param destination the depot to go to.
85 * @param order is this order a 'default' order, or an overridden vehicle order?
86 * @param non_stop_type how to get to the depot?
87 * @param action what to do in the depot?
88 * @param cargo the cargo type to change to.
90 void Order::MakeGoToDepot(DepotID destination
, OrderDepotTypeFlags order
, OrderNonStopFlags non_stop_type
, OrderDepotActionFlags action
, CargoID cargo
)
92 this->type
= OT_GOTO_DEPOT
;
93 this->SetDepotOrderType(order
);
94 this->SetDepotActionType(action
);
95 this->SetNonStopType(non_stop_type
);
96 this->dest
= destination
;
97 this->SetRefit(cargo
);
101 * Makes this order a Go To Waypoint order.
102 * @param destination the waypoint to go to.
104 void Order::MakeGoToWaypoint(StationID destination
)
106 this->type
= OT_GOTO_WAYPOINT
;
108 this->dest
= destination
;
112 * Makes this order a Loading order.
113 * @param ordered is this an ordered stop?
115 void Order::MakeLoading(bool ordered
)
117 this->type
= OT_LOADING
;
118 if (!ordered
) this->flags
= 0;
122 * Makes this order a Leave Station order.
124 void Order::MakeLeaveStation()
126 this->type
= OT_LEAVESTATION
;
131 * Makes this order a Dummy order.
133 void Order::MakeDummy()
135 this->type
= OT_DUMMY
;
140 * Makes this order an conditional order.
141 * @param order the order to jump to.
143 void Order::MakeConditional(VehicleOrderID order
)
145 this->type
= OT_CONDITIONAL
;
151 * Makes this order an implicit order.
152 * @param destination the station to go to.
154 void Order::MakeImplicit(StationID destination
)
156 this->type
= OT_IMPLICIT
;
157 this->dest
= destination
;
161 * Make this depot/station order also a refit order.
162 * @param cargo the cargo type to change to.
163 * @pre IsType(OT_GOTO_DEPOT) || IsType(OT_GOTO_STATION).
165 void Order::SetRefit(CargoID cargo
)
167 this->refit_cargo
= cargo
;
171 * Does this order have the same type, flags and destination?
172 * @param other the second order to compare to.
173 * @return true if the type, flags and destination match.
175 bool Order::Equals(const Order
&other
) const
177 /* In case of go to nearest depot orders we need "only" compare the flags
178 * with the other and not the nearest depot order bit or the actual
179 * destination because those get clear/filled in during the order
180 * evaluation. If we do not do this the order will continuously be seen as
181 * a different order and it will try to find a "nearest depot" every tick. */
182 if ((this->IsType(OT_GOTO_DEPOT
) && this->type
== other
.type
) &&
183 ((this->GetDepotActionType() & ODATFB_NEAREST_DEPOT
) != 0 ||
184 (other
.GetDepotActionType() & ODATFB_NEAREST_DEPOT
) != 0)) {
185 return this->GetDepotOrderType() == other
.GetDepotOrderType() &&
186 (this->GetDepotActionType() & ~ODATFB_NEAREST_DEPOT
) == (other
.GetDepotActionType() & ~ODATFB_NEAREST_DEPOT
);
189 return this->type
== other
.type
&& this->flags
== other
.flags
&& this->dest
== other
.dest
;
193 * Pack this order into a 32 bits integer, or actually only
194 * the type, flags and destination.
195 * @return the packed representation.
196 * @note unpacking is done in the constructor.
198 uint32_t Order::Pack() const
200 return this->dest
<< 16 | this->flags
<< 8 | this->type
;
204 * Pack this order into a 16 bits integer as close to the TTD
205 * representation as possible.
206 * @return the TTD-like packed representation.
208 uint16_t Order::MapOldOrder() const
210 uint16_t order
= this->GetType();
211 switch (this->type
) {
212 case OT_GOTO_STATION
:
213 if (this->GetUnloadType() & OUFB_UNLOAD
) SetBit(order
, 5);
214 if (this->GetLoadType() & OLFB_FULL_LOAD
) SetBit(order
, 6);
215 if (this->GetNonStopType() & ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS
) SetBit(order
, 7);
216 order
|= GB(this->GetDestination(), 0, 8) << 8;
219 if (!(this->GetDepotOrderType() & ODTFB_PART_OF_ORDERS
)) SetBit(order
, 6);
221 order
|= GB(this->GetDestination(), 0, 8) << 8;
224 if (this->GetLoadType() & OLFB_FULL_LOAD
) SetBit(order
, 6);
232 * Updates the widgets of a vehicle which contains the order-data
235 void InvalidateVehicleOrder(const Vehicle
*v
, int data
)
237 SetWindowDirty(WC_VEHICLE_VIEW
, v
->index
);
240 /* Calls SetDirty() too */
241 InvalidateWindowData(WC_VEHICLE_ORDERS
, v
->index
, data
);
242 InvalidateWindowData(WC_VEHICLE_TIMETABLE
, v
->index
, data
);
246 SetWindowDirty(WC_VEHICLE_ORDERS
, v
->index
);
247 SetWindowDirty(WC_VEHICLE_TIMETABLE
, v
->index
);
252 * Assign data to an order (from another order)
253 * This function makes sure that the index is maintained correctly
254 * @param other the data to copy (except next pointer).
257 void Order::AssignOrder(const Order
&other
)
259 this->type
= other
.type
;
260 this->flags
= other
.flags
;
261 this->dest
= other
.dest
;
263 this->refit_cargo
= other
.refit_cargo
;
265 this->wait_time
= other
.wait_time
;
266 this->travel_time
= other
.travel_time
;
267 this->max_speed
= other
.max_speed
;
271 * Recomputes everything.
272 * @param chain first order in the chain
273 * @param v one of vehicle that is using this orderlist
275 void OrderList::Initialize(Order
*chain
, Vehicle
*v
)
278 this->first_shared
= v
;
280 this->num_orders
= 0;
281 this->num_manual_orders
= 0;
282 this->num_vehicles
= 1;
283 this->timetable_duration
= 0;
285 for (Order
*o
= this->first
; o
!= nullptr; o
= o
->next
) {
287 if (!o
->IsType(OT_IMPLICIT
)) ++this->num_manual_orders
;
288 this->total_duration
+= o
->GetWaitTime() + o
->GetTravelTime();
291 this->RecalculateTimetableDuration();
293 for (Vehicle
*u
= this->first_shared
->PreviousShared(); u
!= nullptr; u
= u
->PreviousShared()) {
294 ++this->num_vehicles
;
295 this->first_shared
= u
;
298 for (const Vehicle
*u
= v
->NextShared(); u
!= nullptr; u
= u
->NextShared()) ++this->num_vehicles
;
302 * Recomputes Timetable duration.
303 * Split out into a separate function so it can be used by afterload.
305 void OrderList::RecalculateTimetableDuration()
307 this->timetable_duration
= 0;
308 for (Order
*o
= this->first
; o
!= nullptr; o
= o
->next
) {
309 this->timetable_duration
+= o
->GetTimetabledWait() + o
->GetTimetabledTravel();
314 * Free a complete order chain.
315 * @param keep_orderlist If this is true only delete the orders, otherwise also delete the OrderList.
316 * @note do not use on "current_order" vehicle orders!
318 void OrderList::FreeChain(bool keep_orderlist
)
321 for (Order
*o
= this->first
; o
!= nullptr; o
= next
) {
326 if (keep_orderlist
) {
327 this->first
= nullptr;
328 this->num_orders
= 0;
329 this->num_manual_orders
= 0;
330 this->timetable_duration
= 0;
337 * Get a certain order of the order chain.
338 * @param index zero-based index of the order within the chain.
339 * @return the order at position index.
341 Order
*OrderList::GetOrderAt(int index
) const
343 if (index
< 0) return nullptr;
345 Order
*order
= this->first
;
347 while (order
!= nullptr && index
-- > 0) {
354 * Get the next order which will make the given vehicle stop at a station
355 * or refit at a depot or evaluate a non-trivial condition.
356 * @param next The order to start looking at.
357 * @param hops The number of orders we have already looked at.
359 * \li a station order
360 * \li a refitting depot order
361 * \li a non-trivial conditional order
362 * \li nullptr if the vehicle won't stop anymore.
364 const Order
*OrderList::GetNextDecisionNode(const Order
*next
, uint hops
) const
366 if (hops
> this->GetNumOrders() || next
== nullptr) return nullptr;
368 if (next
->IsType(OT_CONDITIONAL
)) {
369 if (next
->GetConditionVariable() != OCV_UNCONDITIONALLY
) return next
;
371 /* We can evaluate trivial conditions right away. They're conceptually
372 * the same as regular order progression. */
373 return this->GetNextDecisionNode(
374 this->GetOrderAt(next
->GetConditionSkipToOrder()),
378 if (next
->IsType(OT_GOTO_DEPOT
)) {
379 if ((next
->GetDepotActionType() & ODATFB_HALT
) != 0) return nullptr;
380 if (next
->IsRefit()) return next
;
383 if (!next
->CanLoadOrUnload()) {
384 return this->GetNextDecisionNode(this->GetNext(next
), hops
+ 1);
391 * Recursively determine the next deterministic station to stop at.
392 * @param v The vehicle we're looking at.
393 * @param first Order to start searching at or nullptr to start at cur_implicit_order_index + 1.
394 * @param hops Number of orders we have already looked at.
395 * @return Next stopping station or INVALID_STATION.
396 * @pre The vehicle is currently loading and v->last_station_visited is meaningful.
397 * @note This function may draw a random number. Don't use it from the GUI.
399 StationIDStack
OrderList::GetNextStoppingStation(const Vehicle
*v
, const Order
*first
, uint hops
) const
402 const Order
*next
= first
;
403 if (first
== nullptr) {
404 next
= this->GetOrderAt(v
->cur_implicit_order_index
);
405 if (next
== nullptr) {
406 next
= this->GetFirstOrder();
407 if (next
== nullptr) return INVALID_STATION
;
409 /* GetNext never returns nullptr if there is a valid station in the list.
410 * As the given "next" is already valid and a station in the list, we
411 * don't have to check for nullptr here. */
412 next
= this->GetNext(next
);
413 assert(next
!= nullptr);
418 next
= this->GetNextDecisionNode(next
, ++hops
);
420 /* Resolve possibly nested conditionals by estimation. */
421 while (next
!= nullptr && next
->IsType(OT_CONDITIONAL
)) {
422 /* We return both options of conditional orders. */
423 const Order
*skip_to
= this->GetNextDecisionNode(
424 this->GetOrderAt(next
->GetConditionSkipToOrder()), hops
);
425 const Order
*advance
= this->GetNextDecisionNode(
426 this->GetNext(next
), hops
);
427 if (advance
== nullptr || advance
== first
|| skip_to
== advance
) {
428 next
= (skip_to
== first
) ? nullptr : skip_to
;
429 } else if (skip_to
== nullptr || skip_to
== first
) {
430 next
= (advance
== first
) ? nullptr : advance
;
432 StationIDStack st1
= this->GetNextStoppingStation(v
, skip_to
, hops
);
433 StationIDStack st2
= this->GetNextStoppingStation(v
, advance
, hops
);
434 while (!st2
.IsEmpty()) st1
.Push(st2
.Pop());
440 /* Don't return a next stop if the vehicle has to unload everything. */
441 if (next
== nullptr || ((next
->IsType(OT_GOTO_STATION
) || next
->IsType(OT_IMPLICIT
)) &&
442 next
->GetDestination() == v
->last_station_visited
&&
443 (next
->GetUnloadType() & (OUFB_TRANSFER
| OUFB_UNLOAD
)) != 0)) {
444 return INVALID_STATION
;
446 } while (next
->IsType(OT_GOTO_DEPOT
) || next
->GetDestination() == v
->last_station_visited
);
448 return next
->GetDestination();
452 * Insert a new order into the order chain.
453 * @param new_order is the order to insert into the chain.
454 * @param index is the position where the order is supposed to be inserted.
456 void OrderList::InsertOrderAt(Order
*new_order
, int index
)
458 if (this->first
== nullptr) {
459 this->first
= new_order
;
462 /* Insert as first or only order */
463 new_order
->next
= this->first
;
464 this->first
= new_order
;
465 } else if (index
>= this->num_orders
) {
466 /* index is after the last order, add it to the end */
467 this->GetLastOrder()->next
= new_order
;
469 /* Put the new order in between */
470 Order
*order
= this->GetOrderAt(index
- 1);
471 new_order
->next
= order
->next
;
472 order
->next
= new_order
;
476 if (!new_order
->IsType(OT_IMPLICIT
)) ++this->num_manual_orders
;
477 this->timetable_duration
+= new_order
->GetTimetabledWait() + new_order
->GetTimetabledTravel();
478 this->total_duration
+= new_order
->GetWaitTime() + new_order
->GetTravelTime();
480 /* We can visit oil rigs and buoys that are not our own. They will be shown in
481 * the list of stations. So, we need to invalidate that window if needed. */
482 if (new_order
->IsType(OT_GOTO_STATION
) || new_order
->IsType(OT_GOTO_WAYPOINT
)) {
483 BaseStation
*bs
= BaseStation::Get(new_order
->GetDestination());
484 if (bs
->owner
== OWNER_NONE
) InvalidateWindowClassesData(WC_STATION_LIST
, 0);
491 * Remove an order from the order list and delete it.
492 * @param index is the position of the order which is to be deleted.
494 void OrderList::DeleteOrderAt(int index
)
496 if (index
>= this->num_orders
) return;
501 to_remove
= this->first
;
502 this->first
= to_remove
->next
;
504 Order
*prev
= GetOrderAt(index
- 1);
505 to_remove
= prev
->next
;
506 prev
->next
= to_remove
->next
;
509 if (!to_remove
->IsType(OT_IMPLICIT
)) --this->num_manual_orders
;
510 this->timetable_duration
-= (to_remove
->GetTimetabledWait() + to_remove
->GetTimetabledTravel());
511 this->total_duration
-= (to_remove
->GetWaitTime() + to_remove
->GetTravelTime());
516 * Move an order to another position within the order list.
517 * @param from is the zero-based position of the order to move.
518 * @param to is the zero-based position where the order is moved to.
520 void OrderList::MoveOrder(int from
, int to
)
522 if (from
>= this->num_orders
|| to
>= this->num_orders
|| from
== to
) return;
526 /* Take the moving order out of the pointer-chain */
528 moving_one
= this->first
;
529 this->first
= moving_one
->next
;
531 Order
*one_before
= GetOrderAt(from
- 1);
532 moving_one
= one_before
->next
;
533 one_before
->next
= moving_one
->next
;
536 /* Insert the moving_order again in the pointer-chain */
538 moving_one
->next
= this->first
;
539 this->first
= moving_one
;
541 Order
*one_before
= GetOrderAt(to
- 1);
542 moving_one
->next
= one_before
->next
;
543 one_before
->next
= moving_one
;
548 * Removes the vehicle from the shared order list.
549 * @note This is supposed to be called when the vehicle is still in the chain
550 * @param v vehicle to remove from the list
552 void OrderList::RemoveVehicle(Vehicle
*v
)
554 --this->num_vehicles
;
555 if (v
== this->first_shared
) this->first_shared
= v
->NextShared();
559 * Checks whether all orders of the list have a filled timetable.
560 * @return whether all orders have a filled timetable.
562 bool OrderList::IsCompleteTimetable() const
564 for (Order
*o
= this->first
; o
!= nullptr; o
= o
->next
) {
565 /* Implicit orders are, by definition, not timetabled. */
566 if (o
->IsType(OT_IMPLICIT
)) continue;
567 if (!o
->IsCompletelyTimetabled()) return false;
574 * Checks for internal consistency of order list. Triggers assertion if something is wrong.
576 void OrderList::DebugCheckSanity() const
578 VehicleOrderID check_num_orders
= 0;
579 VehicleOrderID check_num_manual_orders
= 0;
580 uint check_num_vehicles
= 0;
581 TimerGameTick::Ticks check_timetable_duration
= 0;
582 TimerGameTick::Ticks check_total_duration
= 0;
584 Debug(misc
, 6, "Checking OrderList {} for sanity...", this->index
);
586 for (const Order
*o
= this->first
; o
!= nullptr; o
= o
->next
) {
588 if (!o
->IsType(OT_IMPLICIT
)) ++check_num_manual_orders
;
589 check_timetable_duration
+= o
->GetTimetabledWait() + o
->GetTimetabledTravel();
590 check_total_duration
+= o
->GetWaitTime() + o
->GetTravelTime();
592 assert(this->num_orders
== check_num_orders
);
593 assert(this->num_manual_orders
== check_num_manual_orders
);
594 assert(this->timetable_duration
== check_timetable_duration
);
595 assert(this->total_duration
== check_total_duration
);
597 for (const Vehicle
*v
= this->first_shared
; v
!= nullptr; v
= v
->NextShared()) {
598 ++check_num_vehicles
;
599 assert(v
->orders
== this);
601 assert(this->num_vehicles
== check_num_vehicles
);
602 Debug(misc
, 6, "... detected {} orders ({} manual), {} vehicles, {} timetabled, {} total",
603 (uint
)this->num_orders
, (uint
)this->num_manual_orders
,
604 this->num_vehicles
, this->timetable_duration
, this->total_duration
);
609 * Checks whether the order goes to a station or not, i.e. whether the
610 * destination is a station
611 * @param v the vehicle to check for
612 * @param o the order to check
613 * @return true if the destination is a station
615 static inline bool OrderGoesToStation(const Vehicle
*v
, const Order
*o
)
617 return o
->IsType(OT_GOTO_STATION
) ||
618 (v
->type
== VEH_AIRCRAFT
&& o
->IsType(OT_GOTO_DEPOT
) && o
->GetDestination() != INVALID_STATION
);
622 * Delete all news items regarding defective orders about a vehicle
623 * This could kill still valid warnings (for example about void order when just
624 * another order gets added), but assume the company will notice the problems,
625 * when they're changing the orders.
627 static void DeleteOrderWarnings(const Vehicle
*v
)
629 DeleteVehicleNews(v
->index
, AdviceType::Order
);
633 * Returns a tile somewhat representing the order destination (not suitable for pathfinding).
634 * @param v The vehicle to get the location for.
635 * @param airport Get the airport tile and not the station location for aircraft.
636 * @return destination of order, or INVALID_TILE if none.
638 TileIndex
Order::GetLocation(const Vehicle
*v
, bool airport
) const
640 switch (this->GetType()) {
641 case OT_GOTO_WAYPOINT
:
642 case OT_GOTO_STATION
:
644 if (airport
&& v
->type
== VEH_AIRCRAFT
) return Station::Get(this->GetDestination())->airport
.tile
;
645 return BaseStation::Get(this->GetDestination())->xy
;
648 if (this->GetDestination() == INVALID_DEPOT
) return INVALID_TILE
;
649 return (v
->type
== VEH_AIRCRAFT
) ? Station::Get(this->GetDestination())->xy
: Depot::Get(this->GetDestination())->xy
;
657 * Get the distance between two orders of a vehicle. Conditional orders are resolved
658 * and the bigger distance of the two order branches is returned.
659 * @param prev Origin order.
660 * @param cur Destination order.
661 * @param v The vehicle to get the distance for.
662 * @param conditional_depth Internal param for resolving conditional orders.
663 * @return Maximum distance between the two orders.
665 uint
GetOrderDistance(const Order
*prev
, const Order
*cur
, const Vehicle
*v
, int conditional_depth
)
667 if (cur
->IsType(OT_CONDITIONAL
)) {
668 if (conditional_depth
> v
->GetNumOrders()) return 0;
672 int dist1
= GetOrderDistance(prev
, v
->GetOrder(cur
->GetConditionSkipToOrder()), v
, conditional_depth
);
673 int dist2
= GetOrderDistance(prev
, cur
->next
== nullptr ? v
->orders
->GetFirstOrder() : cur
->next
, v
, conditional_depth
);
674 return std::max(dist1
, dist2
);
677 TileIndex prev_tile
= prev
->GetLocation(v
, true);
678 TileIndex cur_tile
= cur
->GetLocation(v
, true);
679 if (prev_tile
== INVALID_TILE
|| cur_tile
== INVALID_TILE
) return 0;
680 return v
->type
== VEH_AIRCRAFT
? DistanceSquare(prev_tile
, cur_tile
) : DistanceManhattan(prev_tile
, cur_tile
);
684 * Add an order to the orderlist of a vehicle.
685 * @param flags operation to perform
686 * @param veh ID of the vehicle
687 * @param sel_ord the selected order (if any). If the last order is given,
688 * the order will be inserted before that one
689 * the maximum vehicle order id is 254.
690 * @param new_order order to insert
691 * @return the cost of this operation or an error
693 CommandCost
CmdInsertOrder(DoCommandFlag flags
, VehicleID veh
, VehicleOrderID sel_ord
, const Order
&new_order
)
695 Vehicle
*v
= Vehicle::GetIfValid(veh
);
696 if (v
== nullptr || !v
->IsPrimaryVehicle()) return CMD_ERROR
;
698 CommandCost ret
= CheckOwnership(v
->owner
);
699 if (ret
.Failed()) return ret
;
701 /* Validate properties we don't want to have different from default as they are set by other commands. */
702 if (new_order
.GetRefitCargo() != CARGO_NO_REFIT
|| new_order
.GetWaitTime() != 0 || new_order
.GetTravelTime() != 0 || new_order
.GetMaxSpeed() != UINT16_MAX
) return CMD_ERROR
;
704 /* Check if the inserted order is to the correct destination (owner, type),
705 * and has the correct flags if any */
706 switch (new_order
.GetType()) {
707 case OT_GOTO_STATION
: {
708 const Station
*st
= Station::GetIfValid(new_order
.GetDestination());
709 if (st
== nullptr) return CMD_ERROR
;
711 if (st
->owner
!= OWNER_NONE
) {
712 ret
= CheckOwnership(st
->owner
);
713 if (ret
.Failed()) return ret
;
716 if (!CanVehicleUseStation(v
, st
)) return CommandCost(STR_ERROR_CAN_T_ADD_ORDER
, GetVehicleCannotUseStationReason(v
, st
));
717 for (Vehicle
*u
= v
->FirstShared(); u
!= nullptr; u
= u
->NextShared()) {
718 if (!CanVehicleUseStation(u
, st
)) return CommandCost(STR_ERROR_CAN_T_ADD_ORDER_SHARED
, GetVehicleCannotUseStationReason(u
, st
));
721 /* Non stop only allowed for ground vehicles. */
722 if (new_order
.GetNonStopType() != ONSF_STOP_EVERYWHERE
&& !v
->IsGroundVehicle()) return CMD_ERROR
;
724 /* Filter invalid load/unload types. */
725 switch (new_order
.GetLoadType()) {
726 case OLF_LOAD_IF_POSSIBLE
:
731 case OLF_FULL_LOAD_ANY
:
732 if (v
->HasUnbunchingOrder()) return CommandCost(STR_ERROR_UNBUNCHING_NO_FULL_LOAD
);
738 switch (new_order
.GetUnloadType()) {
739 case OUF_UNLOAD_IF_POSSIBLE
: case OUFB_UNLOAD
: case OUFB_TRANSFER
: case OUFB_NO_UNLOAD
: break;
740 default: return CMD_ERROR
;
743 /* Filter invalid stop locations */
744 switch (new_order
.GetStopLocation()) {
745 case OSL_PLATFORM_NEAR_END
:
746 case OSL_PLATFORM_MIDDLE
:
747 if (v
->type
!= VEH_TRAIN
) return CMD_ERROR
;
750 case OSL_PLATFORM_FAR_END
:
760 case OT_GOTO_DEPOT
: {
761 if ((new_order
.GetDepotActionType() & ODATFB_NEAREST_DEPOT
) == 0) {
762 if (v
->type
== VEH_AIRCRAFT
) {
763 const Station
*st
= Station::GetIfValid(new_order
.GetDestination());
765 if (st
== nullptr) return CMD_ERROR
;
767 ret
= CheckOwnership(st
->owner
);
768 if (ret
.Failed()) return ret
;
770 if (!CanVehicleUseStation(v
, st
) || !st
->airport
.HasHangar()) {
774 const Depot
*dp
= Depot::GetIfValid(new_order
.GetDestination());
776 if (dp
== nullptr) return CMD_ERROR
;
778 ret
= CheckOwnership(GetTileOwner(dp
->xy
));
779 if (ret
.Failed()) return ret
;
783 if (!IsRailDepotTile(dp
->xy
)) return CMD_ERROR
;
787 if (!IsRoadDepotTile(dp
->xy
)) return CMD_ERROR
;
791 if (!IsShipDepotTile(dp
->xy
)) return CMD_ERROR
;
794 default: return CMD_ERROR
;
799 if (new_order
.GetNonStopType() != ONSF_STOP_EVERYWHERE
&& !v
->IsGroundVehicle()) return CMD_ERROR
;
800 if (new_order
.GetDepotOrderType() & ~(ODTFB_PART_OF_ORDERS
| ((new_order
.GetDepotOrderType() & ODTFB_PART_OF_ORDERS
) != 0 ? ODTFB_SERVICE
: 0))) return CMD_ERROR
;
801 if (new_order
.GetDepotActionType() & ~(ODATFB_HALT
| ODATFB_NEAREST_DEPOT
| ODATFB_UNBUNCH
)) return CMD_ERROR
;
803 /* Vehicles cannot have a "service if needed" order that also has a depot action. */
804 if ((new_order
.GetDepotOrderType() & ODTFB_SERVICE
) && (new_order
.GetDepotActionType() & (ODATFB_HALT
| ODATFB_UNBUNCH
))) return CMD_ERROR
;
806 /* Check if we're allowed to have a new unbunching order. */
807 if ((new_order
.GetDepotActionType() & ODATFB_UNBUNCH
)) {
808 if (v
->HasFullLoadOrder()) return CommandCost(STR_ERROR_CAN_T_ADD_ORDER
, STR_ERROR_UNBUNCHING_NO_UNBUNCHING_FULL_LOAD
);
809 if (v
->HasUnbunchingOrder()) return CommandCost(STR_ERROR_CAN_T_ADD_ORDER
, STR_ERROR_UNBUNCHING_ONLY_ONE_ALLOWED
);
810 if (v
->HasConditionalOrder()) return CommandCost(STR_ERROR_CAN_T_ADD_ORDER
, STR_ERROR_UNBUNCHING_NO_UNBUNCHING_CONDITIONAL
);
815 case OT_GOTO_WAYPOINT
: {
816 const Waypoint
*wp
= Waypoint::GetIfValid(new_order
.GetDestination());
817 if (wp
== nullptr) return CMD_ERROR
;
820 default: return CMD_ERROR
;
823 if (!(wp
->facilities
& FACIL_TRAIN
)) return CommandCost(STR_ERROR_CAN_T_ADD_ORDER
, STR_ERROR_NO_RAIL_WAYPOINT
);
825 ret
= CheckOwnership(wp
->owner
);
826 if (ret
.Failed()) return ret
;
831 if (!(wp
->facilities
& (FACIL_BUS_STOP
| FACIL_TRUCK_STOP
))) return CommandCost(STR_ERROR_CAN_T_ADD_ORDER
, STR_ERROR_NO_ROAD_WAYPOINT
);
833 ret
= CheckOwnership(wp
->owner
);
834 if (ret
.Failed()) return ret
;
839 if (!(wp
->facilities
& FACIL_DOCK
)) return CommandCost(STR_ERROR_CAN_T_ADD_ORDER
, STR_ERROR_NO_BUOY
);
840 if (wp
->owner
!= OWNER_NONE
) {
841 ret
= CheckOwnership(wp
->owner
);
842 if (ret
.Failed()) return ret
;
847 /* Order flags can be any of the following for waypoints:
849 * non-stop orders (if any) are only valid for trains and road vehicles */
850 if (new_order
.GetNonStopType() != ONSF_STOP_EVERYWHERE
&& !v
->IsGroundVehicle()) return CMD_ERROR
;
854 case OT_CONDITIONAL
: {
855 VehicleOrderID skip_to
= new_order
.GetConditionSkipToOrder();
856 if (skip_to
!= 0 && skip_to
>= v
->GetNumOrders()) return CMD_ERROR
; // Always allow jumping to the first (even when there is no order).
857 if (new_order
.GetConditionVariable() >= OCV_END
) return CMD_ERROR
;
858 if (v
->HasUnbunchingOrder()) return CommandCost(STR_ERROR_UNBUNCHING_NO_CONDITIONAL
);
860 OrderConditionComparator occ
= new_order
.GetConditionComparator();
861 if (occ
>= OCC_END
) return CMD_ERROR
;
862 switch (new_order
.GetConditionVariable()) {
863 case OCV_REQUIRES_SERVICE
:
864 if (occ
!= OCC_IS_TRUE
&& occ
!= OCC_IS_FALSE
) return CMD_ERROR
;
867 case OCV_UNCONDITIONALLY
:
868 if (occ
!= OCC_EQUALS
) return CMD_ERROR
;
869 if (new_order
.GetConditionValue() != 0) return CMD_ERROR
;
872 case OCV_LOAD_PERCENTAGE
:
873 case OCV_RELIABILITY
:
874 if (new_order
.GetConditionValue() > 100) return CMD_ERROR
;
878 if (occ
== OCC_IS_TRUE
|| occ
== OCC_IS_FALSE
) return CMD_ERROR
;
884 default: return CMD_ERROR
;
887 if (sel_ord
> v
->GetNumOrders()) return CMD_ERROR
;
889 if (v
->GetNumOrders() >= MAX_VEH_ORDER_ID
) return CommandCost(STR_ERROR_TOO_MANY_ORDERS
);
890 if (!Order::CanAllocateItem()) return CommandCost(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS
);
891 if (v
->orders
== nullptr && !OrderList::CanAllocateItem()) return CommandCost(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS
);
893 if (flags
& DC_EXEC
) {
894 Order
*new_o
= new Order();
895 new_o
->AssignOrder(new_order
);
896 InsertOrder(v
, new_o
, sel_ord
);
899 return CommandCost();
903 * Insert a new order but skip the validation.
904 * @param v The vehicle to insert the order to.
905 * @param new_o The new order.
906 * @param sel_ord The position the order should be inserted at.
908 void InsertOrder(Vehicle
*v
, Order
*new_o
, VehicleOrderID sel_ord
)
910 /* Create new order and link in list */
911 if (v
->orders
== nullptr) {
912 v
->orders
= new OrderList(new_o
, v
);
914 v
->orders
->InsertOrderAt(new_o
, sel_ord
);
917 Vehicle
*u
= v
->FirstShared();
918 DeleteOrderWarnings(u
);
919 for (; u
!= nullptr; u
= u
->NextShared()) {
920 assert(v
->orders
== u
->orders
);
922 /* If there is added an order before the current one, we need
923 * to update the selected order. We do not change implicit/real order indices though.
924 * If the new order is between the current implicit order and real order, the implicit order will
925 * later skip the inserted order. */
926 if (sel_ord
<= u
->cur_real_order_index
) {
927 uint cur
= u
->cur_real_order_index
+ 1;
928 /* Check if we don't go out of bound */
929 if (cur
< u
->GetNumOrders()) {
930 u
->cur_real_order_index
= cur
;
933 if (sel_ord
== u
->cur_implicit_order_index
&& u
->IsGroundVehicle()) {
934 /* We are inserting an order just before the current implicit order.
935 * We do not know whether we will reach current implicit or the newly inserted order first.
936 * So, disable creation of implicit orders until we are on track again. */
937 uint16_t &gv_flags
= u
->GetGroundVehicleFlags();
938 SetBit(gv_flags
, GVF_SUPPRESS_IMPLICIT_ORDERS
);
940 if (sel_ord
<= u
->cur_implicit_order_index
) {
941 uint cur
= u
->cur_implicit_order_index
+ 1;
942 /* Check if we don't go out of bound */
943 if (cur
< u
->GetNumOrders()) {
944 u
->cur_implicit_order_index
= cur
;
947 /* Unbunching data is no longer valid. */
948 u
->ResetDepotUnbunching();
950 /* Update any possible open window of the vehicle */
951 InvalidateVehicleOrder(u
, INVALID_VEH_ORDER_ID
| (sel_ord
<< 8));
954 /* As we insert an order, the order to skip to will be 'wrong'. */
955 VehicleOrderID cur_order_id
= 0;
956 for (Order
*order
: v
->Orders()) {
957 if (order
->IsType(OT_CONDITIONAL
)) {
958 VehicleOrderID order_id
= order
->GetConditionSkipToOrder();
959 if (order_id
>= sel_ord
) {
960 order
->SetConditionSkipToOrder(order_id
+ 1);
962 if (order_id
== cur_order_id
) {
963 order
->SetConditionSkipToOrder((order_id
+ 1) % v
->GetNumOrders());
969 /* Make sure to rebuild the whole list */
970 InvalidateWindowClassesData(GetWindowClassForVehicleType(v
->type
), 0);
974 * Declone an order-list
975 * @param *dst delete the orders of this vehicle
976 * @param flags execution flags
978 static CommandCost
DecloneOrder(Vehicle
*dst
, DoCommandFlag flags
)
980 if (flags
& DC_EXEC
) {
981 DeleteVehicleOrders(dst
);
982 InvalidateVehicleOrder(dst
, VIWD_REMOVE_ALL_ORDERS
);
983 InvalidateWindowClassesData(GetWindowClassForVehicleType(dst
->type
), 0);
985 return CommandCost();
989 * Delete an order from the orderlist of a vehicle.
990 * @param flags operation to perform
991 * @param veh_id the ID of the vehicle
992 * @param sel_ord the order to delete (max 255)
993 * @return the cost of this operation or an error
995 CommandCost
CmdDeleteOrder(DoCommandFlag flags
, VehicleID veh_id
, VehicleOrderID sel_ord
)
997 Vehicle
*v
= Vehicle::GetIfValid(veh_id
);
999 if (v
== nullptr || !v
->IsPrimaryVehicle()) return CMD_ERROR
;
1001 CommandCost ret
= CheckOwnership(v
->owner
);
1002 if (ret
.Failed()) return ret
;
1004 /* If we did not select an order, we maybe want to de-clone the orders */
1005 if (sel_ord
>= v
->GetNumOrders()) return DecloneOrder(v
, flags
);
1007 if (v
->GetOrder(sel_ord
) == nullptr) return CMD_ERROR
;
1009 if (flags
& DC_EXEC
) DeleteOrder(v
, sel_ord
);
1010 return CommandCost();
1014 * Cancel the current loading order of the vehicle as the order was deleted.
1015 * @param v the vehicle
1017 static void CancelLoadingDueToDeletedOrder(Vehicle
*v
)
1019 assert(v
->current_order
.IsType(OT_LOADING
));
1020 /* NON-stop flag is misused to see if a train is in a station that is
1021 * on its order list or not */
1022 v
->current_order
.SetNonStopType(ONSF_STOP_EVERYWHERE
);
1023 /* When full loading, "cancel" that order so the vehicle doesn't
1024 * stay indefinitely at this station anymore. */
1025 if (v
->current_order
.GetLoadType() & OLFB_FULL_LOAD
) v
->current_order
.SetLoadType(OLF_LOAD_IF_POSSIBLE
);
1029 * Delete an order but skip the parameter validation.
1030 * @param v The vehicle to delete the order from.
1031 * @param sel_ord The id of the order to be deleted.
1033 void DeleteOrder(Vehicle
*v
, VehicleOrderID sel_ord
)
1035 v
->orders
->DeleteOrderAt(sel_ord
);
1037 Vehicle
*u
= v
->FirstShared();
1038 DeleteOrderWarnings(u
);
1039 for (; u
!= nullptr; u
= u
->NextShared()) {
1040 assert(v
->orders
== u
->orders
);
1042 if (sel_ord
== u
->cur_real_order_index
&& u
->current_order
.IsType(OT_LOADING
)) {
1043 CancelLoadingDueToDeletedOrder(u
);
1046 if (sel_ord
< u
->cur_real_order_index
) {
1047 u
->cur_real_order_index
--;
1048 } else if (sel_ord
== u
->cur_real_order_index
) {
1049 u
->UpdateRealOrderIndex();
1052 if (sel_ord
< u
->cur_implicit_order_index
) {
1053 u
->cur_implicit_order_index
--;
1054 } else if (sel_ord
== u
->cur_implicit_order_index
) {
1055 /* Make sure the index is valid */
1056 if (u
->cur_implicit_order_index
>= u
->GetNumOrders()) u
->cur_implicit_order_index
= 0;
1058 /* Skip non-implicit orders for the implicit-order-index (e.g. if the current implicit order was deleted */
1059 while (u
->cur_implicit_order_index
!= u
->cur_real_order_index
&& !u
->GetOrder(u
->cur_implicit_order_index
)->IsType(OT_IMPLICIT
)) {
1060 u
->cur_implicit_order_index
++;
1061 if (u
->cur_implicit_order_index
>= u
->GetNumOrders()) u
->cur_implicit_order_index
= 0;
1064 /* Unbunching data is no longer valid. */
1065 u
->ResetDepotUnbunching();
1067 /* Update any possible open window of the vehicle */
1068 InvalidateVehicleOrder(u
, sel_ord
| (INVALID_VEH_ORDER_ID
<< 8));
1071 /* As we delete an order, the order to skip to will be 'wrong'. */
1072 VehicleOrderID cur_order_id
= 0;
1073 for (Order
*order
: v
->Orders()) {
1074 if (order
->IsType(OT_CONDITIONAL
)) {
1075 VehicleOrderID order_id
= order
->GetConditionSkipToOrder();
1076 if (order_id
>= sel_ord
) {
1077 order_id
= std::max(order_id
- 1, 0);
1079 if (order_id
== cur_order_id
) {
1080 order_id
= (order_id
+ 1) % v
->GetNumOrders();
1082 order
->SetConditionSkipToOrder(order_id
);
1087 InvalidateWindowClassesData(GetWindowClassForVehicleType(v
->type
), 0);
1091 * Goto order of order-list.
1092 * @param flags operation to perform
1093 * @param veh_id The ID of the vehicle which order is skipped
1094 * @param sel_ord the selected order to which we want to skip
1095 * @return the cost of this operation or an error
1097 CommandCost
CmdSkipToOrder(DoCommandFlag flags
, VehicleID veh_id
, VehicleOrderID sel_ord
)
1099 Vehicle
*v
= Vehicle::GetIfValid(veh_id
);
1101 if (v
== nullptr || !v
->IsPrimaryVehicle() || sel_ord
== v
->cur_implicit_order_index
|| sel_ord
>= v
->GetNumOrders() || v
->GetNumOrders() < 2) return CMD_ERROR
;
1103 CommandCost ret
= CheckOwnership(v
->owner
);
1104 if (ret
.Failed()) return ret
;
1106 if (flags
& DC_EXEC
) {
1107 if (v
->current_order
.IsType(OT_LOADING
)) v
->LeaveStation();
1109 v
->cur_implicit_order_index
= v
->cur_real_order_index
= sel_ord
;
1110 v
->UpdateRealOrderIndex();
1112 /* Unbunching data is no longer valid. */
1113 v
->ResetDepotUnbunching();
1115 InvalidateVehicleOrder(v
, VIWD_MODIFY_ORDERS
);
1117 /* We have an aircraft/ship, they have a mini-schedule, so update them all */
1118 if (v
->type
== VEH_AIRCRAFT
) SetWindowClassesDirty(WC_AIRCRAFT_LIST
);
1119 if (v
->type
== VEH_SHIP
) SetWindowClassesDirty(WC_SHIPS_LIST
);
1122 return CommandCost();
1126 * Move an order inside the orderlist
1127 * @param flags operation to perform
1128 * @param veh the ID of the vehicle
1129 * @param moving_order the order to move
1130 * @param target_order the target order
1131 * @return the cost of this operation or an error
1132 * @note The target order will move one place down in the orderlist
1133 * if you move the order upwards else it'll move it one place down
1135 CommandCost
CmdMoveOrder(DoCommandFlag flags
, VehicleID veh
, VehicleOrderID moving_order
, VehicleOrderID target_order
)
1137 Vehicle
*v
= Vehicle::GetIfValid(veh
);
1138 if (v
== nullptr || !v
->IsPrimaryVehicle()) return CMD_ERROR
;
1140 CommandCost ret
= CheckOwnership(v
->owner
);
1141 if (ret
.Failed()) return ret
;
1143 /* Don't make senseless movements */
1144 if (moving_order
>= v
->GetNumOrders() || target_order
>= v
->GetNumOrders() ||
1145 moving_order
== target_order
|| v
->GetNumOrders() <= 1) return CMD_ERROR
;
1147 Order
*moving_one
= v
->GetOrder(moving_order
);
1148 /* Don't move an empty order */
1149 if (moving_one
== nullptr) return CMD_ERROR
;
1151 if (flags
& DC_EXEC
) {
1152 v
->orders
->MoveOrder(moving_order
, target_order
);
1154 /* Update shared list */
1155 Vehicle
*u
= v
->FirstShared();
1157 DeleteOrderWarnings(u
);
1159 for (; u
!= nullptr; u
= u
->NextShared()) {
1160 /* Update the current order.
1161 * There are multiple ways to move orders, which result in cur_implicit_order_index
1162 * and cur_real_order_index to not longer make any sense. E.g. moving another
1163 * real order between them.
1165 * Basically one could choose to preserve either of them, but not both.
1166 * While both ways are suitable in this or that case from a human point of view, neither
1167 * of them makes really sense.
1168 * However, from an AI point of view, preserving cur_real_order_index is the most
1169 * predictable and transparent behaviour.
1171 * With that decision it basically does not matter what we do to cur_implicit_order_index.
1172 * If we change orders between the implicit- and real-index, the implicit orders are mostly likely
1173 * completely out-dated anyway. So, keep it simple and just keep cur_implicit_order_index as well.
1174 * The worst which can happen is that a lot of implicit orders are removed when reaching current_order.
1176 if (u
->cur_real_order_index
== moving_order
) {
1177 u
->cur_real_order_index
= target_order
;
1178 } else if (u
->cur_real_order_index
> moving_order
&& u
->cur_real_order_index
<= target_order
) {
1179 u
->cur_real_order_index
--;
1180 } else if (u
->cur_real_order_index
< moving_order
&& u
->cur_real_order_index
>= target_order
) {
1181 u
->cur_real_order_index
++;
1184 if (u
->cur_implicit_order_index
== moving_order
) {
1185 u
->cur_implicit_order_index
= target_order
;
1186 } else if (u
->cur_implicit_order_index
> moving_order
&& u
->cur_implicit_order_index
<= target_order
) {
1187 u
->cur_implicit_order_index
--;
1188 } else if (u
->cur_implicit_order_index
< moving_order
&& u
->cur_implicit_order_index
>= target_order
) {
1189 u
->cur_implicit_order_index
++;
1191 /* Unbunching data is no longer valid. */
1192 u
->ResetDepotUnbunching();
1195 assert(v
->orders
== u
->orders
);
1196 /* Update any possible open window of the vehicle */
1197 InvalidateVehicleOrder(u
, moving_order
| (target_order
<< 8));
1200 /* As we move an order, the order to skip to will be 'wrong'. */
1201 for (Order
*order
: v
->Orders()) {
1202 if (order
->IsType(OT_CONDITIONAL
)) {
1203 VehicleOrderID order_id
= order
->GetConditionSkipToOrder();
1204 if (order_id
== moving_order
) {
1205 order_id
= target_order
;
1206 } else if (order_id
> moving_order
&& order_id
<= target_order
) {
1208 } else if (order_id
< moving_order
&& order_id
>= target_order
) {
1211 order
->SetConditionSkipToOrder(order_id
);
1215 /* Make sure to rebuild the whole list */
1216 InvalidateWindowClassesData(GetWindowClassForVehicleType(v
->type
), 0);
1219 return CommandCost();
1223 * Modify an order in the orderlist of a vehicle.
1224 * @param flags operation to perform
1225 * @param veh ID of the vehicle
1226 * @param sel_ord the selected order (if any). If the last order is given,
1227 * the order will be inserted before that one
1228 * the maximum vehicle order id is 254.
1229 * @param mof what data to modify (@see ModifyOrderFlags)
1230 * @param data the data to modify
1231 * @return the cost of this operation or an error
1233 CommandCost
CmdModifyOrder(DoCommandFlag flags
, VehicleID veh
, VehicleOrderID sel_ord
, ModifyOrderFlags mof
, uint16_t data
)
1235 if (mof
>= MOF_END
) return CMD_ERROR
;
1237 Vehicle
*v
= Vehicle::GetIfValid(veh
);
1238 if (v
== nullptr || !v
->IsPrimaryVehicle()) return CMD_ERROR
;
1240 CommandCost ret
= CheckOwnership(v
->owner
);
1241 if (ret
.Failed()) return ret
;
1243 /* Is it a valid order? */
1244 if (sel_ord
>= v
->GetNumOrders()) return CMD_ERROR
;
1246 Order
*order
= v
->GetOrder(sel_ord
);
1247 assert(order
!= nullptr);
1248 switch (order
->GetType()) {
1249 case OT_GOTO_STATION
:
1250 if (mof
!= MOF_NON_STOP
&& mof
!= MOF_STOP_LOCATION
&& mof
!= MOF_UNLOAD
&& mof
!= MOF_LOAD
) return CMD_ERROR
;
1254 if (mof
!= MOF_NON_STOP
&& mof
!= MOF_DEPOT_ACTION
) return CMD_ERROR
;
1257 case OT_GOTO_WAYPOINT
:
1258 if (mof
!= MOF_NON_STOP
) return CMD_ERROR
;
1261 case OT_CONDITIONAL
:
1262 if (mof
!= MOF_COND_VARIABLE
&& mof
!= MOF_COND_COMPARATOR
&& mof
!= MOF_COND_VALUE
&& mof
!= MOF_COND_DESTINATION
) return CMD_ERROR
;
1270 default: NOT_REACHED();
1273 if (!v
->IsGroundVehicle()) return CMD_ERROR
;
1274 if (data
>= ONSF_END
) return CMD_ERROR
;
1275 if (data
== order
->GetNonStopType()) return CMD_ERROR
;
1278 case MOF_STOP_LOCATION
:
1279 if (v
->type
!= VEH_TRAIN
) return CMD_ERROR
;
1280 if (data
>= OSL_END
) return CMD_ERROR
;
1284 if (order
->GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION
) return CMD_ERROR
;
1285 if ((data
& ~(OUFB_UNLOAD
| OUFB_TRANSFER
| OUFB_NO_UNLOAD
)) != 0) return CMD_ERROR
;
1286 /* Unload and no-unload are mutual exclusive and so are transfer and no unload. */
1287 if (data
!= 0 && ((data
& (OUFB_UNLOAD
| OUFB_TRANSFER
)) != 0) == ((data
& OUFB_NO_UNLOAD
) != 0)) return CMD_ERROR
;
1288 if (data
== order
->GetUnloadType()) return CMD_ERROR
;
1292 if (order
->GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION
) return CMD_ERROR
;
1293 if (data
> OLFB_NO_LOAD
|| data
== 1) return CMD_ERROR
;
1294 if (data
== order
->GetLoadType()) return CMD_ERROR
;
1295 if ((data
& (OLFB_FULL_LOAD
| OLF_FULL_LOAD_ANY
)) && v
->HasUnbunchingOrder()) return CommandCost(STR_ERROR_UNBUNCHING_NO_FULL_LOAD
);
1298 case MOF_DEPOT_ACTION
:
1299 if (data
>= DA_END
) return CMD_ERROR
;
1300 /* Check if we are allowed to add unbunching. We are always allowed to remove it. */
1301 if (data
== DA_UNBUNCH
) {
1302 /* Only one unbunching order is allowed in a vehicle's orders. If this order already has an unbunching action, no error is needed. */
1303 if (v
->HasUnbunchingOrder() && !(order
->GetDepotActionType() & ODATFB_UNBUNCH
)) return CommandCost(STR_ERROR_UNBUNCHING_ONLY_ONE_ALLOWED
);
1304 /* We don't allow unbunching if the vehicle has a conditional order. */
1305 if (v
->HasConditionalOrder()) return CommandCost(STR_ERROR_UNBUNCHING_NO_UNBUNCHING_CONDITIONAL
);
1306 /* We don't allow unbunching if the vehicle has a full load order. */
1307 if (v
->HasFullLoadOrder()) return CommandCost(STR_ERROR_UNBUNCHING_NO_UNBUNCHING_FULL_LOAD
);
1311 case MOF_COND_VARIABLE
:
1312 if (data
>= OCV_END
) return CMD_ERROR
;
1315 case MOF_COND_COMPARATOR
:
1316 if (data
>= OCC_END
) return CMD_ERROR
;
1317 switch (order
->GetConditionVariable()) {
1318 case OCV_UNCONDITIONALLY
: return CMD_ERROR
;
1320 case OCV_REQUIRES_SERVICE
:
1321 if (data
!= OCC_IS_TRUE
&& data
!= OCC_IS_FALSE
) return CMD_ERROR
;
1325 if (data
== OCC_IS_TRUE
|| data
== OCC_IS_FALSE
) return CMD_ERROR
;
1330 case MOF_COND_VALUE
:
1331 switch (order
->GetConditionVariable()) {
1332 case OCV_UNCONDITIONALLY
:
1333 case OCV_REQUIRES_SERVICE
:
1336 case OCV_LOAD_PERCENTAGE
:
1337 case OCV_RELIABILITY
:
1338 if (data
> 100) return CMD_ERROR
;
1342 if (data
> 2047) return CMD_ERROR
;
1347 case MOF_COND_DESTINATION
:
1348 if (data
>= v
->GetNumOrders()) return CMD_ERROR
;
1352 if (flags
& DC_EXEC
) {
1355 order
->SetNonStopType((OrderNonStopFlags
)data
);
1356 if (data
& ONSF_NO_STOP_AT_DESTINATION_STATION
) {
1357 order
->SetRefit(CARGO_NO_REFIT
);
1358 order
->SetLoadType(OLF_LOAD_IF_POSSIBLE
);
1359 order
->SetUnloadType(OUF_UNLOAD_IF_POSSIBLE
);
1363 case MOF_STOP_LOCATION
:
1364 order
->SetStopLocation((OrderStopLocation
)data
);
1368 order
->SetUnloadType((OrderUnloadFlags
)data
);
1372 order
->SetLoadType((OrderLoadFlags
)data
);
1373 if (data
& OLFB_NO_LOAD
) order
->SetRefit(CARGO_NO_REFIT
);
1376 case MOF_DEPOT_ACTION
: {
1379 order
->SetDepotOrderType((OrderDepotTypeFlags
)(order
->GetDepotOrderType() & ~ODTFB_SERVICE
));
1380 order
->SetDepotActionType((OrderDepotActionFlags
)(order
->GetDepotActionType() & ~ODATFB_HALT
));
1381 order
->SetDepotActionType((OrderDepotActionFlags
)(order
->GetDepotActionType() & ~ODATFB_UNBUNCH
));
1385 order
->SetDepotOrderType((OrderDepotTypeFlags
)(order
->GetDepotOrderType() | ODTFB_SERVICE
));
1386 order
->SetDepotActionType((OrderDepotActionFlags
)(order
->GetDepotActionType() & ~ODATFB_HALT
));
1387 order
->SetDepotActionType((OrderDepotActionFlags
)(order
->GetDepotActionType() & ~ODATFB_UNBUNCH
));
1388 order
->SetRefit(CARGO_NO_REFIT
);
1392 order
->SetDepotOrderType((OrderDepotTypeFlags
)(order
->GetDepotOrderType() & ~ODTFB_SERVICE
));
1393 order
->SetDepotActionType((OrderDepotActionFlags
)(order
->GetDepotActionType() | ODATFB_HALT
));
1394 order
->SetDepotActionType((OrderDepotActionFlags
)(order
->GetDepotActionType() & ~ODATFB_UNBUNCH
));
1395 order
->SetRefit(CARGO_NO_REFIT
);
1399 order
->SetDepotOrderType((OrderDepotTypeFlags
)(order
->GetDepotOrderType() & ~ODTFB_SERVICE
));
1400 order
->SetDepotActionType((OrderDepotActionFlags
)(order
->GetDepotActionType() & ~ODATFB_HALT
));
1401 order
->SetDepotActionType((OrderDepotActionFlags
)(order
->GetDepotActionType() | ODATFB_UNBUNCH
));
1410 case MOF_COND_VARIABLE
: {
1411 order
->SetConditionVariable((OrderConditionVariable
)data
);
1413 OrderConditionComparator occ
= order
->GetConditionComparator();
1414 switch (order
->GetConditionVariable()) {
1415 case OCV_UNCONDITIONALLY
:
1416 order
->SetConditionComparator(OCC_EQUALS
);
1417 order
->SetConditionValue(0);
1420 case OCV_REQUIRES_SERVICE
:
1421 if (occ
!= OCC_IS_TRUE
&& occ
!= OCC_IS_FALSE
) order
->SetConditionComparator(OCC_IS_TRUE
);
1422 order
->SetConditionValue(0);
1425 case OCV_LOAD_PERCENTAGE
:
1426 case OCV_RELIABILITY
:
1427 if (order
->GetConditionValue() > 100) order
->SetConditionValue(100);
1431 if (occ
== OCC_IS_TRUE
|| occ
== OCC_IS_FALSE
) order
->SetConditionComparator(OCC_EQUALS
);
1437 case MOF_COND_COMPARATOR
:
1438 order
->SetConditionComparator((OrderConditionComparator
)data
);
1441 case MOF_COND_VALUE
:
1442 order
->SetConditionValue(data
);
1445 case MOF_COND_DESTINATION
:
1446 order
->SetConditionSkipToOrder(data
);
1449 default: NOT_REACHED();
1452 /* Update the windows and full load flags, also for vehicles that share the same order list */
1453 Vehicle
*u
= v
->FirstShared();
1454 DeleteOrderWarnings(u
);
1455 for (; u
!= nullptr; u
= u
->NextShared()) {
1456 /* Toggle u->current_order "Full load" flag if it changed.
1457 * However, as the same flag is used for depot orders, check
1458 * whether we are not going to a depot as there are three
1459 * cases where the full load flag can be active and only
1460 * one case where the flag is used for depot orders. In the
1461 * other cases for the OrderType the flags are not used,
1462 * so do not care and those orders should not be active
1463 * when this function is called.
1465 if (sel_ord
== u
->cur_real_order_index
&&
1466 (u
->current_order
.IsType(OT_GOTO_STATION
) || u
->current_order
.IsType(OT_LOADING
)) &&
1467 u
->current_order
.GetLoadType() != order
->GetLoadType()) {
1468 u
->current_order
.SetLoadType(order
->GetLoadType());
1471 /* Unbunching data is no longer valid. */
1472 u
->ResetDepotUnbunching();
1474 InvalidateVehicleOrder(u
, VIWD_MODIFY_ORDERS
);
1478 return CommandCost();
1482 * Check if an aircraft has enough range for an order list.
1483 * @param v_new Aircraft to check.
1484 * @param v_order Vehicle currently holding the order list.
1485 * @param first First order in the source order list.
1486 * @return True if the aircraft has enough range for the orders, false otherwise.
1488 static bool CheckAircraftOrderDistance(const Aircraft
*v_new
, const Vehicle
*v_order
, const Order
*first
)
1490 if (first
== nullptr || v_new
->acache
.cached_max_range
== 0) return true;
1492 /* Iterate over all orders to check the distance between all
1493 * 'goto' orders and their respective next order (of any type). */
1494 for (const Order
*o
= first
; o
!= nullptr; o
= o
->next
) {
1495 switch (o
->GetType()) {
1496 case OT_GOTO_STATION
:
1498 case OT_GOTO_WAYPOINT
:
1499 /* If we don't have a next order, we've reached the end and must check the first order instead. */
1500 if (GetOrderDistance(o
, o
->next
!= nullptr ? o
->next
: first
, v_order
) > v_new
->acache
.cached_max_range_sqr
) return false;
1511 * Clone/share/copy an order-list of another vehicle.
1512 * @param flags operation to perform
1513 * @param action action to perform
1514 * @param veh_dst destination vehicle to clone orders to
1515 * @param veh_src source vehicle to clone orders from, if any (none for CO_UNSHARE)
1516 * @return the cost of this operation or an error
1518 CommandCost
CmdCloneOrder(DoCommandFlag flags
, CloneOptions action
, VehicleID veh_dst
, VehicleID veh_src
)
1520 Vehicle
*dst
= Vehicle::GetIfValid(veh_dst
);
1521 if (dst
== nullptr || !dst
->IsPrimaryVehicle()) return CMD_ERROR
;
1523 CommandCost ret
= CheckOwnership(dst
->owner
);
1524 if (ret
.Failed()) return ret
;
1528 Vehicle
*src
= Vehicle::GetIfValid(veh_src
);
1531 if (src
== nullptr || !src
->IsPrimaryVehicle() || dst
->type
!= src
->type
|| dst
== src
) return CMD_ERROR
;
1533 ret
= CheckOwnership(src
->owner
);
1534 if (ret
.Failed()) return ret
;
1536 /* Trucks can't share orders with busses (and visa versa) */
1537 if (src
->type
== VEH_ROAD
&& RoadVehicle::From(src
)->IsBus() != RoadVehicle::From(dst
)->IsBus()) {
1541 /* Is the vehicle already in the shared list? */
1542 if (src
->FirstShared() == dst
->FirstShared()) return CMD_ERROR
;
1544 for (const Order
*order
: src
->Orders()) {
1545 if (!OrderGoesToStation(dst
, order
)) continue;
1547 /* Allow copying unreachable destinations if they were already unreachable for the source.
1548 * This is basically to allow cloning / autorenewing / autoreplacing vehicles, while the stations
1549 * are temporarily invalid due to reconstruction. */
1550 const Station
*st
= Station::Get(order
->GetDestination());
1551 if (CanVehicleUseStation(src
, st
) && !CanVehicleUseStation(dst
, st
)) {
1552 return CommandCost(STR_ERROR_CAN_T_COPY_SHARE_ORDER
, GetVehicleCannotUseStationReason(dst
, st
));
1556 /* Check for aircraft range limits. */
1557 if (dst
->type
== VEH_AIRCRAFT
&& !CheckAircraftOrderDistance(Aircraft::From(dst
), src
, src
->GetFirstOrder())) {
1558 return CommandCost(STR_ERROR_AIRCRAFT_NOT_ENOUGH_RANGE
);
1561 if (src
->orders
== nullptr && !OrderList::CanAllocateItem()) {
1562 return CommandCost(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS
);
1565 if (flags
& DC_EXEC
) {
1566 /* If the destination vehicle had a OrderList, destroy it.
1567 * We only reset the order indices, if the new orders are obviously different.
1568 * (We mainly do this to keep the order indices valid and in range.) */
1569 DeleteVehicleOrders(dst
, false, dst
->GetNumOrders() != src
->GetNumOrders());
1571 dst
->orders
= src
->orders
;
1573 /* Link this vehicle in the shared-list */
1574 dst
->AddToShared(src
);
1576 InvalidateVehicleOrder(dst
, VIWD_REMOVE_ALL_ORDERS
);
1577 InvalidateVehicleOrder(src
, VIWD_MODIFY_ORDERS
);
1579 InvalidateWindowClassesData(GetWindowClassForVehicleType(dst
->type
), 0);
1585 Vehicle
*src
= Vehicle::GetIfValid(veh_src
);
1588 if (src
== nullptr || !src
->IsPrimaryVehicle() || dst
->type
!= src
->type
|| dst
== src
) return CMD_ERROR
;
1590 ret
= CheckOwnership(src
->owner
);
1591 if (ret
.Failed()) return ret
;
1593 /* Trucks can't copy all the orders from busses (and visa versa),
1594 * and neither can helicopters and aircraft. */
1595 for (const Order
*order
: src
->Orders()) {
1596 if (!OrderGoesToStation(dst
, order
)) continue;
1597 Station
*st
= Station::Get(order
->GetDestination());
1598 if (!CanVehicleUseStation(dst
, st
)) {
1599 return CommandCost(STR_ERROR_CAN_T_COPY_SHARE_ORDER
, GetVehicleCannotUseStationReason(dst
, st
));
1603 /* Check for aircraft range limits. */
1604 if (dst
->type
== VEH_AIRCRAFT
&& !CheckAircraftOrderDistance(Aircraft::From(dst
), src
, src
->GetFirstOrder())) {
1605 return CommandCost(STR_ERROR_AIRCRAFT_NOT_ENOUGH_RANGE
);
1608 /* make sure there are orders available */
1609 if (!Order::CanAllocateItem(src
->GetNumOrders()) || !OrderList::CanAllocateItem()) {
1610 return CommandCost(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS
);
1613 if (flags
& DC_EXEC
) {
1614 Order
*first
= nullptr;
1617 /* If the destination vehicle had an order list, destroy the chain but keep the OrderList.
1618 * We only reset the order indices, if the new orders are obviously different.
1619 * (We mainly do this to keep the order indices valid and in range.) */
1620 DeleteVehicleOrders(dst
, true, dst
->GetNumOrders() != src
->GetNumOrders());
1623 for (const Order
*order
: src
->Orders()) {
1624 *order_dst
= new Order();
1625 (*order_dst
)->AssignOrder(*order
);
1626 order_dst
= &(*order_dst
)->next
;
1628 if (dst
->orders
== nullptr) {
1629 dst
->orders
= new OrderList(first
, dst
);
1631 assert(dst
->orders
->GetFirstOrder() == nullptr);
1632 assert(!dst
->orders
->IsShared());
1634 assert(OrderList::CanAllocateItem());
1635 dst
->orders
= new OrderList(first
, dst
);
1638 InvalidateVehicleOrder(dst
, VIWD_REMOVE_ALL_ORDERS
);
1640 InvalidateWindowClassesData(GetWindowClassForVehicleType(dst
->type
), 0);
1645 case CO_UNSHARE
: return DecloneOrder(dst
, flags
);
1646 default: return CMD_ERROR
;
1649 return CommandCost();
1653 * Add/remove refit orders from an order
1654 * @param flags operation to perform
1655 * @param veh VehicleIndex of the vehicle having the order
1656 * @param order_number number of order to modify
1657 * @param cargo CargoID
1658 * @return the cost of this operation or an error
1660 CommandCost
CmdOrderRefit(DoCommandFlag flags
, VehicleID veh
, VehicleOrderID order_number
, CargoID cargo
)
1662 if (cargo
>= NUM_CARGO
&& cargo
!= CARGO_NO_REFIT
&& cargo
!= CARGO_AUTO_REFIT
) return CMD_ERROR
;
1664 const Vehicle
*v
= Vehicle::GetIfValid(veh
);
1665 if (v
== nullptr || !v
->IsPrimaryVehicle()) return CMD_ERROR
;
1667 CommandCost ret
= CheckOwnership(v
->owner
);
1668 if (ret
.Failed()) return ret
;
1670 Order
*order
= v
->GetOrder(order_number
);
1671 if (order
== nullptr) return CMD_ERROR
;
1673 /* Automatic refit cargo is only supported for goto station orders. */
1674 if (cargo
== CARGO_AUTO_REFIT
&& !order
->IsType(OT_GOTO_STATION
)) return CMD_ERROR
;
1676 if (order
->GetLoadType() & OLFB_NO_LOAD
) return CMD_ERROR
;
1678 if (flags
& DC_EXEC
) {
1679 order
->SetRefit(cargo
);
1681 /* Make the depot order an 'always go' order. */
1682 if (cargo
!= CARGO_NO_REFIT
&& order
->IsType(OT_GOTO_DEPOT
)) {
1683 order
->SetDepotOrderType((OrderDepotTypeFlags
)(order
->GetDepotOrderType() & ~ODTFB_SERVICE
));
1684 order
->SetDepotActionType((OrderDepotActionFlags
)(order
->GetDepotActionType() & ~ODATFB_HALT
));
1687 for (Vehicle
*u
= v
->FirstShared(); u
!= nullptr; u
= u
->NextShared()) {
1688 /* Update any possible open window of the vehicle */
1689 InvalidateVehicleOrder(u
, VIWD_MODIFY_ORDERS
);
1691 /* If the vehicle already got the current depot set as current order, then update current order as well */
1692 if (u
->cur_real_order_index
== order_number
&& (u
->current_order
.GetDepotOrderType() & ODTFB_PART_OF_ORDERS
)) {
1693 u
->current_order
.SetRefit(cargo
);
1698 return CommandCost();
1704 * Check the orders of a vehicle, to see if there are invalid orders and stuff
1707 void CheckOrders(const Vehicle
*v
)
1709 /* Does the user wants us to check things? */
1710 if (_settings_client
.gui
.order_review_system
== 0) return;
1712 /* Do nothing for crashed vehicles */
1713 if (v
->vehstatus
& VS_CRASHED
) return;
1715 /* Do nothing for stopped vehicles if setting is '1' */
1716 if (_settings_client
.gui
.order_review_system
== 1 && (v
->vehstatus
& VS_STOPPED
)) return;
1718 /* do nothing we we're not the first vehicle in a share-chain */
1719 if (v
->FirstShared() != v
) return;
1721 /* Only check every 20 days, so that we don't flood the message log */
1722 if (v
->owner
== _local_company
&& v
->day_counter
% 20 == 0) {
1723 StringID message
= INVALID_STRING_ID
;
1725 /* Check the order list */
1728 for (const Order
*order
: v
->Orders()) {
1730 if (order
->IsType(OT_DUMMY
)) {
1731 message
= STR_NEWS_VEHICLE_HAS_VOID_ORDER
;
1734 /* Does station have a load-bay for this vehicle? */
1735 if (order
->IsType(OT_GOTO_STATION
)) {
1736 const Station
*st
= Station::Get(order
->GetDestination());
1739 if (!CanVehicleUseStation(v
, st
)) {
1740 message
= STR_NEWS_VEHICLE_HAS_INVALID_ENTRY
;
1741 } else if (v
->type
== VEH_AIRCRAFT
&&
1742 (AircraftVehInfo(v
->engine_type
)->subtype
& AIR_FAST
) &&
1743 (st
->airport
.GetFTA()->flags
& AirportFTAClass::SHORT_STRIP
) &&
1744 !_cheats
.no_jetcrash
.value
&&
1745 message
== INVALID_STRING_ID
) {
1746 message
= STR_NEWS_PLANE_USES_TOO_SHORT_RUNWAY
;
1751 /* Check if the last and the first order are the same */
1752 if (v
->GetNumOrders() > 1) {
1753 const Order
*last
= v
->GetLastOrder();
1755 if (v
->orders
->GetFirstOrder()->Equals(*last
)) {
1756 message
= STR_NEWS_VEHICLE_HAS_DUPLICATE_ENTRY
;
1760 /* Do we only have 1 station in our order list? */
1761 if (n_st
< 2 && message
== INVALID_STRING_ID
) message
= STR_NEWS_VEHICLE_HAS_TOO_FEW_ORDERS
;
1764 if (v
->orders
!= nullptr) v
->orders
->DebugCheckSanity();
1767 /* We don't have a problem */
1768 if (message
== INVALID_STRING_ID
) return;
1770 SetDParam(0, v
->index
);
1771 AddVehicleAdviceNewsItem(AdviceType::Order
, message
, v
->index
);
1776 * Removes an order from all vehicles. Triggers when, say, a station is removed.
1777 * @param type The type of the order (OT_GOTO_[STATION|DEPOT|WAYPOINT]).
1778 * @param destination The destination. Can be a StationID, DepotID or WaypointID.
1779 * @param hangar Only used for airports in the destination.
1780 * When false, remove airport and hangar orders.
1781 * When true, remove either airport or hangar order.
1783 void RemoveOrderFromAllVehicles(OrderType type
, DestinationID destination
, bool hangar
)
1785 /* Aircraft have StationIDs for depot orders and never use DepotIDs
1786 * This fact is handled specially below
1789 /* Go through all vehicles */
1790 for (Vehicle
*v
: Vehicle::Iterate()) {
1791 if ((v
->type
== VEH_AIRCRAFT
&& v
->current_order
.IsType(OT_GOTO_DEPOT
) && !hangar
? OT_GOTO_STATION
: v
->current_order
.GetType()) == type
&&
1792 (!hangar
|| v
->type
== VEH_AIRCRAFT
) && v
->current_order
.GetDestination() == destination
) {
1793 v
->current_order
.MakeDummy();
1794 SetWindowDirty(WC_VEHICLE_VIEW
, v
->index
);
1797 /* Clear the order from the order-list */
1799 for (Order
*order
: v
->Orders()) {
1803 OrderType ot
= order
->GetType();
1804 if (ot
== OT_GOTO_DEPOT
&& (order
->GetDepotActionType() & ODATFB_NEAREST_DEPOT
) != 0) continue;
1805 if (ot
== OT_GOTO_DEPOT
&& hangar
&& v
->type
!= VEH_AIRCRAFT
) continue; // Not an aircraft? Can't have a hangar order.
1806 if (ot
== OT_IMPLICIT
|| (v
->type
== VEH_AIRCRAFT
&& ot
== OT_GOTO_DEPOT
&& !hangar
)) ot
= OT_GOTO_STATION
;
1807 if (ot
== type
&& order
->GetDestination() == destination
) {
1808 /* We want to clear implicit orders, but we don't want to make them
1809 * dummy orders. They should just vanish. Also check the actual order
1810 * type as ot is currently OT_GOTO_STATION. */
1811 if (order
->IsType(OT_IMPLICIT
)) {
1812 order
= order
->next
; // DeleteOrder() invalidates current order
1814 if (order
!= nullptr) goto restart
;
1818 /* Clear wait time */
1819 v
->orders
->UpdateTotalDuration(-order
->GetWaitTime());
1820 if (order
->IsWaitTimetabled()) {
1821 v
->orders
->UpdateTimetableDuration(-order
->GetTimetabledWait());
1822 order
->SetWaitTimetabled(false);
1824 order
->SetWaitTime(0);
1826 /* Clear order, preserving travel time */
1827 bool travel_timetabled
= order
->IsTravelTimetabled();
1829 order
->SetTravelTimetabled(travel_timetabled
);
1831 for (const Vehicle
*w
= v
->FirstShared(); w
!= nullptr; w
= w
->NextShared()) {
1832 /* In GUI, simulate by removing the order and adding it back */
1833 InvalidateVehicleOrder(w
, id
| (INVALID_VEH_ORDER_ID
<< 8));
1834 InvalidateVehicleOrder(w
, (INVALID_VEH_ORDER_ID
<< 8) | id
);
1840 OrderBackup::RemoveOrder(type
, destination
, hangar
);
1844 * Checks if a vehicle has a depot in its order list.
1845 * @return True iff at least one order is a depot order.
1847 bool Vehicle::HasDepotOrder() const
1849 for (const Order
*order
: this->Orders()) {
1850 if (order
->IsType(OT_GOTO_DEPOT
)) return true;
1857 * Delete all orders from a vehicle
1858 * @param v Vehicle whose orders to reset
1859 * @param keep_orderlist If true, do not free the order list, only empty it.
1860 * @param reset_order_indices If true, reset cur_implicit_order_index and cur_real_order_index
1861 * and cancel the current full load order (if the vehicle is loading).
1862 * If false, _you_ have to make sure the order indices are valid after
1863 * your messing with them!
1865 void DeleteVehicleOrders(Vehicle
*v
, bool keep_orderlist
, bool reset_order_indices
)
1867 DeleteOrderWarnings(v
);
1869 if (v
->IsOrderListShared()) {
1870 /* Remove ourself from the shared order list. */
1871 v
->RemoveFromShared();
1872 v
->orders
= nullptr;
1873 } else if (v
->orders
!= nullptr) {
1874 /* Remove the orders */
1875 v
->orders
->FreeChain(keep_orderlist
);
1876 if (!keep_orderlist
) v
->orders
= nullptr;
1879 /* Unbunching data is no longer valid. */
1880 v
->ResetDepotUnbunching();
1882 if (reset_order_indices
) {
1883 v
->cur_implicit_order_index
= v
->cur_real_order_index
= 0;
1884 if (v
->current_order
.IsType(OT_LOADING
)) {
1885 CancelLoadingDueToDeletedOrder(v
);
1891 * Clamp the service interval to the correct min/max. The actual min/max values
1892 * depend on whether it's in days, minutes, or percent.
1893 * @param interval The proposed service interval.
1894 * @param ispercent Whether the interval is a percent.
1895 * @return The service interval clamped to use the chosen units.
1897 uint16_t GetServiceIntervalClamped(int interval
, bool ispercent
)
1899 /* Service intervals are in percents. */
1900 if (ispercent
) return Clamp(interval
, MIN_SERVINT_PERCENT
, MAX_SERVINT_PERCENT
);
1902 /* Service intervals are in minutes. */
1903 if (TimerGameEconomy::UsingWallclockUnits(_game_mode
== GM_MENU
)) return Clamp(interval
, MIN_SERVINT_MINUTES
, MAX_SERVINT_MINUTES
);
1905 /* Service intervals are in days. */
1906 return Clamp(interval
, MIN_SERVINT_DAYS
, MAX_SERVINT_DAYS
);
1911 * Check if a vehicle has any valid orders
1913 * @return false if there are no valid orders
1914 * @note Conditional orders are not considered valid destination orders
1917 static bool CheckForValidOrders(const Vehicle
*v
)
1919 for (const Order
*order
: v
->Orders()) {
1920 switch (order
->GetType()) {
1921 case OT_GOTO_STATION
:
1923 case OT_GOTO_WAYPOINT
:
1935 * Compare the variable and value based on the given comparator.
1937 static bool OrderConditionCompare(OrderConditionComparator occ
, int variable
, int value
)
1940 case OCC_EQUALS
: return variable
== value
;
1941 case OCC_NOT_EQUALS
: return variable
!= value
;
1942 case OCC_LESS_THAN
: return variable
< value
;
1943 case OCC_LESS_EQUALS
: return variable
<= value
;
1944 case OCC_MORE_THAN
: return variable
> value
;
1945 case OCC_MORE_EQUALS
: return variable
>= value
;
1946 case OCC_IS_TRUE
: return variable
!= 0;
1947 case OCC_IS_FALSE
: return variable
== 0;
1948 default: NOT_REACHED();
1952 template <typename T
, std::enable_if_t
<std::is_base_of
<StrongTypedefBase
, T
>::value
, int> = 0>
1953 static bool OrderConditionCompare(OrderConditionComparator occ
, T variable
, int value
)
1955 return OrderConditionCompare(occ
, variable
.base(), value
);
1959 * Process a conditional order and determine the next order.
1960 * @param order the order the vehicle currently has
1961 * @param v the vehicle to update
1962 * @return index of next order to jump to, or INVALID_VEH_ORDER_ID to use the next order
1964 VehicleOrderID
ProcessConditionalOrder(const Order
*order
, const Vehicle
*v
)
1966 if (order
->GetType() != OT_CONDITIONAL
) return INVALID_VEH_ORDER_ID
;
1968 bool skip_order
= false;
1969 OrderConditionComparator occ
= order
->GetConditionComparator();
1970 uint16_t value
= order
->GetConditionValue();
1972 switch (order
->GetConditionVariable()) {
1973 case OCV_LOAD_PERCENTAGE
: skip_order
= OrderConditionCompare(occ
, CalcPercentVehicleFilled(v
, nullptr), value
); break;
1974 case OCV_RELIABILITY
: skip_order
= OrderConditionCompare(occ
, ToPercent16(v
->reliability
), value
); break;
1975 case OCV_MAX_RELIABILITY
: skip_order
= OrderConditionCompare(occ
, ToPercent16(v
->GetEngine()->reliability
), value
); break;
1976 case OCV_MAX_SPEED
: skip_order
= OrderConditionCompare(occ
, v
->GetDisplayMaxSpeed() * 10 / 16, value
); break;
1977 case OCV_AGE
: skip_order
= OrderConditionCompare(occ
, TimerGameCalendar::DateToYear(v
->age
), value
); break;
1978 case OCV_REQUIRES_SERVICE
: skip_order
= OrderConditionCompare(occ
, v
->NeedsServicing(), value
); break;
1979 case OCV_UNCONDITIONALLY
: skip_order
= true; break;
1980 case OCV_REMAINING_LIFETIME
: skip_order
= OrderConditionCompare(occ
, std::max(TimerGameCalendar::DateToYear(v
->max_age
- v
->age
+ CalendarTime::DAYS_IN_LEAP_YEAR
- 1), TimerGameCalendar::Year(0)), value
); break;
1981 default: NOT_REACHED();
1984 return skip_order
? order
->GetConditionSkipToOrder() : (VehicleOrderID
)INVALID_VEH_ORDER_ID
;
1988 * Update the vehicle's destination tile from an order.
1989 * @param order the order the vehicle currently has
1990 * @param v the vehicle to update
1991 * @param conditional_depth the depth (amount of steps) to go with conditional orders. This to prevent infinite loops.
1992 * @param pbs_look_ahead Whether we are forecasting orders for pbs reservations in advance. If true, the order indices must not be modified.
1994 bool UpdateOrderDest(Vehicle
*v
, const Order
*order
, int conditional_depth
, bool pbs_look_ahead
)
1996 if (conditional_depth
> v
->GetNumOrders()) {
1997 v
->current_order
.Free();
1998 v
->SetDestTile(TileIndex
{});
2002 switch (order
->GetType()) {
2003 case OT_GOTO_STATION
:
2004 v
->SetDestTile(v
->GetOrderStationLocation(order
->GetDestination()));
2008 if ((order
->GetDepotOrderType() & ODTFB_SERVICE
) && !v
->NeedsServicing()) {
2009 assert(!pbs_look_ahead
);
2010 UpdateVehicleTimetable(v
, true);
2011 v
->IncrementRealOrderIndex();
2015 if (v
->current_order
.GetDepotActionType() & ODATFB_NEAREST_DEPOT
) {
2016 /* If the vehicle can't find its destination, delay its next search.
2017 * In case many vehicles are in this state, use the vehicle index to spread out pathfinder calls. */
2018 if (v
->dest_tile
== 0 && TimerGameEconomy::date_fract
!= (v
->index
% Ticks::DAY_TICKS
)) break;
2020 /* We need to search for the nearest depot (hangar). */
2021 ClosestDepot closestDepot
= v
->FindClosestDepot();
2023 if (closestDepot
.found
) {
2024 /* PBS reservations cannot reverse */
2025 if (pbs_look_ahead
&& closestDepot
.reverse
) return false;
2027 v
->SetDestTile(closestDepot
.location
);
2028 v
->current_order
.SetDestination(closestDepot
.destination
);
2030 /* If there is no depot in front, reverse automatically (trains only) */
2031 if (v
->type
== VEH_TRAIN
&& closestDepot
.reverse
) Command
<CMD_REVERSE_TRAIN_DIRECTION
>::Do(DC_EXEC
, v
->index
, false);
2033 if (v
->type
== VEH_AIRCRAFT
) {
2034 Aircraft
*a
= Aircraft::From(v
);
2035 if (a
->state
== FLYING
&& a
->targetairport
!= closestDepot
.destination
) {
2036 /* The aircraft is now heading for a different hangar than the next in the orders */
2037 AircraftNextAirportPos_and_Order(a
);
2043 /* If there is no depot, we cannot help PBS either. */
2044 if (pbs_look_ahead
) return false;
2046 UpdateVehicleTimetable(v
, true);
2047 v
->IncrementRealOrderIndex();
2049 if (v
->type
!= VEH_AIRCRAFT
) {
2050 v
->SetDestTile(Depot::Get(order
->GetDestination())->xy
);
2052 Aircraft
*a
= Aircraft::From(v
);
2053 DestinationID destination
= a
->current_order
.GetDestination();
2054 if (a
->targetairport
!= destination
) {
2055 /* The aircraft is now heading for a different hangar than the next in the orders */
2056 a
->SetDestTile(a
->GetOrderStationLocation(destination
));
2063 case OT_GOTO_WAYPOINT
:
2064 v
->SetDestTile(Waypoint::Get(order
->GetDestination())->xy
);
2067 case OT_CONDITIONAL
: {
2068 assert(!pbs_look_ahead
);
2069 VehicleOrderID next_order
= ProcessConditionalOrder(order
, v
);
2070 if (next_order
!= INVALID_VEH_ORDER_ID
) {
2071 /* Jump to next_order. cur_implicit_order_index becomes exactly that order,
2072 * cur_real_order_index might come after next_order. */
2073 UpdateVehicleTimetable(v
, false);
2074 v
->cur_implicit_order_index
= v
->cur_real_order_index
= next_order
;
2075 v
->UpdateRealOrderIndex();
2076 v
->current_order_time
+= v
->GetOrder(v
->cur_real_order_index
)->GetTimetabledTravel();
2078 /* Disable creation of implicit orders.
2079 * When inserting them we do not know that we would have to make the conditional orders point to them. */
2080 if (v
->IsGroundVehicle()) {
2081 uint16_t &gv_flags
= v
->GetGroundVehicleFlags();
2082 SetBit(gv_flags
, GVF_SUPPRESS_IMPLICIT_ORDERS
);
2085 UpdateVehicleTimetable(v
, true);
2086 v
->IncrementRealOrderIndex();
2092 v
->SetDestTile(TileIndex
{});
2096 assert(v
->cur_implicit_order_index
< v
->GetNumOrders());
2097 assert(v
->cur_real_order_index
< v
->GetNumOrders());
2099 /* Get the current order */
2100 order
= v
->GetOrder(v
->cur_real_order_index
);
2101 if (order
!= nullptr && order
->IsType(OT_IMPLICIT
)) {
2102 assert(v
->GetNumManualOrders() == 0);
2106 if (order
== nullptr) {
2107 v
->current_order
.Free();
2108 v
->SetDestTile(TileIndex
{});
2112 v
->current_order
= *order
;
2113 return UpdateOrderDest(v
, order
, conditional_depth
+ 1, pbs_look_ahead
);
2117 * Handle the orders of a vehicle and determine the next place
2118 * to go to if needed.
2119 * @param v the vehicle to do this for.
2120 * @return true *if* the vehicle is eligible for reversing
2121 * (basically only when leaving a station).
2123 bool ProcessOrders(Vehicle
*v
)
2125 switch (v
->current_order
.GetType()) {
2127 /* Let a depot order in the orderlist interrupt. */
2128 if (!(v
->current_order
.GetDepotOrderType() & ODTFB_PART_OF_ORDERS
)) return false;
2134 case OT_LEAVESTATION
:
2135 if (v
->type
!= VEH_AIRCRAFT
) return false;
2142 * Reversing because of order change is allowed only just after leaving a
2143 * station (and the difficulty setting to allowed, of course)
2144 * this can be detected because only after OT_LEAVESTATION, current_order
2145 * will be reset to nothing. (That also happens if no order, but in that case
2146 * it won't hit the point in code where may_reverse is checked)
2148 bool may_reverse
= v
->current_order
.IsType(OT_NOTHING
);
2150 /* Check if we've reached a 'via' destination. */
2151 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
)) &&
2152 IsTileType(v
->tile
, MP_STATION
) &&
2153 v
->current_order
.GetDestination() == GetStationIndex(v
->tile
)) {
2154 v
->DeleteUnreachedImplicitOrders();
2155 /* We set the last visited station here because we do not want
2156 * the train to stop at this 'via' station if the next order
2157 * is a no-non-stop order; in that case not setting the last
2158 * visited station will cause the vehicle to still stop. */
2159 v
->last_station_visited
= v
->current_order
.GetDestination();
2160 UpdateVehicleTimetable(v
, true);
2161 v
->IncrementImplicitOrderIndex();
2164 /* Get the current order */
2165 assert(v
->cur_implicit_order_index
== 0 || v
->cur_implicit_order_index
< v
->GetNumOrders());
2166 v
->UpdateRealOrderIndex();
2168 const Order
*order
= v
->GetOrder(v
->cur_real_order_index
);
2169 if (order
!= nullptr && order
->IsType(OT_IMPLICIT
)) {
2170 assert(v
->GetNumManualOrders() == 0);
2174 /* If no order, do nothing. */
2175 if (order
== nullptr || (v
->type
== VEH_AIRCRAFT
&& !CheckForValidOrders(v
))) {
2176 if (v
->type
== VEH_AIRCRAFT
) {
2177 /* Aircraft do something vastly different here, so handle separately */
2178 HandleMissingAircraftOrders(Aircraft::From(v
));
2182 v
->current_order
.Free();
2183 v
->SetDestTile(TileIndex
{});
2187 /* If it is unchanged, keep it. */
2188 if (order
->Equals(v
->current_order
) && (v
->type
== VEH_AIRCRAFT
|| v
->dest_tile
!= 0) &&
2189 (v
->type
!= VEH_SHIP
|| !order
->IsType(OT_GOTO_STATION
) || Station::Get(order
->GetDestination())->ship_station
.tile
!= INVALID_TILE
)) {
2193 /* Otherwise set it, and determine the destination tile. */
2194 v
->current_order
= *order
;
2196 InvalidateVehicleOrder(v
, VIWD_MODIFY_ORDERS
);
2207 SetWindowClassesDirty(GetWindowClassForVehicleType(v
->type
));
2211 return UpdateOrderDest(v
, order
) && may_reverse
;
2215 * Check whether the given vehicle should stop at the given station
2216 * based on this order and the non-stop settings.
2217 * @param v the vehicle that might be stopping.
2218 * @param station the station to stop at.
2219 * @return true if the vehicle should stop.
2221 bool Order::ShouldStopAtStation(const Vehicle
*v
, StationID station
) const
2223 bool is_dest_station
= this->IsType(OT_GOTO_STATION
) && this->dest
== station
;
2225 return (!this->IsType(OT_GOTO_DEPOT
) || (this->GetDepotOrderType() & ODTFB_PART_OF_ORDERS
) != 0) &&
2226 v
->last_station_visited
!= station
&& // Do stop only when we've not just been there
2227 /* Finally do stop when there is no non-stop flag set for this type of station. */
2228 !(this->GetNonStopType() & (is_dest_station
? ONSF_NO_STOP_AT_DESTINATION_STATION
: ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS
));
2231 bool Order::CanLoadOrUnload() const
2233 return (this->IsType(OT_GOTO_STATION
) || this->IsType(OT_IMPLICIT
)) &&
2234 (this->GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION
) == 0 &&
2235 ((this->GetLoadType() & OLFB_NO_LOAD
) == 0 ||
2236 (this->GetUnloadType() & OUFB_NO_UNLOAD
) == 0);
2240 * A vehicle can leave the current station with cargo if:
2241 * 1. it can load cargo here OR
2242 * 2a. it could leave the last station with cargo AND
2243 * 2b. it doesn't have to unload all cargo here.
2245 bool Order::CanLeaveWithCargo(bool has_cargo
) const
2247 return (this->GetLoadType() & OLFB_NO_LOAD
) == 0 || (has_cargo
&&
2248 (this->GetUnloadType() & (OUFB_UNLOAD
| OUFB_TRANSFER
)) == 0);