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_map.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
;
89 switch (GetTileType(tile
)) {
90 case MP_RAILWAY
: type
= VEH_TRAIN
; break;
91 case MP_ROAD
: type
= VEH_ROAD
; break;
92 case MP_WATER
: type
= VEH_SHIP
; break;
93 case MP_STATION
: type
= VEH_AIRCRAFT
; break;
94 default: NOT_REACHED(); // Safe due to IsDepotTile()
97 /* Validate the engine type. */
98 EngineID eid
= GB(p1
, 0, 16);
99 if (!IsEngineBuildable(eid
, type
, _current_company
)) return_cmd_error(STR_ERROR_RAIL_VEHICLE_NOT_AVAILABLE
+ type
);
101 const Engine
*e
= Engine::Get(eid
);
102 CommandCost
value(EXPENSES_NEW_VEHICLES
, e
->GetCost());
104 /* Engines without valid cargo should not be available */
105 if (e
->GetDefaultCargoType() == CT_INVALID
) return CMD_ERROR
;
107 /* Check whether the number of vehicles we need to build can be built according to pool space. */
110 case VEH_TRAIN
: num_vehicles
= (e
->u
.rail
.railveh_type
== RAILVEH_MULTIHEAD
? 2 : 1) + CountArticulatedParts(eid
, false); break;
111 case VEH_ROAD
: num_vehicles
= 1 + CountArticulatedParts(eid
, false); break;
112 case VEH_SHIP
: num_vehicles
= 1; break;
113 case VEH_AIRCRAFT
: num_vehicles
= e
->u
.air
.subtype
& AIR_CTOL
? 2 : 3; break;
114 default: NOT_REACHED(); // Safe due to IsDepotTile()
116 if (!Vehicle::CanAllocateItem(num_vehicles
)) return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME
);
118 /* Check whether we can allocate a unit number. Autoreplace does not allocate
119 * an unit number as it will (always) reuse the one of the replaced vehicle
120 * and (train) wagons don't have an unit number in any scenario. */
121 UnitID unit_num
= (flags
& DC_AUTOREPLACE
|| (type
== VEH_TRAIN
&& e
->u
.rail
.railveh_type
== RAILVEH_WAGON
)) ? 0 : GetFreeUnitNumber(type
);
122 if (unit_num
== UINT16_MAX
) return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME
);
126 case VEH_TRAIN
: value
.AddCost(CmdBuildRailVehicle(tile
, flags
, e
, GB(p1
, 16, 16), &v
)); break;
127 case VEH_ROAD
: value
.AddCost(CmdBuildRoadVehicle(tile
, flags
, e
, GB(p1
, 16, 16), &v
)); break;
128 case VEH_SHIP
: value
.AddCost(CmdBuildShip (tile
, flags
, e
, GB(p1
, 16, 16), &v
)); break;
129 case VEH_AIRCRAFT
: value
.AddCost(CmdBuildAircraft (tile
, flags
, e
, GB(p1
, 16, 16), &v
)); break;
130 default: NOT_REACHED(); // Safe due to IsDepotTile()
133 if (value
.Succeeded() && flags
& DC_EXEC
) {
134 v
->unitnumber
= unit_num
;
135 v
->value
= value
.GetCost();
137 InvalidateWindowData(WC_VEHICLE_DEPOT
, v
->tile
);
138 InvalidateWindowClassesData(GetWindowClassForVehicleType(type
), 0);
139 SetWindowDirty(WC_COMPANY
, _current_company
);
140 if (IsLocalCompany()) {
141 InvalidateAutoreplaceWindow(v
->engine_type
, v
->group_id
); // updates the auto replace window (must be called before incrementing num_engines)
144 GroupStatistics::CountEngine(v
, 1);
145 GroupStatistics::UpdateAutoreplace(_current_company
);
147 if (v
->IsPrimaryVehicle()) {
148 GroupStatistics::CountVehicle(v
, 1);
149 OrderBackup::Restore(v
, p2
);
156 CommandCost
CmdSellRailWagon(DoCommandFlag flags
, Vehicle
*v
, uint16 data
, uint32 user
);
160 * @param tile unused.
161 * @param flags for command.
162 * @param p1 various bitstuffed data.
163 * bits 0-19: vehicle ID being sold.
164 * bits 20-30: vehicle type specific bits passed on to the vehicle build functions.
165 * bit 31: make a backup of the vehicle's order (if an engine).
167 * @param text unused.
168 * @return the cost of this operation or an error.
170 CommandCost
CmdSellVehicle(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
172 Vehicle
*v
= Vehicle::GetIfValid(GB(p1
, 0, 20));
173 if (v
== NULL
) return CMD_ERROR
;
175 Vehicle
*front
= v
->First();
177 CommandCost ret
= CheckOwnership(front
->owner
);
178 if (ret
.Failed()) return ret
;
180 if (front
->vehstatus
& VS_CRASHED
) return_cmd_error(STR_ERROR_VEHICLE_IS_DESTROYED
);
182 if (!front
->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAIN_MUST_BE_STOPPED_INSIDE_DEPOT
+ front
->type
);
184 /* Can we actually make the order backup, i.e. are there enough orders? */
185 if (p1
& MAKE_ORDER_BACKUP_FLAG
&&
186 front
->orders
.list
!= NULL
&&
187 !front
->orders
.list
->IsShared() &&
188 !Order::CanAllocateItem(front
->orders
.list
->GetNumOrders())) {
189 /* Only happens in exceptional cases when there aren't enough orders anyhow.
190 * Thus it should be safe to just drop the orders in that case. */
191 p1
&= ~MAKE_ORDER_BACKUP_FLAG
;
194 if (v
->type
== VEH_TRAIN
) {
195 ret
= CmdSellRailWagon(flags
, v
, GB(p1
, 20, 12), p2
);
197 ret
= CommandCost(EXPENSES_NEW_VEHICLES
, -front
->value
);
199 if (flags
& DC_EXEC
) {
200 if (front
->IsPrimaryVehicle() && p1
& MAKE_ORDER_BACKUP_FLAG
) OrderBackup::Backup(front
, p2
);
209 * Helper to run the refit cost callback.
210 * @param v The vehicle we are refitting, can be NULL.
211 * @param engine_type Which engine to refit
212 * @param new_cid Cargo type we are refitting to.
213 * @param new_subtype New cargo subtype.
214 * @param [out] auto_refit_allowed The refit is allowed as an auto-refit.
215 * @return Price for refitting
217 static int GetRefitCostFactor(const Vehicle
*v
, EngineID engine_type
, CargoID new_cid
, byte new_subtype
, bool *auto_refit_allowed
)
219 /* Prepare callback param with info about the new cargo type. */
220 const Engine
*e
= Engine::Get(engine_type
);
222 /* Is this vehicle a NewGRF vehicle? */
223 if (e
->GetGRF() != NULL
) {
224 const CargoSpec
*cs
= CargoSpec::Get(new_cid
);
225 uint32 param1
= (cs
->classes
<< 16) | (new_subtype
<< 8) | e
->GetGRF()->cargo_map
[new_cid
];
227 uint16 cb_res
= GetVehicleCallback(CBID_VEHICLE_REFIT_COST
, param1
, 0, engine_type
, v
);
228 if (cb_res
!= CALLBACK_FAILED
) {
229 *auto_refit_allowed
= HasBit(cb_res
, 14);
230 int factor
= GB(cb_res
, 0, 14);
231 if (factor
>= 0x2000) factor
-= 0x4000; // Treat as signed integer.
236 *auto_refit_allowed
= e
->info
.refit_cost
== 0;
237 return (v
== NULL
|| v
->cargo_type
!= new_cid
) ? e
->info
.refit_cost
: 0;
241 * Learn the price of refitting a certain engine
242 * @param v The vehicle we are refitting, can be NULL.
243 * @param engine_type Which engine to refit
244 * @param new_cid Cargo type we are refitting to.
245 * @param new_subtype New cargo subtype.
246 * @param [out] auto_refit_allowed The refit is allowed as an auto-refit.
247 * @return Price for refitting
249 static CommandCost
GetRefitCost(const Vehicle
*v
, EngineID engine_type
, CargoID new_cid
, byte new_subtype
, bool *auto_refit_allowed
)
251 ExpensesType expense_type
;
252 const Engine
*e
= Engine::Get(engine_type
);
254 int cost_factor
= GetRefitCostFactor(v
, engine_type
, new_cid
, new_subtype
, auto_refit_allowed
);
257 base_price
= PR_BUILD_VEHICLE_SHIP
;
258 expense_type
= EXPENSES_SHIP_RUN
;
262 base_price
= PR_BUILD_VEHICLE_ROAD
;
263 expense_type
= EXPENSES_ROADVEH_RUN
;
267 base_price
= PR_BUILD_VEHICLE_AIRCRAFT
;
268 expense_type
= EXPENSES_AIRCRAFT_RUN
;
272 base_price
= (e
->u
.rail
.railveh_type
== RAILVEH_WAGON
) ? PR_BUILD_VEHICLE_WAGON
: PR_BUILD_VEHICLE_TRAIN
;
274 expense_type
= EXPENSES_TRAIN_RUN
;
277 default: NOT_REACHED();
279 if (cost_factor
< 0) {
280 return CommandCost(expense_type
, -GetPrice(base_price
, -cost_factor
, e
->GetGRF(), -10));
282 return CommandCost(expense_type
, GetPrice(base_price
, cost_factor
, e
->GetGRF(), -10));
286 /** Helper structure for RefitVehicle() */
288 Vehicle
*v
; ///< Vehicle to refit
289 uint capacity
; ///< New capacity of vehicle
290 uint mail_capacity
; ///< New mail capacity of aircraft
291 byte subtype
; ///< cargo subtype to refit to
295 * Refits a vehicle (chain).
296 * This is the vehicle-type independent part of the CmdRefitXXX functions.
297 * @param v The vehicle to refit.
298 * @param only_this Whether to only refit this vehicle, or to check the rest of them.
299 * @param num_vehicles Number of vehicles to refit (not counting articulated parts). Zero means the whole chain.
300 * @param new_cid Cargotype to refit to
301 * @param new_subtype Cargo subtype to refit to. 0xFF means to try keeping the same subtype according to GetBestFittingSubType().
302 * @param flags Command flags
303 * @param auto_refit Refitting is done as automatic refitting outside a depot.
304 * @return Refit cost.
306 static CommandCost
RefitVehicle(Vehicle
*v
, bool only_this
, uint8 num_vehicles
, CargoID new_cid
, byte new_subtype
, DoCommandFlag flags
, bool auto_refit
)
308 CommandCost
cost(v
->GetExpenseType(false));
309 uint total_capacity
= 0;
310 uint total_mail_capacity
= 0;
311 num_vehicles
= num_vehicles
== 0 ? UINT8_MAX
: num_vehicles
;
313 VehicleSet vehicles_to_refit
;
315 GetVehicleSet(vehicles_to_refit
, v
, num_vehicles
);
316 /* In this case, we need to check the whole chain. */
320 static SmallVector
<RefitResult
, 16> refit_result
;
321 refit_result
.Clear();
323 v
->InvalidateNewGRFCacheOfChain();
324 byte actual_subtype
= new_subtype
;
325 for (; v
!= NULL
; v
= (only_this
? NULL
: v
->Next())) {
326 /* Reset actual_subtype for every new vehicle */
327 if (!v
->IsArticulatedPart()) actual_subtype
= new_subtype
;
329 if (v
->type
== VEH_TRAIN
&& !vehicles_to_refit
.Contains(v
->index
) && !only_this
) continue;
331 const Engine
*e
= v
->GetEngine();
332 if (!e
->CanCarryCargo()) continue;
334 /* If the vehicle is not refittable, or does not allow automatic refitting,
335 * count its capacity nevertheless if the cargo matches */
336 bool refittable
= HasBit(e
->info
.refit_mask
, new_cid
) && (!auto_refit
|| HasBit(e
->info
.misc_flags
, EF_AUTO_REFIT
));
337 if (!refittable
&& v
->cargo_type
!= new_cid
) continue;
339 /* Determine best fitting subtype if requested */
340 if (actual_subtype
== 0xFF) {
341 actual_subtype
= GetBestFittingSubType(v
, v
, new_cid
);
344 /* Back up the vehicle's cargo type */
345 CargoID temp_cid
= v
->cargo_type
;
346 byte temp_subtype
= v
->cargo_subtype
;
348 v
->cargo_type
= new_cid
;
349 v
->cargo_subtype
= actual_subtype
;
352 uint16 mail_capacity
= 0;
353 uint amount
= e
->DetermineCapacity(v
, &mail_capacity
);
354 total_capacity
+= amount
;
355 /* mail_capacity will always be zero if the vehicle is not an aircraft. */
356 total_mail_capacity
+= mail_capacity
;
358 if (!refittable
) continue;
360 /* Restore the original cargo type */
361 v
->cargo_type
= temp_cid
;
362 v
->cargo_subtype
= temp_subtype
;
364 bool auto_refit_allowed
;
365 CommandCost refit_cost
= GetRefitCost(v
, v
->engine_type
, new_cid
, actual_subtype
, &auto_refit_allowed
);
366 if (auto_refit
&& !auto_refit_allowed
) {
367 /* Sorry, auto-refitting not allowed, subtract the cargo amount again from the total. */
368 total_capacity
-= amount
;
369 total_mail_capacity
-= mail_capacity
;
371 if (v
->cargo_type
== new_cid
) {
372 /* Add the old capacity nevertheless, if the cargo matches */
373 total_capacity
+= v
->cargo_cap
;
374 if (v
->type
== VEH_AIRCRAFT
) total_mail_capacity
+= v
->Next()->cargo_cap
;
378 cost
.AddCost(refit_cost
);
380 /* Record the refitting.
381 * Do not execute the refitting immediately, so DetermineCapacity and GetRefitCost do the same in test and exec run.
384 * - If the capacity of vehicles depends on other vehicles in the chain, the actual capacity is
385 * set after RefitVehicle() via ConsistChanged() and friends. The estimation via _returned_refit_capacity will be wrong.
386 * - We have to call the refit cost callback with the pre-refit configuration of the chain because we want refit and
387 * autorefit to behave the same, and we need its result for auto_refit_allowed.
389 RefitResult
*result
= refit_result
.Append();
391 result
->capacity
= amount
;
392 result
->mail_capacity
= mail_capacity
;
393 result
->subtype
= actual_subtype
;
396 if (flags
& DC_EXEC
) {
397 /* Store the result */
398 for (RefitResult
*result
= refit_result
.Begin(); result
!= refit_result
.End(); result
++) {
399 Vehicle
*u
= result
->v
;
400 u
->refit_cap
= (u
->cargo_type
== new_cid
) ? min(result
->capacity
, u
->refit_cap
) : 0;
401 if (u
->cargo
.TotalCount() > u
->refit_cap
) u
->cargo
.Truncate(u
->cargo
.TotalCount() - u
->refit_cap
);
402 u
->cargo_type
= new_cid
;
403 u
->cargo_cap
= result
->capacity
;
404 u
->cargo_subtype
= result
->subtype
;
405 if (u
->type
== VEH_AIRCRAFT
) {
406 Vehicle
*w
= u
->Next();
407 w
->refit_cap
= min(w
->refit_cap
, result
->mail_capacity
);
408 w
->cargo_cap
= result
->mail_capacity
;
409 if (w
->cargo
.TotalCount() > w
->refit_cap
) w
->cargo
.Truncate(w
->cargo
.TotalCount() - w
->refit_cap
);
414 refit_result
.Clear();
415 _returned_refit_capacity
= total_capacity
;
416 _returned_mail_refit_capacity
= total_mail_capacity
;
421 * Refits a vehicle to the specified cargo type.
423 * @param flags type of operation
424 * @param p1 vehicle ID to refit
425 * @param p2 various bitstuffed elements
426 * - p2 = (bit 0-4) - New cargo type to refit to.
427 * - p2 = (bit 6) - Automatic refitting.
428 * - p2 = (bit 7) - Refit only this vehicle. Used only for cloning vehicles.
429 * - p2 = (bit 8-15) - New cargo subtype to refit to. 0xFF means to try keeping the same subtype according to GetBestFittingSubType().
430 * - p2 = (bit 16-23) - Number of vehicles to refit (not counting articulated parts). Zero means all vehicles.
431 * Only used if "refit only this vehicle" is false.
433 * @return the cost of this operation or an error
435 CommandCost
CmdRefitVehicle(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
437 Vehicle
*v
= Vehicle::GetIfValid(p1
);
438 if (v
== NULL
) return CMD_ERROR
;
440 /* Don't allow disasters and sparks and such to be refitted.
441 * We cannot check for IsPrimaryVehicle as autoreplace also refits in free wagon chains. */
442 if (!IsCompanyBuildableVehicleType(v
->type
)) return CMD_ERROR
;
444 Vehicle
*front
= v
->First();
446 CommandCost ret
= CheckOwnership(front
->owner
);
447 if (ret
.Failed()) return ret
;
449 bool auto_refit
= HasBit(p2
, 6);
451 /* Don't allow shadows and such to be refitted. */
452 if (v
!= front
&& (v
->type
== VEH_SHIP
|| v
->type
== VEH_AIRCRAFT
)) return CMD_ERROR
;
453 /* Allow auto-refitting only during loading and normal refitting only in a depot. */
454 if ((!auto_refit
|| !front
->current_order
.IsType(OT_LOADING
)) && !front
->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAIN_MUST_BE_STOPPED_INSIDE_DEPOT
+ front
->type
);
455 if (front
->vehstatus
& VS_CRASHED
) return_cmd_error(STR_ERROR_VEHICLE_IS_DESTROYED
);
458 CargoID new_cid
= GB(p2
, 0, 5);
459 byte new_subtype
= GB(p2
, 8, 8);
460 if (new_cid
>= NUM_CARGO
) return CMD_ERROR
;
462 /* For ships and aircrafts there is always only one. */
463 bool only_this
= HasBit(p2
, 7) || front
->type
== VEH_SHIP
|| front
->type
== VEH_AIRCRAFT
;
464 uint8 num_vehicles
= GB(p2
, 16, 8);
466 CommandCost cost
= RefitVehicle(v
, only_this
, num_vehicles
, new_cid
, new_subtype
, flags
, auto_refit
);
468 if (flags
& DC_EXEC
) {
469 /* Update the cached variables */
472 Train::From(front
)->ConsistChanged(auto_refit
);
475 RoadVehUpdateCache(RoadVehicle::From(front
), auto_refit
);
476 if (_settings_game
.vehicle
.roadveh_acceleration_model
!= AM_ORIGINAL
) RoadVehicle::From(front
)->CargoChanged();
480 v
->InvalidateNewGRFCacheOfChain();
481 Ship::From(v
)->UpdateCache();
485 v
->InvalidateNewGRFCacheOfChain();
486 UpdateAircraftCache(Aircraft::From(v
), true);
489 default: NOT_REACHED();
493 InvalidateWindowData(WC_VEHICLE_DETAILS
, front
->index
);
494 SetWindowDirty(WC_VEHICLE_DEPOT
, front
->tile
);
495 InvalidateWindowClassesData(GetWindowClassForVehicleType(v
->type
), 0);
497 /* Always invalidate the cache; querycost might have filled it. */
498 v
->InvalidateNewGRFCacheOfChain();
505 * Start/Stop a vehicle
507 * @param flags type of operation
508 * @param p1 vehicle to start/stop, don't forget to change CcStartStopVehicle if you modify this!
509 * @param p2 bit 0: Shall the start/stop newgrf callback be evaluated (only valid with DC_AUTOREPLACE for network safety)
511 * @return the cost of this operation or an error
513 CommandCost
CmdStartStopVehicle(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
515 /* Disable the effect of p2 bit 0, when DC_AUTOREPLACE is not set */
516 if ((flags
& DC_AUTOREPLACE
) == 0) SetBit(p2
, 0);
518 Vehicle
*v
= Vehicle::GetIfValid(p1
);
519 if (v
== NULL
|| !v
->IsPrimaryVehicle()) return CMD_ERROR
;
521 CommandCost ret
= CheckOwnership(v
->owner
);
522 if (ret
.Failed()) return ret
;
524 if (v
->vehstatus
& VS_CRASHED
) return_cmd_error(STR_ERROR_VEHICLE_IS_DESTROYED
);
528 if ((v
->vehstatus
& VS_STOPPED
) && Train::From(v
)->gcache
.cached_power
== 0) return_cmd_error(STR_ERROR_TRAIN_START_NO_POWER
);
536 Aircraft
*a
= Aircraft::From(v
);
537 /* cannot stop airplane when in flight, or when taking off / landing */
538 if (!(v
->vehstatus
& VS_CRASHED
) && a
->state
>= STARTTAKEOFF
&& a
->state
< TERM7
) return_cmd_error(STR_ERROR_AIRCRAFT_IS_IN_FLIGHT
);
542 default: return CMD_ERROR
;
546 /* Check if this vehicle can be started/stopped. Failure means 'allow'. */
547 uint16 callback
= GetVehicleCallback(CBID_VEHICLE_START_STOP_CHECK
, 0, 0, v
->engine_type
, v
);
548 StringID error
= STR_NULL
;
549 if (callback
!= CALLBACK_FAILED
) {
550 if (v
->GetGRF()->grf_version
< 8) {
551 /* 8 bit result 0xFF means 'allow' */
552 if (callback
< 0x400 && GB(callback
, 0, 8) != 0xFF) error
= GetGRFStringID(v
->GetGRFID(), 0xD000 + callback
);
554 if (callback
< 0x400) {
555 error
= GetGRFStringID(v
->GetGRFID(), 0xD000 + callback
);
561 default: // unknown reason -> disallow
562 error
= STR_ERROR_INCOMPATIBLE_RAIL_TYPES
;
568 if (error
!= STR_NULL
) return_cmd_error(error
);
571 if (flags
& DC_EXEC
) {
572 if (v
->IsStoppedInDepot() && (flags
& DC_AUTOREPLACE
) == 0) DeleteVehicleNews(p1
, STR_NEWS_TRAIN_IS_WAITING
+ v
->type
);
574 v
->vehstatus
^= VS_STOPPED
;
575 if (v
->type
!= VEH_TRAIN
) v
->cur_speed
= 0; // trains can stop 'slowly'
577 SetWindowWidgetDirty(WC_VEHICLE_VIEW
, v
->index
, WID_VV_START_STOP
);
578 SetWindowDirty(WC_VEHICLE_DEPOT
, v
->tile
);
579 SetWindowClassesDirty(GetWindowClassForVehicleType(v
->type
));
581 return CommandCost();
585 * Starts or stops a lot of vehicles
586 * @param tile Tile of the depot where the vehicles are started/stopped (only used for depots)
587 * @param flags type of operation
589 * - bit 0 set = start vehicles, unset = stop vehicles
590 * - bit 1 if set, then it's a vehicle list window, not a depot and Tile is ignored in this case
591 * @param p2 packed VehicleListIdentifier
593 * @return the cost of this operation or an error
595 CommandCost
CmdMassStartStopVehicle(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
598 bool do_start
= HasBit(p1
, 0);
599 bool vehicle_list_window
= HasBit(p1
, 1);
601 VehicleListIdentifier vli
;
602 if (!vli
.Unpack(p2
)) return CMD_ERROR
;
603 if (!IsCompanyBuildableVehicleType(vli
.vtype
)) return CMD_ERROR
;
605 if (vehicle_list_window
) {
606 if (!GenerateVehicleSortList(&list
, vli
)) return CMD_ERROR
;
608 /* Get the list of vehicles in the depot */
609 BuildDepotVehicleList(vli
.vtype
, tile
, &list
, NULL
);
612 for (uint i
= 0; i
< list
.Length(); i
++) {
613 const Vehicle
*v
= list
[i
];
615 if (!!(v
->vehstatus
& VS_STOPPED
) != do_start
) continue;
617 if (!vehicle_list_window
&& !v
->IsChainInDepot()) continue;
619 /* Just try and don't care if some vehicle's can't be stopped. */
620 DoCommand(tile
, v
->index
, 0, flags
, CMD_START_STOP_VEHICLE
);
623 return CommandCost();
627 * Sells all vehicles in a depot
628 * @param tile Tile of the depot where the depot is
629 * @param flags type of operation
630 * @param p1 Vehicle type
633 * @return the cost of this operation or an error
635 CommandCost
CmdDepotSellAllVehicles(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
639 CommandCost
cost(EXPENSES_NEW_VEHICLES
);
640 VehicleType vehicle_type
= Extract
<VehicleType
, 0, 3>(p1
);
642 if (!IsCompanyBuildableVehicleType(vehicle_type
)) return CMD_ERROR
;
644 uint sell_command
= GetCmdSellVeh(vehicle_type
);
646 /* Get the list of vehicles in the depot */
647 BuildDepotVehicleList(vehicle_type
, tile
, &list
, &list
);
649 CommandCost last_error
= CMD_ERROR
;
650 bool had_success
= false;
651 for (uint i
= 0; i
< list
.Length(); i
++) {
652 CommandCost ret
= DoCommand(tile
, list
[i
]->index
| (1 << 20), 0, flags
, sell_command
);
653 if (ret
.Succeeded()) {
661 return had_success
? cost
: last_error
;
665 * Autoreplace all vehicles in the depot
666 * @param tile Tile of the depot where the vehicles are
667 * @param flags type of operation
668 * @param p1 Type of vehicle
671 * @return the cost of this operation or an error
673 CommandCost
CmdDepotMassAutoReplace(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
676 CommandCost cost
= CommandCost(EXPENSES_NEW_VEHICLES
);
677 VehicleType vehicle_type
= Extract
<VehicleType
, 0, 3>(p1
);
679 if (!IsCompanyBuildableVehicleType(vehicle_type
)) return CMD_ERROR
;
680 if (!IsDepotTile(tile
) || !IsTileOwner(tile
, _current_company
)) return CMD_ERROR
;
682 /* Get the list of vehicles in the depot */
683 BuildDepotVehicleList(vehicle_type
, tile
, &list
, &list
, true);
685 for (uint i
= 0; i
< list
.Length(); i
++) {
686 const Vehicle
*v
= list
[i
];
688 /* Ensure that the vehicle completely in the depot */
689 if (!v
->IsChainInDepot()) continue;
691 CommandCost ret
= DoCommand(0, v
->index
, 0, flags
, CMD_AUTOREPLACE_VEHICLE
);
693 if (ret
.Succeeded()) cost
.AddCost(ret
);
699 * Test if a name is unique among vehicle names.
700 * @param name Name to test.
701 * @return True ifffffff the name is unique.
703 static bool IsUniqueVehicleName(const char *name
)
707 FOR_ALL_VEHICLES(v
) {
708 if (v
->name
!= NULL
&& strcmp(v
->name
, name
) == 0) return false;
715 * Clone the custom name of a vehicle, adding or incrementing a number.
716 * @param src Source vehicle, with a custom name.
717 * @param dst Destination vehicle.
719 static void CloneVehicleName(const Vehicle
*src
, Vehicle
*dst
)
723 /* Find the position of the first digit in the last group of digits. */
724 size_t number_position
;
725 for (number_position
= strlen(src
->name
); number_position
> 0; number_position
--) {
726 /* The design of UTF-8 lets this work simply without having to check
727 * for UTF-8 sequences. */
728 if (src
->name
[number_position
- 1] < '0' || src
->name
[number_position
- 1] > '9') break;
731 /* Format buffer and determine starting number. */
734 if (number_position
== strlen(src
->name
)) {
735 /* No digit at the end, so start at number 2. */
736 strecpy(buf
, src
->name
, lastof(buf
));
737 strecat(buf
, " ", lastof(buf
));
738 number_position
= strlen(buf
);
741 /* Found digits, parse them and start at the next number. */
742 strecpy(buf
, src
->name
, lastof(buf
));
743 buf
[number_position
] = '\0';
745 num
= strtol(&src
->name
[number_position
], &endptr
, 10) + 1;
746 padding
= endptr
- &src
->name
[number_position
];
749 /* Check if this name is already taken. */
750 for (int max_iterations
= 1000; max_iterations
> 0; max_iterations
--, num
++) {
751 /* Attach the number to the temporary name. */
752 seprintf(&buf
[number_position
], lastof(buf
), "%0*d", padding
, num
);
754 /* Check the name is unique. */
755 if (IsUniqueVehicleName(buf
)) {
756 dst
->name
= strdup(buf
);
761 /* All done. If we didn't find a name, it'll just use its default. */
765 * Clone a vehicle. If it is a train, it will clone all the cars too
766 * @param tile tile of the depot where the cloned vehicle is build
767 * @param flags type of operation
768 * @param p1 the original vehicle's index
769 * @param p2 1 = shared orders, else copied orders
771 * @return the cost of this operation or an error
773 CommandCost
CmdCloneVehicle(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
775 CommandCost
total_cost(EXPENSES_NEW_VEHICLES
);
777 Vehicle
*v
= Vehicle::GetIfValid(p1
);
778 if (v
== NULL
|| !v
->IsPrimaryVehicle()) return CMD_ERROR
;
779 Vehicle
*v_front
= v
;
781 Vehicle
*w_front
= NULL
;
782 Vehicle
*w_rear
= NULL
;
785 * v_front is the front engine in the original vehicle
786 * v is the car/vehicle of the original vehicle that is currently being copied
787 * w_front is the front engine of the cloned vehicle
788 * w is the car/vehicle currently being cloned
789 * w_rear is the rear end of the cloned train. It's used to add more cars and is only used by trains
792 CommandCost ret
= CheckOwnership(v
->owner
);
793 if (ret
.Failed()) return ret
;
795 if (v
->type
== VEH_TRAIN
&& (!v
->IsFrontEngine() || Train::From(v
)->crash_anim_pos
>= 4400)) return CMD_ERROR
;
797 /* check that we can allocate enough vehicles */
798 if (!(flags
& DC_EXEC
)) {
802 } while ((v
= v
->Next()) != NULL
);
804 if (!Vehicle::CanAllocateItem(veh_counter
)) {
805 return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME
);
812 if (v
->type
== VEH_TRAIN
&& Train::From(v
)->IsRearDualheaded()) {
813 /* we build the rear ends of multiheaded trains with the front ones */
817 /* In case we're building a multi headed vehicle and the maximum number of
818 * vehicles is almost reached (e.g. max trains - 1) not all vehicles would
819 * be cloned. When the non-primary engines were build they were seen as
820 * 'new' vehicles whereas they would immediately be joined with a primary
821 * engine. This caused the vehicle to be not build as 'the limit' had been
822 * reached, resulting in partially build vehicles and such. */
823 DoCommandFlag build_flags
= flags
;
824 if ((flags
& DC_EXEC
) && !v
->IsPrimaryVehicle()) build_flags
|= DC_AUTOREPLACE
;
826 CommandCost cost
= DoCommand(tile
, v
->engine_type
| (1 << 16), 0, build_flags
, GetCmdBuildVeh(v
));
829 /* Can't build a part, then sell the stuff we already made; clear up the mess */
830 if (w_front
!= NULL
) DoCommand(w_front
->tile
, w_front
->index
| (1 << 20), 0, flags
, GetCmdSellVeh(w_front
));
834 total_cost
.AddCost(cost
);
836 if (flags
& DC_EXEC
) {
837 w
= Vehicle::Get(_new_vehicle_id
);
839 if (v
->type
== VEH_TRAIN
&& HasBit(Train::From(v
)->flags
, VRF_REVERSE_DIRECTION
)) {
840 SetBit(Train::From(w
)->flags
, VRF_REVERSE_DIRECTION
);
843 if (v
->type
== VEH_TRAIN
&& !v
->IsFrontEngine()) {
844 /* this s a train car
845 * add this unit to the end of the train */
846 CommandCost result
= DoCommand(0, w
->index
| 1 << 20, w_rear
->index
, flags
, CMD_MOVE_RAIL_VEHICLE
);
847 if (result
.Failed()) {
848 /* The train can't be joined to make the same consist as the original.
849 * Sell what we already made (clean up) and return an error. */
850 DoCommand(w_front
->tile
, w_front
->index
| 1 << 20, 0, flags
, GetCmdSellVeh(w_front
));
851 DoCommand(w_front
->tile
, w
->index
| 1 << 20, 0, flags
, GetCmdSellVeh(w
));
852 return result
; // return error and the message returned from CMD_MOVE_RAIL_VEHICLE
855 /* this is a front engine or not a train. */
857 w
->service_interval
= v
->service_interval
;
858 w
->SetServiceIntervalIsCustom(v
->ServiceIntervalIsCustom());
859 w
->SetServiceIntervalIsPercent(v
->ServiceIntervalIsPercent());
861 w_rear
= w
; // trains needs to know the last car in the train, so they can add more in next loop
863 } while (v
->type
== VEH_TRAIN
&& (v
= v
->GetNextVehicle()) != NULL
);
865 if ((flags
& DC_EXEC
) && v_front
->type
== VEH_TRAIN
) {
866 /* for trains this needs to be the front engine due to the callback function */
867 _new_vehicle_id
= w_front
->index
;
870 if (flags
& DC_EXEC
) {
871 /* Cloned vehicles belong to the same group */
872 DoCommand(0, v_front
->group_id
, w_front
->index
, flags
, CMD_ADD_VEHICLE_GROUP
);
876 /* Take care of refitting. */
880 /* Both building and refitting are influenced by newgrf callbacks, which
881 * makes it impossible to accurately estimate the cloning costs. In
882 * particular, it is possible for engines of the same type to be built with
883 * different numbers of articulated parts, so when refitting we have to
884 * loop over real vehicles first, and then the articulated parts of those
885 * vehicles in a different loop. */
888 if (flags
& DC_EXEC
) {
891 /* Find out what's the best sub type */
892 byte subtype
= GetBestFittingSubType(v
, w
, v
->cargo_type
);
893 if (w
->cargo_type
!= v
->cargo_type
|| w
->cargo_subtype
!= subtype
) {
894 CommandCost cost
= DoCommand(0, w
->index
, v
->cargo_type
| 1U << 7 | (subtype
<< 8), flags
, GetCmdRefitVeh(v
));
895 if (cost
.Succeeded()) total_cost
.AddCost(cost
);
898 if (w
->IsGroundVehicle() && w
->HasArticulatedPart()) {
899 w
= w
->GetNextArticulatedPart();
904 const Engine
*e
= v
->GetEngine();
905 CargoID initial_cargo
= (e
->CanCarryCargo() ? e
->GetDefaultCargoType() : (CargoID
)CT_INVALID
);
907 if (v
->cargo_type
!= initial_cargo
&& initial_cargo
!= CT_INVALID
) {
909 total_cost
.AddCost(GetRefitCost(NULL
, v
->engine_type
, v
->cargo_type
, v
->cargo_subtype
, &dummy
));
913 if (v
->IsGroundVehicle() && v
->HasArticulatedPart()) {
914 v
= v
->GetNextArticulatedPart();
920 if ((flags
& DC_EXEC
) && v
->type
== VEH_TRAIN
) w
= w
->GetNextVehicle();
921 } while (v
->type
== VEH_TRAIN
&& (v
= v
->GetNextVehicle()) != NULL
);
923 if (flags
& DC_EXEC
) {
925 * Set the orders of the vehicle. Cannot do it earlier as we need
926 * the vehicle refitted before doing this, otherwise the moved
927 * cargo types might not match (passenger vs non-passenger)
929 DoCommand(0, w_front
->index
| (p2
& 1 ? CO_SHARE
: CO_COPY
) << 30, v_front
->index
, flags
, CMD_CLONE_ORDER
);
931 /* Now clone the vehicle's name, if it has one. */
932 if (v_front
->name
!= NULL
) CloneVehicleName(v_front
, w_front
);
935 /* Since we can't estimate the cost of cloning a vehicle accurately we must
936 * check whether the company has enough money manually. */
937 if (!CheckCompanyHasMoney(total_cost
)) {
938 if (flags
& DC_EXEC
) {
939 /* The vehicle has already been bought, so now it must be sold again. */
940 DoCommand(w_front
->tile
, w_front
->index
| 1 << 20, 0, flags
, GetCmdSellVeh(w_front
));
949 * Send all vehicles of type to depots
950 * @param flags the flags used for DoCommand()
951 * @param service should the vehicles only get service in the depots
952 * @param vli identifier of the vehicle list
953 * @return 0 for success and CMD_ERROR if no vehicle is able to go to depot
955 static CommandCost
SendAllVehiclesToDepot(DoCommandFlag flags
, bool service
, const VehicleListIdentifier
&vli
)
959 if (!GenerateVehicleSortList(&list
, vli
)) return CMD_ERROR
;
961 /* Send all the vehicles to a depot */
962 bool had_success
= false;
963 for (uint i
= 0; i
< list
.Length(); i
++) {
964 const Vehicle
*v
= list
[i
];
965 CommandCost ret
= DoCommand(v
->tile
, v
->index
| (service
? DEPOT_SERVICE
: 0U) | DEPOT_DONT_CANCEL
, 0, flags
, GetCmdSendToDepot(vli
.vtype
));
967 if (ret
.Succeeded()) {
970 /* Return 0 if DC_EXEC is not set this is a valid goto depot command)
971 * In this case we know that at least one vehicle can be sent to a depot
972 * and we will issue the command. We can now safely quit the loop, knowing
973 * it will succeed at least once. With DC_EXEC we really need to send them to the depot */
974 if (!(flags
& DC_EXEC
)) break;
978 return had_success
? CommandCost() : CMD_ERROR
;
982 * Send a vehicle to the depot.
984 * @param flags for command type
986 * - p1 0-20: bitvehicle ID to send to the depot
987 * - p1 bits 25-8 - DEPOT_ flags (see vehicle_type.h)
988 * @param p2 packed VehicleListIdentifier.
990 * @return the cost of this operation or an error
992 CommandCost
CmdSendVehicleToDepot(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
994 if (p1
& DEPOT_MASS_SEND
) {
995 /* Mass goto depot requested */
996 VehicleListIdentifier vli
;
997 if (!vli
.Unpack(p2
)) return CMD_ERROR
;
998 return SendAllVehiclesToDepot(flags
, (p1
& DEPOT_SERVICE
) != 0, vli
);
1001 Vehicle
*v
= Vehicle::GetIfValid(GB(p1
, 0, 20));
1002 if (v
== NULL
) return CMD_ERROR
;
1003 if (!v
->IsPrimaryVehicle()) return CMD_ERROR
;
1005 return v
->SendToDepot(flags
, (DepotCommand
)(p1
& DEPOT_COMMAND_MASK
));
1009 * Give a custom name to your vehicle
1010 * @param tile unused
1011 * @param flags type of operation
1012 * @param p1 vehicle ID to name
1014 * @param text the new name or an empty string when resetting to the default
1015 * @return the cost of this operation or an error
1017 CommandCost
CmdRenameVehicle(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1019 Vehicle
*v
= Vehicle::GetIfValid(p1
);
1020 if (v
== NULL
|| !v
->IsPrimaryVehicle()) return CMD_ERROR
;
1022 CommandCost ret
= CheckOwnership(v
->owner
);
1023 if (ret
.Failed()) return ret
;
1025 bool reset
= StrEmpty(text
);
1028 if (Utf8StringLength(text
) >= MAX_LENGTH_VEHICLE_NAME_CHARS
) return CMD_ERROR
;
1029 if (!(flags
& DC_AUTOREPLACE
) && !IsUniqueVehicleName(text
)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE
);
1032 if (flags
& DC_EXEC
) {
1034 v
->name
= reset
? NULL
: strdup(text
);
1035 InvalidateWindowClassesData(GetWindowClassForVehicleType(v
->type
), 1);
1036 MarkWholeScreenDirty();
1039 return CommandCost();
1044 * Change the service interval of a vehicle
1045 * @param tile unused
1046 * @param flags type of operation
1047 * @param p1 vehicle ID that is being service-interval-changed
1049 * - p2 = (bit 0-15) - new service interval
1050 * - p2 = (bit 16) - service interval is custom flag
1051 * - p2 = (bit 17) - service interval is percentage flag
1052 * @param text unused
1053 * @return the cost of this operation or an error
1055 CommandCost
CmdChangeServiceInt(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1057 Vehicle
*v
= Vehicle::GetIfValid(p1
);
1058 if (v
== NULL
|| !v
->IsPrimaryVehicle()) return CMD_ERROR
;
1060 CommandCost ret
= CheckOwnership(v
->owner
);
1061 if (ret
.Failed()) return ret
;
1063 const Company
*company
= Company::Get(v
->owner
);
1064 bool iscustom
= HasBit(p2
, 16);
1065 bool ispercent
= iscustom
? HasBit(p2
, 17) : company
->settings
.vehicle
.servint_ispercent
;
1069 serv_int
= GB(p2
, 0, 16);
1070 if (serv_int
!= GetServiceIntervalClamped(serv_int
, ispercent
)) return CMD_ERROR
;
1072 serv_int
= CompanyServiceInterval(company
, v
->type
);
1075 if (flags
& DC_EXEC
) {
1076 v
->SetServiceInterval(serv_int
);
1077 v
->SetServiceIntervalIsCustom(iscustom
);
1078 v
->SetServiceIntervalIsPercent(ispercent
);
1079 SetWindowDirty(WC_VEHICLE_DETAILS
, v
->index
);
1082 return CommandCost();