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