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        */
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 
00695 TileIndex Order::GetLocation(const Vehicle *v, bool airport) const
00696 {
00697   switch (this->GetType()) {
00698     case OT_GOTO_WAYPOINT:
00699     case OT_GOTO_STATION:
00700     case OT_IMPLICIT:
00701       if (airport && v->type == VEH_AIRCRAFT) return Station::Get(this->GetDestination())->airport.tile;
00702       return BaseStation::Get(this->GetDestination())->xy;
00703 
00704     case OT_GOTO_DEPOT:
00705       if ((this->GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0) return INVALID_TILE;
00706       return (v->type == VEH_AIRCRAFT) ? Station::Get(this->GetDestination())->xy : Depot::Get(this->GetDestination())->xy;
00707 
00708     default:
00709       return INVALID_TILE;
00710   }
00711 }
00712 
00722 uint GetOrderDistance(const Order *prev, const Order *cur, const Vehicle *v, int conditional_depth)
00723 {
00724   if (cur->IsType(OT_CONDITIONAL)) {
00725     if (conditional_depth > v->GetNumOrders()) return 0;
00726 
00727     conditional_depth++;
00728 
00729     int dist1 = GetOrderDistance(prev, v->GetOrder(cur->GetConditionSkipToOrder()), v, conditional_depth);
00730     int dist2 = GetOrderDistance(prev, cur->next == NULL ? v->orders.list->GetFirstOrder() : cur->next, v, conditional_depth);
00731     return max(dist1, dist2);
00732   }
00733 
00734   TileIndex prev_tile = prev->GetLocation(v, true);
00735   TileIndex cur_tile = cur->GetLocation(v, true);
00736   if (prev_tile == INVALID_TILE || cur_tile == INVALID_TILE) return 0;
00737   return v->type == VEH_AIRCRAFT ? DistanceSquare(prev_tile, cur_tile) : DistanceManhattan(prev_tile, cur_tile);
00738 }
00739 
00753 CommandCost CmdInsertOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00754 {
00755   VehicleID veh          = GB(p1,  0, 20);
00756   VehicleOrderID sel_ord = GB(p1, 20, 8);
00757   Order new_order(p2);
00758 
00759   Vehicle *v = Vehicle::GetIfValid(veh);
00760   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
00761 
00762   CommandCost ret = CheckOwnership(v->owner);
00763   if (ret.Failed()) return ret;
00764 
00765   /* Check if the inserted order is to the correct destination (owner, type),
00766    * and has the correct flags if any */
00767   switch (new_order.GetType()) {
00768     case OT_GOTO_STATION: {
00769       const Station *st = Station::GetIfValid(new_order.GetDestination());
00770       if (st == NULL) return CMD_ERROR;
00771 
00772       if (st->owner != OWNER_NONE) {
00773         CommandCost ret = CheckOwnership(st->owner);
00774         if (ret.Failed()) return ret;
00775       }
00776 
00777       if (!CanVehicleUseStation(v, st)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER);
00778       for (Vehicle *u = v->FirstShared(); u != NULL; u = u->NextShared()) {
00779         if (!CanVehicleUseStation(u, st)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER_SHARED);
00780       }
00781 
00782       /* Non stop only allowed for ground vehicles. */
00783       if (new_order.GetNonStopType() != ONSF_STOP_EVERYWHERE && !v->IsGroundVehicle()) return CMD_ERROR;
00784 
00785       /* Filter invalid load/unload types. */
00786       switch (new_order.GetLoadType()) {
00787         case OLF_LOAD_IF_POSSIBLE: case OLFB_FULL_LOAD: case OLF_FULL_LOAD_ANY: case OLFB_NO_LOAD: break;
00788         default: return CMD_ERROR;
00789       }
00790       switch (new_order.GetUnloadType()) {
00791         case OUF_UNLOAD_IF_POSSIBLE: case OUFB_UNLOAD: case OUFB_TRANSFER: case OUFB_NO_UNLOAD: break;
00792         default: return CMD_ERROR;
00793       }
00794 
00795       /* Filter invalid stop locations */
00796       switch (new_order.GetStopLocation()) {
00797         case OSL_PLATFORM_NEAR_END:
00798         case OSL_PLATFORM_MIDDLE:
00799           if (v->type != VEH_TRAIN) return CMD_ERROR;
00800           /* FALL THROUGH */
00801         case OSL_PLATFORM_FAR_END:
00802           break;
00803 
00804         default:
00805           return CMD_ERROR;
00806       }
00807 
00808       break;
00809     }
00810 
00811     case OT_GOTO_DEPOT: {
00812       if ((new_order.GetDepotActionType() & ODATFB_NEAREST_DEPOT) == 0) {
00813         if (v->type == VEH_AIRCRAFT) {
00814           const Station *st = Station::GetIfValid(new_order.GetDestination());
00815 
00816           if (st == NULL) return CMD_ERROR;
00817 
00818           CommandCost ret = CheckOwnership(st->owner);
00819           if (ret.Failed()) return ret;
00820 
00821           if (!CanVehicleUseStation(v, st) || !st->airport.HasHangar()) {
00822             return CMD_ERROR;
00823           }
00824         } else {
00825           const Depot *dp = Depot::GetIfValid(new_order.GetDestination());
00826 
00827           if (dp == NULL) return CMD_ERROR;
00828 
00829           CommandCost ret = CheckOwnership(GetTileOwner(dp->xy));
00830           if (ret.Failed()) return ret;
00831 
00832           switch (v->type) {
00833             case VEH_TRAIN:
00834               if (!IsRailDepotTile(dp->xy)) return CMD_ERROR;
00835               break;
00836 
00837             case VEH_ROAD:
00838               if (!IsRoadDepotTile(dp->xy)) return CMD_ERROR;
00839               break;
00840 
00841             case VEH_SHIP:
00842               if (!IsShipDepotTile(dp->xy)) return CMD_ERROR;
00843               break;
00844 
00845             default: return CMD_ERROR;
00846           }
00847         }
00848       }
00849 
00850       if (new_order.GetNonStopType() != ONSF_STOP_EVERYWHERE && !v->IsGroundVehicle()) return CMD_ERROR;
00851       if (new_order.GetDepotOrderType() & ~(ODTFB_PART_OF_ORDERS | ((new_order.GetDepotOrderType() & ODTFB_PART_OF_ORDERS) != 0 ? ODTFB_SERVICE : 0))) return CMD_ERROR;
00852       if (new_order.GetDepotActionType() & ~(ODATFB_HALT | ODATFB_NEAREST_DEPOT)) return CMD_ERROR;
00853       if ((new_order.GetDepotOrderType() & ODTFB_SERVICE) && (new_order.GetDepotActionType() & ODATFB_HALT)) return CMD_ERROR;
00854       break;
00855     }
00856 
00857     case OT_GOTO_WAYPOINT: {
00858       const Waypoint *wp = Waypoint::GetIfValid(new_order.GetDestination());
00859       if (wp == NULL) return CMD_ERROR;
00860 
00861       switch (v->type) {
00862         default: return CMD_ERROR;
00863 
00864         case VEH_TRAIN: {
00865           if (!(wp->facilities & FACIL_TRAIN)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER);
00866 
00867           CommandCost ret = CheckOwnership(wp->owner);
00868           if (ret.Failed()) return ret;
00869           break;
00870         }
00871 
00872         case VEH_SHIP:
00873           if (!(wp->facilities & FACIL_DOCK)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER);
00874           if (wp->owner != OWNER_NONE) {
00875             CommandCost ret = CheckOwnership(wp->owner);
00876             if (ret.Failed()) return ret;
00877           }
00878           break;
00879       }
00880 
00881       /* Order flags can be any of the following for waypoints:
00882        * [non-stop]
00883        * non-stop orders (if any) are only valid for trains */
00884       if (new_order.GetNonStopType() != ONSF_STOP_EVERYWHERE && v->type != VEH_TRAIN) return CMD_ERROR;
00885       break;
00886     }
00887 
00888     case OT_CONDITIONAL: {
00889       VehicleOrderID skip_to = new_order.GetConditionSkipToOrder();
00890       if (skip_to != 0 && skip_to >= v->GetNumOrders()) return CMD_ERROR; // Always allow jumping to the first (even when there is no order).
00891       if (new_order.GetConditionVariable() >= OCV_END) return CMD_ERROR;
00892 
00893       OrderConditionComparator occ = new_order.GetConditionComparator();
00894       if (occ >= OCC_END) return CMD_ERROR;
00895       switch (new_order.GetConditionVariable()) {
00896         case OCV_REQUIRES_SERVICE:
00897           if (occ != OCC_IS_TRUE && occ != OCC_IS_FALSE) return CMD_ERROR;
00898           break;
00899 
00900         case OCV_UNCONDITIONALLY:
00901           if (occ != OCC_EQUALS) return CMD_ERROR;
00902           if (new_order.GetConditionValue() != 0) return CMD_ERROR;
00903           break;
00904 
00905         case OCV_LOAD_PERCENTAGE:
00906         case OCV_RELIABILITY:
00907           if (new_order.GetConditionValue() > 100) return CMD_ERROR;
00908           /* FALL THROUGH */
00909         default:
00910           if (occ == OCC_IS_TRUE || occ == OCC_IS_FALSE) return CMD_ERROR;
00911           break;
00912       }
00913       break;
00914     }
00915 
00916     default: return CMD_ERROR;
00917   }
00918 
00919   if (sel_ord > v->GetNumOrders()) return CMD_ERROR;
00920 
00921   if (v->GetNumOrders() >= MAX_VEH_ORDER_ID) return_cmd_error(STR_ERROR_TOO_MANY_ORDERS);
00922   if (!Order::CanAllocateItem()) return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
00923   if (v->orders.list == NULL && !OrderList::CanAllocateItem()) return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
00924 
00925   if (v->type == VEH_SHIP && _settings_game.pf.pathfinder_for_ships != VPF_NPF) {
00926     /* Make sure the new destination is not too far away from the previous */
00927     const Order *prev = NULL;
00928     uint n = 0;
00929 
00930     /* Find the last goto station or depot order before the insert location.
00931      * If the order is to be inserted at the beginning of the order list this
00932      * finds the last order in the list. */
00933     const Order *o;
00934     FOR_VEHICLE_ORDERS(v, o) {
00935       switch (o->GetType()) {
00936         case OT_GOTO_STATION:
00937         case OT_GOTO_DEPOT:
00938         case OT_GOTO_WAYPOINT:
00939           prev = o;
00940           break;
00941 
00942         default: break;
00943       }
00944       if (++n == sel_ord && prev != NULL) break;
00945     }
00946     if (prev != NULL) {
00947       uint dist;
00948       if (new_order.IsType(OT_CONDITIONAL)) {
00949         /* The order is not yet inserted, so we have to do the first iteration here. */
00950         dist = GetOrderDistance(prev, v->GetOrder(new_order.GetConditionSkipToOrder()), v);
00951       } else {
00952         dist = GetOrderDistance(prev, &new_order, v);
00953       }
00954 
00955       if (dist >= 130) {
00956         return_cmd_error(STR_ERROR_TOO_FAR_FROM_PREVIOUS_DESTINATION);
00957       }
00958     }
00959   }
00960 
00961   if (flags & DC_EXEC) {
00962     Order *new_o = new Order();
00963     new_o->AssignOrder(new_order);
00964     InsertOrder(v, new_o, sel_ord);
00965   }
00966 
00967   return CommandCost();
00968 }
00969 
00976 void InsertOrder(Vehicle *v, Order *new_o, VehicleOrderID sel_ord)
00977 {
00978   /* Create new order and link in list */
00979   if (v->orders.list == NULL) {
00980     v->orders.list = new OrderList(new_o, v);
00981   } else {
00982     v->orders.list->InsertOrderAt(new_o, sel_ord);
00983   }
00984 
00985   Vehicle *u = v->FirstShared();
00986   DeleteOrderWarnings(u);
00987   for (; u != NULL; u = u->NextShared()) {
00988     assert(v->orders.list == u->orders.list);
00989 
00990     /* If there is added an order before the current one, we need
00991      * to update the selected order. We do not change implicit/real order indices though.
00992      * If the new order is between the current implicit order and real order, the implicit order will
00993      * later skip the inserted order. */
00994     if (sel_ord <= u->cur_real_order_index) {
00995       uint cur = u->cur_real_order_index + 1;
00996       /* Check if we don't go out of bound */
00997       if (cur < u->GetNumOrders()) {
00998         u->cur_real_order_index = cur;
00999       }
01000     }
01001     if (sel_ord == u->cur_implicit_order_index && u->IsGroundVehicle()) {
01002       /* We are inserting an order just before the current implicit order.
01003        * We do not know whether we will reach current implicit or the newly inserted order first.
01004        * So, disable creation of implicit orders until we are on track again. */
01005       uint16 &gv_flags = u->GetGroundVehicleFlags();
01006       SetBit(gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS);
01007     }
01008     if (sel_ord <= u->cur_implicit_order_index) {
01009       uint cur = u->cur_implicit_order_index + 1;
01010       /* Check if we don't go out of bound */
01011       if (cur < u->GetNumOrders()) {
01012         u->cur_implicit_order_index = cur;
01013       }
01014     }
01015     /* Update any possible open window of the vehicle */
01016     InvalidateVehicleOrder(u, INVALID_VEH_ORDER_ID | (sel_ord << 8));
01017   }
01018 
01019   /* As we insert an order, the order to skip to will be 'wrong'. */
01020   VehicleOrderID cur_order_id = 0;
01021   Order *order;
01022   FOR_VEHICLE_ORDERS(v, order) {
01023     if (order->IsType(OT_CONDITIONAL)) {
01024       VehicleOrderID order_id = order->GetConditionSkipToOrder();
01025       if (order_id >= sel_ord) {
01026         order->SetConditionSkipToOrder(order_id + 1);
01027       }
01028       if (order_id == cur_order_id) {
01029         order->SetConditionSkipToOrder((order_id + 1) % v->GetNumOrders());
01030       }
01031     }
01032     cur_order_id++;
01033   }
01034 
01035   /* Make sure to rebuild the whole list */
01036   InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
01037 }
01038 
01044 static CommandCost DecloneOrder(Vehicle *dst, DoCommandFlag flags)
01045 {
01046   if (flags & DC_EXEC) {
01047     DeleteVehicleOrders(dst);
01048     InvalidateVehicleOrder(dst, -1);
01049 
01050     InvalidateWindowClassesData(GetWindowClassForVehicleType(dst->type), 0);
01051   }
01052   return CommandCost();
01053 }
01054 
01064 CommandCost CmdDeleteOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01065 {
01066   VehicleID veh_id = GB(p1, 0, 20);
01067   VehicleOrderID sel_ord = GB(p2, 0, 8);
01068 
01069   Vehicle *v = Vehicle::GetIfValid(veh_id);
01070 
01071   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
01072 
01073   CommandCost ret = CheckOwnership(v->owner);
01074   if (ret.Failed()) return ret;
01075 
01076   /* If we did not select an order, we maybe want to de-clone the orders */
01077   if (sel_ord >= v->GetNumOrders()) return DecloneOrder(v, flags);
01078 
01079   if (v->GetOrder(sel_ord) == NULL) return CMD_ERROR;
01080 
01081   if (flags & DC_EXEC) DeleteOrder(v, sel_ord);
01082   return CommandCost();
01083 }
01084 
01089 static void CancelLoadingDueToDeletedOrder(Vehicle *v)
01090 {
01091   assert(v->current_order.IsType(OT_LOADING));
01092   /* NON-stop flag is misused to see if a train is in a station that is
01093    * on his order list or not */
01094   v->current_order.SetNonStopType(ONSF_STOP_EVERYWHERE);
01095   /* When full loading, "cancel" that order so the vehicle doesn't
01096    * stay indefinitely at this station anymore. */
01097   if (v->current_order.GetLoadType() & OLFB_FULL_LOAD) v->current_order.SetLoadType(OLF_LOAD_IF_POSSIBLE);
01098 }
01099 
01105 void DeleteOrder(Vehicle *v, VehicleOrderID sel_ord)
01106 {
01107   v->orders.list->DeleteOrderAt(sel_ord);
01108 
01109   Vehicle *u = v->FirstShared();
01110   DeleteOrderWarnings(u);
01111   for (; u != NULL; u = u->NextShared()) {
01112     assert(v->orders.list == u->orders.list);
01113 
01114     if (sel_ord == u->cur_real_order_index && u->current_order.IsType(OT_LOADING)) {
01115       CancelLoadingDueToDeletedOrder(u);
01116     }
01117 
01118     if (sel_ord < u->cur_real_order_index) {
01119       u->cur_real_order_index--;
01120     } else if (sel_ord == u->cur_real_order_index) {
01121       u->UpdateRealOrderIndex();
01122     }
01123 
01124     if (sel_ord < u->cur_implicit_order_index) {
01125       u->cur_implicit_order_index--;
01126     } else if (sel_ord == u->cur_implicit_order_index) {
01127       /* Make sure the index is valid */
01128       if (u->cur_implicit_order_index >= u->GetNumOrders()) u->cur_implicit_order_index = 0;
01129 
01130       /* Skip non-implicit orders for the implicit-order-index (e.g. if the current implicit order was deleted */
01131       while (u->cur_implicit_order_index != u->cur_real_order_index && !u->GetOrder(u->cur_implicit_order_index)->IsType(OT_IMPLICIT)) {
01132         u->cur_implicit_order_index++;
01133         if (u->cur_implicit_order_index >= u->GetNumOrders()) u->cur_implicit_order_index = 0;
01134       }
01135     }
01136 
01137     /* Update any possible open window of the vehicle */
01138     InvalidateVehicleOrder(u, sel_ord | (INVALID_VEH_ORDER_ID << 8));
01139   }
01140 
01141   /* As we delete an order, the order to skip to will be 'wrong'. */
01142   VehicleOrderID cur_order_id = 0;
01143   Order *order = NULL;
01144   FOR_VEHICLE_ORDERS(v, order) {
01145     if (order->IsType(OT_CONDITIONAL)) {
01146       VehicleOrderID order_id = order->GetConditionSkipToOrder();
01147       if (order_id >= sel_ord) {
01148         order_id = max(order_id - 1, 0);
01149       }
01150       if (order_id == cur_order_id) {
01151         order_id = (order_id + 1) % v->GetNumOrders();
01152       }
01153       order->SetConditionSkipToOrder(order_id);
01154     }
01155     cur_order_id++;
01156   }
01157 
01158   InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
01159 }
01160 
01170 CommandCost CmdSkipToOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01171 {
01172   VehicleID veh_id = GB(p1, 0, 20);
01173   VehicleOrderID sel_ord = GB(p2, 0, 8);
01174 
01175   Vehicle *v = Vehicle::GetIfValid(veh_id);
01176 
01177   if (v == NULL || !v->IsPrimaryVehicle() || sel_ord == v->cur_implicit_order_index || sel_ord >= v->GetNumOrders() || v->GetNumOrders() < 2) return CMD_ERROR;
01178 
01179   CommandCost ret = CheckOwnership(v->owner);
01180   if (ret.Failed()) return ret;
01181 
01182   if (flags & DC_EXEC) {
01183     if (v->current_order.IsType(OT_LOADING)) v->LeaveStation();
01184 
01185     v->cur_implicit_order_index = v->cur_real_order_index = sel_ord;
01186     v->UpdateRealOrderIndex();
01187 
01188     InvalidateVehicleOrder(v, -2);
01189   }
01190 
01191   /* We have an aircraft/ship, they have a mini-schedule, so update them all */
01192   if (v->type == VEH_AIRCRAFT) SetWindowClassesDirty(WC_AIRCRAFT_LIST);
01193   if (v->type == VEH_SHIP) SetWindowClassesDirty(WC_SHIPS_LIST);
01194 
01195   return CommandCost();
01196 }
01197 
01211 CommandCost CmdMoveOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01212 {
01213   VehicleID veh = GB(p1, 0, 20);
01214   VehicleOrderID moving_order = GB(p2,  0, 16);
01215   VehicleOrderID target_order = GB(p2, 16, 16);
01216 
01217   Vehicle *v = Vehicle::GetIfValid(veh);
01218   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
01219 
01220   CommandCost ret = CheckOwnership(v->owner);
01221   if (ret.Failed()) return ret;
01222 
01223   /* Don't make senseless movements */
01224   if (moving_order >= v->GetNumOrders() || target_order >= v->GetNumOrders() ||
01225       moving_order == target_order || v->GetNumOrders() <= 1) return CMD_ERROR;
01226 
01227   Order *moving_one = v->GetOrder(moving_order);
01228   /* Don't move an empty order */
01229   if (moving_one == NULL) return CMD_ERROR;
01230 
01231   if (flags & DC_EXEC) {
01232     v->orders.list->MoveOrder(moving_order, target_order);
01233 
01234     /* Update shared list */
01235     Vehicle *u = v->FirstShared();
01236 
01237     DeleteOrderWarnings(u);
01238 
01239     for (; u != NULL; u = u->NextShared()) {
01240       /* Update the current order.
01241        * There are multiple ways to move orders, which result in cur_implicit_order_index
01242        * and cur_real_order_index to not longer make any sense. E.g. moving another
01243        * real order between them.
01244        *
01245        * Basically one could choose to preserve either of them, but not both.
01246        * While both ways are suitable in this or that case from a human point of view, neither
01247        * of them makes really sense.
01248        * However, from an AI point of view, preserving cur_real_order_index is the most
01249        * predictable and transparent behaviour.
01250        *
01251        * With that decision it basically does not matter what we do to cur_implicit_order_index.
01252        * If we change orders between the implict- and real-index, the implicit orders are mostly likely
01253        * completely out-dated anyway. So, keep it simple and just keep cur_implicit_order_index as well.
01254        * The worst which can happen is that a lot of implicit orders are removed when reaching current_order.
01255        */
01256       if (u->cur_real_order_index == moving_order) {
01257         u->cur_real_order_index = target_order;
01258       } else if (u->cur_real_order_index > moving_order && u->cur_real_order_index <= target_order) {
01259         u->cur_real_order_index--;
01260       } else if (u->cur_real_order_index < moving_order && u->cur_real_order_index >= target_order) {
01261         u->cur_real_order_index++;
01262       }
01263 
01264       if (u->cur_implicit_order_index == moving_order) {
01265         u->cur_implicit_order_index = target_order;
01266       } else if (u->cur_implicit_order_index > moving_order && u->cur_implicit_order_index <= target_order) {
01267         u->cur_implicit_order_index--;
01268       } else if (u->cur_implicit_order_index < moving_order && u->cur_implicit_order_index >= target_order) {
01269         u->cur_implicit_order_index++;
01270       }
01271 
01272       assert(v->orders.list == u->orders.list);
01273       /* Update any possible open window of the vehicle */
01274       InvalidateVehicleOrder(u, moving_order | (target_order << 8));
01275     }
01276 
01277     /* As we move an order, the order to skip to will be 'wrong'. */
01278     Order *order;
01279     FOR_VEHICLE_ORDERS(v, order) {
01280       if (order->IsType(OT_CONDITIONAL)) {
01281         VehicleOrderID order_id = order->GetConditionSkipToOrder();
01282         if (order_id == moving_order) {
01283           order_id = target_order;
01284         } else if (order_id > moving_order && order_id <= target_order) {
01285           order_id--;
01286         } else if (order_id < moving_order && order_id >= target_order) {
01287           order_id++;
01288         }
01289         order->SetConditionSkipToOrder(order_id);
01290       }
01291     }
01292 
01293     /* Make sure to rebuild the whole list */
01294     InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
01295   }
01296 
01297   return CommandCost();
01298 }
01299 
01315 CommandCost CmdModifyOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01316 {
01317   VehicleOrderID sel_ord = GB(p1, 20,  8);
01318   VehicleID veh          = GB(p1,  0, 20);
01319   ModifyOrderFlags mof   = Extract<ModifyOrderFlags, 0, 4>(p2);
01320   uint16 data            = GB(p2,  4, 11);
01321 
01322   if (mof >= MOF_END) return CMD_ERROR;
01323 
01324   Vehicle *v = Vehicle::GetIfValid(veh);
01325   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
01326 
01327   CommandCost ret = CheckOwnership(v->owner);
01328   if (ret.Failed()) return ret;
01329 
01330   /* Is it a valid order? */
01331   if (sel_ord >= v->GetNumOrders()) return CMD_ERROR;
01332 
01333   Order *order = v->GetOrder(sel_ord);
01334   switch (order->GetType()) {
01335     case OT_GOTO_STATION:
01336       if (mof == MOF_COND_VARIABLE || mof == MOF_COND_COMPARATOR || mof == MOF_DEPOT_ACTION || mof == MOF_COND_VALUE) return CMD_ERROR;
01337       break;
01338 
01339     case OT_GOTO_DEPOT:
01340       if (mof != MOF_NON_STOP && mof != MOF_DEPOT_ACTION) return CMD_ERROR;
01341       break;
01342 
01343     case OT_GOTO_WAYPOINT:
01344       if (mof != MOF_NON_STOP) return CMD_ERROR;
01345       break;
01346 
01347     case OT_CONDITIONAL:
01348       if (mof != MOF_COND_VARIABLE && mof != MOF_COND_COMPARATOR && mof != MOF_COND_VALUE && mof != MOF_COND_DESTINATION) return CMD_ERROR;
01349       break;
01350 
01351     default:
01352       return CMD_ERROR;
01353   }
01354 
01355   switch (mof) {
01356     default: NOT_REACHED();
01357 
01358     case MOF_NON_STOP:
01359       if (!v->IsGroundVehicle()) return CMD_ERROR;
01360       if (data >= ONSF_END) return CMD_ERROR;
01361       if (data == order->GetNonStopType()) return CMD_ERROR;
01362       break;
01363 
01364     case MOF_STOP_LOCATION:
01365       if (v->type != VEH_TRAIN) return CMD_ERROR;
01366       if (data >= OSL_END) return CMD_ERROR;
01367       break;
01368 
01369     case MOF_UNLOAD:
01370       if ((data & ~(OUFB_UNLOAD | OUFB_TRANSFER | OUFB_NO_UNLOAD)) != 0) return CMD_ERROR;
01371       /* Unload and no-unload are mutual exclusive and so are transfer and no unload. */
01372       if (data != 0 && ((data & (OUFB_UNLOAD | OUFB_TRANSFER)) != 0) == ((data & OUFB_NO_UNLOAD) != 0)) return CMD_ERROR;
01373       if (data == order->GetUnloadType()) return CMD_ERROR;
01374       break;
01375 
01376     case MOF_LOAD:
01377       if (data > OLFB_NO_LOAD || data == 1) return CMD_ERROR;
01378       if (data == order->GetLoadType()) return CMD_ERROR;
01379       break;
01380 
01381     case MOF_DEPOT_ACTION:
01382       if (data >= DA_END) return CMD_ERROR;
01383       break;
01384 
01385     case MOF_COND_VARIABLE:
01386       if (data >= OCV_END) return CMD_ERROR;
01387       break;
01388 
01389     case MOF_COND_COMPARATOR:
01390       if (data >= OCC_END) return CMD_ERROR;
01391       switch (order->GetConditionVariable()) {
01392         case OCV_UNCONDITIONALLY: return CMD_ERROR;
01393 
01394         case OCV_REQUIRES_SERVICE:
01395           if (data != OCC_IS_TRUE && data != OCC_IS_FALSE) return CMD_ERROR;
01396           break;
01397 
01398         default:
01399           if (data == OCC_IS_TRUE || data == OCC_IS_FALSE) return CMD_ERROR;
01400           break;
01401       }
01402       break;
01403 
01404     case MOF_COND_VALUE:
01405       switch (order->GetConditionVariable()) {
01406         case OCV_UNCONDITIONALLY: return CMD_ERROR;
01407 
01408         case OCV_LOAD_PERCENTAGE:
01409         case OCV_RELIABILITY:
01410           if (data > 100) return CMD_ERROR;
01411           break;
01412 
01413         default:
01414           if (data > 2047) return CMD_ERROR;
01415           break;
01416       }
01417       break;
01418 
01419     case MOF_COND_DESTINATION:
01420       if (data >= v->GetNumOrders()) return CMD_ERROR;
01421       break;
01422   }
01423 
01424   if (flags & DC_EXEC) {
01425     switch (mof) {
01426       case MOF_NON_STOP:
01427         order->SetNonStopType((OrderNonStopFlags)data);
01428         if (data & ONSF_NO_STOP_AT_DESTINATION_STATION) order->SetRefit(CT_NO_REFIT);
01429         break;
01430 
01431       case MOF_STOP_LOCATION:
01432         order->SetStopLocation((OrderStopLocation)data);
01433         break;
01434 
01435       case MOF_UNLOAD:
01436         order->SetUnloadType((OrderUnloadFlags)data);
01437         break;
01438 
01439       case MOF_LOAD:
01440         order->SetLoadType((OrderLoadFlags)data);
01441         if (data & OLFB_NO_LOAD) order->SetRefit(CT_NO_REFIT);
01442         break;
01443 
01444       case MOF_DEPOT_ACTION: {
01445         switch (data) {
01446           case DA_ALWAYS_GO:
01447             order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() & ~ODTFB_SERVICE));
01448             order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_HALT));
01449             break;
01450 
01451           case DA_SERVICE:
01452             order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() | ODTFB_SERVICE));
01453             order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_HALT));
01454             order->SetRefit(CT_NO_REFIT);
01455             break;
01456 
01457           case DA_STOP:
01458             order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() & ~ODTFB_SERVICE));
01459             order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() | ODATFB_HALT));
01460             order->SetRefit(CT_NO_REFIT);
01461             break;
01462 
01463           default:
01464             NOT_REACHED();
01465         }
01466         break;
01467       }
01468 
01469       case MOF_COND_VARIABLE: {
01470         order->SetConditionVariable((OrderConditionVariable)data);
01471 
01472         OrderConditionComparator occ = order->GetConditionComparator();
01473         switch (order->GetConditionVariable()) {
01474           case OCV_UNCONDITIONALLY:
01475             order->SetConditionComparator(OCC_EQUALS);
01476             order->SetConditionValue(0);
01477             break;
01478 
01479           case OCV_REQUIRES_SERVICE:
01480             if (occ != OCC_IS_TRUE && occ != OCC_IS_FALSE) order->SetConditionComparator(OCC_IS_TRUE);
01481             break;
01482 
01483           case OCV_LOAD_PERCENTAGE:
01484           case OCV_RELIABILITY:
01485             if (order->GetConditionValue() > 100) order->SetConditionValue(100);
01486             /* FALL THROUGH */
01487           default:
01488             if (occ == OCC_IS_TRUE || occ == OCC_IS_FALSE) order->SetConditionComparator(OCC_EQUALS);
01489             break;
01490         }
01491         break;
01492       }
01493 
01494       case MOF_COND_COMPARATOR:
01495         order->SetConditionComparator((OrderConditionComparator)data);
01496         break;
01497 
01498       case MOF_COND_VALUE:
01499         order->SetConditionValue(data);
01500         break;
01501 
01502       case MOF_COND_DESTINATION:
01503         order->SetConditionSkipToOrder(data);
01504         break;
01505 
01506       default: NOT_REACHED();
01507     }
01508 
01509     /* Update the windows and full load flags, also for vehicles that share the same order list */
01510     Vehicle *u = v->FirstShared();
01511     DeleteOrderWarnings(u);
01512     for (; u != NULL; u = u->NextShared()) {
01513       /* Toggle u->current_order "Full load" flag if it changed.
01514        * However, as the same flag is used for depot orders, check
01515        * whether we are not going to a depot as there are three
01516        * cases where the full load flag can be active and only
01517        * one case where the flag is used for depot orders. In the
01518        * other cases for the OrderTypeByte the flags are not used,
01519        * so do not care and those orders should not be active
01520        * when this function is called.
01521        */
01522       if (sel_ord == u->cur_real_order_index &&
01523           (u->current_order.IsType(OT_GOTO_STATION) || u->current_order.IsType(OT_LOADING)) &&
01524           u->current_order.GetLoadType() != order->GetLoadType()) {
01525         u->current_order.SetLoadType(order->GetLoadType());
01526       }
01527       InvalidateVehicleOrder(u, -2);
01528     }
01529   }
01530 
01531   return CommandCost();
01532 }
01533 
01541 static bool CheckAircraftOrderDistance(const Aircraft *v_new, const Vehicle *v_order, const Order *first)
01542 {
01543   if (first == NULL || v_new->acache.cached_max_range == 0) return true;
01544 
01545   /* Iterate over all orders to check the distance between all
01546    * 'goto' orders and their respective next order (of any type). */
01547   for (const Order *o = first; o != NULL; o = o->next) {
01548     switch (o->GetType()) {
01549       case OT_GOTO_STATION:
01550       case OT_GOTO_DEPOT:
01551       case OT_GOTO_WAYPOINT:
01552         /* If we don't have a next order, we've reached the end and must check the first order instead. */
01553         if (GetOrderDistance(o, o->next != NULL ? o->next : first, v_order) > v_new->acache.cached_max_range_sqr) return false;
01554         break;
01555 
01556       default: break;
01557     }
01558   }
01559 
01560   return true;
01561 }
01562 
01574 CommandCost CmdCloneOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01575 {
01576   VehicleID veh_src = GB(p2, 0, 20);
01577   VehicleID veh_dst = GB(p1, 0, 20);
01578 
01579   Vehicle *dst = Vehicle::GetIfValid(veh_dst);
01580   if (dst == NULL || !dst->IsPrimaryVehicle()) return CMD_ERROR;
01581 
01582   CommandCost ret = CheckOwnership(dst->owner);
01583   if (ret.Failed()) return ret;
01584 
01585   switch (GB(p1, 30, 2)) {
01586     case CO_SHARE: {
01587       Vehicle *src = Vehicle::GetIfValid(veh_src);
01588 
01589       /* Sanity checks */
01590       if (src == NULL || !src->IsPrimaryVehicle() || dst->type != src->type || dst == src) return CMD_ERROR;
01591 
01592       CommandCost ret = CheckOwnership(src->owner);
01593       if (ret.Failed()) return ret;
01594 
01595       /* Trucks can't share orders with busses (and visa versa) */
01596       if (src->type == VEH_ROAD && RoadVehicle::From(src)->IsBus() != RoadVehicle::From(dst)->IsBus()) {
01597         return CMD_ERROR;
01598       }
01599 
01600       /* Is the vehicle already in the shared list? */
01601       if (src->FirstShared() == dst->FirstShared()) return CMD_ERROR;
01602 
01603       const Order *order;
01604 
01605       FOR_VEHICLE_ORDERS(src, order) {
01606         if (OrderGoesToStation(dst, order) &&
01607             !CanVehicleUseStation(dst, Station::Get(order->GetDestination()))) {
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, -1);
01633         InvalidateVehicleOrder(src, -2);
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, -1);
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) {
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, -2);
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, -2);
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 }