order_cmd.cpp

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