# vehicle_cmd.cpp

Go to the documentation of this file.

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