4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * 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/>.
10 /** @file vehicle_cmd.cpp Commands for vehicles. */
14 #include "news_func.h"
16 #include "cmd_helper.h"
17 #include "command_func.h"
18 #include "company_func.h"
21 #include "newgrf_text.h"
22 #include "vehicle_func.h"
23 #include "string_func.h"
24 #include "depot_func.h"
25 #include "vehiclelist.h"
26 #include "engine_func.h"
27 #include "articulated_vehicles.h"
28 #include "autoreplace_gui.h"
30 #include "order_backup.h"
33 #include "company_base.h"
35 #include "table/strings.h"
37 /* Tables used in vehicle.h to find the right command for a certain vehicle type */
38 const uint32 _veh_build_proc_table
[] = {
39 CMD_BUILD_VEHICLE
| CMD_MSG(STR_ERROR_CAN_T_BUY_TRAIN
),
40 CMD_BUILD_VEHICLE
| CMD_MSG(STR_ERROR_CAN_T_BUY_ROAD_VEHICLE
),
41 CMD_BUILD_VEHICLE
| CMD_MSG(STR_ERROR_CAN_T_BUY_SHIP
),
42 CMD_BUILD_VEHICLE
| CMD_MSG(STR_ERROR_CAN_T_BUY_AIRCRAFT
),
45 const uint32 _veh_sell_proc_table
[] = {
46 CMD_SELL_VEHICLE
| CMD_MSG(STR_ERROR_CAN_T_SELL_TRAIN
),
47 CMD_SELL_VEHICLE
| CMD_MSG(STR_ERROR_CAN_T_SELL_ROAD_VEHICLE
),
48 CMD_SELL_VEHICLE
| CMD_MSG(STR_ERROR_CAN_T_SELL_SHIP
),
49 CMD_SELL_VEHICLE
| CMD_MSG(STR_ERROR_CAN_T_SELL_AIRCRAFT
),
52 const uint32 _veh_refit_proc_table
[] = {
53 CMD_REFIT_VEHICLE
| CMD_MSG(STR_ERROR_CAN_T_REFIT_TRAIN
),
54 CMD_REFIT_VEHICLE
| CMD_MSG(STR_ERROR_CAN_T_REFIT_ROAD_VEHICLE
),
55 CMD_REFIT_VEHICLE
| CMD_MSG(STR_ERROR_CAN_T_REFIT_SHIP
),
56 CMD_REFIT_VEHICLE
| CMD_MSG(STR_ERROR_CAN_T_REFIT_AIRCRAFT
),
59 const uint32 _send_to_depot_proc_table
[] = {
60 CMD_SEND_VEHICLE_TO_DEPOT
| CMD_MSG(STR_ERROR_CAN_T_SEND_TRAIN_TO_DEPOT
),
61 CMD_SEND_VEHICLE_TO_DEPOT
| CMD_MSG(STR_ERROR_CAN_T_SEND_ROAD_VEHICLE_TO_DEPOT
),
62 CMD_SEND_VEHICLE_TO_DEPOT
| CMD_MSG(STR_ERROR_CAN_T_SEND_SHIP_TO_DEPOT
),
63 CMD_SEND_VEHICLE_TO_DEPOT
| CMD_MSG(STR_ERROR_CAN_T_SEND_AIRCRAFT_TO_HANGAR
),
67 CommandCost
CmdBuildRailVehicle(TileIndex tile
, DoCommandFlag flags
, const Engine
*e
, uint16 data
, Vehicle
**v
);
68 CommandCost
CmdBuildRoadVehicle(TileIndex tile
, DoCommandFlag flags
, const Engine
*e
, uint16 data
, Vehicle
**v
);
69 CommandCost
CmdBuildShip (TileIndex tile
, DoCommandFlag flags
, const Engine
*e
, uint16 data
, Vehicle
**v
);
70 CommandCost
CmdBuildAircraft (TileIndex tile
, DoCommandFlag flags
, const Engine
*e
, uint16 data
, Vehicle
**v
);
74 * @param tile tile of depot where the vehicle is built
75 * @param flags for command
76 * @param p1 various bitstuffed data
77 * bits 0-15: vehicle type being built.
78 * bits 16-31: vehicle type specific bits passed on to the vehicle build functions.
81 * @return the cost of this operation or an error
83 CommandCost
CmdBuildVehicle(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
85 /* Elementary check for valid location. */
86 if (!IsDepotTile(tile
) || !IsTileOwner(tile
, _current_company
)) return CMD_ERROR
;
88 VehicleType type
= GetDepotVehicleType(tile
);
90 /* Validate the engine type. */
91 EngineID eid
= GB(p1
, 0, 16);
92 if (!IsEngineBuildable(eid
, type
, _current_company
)) return_cmd_error(STR_ERROR_RAIL_VEHICLE_NOT_AVAILABLE
+ type
);
94 const Engine
*e
= Engine::Get(eid
);
95 CommandCost
value(EXPENSES_NEW_VEHICLES
, e
->GetCost());
97 /* Engines without valid cargo should not be available */
98 if (e
->GetDefaultCargoType() == CT_INVALID
) return CMD_ERROR
;
100 /* Check whether the number of vehicles we need to build can be built according to pool space. */
103 case VEH_TRAIN
: num_vehicles
= (e
->u
.rail
.railveh_type
== RAILVEH_MULTIHEAD
? 2 : 1) + CountArticulatedParts(eid
, false); break;
104 case VEH_ROAD
: num_vehicles
= 1 + CountArticulatedParts(eid
, false); break;
105 case VEH_SHIP
: num_vehicles
= 1; break;
106 case VEH_AIRCRAFT
: num_vehicles
= e
->u
.air
.subtype
& AIR_CTOL
? 2 : 3; break;
107 default: NOT_REACHED(); // Safe due to IsDepotTile()
109 if (!Vehicle::CanAllocateItem(num_vehicles
)) return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME
);
111 /* Check whether we can allocate a unit number. Autoreplace does not allocate
112 * an unit number as it will (always) reuse the one of the replaced vehicle
113 * and (train) wagons don't have an unit number in any scenario. */
114 UnitID unit_num
= (flags
& DC_AUTOREPLACE
|| (type
== VEH_TRAIN
&& e
->u
.rail
.railveh_type
== RAILVEH_WAGON
)) ? 0 : GetFreeUnitNumber(type
);
115 if (unit_num
== UINT16_MAX
) return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME
);
119 case VEH_TRAIN
: value
.AddCost(CmdBuildRailVehicle(tile
, flags
, e
, GB(p1
, 16, 16), &v
)); break;
120 case VEH_ROAD
: value
.AddCost(CmdBuildRoadVehicle(tile
, flags
, e
, GB(p1
, 16, 16), &v
)); break;
121 case VEH_SHIP
: value
.AddCost(CmdBuildShip (tile
, flags
, e
, GB(p1
, 16, 16), &v
)); break;
122 case VEH_AIRCRAFT
: value
.AddCost(CmdBuildAircraft (tile
, flags
, e
, GB(p1
, 16, 16), &v
)); break;
123 default: NOT_REACHED(); // Safe due to IsDepotTile()
126 if (value
.Succeeded() && flags
& DC_EXEC
) {
127 v
->unitnumber
= unit_num
;
128 v
->value
= value
.GetCost();
130 InvalidateWindowData(WC_VEHICLE_DEPOT
, v
->tile
);
131 InvalidateWindowClassesData(GetWindowClassForVehicleType(type
), 0);
132 SetWindowDirty(WC_COMPANY
, _current_company
);
133 if (IsLocalCompany()) {
134 InvalidateAutoreplaceWindow(v
->engine_type
, v
->group_id
); // updates the auto replace window (must be called before incrementing num_engines)
137 GroupStatistics::CountEngine(v
, 1);
138 GroupStatistics::UpdateAutoreplace(_current_company
);
140 if (v
->IsPrimaryVehicle()) {
141 GroupStatistics::CountVehicle(v
, 1);
142 OrderBackup::Restore(v
, p2
);
149 CommandCost
CmdSellRailWagon(DoCommandFlag flags
, Vehicle
*v
, uint16 data
, uint32 user
);
153 * @param tile unused.
154 * @param flags for command.
155 * @param p1 various bitstuffed data.
156 * bits 0-19: vehicle ID being sold.
157 * bits 20-30: vehicle type specific bits passed on to the vehicle build functions.
158 * bit 31: make a backup of the vehicle's order (if an engine).
160 * @param text unused.
161 * @return the cost of this operation or an error.
163 CommandCost
CmdSellVehicle(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
165 Vehicle
*v
= Vehicle::GetIfValid(GB(p1
, 0, 20));
166 if (v
== NULL
) return CMD_ERROR
;
168 Vehicle
*front
= v
->First();
170 CommandCost ret
= CheckOwnership(front
->owner
);
171 if (ret
.Failed()) return ret
;
173 if (front
->vehstatus
& VS_CRASHED
) return_cmd_error(STR_ERROR_VEHICLE_IS_DESTROYED
);
175 if (!front
->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAIN_MUST_BE_STOPPED_INSIDE_DEPOT
+ front
->type
);
177 /* Can we actually make the order backup, i.e. are there enough orders? */
178 if (p1
& MAKE_ORDER_BACKUP_FLAG
&&
179 front
->orders
.list
!= NULL
&&
180 !front
->orders
.list
->IsShared() &&
181 !Order::CanAllocateItem(front
->orders
.list
->GetNumOrders())) {
182 /* Only happens in exceptional cases when there aren't enough orders anyhow.
183 * Thus it should be safe to just drop the orders in that case. */
184 p1
&= ~MAKE_ORDER_BACKUP_FLAG
;
187 if (v
->type
== VEH_TRAIN
) {
188 ret
= CmdSellRailWagon(flags
, v
, GB(p1
, 20, 12), p2
);
190 ret
= CommandCost(EXPENSES_NEW_VEHICLES
, -front
->value
);
192 if (flags
& DC_EXEC
) {
193 if (front
->IsPrimaryVehicle() && p1
& MAKE_ORDER_BACKUP_FLAG
) OrderBackup::Backup(front
, p2
);
202 * Helper to run the refit cost callback.
203 * @param v The vehicle we are refitting, can be NULL.
204 * @param engine_type Which engine to refit
205 * @param new_cid Cargo type we are refitting to.
206 * @param new_subtype New cargo subtype.
207 * @param [out] auto_refit_allowed The refit is allowed as an auto-refit.
208 * @return Price for refitting
210 static int GetRefitCostFactor(const Vehicle
*v
, EngineID engine_type
, CargoID new_cid
, byte new_subtype
, bool *auto_refit_allowed
)
212 /* Prepare callback param with info about the new cargo type. */
213 const Engine
*e
= Engine::Get(engine_type
);
215 /* Is this vehicle a NewGRF vehicle? */
216 if (e
->GetGRF() != NULL
) {
217 const CargoSpec
*cs
= CargoSpec::Get(new_cid
);
218 uint32 param1
= (cs
->classes
<< 16) | (new_subtype
<< 8) | e
->GetGRF()->cargo_map
[new_cid
];
220 uint16 cb_res
= GetVehicleCallback(CBID_VEHICLE_REFIT_COST
, param1
, 0, engine_type
, v
);
221 if (cb_res
!= CALLBACK_FAILED
) {
222 *auto_refit_allowed
= HasBit(cb_res
, 14);
223 int factor
= GB(cb_res
, 0, 14);
224 if (factor
>= 0x2000) factor
-= 0x4000; // Treat as signed integer.
229 *auto_refit_allowed
= e
->info
.refit_cost
== 0;
230 return (v
== NULL
|| v
->cargo_type
!= new_cid
) ? e
->info
.refit_cost
: 0;
234 * Learn the price of refitting a certain engine
235 * @param v The vehicle we are refitting, can be NULL.
236 * @param engine_type Which engine to refit
237 * @param new_cid Cargo type we are refitting to.
238 * @param new_subtype New cargo subtype.
239 * @param [out] auto_refit_allowed The refit is allowed as an auto-refit.
240 * @return Price for refitting
242 static CommandCost
GetRefitCost(const Vehicle
*v
, EngineID engine_type
, CargoID new_cid
, byte new_subtype
, bool *auto_refit_allowed
)
244 ExpensesType expense_type
;
245 const Engine
*e
= Engine::Get(engine_type
);
247 int cost_factor
= GetRefitCostFactor(v
, engine_type
, new_cid
, new_subtype
, auto_refit_allowed
);
250 base_price
= PR_BUILD_VEHICLE_SHIP
;
251 expense_type
= EXPENSES_SHIP_RUN
;
255 base_price
= PR_BUILD_VEHICLE_ROAD
;
256 expense_type
= EXPENSES_ROADVEH_RUN
;
260 base_price
= PR_BUILD_VEHICLE_AIRCRAFT
;
261 expense_type
= EXPENSES_AIRCRAFT_RUN
;
265 base_price
= (e
->u
.rail
.railveh_type
== RAILVEH_WAGON
) ? PR_BUILD_VEHICLE_WAGON
: PR_BUILD_VEHICLE_TRAIN
;
267 expense_type
= EXPENSES_TRAIN_RUN
;
270 default: NOT_REACHED();
272 if (cost_factor
< 0) {
273 return CommandCost(expense_type
, -GetPrice(base_price
, -cost_factor
, e
->GetGRF(), -10));
275 return CommandCost(expense_type
, GetPrice(base_price
, cost_factor
, e
->GetGRF(), -10));
279 /** Helper structure for RefitVehicle() */
281 Vehicle
*v
; ///< Vehicle to refit
282 uint capacity
; ///< New capacity of vehicle
283 uint mail_capacity
; ///< New mail capacity of aircraft
284 byte subtype
; ///< cargo subtype to refit to
288 * Refits a vehicle (chain).
289 * This is the vehicle-type independent part of the CmdRefitXXX functions.
290 * @param v The vehicle to refit.
291 * @param only_this Whether to only refit this vehicle, or to check the rest of them.
292 * @param num_vehicles Number of vehicles to refit (not counting articulated parts). Zero means the whole chain.
293 * @param new_cid Cargotype to refit to
294 * @param new_subtype Cargo subtype to refit to. 0xFF means to try keeping the same subtype according to GetBestFittingSubType().
295 * @param flags Command flags
296 * @param auto_refit Refitting is done as automatic refitting outside a depot.
297 * @return Refit cost.
299 static CommandCost
RefitVehicle(Vehicle
*v
, bool only_this
, uint8 num_vehicles
, CargoID new_cid
, byte new_subtype
, DoCommandFlag flags
, bool auto_refit
)
301 CommandCost
cost(v
->GetExpenseType(false));
302 uint total_capacity
= 0;
303 uint total_mail_capacity
= 0;
304 num_vehicles
= num_vehicles
== 0 ? UINT8_MAX
: num_vehicles
;
306 VehicleSet vehicles_to_refit
;
308 GetVehicleSet(vehicles_to_refit
, v
, num_vehicles
);
309 /* In this case, we need to check the whole chain. */
313 static SmallVector
<RefitResult
, 16> refit_result
;
314 refit_result
.Clear();
316 v
->InvalidateNewGRFCacheOfChain();
317 byte actual_subtype
= new_subtype
;
318 for (; v
!= NULL
; v
= (only_this
? NULL
: v
->Next())) {
319 /* Reset actual_subtype for every new vehicle */
320 if (!v
->IsArticulatedPart()) actual_subtype
= new_subtype
;
322 if (v
->type
== VEH_TRAIN
&& !vehicles_to_refit
.Contains(v
->index
) && !only_this
) continue;
324 const Engine
*e
= v
->GetEngine();
325 if (!e
->CanCarryCargo()) continue;
327 /* If the vehicle is not refittable, or does not allow automatic refitting,
328 * count its capacity nevertheless if the cargo matches */
329 bool refittable
= HasBit(e
->info
.refit_mask
, new_cid
) && (!auto_refit
|| HasBit(e
->info
.misc_flags
, EF_AUTO_REFIT
));
330 if (!refittable
&& v
->cargo_type
!= new_cid
) continue;
332 /* Determine best fitting subtype if requested */
333 if (actual_subtype
== 0xFF) {
334 actual_subtype
= GetBestFittingSubType(v
, v
, new_cid
);
337 /* Back up the vehicle's cargo type */
338 CargoID temp_cid
= v
->cargo_type
;
339 byte temp_subtype
= v
->cargo_subtype
;
341 v
->cargo_type
= new_cid
;
342 v
->cargo_subtype
= actual_subtype
;
345 uint16 mail_capacity
= 0;
346 uint amount
= e
->DetermineCapacity(v
, &mail_capacity
);
347 total_capacity
+= amount
;
348 /* mail_capacity will always be zero if the vehicle is not an aircraft. */
349 total_mail_capacity
+= mail_capacity
;
351 if (!refittable
) continue;
353 /* Restore the original cargo type */
354 v
->cargo_type
= temp_cid
;
355 v
->cargo_subtype
= temp_subtype
;
357 bool auto_refit_allowed
;
358 CommandCost refit_cost
= GetRefitCost(v
, v
->engine_type
, new_cid
, actual_subtype
, &auto_refit_allowed
);
359 if (auto_refit
&& !auto_refit_allowed
) {
360 /* Sorry, auto-refitting not allowed, subtract the cargo amount again from the total. */
361 total_capacity
-= amount
;
362 total_mail_capacity
-= mail_capacity
;
364 if (v
->cargo_type
== new_cid
) {
365 /* Add the old capacity nevertheless, if the cargo matches */
366 total_capacity
+= v
->cargo_cap
;
367 if (v
->type
== VEH_AIRCRAFT
) total_mail_capacity
+= v
->Next()->cargo_cap
;
371 cost
.AddCost(refit_cost
);
373 /* Record the refitting.
374 * Do not execute the refitting immediately, so DetermineCapacity and GetRefitCost do the same in test and exec run.
377 * - If the capacity of vehicles depends on other vehicles in the chain, the actual capacity is
378 * set after RefitVehicle() via ConsistChanged() and friends. The estimation via _returned_refit_capacity will be wrong.
379 * - We have to call the refit cost callback with the pre-refit configuration of the chain because we want refit and
380 * autorefit to behave the same, and we need its result for auto_refit_allowed.
382 RefitResult
*result
= refit_result
.Append();
384 result
->capacity
= amount
;
385 result
->mail_capacity
= mail_capacity
;
386 result
->subtype
= actual_subtype
;
389 if (flags
& DC_EXEC
) {
390 /* Store the result */
391 for (RefitResult
*result
= refit_result
.Begin(); result
!= refit_result
.End(); result
++) {
392 Vehicle
*u
= result
->v
;
393 u
->refit_cap
= (u
->cargo_type
== new_cid
) ? min(result
->capacity
, u
->refit_cap
) : 0;
394 if (u
->cargo
.TotalCount() > u
->refit_cap
) u
->cargo
.Truncate(u
->cargo
.TotalCount() - u
->refit_cap
);
395 u
->cargo_type
= new_cid
;
396 u
->cargo_cap
= result
->capacity
;
397 u
->cargo_subtype
= result
->subtype
;
398 if (u
->type
== VEH_AIRCRAFT
) {
399 Vehicle
*w
= u
->Next();
400 w
->refit_cap
= min(w
->refit_cap
, result
->mail_capacity
);
401 w
->cargo_cap
= result
->mail_capacity
;
402 if (w
->cargo
.TotalCount() > w
->refit_cap
) w
->cargo
.Truncate(w
->cargo
.TotalCount() - w
->refit_cap
);
407 refit_result
.Clear();
408 _returned_refit_capacity
= total_capacity
;
409 _returned_mail_refit_capacity
= total_mail_capacity
;
414 * Refits a vehicle to the specified cargo type.
416 * @param flags type of operation
417 * @param p1 vehicle ID to refit
418 * @param p2 various bitstuffed elements
419 * - p2 = (bit 0-4) - New cargo type to refit to.
420 * - p2 = (bit 6) - Automatic refitting.
421 * - p2 = (bit 7) - Refit only this vehicle. Used only for cloning vehicles.
422 * - p2 = (bit 8-15) - New cargo subtype to refit to. 0xFF means to try keeping the same subtype according to GetBestFittingSubType().
423 * - p2 = (bit 16-23) - Number of vehicles to refit (not counting articulated parts). Zero means all vehicles.
424 * Only used if "refit only this vehicle" is false.
426 * @return the cost of this operation or an error
428 CommandCost
CmdRefitVehicle(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
430 Vehicle
*v
= Vehicle::GetIfValid(p1
);
431 if (v
== NULL
) return CMD_ERROR
;
433 /* Don't allow disasters and sparks and such to be refitted.
434 * We cannot check for IsPrimaryVehicle as autoreplace also refits in free wagon chains. */
435 if (!IsCompanyBuildableVehicleType(v
->type
)) return CMD_ERROR
;
437 Vehicle
*front
= v
->First();
439 CommandCost ret
= CheckOwnership(front
->owner
);
440 if (ret
.Failed()) return ret
;
442 bool auto_refit
= HasBit(p2
, 6);
443 bool free_wagon
= v
->type
== VEH_TRAIN
&& Train::From(front
)->IsFreeWagon(); // used by autoreplace/renew
445 /* Don't allow shadows and such to be refitted. */
446 if (v
!= front
&& (v
->type
== VEH_SHIP
|| v
->type
== VEH_AIRCRAFT
)) return CMD_ERROR
;
447 /* Allow auto-refitting only during loading and normal refitting only in a depot. */
448 if (!free_wagon
&& (!auto_refit
|| !front
->current_order
.IsType(OT_LOADING
)) && !front
->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAIN_MUST_BE_STOPPED_INSIDE_DEPOT
+ front
->type
);
449 if (front
->vehstatus
& VS_CRASHED
) return_cmd_error(STR_ERROR_VEHICLE_IS_DESTROYED
);
452 CargoID new_cid
= GB(p2
, 0, 5);
453 byte new_subtype
= GB(p2
, 8, 8);
454 if (new_cid
>= NUM_CARGO
) return CMD_ERROR
;
456 /* For ships and aircrafts there is always only one. */
457 bool only_this
= HasBit(p2
, 7) || front
->type
== VEH_SHIP
|| front
->type
== VEH_AIRCRAFT
;
458 uint8 num_vehicles
= GB(p2
, 16, 8);
460 CommandCost cost
= RefitVehicle(v
, only_this
, num_vehicles
, new_cid
, new_subtype
, flags
, auto_refit
);
462 if (flags
& DC_EXEC
) {
463 /* Update the cached variables */
466 Train::From(front
)->ConsistChanged(auto_refit
);
469 RoadVehUpdateCache(RoadVehicle::From(front
), auto_refit
);
470 if (_settings_game
.vehicle
.roadveh_acceleration_model
!= AM_ORIGINAL
) RoadVehicle::From(front
)->CargoChanged();
474 v
->InvalidateNewGRFCacheOfChain();
475 Ship::From(v
)->UpdateCache();
479 v
->InvalidateNewGRFCacheOfChain();
480 UpdateAircraftCache(Aircraft::From(v
), true);
483 default: NOT_REACHED();
488 InvalidateWindowData(WC_VEHICLE_DETAILS
, front
->index
);
489 InvalidateWindowClassesData(GetWindowClassForVehicleType(v
->type
), 0);
491 SetWindowDirty(WC_VEHICLE_DEPOT
, front
->tile
);
493 /* Always invalidate the cache; querycost might have filled it. */
494 v
->InvalidateNewGRFCacheOfChain();
501 * Start/Stop a vehicle
503 * @param flags type of operation
504 * @param p1 vehicle to start/stop, don't forget to change CcStartStopVehicle if you modify this!
505 * @param p2 bit 0: Shall the start/stop newgrf callback be evaluated (only valid with DC_AUTOREPLACE for network safety)
507 * @return the cost of this operation or an error
509 CommandCost
CmdStartStopVehicle(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
511 /* Disable the effect of p2 bit 0, when DC_AUTOREPLACE is not set */
512 if ((flags
& DC_AUTOREPLACE
) == 0) SetBit(p2
, 0);
514 Vehicle
*v
= Vehicle::GetIfValid(p1
);
515 if (v
== NULL
|| !v
->IsPrimaryVehicle()) return CMD_ERROR
;
517 CommandCost ret
= CheckOwnership(v
->owner
);
518 if (ret
.Failed()) return ret
;
520 if (v
->vehstatus
& VS_CRASHED
) return_cmd_error(STR_ERROR_VEHICLE_IS_DESTROYED
);
524 if ((v
->vehstatus
& VS_STOPPED
) && Train::From(v
)->gcache
.cached_power
== 0) return_cmd_error(STR_ERROR_TRAIN_START_NO_POWER
);
532 Aircraft
*a
= Aircraft::From(v
);
533 /* cannot stop airplane when in flight, or when taking off / landing */
534 if (!(v
->vehstatus
& VS_CRASHED
) && a
->state
>= STARTTAKEOFF
&& a
->state
< TERM7
) return_cmd_error(STR_ERROR_AIRCRAFT_IS_IN_FLIGHT
);
538 default: return CMD_ERROR
;
542 /* Check if this vehicle can be started/stopped. Failure means 'allow'. */
543 uint16 callback
= GetVehicleCallback(CBID_VEHICLE_START_STOP_CHECK
, 0, 0, v
->engine_type
, v
);
544 StringID error
= STR_NULL
;
545 if (callback
!= CALLBACK_FAILED
) {
546 if (v
->GetGRF()->grf_version
< 8) {
547 /* 8 bit result 0xFF means 'allow' */
548 if (callback
< 0x400 && GB(callback
, 0, 8) != 0xFF) error
= GetGRFStringID(v
->GetGRFID(), 0xD000 + callback
);
550 if (callback
< 0x400) {
551 error
= GetGRFStringID(v
->GetGRFID(), 0xD000 + callback
);
557 default: // unknown reason -> disallow
558 error
= STR_ERROR_INCOMPATIBLE_RAIL_TYPES
;
564 if (error
!= STR_NULL
) return_cmd_error(error
);
567 if (flags
& DC_EXEC
) {
568 if (v
->IsStoppedInDepot() && (flags
& DC_AUTOREPLACE
) == 0) DeleteVehicleNews(p1
, STR_NEWS_TRAIN_IS_WAITING
+ v
->type
);
570 v
->vehstatus
^= VS_STOPPED
;
571 if (v
->type
!= VEH_TRAIN
) v
->cur_speed
= 0; // trains can stop 'slowly'
573 SetWindowWidgetDirty(WC_VEHICLE_VIEW
, v
->index
, WID_VV_START_STOP
);
574 SetWindowDirty(WC_VEHICLE_DEPOT
, v
->tile
);
575 SetWindowClassesDirty(GetWindowClassForVehicleType(v
->type
));
577 return CommandCost();
581 * Starts or stops a lot of vehicles
582 * @param tile Tile of the depot where the vehicles are started/stopped (only used for depots)
583 * @param flags type of operation
585 * - bit 0 set = start vehicles, unset = stop vehicles
586 * - bit 1 if set, then it's a vehicle list window, not a depot and Tile is ignored in this case
587 * @param p2 packed VehicleListIdentifier
589 * @return the cost of this operation or an error
591 CommandCost
CmdMassStartStopVehicle(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
594 bool do_start
= HasBit(p1
, 0);
595 bool vehicle_list_window
= HasBit(p1
, 1);
597 VehicleListIdentifier vli
;
598 if (!vli
.Unpack(p2
)) return CMD_ERROR
;
599 if (!IsCompanyBuildableVehicleType(vli
.vtype
)) return CMD_ERROR
;
601 if (vehicle_list_window
) {
602 if (!GenerateVehicleSortList(&list
, vli
)) return CMD_ERROR
;
604 /* Get the list of vehicles in the depot */
605 BuildDepotVehicleList(vli
.vtype
, tile
, &list
, NULL
);
608 for (uint i
= 0; i
< list
.Length(); i
++) {
609 const Vehicle
*v
= list
[i
];
611 if (!!(v
->vehstatus
& VS_STOPPED
) != do_start
) continue;
613 if (!vehicle_list_window
&& !v
->IsChainInDepot()) continue;
615 /* Just try and don't care if some vehicle's can't be stopped. */
616 DoCommand(tile
, v
->index
, 0, flags
, CMD_START_STOP_VEHICLE
);
619 return CommandCost();
623 * Sells all vehicles in a depot
624 * @param tile Tile of the depot where the depot is
625 * @param flags type of operation
626 * @param p1 Vehicle type
629 * @return the cost of this operation or an error
631 CommandCost
CmdDepotSellAllVehicles(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
635 CommandCost
cost(EXPENSES_NEW_VEHICLES
);
636 VehicleType vehicle_type
= Extract
<VehicleType
, 0, 3>(p1
);
638 if (!IsCompanyBuildableVehicleType(vehicle_type
)) return CMD_ERROR
;
640 uint sell_command
= GetCmdSellVeh(vehicle_type
);
642 /* Get the list of vehicles in the depot */
643 BuildDepotVehicleList(vehicle_type
, tile
, &list
, &list
);
645 CommandCost last_error
= CMD_ERROR
;
646 bool had_success
= false;
647 for (uint i
= 0; i
< list
.Length(); i
++) {
648 CommandCost ret
= DoCommand(tile
, list
[i
]->index
| (1 << 20), 0, flags
, sell_command
);
649 if (ret
.Succeeded()) {
657 return had_success
? cost
: last_error
;
661 * Autoreplace all vehicles in the depot
662 * @param tile Tile of the depot where the vehicles are
663 * @param flags type of operation
664 * @param p1 Type of vehicle
667 * @return the cost of this operation or an error
669 CommandCost
CmdDepotMassAutoReplace(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
672 CommandCost cost
= CommandCost(EXPENSES_NEW_VEHICLES
);
673 VehicleType vehicle_type
= Extract
<VehicleType
, 0, 3>(p1
);
675 if (!IsCompanyBuildableVehicleType(vehicle_type
)) return CMD_ERROR
;
676 if (!IsDepotTile(tile
) || !IsTileOwner(tile
, _current_company
)) return CMD_ERROR
;
678 /* Get the list of vehicles in the depot */
679 BuildDepotVehicleList(vehicle_type
, tile
, &list
, &list
, true);
681 for (uint i
= 0; i
< list
.Length(); i
++) {
682 const Vehicle
*v
= list
[i
];
684 /* Ensure that the vehicle completely in the depot */
685 if (!v
->IsChainInDepot()) continue;
687 CommandCost ret
= DoCommand(0, v
->index
, 0, flags
, CMD_AUTOREPLACE_VEHICLE
);
689 if (ret
.Succeeded()) cost
.AddCost(ret
);
695 * Test if a name is unique among vehicle names.
696 * @param name Name to test.
697 * @return True ifffffff the name is unique.
699 static bool IsUniqueVehicleName(const char *name
)
703 FOR_ALL_VEHICLES(v
) {
704 if (v
->name
!= NULL
&& strcmp(v
->name
, name
) == 0) return false;
711 * Clone the custom name of a vehicle, adding or incrementing a number.
712 * @param src Source vehicle, with a custom name.
713 * @param dst Destination vehicle.
715 static void CloneVehicleName(const Vehicle
*src
, Vehicle
*dst
)
719 /* Find the position of the first digit in the last group of digits. */
720 size_t number_position
;
721 for (number_position
= strlen(src
->name
); number_position
> 0; number_position
--) {
722 /* The design of UTF-8 lets this work simply without having to check
723 * for UTF-8 sequences. */
724 if (src
->name
[number_position
- 1] < '0' || src
->name
[number_position
- 1] > '9') break;
727 /* Format buffer and determine starting number. */
730 if (number_position
== strlen(src
->name
)) {
731 /* No digit at the end, so start at number 2. */
732 strecpy(buf
, src
->name
, lastof(buf
));
733 strecat(buf
, " ", lastof(buf
));
734 number_position
= strlen(buf
);
737 /* Found digits, parse them and start at the next number. */
738 strecpy(buf
, src
->name
, lastof(buf
));
739 buf
[number_position
] = '\0';
741 num
= strtol(&src
->name
[number_position
], &endptr
, 10) + 1;
742 padding
= endptr
- &src
->name
[number_position
];
745 /* Check if this name is already taken. */
746 for (int max_iterations
= 1000; max_iterations
> 0; max_iterations
--, num
++) {
747 /* Attach the number to the temporary name. */
748 seprintf(&buf
[number_position
], lastof(buf
), "%0*d", padding
, num
);
750 /* Check the name is unique. */
751 if (IsUniqueVehicleName(buf
)) {
752 dst
->name
= strdup(buf
);
757 /* All done. If we didn't find a name, it'll just use its default. */
761 * Clone a vehicle. If it is a train, it will clone all the cars too
762 * @param tile tile of the depot where the cloned vehicle is build
763 * @param flags type of operation
764 * @param p1 the original vehicle's index
765 * @param p2 1 = shared orders, else copied orders
767 * @return the cost of this operation or an error
769 CommandCost
CmdCloneVehicle(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
771 CommandCost
total_cost(EXPENSES_NEW_VEHICLES
);
773 Vehicle
*v
= Vehicle::GetIfValid(p1
);
774 if (v
== NULL
|| !v
->IsPrimaryVehicle()) return CMD_ERROR
;
775 Vehicle
*v_front
= v
;
777 Vehicle
*w_front
= NULL
;
778 Vehicle
*w_rear
= NULL
;
781 * v_front is the front engine in the original vehicle
782 * v is the car/vehicle of the original vehicle that is currently being copied
783 * w_front is the front engine of the cloned vehicle
784 * w is the car/vehicle currently being cloned
785 * w_rear is the rear end of the cloned train. It's used to add more cars and is only used by trains
788 CommandCost ret
= CheckOwnership(v
->owner
);
789 if (ret
.Failed()) return ret
;
791 if (v
->type
== VEH_TRAIN
&& (!v
->IsFrontEngine() || Train::From(v
)->crash_anim_pos
>= 4400)) return CMD_ERROR
;
793 /* check that we can allocate enough vehicles */
794 if (!(flags
& DC_EXEC
)) {
798 } while ((v
= v
->Next()) != NULL
);
800 if (!Vehicle::CanAllocateItem(veh_counter
)) {
801 return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME
);
808 if (v
->type
== VEH_TRAIN
&& Train::From(v
)->IsRearDualheaded()) {
809 /* we build the rear ends of multiheaded trains with the front ones */
813 /* In case we're building a multi headed vehicle and the maximum number of
814 * vehicles is almost reached (e.g. max trains - 1) not all vehicles would
815 * be cloned. When the non-primary engines were build they were seen as
816 * 'new' vehicles whereas they would immediately be joined with a primary
817 * engine. This caused the vehicle to be not build as 'the limit' had been
818 * reached, resulting in partially build vehicles and such. */
819 DoCommandFlag build_flags
= flags
;
820 if ((flags
& DC_EXEC
) && !v
->IsPrimaryVehicle()) build_flags
|= DC_AUTOREPLACE
;
822 CommandCost cost
= DoCommand(tile
, v
->engine_type
| (1 << 16), 0, build_flags
, GetCmdBuildVeh(v
));
825 /* Can't build a part, then sell the stuff we already made; clear up the mess */
826 if (w_front
!= NULL
) DoCommand(w_front
->tile
, w_front
->index
| (1 << 20), 0, flags
, GetCmdSellVeh(w_front
));
830 total_cost
.AddCost(cost
);
832 if (flags
& DC_EXEC
) {
833 w
= Vehicle::Get(_new_vehicle_id
);
835 if (v
->type
== VEH_TRAIN
&& HasBit(Train::From(v
)->flags
, VRF_REVERSE_DIRECTION
)) {
836 SetBit(Train::From(w
)->flags
, VRF_REVERSE_DIRECTION
);
839 if (v
->type
== VEH_TRAIN
&& !v
->IsFrontEngine()) {
840 /* this s a train car
841 * add this unit to the end of the train */
842 CommandCost result
= DoCommand(0, w
->index
| 1 << 20, w_rear
->index
, flags
, CMD_MOVE_RAIL_VEHICLE
);
843 if (result
.Failed()) {
844 /* The train can't be joined to make the same consist as the original.
845 * Sell what we already made (clean up) and return an error. */
846 DoCommand(w_front
->tile
, w_front
->index
| 1 << 20, 0, flags
, GetCmdSellVeh(w_front
));
847 DoCommand(w_front
->tile
, w
->index
| 1 << 20, 0, flags
, GetCmdSellVeh(w
));
848 return result
; // return error and the message returned from CMD_MOVE_RAIL_VEHICLE
851 /* this is a front engine or not a train. */
853 w
->service_interval
= v
->service_interval
;
854 w
->SetServiceIntervalIsCustom(v
->ServiceIntervalIsCustom());
855 w
->SetServiceIntervalIsPercent(v
->ServiceIntervalIsPercent());
857 w_rear
= w
; // trains needs to know the last car in the train, so they can add more in next loop
859 } while (v
->type
== VEH_TRAIN
&& (v
= v
->GetNextVehicle()) != NULL
);
861 if ((flags
& DC_EXEC
) && v_front
->type
== VEH_TRAIN
) {
862 /* for trains this needs to be the front engine due to the callback function */
863 _new_vehicle_id
= w_front
->index
;
866 if (flags
& DC_EXEC
) {
867 /* Cloned vehicles belong to the same group */
868 DoCommand(0, v_front
->group_id
, w_front
->index
, flags
, CMD_ADD_VEHICLE_GROUP
);
872 /* Take care of refitting. */
876 /* Both building and refitting are influenced by newgrf callbacks, which
877 * makes it impossible to accurately estimate the cloning costs. In
878 * particular, it is possible for engines of the same type to be built with
879 * different numbers of articulated parts, so when refitting we have to
880 * loop over real vehicles first, and then the articulated parts of those
881 * vehicles in a different loop. */
884 if (flags
& DC_EXEC
) {
887 /* Find out what's the best sub type */
888 byte subtype
= GetBestFittingSubType(v
, w
, v
->cargo_type
);
889 if (w
->cargo_type
!= v
->cargo_type
|| w
->cargo_subtype
!= subtype
) {
890 CommandCost cost
= DoCommand(0, w
->index
, v
->cargo_type
| 1U << 7 | (subtype
<< 8), flags
, GetCmdRefitVeh(v
));
891 if (cost
.Succeeded()) total_cost
.AddCost(cost
);
894 if (w
->IsGroundVehicle() && w
->HasArticulatedPart()) {
895 w
= w
->GetNextArticulatedPart();
900 const Engine
*e
= v
->GetEngine();
901 CargoID initial_cargo
= (e
->CanCarryCargo() ? e
->GetDefaultCargoType() : (CargoID
)CT_INVALID
);
903 if (v
->cargo_type
!= initial_cargo
&& initial_cargo
!= CT_INVALID
) {
905 total_cost
.AddCost(GetRefitCost(NULL
, v
->engine_type
, v
->cargo_type
, v
->cargo_subtype
, &dummy
));
909 if (v
->IsGroundVehicle() && v
->HasArticulatedPart()) {
910 v
= v
->GetNextArticulatedPart();
916 if ((flags
& DC_EXEC
) && v
->type
== VEH_TRAIN
) w
= w
->GetNextVehicle();
917 } while (v
->type
== VEH_TRAIN
&& (v
= v
->GetNextVehicle()) != NULL
);
919 if (flags
& DC_EXEC
) {
921 * Set the orders of the vehicle. Cannot do it earlier as we need
922 * the vehicle refitted before doing this, otherwise the moved
923 * cargo types might not match (passenger vs non-passenger)
925 DoCommand(0, w_front
->index
| (p2
& 1 ? CO_SHARE
: CO_COPY
) << 30, v_front
->index
, flags
, CMD_CLONE_ORDER
);
927 /* Now clone the vehicle's name, if it has one. */
928 if (v_front
->name
!= NULL
) CloneVehicleName(v_front
, w_front
);
931 /* Since we can't estimate the cost of cloning a vehicle accurately we must
932 * check whether the company has enough money manually. */
933 if (!CheckCompanyHasMoney(total_cost
)) {
934 if (flags
& DC_EXEC
) {
935 /* The vehicle has already been bought, so now it must be sold again. */
936 DoCommand(w_front
->tile
, w_front
->index
| 1 << 20, 0, flags
, GetCmdSellVeh(w_front
));
945 * Send all vehicles of type to depots
946 * @param flags the flags used for DoCommand()
947 * @param service should the vehicles only get service in the depots
948 * @param vli identifier of the vehicle list
949 * @return 0 for success and CMD_ERROR if no vehicle is able to go to depot
951 static CommandCost
SendAllVehiclesToDepot(DoCommandFlag flags
, bool service
, const VehicleListIdentifier
&vli
)
955 if (!GenerateVehicleSortList(&list
, vli
)) return CMD_ERROR
;
957 /* Send all the vehicles to a depot */
958 bool had_success
= false;
959 for (uint i
= 0; i
< list
.Length(); i
++) {
960 const Vehicle
*v
= list
[i
];
961 CommandCost ret
= DoCommand(v
->tile
, v
->index
| (service
? DEPOT_SERVICE
: 0U) | DEPOT_DONT_CANCEL
, 0, flags
, GetCmdSendToDepot(vli
.vtype
));
963 if (ret
.Succeeded()) {
966 /* Return 0 if DC_EXEC is not set this is a valid goto depot command)
967 * In this case we know that at least one vehicle can be sent to a depot
968 * and we will issue the command. We can now safely quit the loop, knowing
969 * it will succeed at least once. With DC_EXEC we really need to send them to the depot */
970 if (!(flags
& DC_EXEC
)) break;
974 return had_success
? CommandCost() : CMD_ERROR
;
978 * Send a vehicle to the depot.
980 * @param flags for command type
982 * - p1 0-20: bitvehicle ID to send to the depot
983 * - p1 bits 25-8 - DEPOT_ flags (see vehicle_type.h)
984 * @param p2 packed VehicleListIdentifier.
986 * @return the cost of this operation or an error
988 CommandCost
CmdSendVehicleToDepot(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
990 if (p1
& DEPOT_MASS_SEND
) {
991 /* Mass goto depot requested */
992 VehicleListIdentifier vli
;
993 if (!vli
.Unpack(p2
)) return CMD_ERROR
;
994 return SendAllVehiclesToDepot(flags
, (p1
& DEPOT_SERVICE
) != 0, vli
);
997 Vehicle
*v
= Vehicle::GetIfValid(GB(p1
, 0, 20));
998 if (v
== NULL
) return CMD_ERROR
;
999 if (!v
->IsPrimaryVehicle()) return CMD_ERROR
;
1001 return v
->SendToDepot(flags
, (DepotCommand
)(p1
& DEPOT_COMMAND_MASK
));
1005 * Give a custom name to your vehicle
1006 * @param tile unused
1007 * @param flags type of operation
1008 * @param p1 vehicle ID to name
1010 * @param text the new name or an empty string when resetting to the default
1011 * @return the cost of this operation or an error
1013 CommandCost
CmdRenameVehicle(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1015 Vehicle
*v
= Vehicle::GetIfValid(p1
);
1016 if (v
== NULL
|| !v
->IsPrimaryVehicle()) return CMD_ERROR
;
1018 CommandCost ret
= CheckOwnership(v
->owner
);
1019 if (ret
.Failed()) return ret
;
1021 bool reset
= StrEmpty(text
);
1024 if (Utf8StringLength(text
) >= MAX_LENGTH_VEHICLE_NAME_CHARS
) return CMD_ERROR
;
1025 if (!(flags
& DC_AUTOREPLACE
) && !IsUniqueVehicleName(text
)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE
);
1028 if (flags
& DC_EXEC
) {
1030 v
->name
= reset
? NULL
: strdup(text
);
1031 InvalidateWindowClassesData(GetWindowClassForVehicleType(v
->type
), 1);
1032 MarkWholeScreenDirty();
1035 return CommandCost();
1040 * Change the service interval of a vehicle
1041 * @param tile unused
1042 * @param flags type of operation
1043 * @param p1 vehicle ID that is being service-interval-changed
1045 * - p2 = (bit 0-15) - new service interval
1046 * - p2 = (bit 16) - service interval is custom flag
1047 * - p2 = (bit 17) - service interval is percentage flag
1048 * @param text unused
1049 * @return the cost of this operation or an error
1051 CommandCost
CmdChangeServiceInt(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1053 Vehicle
*v
= Vehicle::GetIfValid(p1
);
1054 if (v
== NULL
|| !v
->IsPrimaryVehicle()) return CMD_ERROR
;
1056 CommandCost ret
= CheckOwnership(v
->owner
);
1057 if (ret
.Failed()) return ret
;
1059 const Company
*company
= Company::Get(v
->owner
);
1060 bool iscustom
= HasBit(p2
, 16);
1061 bool ispercent
= iscustom
? HasBit(p2
, 17) : company
->settings
.vehicle
.servint_ispercent
;
1065 serv_int
= GB(p2
, 0, 16);
1066 if (serv_int
!= GetServiceIntervalClamped(serv_int
, ispercent
)) return CMD_ERROR
;
1068 serv_int
= CompanyServiceInterval(company
, v
->type
);
1071 if (flags
& DC_EXEC
) {
1072 v
->SetServiceInterval(serv_int
);
1073 v
->SetServiceIntervalIsCustom(iscustom
);
1074 v
->SetServiceIntervalIsPercent(ispercent
);
1075 SetWindowDirty(WC_VEHICLE_DETAILS
, v
->index
);
1078 return CommandCost();