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 "vehicle_gui.h"
00019 #include "strings_func.h"
00020 #include "window_func.h"
00021 #include "timetable.h"
00022 #include "vehicle_func.h"
00023 #include "depot_base.h"
00024 #include "core/pool_func.hpp"
00025 #include "core/random_func.hpp"
00026 #include "aircraft.h"
00027 #include "roadveh.h"
00028 #include "station_base.h"
00029 #include "waypoint_base.h"
00030 #include "company_base.h"
00031 #include "order_backup.h"
00032 
00033 #include "table/strings.h"
00034 
00035 /* DestinationID must be at least as large as every these below, because it can
00036  * be any of them
00037  */
00038 assert_compile(sizeof(DestinationID) >= sizeof(DepotID));
00039 assert_compile(sizeof(DestinationID) >= sizeof(StationID));
00040 
00041 OrderPool _order_pool("Order");
00042 INSTANTIATE_POOL_METHODS(Order)
00043 OrderListPool _orderlist_pool("OrderList");
00044 INSTANTIATE_POOL_METHODS(OrderList)
00045 
00047 Order::~Order()
00048 {
00049   if (CleaningPool()) return;
00050 
00051   /* We can visit oil rigs and buoys that are not our own. They will be shown in
00052    * the list of stations. So, we need to invalidate that window if needed. */
00053   if (this->IsType(OT_GOTO_STATION) || this->IsType(OT_GOTO_WAYPOINT)) {
00054     BaseStation *bs = BaseStation::GetIfValid(this->GetDestination());
00055     if (bs != NULL && bs->owner == OWNER_NONE) InvalidateWindowClassesData(WC_STATION_LIST, 0);
00056   }
00057 }
00058 
00063 void Order::Free()
00064 {
00065   this->type  = OT_NOTHING;
00066   this->flags = 0;
00067   this->dest  = 0;
00068   this->next  = NULL;
00069 }
00070 
00075 void Order::MakeGoToStation(StationID destination)
00076 {
00077   this->type = OT_GOTO_STATION;
00078   this->flags = 0;
00079   this->dest = destination;
00080 }
00081 
00091 void Order::MakeGoToDepot(DepotID destination, OrderDepotTypeFlags order, OrderNonStopFlags non_stop_type, OrderDepotActionFlags action, CargoID cargo, byte subtype)
00092 {
00093   this->type = OT_GOTO_DEPOT;
00094   this->SetDepotOrderType(order);
00095   this->SetDepotActionType(action);
00096   this->SetNonStopType(non_stop_type);
00097   this->dest = destination;
00098   this->SetRefit(cargo, subtype);
00099 }
00100 
00105 void Order::MakeGoToWaypoint(StationID destination)
00106 {
00107   this->type = OT_GOTO_WAYPOINT;
00108   this->flags = 0;
00109   this->dest = destination;
00110 }
00111 
00116 void Order::MakeLoading(bool ordered)
00117 {
00118   this->type = OT_LOADING;
00119   if (!ordered) this->flags = 0;
00120 }
00121 
00125 void Order::MakeLeaveStation()
00126 {
00127   this->type = OT_LEAVESTATION;
00128   this->flags = 0;
00129 }
00130 
00134 void Order::MakeDummy()
00135 {
00136   this->type = OT_DUMMY;
00137   this->flags = 0;
00138 }
00139 
00144 void Order::MakeConditional(VehicleOrderID order)
00145 {
00146   this->type = OT_CONDITIONAL;
00147   this->flags = order;
00148   this->dest = 0;
00149 }
00150 
00155 void Order::MakeImplicit(StationID destination)
00156 {
00157   this->type = OT_IMPLICIT;
00158   this->dest = destination;
00159 }
00160 
00167 void Order::SetRefit(CargoID cargo, byte subtype)
00168 {
00169   this->refit_cargo = cargo;
00170   this->refit_subtype = subtype;
00171 }
00172 
00178 bool Order::Equals(const Order &other) const
00179 {
00180   /* In case of go to nearest depot orders we need "only" compare the flags
00181    * with the other and not the nearest depot order bit or the actual
00182    * destination because those get clear/filled in during the order
00183    * evaluation. If we do not do this the order will continuously be seen as
00184    * a different order and it will try to find a "nearest depot" every tick. */
00185   if ((this->IsType(OT_GOTO_DEPOT) && this->type == other.type) &&
00186       ((this->GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0 ||
00187        (other.GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0)) {
00188     return this->GetDepotOrderType() == other.GetDepotOrderType() &&
00189         (this->GetDepotActionType() & ~ODATFB_NEAREST_DEPOT) == (other.GetDepotActionType() & ~ODATFB_NEAREST_DEPOT);
00190   }
00191 
00192   return this->type == other.type && this->flags == other.flags && this->dest == other.dest;
00193 }
00194 
00201 uint32 Order::Pack() const
00202 {
00203   return this->dest << 16 | this->flags << 8 | this->type;
00204 }
00205 
00211 uint16 Order::MapOldOrder() const
00212 {
00213   uint16 order = this->GetType();
00214   switch (this->type) {
00215     case OT_GOTO_STATION:
00216       if (this->GetUnloadType() & OUFB_UNLOAD) SetBit(order, 5);
00217       if (this->GetLoadType() & OLFB_FULL_LOAD) SetBit(order, 6);
00218       if (this->GetNonStopType() & ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS) SetBit(order, 7);
00219       order |= GB(this->GetDestination(), 0, 8) << 8;
00220       break;
00221     case OT_GOTO_DEPOT:
00222       if (!(this->GetDepotOrderType() & ODTFB_PART_OF_ORDERS)) SetBit(order, 6);
00223       SetBit(order, 7);
00224       order |= GB(this->GetDestination(), 0, 8) << 8;
00225       break;
00226     case OT_LOADING:
00227       if (this->GetLoadType() & OLFB_FULL_LOAD) SetBit(order, 6);
00228       break;
00229   }
00230   return order;
00231 }
00232 
00237 Order::Order(uint32 packed)
00238 {
00239   this->type    = (OrderType)GB(packed,  0,  8);
00240   this->flags   = GB(packed,  8,  8);
00241   this->dest    = GB(packed, 16, 16);
00242   this->next    = NULL;
00243   this->refit_cargo   = CT_NO_REFIT;
00244   this->refit_subtype = 0;
00245   this->wait_time     = 0;
00246   this->travel_time   = 0;
00247 }
00248 
00254 void InvalidateVehicleOrder(const Vehicle *v, int data)
00255 {
00256   SetWindowDirty(WC_VEHICLE_VIEW, v->index);
00257 
00258   if (data != 0) {
00259     /* Calls SetDirty() too */
00260     InvalidateWindowData(WC_VEHICLE_ORDERS,    v->index, data);
00261     InvalidateWindowData(WC_VEHICLE_TIMETABLE, v->index, data);
00262     return;
00263   }
00264 
00265   SetWindowDirty(WC_VEHICLE_ORDERS,    v->index);
00266   SetWindowDirty(WC_VEHICLE_TIMETABLE, v->index);
00267 }
00268 
00276 void Order::AssignOrder(const Order &other)
00277 {
00278   this->type  = other.type;
00279   this->flags = other.flags;
00280   this->dest  = other.dest;
00281 
00282   this->refit_cargo   = other.refit_cargo;
00283   this->refit_subtype = other.refit_subtype;
00284 
00285   this->wait_time   = other.wait_time;
00286   this->travel_time = other.travel_time;
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        */
00417       const Order *skip_to = this->GetNextStoppingOrder(v,
00418           this->GetOrderAt(next->GetConditionSkipToOrder()),
00419           hops + 1);
00420       const Order *advance = this->GetNextStoppingOrder(v,
00421           this->GetNext(next), hops + 1);
00422       if (advance == NULL) {
00423         return skip_to;
00424       } else if (skip_to == NULL) {
00425         return advance;
00426       } else {
00427         return this->GetBestLoadableNext(v, skip_to, advance);
00428       }
00429     } else {
00430       /* Otherwise we're optimistic and expect that the
00431        * condition value won't change until it's evaluated.
00432        */
00433       VehicleOrderID skip_to = ProcessConditionalOrder(next, v);
00434       if (skip_to != INVALID_VEH_ORDER_ID) {
00435         return this->GetNextStoppingOrder(v,
00436             this->GetOrderAt(skip_to), hops + 1);
00437       } else {
00438         return this->GetNextStoppingOrder(v,
00439             this->GetNext(next), hops + 1);
00440       }
00441     }
00442   }
00443 
00444   if (next->IsType(OT_GOTO_DEPOT)) {
00445     if (next->GetDepotActionType() == ODATFB_HALT) return NULL;
00446     if (next->IsRefit()) return next;
00447   }
00448 
00449   if (!next->CanLoadOrUnload()) {
00450     return this->GetNextStoppingOrder(v, this->GetNext(next), hops + 1);
00451   }
00452 
00453   return next;
00454 }
00455 
00463 StationID OrderList::GetNextStoppingStation(const Vehicle *v) const
00464 {
00465   
00466   const Order *next = this->GetOrderAt(v->cur_implicit_order_index);
00467   if (next == NULL) {
00468     next = this->GetFirstOrder();
00469     if (next == NULL) return INVALID_STATION;
00470   } else {
00471     next = this->GetNext(next);
00472   }
00473 
00474   uint hops = 0;
00475   do {
00476     next = this->GetNextStoppingOrder(v, next, ++hops, true);
00477     /* Don't return a next stop if the vehicle has to unload everything. */
00478     if (next == NULL || (next->GetDestination() == v->last_station_visited &&
00479         (next->GetUnloadType() & (OUFB_TRANSFER | OUFB_UNLOAD)) == 0)) {
00480       return INVALID_STATION;
00481     }
00482   } while (next->IsType(OT_GOTO_DEPOT) || next->GetDestination() == v->last_station_visited);
00483 
00484   return next->GetDestination();
00485 }
00486 
00492 void OrderList::InsertOrderAt(Order *new_order, int index)
00493 {
00494   if (this->first == NULL) {
00495     this->first = new_order;
00496   } else {
00497     if (index == 0) {
00498       /* Insert as first or only order */
00499       new_order->next = this->first;
00500       this->first = new_order;
00501     } else if (index >= this->num_orders) {
00502       /* index is after the last order, add it to the end */
00503       this->GetLastOrder()->next = new_order;
00504     } else {
00505       /* Put the new order in between */
00506       Order *order = this->GetOrderAt(index - 1);
00507       new_order->next = order->next;
00508       order->next = new_order;
00509     }
00510   }
00511   ++this->num_orders;
00512   if (!new_order->IsType(OT_IMPLICIT)) ++this->num_manual_orders;
00513   this->timetable_duration += new_order->wait_time + new_order->travel_time;
00514 
00515   /* We can visit oil rigs and buoys that are not our own. They will be shown in
00516    * the list of stations. So, we need to invalidate that window if needed. */
00517   if (new_order->IsType(OT_GOTO_STATION) || new_order->IsType(OT_GOTO_WAYPOINT)) {
00518     BaseStation *bs = BaseStation::Get(new_order->GetDestination());
00519     if (bs->owner == OWNER_NONE) InvalidateWindowClassesData(WC_STATION_LIST, 0);
00520   }
00521 
00522 }
00523 
00524 
00529 void OrderList::DeleteOrderAt(int index)
00530 {
00531   if (index >= this->num_orders) return;
00532 
00533   Order *to_remove;
00534 
00535   if (index == 0) {
00536     to_remove = this->first;
00537     this->first = to_remove->next;
00538   } else {
00539     Order *prev = GetOrderAt(index - 1);
00540     to_remove = prev->next;
00541     prev->next = to_remove->next;
00542   }
00543   --this->num_orders;
00544   if (!to_remove->IsType(OT_IMPLICIT)) --this->num_manual_orders;
00545   this->timetable_duration -= (to_remove->wait_time + to_remove->travel_time);
00546   delete to_remove;
00547 }
00548 
00554 void OrderList::MoveOrder(int from, int to)
00555 {
00556   if (from >= this->num_orders || to >= this->num_orders || from == to) return;
00557 
00558   Order *moving_one;
00559 
00560   /* Take the moving order out of the pointer-chain */
00561   if (from == 0) {
00562     moving_one = this->first;
00563     this->first = moving_one->next;
00564   } else {
00565     Order *one_before = GetOrderAt(from - 1);
00566     moving_one = one_before->next;
00567     one_before->next = moving_one->next;
00568   }
00569 
00570   /* Insert the moving_order again in the pointer-chain */
00571   if (to == 0) {
00572     moving_one->next = this->first;
00573     this->first = moving_one;
00574   } else {
00575     Order *one_before = GetOrderAt(to - 1);
00576     moving_one->next = one_before->next;
00577     one_before->next = moving_one;
00578   }
00579 }
00580 
00586 void OrderList::RemoveVehicle(Vehicle *v)
00587 {
00588   --this->num_vehicles;
00589   if (v == this->first_shared) this->first_shared = v->NextShared();
00590 }
00591 
00596 bool OrderList::IsVehicleInSharedOrdersList(const Vehicle *v) const
00597 {
00598   for (const Vehicle *v_shared = this->first_shared; v_shared != NULL; v_shared = v_shared->NextShared()) {
00599     if (v_shared == v) return true;
00600   }
00601 
00602   return false;
00603 }
00604 
00610 int OrderList::GetPositionInSharedOrderList(const Vehicle *v) const
00611 {
00612   int count = 0;
00613   for (const Vehicle *v_shared = v->PreviousShared(); v_shared != NULL; v_shared = v_shared->PreviousShared()) count++;
00614   return count;
00615 }
00616 
00621 bool OrderList::IsCompleteTimetable() const
00622 {
00623   for (Order *o = this->first; o != NULL; o = o->next) {
00624     /* Implicit orders are, by definition, not timetabled. */
00625     if (o->IsType(OT_IMPLICIT)) continue;
00626     if (!o->IsCompletelyTimetabled()) return false;
00627   }
00628   return true;
00629 }
00630 
00634 void OrderList::DebugCheckSanity() const
00635 {
00636   VehicleOrderID check_num_orders = 0;
00637   VehicleOrderID check_num_manual_orders = 0;
00638   uint check_num_vehicles = 0;
00639   Ticks check_timetable_duration = 0;
00640 
00641   DEBUG(misc, 6, "Checking OrderList %hu for sanity...", this->index);
00642 
00643   for (const Order *o = this->first; o != NULL; o = o->next) {
00644     ++check_num_orders;
00645     if (!o->IsType(OT_IMPLICIT)) ++check_num_manual_orders;
00646     check_timetable_duration += o->wait_time + o->travel_time;
00647   }
00648   assert(this->num_orders == check_num_orders);
00649   assert(this->num_manual_orders == check_num_manual_orders);
00650   assert(this->timetable_duration == check_timetable_duration);
00651 
00652   for (const Vehicle *v = this->first_shared; v != NULL; v = v->NextShared()) {
00653     ++check_num_vehicles;
00654     assert(v->orders.list == this);
00655   }
00656   assert(this->num_vehicles == check_num_vehicles);
00657   DEBUG(misc, 6, "... detected %u orders (%u manual), %u vehicles, %i ticks",
00658       (uint)this->num_orders, (uint)this->num_manual_orders,
00659       this->num_vehicles, this->timetable_duration);
00660 }
00661 
00669 static inline bool OrderGoesToStation(const Vehicle *v, const Order *o)
00670 {
00671   return o->IsType(OT_GOTO_STATION) ||
00672       (v->type == VEH_AIRCRAFT && o->IsType(OT_GOTO_DEPOT) && !(o->GetDepotActionType() & ODATFB_NEAREST_DEPOT));
00673 }
00674 
00681 static void DeleteOrderWarnings(const Vehicle *v)
00682 {
00683   DeleteVehicleNews(v->index, STR_NEWS_VEHICLE_HAS_TOO_FEW_ORDERS);
00684   DeleteVehicleNews(v->index, STR_NEWS_VEHICLE_HAS_VOID_ORDER);
00685   DeleteVehicleNews(v->index, STR_NEWS_VEHICLE_HAS_DUPLICATE_ENTRY);
00686   DeleteVehicleNews(v->index, STR_NEWS_VEHICLE_HAS_INVALID_ENTRY);
00687 }
00688 
00694 TileIndex Order::GetLocation(const Vehicle *v) const
00695 {
00696   switch (this->GetType()) {
00697     case OT_GOTO_WAYPOINT:
00698     case OT_GOTO_STATION:
00699     case OT_IMPLICIT:
00700       return BaseStation::Get(this->GetDestination())->xy;
00701 
00702     case OT_GOTO_DEPOT:
00703       if ((this->GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0) return INVALID_TILE;
00704       return (v->type == VEH_AIRCRAFT) ? Station::Get(this->GetDestination())->xy : Depot::Get(this->GetDestination())->xy;
00705 
00706     default:
00707       return INVALID_TILE;
00708   }
00709 }
00710 
00711 static uint GetOrderDistance(const Order *prev, const Order *cur, const Vehicle *v, int conditional_depth = 0)
00712 {
00713   assert(v->type == VEH_SHIP);
00714 
00715   if (cur->IsType(OT_CONDITIONAL)) {
00716     if (conditional_depth > v->GetNumOrders()) return 0;
00717 
00718     conditional_depth++;
00719 
00720     int dist1 = GetOrderDistance(prev, v->GetOrder(cur->GetConditionSkipToOrder()), v, conditional_depth);
00721     int dist2 = GetOrderDistance(prev, cur->next == NULL ? v->orders.list->GetFirstOrder() : cur->next, v, conditional_depth);
00722     return max(dist1, dist2);
00723   }
00724 
00725   TileIndex prev_tile = prev->GetLocation(v);
00726   TileIndex cur_tile = cur->GetLocation(v);
00727   if (prev_tile == INVALID_TILE || cur_tile == INVALID_TILE) return 0;
00728   return DistanceManhattan(prev_tile, cur_tile);
00729 }
00730 
00744 CommandCost CmdInsertOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00745 {
00746   VehicleID veh          = GB(p1,  0, 20);
00747   VehicleOrderID sel_ord = GB(p1, 20, 8);
00748   Order new_order(p2);
00749 
00750   Vehicle *v = Vehicle::GetIfValid(veh);
00751   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
00752 
00753   CommandCost ret = CheckOwnership(v->owner);
00754   if (ret.Failed()) return ret;
00755 
00756   /* Check if the inserted order is to the correct destination (owner, type),
00757    * and has the correct flags if any */
00758   switch (new_order.GetType()) {
00759     case OT_GOTO_STATION: {
00760       const Station *st = Station::GetIfValid(new_order.GetDestination());
00761       if (st == NULL) return CMD_ERROR;
00762 
00763       if (st->owner != OWNER_NONE) {
00764         CommandCost ret = CheckOwnership(st->owner);
00765         if (ret.Failed()) return ret;
00766       }
00767 
00768       if (!CanVehicleUseStation(v, st)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER);
00769       for (Vehicle *u = v->FirstShared(); u != NULL; u = u->NextShared()) {
00770         if (!CanVehicleUseStation(u, st)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER_SHARED);
00771       }
00772 
00773       /* Non stop only allowed for ground vehicles. */
00774       if (new_order.GetNonStopType() != ONSF_STOP_EVERYWHERE && !v->IsGroundVehicle()) return CMD_ERROR;
00775 
00776       /* Filter invalid load/unload types. */
00777       switch (new_order.GetLoadType()) {
00778         case OLF_LOAD_IF_POSSIBLE: case OLFB_FULL_LOAD: case OLF_FULL_LOAD_ANY: case OLFB_NO_LOAD: break;
00779         default: return CMD_ERROR;
00780       }
00781       switch (new_order.GetUnloadType()) {
00782         case OUF_UNLOAD_IF_POSSIBLE: case OUFB_UNLOAD: case OUFB_TRANSFER: case OUFB_NO_UNLOAD: break;
00783         default: return CMD_ERROR;
00784       }
00785 
00786       /* Filter invalid stop locations */
00787       switch (new_order.GetStopLocation()) {
00788         case OSL_PLATFORM_NEAR_END:
00789         case OSL_PLATFORM_MIDDLE:
00790           if (v->type != VEH_TRAIN) return CMD_ERROR;
00791           /* FALL THROUGH */
00792         case OSL_PLATFORM_FAR_END:
00793           break;
00794 
00795         default:
00796           return CMD_ERROR;
00797       }
00798 
00799       break;
00800     }
00801 
00802     case OT_GOTO_DEPOT: {
00803       if ((new_order.GetDepotActionType() & ODATFB_NEAREST_DEPOT) == 0) {
00804         if (v->type == VEH_AIRCRAFT) {
00805           const Station *st = Station::GetIfValid(new_order.GetDestination());
00806 
00807           if (st == NULL) return CMD_ERROR;
00808 
00809           CommandCost ret = CheckOwnership(st->owner);
00810           if (ret.Failed()) return ret;
00811 
00812           if (!CanVehicleUseStation(v, st) || !st->airport.HasHangar()) {
00813             return CMD_ERROR;
00814           }
00815         } else {
00816           const Depot *dp = Depot::GetIfValid(new_order.GetDestination());
00817 
00818           if (dp == NULL) return CMD_ERROR;
00819 
00820           CommandCost ret = CheckOwnership(GetTileOwner(dp->xy));
00821           if (ret.Failed()) return ret;
00822 
00823           switch (v->type) {
00824             case VEH_TRAIN:
00825               if (!IsRailDepotTile(dp->xy)) return CMD_ERROR;
00826               break;
00827 
00828             case VEH_ROAD:
00829               if (!IsRoadDepotTile(dp->xy)) return CMD_ERROR;
00830               break;
00831 
00832             case VEH_SHIP:
00833               if (!IsShipDepotTile(dp->xy)) return CMD_ERROR;
00834               break;
00835 
00836             default: return CMD_ERROR;
00837           }
00838         }
00839       }
00840 
00841       if (new_order.GetNonStopType() != ONSF_STOP_EVERYWHERE && !v->IsGroundVehicle()) return CMD_ERROR;
00842       if (new_order.GetDepotOrderType() & ~(ODTFB_PART_OF_ORDERS | ((new_order.GetDepotOrderType() & ODTFB_PART_OF_ORDERS) != 0 ? ODTFB_SERVICE : 0))) return CMD_ERROR;
00843       if (new_order.GetDepotActionType() & ~(ODATFB_HALT | ODATFB_NEAREST_DEPOT)) return CMD_ERROR;
00844       if ((new_order.GetDepotOrderType() & ODTFB_SERVICE) && (new_order.GetDepotActionType() & ODATFB_HALT)) return CMD_ERROR;
00845       break;
00846     }
00847 
00848     case OT_GOTO_WAYPOINT: {
00849       const Waypoint *wp = Waypoint::GetIfValid(new_order.GetDestination());
00850       if (wp == NULL) return CMD_ERROR;
00851 
00852       switch (v->type) {
00853         default: return CMD_ERROR;
00854 
00855         case VEH_TRAIN: {
00856           if (!(wp->facilities & FACIL_TRAIN)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER);
00857 
00858           CommandCost ret = CheckOwnership(wp->owner);
00859           if (ret.Failed()) return ret;
00860           break;
00861         }
00862 
00863         case VEH_SHIP:
00864           if (!(wp->facilities & FACIL_DOCK)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER);
00865           if (wp->owner != OWNER_NONE) {
00866             CommandCost ret = CheckOwnership(wp->owner);
00867             if (ret.Failed()) return ret;
00868           }
00869           break;
00870       }
00871 
00872       /* Order flags can be any of the following for waypoints:
00873        * [non-stop]
00874        * non-stop orders (if any) are only valid for trains */
00875       if (new_order.GetNonStopType() != ONSF_STOP_EVERYWHERE && v->type != VEH_TRAIN) return CMD_ERROR;
00876       break;
00877     }
00878 
00879     case OT_CONDITIONAL: {
00880       VehicleOrderID skip_to = new_order.GetConditionSkipToOrder();
00881       if (skip_to != 0 && skip_to >= v->GetNumOrders()) return CMD_ERROR; // Always allow jumping to the first (even when there is no order).
00882       if (new_order.GetConditionVariable() >= OCV_END) return CMD_ERROR;
00883 
00884       OrderConditionComparator occ = new_order.GetConditionComparator();
00885       if (occ >= OCC_END) return CMD_ERROR;
00886       switch (new_order.GetConditionVariable()) {
00887         case OCV_REQUIRES_SERVICE:
00888           if (occ != OCC_IS_TRUE && occ != OCC_IS_FALSE) return CMD_ERROR;
00889           break;
00890 
00891         case OCV_UNCONDITIONALLY:
00892           if (occ != OCC_EQUALS) return CMD_ERROR;
00893           if (new_order.GetConditionValue() != 0) return CMD_ERROR;
00894           break;
00895 
00896         case OCV_LOAD_PERCENTAGE:
00897         case OCV_RELIABILITY:
00898           if (new_order.GetConditionValue() > 100) return CMD_ERROR;
00899           /* FALL THROUGH */
00900         default:
00901           if (occ == OCC_IS_TRUE || occ == OCC_IS_FALSE) return CMD_ERROR;
00902           break;
00903       }
00904       break;
00905     }
00906 
00907     default: return CMD_ERROR;
00908   }
00909 
00910   if (sel_ord > v->GetNumOrders()) return CMD_ERROR;
00911 
00912   if (v->GetNumOrders() >= MAX_VEH_ORDER_ID) return_cmd_error(STR_ERROR_TOO_MANY_ORDERS);
00913   if (!Order::CanAllocateItem()) return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
00914   if (v->orders.list == NULL && !OrderList::CanAllocateItem()) return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
00915 
00916   if (v->type == VEH_SHIP && _settings_game.pf.pathfinder_for_ships != VPF_NPF) {
00917     /* Make sure the new destination is not too far away from the previous */
00918     const Order *prev = NULL;
00919     uint n = 0;
00920 
00921     /* Find the last goto station or depot order before the insert location.
00922      * If the order is to be inserted at the beginning of the order list this
00923      * finds the last order in the list. */
00924     const Order *o;
00925     FOR_VEHICLE_ORDERS(v, o) {
00926       switch (o->GetType()) {
00927         case OT_GOTO_STATION:
00928         case OT_GOTO_DEPOT:
00929         case OT_GOTO_WAYPOINT:
00930           prev = o;
00931           break;
00932 
00933         default: break;
00934       }
00935       if (++n == sel_ord && prev != NULL) break;
00936     }
00937     if (prev != NULL) {
00938       uint dist = GetOrderDistance(prev, &new_order, v);
00939       if (dist >= 130) {
00940         return_cmd_error(STR_ERROR_TOO_FAR_FROM_PREVIOUS_DESTINATION);
00941       }
00942     }
00943   }
00944 
00945   if (flags & DC_EXEC) {
00946     Order *new_o = new Order();
00947     new_o->AssignOrder(new_order);
00948     InsertOrder(v, new_o, sel_ord);
00949   }
00950 
00951   return CommandCost();
00952 }
00953 
00960 void InsertOrder(Vehicle *v, Order *new_o, VehicleOrderID sel_ord)
00961 {
00962   /* Create new order and link in list */
00963   if (v->orders.list == NULL) {
00964     v->orders.list = new OrderList(new_o, v);
00965   } else {
00966     v->orders.list->InsertOrderAt(new_o, sel_ord);
00967   }
00968 
00969   Vehicle *u = v->FirstShared();
00970   DeleteOrderWarnings(u);
00971   for (; u != NULL; u = u->NextShared()) {
00972     assert(v->orders.list == u->orders.list);
00973 
00974     /* If there is added an order before the current one, we need
00975      * to update the selected order. We do not change implicit/real order indices though.
00976      * If the new order is between the current implicit order and real order, the implicit order will
00977      * later skip the inserted order. */
00978     if (sel_ord <= u->cur_real_order_index) {
00979       uint cur = u->cur_real_order_index + 1;
00980       /* Check if we don't go out of bound */
00981       if (cur < u->GetNumOrders()) {
00982         u->cur_real_order_index = cur;
00983       }
00984     }
00985     if (sel_ord == u->cur_implicit_order_index && u->IsGroundVehicle()) {
00986       /* We are inserting an order just before the current implicit order.
00987        * We do not know whether we will reach current implicit or the newly inserted order first.
00988        * So, disable creation of implicit orders until we are on track again. */
00989       uint16 &gv_flags = u->GetGroundVehicleFlags();
00990       SetBit(gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS);
00991     }
00992     if (sel_ord <= u->cur_implicit_order_index) {
00993       uint cur = u->cur_implicit_order_index + 1;
00994       /* Check if we don't go out of bound */
00995       if (cur < u->GetNumOrders()) {
00996         u->cur_implicit_order_index = cur;
00997       }
00998     }
00999     /* Update any possible open window of the vehicle */
01000     InvalidateVehicleOrder(u, INVALID_VEH_ORDER_ID | (sel_ord << 8));
01001   }
01002 
01003   /* As we insert an order, the order to skip to will be 'wrong'. */
01004   VehicleOrderID cur_order_id = 0;
01005   Order *order;
01006   FOR_VEHICLE_ORDERS(v, order) {
01007     if (order->IsType(OT_CONDITIONAL)) {
01008       VehicleOrderID order_id = order->GetConditionSkipToOrder();
01009       if (order_id >= sel_ord) {
01010         order->SetConditionSkipToOrder(order_id + 1);
01011       }
01012       if (order_id == cur_order_id) {
01013         order->SetConditionSkipToOrder((order_id + 1) % v->GetNumOrders());
01014       }
01015     }
01016     cur_order_id++;
01017   }
01018 
01019   /* Make sure to rebuild the whole list */
01020   InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
01021 }
01022 
01028 static CommandCost DecloneOrder(Vehicle *dst, DoCommandFlag flags)
01029 {
01030   if (flags & DC_EXEC) {
01031     DeleteVehicleOrders(dst);
01032     InvalidateVehicleOrder(dst, -1);
01033 
01034     InvalidateWindowClassesData(GetWindowClassForVehicleType(dst->type), 0);
01035   }
01036   return CommandCost();
01037 }
01038 
01048 CommandCost CmdDeleteOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01049 {
01050   VehicleID veh_id = GB(p1, 0, 20);
01051   VehicleOrderID sel_ord = GB(p2, 0, 8);
01052 
01053   Vehicle *v = Vehicle::GetIfValid(veh_id);
01054 
01055   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
01056 
01057   CommandCost ret = CheckOwnership(v->owner);
01058   if (ret.Failed()) return ret;
01059 
01060   /* If we did not select an order, we maybe want to de-clone the orders */
01061   if (sel_ord >= v->GetNumOrders()) return DecloneOrder(v, flags);
01062 
01063   if (v->GetOrder(sel_ord) == NULL) return CMD_ERROR;
01064 
01065   if (flags & DC_EXEC) DeleteOrder(v, sel_ord);
01066   return CommandCost();
01067 }
01068 
01073 static void CancelLoadingDueToDeletedOrder(Vehicle *v)
01074 {
01075   assert(v->current_order.IsType(OT_LOADING));
01076   /* NON-stop flag is misused to see if a train is in a station that is
01077    * on his order list or not */
01078   v->current_order.SetNonStopType(ONSF_STOP_EVERYWHERE);
01079   /* When full loading, "cancel" that order so the vehicle doesn't
01080    * stay indefinitely at this station anymore. */
01081   if (v->current_order.GetLoadType() & OLFB_FULL_LOAD) v->current_order.SetLoadType(OLF_LOAD_IF_POSSIBLE);
01082 }
01083 
01089 void DeleteOrder(Vehicle *v, VehicleOrderID sel_ord)
01090 {
01091   v->orders.list->DeleteOrderAt(sel_ord);
01092 
01093   Vehicle *u = v->FirstShared();
01094   DeleteOrderWarnings(u);
01095   for (; u != NULL; u = u->NextShared()) {
01096     assert(v->orders.list == u->orders.list);
01097 
01098     if (sel_ord == u->cur_real_order_index && u->current_order.IsType(OT_LOADING)) {
01099       CancelLoadingDueToDeletedOrder(u);
01100     }
01101 
01102     if (sel_ord < u->cur_real_order_index) {
01103       u->cur_real_order_index--;
01104     } else if (sel_ord == u->cur_real_order_index) {
01105       u->UpdateRealOrderIndex();
01106     }
01107 
01108     if (sel_ord < u->cur_implicit_order_index) {
01109       u->cur_implicit_order_index--;
01110     } else if (sel_ord == u->cur_implicit_order_index) {
01111       /* Make sure the index is valid */
01112       if (u->cur_implicit_order_index >= u->GetNumOrders()) u->cur_implicit_order_index = 0;
01113 
01114       /* Skip non-implicit orders for the implicit-order-index (e.g. if the current implicit order was deleted */
01115       while (u->cur_implicit_order_index != u->cur_real_order_index && !u->GetOrder(u->cur_implicit_order_index)->IsType(OT_IMPLICIT)) {
01116         u->cur_implicit_order_index++;
01117         if (u->cur_implicit_order_index >= u->GetNumOrders()) u->cur_implicit_order_index = 0;
01118       }
01119     }
01120 
01121     /* Update any possible open window of the vehicle */
01122     InvalidateVehicleOrder(u, sel_ord | (INVALID_VEH_ORDER_ID << 8));
01123   }
01124 
01125   /* As we delete an order, the order to skip to will be 'wrong'. */
01126   VehicleOrderID cur_order_id = 0;
01127   Order *order = NULL;
01128   FOR_VEHICLE_ORDERS(v, order) {
01129     if (order->IsType(OT_CONDITIONAL)) {
01130       VehicleOrderID order_id = order->GetConditionSkipToOrder();
01131       if (order_id >= sel_ord) {
01132         order_id = max(order_id - 1, 0);
01133       }
01134       if (order_id == cur_order_id) {
01135         order_id = (order_id + 1) % v->GetNumOrders();
01136       }
01137       order->SetConditionSkipToOrder(order_id);
01138     }
01139     cur_order_id++;
01140   }
01141 
01142   InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
01143 }
01144 
01154 CommandCost CmdSkipToOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01155 {
01156   VehicleID veh_id = GB(p1, 0, 20);
01157   VehicleOrderID sel_ord = GB(p2, 0, 8);
01158 
01159   Vehicle *v = Vehicle::GetIfValid(veh_id);
01160 
01161   if (v == NULL || !v->IsPrimaryVehicle() || sel_ord == v->cur_implicit_order_index || sel_ord >= v->GetNumOrders() || v->GetNumOrders() < 2) return CMD_ERROR;
01162 
01163   CommandCost ret = CheckOwnership(v->owner);
01164   if (ret.Failed()) return ret;
01165 
01166   if (flags & DC_EXEC) {
01167     if (v->current_order.IsType(OT_LOADING)) v->LeaveStation();
01168 
01169     v->cur_implicit_order_index = v->cur_real_order_index = sel_ord;
01170     v->UpdateRealOrderIndex();
01171 
01172     InvalidateVehicleOrder(v, -2);
01173   }
01174 
01175   /* We have an aircraft/ship, they have a mini-schedule, so update them all */
01176   if (v->type == VEH_AIRCRAFT) SetWindowClassesDirty(WC_AIRCRAFT_LIST);
01177   if (v->type == VEH_SHIP) SetWindowClassesDirty(WC_SHIPS_LIST);
01178 
01179   return CommandCost();
01180 }
01181 
01195 CommandCost CmdMoveOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01196 {
01197   VehicleID veh = GB(p1, 0, 20);
01198   VehicleOrderID moving_order = GB(p2,  0, 16);
01199   VehicleOrderID target_order = GB(p2, 16, 16);
01200 
01201   Vehicle *v = Vehicle::GetIfValid(veh);
01202   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
01203 
01204   CommandCost ret = CheckOwnership(v->owner);
01205   if (ret.Failed()) return ret;
01206 
01207   /* Don't make senseless movements */
01208   if (moving_order >= v->GetNumOrders() || target_order >= v->GetNumOrders() ||
01209       moving_order == target_order || v->GetNumOrders() <= 1) return CMD_ERROR;
01210 
01211   Order *moving_one = v->GetOrder(moving_order);
01212   /* Don't move an empty order */
01213   if (moving_one == NULL) return CMD_ERROR;
01214 
01215   if (flags & DC_EXEC) {
01216     v->orders.list->MoveOrder(moving_order, target_order);
01217 
01218     /* Update shared list */
01219     Vehicle *u = v->FirstShared();
01220 
01221     DeleteOrderWarnings(u);
01222 
01223     for (; u != NULL; u = u->NextShared()) {
01224       /* Update the current order.
01225        * There are multiple ways to move orders, which result in cur_implicit_order_index
01226        * and cur_real_order_index to not longer make any sense. E.g. moving another
01227        * real order between them.
01228        *
01229        * Basically one could choose to preserve either of them, but not both.
01230        * While both ways are suitable in this or that case from a human point of view, neither
01231        * of them makes really sense.
01232        * However, from an AI point of view, preserving cur_real_order_index is the most
01233        * predictable and transparent behaviour.
01234        *
01235        * With that decision it basically does not matter what we do to cur_implicit_order_index.
01236        * If we change orders between the implict- and real-index, the implicit orders are mostly likely
01237        * completely out-dated anyway. So, keep it simple and just keep cur_implicit_order_index as well.
01238        * The worst which can happen is that a lot of implicit orders are removed when reaching current_order.
01239        */
01240       if (u->cur_real_order_index == moving_order) {
01241         u->cur_real_order_index = target_order;
01242       } else if (u->cur_real_order_index > moving_order && u->cur_real_order_index <= target_order) {
01243         u->cur_real_order_index--;
01244       } else if (u->cur_real_order_index < moving_order && u->cur_real_order_index >= target_order) {
01245         u->cur_real_order_index++;
01246       }
01247 
01248       if (u->cur_implicit_order_index == moving_order) {
01249         u->cur_implicit_order_index = target_order;
01250       } else if (u->cur_implicit_order_index > moving_order && u->cur_implicit_order_index <= target_order) {
01251         u->cur_implicit_order_index--;
01252       } else if (u->cur_implicit_order_index < moving_order && u->cur_implicit_order_index >= target_order) {
01253         u->cur_implicit_order_index++;
01254       }
01255 
01256       assert(v->orders.list == u->orders.list);
01257       /* Update any possible open window of the vehicle */
01258       InvalidateVehicleOrder(u, moving_order | (target_order << 8));
01259     }
01260 
01261     /* As we move an order, the order to skip to will be 'wrong'. */
01262     Order *order;
01263     FOR_VEHICLE_ORDERS(v, order) {
01264       if (order->IsType(OT_CONDITIONAL)) {
01265         VehicleOrderID order_id = order->GetConditionSkipToOrder();
01266         if (order_id == moving_order) {
01267           order_id = target_order;
01268         } else if (order_id > moving_order && order_id <= target_order) {
01269           order_id--;
01270         } else if (order_id < moving_order && order_id >= target_order) {
01271           order_id++;
01272         }
01273         order->SetConditionSkipToOrder(order_id);
01274       }
01275     }
01276 
01277     /* Make sure to rebuild the whole list */
01278     InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
01279   }
01280 
01281   return CommandCost();
01282 }
01283 
01299 CommandCost CmdModifyOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01300 {
01301   VehicleOrderID sel_ord = GB(p1, 20,  8);
01302   VehicleID veh          = GB(p1,  0, 20);
01303   ModifyOrderFlags mof   = Extract<ModifyOrderFlags, 0, 4>(p2);
01304   uint16 data            = GB(p2,  4, 11);
01305 
01306   if (mof >= MOF_END) return CMD_ERROR;
01307 
01308   Vehicle *v = Vehicle::GetIfValid(veh);
01309   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
01310 
01311   CommandCost ret = CheckOwnership(v->owner);
01312   if (ret.Failed()) return ret;
01313 
01314   /* Is it a valid order? */
01315   if (sel_ord >= v->GetNumOrders()) return CMD_ERROR;
01316 
01317   Order *order = v->GetOrder(sel_ord);
01318   switch (order->GetType()) {
01319     case OT_GOTO_STATION:
01320       if (mof == MOF_COND_VARIABLE || mof == MOF_COND_COMPARATOR || mof == MOF_DEPOT_ACTION || mof == MOF_COND_VALUE) return CMD_ERROR;
01321       break;
01322 
01323     case OT_GOTO_DEPOT:
01324       if (mof != MOF_NON_STOP && mof != MOF_DEPOT_ACTION) return CMD_ERROR;
01325       break;
01326 
01327     case OT_GOTO_WAYPOINT:
01328       if (mof != MOF_NON_STOP) return CMD_ERROR;
01329       break;
01330 
01331     case OT_CONDITIONAL:
01332       if (mof != MOF_COND_VARIABLE && mof != MOF_COND_COMPARATOR && mof != MOF_COND_VALUE && mof != MOF_COND_DESTINATION) return CMD_ERROR;
01333       break;
01334 
01335     default:
01336       return CMD_ERROR;
01337   }
01338 
01339   switch (mof) {
01340     default: NOT_REACHED();
01341 
01342     case MOF_NON_STOP:
01343       if (!v->IsGroundVehicle()) return CMD_ERROR;
01344       if (data >= ONSF_END) return CMD_ERROR;
01345       if (data == order->GetNonStopType()) return CMD_ERROR;
01346       break;
01347 
01348     case MOF_STOP_LOCATION:
01349       if (v->type != VEH_TRAIN) return CMD_ERROR;
01350       if (data >= OSL_END) return CMD_ERROR;
01351       break;
01352 
01353     case MOF_UNLOAD:
01354       if ((data & ~(OUFB_UNLOAD | OUFB_TRANSFER | OUFB_NO_UNLOAD)) != 0) return CMD_ERROR;
01355       /* Unload and no-unload are mutual exclusive and so are transfer and no unload. */
01356       if (data != 0 && ((data & (OUFB_UNLOAD | OUFB_TRANSFER)) != 0) == ((data & OUFB_NO_UNLOAD) != 0)) return CMD_ERROR;
01357       if (data == order->GetUnloadType()) return CMD_ERROR;
01358       break;
01359 
01360     case MOF_LOAD:
01361       if (data > OLFB_NO_LOAD || data == 1) return CMD_ERROR;
01362       if (data == order->GetLoadType()) return CMD_ERROR;
01363       break;
01364 
01365     case MOF_DEPOT_ACTION:
01366       if (data >= DA_END) return CMD_ERROR;
01367       break;
01368 
01369     case MOF_COND_VARIABLE:
01370       if (data >= OCV_END) return CMD_ERROR;
01371       break;
01372 
01373     case MOF_COND_COMPARATOR:
01374       if (data >= OCC_END) return CMD_ERROR;
01375       switch (order->GetConditionVariable()) {
01376         case OCV_UNCONDITIONALLY: return CMD_ERROR;
01377 
01378         case OCV_REQUIRES_SERVICE:
01379           if (data != OCC_IS_TRUE && data != OCC_IS_FALSE) return CMD_ERROR;
01380           break;
01381 
01382         default:
01383           if (data == OCC_IS_TRUE || data == OCC_IS_FALSE) return CMD_ERROR;
01384           break;
01385       }
01386       break;
01387 
01388     case MOF_COND_VALUE:
01389       switch (order->GetConditionVariable()) {
01390         case OCV_UNCONDITIONALLY: return CMD_ERROR;
01391 
01392         case OCV_LOAD_PERCENTAGE:
01393         case OCV_RELIABILITY:
01394           if (data > 100) return CMD_ERROR;
01395           break;
01396 
01397         default:
01398           if (data > 2047) return CMD_ERROR;
01399           break;
01400       }
01401       break;
01402 
01403     case MOF_COND_DESTINATION:
01404       if (data >= v->GetNumOrders()) return CMD_ERROR;
01405       break;
01406   }
01407 
01408   if (flags & DC_EXEC) {
01409     switch (mof) {
01410       case MOF_NON_STOP:
01411         order->SetNonStopType((OrderNonStopFlags)data);
01412         if (data & ONSF_NO_STOP_AT_DESTINATION_STATION) order->SetRefit(CT_NO_REFIT);
01413         break;
01414 
01415       case MOF_STOP_LOCATION:
01416         order->SetStopLocation((OrderStopLocation)data);
01417         break;
01418 
01419       case MOF_UNLOAD:
01420         order->SetUnloadType((OrderUnloadFlags)data);
01421         break;
01422 
01423       case MOF_LOAD:
01424         order->SetLoadType((OrderLoadFlags)data);
01425         if (data & OLFB_NO_LOAD) order->SetRefit(CT_NO_REFIT);
01426         break;
01427 
01428       case MOF_DEPOT_ACTION: {
01429         switch (data) {
01430           case DA_ALWAYS_GO:
01431             order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() & ~ODTFB_SERVICE));
01432             order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_HALT));
01433             break;
01434 
01435           case DA_SERVICE:
01436             order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() | ODTFB_SERVICE));
01437             order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_HALT));
01438             order->SetRefit(CT_NO_REFIT);
01439             break;
01440 
01441           case DA_STOP:
01442             order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() & ~ODTFB_SERVICE));
01443             order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() | ODATFB_HALT));
01444             order->SetRefit(CT_NO_REFIT);
01445             break;
01446 
01447           default:
01448             NOT_REACHED();
01449         }
01450         break;
01451       }
01452 
01453       case MOF_COND_VARIABLE: {
01454         order->SetConditionVariable((OrderConditionVariable)data);
01455 
01456         OrderConditionComparator occ = order->GetConditionComparator();
01457         switch (order->GetConditionVariable()) {
01458           case OCV_UNCONDITIONALLY:
01459             order->SetConditionComparator(OCC_EQUALS);
01460             order->SetConditionValue(0);
01461             break;
01462 
01463           case OCV_REQUIRES_SERVICE:
01464             if (occ != OCC_IS_TRUE && occ != OCC_IS_FALSE) order->SetConditionComparator(OCC_IS_TRUE);
01465             break;
01466 
01467           case OCV_LOAD_PERCENTAGE:
01468           case OCV_RELIABILITY:
01469             if (order->GetConditionValue() > 100) order->SetConditionValue(100);
01470             /* FALL THROUGH */
01471           default:
01472             if (occ == OCC_IS_TRUE || occ == OCC_IS_FALSE) order->SetConditionComparator(OCC_EQUALS);
01473             break;
01474         }
01475         break;
01476       }
01477 
01478       case MOF_COND_COMPARATOR:
01479         order->SetConditionComparator((OrderConditionComparator)data);
01480         break;
01481 
01482       case MOF_COND_VALUE:
01483         order->SetConditionValue(data);
01484         break;
01485 
01486       case MOF_COND_DESTINATION:
01487         order->SetConditionSkipToOrder(data);
01488         break;
01489 
01490       default: NOT_REACHED();
01491     }
01492 
01493     /* Update the windows and full load flags, also for vehicles that share the same order list */
01494     Vehicle *u = v->FirstShared();
01495     DeleteOrderWarnings(u);
01496     for (; u != NULL; u = u->NextShared()) {
01497       /* Toggle u->current_order "Full load" flag if it changed.
01498        * However, as the same flag is used for depot orders, check
01499        * whether we are not going to a depot as there are three
01500        * cases where the full load flag can be active and only
01501        * one case where the flag is used for depot orders. In the
01502        * other cases for the OrderTypeByte the flags are not used,
01503        * so do not care and those orders should not be active
01504        * when this function is called.
01505        */
01506       if (sel_ord == u->cur_real_order_index &&
01507           (u->current_order.IsType(OT_GOTO_STATION) || u->current_order.IsType(OT_LOADING)) &&
01508           u->current_order.GetLoadType() != order->GetLoadType()) {
01509         u->current_order.SetLoadType(order->GetLoadType());
01510       }
01511       InvalidateVehicleOrder(u, -2);
01512     }
01513   }
01514 
01515   return CommandCost();
01516 }
01517 
01529 CommandCost CmdCloneOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01530 {
01531   VehicleID veh_src = GB(p2, 0, 20);
01532   VehicleID veh_dst = GB(p1, 0, 20);
01533 
01534   Vehicle *dst = Vehicle::GetIfValid(veh_dst);
01535   if (dst == NULL || !dst->IsPrimaryVehicle()) return CMD_ERROR;
01536 
01537   CommandCost ret = CheckOwnership(dst->owner);
01538   if (ret.Failed()) return ret;
01539 
01540   switch (GB(p1, 30, 2)) {
01541     case CO_SHARE: {
01542       Vehicle *src = Vehicle::GetIfValid(veh_src);
01543 
01544       /* Sanity checks */
01545       if (src == NULL || !src->IsPrimaryVehicle() || dst->type != src->type || dst == src) return CMD_ERROR;
01546 
01547       CommandCost ret = CheckOwnership(src->owner);
01548       if (ret.Failed()) return ret;
01549 
01550       /* Trucks can't share orders with busses (and visa versa) */
01551       if (src->type == VEH_ROAD && RoadVehicle::From(src)->IsBus() != RoadVehicle::From(dst)->IsBus()) {
01552         return CMD_ERROR;
01553       }
01554 
01555       /* Is the vehicle already in the shared list? */
01556       if (src->FirstShared() == dst->FirstShared()) return CMD_ERROR;
01557 
01558       const Order *order;
01559 
01560       FOR_VEHICLE_ORDERS(src, order) {
01561         if (OrderGoesToStation(dst, order) &&
01562             !CanVehicleUseStation(dst, Station::Get(order->GetDestination()))) {
01563           return_cmd_error(STR_ERROR_CAN_T_COPY_SHARE_ORDER);
01564         }
01565       }
01566 
01567       if (src->orders.list == NULL && !OrderList::CanAllocateItem()) {
01568         return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
01569       }
01570 
01571       if (flags & DC_EXEC) {
01572         /* If the destination vehicle had a OrderList, destroy it.
01573          * We only reset the order indices, if the new orders are obviously different.
01574          * (We mainly do this to keep the order indices valid and in range.) */
01575         DeleteVehicleOrders(dst, false, dst->GetNumOrders() != src->GetNumOrders());
01576 
01577         dst->orders.list = src->orders.list;
01578 
01579         /* Link this vehicle in the shared-list */
01580         dst->AddToShared(src);
01581 
01582         InvalidateVehicleOrder(dst, -1);
01583         InvalidateVehicleOrder(src, -2);
01584 
01585         InvalidateWindowClassesData(GetWindowClassForVehicleType(dst->type), 0);
01586       }
01587       break;
01588     }
01589 
01590     case CO_COPY: {
01591       Vehicle *src = Vehicle::GetIfValid(veh_src);
01592 
01593       /* Sanity checks */
01594       if (src == NULL || !src->IsPrimaryVehicle() || dst->type != src->type || dst == src) return CMD_ERROR;
01595 
01596       CommandCost ret = CheckOwnership(src->owner);
01597       if (ret.Failed()) return ret;
01598 
01599       /* Trucks can't copy all the orders from busses (and visa versa),
01600        * and neither can helicopters and aircarft. */
01601       const Order *order;
01602       FOR_VEHICLE_ORDERS(src, order) {
01603         if (OrderGoesToStation(dst, order) &&
01604             !CanVehicleUseStation(dst, Station::Get(order->GetDestination()))) {
01605           return_cmd_error(STR_ERROR_CAN_T_COPY_SHARE_ORDER);
01606         }
01607       }
01608 
01609       /* make sure there are orders available */
01610       int delta = dst->IsOrderListShared() ? src->GetNumOrders() + 1 : src->GetNumOrders() - dst->GetNumOrders();
01611       if (!Order::CanAllocateItem(delta) ||
01612           ((dst->orders.list == NULL || dst->IsOrderListShared()) && !OrderList::CanAllocateItem())) {
01613         return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
01614       }
01615 
01616       if (flags & DC_EXEC) {
01617         const Order *order;
01618         Order *first = NULL;
01619         Order **order_dst;
01620 
01621         /* If the destination vehicle had an order list, destroy the chain but keep the OrderList.
01622          * We only reset the order indices, if the new orders are obviously different.
01623          * (We mainly do this to keep the order indices valid and in range.) */
01624         DeleteVehicleOrders(dst, true, dst->GetNumOrders() != src->GetNumOrders());
01625 
01626         order_dst = &first;
01627         FOR_VEHICLE_ORDERS(src, order) {
01628           *order_dst = new Order();
01629           (*order_dst)->AssignOrder(*order);
01630           order_dst = &(*order_dst)->next;
01631         }
01632         if (dst->orders.list == NULL) {
01633           dst->orders.list = new OrderList(first, dst);
01634         } else {
01635           assert(dst->orders.list->GetFirstOrder() == NULL);
01636           assert(!dst->orders.list->IsShared());
01637           delete dst->orders.list;
01638           assert(OrderList::CanAllocateItem());
01639           dst->orders.list = new OrderList(first, dst);
01640         }
01641 
01642         InvalidateVehicleOrder(dst, -1);
01643 
01644         InvalidateWindowClassesData(GetWindowClassForVehicleType(dst->type), 0);
01645       }
01646       break;
01647     }
01648 
01649     case CO_UNSHARE: return DecloneOrder(dst, flags);
01650     default: return CMD_ERROR;
01651   }
01652 
01653   return CommandCost();
01654 }
01655 
01668 CommandCost CmdOrderRefit(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01669 {
01670   VehicleID veh = GB(p1, 0, 20);
01671   VehicleOrderID order_number  = GB(p2, 16, 8);
01672   CargoID cargo = GB(p2, 0, 8);
01673   byte subtype  = GB(p2, 8, 8);
01674 
01675   if (cargo >= NUM_CARGO && cargo != CT_NO_REFIT && cargo != CT_AUTO_REFIT) return CMD_ERROR;
01676 
01677   const Vehicle *v = Vehicle::GetIfValid(veh);
01678   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
01679 
01680   CommandCost ret = CheckOwnership(v->owner);
01681   if (ret.Failed()) return ret;
01682 
01683   Order *order = v->GetOrder(order_number);
01684   if (order == NULL) return CMD_ERROR;
01685 
01686   /* Automatic refit cargo is only supported for goto station orders. */
01687   if (cargo == CT_AUTO_REFIT && !order->IsType(OT_GOTO_STATION)) return CMD_ERROR;
01688 
01689   if (flags & DC_EXEC) {
01690     order->SetRefit(cargo, subtype);
01691 
01692     /* Make the depot order an 'always go' order. */
01693     if (cargo != CT_NO_REFIT) {
01694       order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() & ~ODTFB_SERVICE));
01695       order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_HALT));
01696     }
01697 
01698     for (Vehicle *u = v->FirstShared(); u != NULL; u = u->NextShared()) {
01699       /* Update any possible open window of the vehicle */
01700       InvalidateVehicleOrder(u, -2);
01701 
01702       /* If the vehicle already got the current depot set as current order, then update current order as well */
01703       if (u->cur_real_order_index == order_number && (u->current_order.GetDepotOrderType() & ODTFB_PART_OF_ORDERS)) {
01704         u->current_order.SetRefit(cargo, subtype);
01705       }
01706     }
01707   }
01708 
01709   return CommandCost();
01710 }
01711 
01712 
01718 void CheckOrders(const Vehicle *v)
01719 {
01720   /* Does the user wants us to check things? */
01721   if (_settings_client.gui.order_review_system == 0) return;
01722 
01723   /* Do nothing for crashed vehicles */
01724   if (v->vehstatus & VS_CRASHED) return;
01725 
01726   /* Do nothing for stopped vehicles if setting is '1' */
01727   if (_settings_client.gui.order_review_system == 1 && (v->vehstatus & VS_STOPPED)) return;
01728 
01729   /* do nothing we we're not the first vehicle in a share-chain */
01730   if (v->FirstShared() != v) return;
01731 
01732   /* Only check every 20 days, so that we don't flood the message log */
01733   if (v->owner == _local_company && v->day_counter % 20 == 0) {
01734     int n_st, problem_type = -1;
01735     const Order *order;
01736     int message = 0;
01737 
01738     /* Check the order list */
01739     n_st = 0;
01740 
01741     FOR_VEHICLE_ORDERS(v, order) {
01742       /* Dummy order? */
01743       if (order->IsType(OT_DUMMY)) {
01744         problem_type = 1;
01745         break;
01746       }
01747       /* Does station have a load-bay for this vehicle? */
01748       if (order->IsType(OT_GOTO_STATION)) {
01749         const Station *st = Station::Get(order->GetDestination());
01750 
01751         n_st++;
01752         if (!CanVehicleUseStation(v, st)) problem_type = 3;
01753       }
01754     }
01755 
01756     /* Check if the last and the first order are the same */
01757     if (v->GetNumOrders() > 1) {
01758       const Order *last = v->GetLastOrder();
01759 
01760       if (v->orders.list->GetFirstOrder()->Equals(*last)) {
01761         problem_type = 2;
01762       }
01763     }
01764 
01765     /* Do we only have 1 station in our order list? */
01766     if (n_st < 2 && problem_type == -1) problem_type = 0;
01767 
01768 #ifndef NDEBUG
01769     if (v->orders.list != NULL) v->orders.list->DebugCheckSanity();
01770 #endif
01771 
01772     /* We don't have a problem */
01773     if (problem_type < 0) return;
01774 
01775     message = STR_NEWS_VEHICLE_HAS_TOO_FEW_ORDERS + problem_type;
01776     //DEBUG(misc, 3, "Triggered News Item for vehicle %d", v->index);
01777 
01778     SetDParam(0, v->index);
01779     AddVehicleNewsItem(
01780       message,
01781       NS_ADVICE,
01782       v->index
01783     );
01784   }
01785 }
01786 
01792 void RemoveOrderFromAllVehicles(OrderType type, DestinationID destination)
01793 {
01794   Vehicle *v;
01795 
01796   /* Aircraft have StationIDs for depot orders and never use DepotIDs
01797    * This fact is handled specially below
01798    */
01799 
01800   /* Go through all vehicles */
01801   FOR_ALL_VEHICLES(v) {
01802     Order *order;
01803 
01804     order = &v->current_order;
01805     if ((v->type == VEH_AIRCRAFT && order->IsType(OT_GOTO_DEPOT) ? OT_GOTO_STATION : order->GetType()) == type &&
01806         v->current_order.GetDestination() == destination) {
01807       order->MakeDummy();
01808       SetWindowDirty(WC_VEHICLE_VIEW, v->index);
01809     }
01810 
01811     /* Clear the order from the order-list */
01812     int id = -1;
01813     FOR_VEHICLE_ORDERS(v, order) {
01814       id++;
01815 restart:
01816 
01817       OrderType ot = order->GetType();
01818       if (ot == OT_GOTO_DEPOT && (order->GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0) continue;
01819       if (ot == OT_IMPLICIT || (v->type == VEH_AIRCRAFT && ot == OT_GOTO_DEPOT)) ot = OT_GOTO_STATION;
01820       if (ot == type && order->GetDestination() == destination) {
01821         /* We want to clear implicit orders, but we don't want to make them
01822          * dummy orders. They should just vanish. Also check the actual order
01823          * type as ot is currently OT_GOTO_STATION. */
01824         if (order->IsType(OT_IMPLICIT)) {
01825           order = order->next; // DeleteOrder() invalidates current order
01826           DeleteOrder(v, id);
01827           if (order != NULL) goto restart;
01828           break;
01829         }
01830 
01831         order->MakeDummy();
01832         for (const Vehicle *w = v->FirstShared(); w != NULL; w = w->NextShared()) {
01833           /* In GUI, simulate by removing the order and adding it back */
01834           InvalidateVehicleOrder(w, id | (INVALID_VEH_ORDER_ID << 8));
01835           InvalidateVehicleOrder(w, (INVALID_VEH_ORDER_ID << 8) | id);
01836         }
01837       }
01838     }
01839   }
01840 
01841   OrderBackup::RemoveOrder(type, destination);
01842 }
01843 
01848 bool Vehicle::HasDepotOrder() const
01849 {
01850   const Order *order;
01851 
01852   FOR_VEHICLE_ORDERS(this, order) {
01853     if (order->IsType(OT_GOTO_DEPOT)) return true;
01854   }
01855 
01856   return false;
01857 }
01858 
01868 void DeleteVehicleOrders(Vehicle *v, bool keep_orderlist, bool reset_order_indices)
01869 {
01870   DeleteOrderWarnings(v);
01871 
01872   if (v->IsOrderListShared()) {
01873     /* Remove ourself from the shared order list. */
01874     v->RemoveFromShared();
01875     v->orders.list = NULL;
01876   } else if (v->orders.list != NULL) {
01877     /* Remove the orders */
01878     v->orders.list->FreeChain(keep_orderlist);
01879     if (!keep_orderlist) v->orders.list = NULL;
01880   }
01881 
01882   if (reset_order_indices) {
01883     v->cur_implicit_order_index = v->cur_real_order_index = 0;
01884     if (v->current_order.IsType(OT_LOADING)) {
01885       CancelLoadingDueToDeletedOrder(v);
01886     }
01887   }
01888 }
01889 
01897 uint16 GetServiceIntervalClamped(uint interval, CompanyID company_id)
01898 {
01899   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);
01900 }
01901 
01910 static bool CheckForValidOrders(const Vehicle *v)
01911 {
01912   const Order *order;
01913 
01914   FOR_VEHICLE_ORDERS(v, order) {
01915     switch (order->GetType()) {
01916       case OT_GOTO_STATION:
01917       case OT_GOTO_DEPOT:
01918       case OT_GOTO_WAYPOINT:
01919         return true;
01920 
01921       default:
01922         break;
01923     }
01924   }
01925 
01926   return false;
01927 }
01928 
01932 static bool OrderConditionCompare(OrderConditionComparator occ, int variable, int value)
01933 {
01934   switch (occ) {
01935     case OCC_EQUALS:      return variable == value;
01936     case OCC_NOT_EQUALS:  return variable != value;
01937     case OCC_LESS_THAN:   return variable <  value;
01938     case OCC_LESS_EQUALS: return variable <= value;
01939     case OCC_MORE_THAN:   return variable >  value;
01940     case OCC_MORE_EQUALS: return variable >= value;
01941     case OCC_IS_TRUE:     return variable != 0;
01942     case OCC_IS_FALSE:    return variable == 0;
01943     default: NOT_REACHED();
01944   }
01945 }
01946 
01953 VehicleOrderID ProcessConditionalOrder(const Order *order, const Vehicle *v)
01954 {
01955   if (order->GetType() != OT_CONDITIONAL) return INVALID_VEH_ORDER_ID;
01956 
01957   bool skip_order = false;
01958   OrderConditionComparator occ = order->GetConditionComparator();
01959   uint16 value = order->GetConditionValue();
01960 
01961   switch (order->GetConditionVariable()) {
01962     case OCV_LOAD_PERCENTAGE:    skip_order = OrderConditionCompare(occ, CalcPercentVehicleFilled(v, NULL), value); break;
01963     case OCV_RELIABILITY:        skip_order = OrderConditionCompare(occ, ToPercent16(v->reliability),       value); break;
01964     case OCV_MAX_SPEED:          skip_order = OrderConditionCompare(occ, v->GetDisplayMaxSpeed() * 10 / 16, value); break;
01965     case OCV_AGE:                skip_order = OrderConditionCompare(occ, v->age / DAYS_IN_LEAP_YEAR,        value); break;
01966     case OCV_REQUIRES_SERVICE:   skip_order = OrderConditionCompare(occ, v->NeedsServicing(),               value); break;
01967     case OCV_UNCONDITIONALLY:    skip_order = true; break;
01968     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;
01969     default: NOT_REACHED();
01970   }
01971 
01972   return skip_order ? order->GetConditionSkipToOrder() : (VehicleOrderID)INVALID_VEH_ORDER_ID;
01973 }
01974 
01982 bool UpdateOrderDest(Vehicle *v, const Order *order, int conditional_depth, bool pbs_look_ahead)
01983 {
01984   if (conditional_depth > v->GetNumOrders()) return false;
01985 
01986   switch (order->GetType()) {
01987     case OT_GOTO_STATION:
01988       v->dest_tile = v->GetOrderStationLocation(order->GetDestination());
01989       return true;
01990 
01991     case OT_GOTO_DEPOT:
01992       if ((order->GetDepotOrderType() & ODTFB_SERVICE) && !v->NeedsServicing()) {
01993         assert(!pbs_look_ahead);
01994         UpdateVehicleTimetable(v, true);
01995         v->IncrementRealOrderIndex();
01996         break;
01997       }
01998 
01999       if (v->current_order.GetDepotActionType() & ODATFB_NEAREST_DEPOT) {
02000         /* We need to search for the nearest depot (hangar). */
02001         TileIndex location;
02002         DestinationID destination;
02003         bool reverse;
02004 
02005         if (v->FindClosestDepot(&location, &destination, &reverse)) {
02006           /* PBS reservations cannot reverse */
02007           if (pbs_look_ahead && reverse) return false;
02008 
02009           v->dest_tile = location;
02010           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());
02011 
02012           /* If there is no depot in front, reverse automatically (trains only) */
02013           if (v->type == VEH_TRAIN && reverse) DoCommand(v->tile, v->index, 0, DC_EXEC, CMD_REVERSE_TRAIN_DIRECTION);
02014 
02015           if (v->type == VEH_AIRCRAFT) {
02016             Aircraft *a = Aircraft::From(v);
02017             if (a->state == FLYING && a->targetairport != destination) {
02018               /* The aircraft is now heading for a different hangar than the next in the orders */
02019               extern void AircraftNextAirportPos_and_Order(Aircraft *a);
02020               AircraftNextAirportPos_and_Order(a);
02021             }
02022           }
02023           return true;
02024         }
02025 
02026         /* If there is no depot, we cannot help PBS either. */
02027         if (pbs_look_ahead) return false;
02028 
02029         UpdateVehicleTimetable(v, true);
02030         v->IncrementRealOrderIndex();
02031       } else {
02032         if (v->type != VEH_AIRCRAFT) {
02033           v->dest_tile = Depot::Get(order->GetDestination())->xy;
02034         }
02035         return true;
02036       }
02037       break;
02038 
02039     case OT_GOTO_WAYPOINT:
02040       v->dest_tile = Waypoint::Get(order->GetDestination())->xy;
02041       return true;
02042 
02043     case OT_CONDITIONAL: {
02044       assert(!pbs_look_ahead);
02045       VehicleOrderID next_order = ProcessConditionalOrder(order, v);
02046       if (next_order != INVALID_VEH_ORDER_ID) {
02047         /* Jump to next_order. cur_implicit_order_index becomes exactly that order,
02048          * cur_real_order_index might come after next_order. */
02049         UpdateVehicleTimetable(v, false);
02050         v->cur_implicit_order_index = v->cur_real_order_index = next_order;
02051         v->UpdateRealOrderIndex();
02052         v->current_order_time += v->GetOrder(v->cur_real_order_index)->travel_time;
02053 
02054         /* Disable creation of implicit orders.
02055          * When inserting them we do not know that we would have to make the conditional orders point to them. */
02056         if (v->IsGroundVehicle()) {
02057           uint16 &gv_flags = v->GetGroundVehicleFlags();
02058           SetBit(gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS);
02059         }
02060       } else {
02061         UpdateVehicleTimetable(v, true);
02062         v->IncrementRealOrderIndex();
02063       }
02064       break;
02065     }
02066 
02067     default:
02068       v->dest_tile = 0;
02069       return false;
02070   }
02071 
02072   assert(v->cur_implicit_order_index < v->GetNumOrders());
02073   assert(v->cur_real_order_index < v->GetNumOrders());
02074 
02075   /* Get the current order */
02076   order = v->GetOrder(v->cur_real_order_index);
02077   if (order != NULL && order->IsType(OT_IMPLICIT)) {
02078     assert(v->GetNumManualOrders() == 0);
02079     order = NULL;
02080   }
02081 
02082   if (order == NULL) {
02083     v->current_order.Free();
02084     v->dest_tile = 0;
02085     return false;
02086   }
02087 
02088   v->current_order = *order;
02089   return UpdateOrderDest(v, order, conditional_depth + 1, pbs_look_ahead);
02090 }
02091 
02099 bool ProcessOrders(Vehicle *v)
02100 {
02101   switch (v->current_order.GetType()) {
02102     case OT_GOTO_DEPOT:
02103       /* Let a depot order in the orderlist interrupt. */
02104       if (!(v->current_order.GetDepotOrderType() & ODTFB_PART_OF_ORDERS)) return false;
02105       break;
02106 
02107     case OT_LOADING:
02108       return false;
02109 
02110     case OT_LEAVESTATION:
02111       if (v->type != VEH_AIRCRAFT) return false;
02112       break;
02113 
02114     default: break;
02115   }
02116 
02124   bool may_reverse = v->current_order.IsType(OT_NOTHING);
02125 
02126   /* Check if we've reached a 'via' destination. */
02127   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)) &&
02128       IsTileType(v->tile, MP_STATION) &&
02129       v->current_order.GetDestination() == GetStationIndex(v->tile)) {
02130     v->DeleteUnreachedImplicitOrders();
02131     /* We set the last visited station here because we do not want
02132      * the train to stop at this 'via' station if the next order
02133      * is a no-non-stop order; in that case not setting the last
02134      * visited station will cause the vehicle to still stop. */
02135     v->last_station_visited = v->current_order.GetDestination();
02136     UpdateVehicleTimetable(v, true);
02137     v->IncrementImplicitOrderIndex();
02138   }
02139 
02140   /* Get the current order */
02141   assert(v->cur_implicit_order_index == 0 || v->cur_implicit_order_index < v->GetNumOrders());
02142   v->UpdateRealOrderIndex();
02143 
02144   const Order *order = v->GetOrder(v->cur_real_order_index);
02145   if (order != NULL && order->IsType(OT_IMPLICIT)) {
02146     assert(v->GetNumManualOrders() == 0);
02147     order = NULL;
02148   }
02149 
02150   /* If no order, do nothing. */
02151   if (order == NULL || (v->type == VEH_AIRCRAFT && !CheckForValidOrders(v))) {
02152     if (v->type == VEH_AIRCRAFT) {
02153       /* Aircraft do something vastly different here, so handle separately */
02154       extern void HandleMissingAircraftOrders(Aircraft *v);
02155       HandleMissingAircraftOrders(Aircraft::From(v));
02156       return false;
02157     }
02158 
02159     v->current_order.Free();
02160     v->dest_tile = 0;
02161     return false;
02162   }
02163 
02164   /* If it is unchanged, keep it. */
02165   if (order->Equals(v->current_order) && (v->type == VEH_AIRCRAFT || v->dest_tile != 0) &&
02166       (v->type != VEH_SHIP || !order->IsType(OT_GOTO_STATION) || Station::Get(order->GetDestination())->dock_tile != INVALID_TILE)) {
02167     return false;
02168   }
02169 
02170   /* Otherwise set it, and determine the destination tile. */
02171   v->current_order = *order;
02172 
02173   InvalidateVehicleOrder(v, -2);
02174   switch (v->type) {
02175     default:
02176       NOT_REACHED();
02177 
02178     case VEH_ROAD:
02179     case VEH_TRAIN:
02180       break;
02181 
02182     case VEH_AIRCRAFT:
02183     case VEH_SHIP:
02184       SetWindowClassesDirty(GetWindowClassForVehicleType(v->type));
02185       break;
02186   }
02187 
02188   return UpdateOrderDest(v, order) && may_reverse;
02189 }
02190 
02198 bool Order::ShouldStopAtStation(const Vehicle *v, StationID station) const
02199 {
02200   bool is_dest_station = this->IsType(OT_GOTO_STATION) && this->dest == station;
02201 
02202   return (!this->IsType(OT_GOTO_DEPOT) || (this->GetDepotOrderType() & ODTFB_PART_OF_ORDERS) != 0) &&
02203       v->last_station_visited != station && // Do stop only when we've not just been there
02204       /* Finally do stop when there is no non-stop flag set for this type of station. */
02205       !(this->GetNonStopType() & (is_dest_station ? ONSF_NO_STOP_AT_DESTINATION_STATION : ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS));
02206 }
02207 
02208 bool Order::CanLoadOrUnload() const
02209 {
02210   return (this->IsType(OT_GOTO_STATION) || this->IsType(OT_IMPLICIT)) &&
02211       (this->GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION) == 0 &&
02212       ((this->GetLoadType() & OLFB_NO_LOAD) == 0 ||
02213       (this->GetUnloadType() & OUFB_NO_UNLOAD) == 0);
02214 }
02215 
02222 bool Order::CanLeaveWithCargo(bool has_cargo) const
02223 {
02224   return (this->GetLoadType() & OLFB_NO_LOAD) == 0 || (has_cargo &&
02225       (this->GetUnloadType() & (OUFB_UNLOAD | OUFB_TRANSFER)) == 0);
02226 }