# order_cmd.cpp

Go to the documentation of this file.

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