vehicle_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 "roadveh.h"
00014 #include "news_func.h"
00015 #include "airport.h"
00016 #include "cmd_helper.h"
00017 #include "command_func.h"
00018 #include "company_func.h"
00019 #include "vehicle_gui.h"
00020 #include "train.h"
00021 #include "aircraft.h"
00022 #include "newgrf_text.h"
00023 #include "window_func.h"
00024 #include "vehicle_func.h"
00025 #include "string_func.h"
00026 #include "depot_map.h"
00027 #include "vehiclelist.h"
00028 #include "engine_func.h"
00029 #include "articulated_vehicles.h"
00030 #include "autoreplace_gui.h"
00031 #include "company_base.h"
00032 #include "order_backup.h"
00033 #include "ship.h"
00034 #include "newgrf.h"
00035 
00036 #include "table/strings.h"
00037 
00038 /* Tables used in vehicle.h to find the right command for a certain vehicle type */
00039 const uint32 _veh_build_proc_table[] = {
00040   CMD_BUILD_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_TRAIN),
00041   CMD_BUILD_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_ROAD_VEHICLE),
00042   CMD_BUILD_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_SHIP),
00043   CMD_BUILD_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_AIRCRAFT),
00044 };
00045 
00046 const uint32 _veh_sell_proc_table[] = {
00047   CMD_SELL_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_SELL_TRAIN),
00048   CMD_SELL_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_SELL_ROAD_VEHICLE),
00049   CMD_SELL_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_SELL_SHIP),
00050   CMD_SELL_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_SELL_AIRCRAFT),
00051 };
00052 
00053 const uint32 _veh_refit_proc_table[] = {
00054   CMD_REFIT_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_REFIT_TRAIN),
00055   CMD_REFIT_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_REFIT_ROAD_VEHICLE),
00056   CMD_REFIT_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_REFIT_SHIP),
00057   CMD_REFIT_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_REFIT_AIRCRAFT),
00058 };
00059 
00060 const uint32 _send_to_depot_proc_table[] = {
00061   /* TrainGotoDepot has a nice randomizer in the pathfinder, which causes desyncs... */
00062   CMD_SEND_VEHICLE_TO_DEPOT | CMD_MSG(STR_ERROR_CAN_T_SEND_TRAIN_TO_DEPOT) | CMD_NO_TEST_IF_IN_NETWORK,
00063   CMD_SEND_VEHICLE_TO_DEPOT | CMD_MSG(STR_ERROR_CAN_T_SEND_ROAD_VEHICLE_TO_DEPOT),
00064   CMD_SEND_VEHICLE_TO_DEPOT | CMD_MSG(STR_ERROR_CAN_T_SEND_SHIP_TO_DEPOT),
00065   CMD_SEND_VEHICLE_TO_DEPOT | CMD_MSG(STR_ERROR_CAN_T_SEND_AIRCRAFT_TO_HANGAR),
00066 };
00067 
00068 
00069 CommandCost CmdBuildRailVehicle(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **v);
00070 CommandCost CmdBuildRoadVehicle(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **v);
00071 CommandCost CmdBuildShip       (TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **v);
00072 CommandCost CmdBuildAircraft   (TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **v);
00073 
00085 CommandCost CmdBuildVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00086 {
00087   /* Elementary check for valid location. */
00088   if (!IsDepotTile(tile) || !IsTileOwner(tile, _current_company)) return CMD_ERROR;
00089 
00090   VehicleType type;
00091   switch (GetTileType(tile)) {
00092     case MP_RAILWAY: type = VEH_TRAIN;    break;
00093     case MP_ROAD:    type = VEH_ROAD;     break;
00094     case MP_WATER:   type = VEH_SHIP;     break;
00095     case MP_STATION: type = VEH_AIRCRAFT; break;
00096     default: NOT_REACHED(); // Safe due to IsDepotTile()
00097   }
00098 
00099   /* Validate the engine type. */
00100   EngineID eid = GB(p1, 0, 16);
00101   if (!IsEngineBuildable(eid, type, _current_company)) return_cmd_error(STR_ERROR_RAIL_VEHICLE_NOT_AVAILABLE + type);
00102 
00103   const Engine *e = Engine::Get(eid);
00104   CommandCost value(EXPENSES_NEW_VEHICLES, e->GetCost());
00105 
00106   /* Engines without valid cargo should not be available */
00107   if (e->GetDefaultCargoType() == CT_INVALID) return CMD_ERROR;
00108 
00109   /* Check whether the number of vehicles we need to build can be built according to pool space. */
00110   uint num_vehicles;
00111   switch (type) {
00112     case VEH_TRAIN:    num_vehicles = (e->u.rail.railveh_type == RAILVEH_MULTIHEAD ? 2 : 1) + CountArticulatedParts(eid, false); break;
00113     case VEH_ROAD:     num_vehicles = 1 + CountArticulatedParts(eid, false); break;
00114     case VEH_SHIP:     num_vehicles = 1; break;
00115     case VEH_AIRCRAFT: num_vehicles = e->u.air.subtype & AIR_CTOL ? 2 : 3; break;
00116     default: NOT_REACHED(); // Safe due to IsDepotTile()
00117   }
00118   if (!Vehicle::CanAllocateItem(num_vehicles)) return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
00119 
00120   /* Check whether we can allocate a unit number. Autoreplace does not allocate
00121    * an unit number as it will (always) reuse the one of the replaced vehicle
00122    * and (train) wagons don't have an unit number in any scenario. */
00123   UnitID unit_num = (flags & DC_AUTOREPLACE || (type == VEH_TRAIN && e->u.rail.railveh_type == RAILVEH_WAGON)) ? 0 : GetFreeUnitNumber(type);
00124   if (unit_num == UINT16_MAX) return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
00125 
00126   Vehicle *v;
00127   switch (type) {
00128     case VEH_TRAIN:    value.AddCost(CmdBuildRailVehicle(tile, flags, e, GB(p1, 16, 16), &v)); break;
00129     case VEH_ROAD:     value.AddCost(CmdBuildRoadVehicle(tile, flags, e, GB(p1, 16, 16), &v)); break;
00130     case VEH_SHIP:     value.AddCost(CmdBuildShip       (tile, flags, e, GB(p1, 16, 16), &v)); break;
00131     case VEH_AIRCRAFT: value.AddCost(CmdBuildAircraft   (tile, flags, e, GB(p1, 16, 16), &v)); break;
00132     default: NOT_REACHED(); // Safe due to IsDepotTile()
00133   }
00134 
00135   if (value.Succeeded() && flags & DC_EXEC) {
00136     v->unitnumber = unit_num;
00137     v->value      = value.GetCost();
00138 
00139     InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
00140     InvalidateWindowClassesData(GetWindowClassForVehicleType(type), 0);
00141     SetWindowDirty(WC_COMPANY, _current_company);
00142     if (IsLocalCompany()) {
00143       InvalidateAutoreplaceWindow(v->engine_type, v->group_id); // updates the auto replace window (must be called before incrementing num_engines)
00144     }
00145 
00146     GroupStatistics::CountEngine(v, 1);
00147     GroupStatistics::UpdateAutoreplace(_current_company);
00148 
00149     if (v->IsPrimaryVehicle()) {
00150       GroupStatistics::CountVehicle(v, 1);
00151       OrderBackup::Restore(v, p2);
00152     }
00153   }
00154 
00155   return value;
00156 }
00157 
00158 CommandCost CmdSellRailWagon(DoCommandFlag flags, Vehicle *v, uint16 data, uint32 user);
00159 
00172 CommandCost CmdSellVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00173 {
00174   Vehicle *v = Vehicle::GetIfValid(GB(p1, 0, 20));
00175   if (v == NULL) return CMD_ERROR;
00176 
00177   Vehicle *front = v->First();
00178 
00179   CommandCost ret = CheckOwnership(front->owner);
00180   if (ret.Failed()) return ret;
00181 
00182   if (front->vehstatus & VS_CRASHED) return_cmd_error(STR_ERROR_VEHICLE_IS_DESTROYED);
00183 
00184   if (!front->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAIN_MUST_BE_STOPPED_INSIDE_DEPOT + front->type);
00185 
00186   /* Can we actually make the order backup, i.e. are there enough orders? */
00187   if (p1 & MAKE_ORDER_BACKUP_FLAG &&
00188       front->orders.list != NULL &&
00189       !front->orders.list->IsShared() &&
00190       !Order::CanAllocateItem(front->orders.list->GetNumOrders())) {
00191     /* Only happens in exceptional cases when there aren't enough orders anyhow.
00192      * Thus it should be safe to just drop the orders in that case. */
00193     p1 &= ~MAKE_ORDER_BACKUP_FLAG;
00194   }
00195 
00196   if (v->type == VEH_TRAIN) {
00197     ret = CmdSellRailWagon(flags, v, GB(p1, 20, 12), p2);
00198   } else {
00199     ret = CommandCost(EXPENSES_NEW_VEHICLES, -front->value);
00200 
00201     if (flags & DC_EXEC) {
00202       if (v->IsPrimaryVehicle() && p1 & MAKE_ORDER_BACKUP_FLAG) OrderBackup::Backup(v, p2);
00203       delete front;
00204     }
00205   }
00206 
00207   return ret;
00208 }
00209 
00219 static int GetRefitCostFactor(const Vehicle *v, EngineID engine_type, CargoID new_cid, byte new_subtype, bool *auto_refit_allowed)
00220 {
00221   /* Prepare callback param with info about the new cargo type. */
00222   const Engine *e = Engine::Get(engine_type);
00223 
00224   /* Is this vehicle a NewGRF vehicle? */
00225   if (e->GetGRF() != NULL) {
00226     const CargoSpec *cs = CargoSpec::Get(new_cid);
00227     uint32 param1 = (cs->classes << 16) | (new_subtype << 8) | e->GetGRF()->cargo_map[new_cid];
00228 
00229     uint16 cb_res = GetVehicleCallback(CBID_VEHICLE_REFIT_COST, param1, 0, engine_type, v);
00230     if (cb_res != CALLBACK_FAILED) {
00231       *auto_refit_allowed = HasBit(cb_res, 14);
00232       int factor = GB(cb_res, 0, 14);
00233       if (factor >= 0x2000) factor -= 0x4000; // Treat as signed integer.
00234       return factor;
00235     }
00236   }
00237 
00238   *auto_refit_allowed = e->info.refit_cost == 0;
00239   return (v == NULL || v->cargo_type != new_cid) ? e->info.refit_cost : 0;
00240 }
00241 
00251 static CommandCost GetRefitCost(const Vehicle *v, EngineID engine_type, CargoID new_cid, byte new_subtype, bool *auto_refit_allowed)
00252 {
00253   ExpensesType expense_type;
00254   const Engine *e = Engine::Get(engine_type);
00255   Price base_price;
00256   int cost_factor = GetRefitCostFactor(v, engine_type, new_cid, new_subtype, auto_refit_allowed);
00257   switch (e->type) {
00258     case VEH_SHIP:
00259       base_price = PR_BUILD_VEHICLE_SHIP;
00260       expense_type = EXPENSES_SHIP_RUN;
00261       break;
00262 
00263     case VEH_ROAD:
00264       base_price = PR_BUILD_VEHICLE_ROAD;
00265       expense_type = EXPENSES_ROADVEH_RUN;
00266       break;
00267 
00268     case VEH_AIRCRAFT:
00269       base_price = PR_BUILD_VEHICLE_AIRCRAFT;
00270       expense_type = EXPENSES_AIRCRAFT_RUN;
00271       break;
00272 
00273     case VEH_TRAIN:
00274       base_price = (e->u.rail.railveh_type == RAILVEH_WAGON) ? PR_BUILD_VEHICLE_WAGON : PR_BUILD_VEHICLE_TRAIN;
00275       cost_factor <<= 1;
00276       expense_type = EXPENSES_TRAIN_RUN;
00277       break;
00278 
00279     default: NOT_REACHED();
00280   }
00281   if (cost_factor < 0) {
00282     return CommandCost(expense_type, -GetPrice(base_price, -cost_factor, e->GetGRF(), -10));
00283   } else {
00284     return CommandCost(expense_type, GetPrice(base_price, cost_factor, e->GetGRF(), -10));
00285   }
00286 }
00287 
00300 static CommandCost RefitVehicle(Vehicle *v, bool only_this, uint8 num_vehicles, CargoID new_cid, byte new_subtype, DoCommandFlag flags, bool auto_refit)
00301 {
00302   CommandCost cost(v->GetExpenseType(false));
00303   uint total_capacity = 0;
00304   uint total_mail_capacity = 0;
00305   num_vehicles = num_vehicles == 0 ? UINT8_MAX : num_vehicles;
00306 
00307   VehicleSet vehicles_to_refit;
00308   if (!only_this) {
00309     GetVehicleSet(vehicles_to_refit, v, num_vehicles);
00310     /* In this case, we need to check the whole chain. */
00311     v = v->First();
00312   }
00313 
00314   v->InvalidateNewGRFCacheOfChain();
00315   for (; v != NULL; v = (only_this ? NULL : v->Next())) {
00316     if (v->type == VEH_TRAIN && !vehicles_to_refit.Contains(v->index) && !only_this) continue;
00317 
00318     const Engine *e = v->GetEngine();
00319     if (!e->CanCarryCargo()) continue;
00320 
00321     /* If the vehicle is not refittable, or does not allow automatic refitting,
00322      * count its capacity nevertheless if the cargo matches */
00323     bool refittable = HasBit(e->info.refit_mask, new_cid) && (!auto_refit || HasBit(e->info.misc_flags, EF_AUTO_REFIT));
00324     if (!refittable && v->cargo_type != new_cid) continue;
00325 
00326     /* Back up the vehicle's cargo type */
00327     CargoID temp_cid = v->cargo_type;
00328     byte temp_subtype = v->cargo_subtype;
00329     if (refittable) {
00330       v->cargo_type = new_cid;
00331       v->cargo_subtype = new_subtype;
00332     }
00333 
00334     uint16 mail_capacity = 0;
00335     uint amount = e->DetermineCapacity(v, &mail_capacity);
00336     total_capacity += amount;
00337     /* mail_capacity will always be zero if the vehicle is not an aircraft. */
00338     total_mail_capacity += mail_capacity;
00339 
00340     if (!refittable) continue;
00341 
00342     /* Restore the original cargo type */
00343     v->cargo_type = temp_cid;
00344     v->cargo_subtype = temp_subtype;
00345 
00346     bool auto_refit_allowed;
00347     CommandCost refit_cost = GetRefitCost(v, v->engine_type, new_cid, new_subtype, &auto_refit_allowed);
00348     if (auto_refit && !auto_refit_allowed) {
00349       /* Sorry, auto-refitting not allowed, subtract the cargo amount again from the total. */
00350       total_capacity -= amount;
00351       total_mail_capacity -= mail_capacity;
00352       continue;
00353     }
00354     cost.AddCost(refit_cost);
00355 
00356     if (flags & DC_EXEC) {
00357       v->refit_cap = (v->cargo_type == new_cid) ? min(amount, v->cargo_cap) : 0;
00358       v->cargo.Truncate(v->refit_cap);
00359       v->cargo_type = new_cid;
00360       v->cargo_cap = amount;
00361       v->cargo_subtype = new_subtype;
00362       if (v->type == VEH_AIRCRAFT) {
00363         Vehicle *u = v->Next();
00364         u->refit_cap = min(u->cargo_cap, mail_capacity);
00365         u->cargo_cap = mail_capacity;
00366         u->cargo.Truncate(mail_capacity);
00367       }
00368     }
00369   }
00370 
00371   _returned_refit_capacity = total_capacity;
00372   _returned_mail_refit_capacity = total_mail_capacity;
00373   return cost;
00374 }
00375 
00391 CommandCost CmdRefitVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00392 {
00393   Vehicle *v = Vehicle::GetIfValid(p1);
00394   if (v == NULL) return CMD_ERROR;
00395 
00396   /* Don't allow disasters and sparks and such to be refitted.
00397    * We cannot check for IsPrimaryVehicle as autoreplace also refits in free wagon chains. */
00398   if (!IsCompanyBuildableVehicleType(v->type)) return CMD_ERROR;
00399 
00400   Vehicle *front = v->First();
00401 
00402   CommandCost ret = CheckOwnership(front->owner);
00403   if (ret.Failed()) return ret;
00404 
00405   bool auto_refit = HasBit(p2, 6);
00406 
00407   /* Don't allow shadows and such to be refitted. */
00408   if (v != front && (v->type == VEH_SHIP || v->type == VEH_AIRCRAFT)) return CMD_ERROR;
00409   /* Allow auto-refitting only during loading and normal refitting only in a depot. */
00410   if ((!auto_refit || !front->current_order.IsType(OT_LOADING)) && !front->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAIN_MUST_BE_STOPPED_INSIDE_DEPOT + front->type);
00411   if (front->vehstatus & VS_CRASHED) return_cmd_error(STR_ERROR_VEHICLE_IS_DESTROYED);
00412 
00413   /* Check cargo */
00414   CargoID new_cid = GB(p2, 0, 5);
00415   byte new_subtype = GB(p2, 8, 8);
00416   if (new_cid >= NUM_CARGO) return CMD_ERROR;
00417 
00418   /* For ships and aircrafts there is always only one. */
00419   bool only_this = HasBit(p2, 7) || front->type == VEH_SHIP || front->type == VEH_AIRCRAFT;
00420   uint8 num_vehicles = GB(p2, 16, 8);
00421 
00422   CommandCost cost = RefitVehicle(v, only_this, num_vehicles, new_cid, new_subtype, flags, auto_refit);
00423 
00424   if (flags & DC_EXEC) {
00425     /* Update the cached variables */
00426     switch (v->type) {
00427       case VEH_TRAIN:
00428         Train::From(front)->ConsistChanged(auto_refit);
00429         break;
00430       case VEH_ROAD:
00431         RoadVehUpdateCache(RoadVehicle::From(front), auto_refit);
00432         if (_settings_game.vehicle.roadveh_acceleration_model != AM_ORIGINAL) RoadVehicle::From(front)->CargoChanged();
00433         break;
00434 
00435       case VEH_SHIP:
00436         v->InvalidateNewGRFCacheOfChain();
00437         v->colourmap = PAL_NONE; // invalidate vehicle colour map
00438         Ship::From(v)->UpdateCache();
00439         break;
00440 
00441       case VEH_AIRCRAFT:
00442         v->InvalidateNewGRFCacheOfChain();
00443         v->colourmap = PAL_NONE; // invalidate vehicle colour map
00444         UpdateAircraftCache(Aircraft::From(v), true);
00445         break;
00446 
00447       default: NOT_REACHED();
00448     }
00449 
00450     InvalidateWindowData(WC_VEHICLE_DETAILS, front->index);
00451     SetWindowDirty(WC_VEHICLE_DEPOT, front->tile);
00452     InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
00453   } else {
00454     /* Always invalidate the cache; querycost might have filled it. */
00455     v->InvalidateNewGRFCacheOfChain();
00456   }
00457 
00458   return cost;
00459 }
00460 
00470 CommandCost CmdStartStopVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00471 {
00472   /* Disable the effect of p2 bit 0, when DC_AUTOREPLACE is not set */
00473   if ((flags & DC_AUTOREPLACE) == 0) SetBit(p2, 0);
00474 
00475   Vehicle *v = Vehicle::GetIfValid(p1);
00476   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
00477 
00478   CommandCost ret = CheckOwnership(v->owner);
00479   if (ret.Failed()) return ret;
00480 
00481   if (v->vehstatus & VS_CRASHED) return_cmd_error(STR_ERROR_VEHICLE_IS_DESTROYED);
00482 
00483   switch (v->type) {
00484     case VEH_TRAIN:
00485       if ((v->vehstatus & VS_STOPPED) && Train::From(v)->gcache.cached_power == 0) return_cmd_error(STR_ERROR_TRAIN_START_NO_POWER);
00486       break;
00487 
00488     case VEH_SHIP:
00489     case VEH_ROAD:
00490       break;
00491 
00492     case VEH_AIRCRAFT: {
00493       Aircraft *a = Aircraft::From(v);
00494       /* cannot stop airplane when in flight, or when taking off / landing */
00495       if (!(v->vehstatus & VS_CRASHED) && a->state >= STARTTAKEOFF && a->state < TERM7) return_cmd_error(STR_ERROR_AIRCRAFT_IS_IN_FLIGHT);
00496       break;
00497     }
00498 
00499     default: return CMD_ERROR;
00500   }
00501 
00502   if (HasBit(p2, 0)) {
00503     /* Check if this vehicle can be started/stopped. Failure means 'allow'. */
00504     uint16 callback = GetVehicleCallback(CBID_VEHICLE_START_STOP_CHECK, 0, 0, v->engine_type, v);
00505     StringID error = STR_NULL;
00506     if (callback != CALLBACK_FAILED) {
00507       if (v->GetGRF()->grf_version < 8) {
00508         /* 8 bit result 0xFF means 'allow' */
00509         if (callback < 0x400 && GB(callback, 0, 8) != 0xFF) error = GetGRFStringID(v->GetGRFID(), 0xD000 + callback);
00510       } else {
00511         if (callback < 0x400) {
00512           error = GetGRFStringID(v->GetGRFID(), 0xD000 + callback);
00513         } else {
00514           switch (callback) {
00515             case 0x400: // allow
00516               break;
00517 
00518             default: // unknown reason -> disallow
00519               error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
00520               break;
00521           }
00522         }
00523       }
00524     }
00525     if (error != STR_NULL) return_cmd_error(error);
00526   }
00527 
00528   if (flags & DC_EXEC) {
00529     if (v->IsStoppedInDepot() && (flags & DC_AUTOREPLACE) == 0) DeleteVehicleNews(p1, STR_NEWS_TRAIN_IS_WAITING + v->type);
00530 
00531     v->vehstatus ^= VS_STOPPED;
00532     if (v->type != VEH_TRAIN) v->cur_speed = 0; // trains can stop 'slowly'
00533     v->MarkDirty();
00534     SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
00535     SetWindowDirty(WC_VEHICLE_DEPOT, v->tile);
00536     SetWindowClassesDirty(GetWindowClassForVehicleType(v->type));
00537   }
00538   return CommandCost();
00539 }
00540 
00552 CommandCost CmdMassStartStopVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00553 {
00554   VehicleList list;
00555   bool do_start = HasBit(p1, 0);
00556   bool vehicle_list_window = HasBit(p1, 1);
00557 
00558   VehicleListIdentifier vli;
00559   if (!vli.Unpack(p2)) return CMD_ERROR;
00560   if (!IsCompanyBuildableVehicleType(vli.vtype)) return CMD_ERROR;
00561 
00562   if (vehicle_list_window) {
00563     if (!GenerateVehicleSortList(&list, vli)) return CMD_ERROR;
00564   } else {
00565     /* Get the list of vehicles in the depot */
00566     BuildDepotVehicleList(vli.vtype, tile, &list, NULL);
00567   }
00568 
00569   for (uint i = 0; i < list.Length(); i++) {
00570     const Vehicle *v = list[i];
00571 
00572     if (!!(v->vehstatus & VS_STOPPED) != do_start) continue;
00573 
00574     if (!vehicle_list_window) {
00575       if (vli.vtype == VEH_TRAIN) {
00576         if (!Train::From(v)->IsInDepot()) continue;
00577       } else {
00578         if (!(v->vehstatus & VS_HIDDEN)) continue;
00579       }
00580     }
00581 
00582     /* Just try and don't care if some vehicle's can't be stopped. */
00583     DoCommand(tile, v->index, 0, flags, CMD_START_STOP_VEHICLE);
00584   }
00585 
00586   return CommandCost();
00587 }
00588 
00598 CommandCost CmdDepotSellAllVehicles(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00599 {
00600   VehicleList list;
00601 
00602   CommandCost cost(EXPENSES_NEW_VEHICLES);
00603   VehicleType vehicle_type = Extract<VehicleType, 0, 3>(p1);
00604 
00605   if (!IsCompanyBuildableVehicleType(vehicle_type)) return CMD_ERROR;
00606 
00607   uint sell_command = GetCmdSellVeh(vehicle_type);
00608 
00609   /* Get the list of vehicles in the depot */
00610   BuildDepotVehicleList(vehicle_type, tile, &list, &list);
00611 
00612   CommandCost last_error = CMD_ERROR;
00613   bool had_success = false;
00614   for (uint i = 0; i < list.Length(); i++) {
00615     CommandCost ret = DoCommand(tile, list[i]->index | (1 << 20), 0, flags, sell_command);
00616     if (ret.Succeeded()) {
00617       cost.AddCost(ret);
00618       had_success = true;
00619     } else {
00620       last_error = ret;
00621     }
00622   }
00623 
00624   return had_success ? cost : last_error;
00625 }
00626 
00636 CommandCost CmdDepotMassAutoReplace(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00637 {
00638   VehicleList list;
00639   CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES);
00640   VehicleType vehicle_type = Extract<VehicleType, 0, 3>(p1);
00641 
00642   if (!IsCompanyBuildableVehicleType(vehicle_type)) return CMD_ERROR;
00643   if (!IsDepotTile(tile) || !IsTileOwner(tile, _current_company)) return CMD_ERROR;
00644 
00645   /* Get the list of vehicles in the depot */
00646   BuildDepotVehicleList(vehicle_type, tile, &list, &list, true);
00647 
00648   for (uint i = 0; i < list.Length(); i++) {
00649     const Vehicle *v = list[i];
00650 
00651     /* Ensure that the vehicle completely in the depot */
00652     if (!v->IsInDepot()) continue;
00653 
00654     CommandCost ret = DoCommand(0, v->index, 0, flags, CMD_AUTOREPLACE_VEHICLE);
00655 
00656     if (ret.Succeeded()) cost.AddCost(ret);
00657   }
00658   return cost;
00659 }
00660 
00666 static bool IsUniqueVehicleName(const char *name)
00667 {
00668   const Vehicle *v;
00669 
00670   FOR_ALL_VEHICLES(v) {
00671     if (v->name != NULL && strcmp(v->name, name) == 0) return false;
00672   }
00673 
00674   return true;
00675 }
00676 
00682 static void CloneVehicleName(const Vehicle *src, Vehicle *dst)
00683 {
00684   char buf[256];
00685 
00686   /* Find the position of the first digit in the last group of digits. */
00687   size_t number_position;
00688   for (number_position = strlen(src->name); number_position > 0; number_position--) {
00689     /* The design of UTF-8 lets this work simply without having to check
00690      * for UTF-8 sequences. */
00691     if (src->name[number_position - 1] < '0' || src->name[number_position - 1] > '9') break;
00692   }
00693 
00694   /* Format buffer and determine starting number. */
00695   int num;
00696   byte padding = 0;
00697   if (number_position == strlen(src->name)) {
00698     /* No digit at the end, so start at number 2. */
00699     strecpy(buf, src->name, lastof(buf));
00700     strecat(buf, " ", lastof(buf));
00701     number_position = strlen(buf);
00702     num = 2;
00703   } else {
00704     /* Found digits, parse them and start at the next number. */
00705     strecpy(buf, src->name, lastof(buf));
00706     buf[number_position] = '\0';
00707     char *endptr;
00708     num = strtol(&src->name[number_position], &endptr, 10) + 1;
00709     padding = endptr - &src->name[number_position];
00710   }
00711 
00712   /* Check if this name is already taken. */
00713   for (int max_iterations = 1000; max_iterations > 0; max_iterations--, num++) {
00714     /* Attach the number to the temporary name. */
00715     seprintf(&buf[number_position], lastof(buf), "%0*d", padding, num);
00716 
00717     /* Check the name is unique. */
00718     if (IsUniqueVehicleName(buf)) {
00719       dst->name = strdup(buf);
00720       break;
00721     }
00722   }
00723 
00724   /* All done. If we didn't find a name, it'll just use its default. */
00725 }
00726 
00736 CommandCost CmdCloneVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00737 {
00738   CommandCost total_cost(EXPENSES_NEW_VEHICLES);
00739 
00740   Vehicle *v = Vehicle::GetIfValid(p1);
00741   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
00742   Vehicle *v_front = v;
00743   Vehicle *w = NULL;
00744   Vehicle *w_front = NULL;
00745   Vehicle *w_rear = NULL;
00746 
00747   /*
00748    * v_front is the front engine in the original vehicle
00749    * v is the car/vehicle of the original vehicle that is currently being copied
00750    * w_front is the front engine of the cloned vehicle
00751    * w is the car/vehicle currently being cloned
00752    * w_rear is the rear end of the cloned train. It's used to add more cars and is only used by trains
00753    */
00754 
00755   CommandCost ret = CheckOwnership(v->owner);
00756   if (ret.Failed()) return ret;
00757 
00758   if (v->type == VEH_TRAIN && (!v->IsFrontEngine() || Train::From(v)->crash_anim_pos >= 4400)) return CMD_ERROR;
00759 
00760   /* check that we can allocate enough vehicles */
00761   if (!(flags & DC_EXEC)) {
00762     int veh_counter = 0;
00763     do {
00764       veh_counter++;
00765     } while ((v = v->Next()) != NULL);
00766 
00767     if (!Vehicle::CanAllocateItem(veh_counter)) {
00768       return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
00769     }
00770   }
00771 
00772   v = v_front;
00773 
00774   do {
00775     if (v->type == VEH_TRAIN && Train::From(v)->IsRearDualheaded()) {
00776       /* we build the rear ends of multiheaded trains with the front ones */
00777       continue;
00778     }
00779 
00780     /* In case we're building a multi headed vehicle and the maximum number of
00781      * vehicles is almost reached (e.g. max trains - 1) not all vehicles would
00782      * be cloned. When the non-primary engines were build they were seen as
00783      * 'new' vehicles whereas they would immediately be joined with a primary
00784      * engine. This caused the vehicle to be not build as 'the limit' had been
00785      * reached, resulting in partially build vehicles and such. */
00786     DoCommandFlag build_flags = flags;
00787     if ((flags & DC_EXEC) && !v->IsPrimaryVehicle()) build_flags |= DC_AUTOREPLACE;
00788 
00789     CommandCost cost = DoCommand(tile, v->engine_type | (1 << 16), 0, build_flags, GetCmdBuildVeh(v));
00790 
00791     if (cost.Failed()) {
00792       /* Can't build a part, then sell the stuff we already made; clear up the mess */
00793       if (w_front != NULL) DoCommand(w_front->tile, w_front->index | (1 << 20), 0, flags, GetCmdSellVeh(w_front));
00794       return cost;
00795     }
00796 
00797     total_cost.AddCost(cost);
00798 
00799     if (flags & DC_EXEC) {
00800       w = Vehicle::Get(_new_vehicle_id);
00801 
00802       if (v->type == VEH_TRAIN && HasBit(Train::From(v)->flags, VRF_REVERSE_DIRECTION)) {
00803         SetBit(Train::From(w)->flags, VRF_REVERSE_DIRECTION);
00804       }
00805 
00806       if (v->type == VEH_TRAIN && !v->IsFrontEngine()) {
00807         /* this s a train car
00808          * add this unit to the end of the train */
00809         CommandCost result = DoCommand(0, w->index | 1 << 20, w_rear->index, flags, CMD_MOVE_RAIL_VEHICLE);
00810         if (result.Failed()) {
00811           /* The train can't be joined to make the same consist as the original.
00812            * Sell what we already made (clean up) and return an error.           */
00813           DoCommand(w_front->tile, w_front->index | 1 << 20, 0, flags, GetCmdSellVeh(w_front));
00814           DoCommand(w_front->tile, w->index       | 1 << 20, 0, flags, GetCmdSellVeh(w));
00815           return result; // return error and the message returned from CMD_MOVE_RAIL_VEHICLE
00816         }
00817       } else {
00818         /* this is a front engine or not a train. */
00819         w_front = w;
00820         w->service_interval = v->service_interval;
00821       }
00822       w_rear = w; // trains needs to know the last car in the train, so they can add more in next loop
00823     }
00824   } while (v->type == VEH_TRAIN && (v = v->GetNextVehicle()) != NULL);
00825 
00826   if ((flags & DC_EXEC) && v_front->type == VEH_TRAIN) {
00827     /* for trains this needs to be the front engine due to the callback function */
00828     _new_vehicle_id = w_front->index;
00829   }
00830 
00831   if (flags & DC_EXEC) {
00832     /* Cloned vehicles belong to the same group */
00833     DoCommand(0, v_front->group_id, w_front->index, flags, CMD_ADD_VEHICLE_GROUP);
00834   }
00835 
00836 
00837   /* Take care of refitting. */
00838   w = w_front;
00839   v = v_front;
00840 
00841   /* Both building and refitting are influenced by newgrf callbacks, which
00842    * makes it impossible to accurately estimate the cloning costs. In
00843    * particular, it is possible for engines of the same type to be built with
00844    * different numbers of articulated parts, so when refitting we have to
00845    * loop over real vehicles first, and then the articulated parts of those
00846    * vehicles in a different loop. */
00847   do {
00848     do {
00849       if (flags & DC_EXEC) {
00850         assert(w != NULL);
00851 
00852         /* Find out what's the best sub type */
00853         byte subtype = GetBestFittingSubType(v, w, v->cargo_type);
00854         if (w->cargo_type != v->cargo_type || w->cargo_subtype != subtype) {
00855           CommandCost cost = DoCommand(0, w->index, v->cargo_type | 1U << 7 | (subtype << 8), flags, GetCmdRefitVeh(v));
00856           if (cost.Succeeded()) total_cost.AddCost(cost);
00857         }
00858 
00859         if (w->IsGroundVehicle() && w->HasArticulatedPart()) {
00860           w = w->GetNextArticulatedPart();
00861         } else {
00862           break;
00863         }
00864       } else {
00865         const Engine *e = v->GetEngine();
00866         CargoID initial_cargo = (e->CanCarryCargo() ? e->GetDefaultCargoType() : (CargoID)CT_INVALID);
00867 
00868         if (v->cargo_type != initial_cargo && initial_cargo != CT_INVALID) {
00869           bool dummy;
00870           total_cost.AddCost(GetRefitCost(NULL, v->engine_type, v->cargo_type, v->cargo_subtype, &dummy));
00871         }
00872       }
00873 
00874       if (v->IsGroundVehicle() && v->HasArticulatedPart()) {
00875         v = v->GetNextArticulatedPart();
00876       } else {
00877         break;
00878       }
00879     } while (v != NULL);
00880 
00881     if ((flags & DC_EXEC) && v->type == VEH_TRAIN) w = w->GetNextVehicle();
00882   } while (v->type == VEH_TRAIN && (v = v->GetNextVehicle()) != NULL);
00883 
00884   if (flags & DC_EXEC) {
00885     /*
00886      * Set the orders of the vehicle. Cannot do it earlier as we need
00887      * the vehicle refitted before doing this, otherwise the moved
00888      * cargo types might not match (passenger vs non-passenger)
00889      */
00890     DoCommand(0, w_front->index | (p2 & 1 ? CO_SHARE : CO_COPY) << 30, v_front->index, flags, CMD_CLONE_ORDER);
00891 
00892     /* Now clone the vehicle's name, if it has one. */
00893     if (v_front->name != NULL) CloneVehicleName(v_front, w_front);
00894   }
00895 
00896   /* Since we can't estimate the cost of cloning a vehicle accurately we must
00897    * check whether the company has enough money manually. */
00898   if (!CheckCompanyHasMoney(total_cost)) {
00899     if (flags & DC_EXEC) {
00900       /* The vehicle has already been bought, so now it must be sold again. */
00901       DoCommand(w_front->tile, w_front->index | 1 << 20, 0, flags, GetCmdSellVeh(w_front));
00902     }
00903     return total_cost;
00904   }
00905 
00906   return total_cost;
00907 }
00908 
00916 static CommandCost SendAllVehiclesToDepot(DoCommandFlag flags, bool service, const VehicleListIdentifier &vli)
00917 {
00918   VehicleList list;
00919 
00920   if (!GenerateVehicleSortList(&list, vli)) return CMD_ERROR;
00921 
00922   /* Send all the vehicles to a depot */
00923   bool had_success = false;
00924   for (uint i = 0; i < list.Length(); i++) {
00925     const Vehicle *v = list[i];
00926     CommandCost ret = DoCommand(v->tile, v->index | (service ? DEPOT_SERVICE : 0U) | DEPOT_DONT_CANCEL, 0, flags, GetCmdSendToDepot(vli.vtype));
00927 
00928     if (ret.Succeeded()) {
00929       had_success = true;
00930 
00931       /* Return 0 if DC_EXEC is not set this is a valid goto depot command)
00932        * In this case we know that at least one vehicle can be sent to a depot
00933        * and we will issue the command. We can now safely quit the loop, knowing
00934        * it will succeed at least once. With DC_EXEC we really need to send them to the depot */
00935       if (!(flags & DC_EXEC)) break;
00936     }
00937   }
00938 
00939   return had_success ? CommandCost() : CMD_ERROR;
00940 }
00941 
00953 CommandCost CmdSendVehicleToDepot(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00954 {
00955   if (p1 & DEPOT_MASS_SEND) {
00956     /* Mass goto depot requested */
00957     VehicleListIdentifier vli;
00958     if (!vli.Unpack(p2)) return CMD_ERROR;
00959     return SendAllVehiclesToDepot(flags, (p1 & DEPOT_SERVICE) != 0, vli);
00960   }
00961 
00962   Vehicle *v = Vehicle::GetIfValid(GB(p1, 0, 20));
00963   if (v == NULL) return CMD_ERROR;
00964 
00965   return v->SendToDepot(flags, (DepotCommand)(p1 & DEPOT_COMMAND_MASK));
00966 }
00967 
00977 CommandCost CmdRenameVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00978 {
00979   Vehicle *v = Vehicle::GetIfValid(p1);
00980   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
00981 
00982   CommandCost ret = CheckOwnership(v->owner);
00983   if (ret.Failed()) return ret;
00984 
00985   bool reset = StrEmpty(text);
00986 
00987   if (!reset) {
00988     if (Utf8StringLength(text) >= MAX_LENGTH_VEHICLE_NAME_CHARS) return CMD_ERROR;
00989     if (!(flags & DC_AUTOREPLACE) && !IsUniqueVehicleName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
00990   }
00991 
00992   if (flags & DC_EXEC) {
00993     free(v->name);
00994     v->name = reset ? NULL : strdup(text);
00995     InvalidateWindowClassesData(WC_TRAINS_LIST, 1);
00996     MarkWholeScreenDirty();
00997   }
00998 
00999   return CommandCost();
01000 }
01001 
01002 
01012 CommandCost CmdChangeServiceInt(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01013 {
01014   Vehicle *v = Vehicle::GetIfValid(p1);
01015   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
01016 
01017   CommandCost ret = CheckOwnership(v->owner);
01018   if (ret.Failed()) return ret;
01019 
01020   uint16 serv_int = GetServiceIntervalClamped(p2, v->owner); // Double check the service interval from the user-input
01021   if (serv_int != p2) return CMD_ERROR;
01022 
01023   if (flags & DC_EXEC) {
01024     v->service_interval = serv_int;
01025     SetWindowDirty(WC_VEHICLE_DETAILS, v->index);
01026   }
01027 
01028   return CommandCost();
01029 }