order_cmd.cpp

Go to the documentation of this file.
00001 /* $Id: order_cmd.cpp 25891 2013-10-20 13:47:58Z fonsinchen $ */
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 
00088 void Order::MakeGoToDepot(DepotID destination, OrderDepotTypeFlags order, OrderNonStopFlags non_stop_type, OrderDepotActionFlags action, CargoID cargo)
00089 {
00090   this->type = OT_GOTO_DEPOT;
00091   this->SetDepotOrderType(order);
00092   this->SetDepotActionType(action);
00093   this->SetNonStopType(non_stop_type);
00094   this->dest = destination;
00095   this->SetRefit(cargo);
00096 }
00097 
00102 void Order::MakeGoToWaypoint(StationID destination)
00103 {
00104   this->type = OT_GOTO_WAYPOINT;
00105   this->flags = 0;
00106   this->dest = destination;
00107 }
00108 
00113 void Order::MakeLoading(bool ordered)
00114 {
00115   this->type = OT_LOADING;
00116   if (!ordered) this->flags = 0;
00117 }
00118 
00122 void Order::MakeLeaveStation()
00123 {
00124   this->type = OT_LEAVESTATION;
00125   this->flags = 0;
00126 }
00127 
00131 void Order::MakeDummy()
00132 {
00133   this->type = OT_DUMMY;
00134   this->flags = 0;
00135 }
00136 
00141 void Order::MakeConditional(VehicleOrderID order)
00142 {
00143   this->type = OT_CONDITIONAL;
00144   this->flags = order;
00145   this->dest = 0;
00146 }
00147 
00152 void Order::MakeImplicit(StationID destination)
00153 {
00154   this->type = OT_IMPLICIT;
00155   this->dest = destination;
00156 }
00157 
00163 void Order::SetRefit(CargoID cargo)
00164 {
00165   this->refit_cargo = cargo;
00166 }
00167 
00173 bool Order::Equals(const Order &other) const
00174 {
00175   /* In case of go to nearest depot orders we need "only" compare the flags
00176    * with the other and not the nearest depot order bit or the actual
00177    * destination because those get clear/filled in during the order
00178    * evaluation. If we do not do this the order will continuously be seen as
00179    * a different order and it will try to find a "nearest depot" every tick. */
00180   if ((this->IsType(OT_GOTO_DEPOT) && this->type == other.type) &&
00181       ((this->GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0 ||
00182        (other.GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0)) {
00183     return this->GetDepotOrderType() == other.GetDepotOrderType() &&
00184         (this->GetDepotActionType() & ~ODATFB_NEAREST_DEPOT) == (other.GetDepotActionType() & ~ODATFB_NEAREST_DEPOT);
00185   }
00186 
00187   return this->type == other.type && this->flags == other.flags && this->dest == other.dest;
00188 }
00189 
00196 uint32 Order::Pack() const
00197 {
00198   return this->dest << 16 | this->flags << 8 | this->type;
00199 }
00200 
00206 uint16 Order::MapOldOrder() const
00207 {
00208   uint16 order = this->GetType();
00209   switch (this->type) {
00210     case OT_GOTO_STATION:
00211       if (this->GetUnloadType() & OUFB_UNLOAD) SetBit(order, 5);
00212       if (this->GetLoadType() & OLFB_FULL_LOAD) SetBit(order, 6);
00213       if (this->GetNonStopType() & ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS) SetBit(order, 7);
00214       order |= GB(this->GetDestination(), 0, 8) << 8;
00215       break;
00216     case OT_GOTO_DEPOT:
00217       if (!(this->GetDepotOrderType() & ODTFB_PART_OF_ORDERS)) SetBit(order, 6);
00218       SetBit(order, 7);
00219       order |= GB(this->GetDestination(), 0, 8) << 8;
00220       break;
00221     case OT_LOADING:
00222       if (this->GetLoadType() & OLFB_FULL_LOAD) SetBit(order, 6);
00223       break;
00224   }
00225   return order;
00226 }
00227 
00232 Order::Order(uint32 packed)
00233 {
00234   this->type    = (OrderType)GB(packed,  0,  8);
00235   this->flags   = GB(packed,  8,  8);
00236   this->dest    = GB(packed, 16, 16);
00237   this->next    = NULL;
00238   this->refit_cargo   = CT_NO_REFIT;
00239   this->wait_time     = 0;
00240   this->travel_time   = 0;
00241   this->max_speed     = UINT16_MAX;
00242 }
00243 
00249 void InvalidateVehicleOrder(const Vehicle *v, int data)
00250 {
00251   SetWindowDirty(WC_VEHICLE_VIEW, v->index);
00252 
00253   if (data != 0) {
00254     /* Calls SetDirty() too */
00255     InvalidateWindowData(WC_VEHICLE_ORDERS,    v->index, data);
00256     InvalidateWindowData(WC_VEHICLE_TIMETABLE, v->index, data);
00257     return;
00258   }
00259 
00260   SetWindowDirty(WC_VEHICLE_ORDERS,    v->index);
00261   SetWindowDirty(WC_VEHICLE_TIMETABLE, v->index);
00262 }
00263 
00271 void Order::AssignOrder(const Order &other)
00272 {
00273   this->type  = other.type;
00274   this->flags = other.flags;
00275   this->dest  = other.dest;
00276 
00277   this->refit_cargo   = other.refit_cargo;
00278 
00279   this->wait_time   = other.wait_time;
00280   this->travel_time = other.travel_time;
00281   this->max_speed   = other.max_speed;
00282 }
00283 
00289 void OrderList::Initialize(Order *chain, Vehicle *v)
00290 {
00291   this->first = chain;
00292   this->first_shared = v;
00293 
00294   this->num_orders = 0;
00295   this->num_manual_orders = 0;
00296   this->num_vehicles = 1;
00297   this->timetable_duration = 0;
00298 
00299   for (Order *o = this->first; o != NULL; o = o->next) {
00300     ++this->num_orders;
00301     if (!o->IsType(OT_IMPLICIT)) ++this->num_manual_orders;
00302     this->timetable_duration += o->wait_time + o->travel_time;
00303   }
00304 
00305   for (Vehicle *u = this->first_shared->PreviousShared(); u != NULL; u = u->PreviousShared()) {
00306     ++this->num_vehicles;
00307     this->first_shared = u;
00308   }
00309 
00310   for (const Vehicle *u = v->NextShared(); u != NULL; u = u->NextShared()) ++this->num_vehicles;
00311 }
00312 
00318 void OrderList::FreeChain(bool keep_orderlist)
00319 {
00320   Order *next;
00321   for (Order *o = this->first; o != NULL; o = next) {
00322     next = o->next;
00323     delete o;
00324   }
00325 
00326   if (keep_orderlist) {
00327     this->first = NULL;
00328     this->num_orders = 0;
00329     this->num_manual_orders = 0;
00330     this->timetable_duration = 0;
00331   } else {
00332     delete this;
00333   }
00334 }
00335 
00341 Order *OrderList::GetOrderAt(int index) const
00342 {
00343   if (index < 0) return NULL;
00344 
00345   Order *order = this->first;
00346 
00347   while (order != NULL && index-- > 0) {
00348     order = order->next;
00349   }
00350   return order;
00351 }
00352 
00364 const Order *OrderList::GetNextDecisionNode(const Order *next, uint hops) const
00365 {
00366   if (hops > this->GetNumOrders() || next == NULL) return NULL;
00367 
00368   if (next->IsType(OT_CONDITIONAL)) {
00369     if (next->GetConditionVariable() != OCV_UNCONDITIONALLY) return next;
00370 
00371     /* We can evaluate trivial conditions right away. They're conceptually
00372      * the same as regular order progression. */
00373     return this->GetNextDecisionNode(
00374         this->GetOrderAt(next->GetConditionSkipToOrder()),
00375         hops + 1);
00376   }
00377 
00378   if (next->IsType(OT_GOTO_DEPOT)) {
00379     if (next->GetDepotActionType() == ODATFB_HALT) return NULL;
00380     if (next->IsRefit()) return next;
00381   }
00382 
00383   if (!next->CanLoadOrUnload()) {
00384     return this->GetNextDecisionNode(this->GetNext(next), hops + 1);
00385   }
00386 
00387   return next;
00388 }
00389 
00398 StationIDStack OrderList::GetNextStoppingStation(const Vehicle *v, const Order *first) const
00399 {
00400 
00401   const Order *next = first;
00402   if (first == NULL) {
00403     next = this->GetOrderAt(v->cur_implicit_order_index);
00404     if (next == NULL) {
00405       next = this->GetFirstOrder();
00406       if (next == NULL) return INVALID_STATION;
00407     } else {
00408       /* GetNext never returns NULL if there is a valid station in the list.
00409        * As the given "next" is already valid and a station in the list, we
00410        * don't have to check for NULL here. */
00411       next = this->GetNext(next);
00412       assert(next != NULL);
00413     }
00414   }
00415 
00416   uint hops = 0;
00417   do {
00418     next = this->GetNextDecisionNode(next, ++hops);
00419 
00420     /* Resolve possibly nested conditionals by estimation. */
00421     while (next != NULL && next->IsType(OT_CONDITIONAL)) {
00422       ++hops;
00423       if (next->GetConditionVariable() == OCV_LOAD_PERCENTAGE) {
00424         /* If the condition is based on load percentage we can't
00425          * tell what it will do. So we choose randomly. */
00426         const Order *skip_to = this->GetNextDecisionNode(
00427             this->GetOrderAt(next->GetConditionSkipToOrder()),
00428             hops);
00429         const Order *advance = this->GetNextDecisionNode(
00430             this->GetNext(next), hops);
00431         if (advance == NULL) {
00432           next = skip_to;
00433         } else if (skip_to == NULL) {
00434           next = advance;
00435         } else {
00436           StationIDStack st1 = this->GetNextStoppingStation(v, skip_to);
00437           StationIDStack st2 = this->GetNextStoppingStation(v, advance);
00438           while (!st2.IsEmpty()) st1.Push(st2.Pop());
00439           return st1;
00440         }
00441       } else {
00442         /* Otherwise we're optimistic and expect that the
00443          * condition value won't change until it's evaluated. */
00444         VehicleOrderID skip_to = ProcessConditionalOrder(next, v);
00445         if (skip_to != INVALID_VEH_ORDER_ID) {
00446           next = this->GetNextDecisionNode(this->GetOrderAt(skip_to),
00447               hops);
00448         } else {
00449           next = this->GetNextDecisionNode(this->GetNext(next), hops);
00450         }
00451       }
00452     }
00453 
00454     /* Don't return a next stop if the vehicle has to unload everything. */
00455     if (next == NULL || ((next->IsType(OT_GOTO_STATION) || next->IsType(OT_IMPLICIT)) &&
00456         next->GetDestination() == v->last_station_visited &&
00457         (next->GetUnloadType() & (OUFB_TRANSFER | OUFB_UNLOAD)) != 0)) {
00458       return INVALID_STATION;
00459     }
00460   } while (next->IsType(OT_GOTO_DEPOT) || next->GetDestination() == v->last_station_visited);
00461 
00462   return next->GetDestination();
00463 }
00464 
00470 void OrderList::InsertOrderAt(Order *new_order, int index)
00471 {
00472   if (this->first == NULL) {
00473     this->first = new_order;
00474   } else {
00475     if (index == 0) {
00476       /* Insert as first or only order */
00477       new_order->next = this->first;
00478       this->first = new_order;
00479     } else if (index >= this->num_orders) {
00480       /* index is after the last order, add it to the end */
00481       this->GetLastOrder()->next = new_order;
00482     } else {
00483       /* Put the new order in between */
00484       Order *order = this->GetOrderAt(index - 1);
00485       new_order->next = order->next;
00486       order->next = new_order;
00487     }
00488   }
00489   ++this->num_orders;
00490   if (!new_order->IsType(OT_IMPLICIT)) ++this->num_manual_orders;
00491   this->timetable_duration += new_order->wait_time + new_order->travel_time;
00492 
00493   /* We can visit oil rigs and buoys that are not our own. They will be shown in
00494    * the list of stations. So, we need to invalidate that window if needed. */
00495   if (new_order->IsType(OT_GOTO_STATION) || new_order->IsType(OT_GOTO_WAYPOINT)) {
00496     BaseStation *bs = BaseStation::Get(new_order->GetDestination());
00497     if (bs->owner == OWNER_NONE) InvalidateWindowClassesData(WC_STATION_LIST, 0);
00498   }
00499 
00500 }
00501 
00502 
00507 void OrderList::DeleteOrderAt(int index)
00508 {
00509   if (index >= this->num_orders) return;
00510 
00511   Order *to_remove;
00512 
00513   if (index == 0) {
00514     to_remove = this->first;
00515     this->first = to_remove->next;
00516   } else {
00517     Order *prev = GetOrderAt(index - 1);
00518     to_remove = prev->next;
00519     prev->next = to_remove->next;
00520   }
00521   --this->num_orders;
00522   if (!to_remove->IsType(OT_IMPLICIT)) --this->num_manual_orders;
00523   this->timetable_duration -= (to_remove->wait_time + to_remove->travel_time);
00524   delete to_remove;
00525 }
00526 
00532 void OrderList::MoveOrder(int from, int to)
00533 {
00534   if (from >= this->num_orders || to >= this->num_orders || from == to) return;
00535 
00536   Order *moving_one;
00537 
00538   /* Take the moving order out of the pointer-chain */
00539   if (from == 0) {
00540     moving_one = this->first;
00541     this->first = moving_one->next;
00542   } else {
00543     Order *one_before = GetOrderAt(from - 1);
00544     moving_one = one_before->next;
00545     one_before->next = moving_one->next;
00546   }
00547 
00548   /* Insert the moving_order again in the pointer-chain */
00549   if (to == 0) {
00550     moving_one->next = this->first;
00551     this->first = moving_one;
00552   } else {
00553     Order *one_before = GetOrderAt(to - 1);
00554     moving_one->next = one_before->next;
00555     one_before->next = moving_one;
00556   }
00557 }
00558 
00564 void OrderList::RemoveVehicle(Vehicle *v)
00565 {
00566   --this->num_vehicles;
00567   if (v == this->first_shared) this->first_shared = v->NextShared();
00568 }
00569 
00574 bool OrderList::IsVehicleInSharedOrdersList(const Vehicle *v) const
00575 {
00576   for (const Vehicle *v_shared = this->first_shared; v_shared != NULL; v_shared = v_shared->NextShared()) {
00577     if (v_shared == v) return true;
00578   }
00579 
00580   return false;
00581 }
00582 
00588 int OrderList::GetPositionInSharedOrderList(const Vehicle *v) const
00589 {
00590   int count = 0;
00591   for (const Vehicle *v_shared = v->PreviousShared(); v_shared != NULL; v_shared = v_shared->PreviousShared()) count++;
00592   return count;
00593 }
00594 
00599 bool OrderList::IsCompleteTimetable() const
00600 {
00601   for (Order *o = this->first; o != NULL; o = o->next) {
00602     /* Implicit orders are, by definition, not timetabled. */
00603     if (o->IsType(OT_IMPLICIT)) continue;
00604     if (!o->IsCompletelyTimetabled()) return false;
00605   }
00606   return true;
00607 }
00608 
00612 void OrderList::DebugCheckSanity() const
00613 {
00614   VehicleOrderID check_num_orders = 0;
00615   VehicleOrderID check_num_manual_orders = 0;
00616   uint check_num_vehicles = 0;
00617   Ticks check_timetable_duration = 0;
00618 
00619   DEBUG(misc, 6, "Checking OrderList %hu for sanity...", this->index);
00620 
00621   for (const Order *o = this->first; o != NULL; o = o->next) {
00622     ++check_num_orders;
00623     if (!o->IsType(OT_IMPLICIT)) ++check_num_manual_orders;
00624     check_timetable_duration += o->wait_time + o->travel_time;
00625   }
00626   assert(this->num_orders == check_num_orders);
00627   assert(this->num_manual_orders == check_num_manual_orders);
00628   assert(this->timetable_duration == check_timetable_duration);
00629 
00630   for (const Vehicle *v = this->first_shared; v != NULL; v = v->NextShared()) {
00631     ++check_num_vehicles;
00632     assert(v->orders.list == this);
00633   }
00634   assert(this->num_vehicles == check_num_vehicles);
00635   DEBUG(misc, 6, "... detected %u orders (%u manual), %u vehicles, %i ticks",
00636       (uint)this->num_orders, (uint)this->num_manual_orders,
00637       this->num_vehicles, this->timetable_duration);
00638 }
00639 
00647 static inline bool OrderGoesToStation(const Vehicle *v, const Order *o)
00648 {
00649   return o->IsType(OT_GOTO_STATION) ||
00650       (v->type == VEH_AIRCRAFT && o->IsType(OT_GOTO_DEPOT) && !(o->GetDepotActionType() & ODATFB_NEAREST_DEPOT));
00651 }
00652 
00659 static void DeleteOrderWarnings(const Vehicle *v)
00660 {
00661   DeleteVehicleNews(v->index, STR_NEWS_VEHICLE_HAS_TOO_FEW_ORDERS);
00662   DeleteVehicleNews(v->index, STR_NEWS_VEHICLE_HAS_VOID_ORDER);
00663   DeleteVehicleNews(v->index, STR_NEWS_VEHICLE_HAS_DUPLICATE_ENTRY);
00664   DeleteVehicleNews(v->index, STR_NEWS_VEHICLE_HAS_INVALID_ENTRY);
00665 }
00666 
00673 TileIndex Order::GetLocation(const Vehicle *v, bool airport) const
00674 {
00675   switch (this->GetType()) {
00676     case OT_GOTO_WAYPOINT:
00677     case OT_GOTO_STATION:
00678     case OT_IMPLICIT:
00679       if (airport && v->type == VEH_AIRCRAFT) return Station::Get(this->GetDestination())->airport.tile;
00680       return BaseStation::Get(this->GetDestination())->xy;
00681 
00682     case OT_GOTO_DEPOT:
00683       if ((this->GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0) return INVALID_TILE;
00684       return (v->type == VEH_AIRCRAFT) ? Station::Get(this->GetDestination())->xy : Depot::Get(this->GetDestination())->xy;
00685 
00686     default:
00687       return INVALID_TILE;
00688   }
00689 }
00690 
00700 uint GetOrderDistance(const Order *prev, const Order *cur, const Vehicle *v, int conditional_depth)
00701 {
00702   if (cur->IsType(OT_CONDITIONAL)) {
00703     if (conditional_depth > v->GetNumOrders()) return 0;
00704 
00705     conditional_depth++;
00706 
00707     int dist1 = GetOrderDistance(prev, v->GetOrder(cur->GetConditionSkipToOrder()), v, conditional_depth);
00708     int dist2 = GetOrderDistance(prev, cur->next == NULL ? v->orders.list->GetFirstOrder() : cur->next, v, conditional_depth);
00709     return max(dist1, dist2);
00710   }
00711 
00712   TileIndex prev_tile = prev->GetLocation(v, true);
00713   TileIndex cur_tile = cur->GetLocation(v, true);
00714   if (prev_tile == INVALID_TILE || cur_tile == INVALID_TILE) return 0;
00715   return v->type == VEH_AIRCRAFT ? DistanceSquare(prev_tile, cur_tile) : DistanceManhattan(prev_tile, cur_tile);
00716 }
00717 
00731 CommandCost CmdInsertOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00732 {
00733   VehicleID veh          = GB(p1,  0, 20);
00734   VehicleOrderID sel_ord = GB(p1, 20, 8);
00735   Order new_order(p2);
00736 
00737   Vehicle *v = Vehicle::GetIfValid(veh);
00738   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
00739 
00740   CommandCost ret = CheckOwnership(v->owner);
00741   if (ret.Failed()) return ret;
00742 
00743   /* Check if the inserted order is to the correct destination (owner, type),
00744    * and has the correct flags if any */
00745   switch (new_order.GetType()) {
00746     case OT_GOTO_STATION: {
00747       const Station *st = Station::GetIfValid(new_order.GetDestination());
00748       if (st == NULL) return CMD_ERROR;
00749 
00750       if (st->owner != OWNER_NONE) {
00751         CommandCost ret = CheckOwnership(st->owner);
00752         if (ret.Failed()) return ret;
00753       }
00754 
00755       if (!CanVehicleUseStation(v, st)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER);
00756       for (Vehicle *u = v->FirstShared(); u != NULL; u = u->NextShared()) {
00757         if (!CanVehicleUseStation(u, st)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER_SHARED);
00758       }
00759 
00760       /* Non stop only allowed for ground vehicles. */
00761       if (new_order.GetNonStopType() != ONSF_STOP_EVERYWHERE && !v->IsGroundVehicle()) return CMD_ERROR;
00762 
00763       /* Filter invalid load/unload types. */
00764       switch (new_order.GetLoadType()) {
00765         case OLF_LOAD_IF_POSSIBLE: case OLFB_FULL_LOAD: case OLF_FULL_LOAD_ANY: case OLFB_NO_LOAD: break;
00766         default: return CMD_ERROR;
00767       }
00768       switch (new_order.GetUnloadType()) {
00769         case OUF_UNLOAD_IF_POSSIBLE: case OUFB_UNLOAD: case OUFB_TRANSFER: case OUFB_NO_UNLOAD: break;
00770         default: return CMD_ERROR;
00771       }
00772 
00773       /* Filter invalid stop locations */
00774       switch (new_order.GetStopLocation()) {
00775         case OSL_PLATFORM_NEAR_END:
00776         case OSL_PLATFORM_MIDDLE:
00777           if (v->type != VEH_TRAIN) return CMD_ERROR;
00778           /* FALL THROUGH */
00779         case OSL_PLATFORM_FAR_END:
00780           break;
00781 
00782         default:
00783           return CMD_ERROR;
00784       }
00785 
00786       break;
00787     }
00788 
00789     case OT_GOTO_DEPOT: {
00790       if ((new_order.GetDepotActionType() & ODATFB_NEAREST_DEPOT) == 0) {
00791         if (v->type == VEH_AIRCRAFT) {
00792           const Station *st = Station::GetIfValid(new_order.GetDestination());
00793 
00794           if (st == NULL) return CMD_ERROR;
00795 
00796           CommandCost ret = CheckOwnership(st->owner);
00797           if (ret.Failed()) return ret;
00798 
00799           if (!CanVehicleUseStation(v, st) || !st->airport.HasHangar()) {
00800             return CMD_ERROR;
00801           }
00802         } else {
00803           const Depot *dp = Depot::GetIfValid(new_order.GetDestination());
00804 
00805           if (dp == NULL) return CMD_ERROR;
00806 
00807           CommandCost ret = CheckOwnership(GetTileOwner(dp->xy));
00808           if (ret.Failed()) return ret;
00809 
00810           switch (v->type) {
00811             case VEH_TRAIN:
00812               if (!IsRailDepotTile(dp->xy)) return CMD_ERROR;
00813               break;
00814 
00815             case VEH_ROAD:
00816               if (!IsRoadDepotTile(dp->xy)) return CMD_ERROR;
00817               break;
00818 
00819             case VEH_SHIP:
00820               if (!IsShipDepotTile(dp->xy)) return CMD_ERROR;
00821               break;
00822 
00823             default: return CMD_ERROR;
00824           }
00825         }
00826       }
00827 
00828       if (new_order.GetNonStopType() != ONSF_STOP_EVERYWHERE && !v->IsGroundVehicle()) return CMD_ERROR;
00829       if (new_order.GetDepotOrderType() & ~(ODTFB_PART_OF_ORDERS | ((new_order.GetDepotOrderType() & ODTFB_PART_OF_ORDERS) != 0 ? ODTFB_SERVICE : 0))) return CMD_ERROR;
00830       if (new_order.GetDepotActionType() & ~(ODATFB_HALT | ODATFB_NEAREST_DEPOT)) return CMD_ERROR;
00831       if ((new_order.GetDepotOrderType() & ODTFB_SERVICE) && (new_order.GetDepotActionType() & ODATFB_HALT)) return CMD_ERROR;
00832       break;
00833     }
00834 
00835     case OT_GOTO_WAYPOINT: {
00836       const Waypoint *wp = Waypoint::GetIfValid(new_order.GetDestination());
00837       if (wp == NULL) return CMD_ERROR;
00838 
00839       switch (v->type) {
00840         default: return CMD_ERROR;
00841 
00842         case VEH_TRAIN: {
00843           if (!(wp->facilities & FACIL_TRAIN)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER);
00844 
00845           CommandCost ret = CheckOwnership(wp->owner);
00846           if (ret.Failed()) return ret;
00847           break;
00848         }
00849 
00850         case VEH_SHIP:
00851           if (!(wp->facilities & FACIL_DOCK)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER);
00852           if (wp->owner != OWNER_NONE) {
00853             CommandCost ret = CheckOwnership(wp->owner);
00854             if (ret.Failed()) return ret;
00855           }
00856           break;
00857       }
00858 
00859       /* Order flags can be any of the following for waypoints:
00860        * [non-stop]
00861        * non-stop orders (if any) are only valid for trains */
00862       if (new_order.GetNonStopType() != ONSF_STOP_EVERYWHERE && v->type != VEH_TRAIN) return CMD_ERROR;
00863       break;
00864     }
00865 
00866     case OT_CONDITIONAL: {
00867       VehicleOrderID skip_to = new_order.GetConditionSkipToOrder();
00868       if (skip_to != 0 && skip_to >= v->GetNumOrders()) return CMD_ERROR; // Always allow jumping to the first (even when there is no order).
00869       if (new_order.GetConditionVariable() >= OCV_END) return CMD_ERROR;
00870 
00871       OrderConditionComparator occ = new_order.GetConditionComparator();
00872       if (occ >= OCC_END) return CMD_ERROR;
00873       switch (new_order.GetConditionVariable()) {
00874         case OCV_REQUIRES_SERVICE:
00875           if (occ != OCC_IS_TRUE && occ != OCC_IS_FALSE) return CMD_ERROR;
00876           break;
00877 
00878         case OCV_UNCONDITIONALLY:
00879           if (occ != OCC_EQUALS) return CMD_ERROR;
00880           if (new_order.GetConditionValue() != 0) return CMD_ERROR;
00881           break;
00882 
00883         case OCV_LOAD_PERCENTAGE:
00884         case OCV_RELIABILITY:
00885           if (new_order.GetConditionValue() > 100) return CMD_ERROR;
00886           /* FALL THROUGH */
00887         default:
00888           if (occ == OCC_IS_TRUE || occ == OCC_IS_FALSE) return CMD_ERROR;
00889           break;
00890       }
00891       break;
00892     }
00893 
00894     default: return CMD_ERROR;
00895   }
00896 
00897   if (sel_ord > v->GetNumOrders()) return CMD_ERROR;
00898 
00899   if (v->GetNumOrders() >= MAX_VEH_ORDER_ID) return_cmd_error(STR_ERROR_TOO_MANY_ORDERS);
00900   if (!Order::CanAllocateItem()) return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
00901   if (v->orders.list == NULL && !OrderList::CanAllocateItem()) return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
00902 
00903   if (v->type == VEH_SHIP && _settings_game.pf.pathfinder_for_ships != VPF_NPF) {
00904     /* Make sure the new destination is not too far away from the previous */
00905     const Order *prev = NULL;
00906     uint n = 0;
00907 
00908     /* Find the last goto station or depot order before the insert location.
00909      * If the order is to be inserted at the beginning of the order list this
00910      * finds the last order in the list. */
00911     const Order *o;
00912     FOR_VEHICLE_ORDERS(v, o) {
00913       switch (o->GetType()) {
00914         case OT_GOTO_STATION:
00915         case OT_GOTO_DEPOT:
00916         case OT_GOTO_WAYPOINT:
00917           prev = o;
00918           break;
00919 
00920         default: break;
00921       }
00922       if (++n == sel_ord && prev != NULL) break;
00923     }
00924     if (prev != NULL) {
00925       uint dist;
00926       if (new_order.IsType(OT_CONDITIONAL)) {
00927         /* The order is not yet inserted, so we have to do the first iteration here. */
00928         dist = GetOrderDistance(prev, v->GetOrder(new_order.GetConditionSkipToOrder()), v);
00929       } else {
00930         dist = GetOrderDistance(prev, &new_order, v);
00931       }
00932 
00933       if (dist >= 130) {
00934         return_cmd_error(STR_ERROR_TOO_FAR_FROM_PREVIOUS_DESTINATION);
00935       }
00936     }
00937   }
00938 
00939   if (flags & DC_EXEC) {
00940     Order *new_o = new Order();
00941     new_o->AssignOrder(new_order);
00942     InsertOrder(v, new_o, sel_ord);
00943   }
00944 
00945   return CommandCost();
00946 }
00947 
00954 void InsertOrder(Vehicle *v, Order *new_o, VehicleOrderID sel_ord)
00955 {
00956   /* Create new order and link in list */
00957   if (v->orders.list == NULL) {
00958     v->orders.list = new OrderList(new_o, v);
00959   } else {
00960     v->orders.list->InsertOrderAt(new_o, sel_ord);
00961   }
00962 
00963   Vehicle *u = v->FirstShared();
00964   DeleteOrderWarnings(u);
00965   for (; u != NULL; u = u->NextShared()) {
00966     assert(v->orders.list == u->orders.list);
00967 
00968     /* If there is added an order before the current one, we need
00969      * to update the selected order. We do not change implicit/real order indices though.
00970      * If the new order is between the current implicit order and real order, the implicit order will
00971      * later skip the inserted order. */
00972     if (sel_ord <= u->cur_real_order_index) {
00973       uint cur = u->cur_real_order_index + 1;
00974       /* Check if we don't go out of bound */
00975       if (cur < u->GetNumOrders()) {
00976         u->cur_real_order_index = cur;
00977       }
00978     }
00979     if (sel_ord == u->cur_implicit_order_index && u->IsGroundVehicle()) {
00980       /* We are inserting an order just before the current implicit order.
00981        * We do not know whether we will reach current implicit or the newly inserted order first.
00982        * So, disable creation of implicit orders until we are on track again. */
00983       uint16 &gv_flags = u->GetGroundVehicleFlags();
00984       SetBit(gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS);
00985     }
00986     if (sel_ord <= u->cur_implicit_order_index) {
00987       uint cur = u->cur_implicit_order_index + 1;
00988       /* Check if we don't go out of bound */
00989       if (cur < u->GetNumOrders()) {
00990         u->cur_implicit_order_index = cur;
00991       }
00992     }
00993     /* Update any possible open window of the vehicle */
00994     InvalidateVehicleOrder(u, INVALID_VEH_ORDER_ID | (sel_ord << 8));
00995   }
00996 
00997   /* As we insert an order, the order to skip to will be 'wrong'. */
00998   VehicleOrderID cur_order_id = 0;
00999   Order *order;
01000   FOR_VEHICLE_ORDERS(v, order) {
01001     if (order->IsType(OT_CONDITIONAL)) {
01002       VehicleOrderID order_id = order->GetConditionSkipToOrder();
01003       if (order_id >= sel_ord) {
01004         order->SetConditionSkipToOrder(order_id + 1);
01005       }
01006       if (order_id == cur_order_id) {
01007         order->SetConditionSkipToOrder((order_id + 1) % v->GetNumOrders());
01008       }
01009     }
01010     cur_order_id++;
01011   }
01012 
01013   /* Make sure to rebuild the whole list */
01014   InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
01015 }
01016 
01022 static CommandCost DecloneOrder(Vehicle *dst, DoCommandFlag flags)
01023 {
01024   if (flags & DC_EXEC) {
01025     DeleteVehicleOrders(dst);
01026     InvalidateVehicleOrder(dst, VIWD_REMOVE_ALL_ORDERS);
01027     InvalidateWindowClassesData(GetWindowClassForVehicleType(dst->type), 0);
01028   }
01029   return CommandCost();
01030 }
01031 
01041 CommandCost CmdDeleteOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01042 {
01043   VehicleID veh_id = GB(p1, 0, 20);
01044   VehicleOrderID sel_ord = GB(p2, 0, 8);
01045 
01046   Vehicle *v = Vehicle::GetIfValid(veh_id);
01047 
01048   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
01049 
01050   CommandCost ret = CheckOwnership(v->owner);
01051   if (ret.Failed()) return ret;
01052 
01053   /* If we did not select an order, we maybe want to de-clone the orders */
01054   if (sel_ord >= v->GetNumOrders()) return DecloneOrder(v, flags);
01055 
01056   if (v->GetOrder(sel_ord) == NULL) return CMD_ERROR;
01057 
01058   if (flags & DC_EXEC) DeleteOrder(v, sel_ord);
01059   return CommandCost();
01060 }
01061 
01066 static void CancelLoadingDueToDeletedOrder(Vehicle *v)
01067 {
01068   assert(v->current_order.IsType(OT_LOADING));
01069   /* NON-stop flag is misused to see if a train is in a station that is
01070    * on his order list or not */
01071   v->current_order.SetNonStopType(ONSF_STOP_EVERYWHERE);
01072   /* When full loading, "cancel" that order so the vehicle doesn't
01073    * stay indefinitely at this station anymore. */
01074   if (v->current_order.GetLoadType() & OLFB_FULL_LOAD) v->current_order.SetLoadType(OLF_LOAD_IF_POSSIBLE);
01075 }
01076 
01082 void DeleteOrder(Vehicle *v, VehicleOrderID sel_ord)
01083 {
01084   v->orders.list->DeleteOrderAt(sel_ord);
01085 
01086   Vehicle *u = v->FirstShared();
01087   DeleteOrderWarnings(u);
01088   for (; u != NULL; u = u->NextShared()) {
01089     assert(v->orders.list == u->orders.list);
01090 
01091     if (sel_ord == u->cur_real_order_index && u->current_order.IsType(OT_LOADING)) {
01092       CancelLoadingDueToDeletedOrder(u);
01093     }
01094 
01095     if (sel_ord < u->cur_real_order_index) {
01096       u->cur_real_order_index--;
01097     } else if (sel_ord == u->cur_real_order_index) {
01098       u->UpdateRealOrderIndex();
01099     }
01100 
01101     if (sel_ord < u->cur_implicit_order_index) {
01102       u->cur_implicit_order_index--;
01103     } else if (sel_ord == u->cur_implicit_order_index) {
01104       /* Make sure the index is valid */
01105       if (u->cur_implicit_order_index >= u->GetNumOrders()) u->cur_implicit_order_index = 0;
01106 
01107       /* Skip non-implicit orders for the implicit-order-index (e.g. if the current implicit order was deleted */
01108       while (u->cur_implicit_order_index != u->cur_real_order_index && !u->GetOrder(u->cur_implicit_order_index)->IsType(OT_IMPLICIT)) {
01109         u->cur_implicit_order_index++;
01110         if (u->cur_implicit_order_index >= u->GetNumOrders()) u->cur_implicit_order_index = 0;
01111       }
01112     }
01113 
01114     /* Update any possible open window of the vehicle */
01115     InvalidateVehicleOrder(u, sel_ord | (INVALID_VEH_ORDER_ID << 8));
01116   }
01117 
01118   /* As we delete an order, the order to skip to will be 'wrong'. */
01119   VehicleOrderID cur_order_id = 0;
01120   Order *order = NULL;
01121   FOR_VEHICLE_ORDERS(v, order) {
01122     if (order->IsType(OT_CONDITIONAL)) {
01123       VehicleOrderID order_id = order->GetConditionSkipToOrder();
01124       if (order_id >= sel_ord) {
01125         order_id = max(order_id - 1, 0);
01126       }
01127       if (order_id == cur_order_id) {
01128         order_id = (order_id + 1) % v->GetNumOrders();
01129       }
01130       order->SetConditionSkipToOrder(order_id);
01131     }
01132     cur_order_id++;
01133   }
01134 
01135   InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
01136 }
01137 
01147 CommandCost CmdSkipToOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01148 {
01149   VehicleID veh_id = GB(p1, 0, 20);
01150   VehicleOrderID sel_ord = GB(p2, 0, 8);
01151 
01152   Vehicle *v = Vehicle::GetIfValid(veh_id);
01153 
01154   if (v == NULL || !v->IsPrimaryVehicle() || sel_ord == v->cur_implicit_order_index || sel_ord >= v->GetNumOrders() || v->GetNumOrders() < 2) return CMD_ERROR;
01155 
01156   CommandCost ret = CheckOwnership(v->owner);
01157   if (ret.Failed()) return ret;
01158 
01159   if (flags & DC_EXEC) {
01160     if (v->current_order.IsType(OT_LOADING)) v->LeaveStation();
01161 
01162     v->cur_implicit_order_index = v->cur_real_order_index = sel_ord;
01163     v->UpdateRealOrderIndex();
01164 
01165     InvalidateVehicleOrder(v, VIWD_MODIFY_ORDERS);
01166   }
01167 
01168   /* We have an aircraft/ship, they have a mini-schedule, so update them all */
01169   if (v->type == VEH_AIRCRAFT) SetWindowClassesDirty(WC_AIRCRAFT_LIST);
01170   if (v->type == VEH_SHIP) SetWindowClassesDirty(WC_SHIPS_LIST);
01171 
01172   return CommandCost();
01173 }
01174 
01188 CommandCost CmdMoveOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01189 {
01190   VehicleID veh = GB(p1, 0, 20);
01191   VehicleOrderID moving_order = GB(p2,  0, 16);
01192   VehicleOrderID target_order = GB(p2, 16, 16);
01193 
01194   Vehicle *v = Vehicle::GetIfValid(veh);
01195   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
01196 
01197   CommandCost ret = CheckOwnership(v->owner);
01198   if (ret.Failed()) return ret;
01199 
01200   /* Don't make senseless movements */
01201   if (moving_order >= v->GetNumOrders() || target_order >= v->GetNumOrders() ||
01202       moving_order == target_order || v->GetNumOrders() <= 1) return CMD_ERROR;
01203 
01204   Order *moving_one = v->GetOrder(moving_order);
01205   /* Don't move an empty order */
01206   if (moving_one == NULL) return CMD_ERROR;
01207 
01208   if (flags & DC_EXEC) {
01209     v->orders.list->MoveOrder(moving_order, target_order);
01210 
01211     /* Update shared list */
01212     Vehicle *u = v->FirstShared();
01213 
01214     DeleteOrderWarnings(u);
01215 
01216     for (; u != NULL; u = u->NextShared()) {
01217       /* Update the current order.
01218        * There are multiple ways to move orders, which result in cur_implicit_order_index
01219        * and cur_real_order_index to not longer make any sense. E.g. moving another
01220        * real order between them.
01221        *
01222        * Basically one could choose to preserve either of them, but not both.
01223        * While both ways are suitable in this or that case from a human point of view, neither
01224        * of them makes really sense.
01225        * However, from an AI point of view, preserving cur_real_order_index is the most
01226        * predictable and transparent behaviour.
01227        *
01228        * With that decision it basically does not matter what we do to cur_implicit_order_index.
01229        * If we change orders between the implicit- and real-index, the implicit orders are mostly likely
01230        * completely out-dated anyway. So, keep it simple and just keep cur_implicit_order_index as well.
01231        * The worst which can happen is that a lot of implicit orders are removed when reaching current_order.
01232        */
01233       if (u->cur_real_order_index == moving_order) {
01234         u->cur_real_order_index = target_order;
01235       } else if (u->cur_real_order_index > moving_order && u->cur_real_order_index <= target_order) {
01236         u->cur_real_order_index--;
01237       } else if (u->cur_real_order_index < moving_order && u->cur_real_order_index >= target_order) {
01238         u->cur_real_order_index++;
01239       }
01240 
01241       if (u->cur_implicit_order_index == moving_order) {
01242         u->cur_implicit_order_index = target_order;
01243       } else if (u->cur_implicit_order_index > moving_order && u->cur_implicit_order_index <= target_order) {
01244         u->cur_implicit_order_index--;
01245       } else if (u->cur_implicit_order_index < moving_order && u->cur_implicit_order_index >= target_order) {
01246         u->cur_implicit_order_index++;
01247       }
01248 
01249       assert(v->orders.list == u->orders.list);
01250       /* Update any possible open window of the vehicle */
01251       InvalidateVehicleOrder(u, moving_order | (target_order << 8));
01252     }
01253 
01254     /* As we move an order, the order to skip to will be 'wrong'. */
01255     Order *order;
01256     FOR_VEHICLE_ORDERS(v, order) {
01257       if (order->IsType(OT_CONDITIONAL)) {
01258         VehicleOrderID order_id = order->GetConditionSkipToOrder();
01259         if (order_id == moving_order) {
01260           order_id = target_order;
01261         } else if (order_id > moving_order && order_id <= target_order) {
01262           order_id--;
01263         } else if (order_id < moving_order && order_id >= target_order) {
01264           order_id++;
01265         }
01266         order->SetConditionSkipToOrder(order_id);
01267       }
01268     }
01269 
01270     /* Make sure to rebuild the whole list */
01271     InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
01272   }
01273 
01274   return CommandCost();
01275 }
01276 
01292 CommandCost CmdModifyOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01293 {
01294   VehicleOrderID sel_ord = GB(p1, 20,  8);
01295   VehicleID veh          = GB(p1,  0, 20);
01296   ModifyOrderFlags mof   = Extract<ModifyOrderFlags, 0, 4>(p2);
01297   uint16 data            = GB(p2,  4, 11);
01298 
01299   if (mof >= MOF_END) return CMD_ERROR;
01300 
01301   Vehicle *v = Vehicle::GetIfValid(veh);
01302   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
01303 
01304   CommandCost ret = CheckOwnership(v->owner);
01305   if (ret.Failed()) return ret;
01306 
01307   /* Is it a valid order? */
01308   if (sel_ord >= v->GetNumOrders()) return CMD_ERROR;
01309 
01310   Order *order = v->GetOrder(sel_ord);
01311   switch (order->GetType()) {
01312     case OT_GOTO_STATION:
01313       if (mof == MOF_COND_VARIABLE || mof == MOF_COND_COMPARATOR || mof == MOF_DEPOT_ACTION || mof == MOF_COND_VALUE) return CMD_ERROR;
01314       break;
01315 
01316     case OT_GOTO_DEPOT:
01317       if (mof != MOF_NON_STOP && mof != MOF_DEPOT_ACTION) return CMD_ERROR;
01318       break;
01319 
01320     case OT_GOTO_WAYPOINT:
01321       if (mof != MOF_NON_STOP) return CMD_ERROR;
01322       break;
01323 
01324     case OT_CONDITIONAL:
01325       if (mof != MOF_COND_VARIABLE && mof != MOF_COND_COMPARATOR && mof != MOF_COND_VALUE && mof != MOF_COND_DESTINATION) return CMD_ERROR;
01326       break;
01327 
01328     default:
01329       return CMD_ERROR;
01330   }
01331 
01332   switch (mof) {
01333     default: NOT_REACHED();
01334 
01335     case MOF_NON_STOP:
01336       if (!v->IsGroundVehicle()) return CMD_ERROR;
01337       if (data >= ONSF_END) return CMD_ERROR;
01338       if (data == order->GetNonStopType()) return CMD_ERROR;
01339       break;
01340 
01341     case MOF_STOP_LOCATION:
01342       if (v->type != VEH_TRAIN) return CMD_ERROR;
01343       if (data >= OSL_END) return CMD_ERROR;
01344       break;
01345 
01346     case MOF_UNLOAD:
01347       if ((data & ~(OUFB_UNLOAD | OUFB_TRANSFER | OUFB_NO_UNLOAD)) != 0) return CMD_ERROR;
01348       /* Unload and no-unload are mutual exclusive and so are transfer and no unload. */
01349       if (data != 0 && ((data & (OUFB_UNLOAD | OUFB_TRANSFER)) != 0) == ((data & OUFB_NO_UNLOAD) != 0)) return CMD_ERROR;
01350       if (data == order->GetUnloadType()) return CMD_ERROR;
01351       break;
01352 
01353     case MOF_LOAD:
01354       if (data > OLFB_NO_LOAD || data == 1) return CMD_ERROR;
01355       if (data == order->GetLoadType()) return CMD_ERROR;
01356       break;
01357 
01358     case MOF_DEPOT_ACTION:
01359       if (data >= DA_END) return CMD_ERROR;
01360       break;
01361 
01362     case MOF_COND_VARIABLE:
01363       if (data >= OCV_END) return CMD_ERROR;
01364       break;
01365 
01366     case MOF_COND_COMPARATOR:
01367       if (data >= OCC_END) return CMD_ERROR;
01368       switch (order->GetConditionVariable()) {
01369         case OCV_UNCONDITIONALLY: return CMD_ERROR;
01370 
01371         case OCV_REQUIRES_SERVICE:
01372           if (data != OCC_IS_TRUE && data != OCC_IS_FALSE) return CMD_ERROR;
01373           break;
01374 
01375         default:
01376           if (data == OCC_IS_TRUE || data == OCC_IS_FALSE) return CMD_ERROR;
01377           break;
01378       }
01379       break;
01380 
01381     case MOF_COND_VALUE:
01382       switch (order->GetConditionVariable()) {
01383         case OCV_UNCONDITIONALLY: return CMD_ERROR;
01384 
01385         case OCV_LOAD_PERCENTAGE:
01386         case OCV_RELIABILITY:
01387           if (data > 100) return CMD_ERROR;
01388           break;
01389 
01390         default:
01391           if (data > 2047) return CMD_ERROR;
01392           break;
01393       }
01394       break;
01395 
01396     case MOF_COND_DESTINATION:
01397       if (data >= v->GetNumOrders()) return CMD_ERROR;
01398       break;
01399   }
01400 
01401   if (flags & DC_EXEC) {
01402     switch (mof) {
01403       case MOF_NON_STOP:
01404         order->SetNonStopType((OrderNonStopFlags)data);
01405         if (data & ONSF_NO_STOP_AT_DESTINATION_STATION) order->SetRefit(CT_NO_REFIT);
01406         break;
01407 
01408       case MOF_STOP_LOCATION:
01409         order->SetStopLocation((OrderStopLocation)data);
01410         break;
01411 
01412       case MOF_UNLOAD:
01413         order->SetUnloadType((OrderUnloadFlags)data);
01414         break;
01415 
01416       case MOF_LOAD:
01417         order->SetLoadType((OrderLoadFlags)data);
01418         if (data & OLFB_NO_LOAD) order->SetRefit(CT_NO_REFIT);
01419         break;
01420 
01421       case MOF_DEPOT_ACTION: {
01422         switch (data) {
01423           case DA_ALWAYS_GO:
01424             order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() & ~ODTFB_SERVICE));
01425             order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_HALT));
01426             break;
01427 
01428           case DA_SERVICE:
01429             order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() | ODTFB_SERVICE));
01430             order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_HALT));
01431             order->SetRefit(CT_NO_REFIT);
01432             break;
01433 
01434           case DA_STOP:
01435             order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() & ~ODTFB_SERVICE));
01436             order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() | ODATFB_HALT));
01437             order->SetRefit(CT_NO_REFIT);
01438             break;
01439 
01440           default:
01441             NOT_REACHED();
01442         }
01443         break;
01444       }
01445 
01446       case MOF_COND_VARIABLE: {
01447         order->SetConditionVariable((OrderConditionVariable)data);
01448 
01449         OrderConditionComparator occ = order->GetConditionComparator();
01450         switch (order->GetConditionVariable()) {
01451           case OCV_UNCONDITIONALLY:
01452             order->SetConditionComparator(OCC_EQUALS);
01453             order->SetConditionValue(0);
01454             break;
01455 
01456           case OCV_REQUIRES_SERVICE:
01457             if (occ != OCC_IS_TRUE && occ != OCC_IS_FALSE) order->SetConditionComparator(OCC_IS_TRUE);
01458             break;
01459 
01460           case OCV_LOAD_PERCENTAGE:
01461           case OCV_RELIABILITY:
01462             if (order->GetConditionValue() > 100) order->SetConditionValue(100);
01463             /* FALL THROUGH */
01464           default:
01465             if (occ == OCC_IS_TRUE || occ == OCC_IS_FALSE) order->SetConditionComparator(OCC_EQUALS);
01466             break;
01467         }
01468         break;
01469       }
01470 
01471       case MOF_COND_COMPARATOR:
01472         order->SetConditionComparator((OrderConditionComparator)data);
01473         break;
01474 
01475       case MOF_COND_VALUE:
01476         order->SetConditionValue(data);
01477         break;
01478 
01479       case MOF_COND_DESTINATION:
01480         order->SetConditionSkipToOrder(data);
01481         break;
01482 
01483       default: NOT_REACHED();
01484     }
01485 
01486     /* Update the windows and full load flags, also for vehicles that share the same order list */
01487     Vehicle *u = v->FirstShared();
01488     DeleteOrderWarnings(u);
01489     for (; u != NULL; u = u->NextShared()) {
01490       /* Toggle u->current_order "Full load" flag if it changed.
01491        * However, as the same flag is used for depot orders, check
01492        * whether we are not going to a depot as there are three
01493        * cases where the full load flag can be active and only
01494        * one case where the flag is used for depot orders. In the
01495        * other cases for the OrderTypeByte the flags are not used,
01496        * so do not care and those orders should not be active
01497        * when this function is called.
01498        */
01499       if (sel_ord == u->cur_real_order_index &&
01500           (u->current_order.IsType(OT_GOTO_STATION) || u->current_order.IsType(OT_LOADING)) &&
01501           u->current_order.GetLoadType() != order->GetLoadType()) {
01502         u->current_order.SetLoadType(order->GetLoadType());
01503       }
01504       InvalidateVehicleOrder(u, VIWD_MODIFY_ORDERS);
01505     }
01506   }
01507 
01508   return CommandCost();
01509 }
01510 
01518 static bool CheckAircraftOrderDistance(const Aircraft *v_new, const Vehicle *v_order, const Order *first)
01519 {
01520   if (first == NULL || v_new->acache.cached_max_range == 0) return true;
01521 
01522   /* Iterate over all orders to check the distance between all
01523    * 'goto' orders and their respective next order (of any type). */
01524   for (const Order *o = first; o != NULL; o = o->next) {
01525     switch (o->GetType()) {
01526       case OT_GOTO_STATION:
01527       case OT_GOTO_DEPOT:
01528       case OT_GOTO_WAYPOINT:
01529         /* If we don't have a next order, we've reached the end and must check the first order instead. */
01530         if (GetOrderDistance(o, o->next != NULL ? o->next : first, v_order) > v_new->acache.cached_max_range_sqr) return false;
01531         break;
01532 
01533       default: break;
01534     }
01535   }
01536 
01537   return true;
01538 }
01539 
01551 CommandCost CmdCloneOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01552 {
01553   VehicleID veh_src = GB(p2, 0, 20);
01554   VehicleID veh_dst = GB(p1, 0, 20);
01555 
01556   Vehicle *dst = Vehicle::GetIfValid(veh_dst);
01557   if (dst == NULL || !dst->IsPrimaryVehicle()) return CMD_ERROR;
01558 
01559   CommandCost ret = CheckOwnership(dst->owner);
01560   if (ret.Failed()) return ret;
01561 
01562   switch (GB(p1, 30, 2)) {
01563     case CO_SHARE: {
01564       Vehicle *src = Vehicle::GetIfValid(veh_src);
01565 
01566       /* Sanity checks */
01567       if (src == NULL || !src->IsPrimaryVehicle() || dst->type != src->type || dst == src) return CMD_ERROR;
01568 
01569       CommandCost ret = CheckOwnership(src->owner);
01570       if (ret.Failed()) return ret;
01571 
01572       /* Trucks can't share orders with busses (and visa versa) */
01573       if (src->type == VEH_ROAD && RoadVehicle::From(src)->IsBus() != RoadVehicle::From(dst)->IsBus()) {
01574         return CMD_ERROR;
01575       }
01576 
01577       /* Is the vehicle already in the shared list? */
01578       if (src->FirstShared() == dst->FirstShared()) return CMD_ERROR;
01579 
01580       const Order *order;
01581 
01582       FOR_VEHICLE_ORDERS(src, order) {
01583         if (!OrderGoesToStation(dst, order)) continue;
01584 
01585         /* Allow copying unreachable destinations if they were already unreachable for the source.
01586          * This is basically to allow cloning / autorenewing / autoreplacing vehicles, while the stations
01587          * are temporarily invalid due to reconstruction. */
01588         const Station *st = Station::Get(order->GetDestination());
01589         if (CanVehicleUseStation(src, st) && !CanVehicleUseStation(dst, st)) {
01590           return_cmd_error(STR_ERROR_CAN_T_COPY_SHARE_ORDER);
01591         }
01592       }
01593 
01594       /* Check for aircraft range limits. */
01595       if (dst->type == VEH_AIRCRAFT && !CheckAircraftOrderDistance(Aircraft::From(dst), src, src->GetFirstOrder())) {
01596         return_cmd_error(STR_ERROR_AIRCRAFT_NOT_ENOUGH_RANGE);
01597       }
01598 
01599       if (src->orders.list == NULL && !OrderList::CanAllocateItem()) {
01600         return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
01601       }
01602 
01603       if (flags & DC_EXEC) {
01604         /* If the destination vehicle had a OrderList, destroy it.
01605          * We only reset the order indices, if the new orders are obviously different.
01606          * (We mainly do this to keep the order indices valid and in range.) */
01607         DeleteVehicleOrders(dst, false, dst->GetNumOrders() != src->GetNumOrders());
01608 
01609         dst->orders.list = src->orders.list;
01610 
01611         /* Link this vehicle in the shared-list */
01612         dst->AddToShared(src);
01613 
01614         InvalidateVehicleOrder(dst, VIWD_REMOVE_ALL_ORDERS);
01615         InvalidateVehicleOrder(src, VIWD_MODIFY_ORDERS);
01616 
01617         InvalidateWindowClassesData(GetWindowClassForVehicleType(dst->type), 0);
01618       }
01619       break;
01620     }
01621 
01622     case CO_COPY: {
01623       Vehicle *src = Vehicle::GetIfValid(veh_src);
01624 
01625       /* Sanity checks */
01626       if (src == NULL || !src->IsPrimaryVehicle() || dst->type != src->type || dst == src) return CMD_ERROR;
01627 
01628       CommandCost ret = CheckOwnership(src->owner);
01629       if (ret.Failed()) return ret;
01630 
01631       /* Trucks can't copy all the orders from busses (and visa versa),
01632        * and neither can helicopters and aircraft. */
01633       const Order *order;
01634       FOR_VEHICLE_ORDERS(src, order) {
01635         if (OrderGoesToStation(dst, order) &&
01636             !CanVehicleUseStation(dst, Station::Get(order->GetDestination()))) {
01637           return_cmd_error(STR_ERROR_CAN_T_COPY_SHARE_ORDER);
01638         }
01639       }
01640 
01641       /* Check for aircraft range limits. */
01642       if (dst->type == VEH_AIRCRAFT && !CheckAircraftOrderDistance(Aircraft::From(dst), src, src->GetFirstOrder())) {
01643         return_cmd_error(STR_ERROR_AIRCRAFT_NOT_ENOUGH_RANGE);
01644       }
01645 
01646       /* make sure there are orders available */
01647       if (!Order::CanAllocateItem(src->GetNumOrders()) || !OrderList::CanAllocateItem()) {
01648         return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
01649       }
01650 
01651       if (flags & DC_EXEC) {
01652         const Order *order;
01653         Order *first = NULL;
01654         Order **order_dst;
01655 
01656         /* If the destination vehicle had an order list, destroy the chain but keep the OrderList.
01657          * We only reset the order indices, if the new orders are obviously different.
01658          * (We mainly do this to keep the order indices valid and in range.) */
01659         DeleteVehicleOrders(dst, true, dst->GetNumOrders() != src->GetNumOrders());
01660 
01661         order_dst = &first;
01662         FOR_VEHICLE_ORDERS(src, order) {
01663           *order_dst = new Order();
01664           (*order_dst)->AssignOrder(*order);
01665           order_dst = &(*order_dst)->next;
01666         }
01667         if (dst->orders.list == NULL) {
01668           dst->orders.list = new OrderList(first, dst);
01669         } else {
01670           assert(dst->orders.list->GetFirstOrder() == NULL);
01671           assert(!dst->orders.list->IsShared());
01672           delete dst->orders.list;
01673           assert(OrderList::CanAllocateItem());
01674           dst->orders.list = new OrderList(first, dst);
01675         }
01676 
01677         InvalidateVehicleOrder(dst, VIWD_REMOVE_ALL_ORDERS);
01678 
01679         InvalidateWindowClassesData(GetWindowClassForVehicleType(dst->type), 0);
01680       }
01681       break;
01682     }
01683 
01684     case CO_UNSHARE: return DecloneOrder(dst, flags);
01685     default: return CMD_ERROR;
01686   }
01687 
01688   return CommandCost();
01689 }
01690 
01702 CommandCost CmdOrderRefit(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01703 {
01704   VehicleID veh = GB(p1, 0, 20);
01705   VehicleOrderID order_number  = GB(p2, 16, 8);
01706   CargoID cargo = GB(p2, 0, 8);
01707 
01708   if (cargo >= NUM_CARGO && cargo != CT_NO_REFIT && cargo != CT_AUTO_REFIT) return CMD_ERROR;
01709 
01710   const Vehicle *v = Vehicle::GetIfValid(veh);
01711   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
01712 
01713   CommandCost ret = CheckOwnership(v->owner);
01714   if (ret.Failed()) return ret;
01715 
01716   Order *order = v->GetOrder(order_number);
01717   if (order == NULL) return CMD_ERROR;
01718 
01719   /* Automatic refit cargo is only supported for goto station orders. */
01720   if (cargo == CT_AUTO_REFIT && !order->IsType(OT_GOTO_STATION)) return CMD_ERROR;
01721 
01722   if (order->GetLoadType() & OLFB_NO_LOAD) return CMD_ERROR;
01723 
01724   if (flags & DC_EXEC) {
01725     order->SetRefit(cargo);
01726 
01727     /* Make the depot order an 'always go' order. */
01728     if (cargo != CT_NO_REFIT && order->IsType(OT_GOTO_DEPOT)) {
01729       order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() & ~ODTFB_SERVICE));
01730       order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_HALT));
01731     }
01732 
01733     for (Vehicle *u = v->FirstShared(); u != NULL; u = u->NextShared()) {
01734       /* Update any possible open window of the vehicle */
01735       InvalidateVehicleOrder(u, VIWD_MODIFY_ORDERS);
01736 
01737       /* If the vehicle already got the current depot set as current order, then update current order as well */
01738       if (u->cur_real_order_index == order_number && (u->current_order.GetDepotOrderType() & ODTFB_PART_OF_ORDERS)) {
01739         u->current_order.SetRefit(cargo);
01740       }
01741     }
01742   }
01743 
01744   return CommandCost();
01745 }
01746 
01747 
01753 void CheckOrders(const Vehicle *v)
01754 {
01755   /* Does the user wants us to check things? */
01756   if (_settings_client.gui.order_review_system == 0) return;
01757 
01758   /* Do nothing for crashed vehicles */
01759   if (v->vehstatus & VS_CRASHED) return;
01760 
01761   /* Do nothing for stopped vehicles if setting is '1' */
01762   if (_settings_client.gui.order_review_system == 1 && (v->vehstatus & VS_STOPPED)) return;
01763 
01764   /* do nothing we we're not the first vehicle in a share-chain */
01765   if (v->FirstShared() != v) return;
01766 
01767   /* Only check every 20 days, so that we don't flood the message log */
01768   if (v->owner == _local_company && v->day_counter % 20 == 0) {
01769     int n_st, problem_type = -1;
01770     const Order *order;
01771     int message = 0;
01772 
01773     /* Check the order list */
01774     n_st = 0;
01775 
01776     FOR_VEHICLE_ORDERS(v, order) {
01777       /* Dummy order? */
01778       if (order->IsType(OT_DUMMY)) {
01779         problem_type = 1;
01780         break;
01781       }
01782       /* Does station have a load-bay for this vehicle? */
01783       if (order->IsType(OT_GOTO_STATION)) {
01784         const Station *st = Station::Get(order->GetDestination());
01785 
01786         n_st++;
01787         if (!CanVehicleUseStation(v, st)) problem_type = 3;
01788       }
01789     }
01790 
01791     /* Check if the last and the first order are the same */
01792     if (v->GetNumOrders() > 1) {
01793       const Order *last = v->GetLastOrder();
01794 
01795       if (v->orders.list->GetFirstOrder()->Equals(*last)) {
01796         problem_type = 2;
01797       }
01798     }
01799 
01800     /* Do we only have 1 station in our order list? */
01801     if (n_st < 2 && problem_type == -1) problem_type = 0;
01802 
01803 #ifndef NDEBUG
01804     if (v->orders.list != NULL) v->orders.list->DebugCheckSanity();
01805 #endif
01806 
01807     /* We don't have a problem */
01808     if (problem_type < 0) return;
01809 
01810     message = STR_NEWS_VEHICLE_HAS_TOO_FEW_ORDERS + problem_type;
01811     //DEBUG(misc, 3, "Triggered News Item for vehicle %d", v->index);
01812 
01813     SetDParam(0, v->index);
01814     AddVehicleAdviceNewsItem(message, v->index);
01815   }
01816 }
01817 
01823 void RemoveOrderFromAllVehicles(OrderType type, DestinationID destination)
01824 {
01825   Vehicle *v;
01826 
01827   /* Aircraft have StationIDs for depot orders and never use DepotIDs
01828    * This fact is handled specially below
01829    */
01830 
01831   /* Go through all vehicles */
01832   FOR_ALL_VEHICLES(v) {
01833     Order *order;
01834 
01835     order = &v->current_order;
01836     if ((v->type == VEH_AIRCRAFT && order->IsType(OT_GOTO_DEPOT) ? OT_GOTO_STATION : order->GetType()) == type &&
01837         v->current_order.GetDestination() == destination) {
01838       order->MakeDummy();
01839       SetWindowDirty(WC_VEHICLE_VIEW, v->index);
01840     }
01841 
01842     /* Clear the order from the order-list */
01843     int id = -1;
01844     FOR_VEHICLE_ORDERS(v, order) {
01845       id++;
01846 restart:
01847 
01848       OrderType ot = order->GetType();
01849       if (ot == OT_GOTO_DEPOT && (order->GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0) continue;
01850       if (ot == OT_IMPLICIT || (v->type == VEH_AIRCRAFT && ot == OT_GOTO_DEPOT)) ot = OT_GOTO_STATION;
01851       if (ot == type && order->GetDestination() == destination) {
01852         /* We want to clear implicit orders, but we don't want to make them
01853          * dummy orders. They should just vanish. Also check the actual order
01854          * type as ot is currently OT_GOTO_STATION. */
01855         if (order->IsType(OT_IMPLICIT)) {
01856           order = order->next; // DeleteOrder() invalidates current order
01857           DeleteOrder(v, id);
01858           if (order != NULL) goto restart;
01859           break;
01860         }
01861 
01862         order->MakeDummy();
01863         for (const Vehicle *w = v->FirstShared(); w != NULL; w = w->NextShared()) {
01864           /* In GUI, simulate by removing the order and adding it back */
01865           InvalidateVehicleOrder(w, id | (INVALID_VEH_ORDER_ID << 8));
01866           InvalidateVehicleOrder(w, (INVALID_VEH_ORDER_ID << 8) | id);
01867         }
01868       }
01869     }
01870   }
01871 
01872   OrderBackup::RemoveOrder(type, destination);
01873 }
01874 
01879 bool Vehicle::HasDepotOrder() const
01880 {
01881   const Order *order;
01882 
01883   FOR_VEHICLE_ORDERS(this, order) {
01884     if (order->IsType(OT_GOTO_DEPOT)) return true;
01885   }
01886 
01887   return false;
01888 }
01889 
01899 void DeleteVehicleOrders(Vehicle *v, bool keep_orderlist, bool reset_order_indices)
01900 {
01901   DeleteOrderWarnings(v);
01902 
01903   if (v->IsOrderListShared()) {
01904     /* Remove ourself from the shared order list. */
01905     v->RemoveFromShared();
01906     v->orders.list = NULL;
01907   } else if (v->orders.list != NULL) {
01908     /* Remove the orders */
01909     v->orders.list->FreeChain(keep_orderlist);
01910     if (!keep_orderlist) v->orders.list = NULL;
01911   }
01912 
01913   if (reset_order_indices) {
01914     v->cur_implicit_order_index = v->cur_real_order_index = 0;
01915     if (v->current_order.IsType(OT_LOADING)) {
01916       CancelLoadingDueToDeletedOrder(v);
01917     }
01918   }
01919 }
01920 
01928 uint16 GetServiceIntervalClamped(uint interval, bool ispercent)
01929 {
01930   return ispercent ? Clamp(interval, MIN_SERVINT_PERCENT, MAX_SERVINT_PERCENT) : Clamp(interval, MIN_SERVINT_DAYS, MAX_SERVINT_DAYS);
01931 }
01932 
01941 static bool CheckForValidOrders(const Vehicle *v)
01942 {
01943   const Order *order;
01944 
01945   FOR_VEHICLE_ORDERS(v, order) {
01946     switch (order->GetType()) {
01947       case OT_GOTO_STATION:
01948       case OT_GOTO_DEPOT:
01949       case OT_GOTO_WAYPOINT:
01950         return true;
01951 
01952       default:
01953         break;
01954     }
01955   }
01956 
01957   return false;
01958 }
01959 
01963 static bool OrderConditionCompare(OrderConditionComparator occ, int variable, int value)
01964 {
01965   switch (occ) {
01966     case OCC_EQUALS:      return variable == value;
01967     case OCC_NOT_EQUALS:  return variable != value;
01968     case OCC_LESS_THAN:   return variable <  value;
01969     case OCC_LESS_EQUALS: return variable <= value;
01970     case OCC_MORE_THAN:   return variable >  value;
01971     case OCC_MORE_EQUALS: return variable >= value;
01972     case OCC_IS_TRUE:     return variable != 0;
01973     case OCC_IS_FALSE:    return variable == 0;
01974     default: NOT_REACHED();
01975   }
01976 }
01977 
01984 VehicleOrderID ProcessConditionalOrder(const Order *order, const Vehicle *v)
01985 {
01986   if (order->GetType() != OT_CONDITIONAL) return INVALID_VEH_ORDER_ID;
01987 
01988   bool skip_order = false;
01989   OrderConditionComparator occ = order->GetConditionComparator();
01990   uint16 value = order->GetConditionValue();
01991 
01992   switch (order->GetConditionVariable()) {
01993     case OCV_LOAD_PERCENTAGE:    skip_order = OrderConditionCompare(occ, CalcPercentVehicleFilled(v, NULL), value); break;
01994     case OCV_RELIABILITY:        skip_order = OrderConditionCompare(occ, ToPercent16(v->reliability),       value); break;
01995     case OCV_MAX_SPEED:          skip_order = OrderConditionCompare(occ, v->GetDisplayMaxSpeed() * 10 / 16, value); break;
01996     case OCV_AGE:                skip_order = OrderConditionCompare(occ, v->age / DAYS_IN_LEAP_YEAR,        value); break;
01997     case OCV_REQUIRES_SERVICE:   skip_order = OrderConditionCompare(occ, v->NeedsServicing(),               value); break;
01998     case OCV_UNCONDITIONALLY:    skip_order = true; break;
01999     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;
02000     default: NOT_REACHED();
02001   }
02002 
02003   return skip_order ? order->GetConditionSkipToOrder() : (VehicleOrderID)INVALID_VEH_ORDER_ID;
02004 }
02005 
02013 bool UpdateOrderDest(Vehicle *v, const Order *order, int conditional_depth, bool pbs_look_ahead)
02014 {
02015   if (conditional_depth > v->GetNumOrders()) {
02016     v->current_order.Free();
02017     v->dest_tile = 0;
02018     return false;
02019   }
02020 
02021   switch (order->GetType()) {
02022     case OT_GOTO_STATION:
02023       v->dest_tile = v->GetOrderStationLocation(order->GetDestination());
02024       return true;
02025 
02026     case OT_GOTO_DEPOT:
02027       if ((order->GetDepotOrderType() & ODTFB_SERVICE) && !v->NeedsServicing()) {
02028         assert(!pbs_look_ahead);
02029         UpdateVehicleTimetable(v, true);
02030         v->IncrementRealOrderIndex();
02031         break;
02032       }
02033 
02034       if (v->current_order.GetDepotActionType() & ODATFB_NEAREST_DEPOT) {
02035         /* We need to search for the nearest depot (hangar). */
02036         TileIndex location;
02037         DestinationID destination;
02038         bool reverse;
02039 
02040         if (v->FindClosestDepot(&location, &destination, &reverse)) {
02041           /* PBS reservations cannot reverse */
02042           if (pbs_look_ahead && reverse) return false;
02043 
02044           v->dest_tile = location;
02045           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());
02046 
02047           /* If there is no depot in front, reverse automatically (trains only) */
02048           if (v->type == VEH_TRAIN && reverse) DoCommand(v->tile, v->index, 0, DC_EXEC, CMD_REVERSE_TRAIN_DIRECTION);
02049 
02050           if (v->type == VEH_AIRCRAFT) {
02051             Aircraft *a = Aircraft::From(v);
02052             if (a->state == FLYING && a->targetairport != destination) {
02053               /* The aircraft is now heading for a different hangar than the next in the orders */
02054               extern void AircraftNextAirportPos_and_Order(Aircraft *a);
02055               AircraftNextAirportPos_and_Order(a);
02056             }
02057           }
02058           return true;
02059         }
02060 
02061         /* If there is no depot, we cannot help PBS either. */
02062         if (pbs_look_ahead) return false;
02063 
02064         UpdateVehicleTimetable(v, true);
02065         v->IncrementRealOrderIndex();
02066       } else {
02067         if (v->type != VEH_AIRCRAFT) {
02068           v->dest_tile = Depot::Get(order->GetDestination())->xy;
02069         }
02070         return true;
02071       }
02072       break;
02073 
02074     case OT_GOTO_WAYPOINT:
02075       v->dest_tile = Waypoint::Get(order->GetDestination())->xy;
02076       return true;
02077 
02078     case OT_CONDITIONAL: {
02079       assert(!pbs_look_ahead);
02080       VehicleOrderID next_order = ProcessConditionalOrder(order, v);
02081       if (next_order != INVALID_VEH_ORDER_ID) {
02082         /* Jump to next_order. cur_implicit_order_index becomes exactly that order,
02083          * cur_real_order_index might come after next_order. */
02084         UpdateVehicleTimetable(v, false);
02085         v->cur_implicit_order_index = v->cur_real_order_index = next_order;
02086         v->UpdateRealOrderIndex();
02087         v->current_order_time += v->GetOrder(v->cur_real_order_index)->travel_time;
02088 
02089         /* Disable creation of implicit orders.
02090          * When inserting them we do not know that we would have to make the conditional orders point to them. */
02091         if (v->IsGroundVehicle()) {
02092           uint16 &gv_flags = v->GetGroundVehicleFlags();
02093           SetBit(gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS);
02094         }
02095       } else {
02096         UpdateVehicleTimetable(v, true);
02097         v->IncrementRealOrderIndex();
02098       }
02099       break;
02100     }
02101 
02102     default:
02103       v->dest_tile = 0;
02104       return false;
02105   }
02106 
02107   assert(v->cur_implicit_order_index < v->GetNumOrders());
02108   assert(v->cur_real_order_index < v->GetNumOrders());
02109 
02110   /* Get the current order */
02111   order = v->GetOrder(v->cur_real_order_index);
02112   if (order != NULL && order->IsType(OT_IMPLICIT)) {
02113     assert(v->GetNumManualOrders() == 0);
02114     order = NULL;
02115   }
02116 
02117   if (order == NULL) {
02118     v->current_order.Free();
02119     v->dest_tile = 0;
02120     return false;
02121   }
02122 
02123   v->current_order = *order;
02124   return UpdateOrderDest(v, order, conditional_depth + 1, pbs_look_ahead);
02125 }
02126 
02134 bool ProcessOrders(Vehicle *v)
02135 {
02136   switch (v->current_order.GetType()) {
02137     case OT_GOTO_DEPOT:
02138       /* Let a depot order in the orderlist interrupt. */
02139       if (!(v->current_order.GetDepotOrderType() & ODTFB_PART_OF_ORDERS)) return false;
02140       break;
02141 
02142     case OT_LOADING:
02143       return false;
02144 
02145     case OT_LEAVESTATION:
02146       if (v->type != VEH_AIRCRAFT) return false;
02147       break;
02148 
02149     default: break;
02150   }
02151 
02159   bool may_reverse = v->current_order.IsType(OT_NOTHING);
02160 
02161   /* Check if we've reached a 'via' destination. */
02162   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)) &&
02163       IsTileType(v->tile, MP_STATION) &&
02164       v->current_order.GetDestination() == GetStationIndex(v->tile)) {
02165     v->DeleteUnreachedImplicitOrders();
02166     /* We set the last visited station here because we do not want
02167      * the train to stop at this 'via' station if the next order
02168      * is a no-non-stop order; in that case not setting the last
02169      * visited station will cause the vehicle to still stop. */
02170     v->last_station_visited = v->current_order.GetDestination();
02171     UpdateVehicleTimetable(v, true);
02172     v->IncrementImplicitOrderIndex();
02173   }
02174 
02175   /* Get the current order */
02176   assert(v->cur_implicit_order_index == 0 || v->cur_implicit_order_index < v->GetNumOrders());
02177   v->UpdateRealOrderIndex();
02178 
02179   const Order *order = v->GetOrder(v->cur_real_order_index);
02180   if (order != NULL && order->IsType(OT_IMPLICIT)) {
02181     assert(v->GetNumManualOrders() == 0);
02182     order = NULL;
02183   }
02184 
02185   /* If no order, do nothing. */
02186   if (order == NULL || (v->type == VEH_AIRCRAFT && !CheckForValidOrders(v))) {
02187     if (v->type == VEH_AIRCRAFT) {
02188       /* Aircraft do something vastly different here, so handle separately */
02189       extern void HandleMissingAircraftOrders(Aircraft *v);
02190       HandleMissingAircraftOrders(Aircraft::From(v));
02191       return false;
02192     }
02193 
02194     v->current_order.Free();
02195     v->dest_tile = 0;
02196     return false;
02197   }
02198 
02199   /* If it is unchanged, keep it. */
02200   if (order->Equals(v->current_order) && (v->type == VEH_AIRCRAFT || v->dest_tile != 0) &&
02201       (v->type != VEH_SHIP || !order->IsType(OT_GOTO_STATION) || Station::Get(order->GetDestination())->dock_tile != INVALID_TILE)) {
02202     return false;
02203   }
02204 
02205   /* Otherwise set it, and determine the destination tile. */
02206   v->current_order = *order;
02207 
02208   InvalidateVehicleOrder(v, VIWD_MODIFY_ORDERS);
02209   switch (v->type) {
02210     default:
02211       NOT_REACHED();
02212 
02213     case VEH_ROAD:
02214     case VEH_TRAIN:
02215       break;
02216 
02217     case VEH_AIRCRAFT:
02218     case VEH_SHIP:
02219       SetWindowClassesDirty(GetWindowClassForVehicleType(v->type));
02220       break;
02221   }
02222 
02223   return UpdateOrderDest(v, order) && may_reverse;
02224 }
02225 
02233 bool Order::ShouldStopAtStation(const Vehicle *v, StationID station) const
02234 {
02235   bool is_dest_station = this->IsType(OT_GOTO_STATION) && this->dest == station;
02236 
02237   return (!this->IsType(OT_GOTO_DEPOT) || (this->GetDepotOrderType() & ODTFB_PART_OF_ORDERS) != 0) &&
02238       v->last_station_visited != station && // Do stop only when we've not just been there
02239       /* Finally do stop when there is no non-stop flag set for this type of station. */
02240       !(this->GetNonStopType() & (is_dest_station ? ONSF_NO_STOP_AT_DESTINATION_STATION : ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS));
02241 }
02242 
02243 bool Order::CanLoadOrUnload() const
02244 {
02245   return (this->IsType(OT_GOTO_STATION) || this->IsType(OT_IMPLICIT)) &&
02246       (this->GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION) == 0 &&
02247       ((this->GetLoadType() & OLFB_NO_LOAD) == 0 ||
02248       (this->GetUnloadType() & OUFB_NO_UNLOAD) == 0);
02249 }
02250 
02257 bool Order::CanLeaveWithCargo(bool has_cargo) const
02258 {
02259   return (this->GetLoadType() & OLFB_NO_LOAD) == 0 || (has_cargo &&
02260       (this->GetUnloadType() & (OUFB_UNLOAD | OUFB_TRANSFER)) == 0);
02261 }