vehicle_cmd.cpp

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