# vehicle_cmd.cpp

Go to the documentation of this file.

    00001 /* $Id: vehicle_cmd.cpp 15718 2009-03-15 00:32:18Z rubidium $ */
    00002
    00005 #include "stdafx.h"
    00006 #include "roadveh.h"
    00007 #include "gfx_func.h"
    00008 #include "news_func.h"
    00009 #include "command_func.h"
    00010 #include "company_func.h"
    00011 #include "vehicle_gui.h"
    00012 #include "train.h"
    00013 #include "newgrf_engine.h"
    00014 #include "newgrf_text.h"
    00015 #include "functions.h"
    00016 #include "window_func.h"
    00017 #include "vehicle_func.h"
    00018 #include "string_func.h"
    00019 #include "depot_map.h"
    00020 #include "vehiclelist.h"
    00021
    00022 #include "table/strings.h"
    00023
    00024 /* Tables used in vehicle.h to find the right command for a certain vehicle type */
    00025 const uint32 _veh_build_proc_table[] = {
    00026   CMD_BUILD_RAIL_VEHICLE,
    00027   CMD_BUILD_ROAD_VEH,
    00028   CMD_BUILD_SHIP,
    00029   CMD_BUILD_AIRCRAFT,
    00030 };
    00031 const uint32 _veh_sell_proc_table[] = {
    00032   CMD_SELL_RAIL_WAGON,
    00033   CMD_SELL_ROAD_VEH,
    00034   CMD_SELL_SHIP,
    00035   CMD_SELL_AIRCRAFT,
    00036 };
    00037
    00038 const uint32 _veh_refit_proc_table[] = {
    00039   CMD_REFIT_RAIL_VEHICLE,
    00040   CMD_REFIT_ROAD_VEH,
    00041   CMD_REFIT_SHIP,
    00042   CMD_REFIT_AIRCRAFT,
    00043 };
    00044
    00045 const uint32 _send_to_depot_proc_table[] = {
    00046   CMD_SEND_TRAIN_TO_DEPOT,
    00047   CMD_SEND_ROADVEH_TO_DEPOT,
    00048   CMD_SEND_SHIP_TO_DEPOT,
    00049   CMD_SEND_AIRCRAFT_TO_HANGAR,
    00050 };
    00051
    00059 CommandCost CmdStartStopVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00060 {
    00061   /* Disable the effect of p2 bit 0, when DC_AUTOREPLACE is not set */
    00062   if ((flags & DC_AUTOREPLACE) == 0) SetBit(p2, 0);
    00063
    00064   if (!IsValidVehicleID(p1)) return CMD_ERROR;
    00065
    00066   Vehicle *v = GetVehicle(p1);
    00067
    00068   if (!CheckOwnership(v->owner)) return CMD_ERROR;
    00069   if (!v->IsPrimaryVehicle()) return CMD_ERROR;
    00070
    00071   switch (v->type) {
    00072     case VEH_TRAIN:
    00073       if (v->vehstatus & VS_STOPPED && v->u.rail.cached_power == 0) return_cmd_error(STR_TRAIN_START_NO_CATENARY);
    00074       break;
    00075
    00076     case VEH_SHIP:
    00077     case VEH_ROAD:
    00078       break;
    00079
    00080     case VEH_AIRCRAFT:
    00081       /* cannot stop airplane when in flight, or when taking off / landing */
    00082       if (v->u.air.state >= STARTTAKEOFF && v->u.air.state < TERM7) return_cmd_error(STR_A017_AIRCRAFT_IS_IN_FLIGHT);
    00083       break;
    00084
    00085     default: return CMD_ERROR;
    00086   }
    00087
    00088   /* Check if this vehicle can be started/stopped. The callback will fail or
    00089    * return 0xFF if it can. */
    00090   uint16 callback = GetVehicleCallback(CBID_VEHICLE_START_STOP_CHECK, 0, 0, v->engine_type, v);
    00091   if (callback != CALLBACK_FAILED && GB(callback, 0, 8) != 0xFF && HasBit(p2, 0)) {
    00092     StringID error = GetGRFStringID(GetEngineGRFID(v->engine_type), 0xD000 + callback);
    00093     return_cmd_error(error);
    00094   }
    00095
    00096   if (flags & DC_EXEC) {
    00097     static const StringID vehicle_waiting_in_depot[] = {
    00098       STR_8814_TRAIN_IS_WAITING_IN_DEPOT,
    00099       STR_9016_ROAD_VEHICLE_IS_WAITING,
    00100       STR_981C_SHIP_IS_WAITING_IN_DEPOT,
    00101       STR_A014_AIRCRAFT_IS_WAITING_IN,
    00102     };
    00103
    00104     static const WindowClass vehicle_list[] = {
    00105       WC_TRAINS_LIST,
    00106       WC_ROADVEH_LIST,
    00107       WC_SHIPS_LIST,
    00108       WC_AIRCRAFT_LIST,
    00109     };
    00110
    00111     if (v->IsStoppedInDepot() && (flags & DC_AUTOREPLACE) == 0) DeleteVehicleNews(p1, vehicle_waiting_in_depot[v->type]);
    00112
    00113     v->vehstatus ^= VS_STOPPED;
    00114     if (v->type != VEH_TRAIN) v->cur_speed = 0; // trains can stop 'slowly'
    00115     InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
    00116     InvalidateWindow(WC_VEHICLE_DEPOT, v->tile);
    00117     InvalidateWindowClasses(vehicle_list[v->type]);
    00118   }
    00119   return CommandCost();
    00120 }
    00121
    00132 CommandCost CmdMassStartStopVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00133 {
    00134   VehicleList list;
    00135   CommandCost return_value = CMD_ERROR;
    00136   VehicleType vehicle_type = (VehicleType)GB(p2, 0, 5);
    00137   bool start_stop = HasBit(p2, 5);
    00138   bool vehicle_list_window = HasBit(p2, 6);
    00139
    00140   if (vehicle_list_window) {
    00141     uint32 id = p1;
    00142     uint16 window_type = p2 & VLW_MASK;
    00143
    00144     GenerateVehicleSortList(&list, vehicle_type, _current_company, id, window_type);
    00145   } else {
    00146     /* Get the list of vehicles in the depot */
    00147     BuildDepotVehicleList(vehicle_type, tile, &list, NULL);
    00148   }
    00149
    00150   for (uint i = 0; i < list.Length(); i++) {
    00151     const Vehicle *v = list[i];
    00152
    00153     if (!!(v->vehstatus & VS_STOPPED) != start_stop) continue;
    00154
    00155     if (!vehicle_list_window) {
    00156       if (vehicle_type == VEH_TRAIN) {
    00157         if (CheckTrainInDepot(v, false) == -1) continue;
    00158       } else {
    00159         if (!(v->vehstatus & VS_HIDDEN)) continue;
    00160       }
    00161     }
    00162
    00163     CommandCost ret = DoCommand(tile, v->index, 0, flags, CMD_START_STOP_VEHICLE);
    00164
    00165     if (CmdSucceeded(ret)) {
    00166       return_value = CommandCost();
    00167       /* We know that the command is valid for at least one vehicle.
    00168        * If we haven't set DC_EXEC, then there is no point in continueing because it will be valid */
    00169       if (!(flags & DC_EXEC)) break;
    00170     }
    00171   }
    00172
    00173   return return_value;
    00174 }
    00175
    00182 CommandCost CmdDepotSellAllVehicles(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00183 {
    00184   VehicleList list;
    00185
    00186   CommandCost cost(EXPENSES_NEW_VEHICLES);
    00187   uint sell_command;
    00188   VehicleType vehicle_type = (VehicleType)GB(p1, 0, 8);
    00189
    00190   switch (vehicle_type) {
    00191     case VEH_TRAIN:    sell_command = CMD_SELL_RAIL_WAGON; break;
    00192     case VEH_ROAD:     sell_command = CMD_SELL_ROAD_VEH;   break;
    00193     case VEH_SHIP:     sell_command = CMD_SELL_SHIP;       break;
    00194     case VEH_AIRCRAFT: sell_command = CMD_SELL_AIRCRAFT;   break;
    00195     default: return CMD_ERROR;
    00196   }
    00197
    00198   /* Get the list of vehicles in the depot */
    00199   BuildDepotVehicleList(vehicle_type, tile, &list, &list);
    00200
    00201   for (uint i = 0; i < list.Length(); i++) {
    00202     CommandCost ret = DoCommand(tile, list[i]->index, 1, flags, sell_command);
    00203     if (CmdSucceeded(ret)) cost.AddCost(ret);
    00204   }
    00205
    00206   if (cost.GetCost() == 0) return CMD_ERROR; // no vehicles to sell
    00207   return cost;
    00208 }
    00209
    00219 CommandCost CmdDepotMassAutoReplace(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00220 {
    00221   VehicleList list;
    00222   CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES);
    00223   VehicleType vehicle_type = (VehicleType)GB(p1, 0, 8);
    00224   bool all_or_nothing = HasBit(p2, 0);
    00225
    00226   if (!IsDepotTile(tile) || !IsTileOwner(tile, _current_company)) return CMD_ERROR;
    00227
    00228   /* Get the list of vehicles in the depot */
    00229   BuildDepotVehicleList(vehicle_type, tile, &list, &list, true);
    00230
    00231   bool did_something = false;
    00232
    00233   for (uint i = 0; i < list.Length(); i++) {
    00234     Vehicle *v = (Vehicle*)list[i];
    00235
    00236     /* Ensure that the vehicle completely in the depot */
    00237     if (!v->IsInDepot()) continue;
    00238
    00239     CommandCost ret = DoCommand(0, v->index, 0, flags, CMD_AUTOREPLACE_VEHICLE);
    00240
    00241     if (CmdSucceeded(ret)) {
    00242       did_something = true;
    00243       cost.AddCost(ret);
    00244     } else {
    00245       if (ret.GetErrorMessage() != STR_AUTOREPLACE_NOTHING_TO_DO && all_or_nothing) {
    00246         /* We failed to replace a vehicle even though we set all or nothing.
    00247          * We should never reach this if DC_EXEC is set since then it should
    00248          * have failed the estimation guess. */
    00249         assert(!(flags & DC_EXEC));
    00250         /* Now we will have to return an error. */
    00251         return CMD_ERROR;
    00252       }
    00253     }
    00254   }
    00255
    00256   if (!did_something) {
    00257     /* Either we didn't replace anything or something went wrong.
    00258      * Either way we want to return an error and not execute this command. */
    00259     cost = CMD_ERROR;
    00260   }
    00261
    00262   return cost;
    00263 }
    00264
    00269 static bool IsUniqueVehicleName(const char *name)
    00270 {
    00271   const Vehicle *v;
    00272
    00273   FOR_ALL_VEHICLES(v) {
    00274     if (v->name != NULL && strcmp(v->name, name) == 0) return false;
    00275   }
    00276
    00277   return true;
    00278 }
    00279
    00284 static void CloneVehicleName(const Vehicle *src, Vehicle *dst)
    00285 {
    00286   char buf[256];
    00287
    00288   /* Find the position of the first digit in the last group of digits. */
    00289   size_t number_position;
    00290   for (number_position = strlen(src->name); number_position > 0; number_position--) {
    00291     /* The design of UTF-8 lets this work simply without having to check
    00292      * for UTF-8 sequences. */
    00293     if (src->name[number_position - 1] < '0' || src->name[number_position - 1] > '9') break;
    00294   }
    00295
    00296   /* Format buffer and determine starting number. */
    00297   int num;
    00298   if (number_position == strlen(src->name)) {
    00299     /* No digit at the end, so start at number 2. */
    00300     strecpy(buf, src->name, lastof(buf));
    00301     strecat(buf, " ", lastof(buf));
    00302     number_position = strlen(buf);
    00303     num = 2;
    00304   } else {
    00305     /* Found digits, parse them and start at the next number. */
    00306     strecpy(buf, src->name, lastof(buf));
    00307     buf[number_position] = '\0';
    00308     num = strtol(&src->name[number_position], NULL, 10) + 1;
    00309   }
    00310
    00311   /* Check if this name is already taken. */
    00312   for (int max_iterations = 1000; max_iterations > 0; max_iterations--, num++) {
    00313     /* Attach the number to the temporary name. */
    00314     seprintf(&buf[number_position], lastof(buf), "%d", num);
    00315
    00316     /* Check the name is unique. */
    00317     if (IsUniqueVehicleName(buf)) {
    00318       dst->name = strdup(buf);
    00319       break;
    00320     }
    00321   }
    00322
    00323   /* All done. If we didn't find a name, it'll just use its default. */
    00324 }
    00325
    00332 CommandCost CmdCloneVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00333 {
    00334   CommandCost total_cost(EXPENSES_NEW_VEHICLES);
    00335   uint32 build_argument = 2;
    00336
    00337   if (!IsValidVehicleID(p1)) return CMD_ERROR;
    00338
    00339   Vehicle *v = GetVehicle(p1);
    00340   Vehicle *v_front = v;
    00341   Vehicle *w = NULL;
    00342   Vehicle *w_front = NULL;
    00343   Vehicle *w_rear = NULL;
    00344
    00345   /*
    00346    * v_front is the front engine in the original vehicle
    00347    * v is the car/vehicle of the original vehicle, that is currently being copied
    00348    * w_front is the front engine of the cloned vehicle
    00349    * w is the car/vehicle currently being cloned
    00350    * w_rear is the rear end of the cloned train. It's used to add more cars and is only used by trains
    00351    */
    00352
    00353   if (!CheckOwnership(v->owner)) return CMD_ERROR;
    00354
    00355   if (v->type == VEH_TRAIN && (!IsFrontEngine(v) || v->u.rail.crash_anim_pos >= 4400)) return CMD_ERROR;
    00356
    00357   /* check that we can allocate enough vehicles */
    00358   if (!(flags & DC_EXEC)) {
    00359     int veh_counter = 0;
    00360     do {
    00361       veh_counter++;
    00362     } while ((v = v->Next()) != NULL);
    00363
    00364     if (!Vehicle::AllocateList(NULL, veh_counter)) {
    00365       return_cmd_error(STR_00E1_TOO_MANY_VEHICLES_IN_GAME);
    00366     }
    00367   }
    00368
    00369   v = v_front;
    00370
    00371   do {
    00372     if (v->type == VEH_TRAIN && IsRearDualheaded(v)) {
    00373       /* we build the rear ends of multiheaded trains with the front ones */
    00374       continue;
    00375     }
    00376
    00377     CommandCost cost = DoCommand(tile, v->engine_type, build_argument, flags, GetCmdBuildVeh(v));
    00378     build_argument = 3; // ensure that we only assign a number to the first engine
    00379
    00380     if (CmdFailed(cost)) return cost;
    00381
    00382     total_cost.AddCost(cost);
    00383
    00384     if (flags & DC_EXEC) {
    00385       w = GetVehicle(_new_vehicle_id);
    00386
    00387       if (v->type == VEH_TRAIN && HasBit(v->u.rail.flags, VRF_REVERSE_DIRECTION)) {
    00388         SetBit(w->u.rail.flags, VRF_REVERSE_DIRECTION);
    00389       }
    00390
    00391       if (v->type == VEH_TRAIN && !IsFrontEngine(v)) {
    00392         /* this s a train car
    00393          * add this unit to the end of the train */
    00394         CommandCost result = DoCommand(0, (w_rear->index << 16) | w->index, 1, flags, CMD_MOVE_RAIL_VEHICLE);
    00395         if (CmdFailed(result)) {
    00396           /* The train can't be joined to make the same consist as the original.
    00397            * Sell what we already made (clean up) and return an error.           */
    00398           DoCommand(w_front->tile, w_front->index, 1, flags, GetCmdSellVeh(w_front));
    00399           DoCommand(w_front->tile, w->index,       1, flags, GetCmdSellVeh(w));
    00400           return result; // return error and the message returned from CMD_MOVE_RAIL_VEHICLE
    00401         }
    00402       } else {
    00403         /* this is a front engine or not a train. */
    00404         w_front = w;
    00405         w->service_interval = v->service_interval;
    00406       }
    00407       w_rear = w; // trains needs to know the last car in the train, so they can add more in next loop
    00408     }
    00409   } while (v->type == VEH_TRAIN && (v = GetNextVehicle(v)) != NULL);
    00410
    00411   if (flags & DC_EXEC && v_front->type == VEH_TRAIN) {
    00412     /* for trains this needs to be the front engine due to the callback function */
    00413     _new_vehicle_id = w_front->index;
    00414   }
    00415
    00416   if (flags & DC_EXEC) {
    00417     /* Cloned vehicles belong to the same group */
    00418     DoCommand(0, v_front->group_id, w_front->index, flags, CMD_ADD_VEHICLE_GROUP);
    00419   }
    00420
    00421
    00422   /* Take care of refitting. */
    00423   w = w_front;
    00424   v = v_front;
    00425
    00426   /* Both building and refitting are influenced by newgrf callbacks, which
    00427    * makes it impossible to accurately estimate the cloning costs. In
    00428    * particular, it is possible for engines of the same type to be built with
    00429    * different numbers of articulated parts, so when refitting we have to
    00430    * loop over real vehicles first, and then the articulated parts of those
    00431    * vehicles in a different loop. */
    00432   do {
    00433     do {
    00434       if (flags & DC_EXEC) {
    00435         assert(w != NULL);
    00436
    00437         if (w->cargo_type != v->cargo_type || w->cargo_subtype != v->cargo_subtype) {
    00438           CommandCost cost = DoCommand(0, w->index, v->cargo_type | (v->cargo_subtype << 8) | 1U << 16 , flags, GetCmdRefitVeh(v));
    00439           if (CmdSucceeded(cost)) total_cost.AddCost(cost);
    00440         }
    00441
    00442         if (w->type == VEH_TRAIN && EngineHasArticPart(w)) {
    00443           w = GetNextArticPart(w);
    00444         } else if (w->type == VEH_ROAD && RoadVehHasArticPart(w)) {
    00445           w = w->Next();
    00446         } else {
    00447           break;
    00448         }
    00449       } else {
    00450         const Engine *e = GetEngine(v->engine_type);
    00451         CargoID initial_cargo = (e->CanCarryCargo() ? e->GetDefaultCargoType() : (CargoID)CT_INVALID);
    00452
    00453         if (v->cargo_type != initial_cargo && initial_cargo != CT_INVALID) {
    00454           total_cost.AddCost(GetRefitCost(v->engine_type));
    00455         }
    00456       }
    00457
    00458       if (v->type == VEH_TRAIN && EngineHasArticPart(v)) {
    00459         v = GetNextArticPart(v);
    00460       } else if (v->type == VEH_ROAD && RoadVehHasArticPart(v)) {
    00461         v = v->Next();
    00462       } else {
    00463         break;
    00464       }
    00465     } while (v != NULL);
    00466
    00467     if ((flags & DC_EXEC) && v->type == VEH_TRAIN) w = GetNextVehicle(w);
    00468   } while (v->type == VEH_TRAIN && (v = GetNextVehicle(v)) != NULL);
    00469
    00470   if (flags & DC_EXEC) {
    00471     /*
    00472      * Set the orders of the vehicle. Cannot do it earlier as we need
    00473      * the vehicle refitted before doing this, otherwise the moved
    00474      * cargo types might not match (passenger vs non-passenger)
    00475      */
    00476     DoCommand(0, (v_front->index << 16) | w_front->index, p2 & 1 ? CO_SHARE : CO_COPY, flags, CMD_CLONE_ORDER);
    00477
    00478     /* Now clone the vehicle's name, if it has one. */
    00479     if (v_front->name != NULL) CloneVehicleName(v_front, w_front);
    00480   }
    00481
    00482   /* Since we can't estimate the cost of cloning a vehicle accurately we must
    00483    * check whether the company has enough money manually. */
    00484   if (!CheckCompanyHasMoney(total_cost)) {
    00485     if (flags & DC_EXEC) {
    00486       /* The vehicle has already been bought, so now it must be sold again. */
    00487       DoCommand(w_front->tile, w_front->index, 1, flags, GetCmdSellVeh(w_front));
    00488     }
    00489     return CMD_ERROR;
    00490   }
    00491
    00492   return total_cost;
    00493 }
    00494
    00504 CommandCost SendAllVehiclesToDepot(VehicleType type, DoCommandFlag flags, bool service, Owner owner, uint16 vlw_flag, uint32 id)
    00505 {
    00506   VehicleList list;
    00507
    00508   GenerateVehicleSortList(&list, type, owner, id, vlw_flag);
    00509
    00510   /* Send all the vehicles to a depot */
    00511   for (uint i = 0; i < list.Length(); i++) {
    00512     const Vehicle *v = list[i];
    00513     CommandCost ret = DoCommand(v->tile, v->index, (service ? 1 : 0) | DEPOT_DONT_CANCEL, flags, GetCmdSendToDepot(type));
    00514
    00515     /* Return 0 if DC_EXEC is not set this is a valid goto depot command)
    00516      * In this case we know that at least one vehicle can be sent to a depot
    00517      * and we will issue the command. We can now safely quit the loop, knowing
    00518      * it will succeed at least once. With DC_EXEC we really need to send them to the depot */
    00519     if (CmdSucceeded(ret) && !(flags & DC_EXEC)) {
    00520       return CommandCost();
    00521     }
    00522   }
    00523
    00524   return (flags & DC_EXEC) ? CommandCost() : CMD_ERROR;
    00525 }
    00526
    00533 CommandCost CmdRenameVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00534 {
    00535   if (!IsValidVehicleID(p1)) return CMD_ERROR;
    00536
    00537   Vehicle *v = GetVehicle(p1);
    00538   if (!CheckOwnership(v->owner)) return CMD_ERROR;
    00539
    00540   bool reset = StrEmpty(text);
    00541
    00542   if (!reset) {
    00543     if (strlen(text) >= MAX_LENGTH_VEHICLE_NAME_BYTES) return CMD_ERROR;
    00544     if (!(flags & DC_AUTOREPLACE) && !IsUniqueVehicleName(text)) return_cmd_error(STR_NAME_MUST_BE_UNIQUE);
    00545   }
    00546
    00547   if (flags & DC_EXEC) {
    00548     free(v->name);
    00549     v->name = reset ? NULL : strdup(text);
    00550     InvalidateWindowClassesData(WC_TRAINS_LIST, 1);
    00551     MarkWholeScreenDirty();
    00552   }
    00553
    00554   return CommandCost();
    00555 }
    00556
    00557
    00564 CommandCost CmdChangeServiceInt(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00565 {
    00566   uint16 serv_int = GetServiceIntervalClamped(p2); // Double check the service interval from the user-input
    00567
    00568   if (serv_int != p2 || !IsValidVehicleID(p1)) return CMD_ERROR;
    00569
    00570   Vehicle *v = GetVehicle(p1);
    00571
    00572   if (!CheckOwnership(v->owner)) return CMD_ERROR;
    00573
    00574   if (flags & DC_EXEC) {
    00575     v->service_interval = serv_int;
    00576     InvalidateWindow(WC_VEHICLE_DETAILS, v->index);
    00577   }
    00578
    00579   return CommandCost();
    00580 }