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 "functions.h"
00024 #include "window_func.h"
00025 #include "vehicle_func.h"
00026 #include "string_func.h"
00027 #include "depot_map.h"
00028 #include "vehiclelist.h"
00029 #include "engine_func.h"
00030 #include "articulated_vehicles.h"
00031 #include "autoreplace_gui.h"
00032 #include "company_base.h"
00033 #include "order_backup.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   /* TrainGotoDepot has a nice randomizer in the pathfinder, which causes desyncs... */
00061   CMD_SEND_VEHICLE_TO_DEPOT | CMD_MSG(STR_ERROR_CAN_T_SEND_TRAIN_TO_DEPOT) | CMD_NO_TEST_IF_IN_NETWORK,
00062   CMD_SEND_VEHICLE_TO_DEPOT | CMD_MSG(STR_ERROR_CAN_T_SEND_ROAD_VEHICLE_TO_DEPOT),
00063   CMD_SEND_VEHICLE_TO_DEPOT | CMD_MSG(STR_ERROR_CAN_T_SEND_SHIP_TO_DEPOT),
00064   CMD_SEND_VEHICLE_TO_DEPOT | CMD_MSG(STR_ERROR_CAN_T_SEND_AIRCRAFT_TO_HANGAR),
00065 };
00066 
00067 
00068 CommandCost CmdBuildRailVehicle(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **v);
00069 CommandCost CmdBuildRoadVehicle(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **v);
00070 CommandCost CmdBuildShip       (TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **v);
00071 CommandCost CmdBuildAircraft   (TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **v);
00072 
00084 CommandCost CmdBuildVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00085 {
00086   /* Elementary check for valid location. */
00087   if (!IsDepotTile(tile) || !IsTileOwner(tile, _current_company)) return CMD_ERROR;
00088 
00089   VehicleType type;
00090   switch (GetTileType(tile)) {
00091     case MP_RAILWAY: type = VEH_TRAIN;    break;
00092     case MP_ROAD:    type = VEH_ROAD;     break;
00093     case MP_WATER:   type = VEH_SHIP;     break;
00094     case MP_STATION: type = VEH_AIRCRAFT; break;
00095     default: NOT_REACHED(); // Safe due to IsDepotTile()
00096   }
00097 
00098   /* Validate the engine type. */
00099   EngineID eid = GB(p1, 0, 16);
00100   if (!IsEngineBuildable(eid, type, _current_company)) return_cmd_error(STR_ERROR_RAIL_VEHICLE_NOT_AVAILABLE + type);
00101 
00102   const Engine *e = Engine::Get(eid);
00103   CommandCost value(EXPENSES_NEW_VEHICLES, e->GetCost());
00104 
00105   /* Engines without valid cargo should not be available */
00106   if (e->GetDefaultCargoType() == CT_INVALID) return CMD_ERROR;
00107 
00108   /* Check whether the number of vehicles we need to build can be built according to pool space. */
00109   uint num_vehicles;
00110   switch (type) {
00111     case VEH_TRAIN:    num_vehicles = (e->u.rail.railveh_type == RAILVEH_MULTIHEAD ? 2 : 1) + CountArticulatedParts(eid, false); break;
00112     case VEH_ROAD:     num_vehicles = 1 + CountArticulatedParts(eid, false); break;
00113     case VEH_SHIP:     num_vehicles = 1; break;
00114     case VEH_AIRCRAFT: num_vehicles = e->u.air.subtype & AIR_CTOL ? 2 : 3; break;
00115     default: NOT_REACHED(); // Safe due to IsDepotTile()
00116   }
00117   if (!Vehicle::CanAllocateItem(num_vehicles)) return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
00118 
00119   /* Check whether we can allocate a unit number. Autoreplace does not allocate
00120    * an unit number as it will (always) reuse the one of the replaced vehicle
00121    * and (train) wagons don't have an unit number in any scenario. */
00122   UnitID unit_num = (flags & DC_AUTOREPLACE || (type == VEH_TRAIN && e->u.rail.railveh_type == RAILVEH_WAGON)) ? 0 : GetFreeUnitNumber(type);
00123   if (unit_num == UINT16_MAX) return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
00124 
00125   Vehicle *v;
00126   switch (type) {
00127     case VEH_TRAIN:    value.AddCost(CmdBuildRailVehicle(tile, flags, e, GB(p1, 16, 16), &v)); break;
00128     case VEH_ROAD:     value.AddCost(CmdBuildRoadVehicle(tile, flags, e, GB(p1, 16, 16), &v)); break;
00129     case VEH_SHIP:     value.AddCost(CmdBuildShip       (tile, flags, e, GB(p1, 16, 16), &v)); break;
00130     case VEH_AIRCRAFT: value.AddCost(CmdBuildAircraft   (tile, flags, e, GB(p1, 16, 16), &v)); break;
00131     default: NOT_REACHED(); // Safe due to IsDepotTile()
00132   }
00133 
00134   if (value.Succeeded() && flags & DC_EXEC) {
00135     v->unitnumber = unit_num;
00136     v->value      = value.GetCost();
00137 
00138     InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
00139     InvalidateWindowClassesData(GetWindowClassForVehicleType(type), 0);
00140     SetWindowDirty(WC_COMPANY, _current_company);
00141     if (IsLocalCompany()) {
00142       InvalidateAutoreplaceWindow(v->engine_type, v->group_id); // updates the auto replace window
00143     }
00144 
00145     Company::Get(_current_company)->num_engines[eid]++;
00146 
00147     if (v->IsPrimaryVehicle()) OrderBackup::Restore(v, p2);
00148   }
00149 
00150   return value;
00151 }
00152 
00153 CommandCost CmdSellRailWagon(DoCommandFlag flags, Vehicle *v, uint16 data, uint32 user);
00154 
00167 CommandCost CmdSellVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00168 {
00169   Vehicle *v = Vehicle::GetIfValid(GB(p1, 0, 20));
00170   if (v == NULL) return CMD_ERROR;
00171 
00172   Vehicle *front = v->First();
00173 
00174   CommandCost ret = CheckOwnership(front->owner);
00175   if (ret.Failed()) return ret;
00176 
00177   if (front->vehstatus & VS_CRASHED) return_cmd_error(STR_ERROR_VEHICLE_IS_DESTROYED);
00178 
00179   if (!front->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAIN_MUST_BE_STOPPED_INSIDE_DEPOT + front->type);
00180 
00181   /* Can we actually make the order backup, i.e. are there enough orders? */
00182   if (p1 & MAKE_ORDER_BACKUP_FLAG &&
00183       front->orders.list != NULL &&
00184       !front->orders.list->IsShared() &&
00185       !Order::CanAllocateItem(front->orders.list->GetNumOrders())) {
00186     /* Only happens in exceptional cases when there aren't enough orders anyhow.
00187      * Thus it should be safe to just drop the orders in that case. */
00188     p1 &= ~MAKE_ORDER_BACKUP_FLAG;
00189   }
00190 
00191   if (v->type == VEH_TRAIN) {
00192     ret = CmdSellRailWagon(flags, v, GB(p1, 20, 12), p2);
00193   } else {
00194     ret = CommandCost(EXPENSES_NEW_VEHICLES, -front->value);
00195 
00196     if (flags & DC_EXEC) {
00197       if (v->IsPrimaryVehicle() && p1 & MAKE_ORDER_BACKUP_FLAG) OrderBackup::Backup(v, p2);
00198       delete front;
00199     }
00200   }
00201 
00202   return ret;
00203 }
00204 
00210 static CommandCost GetRefitCost(EngineID engine_type)
00211 {
00212   ExpensesType expense_type;
00213   const Engine *e = Engine::Get(engine_type);
00214   Price base_price;
00215   uint cost_factor = e->info.refit_cost;
00216   switch (e->type) {
00217     case VEH_SHIP:
00218       base_price = PR_BUILD_VEHICLE_SHIP;
00219       expense_type = EXPENSES_SHIP_RUN;
00220       break;
00221 
00222     case VEH_ROAD:
00223       base_price = PR_BUILD_VEHICLE_ROAD;
00224       expense_type = EXPENSES_ROADVEH_RUN;
00225       break;
00226 
00227     case VEH_AIRCRAFT:
00228       base_price = PR_BUILD_VEHICLE_AIRCRAFT;
00229       expense_type = EXPENSES_AIRCRAFT_RUN;
00230       break;
00231 
00232     case VEH_TRAIN:
00233       base_price = (e->u.rail.railveh_type == RAILVEH_WAGON) ? PR_BUILD_VEHICLE_WAGON : PR_BUILD_VEHICLE_TRAIN;
00234       cost_factor <<= 1;
00235       expense_type = EXPENSES_TRAIN_RUN;
00236       break;
00237 
00238     default: NOT_REACHED();
00239   }
00240   return CommandCost(expense_type, GetPrice(base_price, cost_factor, e->grf_prop.grffile, -10));
00241 }
00242 
00254 static CommandCost RefitVehicle(Vehicle *v, bool only_this, uint8 num_vehicles, CargoID new_cid, byte new_subtype, DoCommandFlag flags)
00255 {
00256   CommandCost cost(v->GetExpenseType(false));
00257   uint total_capacity = 0;
00258   uint total_mail_capacity = 0;
00259   num_vehicles = num_vehicles == 0 ? UINT8_MAX : num_vehicles;
00260 
00261   VehicleSet vehicles_to_refit;
00262   if (!only_this) {
00263     GetVehicleSet(vehicles_to_refit, v, num_vehicles);
00264     /* In this case, we need to check the whole chain. */
00265     v = v->First();
00266   }
00267 
00268   v->InvalidateNewGRFCacheOfChain();
00269   for (; v != NULL; v = (only_this ? NULL : v->Next())) {
00270     if (v->type == VEH_TRAIN && !vehicles_to_refit.Contains(v->index) && !only_this) continue;
00271 
00272     const Engine *e = Engine::Get(v->engine_type);
00273     if (!e->CanCarryCargo() || !HasBit(e->info.refit_mask, new_cid)) continue;
00274 
00275     /* Back up the vehicle's cargo type */
00276     CargoID temp_cid = v->cargo_type;
00277     byte temp_subtype = v->cargo_subtype;
00278     v->cargo_type = new_cid;
00279     v->cargo_subtype = new_subtype;
00280 
00281     uint16 mail_capacity = 0;
00282     uint amount = GetVehicleCapacity(v, &mail_capacity);
00283     total_capacity += amount;
00284     /* mail_capacity will always be zero if the vehicle is not an aircraft. */
00285     total_mail_capacity += mail_capacity;
00286 
00287     /* Restore the original cargo type */
00288     v->cargo_type = temp_cid;
00289     v->cargo_subtype = temp_subtype;
00290 
00291     if (new_cid != v->cargo_type) {
00292       cost.AddCost(GetRefitCost(v->engine_type));
00293     }
00294 
00295     if (flags & DC_EXEC) {
00296       v->cargo.Truncate((v->cargo_type == new_cid) ? amount : 0);
00297       v->cargo_type = new_cid;
00298       v->cargo_cap = amount;
00299       v->cargo_subtype = new_subtype;
00300       if (v->type == VEH_AIRCRAFT) {
00301         Vehicle *u = v->Next();
00302         u->cargo_cap = mail_capacity;
00303         u->cargo.Truncate(mail_capacity);
00304       }
00305     }
00306   }
00307 
00308   _returned_refit_capacity = total_capacity;
00309   _returned_mail_refit_capacity = total_mail_capacity;
00310   return cost;
00311 }
00312 
00326 CommandCost CmdRefitVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00327 {
00328   Vehicle *v = Vehicle::GetIfValid(p1);
00329   if (v == NULL) return CMD_ERROR;
00330 
00331   /* Don't allow disasters and sparks and such to be refitted.
00332    * We cannot check for IsPrimaryVehicle as autoreplace also refits in free wagon chains. */
00333   if (!IsCompanyBuildableVehicleType(v->type)) return CMD_ERROR;
00334 
00335   Vehicle *front = v->First();
00336 
00337   CommandCost ret = CheckOwnership(front->owner);
00338   if (ret.Failed()) return ret;
00339 
00340   /* Don't allow shadows and such to be refitted. */
00341   if (v != front && (v->type == VEH_SHIP || v->type == VEH_AIRCRAFT)) return CMD_ERROR;
00342   if (!front->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAIN_MUST_BE_STOPPED_INSIDE_DEPOT + front->type);
00343   if (front->vehstatus & VS_CRASHED) return_cmd_error(STR_ERROR_VEHICLE_IS_DESTROYED);
00344 
00345   /* Check cargo */
00346   CargoID new_cid = GB(p2, 0, 8);
00347   byte new_subtype = GB(p2, 8, 8);
00348   if (new_cid >= NUM_CARGO) return CMD_ERROR;
00349 
00350   /* For ships and aircrafts there is always only one. */
00351   bool only_this = HasBit(p2, 16) || front->type == VEH_SHIP || front->type == VEH_AIRCRAFT;
00352   uint8 num_vehicles = GB(p2, 17, 8);
00353 
00354   CommandCost cost = RefitVehicle(v, only_this, num_vehicles, new_cid, new_subtype, flags);
00355 
00356   if (flags & DC_EXEC) {
00357     /* Update the cached variables */
00358     switch (v->type) {
00359       case VEH_TRAIN:
00360         Train::From(front)->ConsistChanged(false);
00361         break;
00362       case VEH_ROAD:
00363         RoadVehUpdateCache(RoadVehicle::From(front));
00364         if (_settings_game.vehicle.roadveh_acceleration_model != AM_ORIGINAL) RoadVehicle::From(front)->CargoChanged();
00365         break;
00366 
00367       case VEH_SHIP:
00368       case VEH_AIRCRAFT:
00369         v->InvalidateNewGRFCacheOfChain();
00370         v->colourmap = PAL_NONE; // invalidate vehicle colour map
00371         break;
00372 
00373       default: NOT_REACHED();
00374     }
00375 
00376     InvalidateWindowData(WC_VEHICLE_DETAILS, front->index);
00377     SetWindowDirty(WC_VEHICLE_DEPOT, front->tile);
00378     InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
00379   } else {
00380     /* Always invalidate the cache; querycost might have filled it. */
00381     v->InvalidateNewGRFCacheOfChain();
00382   }
00383 
00384   return cost;
00385 }
00386 
00396 CommandCost CmdStartStopVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00397 {
00398   /* Disable the effect of p2 bit 0, when DC_AUTOREPLACE is not set */
00399   if ((flags & DC_AUTOREPLACE) == 0) SetBit(p2, 0);
00400 
00401   Vehicle *v = Vehicle::GetIfValid(p1);
00402   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
00403 
00404   CommandCost ret = CheckOwnership(v->owner);
00405   if (ret.Failed()) return ret;
00406 
00407   if (v->vehstatus & VS_CRASHED) return_cmd_error(STR_ERROR_VEHICLE_IS_DESTROYED);
00408 
00409   switch (v->type) {
00410     case VEH_TRAIN:
00411       if ((v->vehstatus & VS_STOPPED) && Train::From(v)->gcache.cached_power == 0) return_cmd_error(STR_ERROR_TRAIN_START_NO_CATENARY);
00412       break;
00413 
00414     case VEH_SHIP:
00415     case VEH_ROAD:
00416       break;
00417 
00418     case VEH_AIRCRAFT: {
00419       Aircraft *a = Aircraft::From(v);
00420       /* cannot stop airplane when in flight, or when taking off / landing */
00421       if (!(v->vehstatus & VS_CRASHED) && a->state >= STARTTAKEOFF && a->state < TERM7) return_cmd_error(STR_ERROR_AIRCRAFT_IS_IN_FLIGHT);
00422       break;
00423     }
00424 
00425     default: return CMD_ERROR;
00426   }
00427 
00428   /* Check if this vehicle can be started/stopped. The callback will fail or
00429    * return 0xFF if it can. */
00430   uint16 callback = GetVehicleCallback(CBID_VEHICLE_START_STOP_CHECK, 0, 0, v->engine_type, v);
00431   if (callback != CALLBACK_FAILED && GB(callback, 0, 8) != 0xFF && HasBit(p2, 0)) {
00432     StringID error = GetGRFStringID(GetEngineGRFID(v->engine_type), 0xD000 + callback);
00433     return_cmd_error(error);
00434   }
00435 
00436   if (flags & DC_EXEC) {
00437     if (v->IsStoppedInDepot() && (flags & DC_AUTOREPLACE) == 0) DeleteVehicleNews(p1, STR_NEWS_TRAIN_IS_WAITING + v->type);
00438 
00439     v->vehstatus ^= VS_STOPPED;
00440     if (v->type != VEH_TRAIN) v->cur_speed = 0; // trains can stop 'slowly'
00441     v->MarkDirty();
00442     SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
00443     SetWindowDirty(WC_VEHICLE_DEPOT, v->tile);
00444     SetWindowClassesDirty(GetWindowClassForVehicleType(v->type));
00445   }
00446   return CommandCost();
00447 }
00448 
00460 CommandCost CmdMassStartStopVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00461 {
00462   VehicleList list;
00463   bool do_start = HasBit(p1, 0);
00464   bool vehicle_list_window = HasBit(p1, 1);
00465 
00466   VehicleListIdentifier vli;
00467   if (!vli.Unpack(p2)) return CMD_ERROR;
00468   if (!IsCompanyBuildableVehicleType(vli.vtype)) return CMD_ERROR;
00469 
00470   if (vehicle_list_window) {
00471     if (!GenerateVehicleSortList(&list, vli)) return CMD_ERROR;
00472   } else {
00473     /* Get the list of vehicles in the depot */
00474     BuildDepotVehicleList(vli.vtype, tile, &list, NULL);
00475   }
00476 
00477   for (uint i = 0; i < list.Length(); i++) {
00478     const Vehicle *v = list[i];
00479 
00480     if (!!(v->vehstatus & VS_STOPPED) != do_start) continue;
00481 
00482     if (!vehicle_list_window) {
00483       if (vli.vtype == VEH_TRAIN) {
00484         if (!Train::From(v)->IsInDepot()) continue;
00485       } else {
00486         if (!(v->vehstatus & VS_HIDDEN)) continue;
00487       }
00488     }
00489 
00490     /* Just try and don't care if some vehicle's can't be stopped. */
00491     DoCommand(tile, v->index, 0, flags, CMD_START_STOP_VEHICLE);
00492   }
00493 
00494   return CommandCost();
00495 }
00496 
00506 CommandCost CmdDepotSellAllVehicles(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00507 {
00508   VehicleList list;
00509 
00510   CommandCost cost(EXPENSES_NEW_VEHICLES);
00511   VehicleType vehicle_type = Extract<VehicleType, 0, 3>(p1);
00512   uint sell_command = GetCmdSellVeh(vehicle_type);
00513 
00514   if (!IsCompanyBuildableVehicleType(vehicle_type)) return CMD_ERROR;
00515 
00516   /* Get the list of vehicles in the depot */
00517   BuildDepotVehicleList(vehicle_type, tile, &list, &list);
00518 
00519   CommandCost last_error = CMD_ERROR;
00520   bool had_success = false;
00521   for (uint i = 0; i < list.Length(); i++) {
00522     CommandCost ret = DoCommand(tile, list[i]->index | (1 << 20), 0, flags, sell_command);
00523     if (ret.Succeeded()) {
00524       cost.AddCost(ret);
00525       had_success = true;
00526     } else {
00527       last_error = ret;
00528     }
00529   }
00530 
00531   return had_success ? cost : last_error;
00532 }
00533 
00543 CommandCost CmdDepotMassAutoReplace(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00544 {
00545   VehicleList list;
00546   CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES);
00547   VehicleType vehicle_type = Extract<VehicleType, 0, 3>(p1);
00548 
00549   if (!IsCompanyBuildableVehicleType(vehicle_type)) return CMD_ERROR;
00550   if (!IsDepotTile(tile) || !IsTileOwner(tile, _current_company)) return CMD_ERROR;
00551 
00552   /* Get the list of vehicles in the depot */
00553   BuildDepotVehicleList(vehicle_type, tile, &list, &list, true);
00554 
00555   for (uint i = 0; i < list.Length(); i++) {
00556     const Vehicle *v = list[i];
00557 
00558     /* Ensure that the vehicle completely in the depot */
00559     if (!v->IsInDepot()) continue;
00560 
00561     CommandCost ret = DoCommand(0, v->index, 0, flags, CMD_AUTOREPLACE_VEHICLE);
00562 
00563     if (ret.Succeeded()) cost.AddCost(ret);
00564   }
00565   return cost;
00566 }
00567 
00573 static bool IsUniqueVehicleName(const char *name)
00574 {
00575   const Vehicle *v;
00576 
00577   FOR_ALL_VEHICLES(v) {
00578     if (v->name != NULL && strcmp(v->name, name) == 0) return false;
00579   }
00580 
00581   return true;
00582 }
00583 
00589 static void CloneVehicleName(const Vehicle *src, Vehicle *dst)
00590 {
00591   char buf[256];
00592 
00593   /* Find the position of the first digit in the last group of digits. */
00594   size_t number_position;
00595   for (number_position = strlen(src->name); number_position > 0; number_position--) {
00596     /* The design of UTF-8 lets this work simply without having to check
00597      * for UTF-8 sequences. */
00598     if (src->name[number_position - 1] < '0' || src->name[number_position - 1] > '9') break;
00599   }
00600 
00601   /* Format buffer and determine starting number. */
00602   int num;
00603   byte padding = 0;
00604   if (number_position == strlen(src->name)) {
00605     /* No digit at the end, so start at number 2. */
00606     strecpy(buf, src->name, lastof(buf));
00607     strecat(buf, " ", lastof(buf));
00608     number_position = strlen(buf);
00609     num = 2;
00610   } else {
00611     /* Found digits, parse them and start at the next number. */
00612     strecpy(buf, src->name, lastof(buf));
00613     buf[number_position] = '\0';
00614     char *endptr;
00615     num = strtol(&src->name[number_position], &endptr, 10) + 1;
00616     padding = endptr - &src->name[number_position];
00617   }
00618 
00619   /* Check if this name is already taken. */
00620   for (int max_iterations = 1000; max_iterations > 0; max_iterations--, num++) {
00621     /* Attach the number to the temporary name. */
00622     seprintf(&buf[number_position], lastof(buf), "%0*d", padding, num);
00623 
00624     /* Check the name is unique. */
00625     if (IsUniqueVehicleName(buf)) {
00626       dst->name = strdup(buf);
00627       break;
00628     }
00629   }
00630 
00631   /* All done. If we didn't find a name, it'll just use its default. */
00632 }
00633 
00643 CommandCost CmdCloneVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00644 {
00645   CommandCost total_cost(EXPENSES_NEW_VEHICLES);
00646 
00647   Vehicle *v = Vehicle::GetIfValid(p1);
00648   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
00649   Vehicle *v_front = v;
00650   Vehicle *w = NULL;
00651   Vehicle *w_front = NULL;
00652   Vehicle *w_rear = NULL;
00653 
00654   /*
00655    * v_front is the front engine in the original vehicle
00656    * v is the car/vehicle of the original vehicle that is currently being copied
00657    * w_front is the front engine of the cloned vehicle
00658    * w is the car/vehicle currently being cloned
00659    * w_rear is the rear end of the cloned train. It's used to add more cars and is only used by trains
00660    */
00661 
00662   CommandCost ret = CheckOwnership(v->owner);
00663   if (ret.Failed()) return ret;
00664 
00665   if (v->type == VEH_TRAIN && (!Train::From(v)->IsFrontEngine() || Train::From(v)->crash_anim_pos >= 4400)) return CMD_ERROR;
00666 
00667   /* check that we can allocate enough vehicles */
00668   if (!(flags & DC_EXEC)) {
00669     int veh_counter = 0;
00670     do {
00671       veh_counter++;
00672     } while ((v = v->Next()) != NULL);
00673 
00674     if (!Vehicle::CanAllocateItem(veh_counter)) {
00675       return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
00676     }
00677   }
00678 
00679   v = v_front;
00680 
00681   do {
00682     if (v->type == VEH_TRAIN && Train::From(v)->IsRearDualheaded()) {
00683       /* we build the rear ends of multiheaded trains with the front ones */
00684       continue;
00685     }
00686 
00687     /* In case we're building a multi headed vehicle and the maximum number of
00688      * vehicles is almost reached (e.g. max trains - 1) not all vehicles would
00689      * be cloned. When the non-primary engines were build they were seen as
00690      * 'new' vehicles whereas they would immediately be joined with a primary
00691      * engine. This caused the vehicle to be not build as 'the limit' had been
00692      * reached, resulting in partially build vehicles and such. */
00693     DoCommandFlag build_flags = flags;
00694     if ((flags & DC_EXEC) && !v->IsPrimaryVehicle()) build_flags |= DC_AUTOREPLACE;
00695 
00696     CommandCost cost = DoCommand(tile, v->engine_type | (1 << 16), 0, build_flags, GetCmdBuildVeh(v));
00697 
00698     if (cost.Failed()) {
00699       /* Can't build a part, then sell the stuff we already made; clear up the mess */
00700       if (w_front != NULL) DoCommand(w_front->tile, w_front->index | (1 << 20), 0, flags, GetCmdSellVeh(w_front));
00701       return cost;
00702     }
00703 
00704     total_cost.AddCost(cost);
00705 
00706     if (flags & DC_EXEC) {
00707       w = Vehicle::Get(_new_vehicle_id);
00708 
00709       if (v->type == VEH_TRAIN && HasBit(Train::From(v)->flags, VRF_REVERSE_DIRECTION)) {
00710         SetBit(Train::From(w)->flags, VRF_REVERSE_DIRECTION);
00711       }
00712 
00713       if (v->type == VEH_TRAIN && !Train::From(v)->IsFrontEngine()) {
00714         /* this s a train car
00715          * add this unit to the end of the train */
00716         CommandCost result = DoCommand(0, w->index | 1 << 20, w_rear->index, flags, CMD_MOVE_RAIL_VEHICLE);
00717         if (result.Failed()) {
00718           /* The train can't be joined to make the same consist as the original.
00719            * Sell what we already made (clean up) and return an error.           */
00720           DoCommand(w_front->tile, w_front->index | 1 << 20, 0, flags, GetCmdSellVeh(w_front));
00721           DoCommand(w_front->tile, w->index       | 1 << 20, 0, flags, GetCmdSellVeh(w));
00722           return result; // return error and the message returned from CMD_MOVE_RAIL_VEHICLE
00723         }
00724       } else {
00725         /* this is a front engine or not a train. */
00726         w_front = w;
00727         w->service_interval = v->service_interval;
00728       }
00729       w_rear = w; // trains needs to know the last car in the train, so they can add more in next loop
00730     }
00731   } while (v->type == VEH_TRAIN && (v = Train::From(v)->GetNextVehicle()) != NULL);
00732 
00733   if ((flags & DC_EXEC) && v_front->type == VEH_TRAIN) {
00734     /* for trains this needs to be the front engine due to the callback function */
00735     _new_vehicle_id = w_front->index;
00736   }
00737 
00738   if (flags & DC_EXEC) {
00739     /* Cloned vehicles belong to the same group */
00740     DoCommand(0, v_front->group_id, w_front->index, flags, CMD_ADD_VEHICLE_GROUP);
00741   }
00742 
00743 
00744   /* Take care of refitting. */
00745   w = w_front;
00746   v = v_front;
00747 
00748   /* Both building and refitting are influenced by newgrf callbacks, which
00749    * makes it impossible to accurately estimate the cloning costs. In
00750    * particular, it is possible for engines of the same type to be built with
00751    * different numbers of articulated parts, so when refitting we have to
00752    * loop over real vehicles first, and then the articulated parts of those
00753    * vehicles in a different loop. */
00754   do {
00755     do {
00756       if (flags & DC_EXEC) {
00757         assert(w != NULL);
00758 
00759         /* Find out what's the best sub type */
00760         byte subtype = GetBestFittingSubType(v, w);
00761         if (w->cargo_type != v->cargo_type || w->cargo_subtype != subtype) {
00762           CommandCost cost = DoCommand(0, w->index, v->cargo_type | (subtype << 8) | 1U << 16, flags, GetCmdRefitVeh(v));
00763           if (cost.Succeeded()) total_cost.AddCost(cost);
00764         }
00765 
00766         if (w->type == VEH_TRAIN && Train::From(w)->HasArticulatedPart()) {
00767           w = Train::From(w)->GetNextArticulatedPart();
00768         } else if (w->type == VEH_ROAD && RoadVehicle::From(w)->HasArticulatedPart()) {
00769           w = w->Next();
00770         } else {
00771           break;
00772         }
00773       } else {
00774         const Engine *e = Engine::Get(v->engine_type);
00775         CargoID initial_cargo = (e->CanCarryCargo() ? e->GetDefaultCargoType() : (CargoID)CT_INVALID);
00776 
00777         if (v->cargo_type != initial_cargo && initial_cargo != CT_INVALID) {
00778           total_cost.AddCost(GetRefitCost(v->engine_type));
00779         }
00780       }
00781 
00782       if (v->type == VEH_TRAIN && Train::From(v)->HasArticulatedPart()) {
00783         v = Train::From(v)->GetNextArticulatedPart();
00784       } else if (v->type == VEH_ROAD && RoadVehicle::From(v)->HasArticulatedPart()) {
00785         v = v->Next();
00786       } else {
00787         break;
00788       }
00789     } while (v != NULL);
00790 
00791     if ((flags & DC_EXEC) && v->type == VEH_TRAIN) w = Train::From(w)->GetNextVehicle();
00792   } while (v->type == VEH_TRAIN && (v = Train::From(v)->GetNextVehicle()) != NULL);
00793 
00794   if (flags & DC_EXEC) {
00795     /*
00796      * Set the orders of the vehicle. Cannot do it earlier as we need
00797      * the vehicle refitted before doing this, otherwise the moved
00798      * cargo types might not match (passenger vs non-passenger)
00799      */
00800     DoCommand(0, w_front->index | (p2 & 1 ? CO_SHARE : CO_COPY) << 30, v_front->index, flags, CMD_CLONE_ORDER);
00801 
00802     /* Now clone the vehicle's name, if it has one. */
00803     if (v_front->name != NULL) CloneVehicleName(v_front, w_front);
00804   }
00805 
00806   /* Since we can't estimate the cost of cloning a vehicle accurately we must
00807    * check whether the company has enough money manually. */
00808   if (!CheckCompanyHasMoney(total_cost)) {
00809     if (flags & DC_EXEC) {
00810       /* The vehicle has already been bought, so now it must be sold again. */
00811       DoCommand(w_front->tile, w_front->index | 1 << 20, 0, flags, GetCmdSellVeh(w_front));
00812     }
00813     return total_cost;
00814   }
00815 
00816   return total_cost;
00817 }
00818 
00826 static CommandCost SendAllVehiclesToDepot(DoCommandFlag flags, bool service, const VehicleListIdentifier &vli)
00827 {
00828   VehicleList list;
00829 
00830   if (!GenerateVehicleSortList(&list, vli)) return CMD_ERROR;
00831 
00832   /* Send all the vehicles to a depot */
00833   bool had_success = false;
00834   for (uint i = 0; i < list.Length(); i++) {
00835     const Vehicle *v = list[i];
00836     CommandCost ret = DoCommand(v->tile, v->index | (service ? DEPOT_SERVICE : 0U) | DEPOT_DONT_CANCEL, 0, flags, GetCmdSendToDepot(vli.vtype));
00837 
00838     if (ret.Succeeded()) {
00839       had_success = true;
00840 
00841       /* Return 0 if DC_EXEC is not set this is a valid goto depot command)
00842        * In this case we know that at least one vehicle can be sent to a depot
00843        * and we will issue the command. We can now safely quit the loop, knowing
00844        * it will succeed at least once. With DC_EXEC we really need to send them to the depot */
00845       if (!(flags & DC_EXEC)) break;
00846     }
00847   }
00848 
00849   return had_success ? CommandCost() : CMD_ERROR;
00850 }
00851 
00863 CommandCost CmdSendVehicleToDepot(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00864 {
00865   if (p1 & DEPOT_MASS_SEND) {
00866     /* Mass goto depot requested */
00867     VehicleListIdentifier vli;
00868     if (!vli.Unpack(p2)) return CMD_ERROR;
00869     return SendAllVehiclesToDepot(flags, (p1 & DEPOT_SERVICE) != 0, vli);
00870   }
00871 
00872   Vehicle *v = Vehicle::GetIfValid(GB(p1, 0, 20));
00873   if (v == NULL) return CMD_ERROR;
00874 
00875   return v->SendToDepot(flags, (DepotCommand)(p1 & DEPOT_COMMAND_MASK));
00876 }
00877 
00887 CommandCost CmdRenameVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00888 {
00889   Vehicle *v = Vehicle::GetIfValid(p1);
00890   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
00891 
00892   CommandCost ret = CheckOwnership(v->owner);
00893   if (ret.Failed()) return ret;
00894 
00895   bool reset = StrEmpty(text);
00896 
00897   if (!reset) {
00898     if (Utf8StringLength(text) >= MAX_LENGTH_VEHICLE_NAME_CHARS) return CMD_ERROR;
00899     if (!(flags & DC_AUTOREPLACE) && !IsUniqueVehicleName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
00900   }
00901 
00902   if (flags & DC_EXEC) {
00903     free(v->name);
00904     v->name = reset ? NULL : strdup(text);
00905     InvalidateWindowClassesData(WC_TRAINS_LIST, 1);
00906     MarkWholeScreenDirty();
00907   }
00908 
00909   return CommandCost();
00910 }
00911 
00912 
00922 CommandCost CmdChangeServiceInt(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00923 {
00924   Vehicle *v = Vehicle::GetIfValid(p1);
00925   if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
00926 
00927   CommandCost ret = CheckOwnership(v->owner);
00928   if (ret.Failed()) return ret;
00929 
00930   uint16 serv_int = GetServiceIntervalClamped(p2, v->owner); // Double check the service interval from the user-input
00931   if (serv_int != p2) return CMD_ERROR;
00932 
00933   if (flags & DC_EXEC) {
00934     v->service_interval = serv_int;
00935     SetWindowDirty(WC_VEHICLE_DETAILS, v->index);
00936   }
00937 
00938   return CommandCost();
00939 }

Generated on Sun Jan 23 01:49:12 2011 for OpenTTD by  doxygen 1.6.1