# order_cmd.cpp

Go to the documentation of this file.

    00001 /* $Id$ */
    00002
    00003 /*
    00004  * This file is part of OpenTTD.
    00005  * 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.
    00006  * 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.
    00007  * 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/>.
    00008  */
    00009
    00012 #include "stdafx.h"
    00013 #include "debug.h"
    00014 #include "cmd_helper.h"
    00015 #include "command_func.h"
    00016 #include "company_func.h"
    00017 #include "news_func.h"
    00018 #include "strings_func.h"
    00019 #include "timetable.h"
    00020 #include "vehicle_func.h"
    00021 #include "depot_base.h"
    00022 #include "core/pool_func.hpp"
    00023 #include "core/random_func.hpp"
    00024 #include "aircraft.h"
    00025 #include "roadveh.h"
    00026 #include "station_base.h"
    00027 #include "waypoint_base.h"
    00028 #include "company_base.h"
    00029 #include "order_backup.h"
    00030
    00031 #include "table/strings.h"
    00032
    00033 /* DestinationID must be at least as large as every these below, because it can
    00034  * be any of them
    00035  */
    00036 assert_compile(sizeof(DestinationID) >= sizeof(DepotID));
    00037 assert_compile(sizeof(DestinationID) >= sizeof(StationID));
    00038
    00039 OrderPool _order_pool("Order");
    00040 INSTANTIATE_POOL_METHODS(Order)
    00041 OrderListPool _orderlist_pool("OrderList");
    00042 INSTANTIATE_POOL_METHODS(OrderList)
    00043
    00045 Order::~Order()
    00046 {
    00047   if (CleaningPool()) return;
    00048
    00049   /* We can visit oil rigs and buoys that are not our own. They will be shown in
    00050    * the list of stations. So, we need to invalidate that window if needed. */
    00051   if (this->IsType(OT_GOTO_STATION) || this->IsType(OT_GOTO_WAYPOINT)) {
    00052     BaseStation *bs = BaseStation::GetIfValid(this->GetDestination());
    00053     if (bs != NULL && bs->owner == OWNER_NONE) InvalidateWindowClassesData(WC_STATION_LIST, 0);
    00054   }
    00055 }
    00056
    00061 void Order::Free()
    00062 {
    00063   this->type  = OT_NOTHING;
    00064   this->flags = 0;
    00065   this->dest  = 0;
    00066   this->next  = NULL;
    00067 }
    00068
    00073 void Order::MakeGoToStation(StationID destination)
    00074 {
    00075   this->type = OT_GOTO_STATION;
    00076   this->flags = 0;
    00077   this->dest = destination;
    00078 }
    00079
    00089 void Order::MakeGoToDepot(DepotID destination, OrderDepotTypeFlags order, OrderNonStopFlags non_stop_type, OrderDepotActionFlags action, CargoID cargo, byte subtype)
    00090 {
    00091   this->type = OT_GOTO_DEPOT;
    00092   this->SetDepotOrderType(order);
    00093   this->SetDepotActionType(action);
    00094   this->SetNonStopType(non_stop_type);
    00095   this->dest = destination;
    00096   this->SetRefit(cargo, subtype);
    00097 }
    00098
    00103 void Order::MakeGoToWaypoint(StationID destination)
    00104 {
    00105   this->type = OT_GOTO_WAYPOINT;
    00106   this->flags = 0;
    00107   this->dest = destination;
    00108 }
    00109
    00114 void Order::MakeLoading(bool ordered)
    00115 {
    00116   this->type = OT_LOADING;
    00117   if (!ordered) this->flags = 0;
    00118 }
    00119
    00123 void Order::MakeLeaveStation()
    00124 {
    00125   this->type = OT_LEAVESTATION;
    00126   this->flags = 0;
    00127 }
    00128
    00132 void Order::MakeDummy()
    00133 {
    00134   this->type = OT_DUMMY;
    00135   this->flags = 0;
    00136 }
    00137
    00142 void Order::MakeConditional(VehicleOrderID order)
    00143 {
    00144   this->type = OT_CONDITIONAL;
    00145   this->flags = order;
    00146   this->dest = 0;
    00147 }
    00148
    00153 void Order::MakeImplicit(StationID destination)
    00154 {
    00155   this->type = OT_IMPLICIT;
    00156   this->dest = destination;
    00157 }
    00158
    00165 void Order::SetRefit(CargoID cargo, byte subtype)
    00166 {
    00167   this->refit_cargo = cargo;
    00168   this->refit_subtype = subtype;
    00169 }
    00170
    00176 bool Order::Equals(const Order &other) const
    00177 {
    00178   /* In case of go to nearest depot orders we need "only" compare the flags
    00179    * with the other and not the nearest depot order bit or the actual
    00180    * destination because those get clear/filled in during the order
    00181    * evaluation. If we do not do this the order will continuously be seen as
    00182    * a different order and it will try to find a "nearest depot" every tick. */
    00183   if ((this->IsType(OT_GOTO_DEPOT) && this->type == other.type) &&
    00184       ((this->GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0 ||
    00185        (other.GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0)) {
    00186     return this->GetDepotOrderType() == other.GetDepotOrderType() &&
    00187         (this->GetDepotActionType() & ~ODATFB_NEAREST_DEPOT) == (other.GetDepotActionType() & ~ODATFB_NEAREST_DEPOT);
    00188   }
    00189
    00190   return this->type == other.type && this->flags == other.flags && this->dest == other.dest;
    00191 }
    00192
    00199 uint32 Order::Pack() const
    00200 {
    00201   return this->dest << 16 | this->flags << 8 | this->type;
    00202 }
    00203
    00209 uint16 Order::MapOldOrder() const
    00210 {
    00211   uint16 order = this->GetType();
    00212   switch (this->type) {
    00213     case OT_GOTO_STATION:
    00214       if (this->GetUnloadType() & OUFB_UNLOAD) SetBit(order, 5);
    00215       if (this->GetLoadType() & OLFB_FULL_LOAD) SetBit(order, 6);
    00216       if (this->GetNonStopType() & ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS) SetBit(order, 7);
    00217       order |= GB(this->GetDestination(), 0, 8) << 8;
    00218       break;
    00219     case OT_GOTO_DEPOT:
    00220       if (!(this->GetDepotOrderType() & ODTFB_PART_OF_ORDERS)) SetBit(order, 6);
    00221       SetBit(order, 7);
    00222       order |= GB(this->GetDestination(), 0, 8) << 8;
    00223       break;
    00224     case OT_LOADING:
    00225       if (this->GetLoadType() & OLFB_FULL_LOAD) SetBit(order, 6);
    00226       break;
    00227   }
    00228   return order;
    00229 }
    00230
    00235 Order::Order(uint32 packed)
    00236 {
    00237   this->type    = (OrderType)GB(packed,  0,  8);
    00238   this->flags   = GB(packed,  8,  8);
    00239   this->dest    = GB(packed, 16, 16);
    00240   this->next    = NULL;
    00241   this->refit_cargo   = CT_NO_REFIT;
    00242   this->refit_subtype = 0;
    00243   this->wait_time     = 0;
    00244   this->travel_time   = 0;
    00245   this->max_speed     = UINT16_MAX;
    00246 }
    00247
    00253 void InvalidateVehicleOrder(const Vehicle *v, int data)
    00254 {
    00255   SetWindowDirty(WC_VEHICLE_VIEW, v->index);
    00256
    00257   if (data != 0) {
    00258     /* Calls SetDirty() too */
    00259     InvalidateWindowData(WC_VEHICLE_ORDERS,    v->index, data);
    00260     InvalidateWindowData(WC_VEHICLE_TIMETABLE, v->index, data);
    00261     return;
    00262   }
    00263
    00264   SetWindowDirty(WC_VEHICLE_ORDERS,    v->index);
    00265   SetWindowDirty(WC_VEHICLE_TIMETABLE, v->index);
    00266 }
    00267
    00275 void Order::AssignOrder(const Order &other)
    00276 {
    00277   this->type  = other.type;
    00278   this->flags = other.flags;
    00279   this->dest  = other.dest;
    00280
    00281   this->refit_cargo   = other.refit_cargo;
    00282   this->refit_subtype = other.refit_subtype;
    00283
    00284   this->wait_time   = other.wait_time;
    00285   this->travel_time = other.travel_time;
    00286   this->max_speed   = other.max_speed;
    00287 }
    00288
    00294 void OrderList::Initialize(Order *chain, Vehicle *v)
    00295 {
    00296   this->first = chain;
    00297   this->first_shared = v;
    00298
    00299   this->num_orders = 0;
    00300   this->num_manual_orders = 0;
    00301   this->num_vehicles = 1;
    00302   this->timetable_duration = 0;
    00303
    00304   for (Order *o = this->first; o != NULL; o = o->next) {
    00305     ++this->num_orders;
    00306     if (!o->IsType(OT_IMPLICIT)) ++this->num_manual_orders;
    00307     this->timetable_duration += o->wait_time + o->travel_time;
    00308   }
    00309
    00310   for (Vehicle *u = this->first_shared->PreviousShared(); u != NULL; u = u->PreviousShared()) {
    00311     ++this->num_vehicles;
    00312     this->first_shared = u;
    00313   }
    00314
    00315   for (const Vehicle *u = v->NextShared(); u != NULL; u = u->NextShared()) ++this->num_vehicles;
    00316 }
    00317
    00323 void OrderList::FreeChain(bool keep_orderlist)
    00324 {
    00325   Order *next;
    00326   for (Order *o = this->first; o != NULL; o = next) {
    00327     next = o->next;
    00328     delete o;
    00329   }
    00330
    00331   if (keep_orderlist) {
    00332     this->first = NULL;
    00333     this->num_orders = 0;
    00334     this->num_manual_orders = 0;
    00335     this->timetable_duration = 0;
    00336   } else {
    00337     delete this;
    00338   }
    00339 }
    00340
    00346 Order *OrderList::GetOrderAt(int index) const
    00347 {
    00348   if (index < 0) return NULL;
    00349
    00350   Order *order = this->first;
    00351
    00352   while (order != NULL && index-- > 0) {
    00353     order = order->next;
    00354   }
    00355   return order;
    00356 }
    00357
    00367 const Order *OrderList::GetBestLoadableNext(const Vehicle *v, const Order *o2, const Order *o1) const
    00368 {
    00369   SmallMap<CargoID, uint> capacities;
    00370   v->GetConsistFreeCapacities(capacities);
    00371   uint loadable1 = 0;
    00372   uint loadable2 = 0;
    00373   StationID st1 = o1->GetDestination();
    00374   StationID st2 = o2->GetDestination();
    00375   const Station *cur_station = Station::Get(v->last_station_visited);
    00376   for (SmallPair<CargoID, uint> *i = capacities.Begin(); i != capacities.End(); ++i) {
    00377     const StationCargoPacketMap *loadable_packets = cur_station->goods[i->first].cargo.Packets();
    00378     uint loadable_cargo = 0;
    00379     std::pair<StationCargoPacketMap::const_iterator, StationCargoPacketMap::const_iterator> p =
    00380         loadable_packets->equal_range(st1);
    00381     for (StationCargoPacketMap::const_iterator j = p.first; j != p.second; ++j) {
    00382       loadable_cargo = (*j)->Count();
    00383     }
    00384     loadable1 += min(i->second, loadable_cargo);
    00385
    00386     loadable_cargo = 0;
    00387     p = loadable_packets->equal_range(st2);
    00388     for (StationCargoPacketMap::const_iterator j = p.first; j != p.second; ++j) {
    00389       loadable_cargo = (*j)->Count();
    00390     }
    00391     loadable2 += min(i->second, loadable_cargo);
    00392   }
    00393   if (loadable1 == loadable2) return RandomRange(2) == 0 ? o1 : o2;
    00394   return loadable1 > loadable2 ? o1 : o2;
    00395 }
    00396
    00408 const Order *OrderList::GetNextStoppingOrder(const Vehicle *v, const Order *next, uint hops, bool is_loading) const
    00409 {
    00410   if (hops > this->GetNumOrders() || next == NULL) return NULL;
    00411
    00412   if (next->IsType(OT_CONDITIONAL)) {
    00413     if (is_loading && next->GetConditionVariable() == OCV_LOAD_PERCENTAGE) {
    00414       /* If the condition is based on load percentage we can't
    00415        * tell what it will do. So we choose randomly. */
    00416       const Order *skip_to = this->GetNextStoppingOrder(v,
    00417           this->GetOrderAt(next->GetConditionSkipToOrder()),
    00418           hops + 1);
    00419       const Order *advance = this->GetNextStoppingOrder(v,
    00420           this->GetNext(next), hops + 1);
    00421       if (advance == NULL) return skip_to;
    00422       if (skip_to == NULL) return advance;
    00423       return this->GetBestLoadableNext(v, skip_to, advance);
    00424     }
    00425     /* Otherwise we're optimistic and expect that the
    00426      * condition value won't change until it's evaluated. */
    00427     VehicleOrderID skip_to = ProcessConditionalOrder(next, v);
    00428     if (skip_to != INVALID_VEH_ORDER_ID) {
    00429       return this->GetNextStoppingOrder(v, this->GetOrderAt(skip_to),
    00430           hops + 1);
    00431     }
    00432     return this->GetNextStoppingOrder(v, this->GetNext(next), hops + 1);
    00433   }
    00434
    00435   if (next->IsType(OT_GOTO_DEPOT)) {
    00436     if (next->GetDepotActionType() == ODATFB_HALT) return NULL;
    00437     if (next->IsRefit()) return next;
    00438   }
    00439
    00440   if (!next->CanLoadOrUnload()) {
    00441     return this->GetNextStoppingOrder(v, this->GetNext(next), hops + 1);
    00442   }
    00443
    00444   return next;
    00445 }
    00446
    00454 StationID OrderList::GetNextStoppingStation(const Vehicle *v) const
    00455 {
    00456
    00457   const Order *next = this->GetOrderAt(v->cur_implicit_order_index);
    00458   if (next == NULL) {
    00459     next = this->GetFirstOrder();
    00460     if (next == NULL) return INVALID_STATION;
    00461   } else {
    00462     /* GetNext never returns NULL if there is a valid station in the list.
    00463      * As the given "next" is already valid and a station in the list, we
    00464      * don't have to check for NULL here.
    00465      */
    00466     next = this->GetNext(next);
    00467     assert(next != NULL);
    00468   }
    00469
    00470   uint hops = 0;
    00471   do {
    00472     next = this->GetNextStoppingOrder(v, next, ++hops, true);
    00473     /* Don't return a next stop if the vehicle has to unload everything. */
    00474     if (next == NULL || (next->GetDestination() == v->last_station_visited &&
    00475         (next->GetUnloadType() & (OUFB_TRANSFER | OUFB_UNLOAD)) == 0)) {
    00476       return INVALID_STATION;
    00477     }
    00478   } while (next->IsType(OT_GOTO_DEPOT) || next->GetDestination() == v->last_station_visited);
    00479
    00480   return next->GetDestination();
    00481 }
    00482
    00488 void OrderList::InsertOrderAt(Order *new_order, int index)
    00489 {
    00490   if (this->first == NULL) {
    00491     this->first = new_order;
    00492   } else {
    00493     if (index == 0) {
    00494       /* Insert as first or only order */
    00495       new_order->next = this->first;
    00496       this->first = new_order;
    00497     } else if (index >= this->num_orders) {
    00498       /* index is after the last order, add it to the end */
    00499       this->GetLastOrder()->next = new_order;
    00500     } else {
    00501       /* Put the new order in between */
    00502       Order *order = this->GetOrderAt(index - 1);
    00503       new_order->next = order->next;
    00504       order->next = new_order;
    00505     }
    00506   }
    00507   ++this->num_orders;
    00508   if (!new_order->IsType(OT_IMPLICIT)) ++this->num_manual_orders;
    00509   this->timetable_duration += new_order->wait_time + new_order->travel_time;
    00510
    00511   /* We can visit oil rigs and buoys that are not our own. They will be shown in
    00512    * the list of stations. So, we need to invalidate that window if needed. */
    00513   if (new_order->IsType(OT_GOTO_STATION) || new_order->IsType(OT_GOTO_WAYPOINT)) {
    00514     BaseStation *bs = BaseStation::Get(new_order->GetDestination());
    00515     if (bs->owner == OWNER_NONE) InvalidateWindowClassesData(WC_STATION_LIST, 0);
    00516   }
    00517
    00518 }
    00519
    00520
    00525 void OrderList::DeleteOrderAt(int index)
    00526 {
    00527   if (index >= this->num_orders) return;
    00528
    00529   Order *to_remove;
    00530
    00531   if (index == 0) {
    00532     to_remove = this->first;
    00533     this->first = to_remove->next;
    00534   } else {
    00535     Order *prev = GetOrderAt(index - 1);
    00536     to_remove = prev->next;
    00537     prev->next = to_remove->next;
    00538   }
    00539   --this->num_orders;
    00540   if (!to_remove->IsType(OT_IMPLICIT)) --this->num_manual_orders;
    00541   this->timetable_duration -= (to_remove->wait_time + to_remove->travel_time);
    00542   delete to_remove;
    00543 }
    00544
    00550 void OrderList::MoveOrder(int from, int to)
    00551 {
    00552   if (from >= this->num_orders || to >= this->num_orders || from == to) return;
    00553
    00554   Order *moving_one;
    00555
    00556   /* Take the moving order out of the pointer-chain */
    00557   if (from == 0) {
    00558     moving_one = this->first;
    00559     this->first = moving_one->next;
    00560   } else {
    00561     Order *one_before = GetOrderAt(from - 1);
    00562     moving_one = one_before->next;
    00563     one_before->next = moving_one->next;
    00564   }
    00565
    00566   /* Insert the moving_order again in the pointer-chain */
    00567   if (to == 0) {
    00568     moving_one->next = this->first;
    00569     this->first = moving_one;
    00570   } else {
    00571     Order *one_before = GetOrderAt(to - 1);
    00572     moving_one->next = one_before->next;
    00573     one_before->next = moving_one;
    00574   }
    00575 }
    00576
    00582 void OrderList::RemoveVehicle(Vehicle *v)
    00583 {
    00584   --this->num_vehicles;
    00585   if (v == this->first_shared) this->first_shared = v->NextShared();
    00586 }
    00587
    00592 bool OrderList::IsVehicleInSharedOrdersList(const Vehicle *v) const
    00593 {
    00594   for (const Vehicle *v_shared = this->first_shared; v_shared != NULL; v_shared = v_shared->NextShared()) {
    00595     if (v_shared == v) return true;
    00596   }
    00597
    00598   return false;
    00599 }
    00600
    00606 int OrderList::GetPositionInSharedOrderList(const Vehicle *v) const
    00607 {
    00608   int count = 0;
    00609   for (const Vehicle *v_shared = v->PreviousShared(); v_shared != NULL; v_shared = v_shared->PreviousShared()) count++;
    00610   return count;
    00611 }
    00612
    00617 bool OrderList::IsCompleteTimetable() const
    00618 {
    00619   for (Order *o = this->first; o != NULL; o = o->next) {
    00620     /* Implicit orders are, by definition, not timetabled. */
    00621     if (o->IsType(OT_IMPLICIT)) continue;
    00622     if (!o->IsCompletelyTimetabled()) return false;
    00623   }
    00624   return true;
    00625 }
    00626
    00630 void OrderList::DebugCheckSanity() const
    00631 {
    00632   VehicleOrderID check_num_orders = 0;
    00633   VehicleOrderID check_num_manual_orders = 0;
    00634   uint check_num_vehicles = 0;
    00635   Ticks check_timetable_duration = 0;
    00636
    00637   DEBUG(misc, 6, "Checking OrderList %hu for sanity...", this->index);
    00638
    00639   for (const Order *o = this->first; o != NULL; o = o->next) {
    00640     ++check_num_orders;
    00641     if (!o->IsType(OT_IMPLICIT)) ++check_num_manual_orders;
    00642     check_timetable_duration += o->wait_time + o->travel_time;
    00643   }
    00644   assert(this->num_orders == check_num_orders);
    00645   assert(this->num_manual_orders == check_num_manual_orders);
    00646   assert(this->timetable_duration == check_timetable_duration);
    00647
    00648   for (const Vehicle *v = this->first_shared; v != NULL; v = v->NextShared()) {
    00649     ++check_num_vehicles;
    00650     assert(v->orders.list == this);
    00651   }
    00652   assert(this->num_vehicles == check_num_vehicles);
    00653   DEBUG(misc, 6, "... detected %u orders (%u manual), %u vehicles, %i ticks",
    00654       (uint)this->num_orders, (uint)this->num_manual_orders,
    00655       this->num_vehicles, this->timetable_duration);
    00656 }
    00657
    00665 static inline bool OrderGoesToStation(const Vehicle *v, const Order *o)
    00666 {
    00667   return o->IsType(OT_GOTO_STATION) ||
    00668       (v->type == VEH_AIRCRAFT && o->IsType(OT_GOTO_DEPOT) && !(o->GetDepotActionType() & ODATFB_NEAREST_DEPOT));
    00669 }
    00670
    00677 static void DeleteOrderWarnings(const Vehicle *v)
    00678 {
    00679   DeleteVehicleNews(v->index, STR_NEWS_VEHICLE_HAS_TOO_FEW_ORDERS);
    00680   DeleteVehicleNews(v->index, STR_NEWS_VEHICLE_HAS_VOID_ORDER);
    00681   DeleteVehicleNews(v->index, STR_NEWS_VEHICLE_HAS_DUPLICATE_ENTRY);
    00682   DeleteVehicleNews(v->index, STR_NEWS_VEHICLE_HAS_INVALID_ENTRY);
    00683 }
    00684
    00691 TileIndex Order::GetLocation(const Vehicle *v, bool airport) const
    00692 {
    00693   switch (this->GetType()) {
    00694     case OT_GOTO_WAYPOINT:
    00695     case OT_GOTO_STATION:
    00696     case OT_IMPLICIT:
    00697       if (airport && v->type == VEH_AIRCRAFT) return Station::Get(this->GetDestination())->airport.tile;
    00698       return BaseStation::Get(this->GetDestination())->xy;
    00699
    00700     case OT_GOTO_DEPOT:
    00701       if ((this->GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0) return INVALID_TILE;
    00702       return (v->type == VEH_AIRCRAFT) ? Station::Get(this->GetDestination())->xy : Depot::Get(this->GetDestination())->xy;
    00703
    00704     default:
    00705       return INVALID_TILE;
    00706   }
    00707 }
    00708
    00718 uint GetOrderDistance(const Order *prev, const Order *cur, const Vehicle *v, int conditional_depth)
    00719 {
    00720   if (cur->IsType(OT_CONDITIONAL)) {
    00721     if (conditional_depth > v->GetNumOrders()) return 0;
    00722
    00723     conditional_depth++;
    00724
    00725     int dist1 = GetOrderDistance(prev, v->GetOrder(cur->GetConditionSkipToOrder()), v, conditional_depth);
    00726     int dist2 = GetOrderDistance(prev, cur->next == NULL ? v->orders.list->GetFirstOrder() : cur->next, v, conditional_depth);
    00727     return max(dist1, dist2);
    00728   }
    00729
    00730   TileIndex prev_tile = prev->GetLocation(v, true);
    00731   TileIndex cur_tile = cur->GetLocation(v, true);
    00732   if (prev_tile == INVALID_TILE || cur_tile == INVALID_TILE) return 0;
    00733   return v->type == VEH_AIRCRAFT ? DistanceSquare(prev_tile, cur_tile) : DistanceManhattan(prev_tile, cur_tile);
    00734 }
    00735
    00749 CommandCost CmdInsertOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00750 {
    00751   VehicleID veh          = GB(p1,  0, 20);
    00752   VehicleOrderID sel_ord = GB(p1, 20, 8);
    00753   Order new_order(p2);
    00754
    00755   Vehicle *v = Vehicle::GetIfValid(veh);
    00756   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
    00757
    00758   CommandCost ret = CheckOwnership(v->owner);
    00759   if (ret.Failed()) return ret;
    00760
    00761   /* Check if the inserted order is to the correct destination (owner, type),
    00762    * and has the correct flags if any */
    00763   switch (new_order.GetType()) {
    00764     case OT_GOTO_STATION: {
    00765       const Station *st = Station::GetIfValid(new_order.GetDestination());
    00766       if (st == NULL) return CMD_ERROR;
    00767
    00768       if (st->owner != OWNER_NONE) {
    00769         CommandCost ret = CheckOwnership(st->owner);
    00770         if (ret.Failed()) return ret;
    00771       }
    00772
    00773       if (!CanVehicleUseStation(v, st)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER);
    00774       for (Vehicle *u = v->FirstShared(); u != NULL; u = u->NextShared()) {
    00775         if (!CanVehicleUseStation(u, st)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER_SHARED);
    00776       }
    00777
    00778       /* Non stop only allowed for ground vehicles. */
    00779       if (new_order.GetNonStopType() != ONSF_STOP_EVERYWHERE && !v->IsGroundVehicle()) return CMD_ERROR;
    00780
    00781       /* Filter invalid load/unload types. */
    00782       switch (new_order.GetLoadType()) {
    00783         case OLF_LOAD_IF_POSSIBLE: case OLFB_FULL_LOAD: case OLF_FULL_LOAD_ANY: case OLFB_NO_LOAD: break;
    00784         default: return CMD_ERROR;
    00785       }
    00786       switch (new_order.GetUnloadType()) {
    00787         case OUF_UNLOAD_IF_POSSIBLE: case OUFB_UNLOAD: case OUFB_TRANSFER: case OUFB_NO_UNLOAD: break;
    00788         default: return CMD_ERROR;
    00789       }
    00790
    00791       /* Filter invalid stop locations */
    00792       switch (new_order.GetStopLocation()) {
    00793         case OSL_PLATFORM_NEAR_END:
    00794         case OSL_PLATFORM_MIDDLE:
    00795           if (v->type != VEH_TRAIN) return CMD_ERROR;
    00796           /* FALL THROUGH */
    00797         case OSL_PLATFORM_FAR_END:
    00798           break;
    00799
    00800         default:
    00801           return CMD_ERROR;
    00802       }
    00803
    00804       break;
    00805     }
    00806
    00807     case OT_GOTO_DEPOT: {
    00808       if ((new_order.GetDepotActionType() & ODATFB_NEAREST_DEPOT) == 0) {
    00809         if (v->type == VEH_AIRCRAFT) {
    00810           const Station *st = Station::GetIfValid(new_order.GetDestination());
    00811
    00812           if (st == NULL) return CMD_ERROR;
    00813
    00814           CommandCost ret = CheckOwnership(st->owner);
    00815           if (ret.Failed()) return ret;
    00816
    00817           if (!CanVehicleUseStation(v, st) || !st->airport.HasHangar()) {
    00818             return CMD_ERROR;
    00819           }
    00820         } else {
    00821           const Depot *dp = Depot::GetIfValid(new_order.GetDestination());
    00822
    00823           if (dp == NULL) return CMD_ERROR;
    00824
    00825           CommandCost ret = CheckOwnership(GetTileOwner(dp->xy));
    00826           if (ret.Failed()) return ret;
    00827
    00828           switch (v->type) {
    00829             case VEH_TRAIN:
    00830               if (!IsRailDepotTile(dp->xy)) return CMD_ERROR;
    00831               break;
    00832
    00833             case VEH_ROAD:
    00834               if (!IsRoadDepotTile(dp->xy)) return CMD_ERROR;
    00835               break;
    00836
    00837             case VEH_SHIP:
    00838               if (!IsShipDepotTile(dp->xy)) return CMD_ERROR;
    00839               break;
    00840
    00841             default: return CMD_ERROR;
    00842           }
    00843         }
    00844       }
    00845
    00846       if (new_order.GetNonStopType() != ONSF_STOP_EVERYWHERE && !v->IsGroundVehicle()) return CMD_ERROR;
    00847       if (new_order.GetDepotOrderType() & ~(ODTFB_PART_OF_ORDERS | ((new_order.GetDepotOrderType() & ODTFB_PART_OF_ORDERS) != 0 ? ODTFB_SERVICE : 0))) return CMD_ERROR;
    00848       if (new_order.GetDepotActionType() & ~(ODATFB_HALT | ODATFB_NEAREST_DEPOT)) return CMD_ERROR;
    00849       if ((new_order.GetDepotOrderType() & ODTFB_SERVICE) && (new_order.GetDepotActionType() & ODATFB_HALT)) return CMD_ERROR;
    00850       break;
    00851     }
    00852
    00853     case OT_GOTO_WAYPOINT: {
    00854       const Waypoint *wp = Waypoint::GetIfValid(new_order.GetDestination());
    00855       if (wp == NULL) return CMD_ERROR;
    00856
    00857       switch (v->type) {
    00858         default: return CMD_ERROR;
    00859
    00860         case VEH_TRAIN: {
    00861           if (!(wp->facilities & FACIL_TRAIN)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER);
    00862
    00863           CommandCost ret = CheckOwnership(wp->owner);
    00864           if (ret.Failed()) return ret;
    00865           break;
    00866         }
    00867
    00868         case VEH_SHIP:
    00869           if (!(wp->facilities & FACIL_DOCK)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER);
    00870           if (wp->owner != OWNER_NONE) {
    00871             CommandCost ret = CheckOwnership(wp->owner);
    00872             if (ret.Failed()) return ret;
    00873           }
    00874           break;
    00875       }
    00876
    00877       /* Order flags can be any of the following for waypoints:
    00878        * [non-stop]
    00879        * non-stop orders (if any) are only valid for trains */
    00880       if (new_order.GetNonStopType() != ONSF_STOP_EVERYWHERE && v->type != VEH_TRAIN) return CMD_ERROR;
    00881       break;
    00882     }
    00883
    00884     case OT_CONDITIONAL: {
    00885       VehicleOrderID skip_to = new_order.GetConditionSkipToOrder();
    00886       if (skip_to != 0 && skip_to >= v->GetNumOrders()) return CMD_ERROR; // Always allow jumping to the first (even when there is no order).
    00887       if (new_order.GetConditionVariable() >= OCV_END) return CMD_ERROR;
    00888
    00889       OrderConditionComparator occ = new_order.GetConditionComparator();
    00890       if (occ >= OCC_END) return CMD_ERROR;
    00891       switch (new_order.GetConditionVariable()) {
    00892         case OCV_REQUIRES_SERVICE:
    00893           if (occ != OCC_IS_TRUE && occ != OCC_IS_FALSE) return CMD_ERROR;
    00894           break;
    00895
    00896         case OCV_UNCONDITIONALLY:
    00897           if (occ != OCC_EQUALS) return CMD_ERROR;
    00898           if (new_order.GetConditionValue() != 0) return CMD_ERROR;
    00899           break;
    00900
    00901         case OCV_LOAD_PERCENTAGE:
    00902         case OCV_RELIABILITY:
    00903           if (new_order.GetConditionValue() > 100) return CMD_ERROR;
    00904           /* FALL THROUGH */
    00905         default:
    00906           if (occ == OCC_IS_TRUE || occ == OCC_IS_FALSE) return CMD_ERROR;
    00907           break;
    00908       }
    00909       break;
    00910     }
    00911
    00912     default: return CMD_ERROR;
    00913   }
    00914
    00915   if (sel_ord > v->GetNumOrders()) return CMD_ERROR;
    00916
    00917   if (v->GetNumOrders() >= MAX_VEH_ORDER_ID) return_cmd_error(STR_ERROR_TOO_MANY_ORDERS);
    00918   if (!Order::CanAllocateItem()) return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
    00919   if (v->orders.list == NULL && !OrderList::CanAllocateItem()) return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
    00920
    00921   if (v->type == VEH_SHIP && _settings_game.pf.pathfinder_for_ships != VPF_NPF) {
    00922     /* Make sure the new destination is not too far away from the previous */
    00923     const Order *prev = NULL;
    00924     uint n = 0;
    00925
    00926     /* Find the last goto station or depot order before the insert location.
    00927      * If the order is to be inserted at the beginning of the order list this
    00928      * finds the last order in the list. */
    00929     const Order *o;
    00930     FOR_VEHICLE_ORDERS(v, o) {
    00931       switch (o->GetType()) {
    00932         case OT_GOTO_STATION:
    00933         case OT_GOTO_DEPOT:
    00934         case OT_GOTO_WAYPOINT:
    00935           prev = o;
    00936           break;
    00937
    00938         default: break;
    00939       }
    00940       if (++n == sel_ord && prev != NULL) break;
    00941     }
    00942     if (prev != NULL) {
    00943       uint dist;
    00944       if (new_order.IsType(OT_CONDITIONAL)) {
    00945         /* The order is not yet inserted, so we have to do the first iteration here. */
    00946         dist = GetOrderDistance(prev, v->GetOrder(new_order.GetConditionSkipToOrder()), v);
    00947       } else {
    00948         dist = GetOrderDistance(prev, &new_order, v);
    00949       }
    00950
    00951       if (dist >= 130) {
    00952         return_cmd_error(STR_ERROR_TOO_FAR_FROM_PREVIOUS_DESTINATION);
    00953       }
    00954     }
    00955   }
    00956
    00957   if (flags & DC_EXEC) {
    00958     Order *new_o = new Order();
    00959     new_o->AssignOrder(new_order);
    00960     InsertOrder(v, new_o, sel_ord);
    00961   }
    00962
    00963   return CommandCost();
    00964 }
    00965
    00972 void InsertOrder(Vehicle *v, Order *new_o, VehicleOrderID sel_ord)
    00973 {
    00974   /* Create new order and link in list */
    00975   if (v->orders.list == NULL) {
    00976     v->orders.list = new OrderList(new_o, v);
    00977   } else {
    00978     v->orders.list->InsertOrderAt(new_o, sel_ord);
    00979   }
    00980
    00981   Vehicle *u = v->FirstShared();
    00982   DeleteOrderWarnings(u);
    00983   for (; u != NULL; u = u->NextShared()) {
    00984     assert(v->orders.list == u->orders.list);
    00985
    00986     /* If there is added an order before the current one, we need
    00987      * to update the selected order. We do not change implicit/real order indices though.
    00988      * If the new order is between the current implicit order and real order, the implicit order will
    00989      * later skip the inserted order. */
    00990     if (sel_ord <= u->cur_real_order_index) {
    00991       uint cur = u->cur_real_order_index + 1;
    00992       /* Check if we don't go out of bound */
    00993       if (cur < u->GetNumOrders()) {
    00994         u->cur_real_order_index = cur;
    00995       }
    00996     }
    00997     if (sel_ord == u->cur_implicit_order_index && u->IsGroundVehicle()) {
    00998       /* We are inserting an order just before the current implicit order.
    00999        * We do not know whether we will reach current implicit or the newly inserted order first.
    01000        * So, disable creation of implicit orders until we are on track again. */
    01001       uint16 &gv_flags = u->GetGroundVehicleFlags();
    01002       SetBit(gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS);
    01003     }
    01004     if (sel_ord <= u->cur_implicit_order_index) {
    01005       uint cur = u->cur_implicit_order_index + 1;
    01006       /* Check if we don't go out of bound */
    01007       if (cur < u->GetNumOrders()) {
    01008         u->cur_implicit_order_index = cur;
    01009       }
    01010     }
    01011     /* Update any possible open window of the vehicle */
    01012     InvalidateVehicleOrder(u, INVALID_VEH_ORDER_ID | (sel_ord << 8));
    01013   }
    01014
    01015   /* As we insert an order, the order to skip to will be 'wrong'. */
    01016   VehicleOrderID cur_order_id = 0;
    01017   Order *order;
    01018   FOR_VEHICLE_ORDERS(v, order) {
    01019     if (order->IsType(OT_CONDITIONAL)) {
    01020       VehicleOrderID order_id = order->GetConditionSkipToOrder();
    01021       if (order_id >= sel_ord) {
    01022         order->SetConditionSkipToOrder(order_id + 1);
    01023       }
    01024       if (order_id == cur_order_id) {
    01025         order->SetConditionSkipToOrder((order_id + 1) % v->GetNumOrders());
    01026       }
    01027     }
    01028     cur_order_id++;
    01029   }
    01030
    01031   /* Make sure to rebuild the whole list */
    01032   InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
    01033 }
    01034
    01040 static CommandCost DecloneOrder(Vehicle *dst, DoCommandFlag flags)
    01041 {
    01042   if (flags & DC_EXEC) {
    01043     DeleteVehicleOrders(dst);
    01044     InvalidateVehicleOrder(dst, VIWD_REMOVE_ALL_ORDERS);
    01045     InvalidateWindowClassesData(GetWindowClassForVehicleType(dst->type), 0);
    01046   }
    01047   return CommandCost();
    01048 }
    01049
    01059 CommandCost CmdDeleteOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    01060 {
    01061   VehicleID veh_id = GB(p1, 0, 20);
    01062   VehicleOrderID sel_ord = GB(p2, 0, 8);
    01063
    01064   Vehicle *v = Vehicle::GetIfValid(veh_id);
    01065
    01066   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
    01067
    01068   CommandCost ret = CheckOwnership(v->owner);
    01069   if (ret.Failed()) return ret;
    01070
    01071   /* If we did not select an order, we maybe want to de-clone the orders */
    01072   if (sel_ord >= v->GetNumOrders()) return DecloneOrder(v, flags);
    01073
    01074   if (v->GetOrder(sel_ord) == NULL) return CMD_ERROR;
    01075
    01076   if (flags & DC_EXEC) DeleteOrder(v, sel_ord);
    01077   return CommandCost();
    01078 }
    01079
    01084 static void CancelLoadingDueToDeletedOrder(Vehicle *v)
    01085 {
    01086   assert(v->current_order.IsType(OT_LOADING));
    01087   /* NON-stop flag is misused to see if a train is in a station that is
    01088    * on his order list or not */
    01089   v->current_order.SetNonStopType(ONSF_STOP_EVERYWHERE);
    01090   /* When full loading, "cancel" that order so the vehicle doesn't
    01091    * stay indefinitely at this station anymore. */
    01092   if (v->current_order.GetLoadType() & OLFB_FULL_LOAD) v->current_order.SetLoadType(OLF_LOAD_IF_POSSIBLE);
    01093 }
    01094
    01100 void DeleteOrder(Vehicle *v, VehicleOrderID sel_ord)
    01101 {
    01102   v->orders.list->DeleteOrderAt(sel_ord);
    01103
    01104   Vehicle *u = v->FirstShared();
    01105   DeleteOrderWarnings(u);
    01106   for (; u != NULL; u = u->NextShared()) {
    01107     assert(v->orders.list == u->orders.list);
    01108
    01109     if (sel_ord == u->cur_real_order_index && u->current_order.IsType(OT_LOADING)) {
    01110       CancelLoadingDueToDeletedOrder(u);
    01111     }
    01112
    01113     if (sel_ord < u->cur_real_order_index) {
    01114       u->cur_real_order_index--;
    01115     } else if (sel_ord == u->cur_real_order_index) {
    01116       u->UpdateRealOrderIndex();
    01117     }
    01118
    01119     if (sel_ord < u->cur_implicit_order_index) {
    01120       u->cur_implicit_order_index--;
    01121     } else if (sel_ord == u->cur_implicit_order_index) {
    01122       /* Make sure the index is valid */
    01123       if (u->cur_implicit_order_index >= u->GetNumOrders()) u->cur_implicit_order_index = 0;
    01124
    01125       /* Skip non-implicit orders for the implicit-order-index (e.g. if the current implicit order was deleted */
    01126       while (u->cur_implicit_order_index != u->cur_real_order_index && !u->GetOrder(u->cur_implicit_order_index)->IsType(OT_IMPLICIT)) {
    01127         u->cur_implicit_order_index++;
    01128         if (u->cur_implicit_order_index >= u->GetNumOrders()) u->cur_implicit_order_index = 0;
    01129       }
    01130     }
    01131
    01132     /* Update any possible open window of the vehicle */
    01133     InvalidateVehicleOrder(u, sel_ord | (INVALID_VEH_ORDER_ID << 8));
    01134   }
    01135
    01136   /* As we delete an order, the order to skip to will be 'wrong'. */
    01137   VehicleOrderID cur_order_id = 0;
    01138   Order *order = NULL;
    01139   FOR_VEHICLE_ORDERS(v, order) {
    01140     if (order->IsType(OT_CONDITIONAL)) {
    01141       VehicleOrderID order_id = order->GetConditionSkipToOrder();
    01142       if (order_id >= sel_ord) {
    01143         order_id = max(order_id - 1, 0);
    01144       }
    01145       if (order_id == cur_order_id) {
    01146         order_id = (order_id + 1) % v->GetNumOrders();
    01147       }
    01148       order->SetConditionSkipToOrder(order_id);
    01149     }
    01150     cur_order_id++;
    01151   }
    01152
    01153   InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
    01154 }
    01155
    01165 CommandCost CmdSkipToOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    01166 {
    01167   VehicleID veh_id = GB(p1, 0, 20);
    01168   VehicleOrderID sel_ord = GB(p2, 0, 8);
    01169
    01170   Vehicle *v = Vehicle::GetIfValid(veh_id);
    01171
    01172   if (v == NULL || !v->IsPrimaryVehicle() || sel_ord == v->cur_implicit_order_index || sel_ord >= v->GetNumOrders() || v->GetNumOrders() < 2) return CMD_ERROR;
    01173
    01174   CommandCost ret = CheckOwnership(v->owner);
    01175   if (ret.Failed()) return ret;
    01176
    01177   if (flags & DC_EXEC) {
    01178     if (v->current_order.IsType(OT_LOADING)) v->LeaveStation();
    01179
    01180     v->cur_implicit_order_index = v->cur_real_order_index = sel_ord;
    01181     v->UpdateRealOrderIndex();
    01182
    01183     InvalidateVehicleOrder(v, VIWD_MODIFY_ORDERS);
    01184   }
    01185
    01186   /* We have an aircraft/ship, they have a mini-schedule, so update them all */
    01187   if (v->type == VEH_AIRCRAFT) SetWindowClassesDirty(WC_AIRCRAFT_LIST);
    01188   if (v->type == VEH_SHIP) SetWindowClassesDirty(WC_SHIPS_LIST);
    01189
    01190   return CommandCost();
    01191 }
    01192
    01206 CommandCost CmdMoveOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    01207 {
    01208   VehicleID veh = GB(p1, 0, 20);
    01209   VehicleOrderID moving_order = GB(p2,  0, 16);
    01210   VehicleOrderID target_order = GB(p2, 16, 16);
    01211
    01212   Vehicle *v = Vehicle::GetIfValid(veh);
    01213   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
    01214
    01215   CommandCost ret = CheckOwnership(v->owner);
    01216   if (ret.Failed()) return ret;
    01217
    01218   /* Don't make senseless movements */
    01219   if (moving_order >= v->GetNumOrders() || target_order >= v->GetNumOrders() ||
    01220       moving_order == target_order || v->GetNumOrders() <= 1) return CMD_ERROR;
    01221
    01222   Order *moving_one = v->GetOrder(moving_order);
    01223   /* Don't move an empty order */
    01224   if (moving_one == NULL) return CMD_ERROR;
    01225
    01226   if (flags & DC_EXEC) {
    01227     v->orders.list->MoveOrder(moving_order, target_order);
    01228
    01229     /* Update shared list */
    01230     Vehicle *u = v->FirstShared();
    01231
    01232     DeleteOrderWarnings(u);
    01233
    01234     for (; u != NULL; u = u->NextShared()) {
    01235       /* Update the current order.
    01236        * There are multiple ways to move orders, which result in cur_implicit_order_index
    01237        * and cur_real_order_index to not longer make any sense. E.g. moving another
    01238        * real order between them.
    01239        *
    01240        * Basically one could choose to preserve either of them, but not both.
    01241        * While both ways are suitable in this or that case from a human point of view, neither
    01242        * of them makes really sense.
    01243        * However, from an AI point of view, preserving cur_real_order_index is the most
    01244        * predictable and transparent behaviour.
    01245        *
    01246        * With that decision it basically does not matter what we do to cur_implicit_order_index.
    01247        * If we change orders between the implict- and real-index, the implicit orders are mostly likely
    01248        * completely out-dated anyway. So, keep it simple and just keep cur_implicit_order_index as well.
    01249        * The worst which can happen is that a lot of implicit orders are removed when reaching current_order.
    01250        */
    01251       if (u->cur_real_order_index == moving_order) {
    01252         u->cur_real_order_index = target_order;
    01253       } else if (u->cur_real_order_index > moving_order && u->cur_real_order_index <= target_order) {
    01254         u->cur_real_order_index--;
    01255       } else if (u->cur_real_order_index < moving_order && u->cur_real_order_index >= target_order) {
    01256         u->cur_real_order_index++;
    01257       }
    01258
    01259       if (u->cur_implicit_order_index == moving_order) {
    01260         u->cur_implicit_order_index = target_order;
    01261       } else if (u->cur_implicit_order_index > moving_order && u->cur_implicit_order_index <= target_order) {
    01262         u->cur_implicit_order_index--;
    01263       } else if (u->cur_implicit_order_index < moving_order && u->cur_implicit_order_index >= target_order) {
    01264         u->cur_implicit_order_index++;
    01265       }
    01266
    01267       assert(v->orders.list == u->orders.list);
    01268       /* Update any possible open window of the vehicle */
    01269       InvalidateVehicleOrder(u, moving_order | (target_order << 8));
    01270     }
    01271
    01272     /* As we move an order, the order to skip to will be 'wrong'. */
    01273     Order *order;
    01274     FOR_VEHICLE_ORDERS(v, order) {
    01275       if (order->IsType(OT_CONDITIONAL)) {
    01276         VehicleOrderID order_id = order->GetConditionSkipToOrder();
    01277         if (order_id == moving_order) {
    01278           order_id = target_order;
    01279         } else if (order_id > moving_order && order_id <= target_order) {
    01280           order_id--;
    01281         } else if (order_id < moving_order && order_id >= target_order) {
    01282           order_id++;
    01283         }
    01284         order->SetConditionSkipToOrder(order_id);
    01285       }
    01286     }
    01287
    01288     /* Make sure to rebuild the whole list */
    01289     InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
    01290   }
    01291
    01292   return CommandCost();
    01293 }
    01294
    01310 CommandCost CmdModifyOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    01311 {
    01312   VehicleOrderID sel_ord = GB(p1, 20,  8);
    01313   VehicleID veh          = GB(p1,  0, 20);
    01314   ModifyOrderFlags mof   = Extract<ModifyOrderFlags, 0, 4>(p2);
    01315   uint16 data            = GB(p2,  4, 11);
    01316
    01317   if (mof >= MOF_END) return CMD_ERROR;
    01318
    01319   Vehicle *v = Vehicle::GetIfValid(veh);
    01320   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
    01321
    01322   CommandCost ret = CheckOwnership(v->owner);
    01323   if (ret.Failed()) return ret;
    01324
    01325   /* Is it a valid order? */
    01326   if (sel_ord >= v->GetNumOrders()) return CMD_ERROR;
    01327
    01328   Order *order = v->GetOrder(sel_ord);
    01329   switch (order->GetType()) {
    01330     case OT_GOTO_STATION:
    01331       if (mof == MOF_COND_VARIABLE || mof == MOF_COND_COMPARATOR || mof == MOF_DEPOT_ACTION || mof == MOF_COND_VALUE) return CMD_ERROR;
    01332       break;
    01333
    01334     case OT_GOTO_DEPOT:
    01335       if (mof != MOF_NON_STOP && mof != MOF_DEPOT_ACTION) return CMD_ERROR;
    01336       break;
    01337
    01338     case OT_GOTO_WAYPOINT:
    01339       if (mof != MOF_NON_STOP) return CMD_ERROR;
    01340       break;
    01341
    01342     case OT_CONDITIONAL:
    01343       if (mof != MOF_COND_VARIABLE && mof != MOF_COND_COMPARATOR && mof != MOF_COND_VALUE && mof != MOF_COND_DESTINATION) return CMD_ERROR;
    01344       break;
    01345
    01346     default:
    01347       return CMD_ERROR;
    01348   }
    01349
    01350   switch (mof) {
    01351     default: NOT_REACHED();
    01352
    01353     case MOF_NON_STOP:
    01354       if (!v->IsGroundVehicle()) return CMD_ERROR;
    01355       if (data >= ONSF_END) return CMD_ERROR;
    01356       if (data == order->GetNonStopType()) return CMD_ERROR;
    01357       break;
    01358
    01359     case MOF_STOP_LOCATION:
    01360       if (v->type != VEH_TRAIN) return CMD_ERROR;
    01361       if (data >= OSL_END) return CMD_ERROR;
    01362       break;
    01363
    01364     case MOF_UNLOAD:
    01365       if ((data & ~(OUFB_UNLOAD | OUFB_TRANSFER | OUFB_NO_UNLOAD)) != 0) return CMD_ERROR;
    01366       /* Unload and no-unload are mutual exclusive and so are transfer and no unload. */
    01367       if (data != 0 && ((data & (OUFB_UNLOAD | OUFB_TRANSFER)) != 0) == ((data & OUFB_NO_UNLOAD) != 0)) return CMD_ERROR;
    01368       if (data == order->GetUnloadType()) return CMD_ERROR;
    01369       break;
    01370
    01371     case MOF_LOAD:
    01372       if (data > OLFB_NO_LOAD || data == 1) return CMD_ERROR;
    01373       if (data == order->GetLoadType()) return CMD_ERROR;
    01374       break;
    01375
    01376     case MOF_DEPOT_ACTION:
    01377       if (data >= DA_END) return CMD_ERROR;
    01378       break;
    01379
    01380     case MOF_COND_VARIABLE:
    01381       if (data >= OCV_END) return CMD_ERROR;
    01382       break;
    01383
    01384     case MOF_COND_COMPARATOR:
    01385       if (data >= OCC_END) return CMD_ERROR;
    01386       switch (order->GetConditionVariable()) {
    01387         case OCV_UNCONDITIONALLY: return CMD_ERROR;
    01388
    01389         case OCV_REQUIRES_SERVICE:
    01390           if (data != OCC_IS_TRUE && data != OCC_IS_FALSE) return CMD_ERROR;
    01391           break;
    01392
    01393         default:
    01394           if (data == OCC_IS_TRUE || data == OCC_IS_FALSE) return CMD_ERROR;
    01395           break;
    01396       }
    01397       break;
    01398
    01399     case MOF_COND_VALUE:
    01400       switch (order->GetConditionVariable()) {
    01401         case OCV_UNCONDITIONALLY: return CMD_ERROR;
    01402
    01403         case OCV_LOAD_PERCENTAGE:
    01404         case OCV_RELIABILITY:
    01405           if (data > 100) return CMD_ERROR;
    01406           break;
    01407
    01408         default:
    01409           if (data > 2047) return CMD_ERROR;
    01410           break;
    01411       }
    01412       break;
    01413
    01414     case MOF_COND_DESTINATION:
    01415       if (data >= v->GetNumOrders()) return CMD_ERROR;
    01416       break;
    01417   }
    01418
    01419   if (flags & DC_EXEC) {
    01420     switch (mof) {
    01421       case MOF_NON_STOP:
    01422         order->SetNonStopType((OrderNonStopFlags)data);
    01423         if (data & ONSF_NO_STOP_AT_DESTINATION_STATION) order->SetRefit(CT_NO_REFIT);
    01424         break;
    01425
    01426       case MOF_STOP_LOCATION:
    01427         order->SetStopLocation((OrderStopLocation)data);
    01428         break;
    01429
    01430       case MOF_UNLOAD:
    01431         order->SetUnloadType((OrderUnloadFlags)data);
    01432         break;
    01433
    01434       case MOF_LOAD:
    01435         order->SetLoadType((OrderLoadFlags)data);
    01436         if (data & OLFB_NO_LOAD) order->SetRefit(CT_NO_REFIT);
    01437         break;
    01438
    01439       case MOF_DEPOT_ACTION: {
    01440         switch (data) {
    01441           case DA_ALWAYS_GO:
    01442             order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() & ~ODTFB_SERVICE));
    01443             order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_HALT));
    01444             break;
    01445
    01446           case DA_SERVICE:
    01447             order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() | ODTFB_SERVICE));
    01448             order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_HALT));
    01449             order->SetRefit(CT_NO_REFIT);
    01450             break;
    01451
    01452           case DA_STOP:
    01453             order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() & ~ODTFB_SERVICE));
    01454             order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() | ODATFB_HALT));
    01455             order->SetRefit(CT_NO_REFIT);
    01456             break;
    01457
    01458           default:
    01459             NOT_REACHED();
    01460         }
    01461         break;
    01462       }
    01463
    01464       case MOF_COND_VARIABLE: {
    01465         order->SetConditionVariable((OrderConditionVariable)data);
    01466
    01467         OrderConditionComparator occ = order->GetConditionComparator();
    01468         switch (order->GetConditionVariable()) {
    01469           case OCV_UNCONDITIONALLY:
    01470             order->SetConditionComparator(OCC_EQUALS);
    01471             order->SetConditionValue(0);
    01472             break;
    01473
    01474           case OCV_REQUIRES_SERVICE:
    01475             if (occ != OCC_IS_TRUE && occ != OCC_IS_FALSE) order->SetConditionComparator(OCC_IS_TRUE);
    01476             break;
    01477
    01478           case OCV_LOAD_PERCENTAGE:
    01479           case OCV_RELIABILITY:
    01480             if (order->GetConditionValue() > 100) order->SetConditionValue(100);
    01481             /* FALL THROUGH */
    01482           default:
    01483             if (occ == OCC_IS_TRUE || occ == OCC_IS_FALSE) order->SetConditionComparator(OCC_EQUALS);
    01484             break;
    01485         }
    01486         break;
    01487       }
    01488
    01489       case MOF_COND_COMPARATOR:
    01490         order->SetConditionComparator((OrderConditionComparator)data);
    01491         break;
    01492
    01493       case MOF_COND_VALUE:
    01494         order->SetConditionValue(data);
    01495         break;
    01496
    01497       case MOF_COND_DESTINATION:
    01498         order->SetConditionSkipToOrder(data);
    01499         break;
    01500
    01501       default: NOT_REACHED();
    01502     }
    01503
    01504     /* Update the windows and full load flags, also for vehicles that share the same order list */
    01505     Vehicle *u = v->FirstShared();
    01506     DeleteOrderWarnings(u);
    01507     for (; u != NULL; u = u->NextShared()) {
    01508       /* Toggle u->current_order "Full load" flag if it changed.
    01509        * However, as the same flag is used for depot orders, check
    01510        * whether we are not going to a depot as there are three
    01511        * cases where the full load flag can be active and only
    01512        * one case where the flag is used for depot orders. In the
    01513        * other cases for the OrderTypeByte the flags are not used,
    01514        * so do not care and those orders should not be active
    01515        * when this function is called.
    01516        */
    01517       if (sel_ord == u->cur_real_order_index &&
    01518           (u->current_order.IsType(OT_GOTO_STATION) || u->current_order.IsType(OT_LOADING)) &&
    01519           u->current_order.GetLoadType() != order->GetLoadType()) {
    01520         u->current_order.SetLoadType(order->GetLoadType());
    01521       }
    01522       InvalidateVehicleOrder(u, VIWD_MODIFY_ORDERS);
    01523     }
    01524   }
    01525
    01526   return CommandCost();
    01527 }
    01528
    01536 static bool CheckAircraftOrderDistance(const Aircraft *v_new, const Vehicle *v_order, const Order *first)
    01537 {
    01538   if (first == NULL || v_new->acache.cached_max_range == 0) return true;
    01539
    01540   /* Iterate over all orders to check the distance between all
    01541    * 'goto' orders and their respective next order (of any type). */
    01542   for (const Order *o = first; o != NULL; o = o->next) {
    01543     switch (o->GetType()) {
    01544       case OT_GOTO_STATION:
    01545       case OT_GOTO_DEPOT:
    01546       case OT_GOTO_WAYPOINT:
    01547         /* If we don't have a next order, we've reached the end and must check the first order instead. */
    01548         if (GetOrderDistance(o, o->next != NULL ? o->next : first, v_order) > v_new->acache.cached_max_range_sqr) return false;
    01549         break;
    01550
    01551       default: break;
    01552     }
    01553   }
    01554
    01555   return true;
    01556 }
    01557
    01569 CommandCost CmdCloneOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    01570 {
    01571   VehicleID veh_src = GB(p2, 0, 20);
    01572   VehicleID veh_dst = GB(p1, 0, 20);
    01573
    01574   Vehicle *dst = Vehicle::GetIfValid(veh_dst);
    01575   if (dst == NULL || !dst->IsPrimaryVehicle()) return CMD_ERROR;
    01576
    01577   CommandCost ret = CheckOwnership(dst->owner);
    01578   if (ret.Failed()) return ret;
    01579
    01580   switch (GB(p1, 30, 2)) {
    01581     case CO_SHARE: {
    01582       Vehicle *src = Vehicle::GetIfValid(veh_src);
    01583
    01584       /* Sanity checks */
    01585       if (src == NULL || !src->IsPrimaryVehicle() || dst->type != src->type || dst == src) return CMD_ERROR;
    01586
    01587       CommandCost ret = CheckOwnership(src->owner);
    01588       if (ret.Failed()) return ret;
    01589
    01590       /* Trucks can't share orders with busses (and visa versa) */
    01591       if (src->type == VEH_ROAD && RoadVehicle::From(src)->IsBus() != RoadVehicle::From(dst)->IsBus()) {
    01592         return CMD_ERROR;
    01593       }
    01594
    01595       /* Is the vehicle already in the shared list? */
    01596       if (src->FirstShared() == dst->FirstShared()) return CMD_ERROR;
    01597
    01598       const Order *order;
    01599
    01600       FOR_VEHICLE_ORDERS(src, order) {
    01601         if (!OrderGoesToStation(dst, order)) continue;
    01602
    01603         /* Allow copying unreachable destinations if they were already unreachable for the source.
    01604          * This is basically to allow cloning / autorenewing / autoreplacing vehicles, while the stations
    01605          * are temporarily invalid due to reconstruction. */
    01606         const Station *st = Station::Get(order->GetDestination());
    01607         if (CanVehicleUseStation(src, st) && !CanVehicleUseStation(dst, st)) {
    01608           return_cmd_error(STR_ERROR_CAN_T_COPY_SHARE_ORDER);
    01609         }
    01610       }
    01611
    01612       /* Check for aircraft range limits. */
    01613       if (dst->type == VEH_AIRCRAFT && !CheckAircraftOrderDistance(Aircraft::From(dst), src, src->GetFirstOrder())) {
    01614         return_cmd_error(STR_ERROR_AIRCRAFT_NOT_ENOUGH_RANGE);
    01615       }
    01616
    01617       if (src->orders.list == NULL && !OrderList::CanAllocateItem()) {
    01618         return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
    01619       }
    01620
    01621       if (flags & DC_EXEC) {
    01622         /* If the destination vehicle had a OrderList, destroy it.
    01623          * We only reset the order indices, if the new orders are obviously different.
    01624          * (We mainly do this to keep the order indices valid and in range.) */
    01625         DeleteVehicleOrders(dst, false, dst->GetNumOrders() != src->GetNumOrders());
    01626
    01627         dst->orders.list = src->orders.list;
    01628
    01629         /* Link this vehicle in the shared-list */
    01630         dst->AddToShared(src);
    01631
    01632         InvalidateVehicleOrder(dst, VIWD_REMOVE_ALL_ORDERS);
    01633         InvalidateVehicleOrder(src, VIWD_MODIFY_ORDERS);
    01634
    01635         InvalidateWindowClassesData(GetWindowClassForVehicleType(dst->type), 0);
    01636       }
    01637       break;
    01638     }
    01639
    01640     case CO_COPY: {
    01641       Vehicle *src = Vehicle::GetIfValid(veh_src);
    01642
    01643       /* Sanity checks */
    01644       if (src == NULL || !src->IsPrimaryVehicle() || dst->type != src->type || dst == src) return CMD_ERROR;
    01645
    01646       CommandCost ret = CheckOwnership(src->owner);
    01647       if (ret.Failed()) return ret;
    01648
    01649       /* Trucks can't copy all the orders from busses (and visa versa),
    01650        * and neither can helicopters and aircarft. */
    01651       const Order *order;
    01652       FOR_VEHICLE_ORDERS(src, order) {
    01653         if (OrderGoesToStation(dst, order) &&
    01654             !CanVehicleUseStation(dst, Station::Get(order->GetDestination()))) {
    01655           return_cmd_error(STR_ERROR_CAN_T_COPY_SHARE_ORDER);
    01656         }
    01657       }
    01658
    01659       /* Check for aircraft range limits. */
    01660       if (dst->type == VEH_AIRCRAFT && !CheckAircraftOrderDistance(Aircraft::From(dst), src, src->GetFirstOrder())) {
    01661         return_cmd_error(STR_ERROR_AIRCRAFT_NOT_ENOUGH_RANGE);
    01662       }
    01663
    01664       /* make sure there are orders available */
    01665       if (!Order::CanAllocateItem(src->GetNumOrders()) || !OrderList::CanAllocateItem()) {
    01666         return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
    01667       }
    01668
    01669       if (flags & DC_EXEC) {
    01670         const Order *order;
    01671         Order *first = NULL;
    01672         Order **order_dst;
    01673
    01674         /* If the destination vehicle had an order list, destroy the chain but keep the OrderList.
    01675          * We only reset the order indices, if the new orders are obviously different.
    01676          * (We mainly do this to keep the order indices valid and in range.) */
    01677         DeleteVehicleOrders(dst, true, dst->GetNumOrders() != src->GetNumOrders());
    01678
    01679         order_dst = &first;
    01680         FOR_VEHICLE_ORDERS(src, order) {
    01681           *order_dst = new Order();
    01682           (*order_dst)->AssignOrder(*order);
    01683           order_dst = &(*order_dst)->next;
    01684         }
    01685         if (dst->orders.list == NULL) {
    01686           dst->orders.list = new OrderList(first, dst);
    01687         } else {
    01688           assert(dst->orders.list->GetFirstOrder() == NULL);
    01689           assert(!dst->orders.list->IsShared());
    01690           delete dst->orders.list;
    01691           assert(OrderList::CanAllocateItem());
    01692           dst->orders.list = new OrderList(first, dst);
    01693         }
    01694
    01695         InvalidateVehicleOrder(dst, VIWD_REMOVE_ALL_ORDERS);
    01696
    01697         InvalidateWindowClassesData(GetWindowClassForVehicleType(dst->type), 0);
    01698       }
    01699       break;
    01700     }
    01701
    01702     case CO_UNSHARE: return DecloneOrder(dst, flags);
    01703     default: return CMD_ERROR;
    01704   }
    01705
    01706   return CommandCost();
    01707 }
    01708
    01721 CommandCost CmdOrderRefit(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    01722 {
    01723   VehicleID veh = GB(p1, 0, 20);
    01724   VehicleOrderID order_number  = GB(p2, 16, 8);
    01725   CargoID cargo = GB(p2, 0, 8);
    01726   byte subtype  = GB(p2, 8, 8);
    01727
    01728   if (cargo >= NUM_CARGO && cargo != CT_NO_REFIT && cargo != CT_AUTO_REFIT) return CMD_ERROR;
    01729
    01730   const Vehicle *v = Vehicle::GetIfValid(veh);
    01731   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
    01732
    01733   CommandCost ret = CheckOwnership(v->owner);
    01734   if (ret.Failed()) return ret;
    01735
    01736   Order *order = v->GetOrder(order_number);
    01737   if (order == NULL) return CMD_ERROR;
    01738
    01739   /* Automatic refit cargo is only supported for goto station orders. */
    01740   if (cargo == CT_AUTO_REFIT && !order->IsType(OT_GOTO_STATION)) return CMD_ERROR;
    01741
    01742   if (flags & DC_EXEC) {
    01743     order->SetRefit(cargo, subtype);
    01744
    01745     /* Make the depot order an 'always go' order. */
    01746     if (cargo != CT_NO_REFIT && order->IsType(OT_GOTO_DEPOT)) {
    01747       order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() & ~ODTFB_SERVICE));
    01748       order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_HALT));
    01749     }
    01750
    01751     for (Vehicle *u = v->FirstShared(); u != NULL; u = u->NextShared()) {
    01752       /* Update any possible open window of the vehicle */
    01753       InvalidateVehicleOrder(u, VIWD_MODIFY_ORDERS);
    01754
    01755       /* If the vehicle already got the current depot set as current order, then update current order as well */
    01756       if (u->cur_real_order_index == order_number && (u->current_order.GetDepotOrderType() & ODTFB_PART_OF_ORDERS)) {
    01757         u->current_order.SetRefit(cargo, subtype);
    01758       }
    01759     }
    01760   }
    01761
    01762   return CommandCost();
    01763 }
    01764
    01765
    01771 void CheckOrders(const Vehicle *v)
    01772 {
    01773   /* Does the user wants us to check things? */
    01774   if (_settings_client.gui.order_review_system == 0) return;
    01775
    01776   /* Do nothing for crashed vehicles */
    01777   if (v->vehstatus & VS_CRASHED) return;
    01778
    01779   /* Do nothing for stopped vehicles if setting is '1' */
    01780   if (_settings_client.gui.order_review_system == 1 && (v->vehstatus & VS_STOPPED)) return;
    01781
    01782   /* do nothing we we're not the first vehicle in a share-chain */
    01783   if (v->FirstShared() != v) return;
    01784
    01785   /* Only check every 20 days, so that we don't flood the message log */
    01786   if (v->owner == _local_company && v->day_counter % 20 == 0) {
    01787     int n_st, problem_type = -1;
    01788     const Order *order;
    01789     int message = 0;
    01790
    01791     /* Check the order list */
    01792     n_st = 0;
    01793
    01794     FOR_VEHICLE_ORDERS(v, order) {
    01795       /* Dummy order? */
    01796       if (order->IsType(OT_DUMMY)) {
    01797         problem_type = 1;
    01798         break;
    01799       }
    01800       /* Does station have a load-bay for this vehicle? */
    01801       if (order->IsType(OT_GOTO_STATION)) {
    01802         const Station *st = Station::Get(order->GetDestination());
    01803
    01804         n_st++;
    01805         if (!CanVehicleUseStation(v, st)) problem_type = 3;
    01806       }
    01807     }
    01808
    01809     /* Check if the last and the first order are the same */
    01810     if (v->GetNumOrders() > 1) {
    01811       const Order *last = v->GetLastOrder();
    01812
    01813       if (v->orders.list->GetFirstOrder()->Equals(*last)) {
    01814         problem_type = 2;
    01815       }
    01816     }
    01817
    01818     /* Do we only have 1 station in our order list? */
    01819     if (n_st < 2 && problem_type == -1) problem_type = 0;
    01820
    01821 #ifndef NDEBUG
    01822     if (v->orders.list != NULL) v->orders.list->DebugCheckSanity();
    01823 #endif
    01824
    01825     /* We don't have a problem */
    01826     if (problem_type < 0) return;
    01827
    01828     message = STR_NEWS_VEHICLE_HAS_TOO_FEW_ORDERS + problem_type;
    01829     //DEBUG(misc, 3, "Triggered News Item for vehicle %d", v->index);
    01830
    01831     SetDParam(0, v->index);
    01832     AddVehicleAdviceNewsItem(message, v->index);
    01833   }
    01834 }
    01835
    01841 void RemoveOrderFromAllVehicles(OrderType type, DestinationID destination)
    01842 {
    01843   Vehicle *v;
    01844
    01845   /* Aircraft have StationIDs for depot orders and never use DepotIDs
    01846    * This fact is handled specially below
    01847    */
    01848
    01849   /* Go through all vehicles */
    01850   FOR_ALL_VEHICLES(v) {
    01851     Order *order;
    01852
    01853     order = &v->current_order;
    01854     if ((v->type == VEH_AIRCRAFT && order->IsType(OT_GOTO_DEPOT) ? OT_GOTO_STATION : order->GetType()) == type &&
    01855         v->current_order.GetDestination() == destination) {
    01856       order->MakeDummy();
    01857       SetWindowDirty(WC_VEHICLE_VIEW, v->index);
    01858     }
    01859
    01860     /* Clear the order from the order-list */
    01861     int id = -1;
    01862     FOR_VEHICLE_ORDERS(v, order) {
    01863       id++;
    01864 restart:
    01865
    01866       OrderType ot = order->GetType();
    01867       if (ot == OT_GOTO_DEPOT && (order->GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0) continue;
    01868       if (ot == OT_IMPLICIT || (v->type == VEH_AIRCRAFT && ot == OT_GOTO_DEPOT)) ot = OT_GOTO_STATION;
    01869       if (ot == type && order->GetDestination() == destination) {
    01870         /* We want to clear implicit orders, but we don't want to make them
    01871          * dummy orders. They should just vanish. Also check the actual order
    01872          * type as ot is currently OT_GOTO_STATION. */
    01873         if (order->IsType(OT_IMPLICIT)) {
    01874           order = order->next; // DeleteOrder() invalidates current order
    01875           DeleteOrder(v, id);
    01876           if (order != NULL) goto restart;
    01877           break;
    01878         }
    01879
    01880         order->MakeDummy();
    01881         for (const Vehicle *w = v->FirstShared(); w != NULL; w = w->NextShared()) {
    01882           /* In GUI, simulate by removing the order and adding it back */
    01883           InvalidateVehicleOrder(w, id | (INVALID_VEH_ORDER_ID << 8));
    01884           InvalidateVehicleOrder(w, (INVALID_VEH_ORDER_ID << 8) | id);
    01885         }
    01886       }
    01887     }
    01888   }
    01889
    01890   OrderBackup::RemoveOrder(type, destination);
    01891 }
    01892
    01897 bool Vehicle::HasDepotOrder() const
    01898 {
    01899   const Order *order;
    01900
    01901   FOR_VEHICLE_ORDERS(this, order) {
    01902     if (order->IsType(OT_GOTO_DEPOT)) return true;
    01903   }
    01904
    01905   return false;
    01906 }
    01907
    01917 void DeleteVehicleOrders(Vehicle *v, bool keep_orderlist, bool reset_order_indices)
    01918 {
    01919   DeleteOrderWarnings(v);
    01920
    01921   if (v->IsOrderListShared()) {
    01922     /* Remove ourself from the shared order list. */
    01923     v->RemoveFromShared();
    01924     v->orders.list = NULL;
    01925   } else if (v->orders.list != NULL) {
    01926     /* Remove the orders */
    01927     v->orders.list->FreeChain(keep_orderlist);
    01928     if (!keep_orderlist) v->orders.list = NULL;
    01929   }
    01930
    01931   if (reset_order_indices) {
    01932     v->cur_implicit_order_index = v->cur_real_order_index = 0;
    01933     if (v->current_order.IsType(OT_LOADING)) {
    01934       CancelLoadingDueToDeletedOrder(v);
    01935     }
    01936   }
    01937 }
    01938
    01946 uint16 GetServiceIntervalClamped(uint interval, CompanyID company_id)
    01947 {
    01948   return (Company::Get(company_id)->settings.vehicle.servint_ispercent) ? Clamp(interval, MIN_SERVINT_PERCENT, MAX_SERVINT_PERCENT) : Clamp(interval, MIN_SERVINT_DAYS, MAX_SERVINT_DAYS);
    01949 }
    01950
    01959 static bool CheckForValidOrders(const Vehicle *v)
    01960 {
    01961   const Order *order;
    01962
    01963   FOR_VEHICLE_ORDERS(v, order) {
    01964     switch (order->GetType()) {
    01965       case OT_GOTO_STATION:
    01966       case OT_GOTO_DEPOT:
    01967       case OT_GOTO_WAYPOINT:
    01968         return true;
    01969
    01970       default:
    01971         break;
    01972     }
    01973   }
    01974
    01975   return false;
    01976 }
    01977
    01981 static bool OrderConditionCompare(OrderConditionComparator occ, int variable, int value)
    01982 {
    01983   switch (occ) {
    01984     case OCC_EQUALS:      return variable == value;
    01985     case OCC_NOT_EQUALS:  return variable != value;
    01986     case OCC_LESS_THAN:   return variable <  value;
    01987     case OCC_LESS_EQUALS: return variable <= value;
    01988     case OCC_MORE_THAN:   return variable >  value;
    01989     case OCC_MORE_EQUALS: return variable >= value;
    01990     case OCC_IS_TRUE:     return variable != 0;
    01991     case OCC_IS_FALSE:    return variable == 0;
    01992     default: NOT_REACHED();
    01993   }
    01994 }
    01995
    02002 VehicleOrderID ProcessConditionalOrder(const Order *order, const Vehicle *v)
    02003 {
    02004   if (order->GetType() != OT_CONDITIONAL) return INVALID_VEH_ORDER_ID;
    02005
    02006   bool skip_order = false;
    02007   OrderConditionComparator occ = order->GetConditionComparator();
    02008   uint16 value = order->GetConditionValue();
    02009
    02010   switch (order->GetConditionVariable()) {
    02011     case OCV_LOAD_PERCENTAGE:    skip_order = OrderConditionCompare(occ, CalcPercentVehicleFilled(v, NULL), value); break;
    02012     case OCV_RELIABILITY:        skip_order = OrderConditionCompare(occ, ToPercent16(v->reliability),       value); break;
    02013     case OCV_MAX_SPEED:          skip_order = OrderConditionCompare(occ, v->GetDisplayMaxSpeed() * 10 / 16, value); break;
    02014     case OCV_AGE:                skip_order = OrderConditionCompare(occ, v->age / DAYS_IN_LEAP_YEAR,        value); break;
    02015     case OCV_REQUIRES_SERVICE:   skip_order = OrderConditionCompare(occ, v->NeedsServicing(),               value); break;
    02016     case OCV_UNCONDITIONALLY:    skip_order = true; break;
    02017     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;
    02018     default: NOT_REACHED();
    02019   }
    02020
    02021   return skip_order ? order->GetConditionSkipToOrder() : (VehicleOrderID)INVALID_VEH_ORDER_ID;
    02022 }
    02023
    02031 bool UpdateOrderDest(Vehicle *v, const Order *order, int conditional_depth, bool pbs_look_ahead)
    02032 {
    02033   if (conditional_depth > v->GetNumOrders()) return false;
    02034
    02035   switch (order->GetType()) {
    02036     case OT_GOTO_STATION:
    02037       v->dest_tile = v->GetOrderStationLocation(order->GetDestination());
    02038       return true;
    02039
    02040     case OT_GOTO_DEPOT:
    02041       if ((order->GetDepotOrderType() & ODTFB_SERVICE) && !v->NeedsServicing()) {
    02042         assert(!pbs_look_ahead);
    02043         UpdateVehicleTimetable(v, true);
    02044         v->IncrementRealOrderIndex();
    02045         break;
    02046       }
    02047
    02048       if (v->current_order.GetDepotActionType() & ODATFB_NEAREST_DEPOT) {
    02049         /* We need to search for the nearest depot (hangar). */
    02050         TileIndex location;
    02051         DestinationID destination;
    02052         bool reverse;
    02053
    02054         if (v->FindClosestDepot(&location, &destination, &reverse)) {
    02055           /* PBS reservations cannot reverse */
    02056           if (pbs_look_ahead && reverse) return false;
    02057
    02058           v->dest_tile = location;
    02059           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(), v->current_order.GetRefitSubtype());
    02060
    02061           /* If there is no depot in front, reverse automatically (trains only) */
    02062           if (v->type == VEH_TRAIN && reverse) DoCommand(v->tile, v->index, 0, DC_EXEC, CMD_REVERSE_TRAIN_DIRECTION);
    02063
    02064           if (v->type == VEH_AIRCRAFT) {
    02065             Aircraft *a = Aircraft::From(v);
    02066             if (a->state == FLYING && a->targetairport != destination) {
    02067               /* The aircraft is now heading for a different hangar than the next in the orders */
    02068               extern void AircraftNextAirportPos_and_Order(Aircraft *a);
    02069               AircraftNextAirportPos_and_Order(a);
    02070             }
    02071           }
    02072           return true;
    02073         }
    02074
    02075         /* If there is no depot, we cannot help PBS either. */
    02076         if (pbs_look_ahead) return false;
    02077
    02078         UpdateVehicleTimetable(v, true);
    02079         v->IncrementRealOrderIndex();
    02080       } else {
    02081         if (v->type != VEH_AIRCRAFT) {
    02082           v->dest_tile = Depot::Get(order->GetDestination())->xy;
    02083         }
    02084         return true;
    02085       }
    02086       break;
    02087
    02088     case OT_GOTO_WAYPOINT:
    02089       v->dest_tile = Waypoint::Get(order->GetDestination())->xy;
    02090       return true;
    02091
    02092     case OT_CONDITIONAL: {
    02093       assert(!pbs_look_ahead);
    02094       VehicleOrderID next_order = ProcessConditionalOrder(order, v);
    02095       if (next_order != INVALID_VEH_ORDER_ID) {
    02096         /* Jump to next_order. cur_implicit_order_index becomes exactly that order,
    02097          * cur_real_order_index might come after next_order. */
    02098         UpdateVehicleTimetable(v, false);
    02099         v->cur_implicit_order_index = v->cur_real_order_index = next_order;
    02100         v->UpdateRealOrderIndex();
    02101         v->current_order_time += v->GetOrder(v->cur_real_order_index)->travel_time;
    02102
    02103         /* Disable creation of implicit orders.
    02104          * When inserting them we do not know that we would have to make the conditional orders point to them. */
    02105         if (v->IsGroundVehicle()) {
    02106           uint16 &gv_flags = v->GetGroundVehicleFlags();
    02107           SetBit(gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS);
    02108         }
    02109       } else {
    02110         UpdateVehicleTimetable(v, true);
    02111         v->IncrementRealOrderIndex();
    02112       }
    02113       break;
    02114     }
    02115
    02116     default:
    02117       v->dest_tile = 0;
    02118       return false;
    02119   }
    02120
    02121   assert(v->cur_implicit_order_index < v->GetNumOrders());
    02122   assert(v->cur_real_order_index < v->GetNumOrders());
    02123
    02124   /* Get the current order */
    02125   order = v->GetOrder(v->cur_real_order_index);
    02126   if (order != NULL && order->IsType(OT_IMPLICIT)) {
    02127     assert(v->GetNumManualOrders() == 0);
    02128     order = NULL;
    02129   }
    02130
    02131   if (order == NULL) {
    02132     v->current_order.Free();
    02133     v->dest_tile = 0;
    02134     return false;
    02135   }
    02136
    02137   v->current_order = *order;
    02138   return UpdateOrderDest(v, order, conditional_depth + 1, pbs_look_ahead);
    02139 }
    02140
    02148 bool ProcessOrders(Vehicle *v)
    02149 {
    02150   switch (v->current_order.GetType()) {
    02151     case OT_GOTO_DEPOT:
    02152       /* Let a depot order in the orderlist interrupt. */
    02153       if (!(v->current_order.GetDepotOrderType() & ODTFB_PART_OF_ORDERS)) return false;
    02154       break;
    02155
    02156     case OT_LOADING:
    02157       return false;
    02158
    02159     case OT_LEAVESTATION:
    02160       if (v->type != VEH_AIRCRAFT) return false;
    02161       break;
    02162
    02163     default: break;
    02164   }
    02165
    02173   bool may_reverse = v->current_order.IsType(OT_NOTHING);
    02174
    02175   /* Check if we've reached a 'via' destination. */
    02176   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)) &&
    02177       IsTileType(v->tile, MP_STATION) &&
    02178       v->current_order.GetDestination() == GetStationIndex(v->tile)) {
    02179     v->DeleteUnreachedImplicitOrders();
    02180     /* We set the last visited station here because we do not want
    02181      * the train to stop at this 'via' station if the next order
    02182      * is a no-non-stop order; in that case not setting the last
    02183      * visited station will cause the vehicle to still stop. */
    02184     v->last_station_visited = v->current_order.GetDestination();
    02185     UpdateVehicleTimetable(v, true);
    02186     v->IncrementImplicitOrderIndex();
    02187   }
    02188
    02189   /* Get the current order */
    02190   assert(v->cur_implicit_order_index == 0 || v->cur_implicit_order_index < v->GetNumOrders());
    02191   v->UpdateRealOrderIndex();
    02192
    02193   const Order *order = v->GetOrder(v->cur_real_order_index);
    02194   if (order != NULL && order->IsType(OT_IMPLICIT)) {
    02195     assert(v->GetNumManualOrders() == 0);
    02196     order = NULL;
    02197   }
    02198
    02199   /* If no order, do nothing. */
    02200   if (order == NULL || (v->type == VEH_AIRCRAFT && !CheckForValidOrders(v))) {
    02201     if (v->type == VEH_AIRCRAFT) {
    02202       /* Aircraft do something vastly different here, so handle separately */
    02203       extern void HandleMissingAircraftOrders(Aircraft *v);
    02204       HandleMissingAircraftOrders(Aircraft::From(v));
    02205       return false;
    02206     }
    02207
    02208     v->current_order.Free();
    02209     v->dest_tile = 0;
    02210     return false;
    02211   }
    02212
    02213   /* If it is unchanged, keep it. */
    02214   if (order->Equals(v->current_order) && (v->type == VEH_AIRCRAFT || v->dest_tile != 0) &&
    02215       (v->type != VEH_SHIP || !order->IsType(OT_GOTO_STATION) || Station::Get(order->GetDestination())->dock_tile != INVALID_TILE)) {
    02216     return false;
    02217   }
    02218
    02219   /* Otherwise set it, and determine the destination tile. */
    02220   v->current_order = *order;
    02221
    02222   InvalidateVehicleOrder(v, VIWD_MODIFY_ORDERS);
    02223   switch (v->type) {
    02224     default:
    02225       NOT_REACHED();
    02226
    02227     case VEH_ROAD:
    02228     case VEH_TRAIN:
    02229       break;
    02230
    02231     case VEH_AIRCRAFT:
    02232     case VEH_SHIP:
    02233       SetWindowClassesDirty(GetWindowClassForVehicleType(v->type));
    02234       break;
    02235   }
    02236
    02237   return UpdateOrderDest(v, order) && may_reverse;
    02238 }
    02239
    02247 bool Order::ShouldStopAtStation(const Vehicle *v, StationID station) const
    02248 {
    02249   bool is_dest_station = this->IsType(OT_GOTO_STATION) && this->dest == station;
    02250
    02251   return (!this->IsType(OT_GOTO_DEPOT) || (this->GetDepotOrderType() & ODTFB_PART_OF_ORDERS) != 0) &&
    02252       v->last_station_visited != station && // Do stop only when we've not just been there
    02253       /* Finally do stop when there is no non-stop flag set for this type of station. */
    02254       !(this->GetNonStopType() & (is_dest_station ? ONSF_NO_STOP_AT_DESTINATION_STATION : ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS));
    02255 }
    02256
    02257 bool Order::CanLoadOrUnload() const
    02258 {
    02259   return (this->IsType(OT_GOTO_STATION) || this->IsType(OT_IMPLICIT)) &&
    02260       (this->GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION) == 0 &&
    02261       ((this->GetLoadType() & OLFB_NO_LOAD) == 0 ||
    02262       (this->GetUnloadType() & OUFB_NO_UNLOAD) == 0);
    02263 }
    02264
    02271 bool Order::CanLeaveWithCargo(bool has_cargo) const
    02272 {
    02273   return (this->GetLoadType() & OLFB_NO_LOAD) == 0 || (has_cargo &&
    02274       (this->GetUnloadType() & (OUFB_UNLOAD | OUFB_TRANSFER)) == 0);
    02275 }