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"
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 extern const StringID _veh_sell_error_table
[] = {
38 STR_ERROR_CAN_T_SELL_TRAIN
,
39 STR_ERROR_CAN_T_SELL_ROAD_VEHICLE
,
40 STR_ERROR_CAN_T_SELL_SHIP
,
41 STR_ERROR_CAN_T_SELL_AIRCRAFT
,
44 extern const StringID _veh_refit_error_table
[] = {
45 STR_ERROR_CAN_T_REFIT_TRAIN
,
46 STR_ERROR_CAN_T_REFIT_ROAD_VEHICLE
,
47 STR_ERROR_CAN_T_REFIT_SHIP
,
48 STR_ERROR_CAN_T_REFIT_AIRCRAFT
,
51 extern const StringID _send_to_depot_error_table
[] = {
52 STR_ERROR_CAN_T_SEND_TRAIN_TO_DEPOT
,
53 STR_ERROR_CAN_T_SEND_ROAD_VEHICLE_TO_DEPOT
,
54 STR_ERROR_CAN_T_SEND_SHIP_TO_DEPOT
,
55 STR_ERROR_CAN_T_SEND_AIRCRAFT_TO_HANGAR
,
59 CommandCost
CmdBuildRailVehicle(TileIndex tile
, DoCommandFlag flags
, const Engine
*e
, uint16 data
, Vehicle
**v
);
60 CommandCost
CmdBuildRoadVehicle(TileIndex tile
, DoCommandFlag flags
, const Engine
*e
, uint16 data
, Vehicle
**v
);
61 CommandCost
CmdBuildShip (TileIndex tile
, DoCommandFlag flags
, const Engine
*e
, uint16 data
, Vehicle
**v
);
62 CommandCost
CmdBuildAircraft (TileIndex tile
, DoCommandFlag flags
, const Engine
*e
, uint16 data
, Vehicle
**v
);
66 * @param tile tile of depot where the vehicle is built
67 * @param flags for command
68 * @param p1 various bitstuffed data
69 * bits 0-15: vehicle type being built.
70 * bits 16-31: vehicle type specific bits passed on to the vehicle build functions.
73 * @return the cost of this operation or an error
75 CommandCost
CmdBuildVehicle(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
77 /* Elementary check for valid location. */
78 if (!IsDepotTile(tile
) || !IsTileOwner(tile
, _current_company
)) return CMD_ERROR
;
80 VehicleType type
= GetDepotVehicleType(tile
);
82 /* Validate the engine type. */
83 EngineID eid
= GB(p1
, 0, 16);
84 if (!IsEngineBuildable(eid
, type
, _current_company
)) return_cmd_error(STR_ERROR_RAIL_VEHICLE_NOT_AVAILABLE
+ type
);
86 const Engine
*e
= Engine::Get(eid
);
87 CommandCost
value(EXPENSES_NEW_VEHICLES
, e
->GetCost());
89 /* Engines without valid cargo should not be available */
90 if (e
->GetDefaultCargoType() == CT_INVALID
) return CMD_ERROR
;
92 /* Check whether the number of vehicles we need to build can be built according to pool space. */
95 case VEH_TRAIN
: num_vehicles
= (e
->u
.rail
.railveh_type
== RAILVEH_MULTIHEAD
? 2 : 1) + CountArticulatedParts(eid
, false); break;
96 case VEH_ROAD
: num_vehicles
= 1 + CountArticulatedParts(eid
, false); break;
97 case VEH_SHIP
: num_vehicles
= 1; break;
98 case VEH_AIRCRAFT
: num_vehicles
= e
->u
.air
.subtype
& AIR_CTOL
? 2 : 3; break;
99 default: NOT_REACHED(); // Safe due to IsDepotTile()
101 if (!Vehicle::CanAllocateItem(num_vehicles
)) return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME
);
103 /* Check whether we can allocate a unit number. Autoreplace does not allocate
104 * an unit number as it will (always) reuse the one of the replaced vehicle
105 * and (train) wagons don't have an unit number in any scenario. */
106 UnitID unit_num
= (flags
& DC_AUTOREPLACE
|| (type
== VEH_TRAIN
&& e
->u
.rail
.railveh_type
== RAILVEH_WAGON
)) ? 0 : GetFreeUnitNumber(type
);
107 if (unit_num
== UINT16_MAX
) return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME
);
111 case VEH_TRAIN
: value
.AddCost(CmdBuildRailVehicle(tile
, flags
, e
, GB(p1
, 16, 16), &v
)); break;
112 case VEH_ROAD
: value
.AddCost(CmdBuildRoadVehicle(tile
, flags
, e
, GB(p1
, 16, 16), &v
)); break;
113 case VEH_SHIP
: value
.AddCost(CmdBuildShip (tile
, flags
, e
, GB(p1
, 16, 16), &v
)); break;
114 case VEH_AIRCRAFT
: value
.AddCost(CmdBuildAircraft (tile
, flags
, e
, GB(p1
, 16, 16), &v
)); break;
115 default: NOT_REACHED(); // Safe due to IsDepotTile()
118 if (value
.Succeeded() && flags
& DC_EXEC
) {
119 v
->unitnumber
= unit_num
;
120 v
->value
= value
.GetCost();
122 InvalidateWindowData(WC_VEHICLE_DEPOT
, v
->tile
);
123 InvalidateWindowClassesData(GetWindowClassForVehicleType(type
), 0);
124 SetWindowDirty(WC_COMPANY
, _current_company
);
125 if (IsLocalCompany()) {
126 InvalidateAutoreplaceWindow(v
->engine_type
, v
->group_id
); // updates the auto replace window (must be called before incrementing num_engines)
129 GroupStatistics::CountEngine(v
, 1);
130 GroupStatistics::UpdateAutoreplace(_current_company
);
132 if (v
->IsPrimaryVehicle()) {
133 GroupStatistics::CountVehicle(v
, 1);
134 OrderBackup::Restore(v
, p2
);
141 CommandCost
CmdSellRailWagon(DoCommandFlag flags
, Vehicle
*v
, uint16 data
, uint32 user
);
145 * @param tile unused.
146 * @param flags for command.
147 * @param p1 various bitstuffed data.
148 * bits 0-19: vehicle ID being sold.
149 * bits 20-30: vehicle type specific bits passed on to the vehicle build functions.
150 * bit 31: make a backup of the vehicle's order (if an engine).
152 * @param text unused.
153 * @return the cost of this operation or an error.
155 CommandCost
CmdSellVehicle(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
157 Vehicle
*v
= Vehicle::GetIfValid(GB(p1
, 0, 20));
158 if (v
== NULL
) return CMD_ERROR
;
160 Vehicle
*front
= v
->First();
162 CommandCost ret
= CheckOwnership(front
->owner
);
163 if (ret
.Failed()) return ret
;
165 if (front
->vehstatus
& VS_CRASHED
) return_cmd_error(STR_ERROR_VEHICLE_IS_DESTROYED
);
167 if (!front
->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAIN_MUST_BE_STOPPED_INSIDE_DEPOT
+ front
->type
);
169 /* Can we actually make the order backup, i.e. are there enough orders? */
170 if (p1
& MAKE_ORDER_BACKUP_FLAG
&&
171 front
->orders
.list
!= NULL
&&
172 !front
->orders
.list
->IsShared() &&
173 !Order::CanAllocateItem(front
->orders
.list
->GetNumOrders())) {
174 /* Only happens in exceptional cases when there aren't enough orders anyhow.
175 * Thus it should be safe to just drop the orders in that case. */
176 p1
&= ~MAKE_ORDER_BACKUP_FLAG
;
179 if (v
->type
== VEH_TRAIN
) {
180 ret
= CmdSellRailWagon(flags
, v
, GB(p1
, 20, 12), p2
);
182 ret
= CommandCost(EXPENSES_NEW_VEHICLES
, -front
->value
);
184 if (flags
& DC_EXEC
) {
185 if (front
->IsPrimaryVehicle() && p1
& MAKE_ORDER_BACKUP_FLAG
) OrderBackup::Backup(front
, p2
);
194 * Helper to run the refit cost callback.
195 * @param v The vehicle we are refitting, can be NULL.
196 * @param engine_type Which engine to refit
197 * @param new_cid Cargo type we are refitting to.
198 * @param new_subtype New cargo subtype.
199 * @param [out] auto_refit_allowed The refit is allowed as an auto-refit.
200 * @return Price for refitting
202 static int GetRefitCostFactor(const Vehicle
*v
, EngineID engine_type
, CargoID new_cid
, byte new_subtype
, bool *auto_refit_allowed
)
204 /* Prepare callback param with info about the new cargo type. */
205 const Engine
*e
= Engine::Get(engine_type
);
207 /* Is this vehicle a NewGRF vehicle? */
208 if (e
->GetGRF() != NULL
) {
209 const CargoSpec
*cs
= CargoSpec::Get(new_cid
);
210 uint32 param1
= (cs
->classes
<< 16) | (new_subtype
<< 8) | e
->GetGRF()->cargo_map
[new_cid
];
212 uint16 cb_res
= GetVehicleCallback(CBID_VEHICLE_REFIT_COST
, param1
, 0, engine_type
, v
);
213 if (cb_res
!= CALLBACK_FAILED
) {
214 *auto_refit_allowed
= HasBit(cb_res
, 14);
215 int factor
= GB(cb_res
, 0, 14);
216 if (factor
>= 0x2000) factor
-= 0x4000; // Treat as signed integer.
221 *auto_refit_allowed
= e
->info
.refit_cost
== 0;
222 return (v
== NULL
|| v
->cargo_type
!= new_cid
) ? e
->info
.refit_cost
: 0;
226 * Learn the price of refitting a certain engine
227 * @param v The vehicle we are refitting, can be NULL.
228 * @param engine_type Which engine to refit
229 * @param new_cid Cargo type we are refitting to.
230 * @param new_subtype New cargo subtype.
231 * @param [out] auto_refit_allowed The refit is allowed as an auto-refit.
232 * @return Price for refitting
234 static CommandCost
GetRefitCost(const Vehicle
*v
, EngineID engine_type
, CargoID new_cid
, byte new_subtype
, bool *auto_refit_allowed
)
236 ExpensesType expense_type
;
237 const Engine
*e
= Engine::Get(engine_type
);
239 int cost_factor
= GetRefitCostFactor(v
, engine_type
, new_cid
, new_subtype
, auto_refit_allowed
);
242 base_price
= PR_BUILD_VEHICLE_SHIP
;
243 expense_type
= EXPENSES_SHIP_RUN
;
247 base_price
= PR_BUILD_VEHICLE_ROAD
;
248 expense_type
= EXPENSES_ROADVEH_RUN
;
252 base_price
= PR_BUILD_VEHICLE_AIRCRAFT
;
253 expense_type
= EXPENSES_AIRCRAFT_RUN
;
257 base_price
= (e
->u
.rail
.railveh_type
== RAILVEH_WAGON
) ? PR_BUILD_VEHICLE_WAGON
: PR_BUILD_VEHICLE_TRAIN
;
259 expense_type
= EXPENSES_TRAIN_RUN
;
262 default: NOT_REACHED();
264 if (cost_factor
< 0) {
265 return CommandCost(expense_type
, -GetPrice(base_price
, -cost_factor
, e
->GetGRF(), -10));
267 return CommandCost(expense_type
, GetPrice(base_price
, cost_factor
, e
->GetGRF(), -10));
271 /** Helper structure for RefitVehicle() */
273 Vehicle
*v
; ///< Vehicle to refit
274 uint capacity
; ///< New capacity of vehicle
275 uint mail_capacity
; ///< New mail capacity of aircraft
276 byte subtype
; ///< cargo subtype to refit to
280 * Refits a vehicle (chain).
281 * This is the vehicle-type independent part of the CmdRefitXXX functions.
282 * @param v The vehicle to refit.
283 * @param only_this Whether to only refit this vehicle, or to check the rest of them.
284 * @param num_vehicles Number of vehicles to refit (not counting articulated parts). Zero means the whole chain.
285 * @param new_cid Cargotype to refit to
286 * @param new_subtype Cargo subtype to refit to. 0xFF means to try keeping the same subtype according to GetBestFittingSubType().
287 * @param flags Command flags
288 * @param auto_refit Refitting is done as automatic refitting outside a depot.
289 * @return Refit cost.
291 static CommandCost
RefitVehicle(Vehicle
*v
, bool only_this
, uint8 num_vehicles
, CargoID new_cid
, byte new_subtype
, DoCommandFlag flags
, bool auto_refit
)
293 CommandCost
cost(v
->GetExpenseType(false));
294 uint total_capacity
= 0;
295 uint total_mail_capacity
= 0;
296 num_vehicles
= num_vehicles
== 0 ? UINT8_MAX
: num_vehicles
;
298 VehicleSet vehicles_to_refit
;
300 GetVehicleSet(vehicles_to_refit
, v
, num_vehicles
);
301 /* In this case, we need to check the whole chain. */
305 static SmallVector
<RefitResult
, 16> refit_result
;
306 refit_result
.Clear();
308 v
->InvalidateNewGRFCacheOfChain();
309 byte actual_subtype
= new_subtype
;
310 for (; v
!= NULL
; v
= (only_this
? NULL
: v
->Next())) {
311 /* Reset actual_subtype for every new vehicle */
312 if (!v
->IsArticulatedPart()) actual_subtype
= new_subtype
;
314 if (v
->type
== VEH_TRAIN
&& !vehicles_to_refit
.Contains(v
->index
) && !only_this
) continue;
316 const Engine
*e
= v
->GetEngine();
317 if (!e
->CanCarryCargo()) continue;
319 /* If the vehicle is not refittable, or does not allow automatic refitting,
320 * count its capacity nevertheless if the cargo matches */
321 bool refittable
= HasBit(e
->info
.refit_mask
, new_cid
) && (!auto_refit
|| HasBit(e
->info
.misc_flags
, EF_AUTO_REFIT
));
322 if (!refittable
&& v
->cargo_type
!= new_cid
) continue;
324 /* Determine best fitting subtype if requested */
325 if (actual_subtype
== 0xFF) {
326 actual_subtype
= GetBestFittingSubType(v
, v
, new_cid
);
329 /* Back up the vehicle's cargo type */
330 CargoID temp_cid
= v
->cargo_type
;
331 byte temp_subtype
= v
->cargo_subtype
;
333 v
->cargo_type
= new_cid
;
334 v
->cargo_subtype
= actual_subtype
;
337 uint16 mail_capacity
= 0;
338 uint amount
= e
->DetermineCapacity(v
, &mail_capacity
);
339 total_capacity
+= amount
;
340 /* mail_capacity will always be zero if the vehicle is not an aircraft. */
341 total_mail_capacity
+= mail_capacity
;
343 if (!refittable
) continue;
345 /* Restore the original cargo type */
346 v
->cargo_type
= temp_cid
;
347 v
->cargo_subtype
= temp_subtype
;
349 bool auto_refit_allowed
;
350 CommandCost refit_cost
= GetRefitCost(v
, v
->engine_type
, new_cid
, actual_subtype
, &auto_refit_allowed
);
351 if (auto_refit
&& !auto_refit_allowed
) {
352 /* Sorry, auto-refitting not allowed, subtract the cargo amount again from the total. */
353 total_capacity
-= amount
;
354 total_mail_capacity
-= mail_capacity
;
356 if (v
->cargo_type
== new_cid
) {
357 /* Add the old capacity nevertheless, if the cargo matches */
358 total_capacity
+= v
->cargo_cap
;
359 if (v
->type
== VEH_AIRCRAFT
) total_mail_capacity
+= v
->Next()->cargo_cap
;
363 cost
.AddCost(refit_cost
);
365 /* Record the refitting.
366 * Do not execute the refitting immediately, so DetermineCapacity and GetRefitCost do the same in test and exec run.
369 * - If the capacity of vehicles depends on other vehicles in the chain, the actual capacity is
370 * set after RefitVehicle() via ConsistChanged() and friends. The estimation via _returned_refit_capacity will be wrong.
371 * - We have to call the refit cost callback with the pre-refit configuration of the chain because we want refit and
372 * autorefit to behave the same, and we need its result for auto_refit_allowed.
374 RefitResult
*result
= refit_result
.Append();
376 result
->capacity
= amount
;
377 result
->mail_capacity
= mail_capacity
;
378 result
->subtype
= actual_subtype
;
381 if (flags
& DC_EXEC
) {
382 /* Store the result */
383 for (RefitResult
*result
= refit_result
.Begin(); result
!= refit_result
.End(); result
++) {
384 Vehicle
*u
= result
->v
;
385 u
->refit_cap
= (u
->cargo_type
== new_cid
) ? min(result
->capacity
, u
->refit_cap
) : 0;
386 if (u
->cargo
.TotalCount() > u
->refit_cap
) u
->cargo
.Truncate(u
->cargo
.TotalCount() - u
->refit_cap
);
387 u
->cargo_type
= new_cid
;
388 u
->cargo_cap
= result
->capacity
;
389 u
->cargo_subtype
= result
->subtype
;
390 if (u
->type
== VEH_AIRCRAFT
) {
391 Vehicle
*w
= u
->Next();
392 w
->refit_cap
= min(w
->refit_cap
, result
->mail_capacity
);
393 w
->cargo_cap
= result
->mail_capacity
;
394 if (w
->cargo
.TotalCount() > w
->refit_cap
) w
->cargo
.Truncate(w
->cargo
.TotalCount() - w
->refit_cap
);
399 refit_result
.Clear();
400 _returned_refit_capacity
= total_capacity
;
401 _returned_mail_refit_capacity
= total_mail_capacity
;
406 * Refits a vehicle to the specified cargo type.
408 * @param flags type of operation
409 * @param p1 vehicle ID to refit
410 * @param p2 various bitstuffed elements
411 * - p2 = (bit 0-4) - New cargo type to refit to.
412 * - p2 = (bit 6) - Automatic refitting.
413 * - p2 = (bit 7) - Refit only this vehicle. Used only for cloning vehicles.
414 * - p2 = (bit 8-15) - New cargo subtype to refit to. 0xFF means to try keeping the same subtype according to GetBestFittingSubType().
415 * - p2 = (bit 16-23) - Number of vehicles to refit (not counting articulated parts). Zero means all vehicles.
416 * Only used if "refit only this vehicle" is false.
418 * @return the cost of this operation or an error
420 CommandCost
CmdRefitVehicle(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
422 Vehicle
*v
= Vehicle::GetIfValid(p1
);
423 if (v
== NULL
) return CMD_ERROR
;
425 /* Don't allow disasters and sparks and such to be refitted.
426 * We cannot check for IsPrimaryVehicle as autoreplace also refits in free wagon chains. */
427 if (!IsCompanyBuildableVehicleType(v
->type
)) return CMD_ERROR
;
429 Vehicle
*front
= v
->First();
431 CommandCost ret
= CheckOwnership(front
->owner
);
432 if (ret
.Failed()) return ret
;
434 bool auto_refit
= HasBit(p2
, 6);
435 bool free_wagon
= v
->type
== VEH_TRAIN
&& Train::From(front
)->IsFreeWagon(); // used by autoreplace/renew
437 /* Don't allow shadows and such to be refitted. */
438 if (v
!= front
&& (v
->type
== VEH_SHIP
|| v
->type
== VEH_AIRCRAFT
)) return CMD_ERROR
;
439 /* Allow auto-refitting only during loading and normal refitting only in a depot. */
440 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
);
441 if (front
->vehstatus
& VS_CRASHED
) return_cmd_error(STR_ERROR_VEHICLE_IS_DESTROYED
);
444 CargoID new_cid
= GB(p2
, 0, 5);
445 byte new_subtype
= GB(p2
, 8, 8);
446 if (new_cid
>= NUM_CARGO
) return CMD_ERROR
;
448 /* For ships and aircrafts there is always only one. */
449 bool only_this
= HasBit(p2
, 7) || front
->type
== VEH_SHIP
|| front
->type
== VEH_AIRCRAFT
;
450 uint8 num_vehicles
= GB(p2
, 16, 8);
452 CommandCost cost
= RefitVehicle(v
, only_this
, num_vehicles
, new_cid
, new_subtype
, flags
, auto_refit
);
454 if (flags
& DC_EXEC
) {
455 /* Update the cached variables */
458 Train::From(front
)->ConsistChanged(auto_refit
? CCF_AUTOREFIT
: CCF_REFIT
);
461 RoadVehUpdateCache(RoadVehicle::From(front
), auto_refit
);
462 if (_settings_game
.vehicle
.roadveh_acceleration_model
!= AM_ORIGINAL
) RoadVehicle::From(front
)->CargoChanged();
466 v
->InvalidateNewGRFCacheOfChain();
467 Ship::From(v
)->UpdateCache();
471 v
->InvalidateNewGRFCacheOfChain();
472 UpdateAircraftCache(Aircraft::From(v
), true);
475 default: NOT_REACHED();
480 InvalidateWindowData(WC_VEHICLE_DETAILS
, front
->index
);
481 InvalidateWindowClassesData(GetWindowClassForVehicleType(v
->type
), 0);
483 SetWindowDirty(WC_VEHICLE_DEPOT
, front
->tile
);
485 /* Always invalidate the cache; querycost might have filled it. */
486 v
->InvalidateNewGRFCacheOfChain();
493 * Start/Stop a vehicle
495 * @param flags type of operation
496 * @param p1 vehicle to start/stop, don't forget to change CcStartStopVehicle if you modify this!
497 * @param p2 bit 0: Shall the start/stop newgrf callback be evaluated (only valid with DC_AUTOREPLACE for network safety)
499 * @return the cost of this operation or an error
501 CommandCost
CmdStartStopVehicle(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
503 /* Disable the effect of p2 bit 0, when DC_AUTOREPLACE is not set */
504 if ((flags
& DC_AUTOREPLACE
) == 0) SetBit(p2
, 0);
506 Vehicle
*v
= Vehicle::GetIfValid(p1
);
507 if (v
== NULL
|| !v
->IsPrimaryVehicle()) return CMD_ERROR
;
509 CommandCost ret
= CheckOwnership(v
->owner
);
510 if (ret
.Failed()) return ret
;
512 if (v
->vehstatus
& VS_CRASHED
) return_cmd_error(STR_ERROR_VEHICLE_IS_DESTROYED
);
516 if ((v
->vehstatus
& VS_STOPPED
) && Train::From(v
)->gcache
.cached_power
== 0) return_cmd_error(STR_ERROR_TRAIN_START_NO_POWER
);
524 Aircraft
*a
= Aircraft::From(v
);
525 /* cannot stop airplane when in flight, or when taking off / landing */
526 if (!(v
->vehstatus
& VS_CRASHED
) && a
->state
>= STARTTAKEOFF
&& a
->state
< TERM7
) return_cmd_error(STR_ERROR_AIRCRAFT_IS_IN_FLIGHT
);
530 default: return CMD_ERROR
;
534 /* Check if this vehicle can be started/stopped. Failure means 'allow'. */
535 uint16 callback
= GetVehicleCallback(CBID_VEHICLE_START_STOP_CHECK
, 0, 0, v
->engine_type
, v
);
536 StringID error
= STR_NULL
;
537 if (callback
!= CALLBACK_FAILED
) {
538 if (v
->GetGRF()->grf_version
< 8) {
539 /* 8 bit result 0xFF means 'allow' */
540 if (callback
< 0x400 && GB(callback
, 0, 8) != 0xFF) error
= GetGRFStringID(v
->GetGRFID(), 0xD000 + callback
);
542 if (callback
< 0x400) {
543 error
= GetGRFStringID(v
->GetGRFID(), 0xD000 + callback
);
549 default: // unknown reason -> disallow
550 error
= STR_ERROR_INCOMPATIBLE_RAIL_TYPES
;
556 if (error
!= STR_NULL
) return_cmd_error(error
);
559 if (flags
& DC_EXEC
) {
560 if (v
->IsStoppedInDepot() && (flags
& DC_AUTOREPLACE
) == 0) DeleteVehicleNews(p1
, STR_NEWS_TRAIN_IS_WAITING
+ v
->type
);
562 v
->vehstatus
^= VS_STOPPED
;
563 if (v
->type
!= VEH_TRAIN
) v
->cur_speed
= 0; // trains can stop 'slowly'
565 SetWindowWidgetDirty(WC_VEHICLE_VIEW
, v
->index
, WID_VV_START_STOP
);
566 SetWindowDirty(WC_VEHICLE_DEPOT
, v
->tile
);
567 SetWindowClassesDirty(GetWindowClassForVehicleType(v
->type
));
569 return CommandCost();
573 * Starts or stops a lot of vehicles
574 * @param tile Tile of the depot where the vehicles are started/stopped (only used for depots)
575 * @param flags type of operation
577 * - bit 0 set = start vehicles, unset = stop vehicles
578 * - bit 1 if set, then it's a vehicle list window, not a depot and Tile is ignored in this case
579 * @param p2 packed VehicleListIdentifier
581 * @return the cost of this operation or an error
583 CommandCost
CmdMassStartStopVehicle(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
586 bool do_start
= HasBit(p1
, 0);
587 bool vehicle_list_window
= HasBit(p1
, 1);
589 VehicleListIdentifier vli
;
590 if (!vli
.Unpack(p2
)) return CMD_ERROR
;
591 if (!IsCompanyBuildableVehicleType(vli
.vtype
)) return CMD_ERROR
;
593 if (vehicle_list_window
) {
594 if (!GenerateVehicleSortList(&list
, vli
)) return CMD_ERROR
;
596 /* Get the list of vehicles in the depot */
597 BuildDepotVehicleList(vli
.vtype
, tile
, &list
, NULL
);
600 for (uint i
= 0; i
< list
.Length(); i
++) {
601 const Vehicle
*v
= list
[i
];
603 if (!!(v
->vehstatus
& VS_STOPPED
) != do_start
) continue;
605 if (!vehicle_list_window
&& !v
->IsChainInDepot()) continue;
607 /* Just try and don't care if some vehicle's can't be stopped. */
608 DoCommand(tile
, v
->index
, 0, flags
, CMD_START_STOP_VEHICLE
);
611 return CommandCost();
615 * Sells all vehicles in a depot
616 * @param tile Tile of the depot where the depot is
617 * @param flags type of operation
618 * @param p1 Vehicle type
621 * @return the cost of this operation or an error
623 CommandCost
CmdDepotSellAllVehicles(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
627 CommandCost
cost(EXPENSES_NEW_VEHICLES
);
628 VehicleType vehicle_type
= Extract
<VehicleType
, 0, 3>(p1
);
630 if (!IsCompanyBuildableVehicleType(vehicle_type
)) return CMD_ERROR
;
632 /* Get the list of vehicles in the depot */
633 BuildDepotVehicleList(vehicle_type
, tile
, &list
, &list
);
635 CommandCost last_error
= CMD_ERROR
;
636 bool had_success
= false;
637 for (uint i
= 0; i
< list
.Length(); i
++) {
638 CommandCost ret
= DoCommand(tile
, list
[i
]->index
| (1 << 20), 0, flags
, CMD_SELL_VEHICLE
);
639 if (ret
.Succeeded()) {
647 return had_success
? cost
: last_error
;
651 * Autoreplace all vehicles in the depot
652 * @param tile Tile of the depot where the vehicles are
653 * @param flags type of operation
654 * @param p1 Type of vehicle
657 * @return the cost of this operation or an error
659 CommandCost
CmdDepotMassAutoReplace(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
662 CommandCost cost
= CommandCost(EXPENSES_NEW_VEHICLES
);
663 VehicleType vehicle_type
= Extract
<VehicleType
, 0, 3>(p1
);
665 if (!IsCompanyBuildableVehicleType(vehicle_type
)) return CMD_ERROR
;
666 if (!IsDepotTile(tile
) || !IsTileOwner(tile
, _current_company
)) return CMD_ERROR
;
668 /* Get the list of vehicles in the depot */
669 BuildDepotVehicleList(vehicle_type
, tile
, &list
, &list
, true);
671 for (uint i
= 0; i
< list
.Length(); i
++) {
672 const Vehicle
*v
= list
[i
];
674 /* Ensure that the vehicle completely in the depot */
675 if (!v
->IsChainInDepot()) continue;
677 CommandCost ret
= DoCommand(0, v
->index
, 0, flags
, CMD_AUTOREPLACE_VEHICLE
);
679 if (ret
.Succeeded()) cost
.AddCost(ret
);
685 * Test if a name is unique among vehicle names.
686 * @param name Name to test.
687 * @return True ifffffff the name is unique.
689 static bool IsUniqueVehicleName(const char *name
)
693 FOR_ALL_VEHICLES(v
) {
694 if (v
->name
!= NULL
&& strcmp(v
->name
, name
) == 0) return false;
701 * Clone the custom name of a vehicle, adding or incrementing a number.
702 * @param src Source vehicle, with a custom name.
703 * @param dst Destination vehicle.
705 static void CloneVehicleName(const Vehicle
*src
, Vehicle
*dst
)
707 /* Find the position of the first digit in the last group of digits. */
708 size_t number_position
;
709 for (number_position
= strlen(src
->name
); number_position
> 0; number_position
--) {
710 /* The design of UTF-8 lets this work simply without having to check
711 * for UTF-8 sequences. */
712 if (src
->name
[number_position
- 1] < '0' || src
->name
[number_position
- 1] > '9') break;
715 /* Format buffer and determine starting number. */
718 buf
.copy (src
->name
);
719 if (src
->name
[number_position
] == '\0') {
720 /* No digit at the end, so start at number 2. */
722 number_position
= buf
.length();
726 /* Found digits, parse them and start at the next number. */
727 buf
.truncate (number_position
);
729 num
= strtol(&src
->name
[number_position
], &endptr
, 10) + 1;
730 padding
= endptr
- &src
->name
[number_position
];
733 /* Check if this name is already taken. */
734 for (int max_iterations
= 1000; max_iterations
> 0; max_iterations
--, num
++) {
735 /* Attach the number to the temporary name. */
736 assert (buf
.length() == number_position
);
737 buf
.append_fmt ("%0*d", padding
, num
);
739 /* Check the name is unique. */
740 if (IsUniqueVehicleName (buf
.c_str())) {
741 dst
->name
= xstrdup (buf
.c_str());
745 buf
.truncate (number_position
);
748 /* All done. If we didn't find a name, it'll just use its default. */
752 * Clone a vehicle. If it is a train, it will clone all the cars too
753 * @param tile tile of the depot where the cloned vehicle is build
754 * @param flags type of operation
755 * @param p1 the original vehicle's index
756 * @param p2 1 = shared orders, else copied orders
758 * @return the cost of this operation or an error
760 CommandCost
CmdCloneVehicle(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
762 CommandCost
total_cost(EXPENSES_NEW_VEHICLES
);
764 Vehicle
*v
= Vehicle::GetIfValid(p1
);
765 if (v
== NULL
|| !v
->IsPrimaryVehicle()) return CMD_ERROR
;
766 Vehicle
*v_front
= v
;
768 Vehicle
*w_front
= NULL
;
769 Vehicle
*w_rear
= NULL
;
772 * v_front is the front engine in the original vehicle
773 * v is the car/vehicle of the original vehicle that is currently being copied
774 * w_front is the front engine of the cloned vehicle
775 * w is the car/vehicle currently being cloned
776 * w_rear is the rear end of the cloned train. It's used to add more cars and is only used by trains
779 CommandCost ret
= CheckOwnership(v
->owner
);
780 if (ret
.Failed()) return ret
;
782 if (v
->type
== VEH_TRAIN
&& (!v
->IsFrontEngine() || Train::From(v
)->crash_anim_pos
>= 4400)) return CMD_ERROR
;
784 /* check that we can allocate enough vehicles */
785 if (!(flags
& DC_EXEC
)) {
789 } while ((v
= v
->Next()) != NULL
);
791 if (!Vehicle::CanAllocateItem(veh_counter
)) {
792 return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME
);
799 if (v
->type
== VEH_TRAIN
&& Train::From(v
)->IsRearDualheaded()) {
800 /* we build the rear ends of multiheaded trains with the front ones */
804 /* In case we're building a multi headed vehicle and the maximum number of
805 * vehicles is almost reached (e.g. max trains - 1) not all vehicles would
806 * be cloned. When the non-primary engines were build they were seen as
807 * 'new' vehicles whereas they would immediately be joined with a primary
808 * engine. This caused the vehicle to be not build as 'the limit' had been
809 * reached, resulting in partially build vehicles and such. */
810 DoCommandFlag build_flags
= flags
;
811 if ((flags
& DC_EXEC
) && !v
->IsPrimaryVehicle()) build_flags
|= DC_AUTOREPLACE
;
813 CommandCost cost
= DoCommand(tile
, v
->engine_type
| (1 << 16), 0, build_flags
, CMD_BUILD_VEHICLE
);
816 /* Can't build a part, then sell the stuff we already made; clear up the mess */
817 if (w_front
!= NULL
) DoCommand(w_front
->tile
, w_front
->index
| (1 << 20), 0, flags
, CMD_SELL_VEHICLE
);
821 total_cost
.AddCost(cost
);
823 if (flags
& DC_EXEC
) {
824 w
= Vehicle::Get(_new_vehicle_id
);
826 if (v
->type
== VEH_TRAIN
&& HasBit(Train::From(v
)->flags
, VRF_REVERSE_DIRECTION
)) {
827 SetBit(Train::From(w
)->flags
, VRF_REVERSE_DIRECTION
);
830 if (v
->type
== VEH_TRAIN
&& !v
->IsFrontEngine()) {
831 /* this s a train car
832 * add this unit to the end of the train */
833 CommandCost result
= DoCommand(0, w
->index
| 1 << 20, w_rear
->index
, flags
, CMD_MOVE_RAIL_VEHICLE
);
834 if (result
.Failed()) {
835 /* The train can't be joined to make the same consist as the original.
836 * Sell what we already made (clean up) and return an error. */
837 DoCommand(w_front
->tile
, w_front
->index
| 1 << 20, 0, flags
, CMD_SELL_VEHICLE
);
838 DoCommand(w_front
->tile
, w
->index
| 1 << 20, 0, flags
, CMD_SELL_VEHICLE
);
839 return result
; // return error and the message returned from CMD_MOVE_RAIL_VEHICLE
842 /* this is a front engine or not a train. */
844 w
->service_interval
= v
->service_interval
;
845 w
->SetServiceIntervalIsCustom(v
->ServiceIntervalIsCustom());
846 w
->SetServiceIntervalIsPercent(v
->ServiceIntervalIsPercent());
848 w_rear
= w
; // trains needs to know the last car in the train, so they can add more in next loop
850 } while (v
->type
== VEH_TRAIN
&& (v
= v
->GetNextVehicle()) != NULL
);
852 if ((flags
& DC_EXEC
) && v_front
->type
== VEH_TRAIN
) {
853 /* for trains this needs to be the front engine due to the callback function */
854 _new_vehicle_id
= w_front
->index
;
857 if (flags
& DC_EXEC
) {
858 /* Cloned vehicles belong to the same group */
859 DoCommand(0, v_front
->group_id
, w_front
->index
, flags
, CMD_ADD_VEHICLE_GROUP
);
863 /* Take care of refitting. */
867 /* Both building and refitting are influenced by newgrf callbacks, which
868 * makes it impossible to accurately estimate the cloning costs. In
869 * particular, it is possible for engines of the same type to be built with
870 * different numbers of articulated parts, so when refitting we have to
871 * loop over real vehicles first, and then the articulated parts of those
872 * vehicles in a different loop. */
875 if (flags
& DC_EXEC
) {
878 /* Find out what's the best sub type */
879 byte subtype
= GetBestFittingSubType(v
, w
, v
->cargo_type
);
880 if (w
->cargo_type
!= v
->cargo_type
|| w
->cargo_subtype
!= subtype
) {
881 CommandCost cost
= DoCommand(0, w
->index
, v
->cargo_type
| 1U << 7 | (subtype
<< 8), flags
, CMD_REFIT_VEHICLE
);
882 if (cost
.Succeeded()) total_cost
.AddCost(cost
);
885 if (w
->IsGroundVehicle() && w
->HasArticulatedPart()) {
886 w
= w
->GetNextArticulatedPart();
891 const Engine
*e
= v
->GetEngine();
892 CargoID initial_cargo
= (e
->CanCarryCargo() ? e
->GetDefaultCargoType() : (CargoID
)CT_INVALID
);
894 if (v
->cargo_type
!= initial_cargo
&& initial_cargo
!= CT_INVALID
) {
896 total_cost
.AddCost(GetRefitCost(NULL
, v
->engine_type
, v
->cargo_type
, v
->cargo_subtype
, &dummy
));
900 if (v
->IsGroundVehicle() && v
->HasArticulatedPart()) {
901 v
= v
->GetNextArticulatedPart();
907 if ((flags
& DC_EXEC
) && v
->type
== VEH_TRAIN
) w
= w
->GetNextVehicle();
908 } while (v
->type
== VEH_TRAIN
&& (v
= v
->GetNextVehicle()) != NULL
);
910 if (flags
& DC_EXEC
) {
912 * Set the orders of the vehicle. Cannot do it earlier as we need
913 * the vehicle refitted before doing this, otherwise the moved
914 * cargo types might not match (passenger vs non-passenger)
916 DoCommand(0, w_front
->index
| (p2
& 1 ? CO_SHARE
: CO_COPY
) << 30, v_front
->index
, flags
, CMD_CLONE_ORDER
);
918 /* Now clone the vehicle's name, if it has one. */
919 if (v_front
->name
!= NULL
) CloneVehicleName(v_front
, w_front
);
922 /* Since we can't estimate the cost of cloning a vehicle accurately we must
923 * check whether the company has enough money manually. */
924 if (!CheckCompanyHasMoney(total_cost
)) {
925 if (flags
& DC_EXEC
) {
926 /* The vehicle has already been bought, so now it must be sold again. */
927 DoCommand(w_front
->tile
, w_front
->index
| 1 << 20, 0, flags
, CMD_SELL_VEHICLE
);
936 * Send all vehicles of type to depots
937 * @param flags the flags used for DoCommand()
938 * @param service should the vehicles only get service in the depots
939 * @param vli identifier of the vehicle list
940 * @return 0 for success and CMD_ERROR if no vehicle is able to go to depot
942 static CommandCost
SendAllVehiclesToDepot(DoCommandFlag flags
, bool service
, const VehicleListIdentifier
&vli
)
946 if (!GenerateVehicleSortList(&list
, vli
)) return CMD_ERROR
;
948 /* Send all the vehicles to a depot */
949 bool had_success
= false;
950 for (uint i
= 0; i
< list
.Length(); i
++) {
951 const Vehicle
*v
= list
[i
];
952 CommandCost ret
= DoCommand(v
->tile
, v
->index
| (service
? DEPOT_SERVICE
: 0U) | DEPOT_DONT_CANCEL
, 0, flags
, CMD_SEND_VEHICLE_TO_DEPOT
);
954 if (ret
.Succeeded()) {
957 /* Return 0 if DC_EXEC is not set this is a valid goto depot command)
958 * In this case we know that at least one vehicle can be sent to a depot
959 * and we will issue the command. We can now safely quit the loop, knowing
960 * it will succeed at least once. With DC_EXEC we really need to send them to the depot */
961 if (!(flags
& DC_EXEC
)) break;
965 return had_success
? CommandCost() : CMD_ERROR
;
969 * Send a vehicle to the depot.
971 * @param flags for command type
973 * - p1 0-20: bitvehicle ID to send to the depot
974 * - p1 bits 25-8 - DEPOT_ flags (see vehicle_type.h)
975 * @param p2 packed VehicleListIdentifier.
977 * @return the cost of this operation or an error
979 CommandCost
CmdSendVehicleToDepot(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
981 if (p1
& DEPOT_MASS_SEND
) {
982 /* Mass goto depot requested */
983 VehicleListIdentifier vli
;
984 if (!vli
.Unpack(p2
)) return CMD_ERROR
;
985 return SendAllVehiclesToDepot(flags
, (p1
& DEPOT_SERVICE
) != 0, vli
);
988 Vehicle
*v
= Vehicle::GetIfValid(GB(p1
, 0, 20));
989 if (v
== NULL
) return CMD_ERROR
;
990 if (!v
->IsPrimaryVehicle()) return CMD_ERROR
;
992 return v
->SendToDepot(flags
, (DepotCommand
)(p1
& DEPOT_COMMAND_MASK
));
996 * Give a custom name to your vehicle
998 * @param flags type of operation
999 * @param p1 vehicle ID to name
1001 * @param text the new name or an empty string when resetting to the default
1002 * @return the cost of this operation or an error
1004 CommandCost
CmdRenameVehicle(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1006 Vehicle
*v
= Vehicle::GetIfValid(p1
);
1007 if (v
== NULL
|| !v
->IsPrimaryVehicle()) return CMD_ERROR
;
1009 CommandCost ret
= CheckOwnership(v
->owner
);
1010 if (ret
.Failed()) return ret
;
1012 bool reset
= StrEmpty(text
);
1015 if (Utf8StringLength(text
) >= MAX_LENGTH_VEHICLE_NAME_CHARS
) return CMD_ERROR
;
1016 if (!(flags
& DC_AUTOREPLACE
) && !IsUniqueVehicleName(text
)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE
);
1019 if (flags
& DC_EXEC
) {
1021 v
->name
= reset
? NULL
: xstrdup(text
);
1022 InvalidateWindowClassesData(GetWindowClassForVehicleType(v
->type
), 1);
1023 MarkWholeScreenDirty();
1026 return CommandCost();
1031 * Change the service interval of a vehicle
1032 * @param tile unused
1033 * @param flags type of operation
1034 * @param p1 vehicle ID that is being service-interval-changed
1036 * - p2 = (bit 0-15) - new service interval
1037 * - p2 = (bit 16) - service interval is custom flag
1038 * - p2 = (bit 17) - service interval is percentage flag
1039 * @param text unused
1040 * @return the cost of this operation or an error
1042 CommandCost
CmdChangeServiceInt(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1044 Vehicle
*v
= Vehicle::GetIfValid(p1
);
1045 if (v
== NULL
|| !v
->IsPrimaryVehicle()) return CMD_ERROR
;
1047 CommandCost ret
= CheckOwnership(v
->owner
);
1048 if (ret
.Failed()) return ret
;
1050 const Company
*company
= Company::Get(v
->owner
);
1051 bool iscustom
= HasBit(p2
, 16);
1052 bool ispercent
= iscustom
? HasBit(p2
, 17) : company
->settings
.vehicle
.servint_ispercent
;
1056 serv_int
= GB(p2
, 0, 16);
1057 if (serv_int
!= GetServiceIntervalClamped(serv_int
, ispercent
)) return CMD_ERROR
;
1059 serv_int
= CompanyServiceInterval(company
, v
->type
);
1062 if (flags
& DC_EXEC
) {
1063 v
->SetServiceInterval(serv_int
);
1064 v
->SetServiceIntervalIsCustom(iscustom
);
1065 v
->SetServiceIntervalIsPercent(ispercent
);
1066 SetWindowDirty(WC_VEHICLE_DETAILS
, v
->index
);
1069 return CommandCost();