order_cmd.cpp

Go to the documentation of this file.
00001 /* $Id: order_cmd.cpp 23740 2012-01-03 21:32:51Z rubidium $ */
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 "aircraft.h"
00024 #include "roadveh.h"
00025 #include "station_base.h"
00026 #include "waypoint_base.h"
00027 #include "company_base.h"
00028 #include "order_backup.h"
00029 
00030 #include "table/strings.h"
00031 
00032 /* DestinationID must be at least as large as every these below, because it can
00033  * be any of them
00034  */
00035 assert_compile(sizeof(DestinationID) >= sizeof(DepotID));
00036 assert_compile(sizeof(DestinationID) >= sizeof(StationID));
00037 
00038 OrderPool _order_pool("Order");
00039 INSTANTIATE_POOL_METHODS(Order)
00040 OrderListPool _orderlist_pool("OrderList");
00041 INSTANTIATE_POOL_METHODS(OrderList)
00042 
00044 Order::~Order()
00045 {
00046   if (CleaningPool()) return;
00047 
00048   /* We can visit oil rigs and buoys that are not our own. They will be shown in
00049    * the list of stations. So, we need to invalidate that window if needed. */
00050   if (this->IsType(OT_GOTO_STATION) || this->IsType(OT_GOTO_WAYPOINT)) {
00051     BaseStation *bs = BaseStation::GetIfValid(this->GetDestination());
00052     if (bs != NULL && bs->owner == OWNER_NONE) InvalidateWindowClassesData(WC_STATION_LIST, 0);
00053   }
00054 }
00055 
00060 void Order::Free()
00061 {
00062   this->type  = OT_NOTHING;
00063   this->flags = 0;
00064   this->dest  = 0;
00065   this->next  = NULL;
00066 }
00067 
00072 void Order::MakeGoToStation(StationID destination)
00073 {
00074   this->type = OT_GOTO_STATION;
00075   this->flags = 0;
00076   this->dest = destination;
00077 }
00078 
00088 void Order::MakeGoToDepot(DepotID destination, OrderDepotTypeFlags order, OrderNonStopFlags non_stop_type, OrderDepotActionFlags action, CargoID cargo, byte subtype)
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, subtype);
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 
00164 void Order::SetRefit(CargoID cargo, byte subtype)
00165 {
00166   this->refit_cargo = cargo;
00167   this->refit_subtype = subtype;
00168 }
00169 
00175 bool Order::Equals(const Order &other) const
00176 {
00177   /* In case of go to nearest depot orders we need "only" compare the flags
00178    * with the other and not the nearest depot order bit or the actual
00179    * destination because those get clear/filled in during the order
00180    * evaluation. If we do not do this the order will continuously be seen as
00181    * a different order and it will try to find a "nearest depot" every tick. */
00182   if ((this->IsType(OT_GOTO_DEPOT) && this->type == other.type) &&
00183       ((this->GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0 ||
00184        (other.GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0)) {
00185     return this->GetDepotOrderType() == other.GetDepotOrderType() &&
00186         (this->GetDepotActionType() & ~ODATFB_NEAREST_DEPOT) == (other.GetDepotActionType() & ~ODATFB_NEAREST_DEPOT);
00187   }
00188 
00189   return this->type == other.type && this->flags == other.flags && this->dest == other.dest;
00190 }
00191 
00198 uint32 Order::Pack() const
00199 {
00200   return this->dest << 16 | this->flags << 8 | this->type;
00201 }
00202 
00208 uint16 Order::MapOldOrder() const
00209 {
00210   uint16 order = this->GetType();
00211   switch (this->type) {
00212     case OT_GOTO_STATION:
00213       if (this->GetUnloadType() & OUFB_UNLOAD) SetBit(order, 5);
00214       if (this->GetLoadType() & OLFB_FULL_LOAD) SetBit(order, 6);
00215       if (this->GetNonStopType() & ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS) SetBit(order, 7);
00216       order |= GB(this->GetDestination(), 0, 8) << 8;
00217       break;
00218     case OT_GOTO_DEPOT:
00219       if (!(this->GetDepotOrderType() & ODTFB_PART_OF_ORDERS)) SetBit(order, 6);
00220       SetBit(order, 7);
00221       order |= GB(this->GetDestination(), 0, 8) << 8;
00222       break;
00223     case OT_LOADING:
00224       if (this->GetLoadType() & OLFB_FULL_LOAD) SetBit(order, 6);
00225       break;
00226   }
00227   return order;
00228 }
00229 
00234 Order::Order(uint32 packed)
00235 {
00236   this->type    = (OrderType)GB(packed,  0,  8);
00237   this->flags   = GB(packed,  8,  8);
00238   this->dest    = GB(packed, 16, 16);
00239   this->next    = NULL;
00240   this->refit_cargo   = CT_NO_REFIT;
00241   this->refit_subtype = 0;
00242   this->wait_time     = 0;
00243   this->travel_time   = 0;
00244 }
00245 
00251 void InvalidateVehicleOrder(const Vehicle *v, int data)
00252 {
00253   SetWindowDirty(WC_VEHICLE_VIEW, v->index);
00254 
00255   if (data != 0) {
00256     /* Calls SetDirty() too */
00257     InvalidateWindowData(WC_VEHICLE_ORDERS,    v->index, data);
00258     InvalidateWindowData(WC_VEHICLE_TIMETABLE, v->index, data);
00259     return;
00260   }
00261 
00262   SetWindowDirty(WC_VEHICLE_ORDERS,    v->index);
00263   SetWindowDirty(WC_VEHICLE_TIMETABLE, v->index);
00264 }
00265 
00273 void Order::AssignOrder(const Order &other)
00274 {
00275   this->type  = other.type;
00276   this->flags = other.flags;
00277   this->dest  = other.dest;
00278 
00279   this->refit_cargo   = other.refit_cargo;
00280   this->refit_subtype = other.refit_subtype;
00281 
00282   this->wait_time   = other.wait_time;
00283   this->travel_time = other.travel_time;
00284 }
00285 
00291 void OrderList::Initialize(Order *chain, Vehicle *v)
00292 {
00293   this->first = chain;
00294   this->first_shared = v;
00295 
00296   this->num_orders = 0;
00297   this->num_manual_orders = 0;
00298   this->num_vehicles = 1;
00299   this->timetable_duration = 0;
00300 
00301   for (Order *o = this->first; o != NULL; o = o->next) {
00302     ++this->num_orders;
00303     if (!o->IsType(OT_IMPLICIT)) ++this->num_manual_orders;
00304     this->timetable_duration += o->wait_time + o->travel_time;
00305   }
00306 
00307   for (Vehicle *u = this->first_shared->PreviousShared(); u != NULL; u = u->PreviousShared()) {
00308     ++this->num_vehicles;
00309     this->first_shared = u;
00310   }
00311 
00312   for (const Vehicle *u = v->NextShared(); u != NULL; u = u->NextShared()) ++this->num_vehicles;
00313 }
00314 
00320 void OrderList::FreeChain(bool keep_orderlist)
00321 {
00322   Order *next;
00323   for (Order *o = this->first; o != NULL; o = next) {
00324     next = o->next;
00325     delete o;
00326   }
00327 
00328   if (keep_orderlist) {
00329     this->first = NULL;
00330     this->num_orders = 0;
00331     this->num_manual_orders = 0;
00332     this->timetable_duration = 0;
00333   } else {
00334     delete this;
00335   }
00336 }
00337 
00343 Order *OrderList::GetOrderAt(int index) const
00344 {
00345   if (index < 0) return NULL;
00346 
00347   Order *order = this->first;
00348 
00349   while (order != NULL && index-- > 0) {
00350     order = order->next;
00351   }
00352   return order;
00353 }
00354 
00360 void OrderList::InsertOrderAt(Order *new_order, int index)
00361 {
00362   if (this->first == NULL) {
00363     this->first = new_order;
00364   } else {
00365     if (index == 0) {
00366       /* Insert as first or only order */
00367       new_order->next = this->first;
00368       this->first = new_order;
00369     } else if (index >= this->num_orders) {
00370       /* index is after the last order, add it to the end */
00371       this->GetLastOrder()->next = new_order;
00372     } else {
00373       /* Put the new order in between */
00374       Order *order = this->GetOrderAt(index - 1);
00375       new_order->next = order->next;
00376       order->next = new_order;
00377     }
00378   }
00379   ++this->num_orders;
00380   if (!new_order->IsType(OT_IMPLICIT)) ++this->num_manual_orders;
00381   this->timetable_duration += new_order->wait_time + new_order->travel_time;
00382 
00383   /* We can visit oil rigs and buoys that are not our own. They will be shown in
00384    * the list of stations. So, we need to invalidate that window if needed. */
00385   if (new_order->IsType(OT_GOTO_STATION) || new_order->IsType(OT_GOTO_WAYPOINT)) {
00386     BaseStation *bs = BaseStation::Get(new_order->GetDestination());
00387     if (bs->owner == OWNER_NONE) InvalidateWindowClassesData(WC_STATION_LIST, 0);
00388   }
00389 
00390 }
00391 
00392 
00397 void OrderList::DeleteOrderAt(int index)
00398 {
00399   if (index >= this->num_orders) return;
00400 
00401   Order *to_remove;
00402 
00403   if (index == 0) {
00404     to_remove = this->first;
00405     this->first = to_remove->next;
00406   } else {
00407     Order *prev = GetOrderAt(index - 1);
00408     to_remove = prev->next;
00409     prev->next = to_remove->next;
00410   }
00411   --this->num_orders;
00412   if (!to_remove->IsType(OT_IMPLICIT)) --this->num_manual_orders;
00413   this->timetable_duration -= (to_remove->wait_time + to_remove->travel_time);
00414   delete to_remove;
00415 }
00416 
00422 void OrderList::MoveOrder(int from, int to)
00423 {
00424   if (from >= this->num_orders || to >= this->num_orders || from == to) return;
00425 
00426   Order *moving_one;
00427 
00428   /* Take the moving order out of the pointer-chain */
00429   if (from == 0) {
00430     moving_one = this->first;
00431     this->first = moving_one->next;
00432   } else {
00433     Order *one_before = GetOrderAt(from - 1);
00434     moving_one = one_before->next;
00435     one_before->next = moving_one->next;
00436   }
00437 
00438   /* Insert the moving_order again in the pointer-chain */
00439   if (to == 0) {
00440     moving_one->next = this->first;
00441     this->first = moving_one;
00442   } else {
00443     Order *one_before = GetOrderAt(to - 1);
00444     moving_one->next = one_before->next;
00445     one_before->next = moving_one;
00446   }
00447 }
00448 
00454 void OrderList::RemoveVehicle(Vehicle *v)
00455 {
00456   --this->num_vehicles;
00457   if (v == this->first_shared) this->first_shared = v->NextShared();
00458 }
00459 
00464 bool OrderList::IsVehicleInSharedOrdersList(const Vehicle *v) const
00465 {
00466   for (const Vehicle *v_shared = this->first_shared; v_shared != NULL; v_shared = v_shared->NextShared()) {
00467     if (v_shared == v) return true;
00468   }
00469 
00470   return false;
00471 }
00472 
00478 int OrderList::GetPositionInSharedOrderList(const Vehicle *v) const
00479 {
00480   int count = 0;
00481   for (const Vehicle *v_shared = v->PreviousShared(); v_shared != NULL; v_shared = v_shared->PreviousShared()) count++;
00482   return count;
00483 }
00484 
00489 bool OrderList::IsCompleteTimetable() const
00490 {
00491   for (Order *o = this->first; o != NULL; o = o->next) {
00492     /* Implicit orders are, by definition, not timetabled. */
00493     if (o->IsType(OT_IMPLICIT)) continue;
00494     if (!o->IsCompletelyTimetabled()) return false;
00495   }
00496   return true;
00497 }
00498 
00502 void OrderList::DebugCheckSanity() const
00503 {
00504   VehicleOrderID check_num_orders = 0;
00505   VehicleOrderID check_num_manual_orders = 0;
00506   uint check_num_vehicles = 0;
00507   Ticks check_timetable_duration = 0;
00508 
00509   DEBUG(misc, 6, "Checking OrderList %hu for sanity...", this->index);
00510 
00511   for (const Order *o = this->first; o != NULL; o = o->next) {
00512     ++check_num_orders;
00513     if (!o->IsType(OT_IMPLICIT)) ++check_num_manual_orders;
00514     check_timetable_duration += o->wait_time + o->travel_time;
00515   }
00516   assert(this->num_orders == check_num_orders);
00517   assert(this->num_manual_orders == check_num_manual_orders);
00518   assert(this->timetable_duration == check_timetable_duration);
00519 
00520   for (const Vehicle *v = this->first_shared; v != NULL; v = v->NextShared()) {
00521     ++check_num_vehicles;
00522     assert(v->orders.list == this);
00523   }
00524   assert(this->num_vehicles == check_num_vehicles);
00525   DEBUG(misc, 6, "... detected %u orders (%u manual), %u vehicles, %i ticks",
00526       (uint)this->num_orders, (uint)this->num_manual_orders,
00527       this->num_vehicles, this->timetable_duration);
00528 }
00529 
00537 static inline bool OrderGoesToStation(const Vehicle *v, const Order *o)
00538 {
00539   return o->IsType(OT_GOTO_STATION) ||
00540       (v->type == VEH_AIRCRAFT && o->IsType(OT_GOTO_DEPOT) && !(o->GetDepotActionType() & ODATFB_NEAREST_DEPOT));
00541 }
00542 
00549 static void DeleteOrderWarnings(const Vehicle *v)
00550 {
00551   DeleteVehicleNews(v->index, STR_NEWS_VEHICLE_HAS_TOO_FEW_ORDERS);
00552   DeleteVehicleNews(v->index, STR_NEWS_VEHICLE_HAS_VOID_ORDER);
00553   DeleteVehicleNews(v->index, STR_NEWS_VEHICLE_HAS_DUPLICATE_ENTRY);
00554   DeleteVehicleNews(v->index, STR_NEWS_VEHICLE_HAS_INVALID_ENTRY);
00555 }
00556 
00563 TileIndex Order::GetLocation(const Vehicle *v, bool airport) const
00564 {
00565   switch (this->GetType()) {
00566     case OT_GOTO_WAYPOINT:
00567     case OT_GOTO_STATION:
00568     case OT_IMPLICIT:
00569       if (airport && v->type == VEH_AIRCRAFT) return Station::Get(this->GetDestination())->airport.tile;
00570       return BaseStation::Get(this->GetDestination())->xy;
00571 
00572     case OT_GOTO_DEPOT:
00573       if ((this->GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0) return INVALID_TILE;
00574       return (v->type == VEH_AIRCRAFT) ? Station::Get(this->GetDestination())->xy : Depot::Get(this->GetDestination())->xy;
00575 
00576     default:
00577       return INVALID_TILE;
00578   }
00579 }
00580 
00590 uint GetOrderDistance(const Order *prev, const Order *cur, const Vehicle *v, int conditional_depth)
00591 {
00592   if (cur->IsType(OT_CONDITIONAL)) {
00593     if (conditional_depth > v->GetNumOrders()) return 0;
00594 
00595     conditional_depth++;
00596 
00597     int dist1 = GetOrderDistance(prev, v->GetOrder(cur->GetConditionSkipToOrder()), v, conditional_depth);
00598     int dist2 = GetOrderDistance(prev, cur->next == NULL ? v->orders.list->GetFirstOrder() : cur->next, v, conditional_depth);
00599     return max(dist1, dist2);
00600   }
00601 
00602   TileIndex prev_tile = prev->GetLocation(v, true);
00603   TileIndex cur_tile = cur->GetLocation(v, true);
00604   if (prev_tile == INVALID_TILE || cur_tile == INVALID_TILE) return 0;
00605   return v->type == VEH_AIRCRAFT ? DistanceSquare(prev_tile, cur_tile) : DistanceManhattan(prev_tile, cur_tile);
00606 }
00607 
00621 CommandCost CmdInsertOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00622 {
00623   VehicleID veh          = GB(p1,  0, 20);
00624   VehicleOrderID sel_ord = GB(p1, 20, 8);
00625   Order new_order(p2);
00626 
00627   Vehicle *v = Vehicle::GetIfValid(veh);
00628   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
00629 
00630   CommandCost ret = CheckOwnership(v->owner);
00631   if (ret.Failed()) return ret;
00632 
00633   /* Check if the inserted order is to the correct destination (owner, type),
00634    * and has the correct flags if any */
00635   switch (new_order.GetType()) {
00636     case OT_GOTO_STATION: {
00637       const Station *st = Station::GetIfValid(new_order.GetDestination());
00638       if (st == NULL) return CMD_ERROR;
00639 
00640       if (st->owner != OWNER_NONE) {
00641         CommandCost ret = CheckOwnership(st->owner);
00642         if (ret.Failed()) return ret;
00643       }
00644 
00645       if (!CanVehicleUseStation(v, st)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER);
00646       for (Vehicle *u = v->FirstShared(); u != NULL; u = u->NextShared()) {
00647         if (!CanVehicleUseStation(u, st)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER_SHARED);
00648       }
00649 
00650       /* Non stop only allowed for ground vehicles. */
00651       if (new_order.GetNonStopType() != ONSF_STOP_EVERYWHERE && !v->IsGroundVehicle()) return CMD_ERROR;
00652 
00653       /* Filter invalid load/unload types. */
00654       switch (new_order.GetLoadType()) {
00655         case OLF_LOAD_IF_POSSIBLE: case OLFB_FULL_LOAD: case OLF_FULL_LOAD_ANY: case OLFB_NO_LOAD: break;
00656         default: return CMD_ERROR;
00657       }
00658       switch (new_order.GetUnloadType()) {
00659         case OUF_UNLOAD_IF_POSSIBLE: case OUFB_UNLOAD: case OUFB_TRANSFER: case OUFB_NO_UNLOAD: break;
00660         default: return CMD_ERROR;
00661       }
00662 
00663       /* Filter invalid stop locations */
00664       switch (new_order.GetStopLocation()) {
00665         case OSL_PLATFORM_NEAR_END:
00666         case OSL_PLATFORM_MIDDLE:
00667           if (v->type != VEH_TRAIN) return CMD_ERROR;
00668           /* FALL THROUGH */
00669         case OSL_PLATFORM_FAR_END:
00670           break;
00671 
00672         default:
00673           return CMD_ERROR;
00674       }
00675 
00676       break;
00677     }
00678 
00679     case OT_GOTO_DEPOT: {
00680       if ((new_order.GetDepotActionType() & ODATFB_NEAREST_DEPOT) == 0) {
00681         if (v->type == VEH_AIRCRAFT) {
00682           const Station *st = Station::GetIfValid(new_order.GetDestination());
00683 
00684           if (st == NULL) return CMD_ERROR;
00685 
00686           CommandCost ret = CheckOwnership(st->owner);
00687           if (ret.Failed()) return ret;
00688 
00689           if (!CanVehicleUseStation(v, st) || !st->airport.HasHangar()) {
00690             return CMD_ERROR;
00691           }
00692         } else {
00693           const Depot *dp = Depot::GetIfValid(new_order.GetDestination());
00694 
00695           if (dp == NULL) return CMD_ERROR;
00696 
00697           CommandCost ret = CheckOwnership(GetTileOwner(dp->xy));
00698           if (ret.Failed()) return ret;
00699 
00700           switch (v->type) {
00701             case VEH_TRAIN:
00702               if (!IsRailDepotTile(dp->xy)) return CMD_ERROR;
00703               break;
00704 
00705             case VEH_ROAD:
00706               if (!IsRoadDepotTile(dp->xy)) return CMD_ERROR;
00707               break;
00708 
00709             case VEH_SHIP:
00710               if (!IsShipDepotTile(dp->xy)) return CMD_ERROR;
00711               break;
00712 
00713             default: return CMD_ERROR;
00714           }
00715         }
00716       }
00717 
00718       if (new_order.GetNonStopType() != ONSF_STOP_EVERYWHERE && !v->IsGroundVehicle()) return CMD_ERROR;
00719       if (new_order.GetDepotOrderType() & ~(ODTFB_PART_OF_ORDERS | ((new_order.GetDepotOrderType() & ODTFB_PART_OF_ORDERS) != 0 ? ODTFB_SERVICE : 0))) return CMD_ERROR;
00720       if (new_order.GetDepotActionType() & ~(ODATFB_HALT | ODATFB_NEAREST_DEPOT)) return CMD_ERROR;
00721       if ((new_order.GetDepotOrderType() & ODTFB_SERVICE) && (new_order.GetDepotActionType() & ODATFB_HALT)) return CMD_ERROR;
00722       break;
00723     }
00724 
00725     case OT_GOTO_WAYPOINT: {
00726       const Waypoint *wp = Waypoint::GetIfValid(new_order.GetDestination());
00727       if (wp == NULL) return CMD_ERROR;
00728 
00729       switch (v->type) {
00730         default: return CMD_ERROR;
00731 
00732         case VEH_TRAIN: {
00733           if (!(wp->facilities & FACIL_TRAIN)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER);
00734 
00735           CommandCost ret = CheckOwnership(wp->owner);
00736           if (ret.Failed()) return ret;
00737           break;
00738         }
00739 
00740         case VEH_SHIP:
00741           if (!(wp->facilities & FACIL_DOCK)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER);
00742           if (wp->owner != OWNER_NONE) {
00743             CommandCost ret = CheckOwnership(wp->owner);
00744             if (ret.Failed()) return ret;
00745           }
00746           break;
00747       }
00748 
00749       /* Order flags can be any of the following for waypoints:
00750        * [non-stop]
00751        * non-stop orders (if any) are only valid for trains */
00752       if (new_order.GetNonStopType() != ONSF_STOP_EVERYWHERE && v->type != VEH_TRAIN) return CMD_ERROR;
00753       break;
00754     }
00755 
00756     case OT_CONDITIONAL: {
00757       VehicleOrderID skip_to = new_order.GetConditionSkipToOrder();
00758       if (skip_to != 0 && skip_to >= v->GetNumOrders()) return CMD_ERROR; // Always allow jumping to the first (even when there is no order).
00759       if (new_order.GetConditionVariable() >= OCV_END) return CMD_ERROR;
00760 
00761       OrderConditionComparator occ = new_order.GetConditionComparator();
00762       if (occ >= OCC_END) return CMD_ERROR;
00763       switch (new_order.GetConditionVariable()) {
00764         case OCV_REQUIRES_SERVICE:
00765           if (occ != OCC_IS_TRUE && occ != OCC_IS_FALSE) return CMD_ERROR;
00766           break;
00767 
00768         case OCV_UNCONDITIONALLY:
00769           if (occ != OCC_EQUALS) return CMD_ERROR;
00770           if (new_order.GetConditionValue() != 0) return CMD_ERROR;
00771           break;
00772 
00773         case OCV_LOAD_PERCENTAGE:
00774         case OCV_RELIABILITY:
00775           if (new_order.GetConditionValue() > 100) return CMD_ERROR;
00776           /* FALL THROUGH */
00777         default:
00778           if (occ == OCC_IS_TRUE || occ == OCC_IS_FALSE) return CMD_ERROR;
00779           break;
00780       }
00781       break;
00782     }
00783 
00784     default: return CMD_ERROR;
00785   }
00786 
00787   if (sel_ord > v->GetNumOrders()) return CMD_ERROR;
00788 
00789   if (v->GetNumOrders() >= MAX_VEH_ORDER_ID) return_cmd_error(STR_ERROR_TOO_MANY_ORDERS);
00790   if (!Order::CanAllocateItem()) return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
00791   if (v->orders.list == NULL && !OrderList::CanAllocateItem()) return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
00792 
00793   if (v->type == VEH_SHIP && _settings_game.pf.pathfinder_for_ships != VPF_NPF) {
00794     /* Make sure the new destination is not too far away from the previous */
00795     const Order *prev = NULL;
00796     uint n = 0;
00797 
00798     /* Find the last goto station or depot order before the insert location.
00799      * If the order is to be inserted at the beginning of the order list this
00800      * finds the last order in the list. */
00801     const Order *o;
00802     FOR_VEHICLE_ORDERS(v, o) {
00803       switch (o->GetType()) {
00804         case OT_GOTO_STATION:
00805         case OT_GOTO_DEPOT:
00806         case OT_GOTO_WAYPOINT:
00807           prev = o;
00808           break;
00809 
00810         default: break;
00811       }
00812       if (++n == sel_ord && prev != NULL) break;
00813     }
00814     if (prev != NULL) {
00815       uint dist = GetOrderDistance(prev, &new_order, v);
00816       if (dist >= 130) {
00817         return_cmd_error(STR_ERROR_TOO_FAR_FROM_PREVIOUS_DESTINATION);
00818       }
00819     }
00820   }
00821 
00822   if (flags & DC_EXEC) {
00823     Order *new_o = new Order();
00824     new_o->AssignOrder(new_order);
00825     InsertOrder(v, new_o, sel_ord);
00826   }
00827 
00828   return CommandCost();
00829 }
00830 
00837 void InsertOrder(Vehicle *v, Order *new_o, VehicleOrderID sel_ord)
00838 {
00839   /* Create new order and link in list */
00840   if (v->orders.list == NULL) {
00841     v->orders.list = new OrderList(new_o, v);
00842   } else {
00843     v->orders.list->InsertOrderAt(new_o, sel_ord);
00844   }
00845 
00846   Vehicle *u = v->FirstShared();
00847   DeleteOrderWarnings(u);
00848   for (; u != NULL; u = u->NextShared()) {
00849     assert(v->orders.list == u->orders.list);
00850 
00851     /* If there is added an order before the current one, we need
00852      * to update the selected order. We do not change implicit/real order indices though.
00853      * If the new order is between the current implicit order and real order, the implicit order will
00854      * later skip the inserted order. */
00855     if (sel_ord <= u->cur_real_order_index) {
00856       uint cur = u->cur_real_order_index + 1;
00857       /* Check if we don't go out of bound */
00858       if (cur < u->GetNumOrders()) {
00859         u->cur_real_order_index = cur;
00860       }
00861     }
00862     if (sel_ord == u->cur_implicit_order_index && u->IsGroundVehicle()) {
00863       /* We are inserting an order just before the current implicit order.
00864        * We do not know whether we will reach current implicit or the newly inserted order first.
00865        * So, disable creation of implicit orders until we are on track again. */
00866       uint16 &gv_flags = u->GetGroundVehicleFlags();
00867       SetBit(gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS);
00868     }
00869     if (sel_ord <= u->cur_implicit_order_index) {
00870       uint cur = u->cur_implicit_order_index + 1;
00871       /* Check if we don't go out of bound */
00872       if (cur < u->GetNumOrders()) {
00873         u->cur_implicit_order_index = cur;
00874       }
00875     }
00876     /* Update any possible open window of the vehicle */
00877     InvalidateVehicleOrder(u, INVALID_VEH_ORDER_ID | (sel_ord << 8));
00878   }
00879 
00880   /* As we insert an order, the order to skip to will be 'wrong'. */
00881   VehicleOrderID cur_order_id = 0;
00882   Order *order;
00883   FOR_VEHICLE_ORDERS(v, order) {
00884     if (order->IsType(OT_CONDITIONAL)) {
00885       VehicleOrderID order_id = order->GetConditionSkipToOrder();
00886       if (order_id >= sel_ord) {
00887         order->SetConditionSkipToOrder(order_id + 1);
00888       }
00889       if (order_id == cur_order_id) {
00890         order->SetConditionSkipToOrder((order_id + 1) % v->GetNumOrders());
00891       }
00892     }
00893     cur_order_id++;
00894   }
00895 
00896   /* Make sure to rebuild the whole list */
00897   InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
00898 }
00899 
00905 static CommandCost DecloneOrder(Vehicle *dst, DoCommandFlag flags)
00906 {
00907   if (flags & DC_EXEC) {
00908     DeleteVehicleOrders(dst);
00909     InvalidateVehicleOrder(dst, -1);
00910     InvalidateWindowClassesData(GetWindowClassForVehicleType(dst->type), 0);
00911   }
00912   return CommandCost();
00913 }
00914 
00924 CommandCost CmdDeleteOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00925 {
00926   VehicleID veh_id = GB(p1, 0, 20);
00927   VehicleOrderID sel_ord = GB(p2, 0, 8);
00928 
00929   Vehicle *v = Vehicle::GetIfValid(veh_id);
00930 
00931   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
00932 
00933   CommandCost ret = CheckOwnership(v->owner);
00934   if (ret.Failed()) return ret;
00935 
00936   /* If we did not select an order, we maybe want to de-clone the orders */
00937   if (sel_ord >= v->GetNumOrders()) return DecloneOrder(v, flags);
00938 
00939   if (v->GetOrder(sel_ord) == NULL) return CMD_ERROR;
00940 
00941   if (flags & DC_EXEC) DeleteOrder(v, sel_ord);
00942   return CommandCost();
00943 }
00944 
00949 static void CancelLoadingDueToDeletedOrder(Vehicle *v)
00950 {
00951   assert(v->current_order.IsType(OT_LOADING));
00952   /* NON-stop flag is misused to see if a train is in a station that is
00953    * on his order list or not */
00954   v->current_order.SetNonStopType(ONSF_STOP_EVERYWHERE);
00955   /* When full loading, "cancel" that order so the vehicle doesn't
00956    * stay indefinitely at this station anymore. */
00957   if (v->current_order.GetLoadType() & OLFB_FULL_LOAD) v->current_order.SetLoadType(OLF_LOAD_IF_POSSIBLE);
00958 }
00959 
00965 void DeleteOrder(Vehicle *v, VehicleOrderID sel_ord)
00966 {
00967   v->orders.list->DeleteOrderAt(sel_ord);
00968 
00969   Vehicle *u = v->FirstShared();
00970   DeleteOrderWarnings(u);
00971   for (; u != NULL; u = u->NextShared()) {
00972     assert(v->orders.list == u->orders.list);
00973 
00974     if (sel_ord == u->cur_real_order_index && u->current_order.IsType(OT_LOADING)) {
00975       CancelLoadingDueToDeletedOrder(u);
00976     }
00977 
00978     if (sel_ord < u->cur_real_order_index) {
00979       u->cur_real_order_index--;
00980     } else if (sel_ord == u->cur_real_order_index) {
00981       u->UpdateRealOrderIndex();
00982     }
00983 
00984     if (sel_ord < u->cur_implicit_order_index) {
00985       u->cur_implicit_order_index--;
00986     } else if (sel_ord == u->cur_implicit_order_index) {
00987       /* Make sure the index is valid */
00988       if (u->cur_implicit_order_index >= u->GetNumOrders()) u->cur_implicit_order_index = 0;
00989 
00990       /* Skip non-implicit orders for the implicit-order-index (e.g. if the current implicit order was deleted */
00991       while (u->cur_implicit_order_index != u->cur_real_order_index && !u->GetOrder(u->cur_implicit_order_index)->IsType(OT_IMPLICIT)) {
00992         u->cur_implicit_order_index++;
00993         if (u->cur_implicit_order_index >= u->GetNumOrders()) u->cur_implicit_order_index = 0;
00994       }
00995     }
00996 
00997     /* Update any possible open window of the vehicle */
00998     InvalidateVehicleOrder(u, sel_ord | (INVALID_VEH_ORDER_ID << 8));
00999   }
01000 
01001   /* As we delete an order, the order to skip to will be 'wrong'. */
01002   VehicleOrderID cur_order_id = 0;
01003   Order *order = NULL;
01004   FOR_VEHICLE_ORDERS(v, order) {
01005     if (order->IsType(OT_CONDITIONAL)) {
01006       VehicleOrderID order_id = order->GetConditionSkipToOrder();
01007       if (order_id >= sel_ord) {
01008         order_id = max(order_id - 1, 0);
01009       }
01010       if (order_id == cur_order_id) {
01011         order_id = (order_id + 1) % v->GetNumOrders();
01012       }
01013       order->SetConditionSkipToOrder(order_id);
01014     }
01015     cur_order_id++;
01016   }
01017 
01018   InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
01019 }
01020 
01030 CommandCost CmdSkipToOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01031 {
01032   VehicleID veh_id = GB(p1, 0, 20);
01033   VehicleOrderID sel_ord = GB(p2, 0, 8);
01034 
01035   Vehicle *v = Vehicle::GetIfValid(veh_id);
01036 
01037   if (v == NULL || !v->IsPrimaryVehicle() || sel_ord == v->cur_implicit_order_index || sel_ord >= v->GetNumOrders() || v->GetNumOrders() < 2) return CMD_ERROR;
01038 
01039   CommandCost ret = CheckOwnership(v->owner);
01040   if (ret.Failed()) return ret;
01041 
01042   if (flags & DC_EXEC) {
01043     v->cur_implicit_order_index = v->cur_real_order_index = sel_ord;
01044     v->UpdateRealOrderIndex();
01045 
01046     if (v->current_order.IsType(OT_LOADING)) v->LeaveStation();
01047 
01048     InvalidateVehicleOrder(v, -2);
01049   }
01050 
01051   /* We have an aircraft/ship, they have a mini-schedule, so update them all */
01052   if (v->type == VEH_AIRCRAFT) SetWindowClassesDirty(WC_AIRCRAFT_LIST);
01053   if (v->type == VEH_SHIP) SetWindowClassesDirty(WC_SHIPS_LIST);
01054 
01055   return CommandCost();
01056 }
01057 
01071 CommandCost CmdMoveOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01072 {
01073   VehicleID veh = GB(p1, 0, 20);
01074   VehicleOrderID moving_order = GB(p2,  0, 16);
01075   VehicleOrderID target_order = GB(p2, 16, 16);
01076 
01077   Vehicle *v = Vehicle::GetIfValid(veh);
01078   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
01079 
01080   CommandCost ret = CheckOwnership(v->owner);
01081   if (ret.Failed()) return ret;
01082 
01083   /* Don't make senseless movements */
01084   if (moving_order >= v->GetNumOrders() || target_order >= v->GetNumOrders() ||
01085       moving_order == target_order || v->GetNumOrders() <= 1) return CMD_ERROR;
01086 
01087   Order *moving_one = v->GetOrder(moving_order);
01088   /* Don't move an empty order */
01089   if (moving_one == NULL) return CMD_ERROR;
01090 
01091   if (flags & DC_EXEC) {
01092     v->orders.list->MoveOrder(moving_order, target_order);
01093 
01094     /* Update shared list */
01095     Vehicle *u = v->FirstShared();
01096 
01097     DeleteOrderWarnings(u);
01098 
01099     for (; u != NULL; u = u->NextShared()) {
01100       /* Update the current order.
01101        * There are multiple ways to move orders, which result in cur_implicit_order_index
01102        * and cur_real_order_index to not longer make any sense. E.g. moving another
01103        * real order between them.
01104        *
01105        * Basically one could choose to preserve either of them, but not both.
01106        * While both ways are suitable in this or that case from a human point of view, neither
01107        * of them makes really sense.
01108        * However, from an AI point of view, preserving cur_real_order_index is the most
01109        * predictable and transparent behaviour.
01110        *
01111        * With that decision it basically does not matter what we do to cur_implicit_order_index.
01112        * If we change orders between the implict- and real-index, the implicit orders are mostly likely
01113        * completely out-dated anyway. So, keep it simple and just keep cur_implicit_order_index as well.
01114        * The worst which can happen is that a lot of implicit orders are removed when reaching current_order.
01115        */
01116       if (u->cur_real_order_index == moving_order) {
01117         u->cur_real_order_index = target_order;
01118       } else if (u->cur_real_order_index > moving_order && u->cur_real_order_index <= target_order) {
01119         u->cur_real_order_index--;
01120       } else if (u->cur_real_order_index < moving_order && u->cur_real_order_index >= target_order) {
01121         u->cur_real_order_index++;
01122       }
01123 
01124       if (u->cur_implicit_order_index == moving_order) {
01125         u->cur_implicit_order_index = target_order;
01126       } else if (u->cur_implicit_order_index > moving_order && u->cur_implicit_order_index <= target_order) {
01127         u->cur_implicit_order_index--;
01128       } else if (u->cur_implicit_order_index < moving_order && u->cur_implicit_order_index >= target_order) {
01129         u->cur_implicit_order_index++;
01130       }
01131 
01132       assert(v->orders.list == u->orders.list);
01133       /* Update any possible open window of the vehicle */
01134       InvalidateVehicleOrder(u, moving_order | (target_order << 8));
01135     }
01136 
01137     /* As we move an order, the order to skip to will be 'wrong'. */
01138     Order *order;
01139     FOR_VEHICLE_ORDERS(v, order) {
01140       if (order->IsType(OT_CONDITIONAL)) {
01141         VehicleOrderID order_id = order->GetConditionSkipToOrder();
01142         if (order_id == moving_order) {
01143           order_id = target_order;
01144         } else if (order_id > moving_order && order_id <= target_order) {
01145           order_id--;
01146         } else if (order_id < moving_order && order_id >= target_order) {
01147           order_id++;
01148         }
01149         order->SetConditionSkipToOrder(order_id);
01150       }
01151     }
01152 
01153     /* Make sure to rebuild the whole list */
01154     InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
01155   }
01156 
01157   return CommandCost();
01158 }
01159 
01175 CommandCost CmdModifyOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01176 {
01177   VehicleOrderID sel_ord = GB(p1, 20,  8);
01178   VehicleID veh          = GB(p1,  0, 20);
01179   ModifyOrderFlags mof   = Extract<ModifyOrderFlags, 0, 4>(p2);
01180   uint16 data            = GB(p2,  4, 11);
01181 
01182   if (mof >= MOF_END) return CMD_ERROR;
01183 
01184   Vehicle *v = Vehicle::GetIfValid(veh);
01185   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
01186 
01187   CommandCost ret = CheckOwnership(v->owner);
01188   if (ret.Failed()) return ret;
01189 
01190   /* Is it a valid order? */
01191   if (sel_ord >= v->GetNumOrders()) return CMD_ERROR;
01192 
01193   Order *order = v->GetOrder(sel_ord);
01194   switch (order->GetType()) {
01195     case OT_GOTO_STATION:
01196       if (mof == MOF_COND_VARIABLE || mof == MOF_COND_COMPARATOR || mof == MOF_DEPOT_ACTION || mof == MOF_COND_VALUE) return CMD_ERROR;
01197       break;
01198 
01199     case OT_GOTO_DEPOT:
01200       if (mof != MOF_NON_STOP && mof != MOF_DEPOT_ACTION) return CMD_ERROR;
01201       break;
01202 
01203     case OT_GOTO_WAYPOINT:
01204       if (mof != MOF_NON_STOP) return CMD_ERROR;
01205       break;
01206 
01207     case OT_CONDITIONAL:
01208       if (mof != MOF_COND_VARIABLE && mof != MOF_COND_COMPARATOR && mof != MOF_COND_VALUE && mof != MOF_COND_DESTINATION) return CMD_ERROR;
01209       break;
01210 
01211     default:
01212       return CMD_ERROR;
01213   }
01214 
01215   switch (mof) {
01216     default: NOT_REACHED();
01217 
01218     case MOF_NON_STOP:
01219       if (!v->IsGroundVehicle()) return CMD_ERROR;
01220       if (data >= ONSF_END) return CMD_ERROR;
01221       if (data == order->GetNonStopType()) return CMD_ERROR;
01222       break;
01223 
01224     case MOF_STOP_LOCATION:
01225       if (v->type != VEH_TRAIN) return CMD_ERROR;
01226       if (data >= OSL_END) return CMD_ERROR;
01227       break;
01228 
01229     case MOF_UNLOAD:
01230       if ((data & ~(OUFB_UNLOAD | OUFB_TRANSFER | OUFB_NO_UNLOAD)) != 0) return CMD_ERROR;
01231       /* Unload and no-unload are mutual exclusive and so are transfer and no unload. */
01232       if (data != 0 && ((data & (OUFB_UNLOAD | OUFB_TRANSFER)) != 0) == ((data & OUFB_NO_UNLOAD) != 0)) return CMD_ERROR;
01233       if (data == order->GetUnloadType()) return CMD_ERROR;
01234       break;
01235 
01236     case MOF_LOAD:
01237       if (data > OLFB_NO_LOAD || data == 1) return CMD_ERROR;
01238       if (data == order->GetLoadType()) return CMD_ERROR;
01239       break;
01240 
01241     case MOF_DEPOT_ACTION:
01242       if (data >= DA_END) return CMD_ERROR;
01243       break;
01244 
01245     case MOF_COND_VARIABLE:
01246       if (data >= OCV_END) return CMD_ERROR;
01247       break;
01248 
01249     case MOF_COND_COMPARATOR:
01250       if (data >= OCC_END) return CMD_ERROR;
01251       switch (order->GetConditionVariable()) {
01252         case OCV_UNCONDITIONALLY: return CMD_ERROR;
01253 
01254         case OCV_REQUIRES_SERVICE:
01255           if (data != OCC_IS_TRUE && data != OCC_IS_FALSE) return CMD_ERROR;
01256           break;
01257 
01258         default:
01259           if (data == OCC_IS_TRUE || data == OCC_IS_FALSE) return CMD_ERROR;
01260           break;
01261       }
01262       break;
01263 
01264     case MOF_COND_VALUE:
01265       switch (order->GetConditionVariable()) {
01266         case OCV_UNCONDITIONALLY: return CMD_ERROR;
01267 
01268         case OCV_LOAD_PERCENTAGE:
01269         case OCV_RELIABILITY:
01270           if (data > 100) return CMD_ERROR;
01271           break;
01272 
01273         default:
01274           if (data > 2047) return CMD_ERROR;
01275           break;
01276       }
01277       break;
01278 
01279     case MOF_COND_DESTINATION:
01280       if (data >= v->GetNumOrders()) return CMD_ERROR;
01281       break;
01282   }
01283 
01284   if (flags & DC_EXEC) {
01285     switch (mof) {
01286       case MOF_NON_STOP:
01287         order->SetNonStopType((OrderNonStopFlags)data);
01288         if (data & ONSF_NO_STOP_AT_DESTINATION_STATION) order->SetRefit(CT_NO_REFIT);
01289         break;
01290 
01291       case MOF_STOP_LOCATION:
01292         order->SetStopLocation((OrderStopLocation)data);
01293         break;
01294 
01295       case MOF_UNLOAD:
01296         order->SetUnloadType((OrderUnloadFlags)data);
01297         break;
01298 
01299       case MOF_LOAD:
01300         order->SetLoadType((OrderLoadFlags)data);
01301         if (data & OLFB_NO_LOAD) order->SetRefit(CT_NO_REFIT);
01302         break;
01303 
01304       case MOF_DEPOT_ACTION: {
01305         switch (data) {
01306           case DA_ALWAYS_GO:
01307             order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() & ~ODTFB_SERVICE));
01308             order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_HALT));
01309             break;
01310 
01311           case DA_SERVICE:
01312             order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() | ODTFB_SERVICE));
01313             order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_HALT));
01314             order->SetRefit(CT_NO_REFIT);
01315             break;
01316 
01317           case DA_STOP:
01318             order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() & ~ODTFB_SERVICE));
01319             order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() | ODATFB_HALT));
01320             order->SetRefit(CT_NO_REFIT);
01321             break;
01322 
01323           default:
01324             NOT_REACHED();
01325         }
01326         break;
01327       }
01328 
01329       case MOF_COND_VARIABLE: {
01330         order->SetConditionVariable((OrderConditionVariable)data);
01331 
01332         OrderConditionComparator occ = order->GetConditionComparator();
01333         switch (order->GetConditionVariable()) {
01334           case OCV_UNCONDITIONALLY:
01335             order->SetConditionComparator(OCC_EQUALS);
01336             order->SetConditionValue(0);
01337             break;
01338 
01339           case OCV_REQUIRES_SERVICE:
01340             if (occ != OCC_IS_TRUE && occ != OCC_IS_FALSE) order->SetConditionComparator(OCC_IS_TRUE);
01341             break;
01342 
01343           case OCV_LOAD_PERCENTAGE:
01344           case OCV_RELIABILITY:
01345             if (order->GetConditionValue() > 100) order->SetConditionValue(100);
01346             /* FALL THROUGH */
01347           default:
01348             if (occ == OCC_IS_TRUE || occ == OCC_IS_FALSE) order->SetConditionComparator(OCC_EQUALS);
01349             break;
01350         }
01351         break;
01352       }
01353 
01354       case MOF_COND_COMPARATOR:
01355         order->SetConditionComparator((OrderConditionComparator)data);
01356         break;
01357 
01358       case MOF_COND_VALUE:
01359         order->SetConditionValue(data);
01360         break;
01361 
01362       case MOF_COND_DESTINATION:
01363         order->SetConditionSkipToOrder(data);
01364         break;
01365 
01366       default: NOT_REACHED();
01367     }
01368 
01369     /* Update the windows and full load flags, also for vehicles that share the same order list */
01370     Vehicle *u = v->FirstShared();
01371     DeleteOrderWarnings(u);
01372     for (; u != NULL; u = u->NextShared()) {
01373       /* Toggle u->current_order "Full load" flag if it changed.
01374        * However, as the same flag is used for depot orders, check
01375        * whether we are not going to a depot as there are three
01376        * cases where the full load flag can be active and only
01377        * one case where the flag is used for depot orders. In the
01378        * other cases for the OrderTypeByte the flags are not used,
01379        * so do not care and those orders should not be active
01380        * when this function is called.
01381        */
01382       if (sel_ord == u->cur_real_order_index &&
01383           (u->current_order.IsType(OT_GOTO_STATION) || u->current_order.IsType(OT_LOADING)) &&
01384           u->current_order.GetLoadType() != order->GetLoadType()) {
01385         u->current_order.SetLoadType(order->GetLoadType());
01386       }
01387       InvalidateVehicleOrder(u, -2);
01388     }
01389   }
01390 
01391   return CommandCost();
01392 }
01393 
01400 bool CheckAircraftOrderDistance(const Aircraft *v, const Order *first)
01401 {
01402   if (first == NULL || v->acache.cached_max_range == 0) return true;
01403 
01404   /* Iterate over all orders to check the distance between all
01405    * 'goto' orders and their respective next order (of any type). */
01406   for (const Order *o = first; o != NULL; o = o->next) {
01407     switch (o->GetType()) {
01408       case OT_GOTO_STATION:
01409       case OT_GOTO_DEPOT:
01410       case OT_GOTO_WAYPOINT:
01411         /* If we don't have a next order, we've reached the end and must check the first order instead. */
01412         if (GetOrderDistance(o, o->next != NULL ? o->next : first, v) > v->acache.cached_max_range_sqr) return false;
01413         break;
01414 
01415       default: break;
01416     }
01417   }
01418 
01419   return true;
01420 }
01421 
01433 CommandCost CmdCloneOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01434 {
01435   VehicleID veh_src = GB(p2, 0, 20);
01436   VehicleID veh_dst = GB(p1, 0, 20);
01437 
01438   Vehicle *dst = Vehicle::GetIfValid(veh_dst);
01439   if (dst == NULL || !dst->IsPrimaryVehicle()) return CMD_ERROR;
01440 
01441   CommandCost ret = CheckOwnership(dst->owner);
01442   if (ret.Failed()) return ret;
01443 
01444   switch (GB(p1, 30, 2)) {
01445     case CO_SHARE: {
01446       Vehicle *src = Vehicle::GetIfValid(veh_src);
01447 
01448       /* Sanity checks */
01449       if (src == NULL || !src->IsPrimaryVehicle() || dst->type != src->type || dst == src) return CMD_ERROR;
01450 
01451       CommandCost ret = CheckOwnership(src->owner);
01452       if (ret.Failed()) return ret;
01453 
01454       /* Trucks can't share orders with busses (and visa versa) */
01455       if (src->type == VEH_ROAD && RoadVehicle::From(src)->IsBus() != RoadVehicle::From(dst)->IsBus()) {
01456         return CMD_ERROR;
01457       }
01458 
01459       /* Is the vehicle already in the shared list? */
01460       if (src->FirstShared() == dst->FirstShared()) return CMD_ERROR;
01461 
01462       const Order *order;
01463 
01464       FOR_VEHICLE_ORDERS(src, order) {
01465         if (OrderGoesToStation(dst, order) &&
01466             !CanVehicleUseStation(dst, Station::Get(order->GetDestination()))) {
01467           return_cmd_error(STR_ERROR_CAN_T_COPY_SHARE_ORDER);
01468         }
01469       }
01470 
01471       /* Check for aircraft range limits. */
01472       if (dst->type == VEH_AIRCRAFT && !CheckAircraftOrderDistance(Aircraft::From(dst), src->GetFirstOrder())) {
01473         return_cmd_error(STR_ERROR_AIRCRAFT_NOT_ENOUGH_RANGE);
01474       }
01475 
01476       if (src->orders.list == NULL && !OrderList::CanAllocateItem()) {
01477         return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
01478       }
01479 
01480       if (flags & DC_EXEC) {
01481         /* If the destination vehicle had a OrderList, destroy it.
01482          * We only reset the order indices, if the new orders are obviously different.
01483          * (We mainly do this to keep the order indices valid and in range.) */
01484         DeleteVehicleOrders(dst, false, dst->GetNumOrders() != src->GetNumOrders());
01485 
01486         dst->orders.list = src->orders.list;
01487 
01488         /* Link this vehicle in the shared-list */
01489         dst->AddToShared(src);
01490 
01491         InvalidateVehicleOrder(dst, -1);
01492         InvalidateVehicleOrder(src, -2);
01493 
01494         InvalidateWindowClassesData(GetWindowClassForVehicleType(dst->type), 0);
01495       }
01496       break;
01497     }
01498 
01499     case CO_COPY: {
01500       Vehicle *src = Vehicle::GetIfValid(veh_src);
01501 
01502       /* Sanity checks */
01503       if (src == NULL || !src->IsPrimaryVehicle() || dst->type != src->type || dst == src) return CMD_ERROR;
01504 
01505       CommandCost ret = CheckOwnership(src->owner);
01506       if (ret.Failed()) return ret;
01507 
01508       /* Trucks can't copy all the orders from busses (and visa versa),
01509        * and neither can helicopters and aircarft. */
01510       const Order *order;
01511       FOR_VEHICLE_ORDERS(src, order) {
01512         if (OrderGoesToStation(dst, order) &&
01513             !CanVehicleUseStation(dst, Station::Get(order->GetDestination()))) {
01514           return_cmd_error(STR_ERROR_CAN_T_COPY_SHARE_ORDER);
01515         }
01516       }
01517 
01518       /* Check for aircraft range limits. */
01519       if (dst->type == VEH_AIRCRAFT && !CheckAircraftOrderDistance(Aircraft::From(dst), src->GetFirstOrder())) {
01520         return_cmd_error(STR_ERROR_AIRCRAFT_NOT_ENOUGH_RANGE);
01521       }
01522 
01523       /* make sure there are orders available */
01524       int delta = dst->IsOrderListShared() ? src->GetNumOrders() + 1 : src->GetNumOrders() - dst->GetNumOrders();
01525       if (!Order::CanAllocateItem(delta) ||
01526           ((dst->orders.list == NULL || dst->IsOrderListShared()) && !OrderList::CanAllocateItem())) {
01527         return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
01528       }
01529 
01530       if (flags & DC_EXEC) {
01531         const Order *order;
01532         Order *first = NULL;
01533         Order **order_dst;
01534 
01535         /* If the destination vehicle had an order list, destroy the chain but keep the OrderList.
01536          * We only reset the order indices, if the new orders are obviously different.
01537          * (We mainly do this to keep the order indices valid and in range.) */
01538         DeleteVehicleOrders(dst, true, dst->GetNumOrders() != src->GetNumOrders());
01539 
01540         order_dst = &first;
01541         FOR_VEHICLE_ORDERS(src, order) {
01542           *order_dst = new Order();
01543           (*order_dst)->AssignOrder(*order);
01544           order_dst = &(*order_dst)->next;
01545         }
01546         if (dst->orders.list == NULL) {
01547           dst->orders.list = new OrderList(first, dst);
01548         } else {
01549           assert(dst->orders.list->GetFirstOrder() == NULL);
01550           assert(!dst->orders.list->IsShared());
01551           delete dst->orders.list;
01552           assert(OrderList::CanAllocateItem());
01553           dst->orders.list = new OrderList(first, dst);
01554         }
01555 
01556         InvalidateVehicleOrder(dst, -1);
01557 
01558         InvalidateWindowClassesData(GetWindowClassForVehicleType(dst->type), 0);
01559       }
01560       break;
01561     }
01562 
01563     case CO_UNSHARE: return DecloneOrder(dst, flags);
01564     default: return CMD_ERROR;
01565   }
01566 
01567   return CommandCost();
01568 }
01569 
01582 CommandCost CmdOrderRefit(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01583 {
01584   VehicleID veh = GB(p1, 0, 20);
01585   VehicleOrderID order_number  = GB(p2, 16, 8);
01586   CargoID cargo = GB(p2, 0, 8);
01587   byte subtype  = GB(p2, 8, 8);
01588 
01589   if (cargo >= NUM_CARGO && cargo != CT_NO_REFIT && cargo != CT_AUTO_REFIT) return CMD_ERROR;
01590 
01591   const Vehicle *v = Vehicle::GetIfValid(veh);
01592   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
01593 
01594   CommandCost ret = CheckOwnership(v->owner);
01595   if (ret.Failed()) return ret;
01596 
01597   Order *order = v->GetOrder(order_number);
01598   if (order == NULL) return CMD_ERROR;
01599 
01600   /* Automatic refit cargo is only supported for goto station orders. */
01601   if (cargo == CT_AUTO_REFIT && !order->IsType(OT_GOTO_STATION)) return CMD_ERROR;
01602 
01603   if (flags & DC_EXEC) {
01604     order->SetRefit(cargo, subtype);
01605 
01606     /* Make the depot order an 'always go' order. */
01607     if (cargo != CT_NO_REFIT) {
01608       order->SetDepotOrderType((OrderDepotTypeFlags)(order->GetDepotOrderType() & ~ODTFB_SERVICE));
01609       order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_HALT));
01610     }
01611 
01612     for (Vehicle *u = v->FirstShared(); u != NULL; u = u->NextShared()) {
01613       /* Update any possible open window of the vehicle */
01614       InvalidateVehicleOrder(u, -2);
01615 
01616       /* If the vehicle already got the current depot set as current order, then update current order as well */
01617       if (u->cur_real_order_index == order_number && (u->current_order.GetDepotOrderType() & ODTFB_PART_OF_ORDERS)) {
01618         u->current_order.SetRefit(cargo, subtype);
01619       }
01620     }
01621   }
01622 
01623   return CommandCost();
01624 }
01625 
01626 
01632 void CheckOrders(const Vehicle *v)
01633 {
01634   /* Does the user wants us to check things? */
01635   if (_settings_client.gui.order_review_system == 0) return;
01636 
01637   /* Do nothing for crashed vehicles */
01638   if (v->vehstatus & VS_CRASHED) return;
01639 
01640   /* Do nothing for stopped vehicles if setting is '1' */
01641   if (_settings_client.gui.order_review_system == 1 && (v->vehstatus & VS_STOPPED)) return;
01642 
01643   /* do nothing we we're not the first vehicle in a share-chain */
01644   if (v->FirstShared() != v) return;
01645 
01646   /* Only check every 20 days, so that we don't flood the message log */
01647   if (v->owner == _local_company && v->day_counter % 20 == 0) {
01648     int n_st, problem_type = -1;
01649     const Order *order;
01650     int message = 0;
01651 
01652     /* Check the order list */
01653     n_st = 0;
01654 
01655     FOR_VEHICLE_ORDERS(v, order) {
01656       /* Dummy order? */
01657       if (order->IsType(OT_DUMMY)) {
01658         problem_type = 1;
01659         break;
01660       }
01661       /* Does station have a load-bay for this vehicle? */
01662       if (order->IsType(OT_GOTO_STATION)) {
01663         const Station *st = Station::Get(order->GetDestination());
01664 
01665         n_st++;
01666         if (!CanVehicleUseStation(v, st)) problem_type = 3;
01667       }
01668     }
01669 
01670     /* Check if the last and the first order are the same */
01671     if (v->GetNumOrders() > 1) {
01672       const Order *last = v->GetLastOrder();
01673 
01674       if (v->orders.list->GetFirstOrder()->Equals(*last)) {
01675         problem_type = 2;
01676       }
01677     }
01678 
01679     /* Do we only have 1 station in our order list? */
01680     if (n_st < 2 && problem_type == -1) problem_type = 0;
01681 
01682 #ifndef NDEBUG
01683     if (v->orders.list != NULL) v->orders.list->DebugCheckSanity();
01684 #endif
01685 
01686     /* We don't have a problem */
01687     if (problem_type < 0) return;
01688 
01689     message = STR_NEWS_VEHICLE_HAS_TOO_FEW_ORDERS + problem_type;
01690     //DEBUG(misc, 3, "Triggered News Item for vehicle %d", v->index);
01691 
01692     SetDParam(0, v->index);
01693     AddVehicleNewsItem(
01694       message,
01695       NS_ADVICE,
01696       v->index
01697     );
01698   }
01699 }
01700 
01706 void RemoveOrderFromAllVehicles(OrderType type, DestinationID destination)
01707 {
01708   Vehicle *v;
01709 
01710   /* Aircraft have StationIDs for depot orders and never use DepotIDs
01711    * This fact is handled specially below
01712    */
01713 
01714   /* Go through all vehicles */
01715   FOR_ALL_VEHICLES(v) {
01716     Order *order;
01717 
01718     order = &v->current_order;
01719     if ((v->type == VEH_AIRCRAFT && order->IsType(OT_GOTO_DEPOT) ? OT_GOTO_STATION : order->GetType()) == type &&
01720         v->current_order.GetDestination() == destination) {
01721       order->MakeDummy();
01722       SetWindowDirty(WC_VEHICLE_VIEW, v->index);
01723     }
01724 
01725     /* Clear the order from the order-list */
01726     int id = -1;
01727     FOR_VEHICLE_ORDERS(v, order) {
01728       id++;
01729 restart:
01730 
01731       OrderType ot = order->GetType();
01732       if (ot == OT_GOTO_DEPOT && (order->GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0) continue;
01733       if (ot == OT_IMPLICIT || (v->type == VEH_AIRCRAFT && ot == OT_GOTO_DEPOT)) ot = OT_GOTO_STATION;
01734       if (ot == type && order->GetDestination() == destination) {
01735         /* We want to clear implicit orders, but we don't want to make them
01736          * dummy orders. They should just vanish. Also check the actual order
01737          * type as ot is currently OT_GOTO_STATION. */
01738         if (order->IsType(OT_IMPLICIT)) {
01739           order = order->next; // DeleteOrder() invalidates current order
01740           DeleteOrder(v, id);
01741           if (order != NULL) goto restart;
01742           break;
01743         }
01744 
01745         order->MakeDummy();
01746         for (const Vehicle *w = v->FirstShared(); w != NULL; w = w->NextShared()) {
01747           /* In GUI, simulate by removing the order and adding it back */
01748           InvalidateVehicleOrder(w, id | (INVALID_VEH_ORDER_ID << 8));
01749           InvalidateVehicleOrder(w, (INVALID_VEH_ORDER_ID << 8) | id);
01750         }
01751       }
01752     }
01753   }
01754 
01755   OrderBackup::RemoveOrder(type, destination);
01756 }
01757 
01762 bool Vehicle::HasDepotOrder() const
01763 {
01764   const Order *order;
01765 
01766   FOR_VEHICLE_ORDERS(this, order) {
01767     if (order->IsType(OT_GOTO_DEPOT)) return true;
01768   }
01769 
01770   return false;
01771 }
01772 
01782 void DeleteVehicleOrders(Vehicle *v, bool keep_orderlist, bool reset_order_indices)
01783 {
01784   DeleteOrderWarnings(v);
01785 
01786   if (v->IsOrderListShared()) {
01787     /* Remove ourself from the shared order list. */
01788     v->RemoveFromShared();
01789     v->orders.list = NULL;
01790   } else if (v->orders.list != NULL) {
01791     /* Remove the orders */
01792     v->orders.list->FreeChain(keep_orderlist);
01793     if (!keep_orderlist) v->orders.list = NULL;
01794   }
01795 
01796   if (reset_order_indices) {
01797     v->cur_implicit_order_index = v->cur_real_order_index = 0;
01798     if (v->current_order.IsType(OT_LOADING)) {
01799       CancelLoadingDueToDeletedOrder(v);
01800     }
01801   }
01802 }
01803 
01811 uint16 GetServiceIntervalClamped(uint interval, CompanyID company_id)
01812 {
01813   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);
01814 }
01815 
01824 static bool CheckForValidOrders(const Vehicle *v)
01825 {
01826   const Order *order;
01827 
01828   FOR_VEHICLE_ORDERS(v, order) {
01829     switch (order->GetType()) {
01830       case OT_GOTO_STATION:
01831       case OT_GOTO_DEPOT:
01832       case OT_GOTO_WAYPOINT:
01833         return true;
01834 
01835       default:
01836         break;
01837     }
01838   }
01839 
01840   return false;
01841 }
01842 
01846 static bool OrderConditionCompare(OrderConditionComparator occ, int variable, int value)
01847 {
01848   switch (occ) {
01849     case OCC_EQUALS:      return variable == value;
01850     case OCC_NOT_EQUALS:  return variable != value;
01851     case OCC_LESS_THAN:   return variable <  value;
01852     case OCC_LESS_EQUALS: return variable <= value;
01853     case OCC_MORE_THAN:   return variable >  value;
01854     case OCC_MORE_EQUALS: return variable >= value;
01855     case OCC_IS_TRUE:     return variable != 0;
01856     case OCC_IS_FALSE:    return variable == 0;
01857     default: NOT_REACHED();
01858   }
01859 }
01860 
01867 VehicleOrderID ProcessConditionalOrder(const Order *order, const Vehicle *v)
01868 {
01869   if (order->GetType() != OT_CONDITIONAL) return INVALID_VEH_ORDER_ID;
01870 
01871   bool skip_order = false;
01872   OrderConditionComparator occ = order->GetConditionComparator();
01873   uint16 value = order->GetConditionValue();
01874 
01875   switch (order->GetConditionVariable()) {
01876     case OCV_LOAD_PERCENTAGE:    skip_order = OrderConditionCompare(occ, CalcPercentVehicleFilled(v, NULL), value); break;
01877     case OCV_RELIABILITY:        skip_order = OrderConditionCompare(occ, ToPercent16(v->reliability),       value); break;
01878     case OCV_MAX_SPEED:          skip_order = OrderConditionCompare(occ, v->GetDisplayMaxSpeed() * 10 / 16, value); break;
01879     case OCV_AGE:                skip_order = OrderConditionCompare(occ, v->age / DAYS_IN_LEAP_YEAR,        value); break;
01880     case OCV_REQUIRES_SERVICE:   skip_order = OrderConditionCompare(occ, v->NeedsServicing(),               value); break;
01881     case OCV_UNCONDITIONALLY:    skip_order = true; break;
01882     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;
01883     default: NOT_REACHED();
01884   }
01885 
01886   return skip_order ? order->GetConditionSkipToOrder() : (VehicleOrderID)INVALID_VEH_ORDER_ID;
01887 }
01888 
01896 bool UpdateOrderDest(Vehicle *v, const Order *order, int conditional_depth, bool pbs_look_ahead)
01897 {
01898   if (conditional_depth > v->GetNumOrders()) return false;
01899 
01900   switch (order->GetType()) {
01901     case OT_GOTO_STATION:
01902       v->dest_tile = v->GetOrderStationLocation(order->GetDestination());
01903       return true;
01904 
01905     case OT_GOTO_DEPOT:
01906       if ((order->GetDepotOrderType() & ODTFB_SERVICE) && !v->NeedsServicing()) {
01907         assert(!pbs_look_ahead);
01908         UpdateVehicleTimetable(v, true);
01909         v->IncrementRealOrderIndex();
01910         break;
01911       }
01912 
01913       if (v->current_order.GetDepotActionType() & ODATFB_NEAREST_DEPOT) {
01914         /* We need to search for the nearest depot (hangar). */
01915         TileIndex location;
01916         DestinationID destination;
01917         bool reverse;
01918 
01919         if (v->FindClosestDepot(&location, &destination, &reverse)) {
01920           /* PBS reservations cannot reverse */
01921           if (pbs_look_ahead && reverse) return false;
01922 
01923           v->dest_tile = location;
01924           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());
01925 
01926           /* If there is no depot in front, reverse automatically (trains only) */
01927           if (v->type == VEH_TRAIN && reverse) DoCommand(v->tile, v->index, 0, DC_EXEC, CMD_REVERSE_TRAIN_DIRECTION);
01928 
01929           if (v->type == VEH_AIRCRAFT) {
01930             Aircraft *a = Aircraft::From(v);
01931             if (a->state == FLYING && a->targetairport != destination) {
01932               /* The aircraft is now heading for a different hangar than the next in the orders */
01933               extern void AircraftNextAirportPos_and_Order(Aircraft *a);
01934               AircraftNextAirportPos_and_Order(a);
01935             }
01936           }
01937           return true;
01938         }
01939 
01940         /* If there is no depot, we cannot help PBS either. */
01941         if (pbs_look_ahead) return false;
01942 
01943         UpdateVehicleTimetable(v, true);
01944         v->IncrementRealOrderIndex();
01945       } else {
01946         if (v->type != VEH_AIRCRAFT) {
01947           v->dest_tile = Depot::Get(order->GetDestination())->xy;
01948         }
01949         return true;
01950       }
01951       break;
01952 
01953     case OT_GOTO_WAYPOINT:
01954       v->dest_tile = Waypoint::Get(order->GetDestination())->xy;
01955       return true;
01956 
01957     case OT_CONDITIONAL: {
01958       assert(!pbs_look_ahead);
01959       VehicleOrderID next_order = ProcessConditionalOrder(order, v);
01960       if (next_order != INVALID_VEH_ORDER_ID) {
01961         /* Jump to next_order. cur_implicit_order_index becomes exactly that order,
01962          * cur_real_order_index might come after next_order. */
01963         UpdateVehicleTimetable(v, false);
01964         v->cur_implicit_order_index = v->cur_real_order_index = next_order;
01965         v->UpdateRealOrderIndex();
01966         v->current_order_time += v->GetOrder(v->cur_real_order_index)->travel_time;
01967 
01968         /* Disable creation of implicit orders.
01969          * When inserting them we do not know that we would have to make the conditional orders point to them. */
01970         if (v->IsGroundVehicle()) {
01971           uint16 &gv_flags = v->GetGroundVehicleFlags();
01972           SetBit(gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS);
01973         }
01974       } else {
01975         UpdateVehicleTimetable(v, true);
01976         v->IncrementRealOrderIndex();
01977       }
01978       break;
01979     }
01980 
01981     default:
01982       v->dest_tile = 0;
01983       return false;
01984   }
01985 
01986   assert(v->cur_implicit_order_index < v->GetNumOrders());
01987   assert(v->cur_real_order_index < v->GetNumOrders());
01988 
01989   /* Get the current order */
01990   order = v->GetOrder(v->cur_real_order_index);
01991   if (order != NULL && order->IsType(OT_IMPLICIT)) {
01992     assert(v->GetNumManualOrders() == 0);
01993     order = NULL;
01994   }
01995 
01996   if (order == NULL) {
01997     v->current_order.Free();
01998     v->dest_tile = 0;
01999     return false;
02000   }
02001 
02002   v->current_order = *order;
02003   return UpdateOrderDest(v, order, conditional_depth + 1, pbs_look_ahead);
02004 }
02005 
02013 bool ProcessOrders(Vehicle *v)
02014 {
02015   switch (v->current_order.GetType()) {
02016     case OT_GOTO_DEPOT:
02017       /* Let a depot order in the orderlist interrupt. */
02018       if (!(v->current_order.GetDepotOrderType() & ODTFB_PART_OF_ORDERS)) return false;
02019       break;
02020 
02021     case OT_LOADING:
02022       return false;
02023 
02024     case OT_LEAVESTATION:
02025       if (v->type != VEH_AIRCRAFT) return false;
02026       break;
02027 
02028     default: break;
02029   }
02030 
02038   bool may_reverse = v->current_order.IsType(OT_NOTHING);
02039 
02040   /* Check if we've reached a 'via' destination. */
02041   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)) &&
02042       IsTileType(v->tile, MP_STATION) &&
02043       v->current_order.GetDestination() == GetStationIndex(v->tile)) {
02044     v->DeleteUnreachedImplicitOrders();
02045     /* We set the last visited station here because we do not want
02046      * the train to stop at this 'via' station if the next order
02047      * is a no-non-stop order; in that case not setting the last
02048      * visited station will cause the vehicle to still stop. */
02049     v->last_station_visited = v->current_order.GetDestination();
02050     UpdateVehicleTimetable(v, true);
02051     v->IncrementImplicitOrderIndex();
02052   }
02053 
02054   /* Get the current order */
02055   assert(v->cur_implicit_order_index == 0 || v->cur_implicit_order_index < v->GetNumOrders());
02056   v->UpdateRealOrderIndex();
02057 
02058   const Order *order = v->GetOrder(v->cur_real_order_index);
02059   if (order != NULL && order->IsType(OT_IMPLICIT)) {
02060     assert(v->GetNumManualOrders() == 0);
02061     order = NULL;
02062   }
02063 
02064   /* If no order, do nothing. */
02065   if (order == NULL || (v->type == VEH_AIRCRAFT && !CheckForValidOrders(v))) {
02066     if (v->type == VEH_AIRCRAFT) {
02067       /* Aircraft do something vastly different here, so handle separately */
02068       extern void HandleMissingAircraftOrders(Aircraft *v);
02069       HandleMissingAircraftOrders(Aircraft::From(v));
02070       return false;
02071     }
02072 
02073     v->current_order.Free();
02074     v->dest_tile = 0;
02075     return false;
02076   }
02077 
02078   /* If it is unchanged, keep it. */
02079   if (order->Equals(v->current_order) && (v->type == VEH_AIRCRAFT || v->dest_tile != 0) &&
02080       (v->type != VEH_SHIP || !order->IsType(OT_GOTO_STATION) || Station::Get(order->GetDestination())->dock_tile != INVALID_TILE)) {
02081     return false;
02082   }
02083 
02084   /* Otherwise set it, and determine the destination tile. */
02085   v->current_order = *order;
02086 
02087   InvalidateVehicleOrder(v, -2);
02088   switch (v->type) {
02089     default:
02090       NOT_REACHED();
02091 
02092     case VEH_ROAD:
02093     case VEH_TRAIN:
02094       break;
02095 
02096     case VEH_AIRCRAFT:
02097     case VEH_SHIP:
02098       SetWindowClassesDirty(GetWindowClassForVehicleType(v->type));
02099       break;
02100   }
02101 
02102   return UpdateOrderDest(v, order) && may_reverse;
02103 }
02104 
02112 bool Order::ShouldStopAtStation(const Vehicle *v, StationID station) const
02113 {
02114   bool is_dest_station = this->IsType(OT_GOTO_STATION) && this->dest == station;
02115 
02116   return (!this->IsType(OT_GOTO_DEPOT) || (this->GetDepotOrderType() & ODTFB_PART_OF_ORDERS) != 0) &&
02117       v->last_station_visited != station && // Do stop only when we've not just been there
02118       /* Finally do stop when there is no non-stop flag set for this type of station. */
02119       !(this->GetNonStopType() & (is_dest_station ? ONSF_NO_STOP_AT_DESTINATION_STATION : ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS));
02120 }