Fix: Don't allow right-click to close world generation progress window. (#13084)
[openttd-github.git] / src / vehicle_cmd.cpp
blobc44fa6a528b3f65429801a49d8295b51c596b9b1
1 /*
2 * This file is part of OpenTTD.
3 * 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.
4 * 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.
5 * 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/>.
6 */
8 /** @file vehicle_cmd.cpp Commands for vehicles. */
10 #include "stdafx.h"
11 #include "roadveh.h"
12 #include "news_func.h"
13 #include "airport.h"
14 #include "command_func.h"
15 #include "company_func.h"
16 #include "train.h"
17 #include "aircraft.h"
18 #include "newgrf_text.h"
19 #include "vehicle_func.h"
20 #include "string_func.h"
21 #include "depot_map.h"
22 #include "vehiclelist.h"
23 #include "engine_func.h"
24 #include "articulated_vehicles.h"
25 #include "autoreplace_gui.h"
26 #include "group.h"
27 #include "order_backup.h"
28 #include "ship.h"
29 #include "newgrf.h"
30 #include "company_base.h"
31 #include "core/random_func.hpp"
32 #include "vehicle_cmd.h"
33 #include "aircraft_cmd.h"
34 #include "autoreplace_cmd.h"
35 #include "group_cmd.h"
36 #include "order_cmd.h"
37 #include "roadveh_cmd.h"
38 #include "train_cmd.h"
39 #include "ship_cmd.h"
40 #include <sstream>
41 #include <iomanip>
43 #include "table/strings.h"
45 #include "safeguards.h"
47 /* Tables used in vehicle_func.h to find the right error message for a certain vehicle type */
48 const StringID _veh_build_msg_table[] = {
49 STR_ERROR_CAN_T_BUY_TRAIN,
50 STR_ERROR_CAN_T_BUY_ROAD_VEHICLE,
51 STR_ERROR_CAN_T_BUY_SHIP,
52 STR_ERROR_CAN_T_BUY_AIRCRAFT,
55 const StringID _veh_sell_msg_table[] = {
56 STR_ERROR_CAN_T_SELL_TRAIN,
57 STR_ERROR_CAN_T_SELL_ROAD_VEHICLE,
58 STR_ERROR_CAN_T_SELL_SHIP,
59 STR_ERROR_CAN_T_SELL_AIRCRAFT,
62 const StringID _veh_refit_msg_table[] = {
63 STR_ERROR_CAN_T_REFIT_TRAIN,
64 STR_ERROR_CAN_T_REFIT_ROAD_VEHICLE,
65 STR_ERROR_CAN_T_REFIT_SHIP,
66 STR_ERROR_CAN_T_REFIT_AIRCRAFT,
69 const StringID _send_to_depot_msg_table[] = {
70 STR_ERROR_CAN_T_SEND_TRAIN_TO_DEPOT,
71 STR_ERROR_CAN_T_SEND_ROAD_VEHICLE_TO_DEPOT,
72 STR_ERROR_CAN_T_SEND_SHIP_TO_DEPOT,
73 STR_ERROR_CAN_T_SEND_AIRCRAFT_TO_HANGAR,
77 /**
78 * Build a vehicle.
79 * @param flags for command
80 * @param tile tile of depot where the vehicle is built
81 * @param eid vehicle type being built.
82 * @param use_free_vehicles use free vehicles when building the vehicle.
83 * @param cargo refit cargo type.
84 * @param client_id User
85 * @return the cost of this operation + the new vehicle ID + the refitted capacity + the refitted mail capacity (aircraft) or an error
87 std::tuple<CommandCost, VehicleID, uint, uint16_t, CargoArray> CmdBuildVehicle(DoCommandFlag flags, TileIndex tile, EngineID eid, bool use_free_vehicles, CargoID cargo, ClientID client_id)
89 /* Elementary check for valid location. */
90 if (!IsDepotTile(tile) || !IsTileOwner(tile, _current_company)) return { CMD_ERROR, INVALID_VEHICLE, 0, 0, {} };
92 VehicleType type = GetDepotVehicleType(tile);
94 /* Validate the engine type. */
95 if (!IsEngineBuildable(eid, type, _current_company)) return { CommandCost(STR_ERROR_RAIL_VEHICLE_NOT_AVAILABLE + type), INVALID_VEHICLE, 0, 0, {} };
97 /* Validate the cargo type. */
98 if (cargo >= NUM_CARGO && IsValidCargoID(cargo)) return { CMD_ERROR, INVALID_VEHICLE, 0, 0, {} };
100 const Engine *e = Engine::Get(eid);
101 CommandCost value(EXPENSES_NEW_VEHICLES, e->GetCost());
103 /* Engines without valid cargo should not be available */
104 CargoID default_cargo = e->GetDefaultCargoType();
105 if (!IsValidCargoID(default_cargo)) return { CMD_ERROR, INVALID_VEHICLE, 0, 0, {} };
107 bool refitting = IsValidCargoID(cargo) && cargo != default_cargo;
109 /* Check whether the number of vehicles we need to build can be built according to pool space. */
110 uint num_vehicles;
111 switch (type) {
112 case VEH_TRAIN: num_vehicles = (e->u.rail.railveh_type == RAILVEH_MULTIHEAD ? 2 : 1) + CountArticulatedParts(eid, false); break;
113 case VEH_ROAD: num_vehicles = 1 + CountArticulatedParts(eid, false); break;
114 case VEH_SHIP: num_vehicles = 1; break;
115 case VEH_AIRCRAFT: num_vehicles = e->u.air.subtype & AIR_CTOL ? 2 : 3; break;
116 default: NOT_REACHED(); // Safe due to IsDepotTile()
118 if (!Vehicle::CanAllocateItem(num_vehicles)) return { CommandCost(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME), INVALID_VEHICLE, 0, 0, {} };
120 /* Check whether we can allocate a unit number. Autoreplace does not allocate
121 * an unit number as it will (always) reuse the one of the replaced vehicle
122 * and (train) wagons don't have an unit number in any scenario. */
123 UnitID unit_num = (flags & DC_QUERY_COST || flags & DC_AUTOREPLACE || (type == VEH_TRAIN && e->u.rail.railveh_type == RAILVEH_WAGON)) ? 0 : GetFreeUnitNumber(type);
124 if (unit_num == UINT16_MAX) return { CommandCost(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME), INVALID_VEHICLE, 0, 0, {} };
126 /* If we are refitting we need to temporarily purchase the vehicle to be able to
127 * test it. */
128 DoCommandFlag subflags = flags;
129 if (refitting && !(flags & DC_EXEC)) subflags |= DC_EXEC | DC_AUTOREPLACE;
131 /* Vehicle construction needs random bits, so we have to save the random
132 * seeds to prevent desyncs. */
133 SavedRandomSeeds saved_seeds;
134 SaveRandomSeeds(&saved_seeds);
136 Vehicle *v = nullptr;
137 switch (type) {
138 case VEH_TRAIN: value.AddCost(CmdBuildRailVehicle(subflags, tile, e, &v)); break;
139 case VEH_ROAD: value.AddCost(CmdBuildRoadVehicle(subflags, tile, e, &v)); break;
140 case VEH_SHIP: value.AddCost(CmdBuildShip (subflags, tile, e, &v)); break;
141 case VEH_AIRCRAFT: value.AddCost(CmdBuildAircraft (subflags, tile, e, &v)); break;
142 default: NOT_REACHED(); // Safe due to IsDepotTile()
145 VehicleID veh_id = INVALID_VEHICLE;
146 uint refitted_capacity = 0;
147 uint16_t refitted_mail_capacity = 0;
148 CargoArray cargo_capacities{};
149 if (value.Succeeded()) {
150 if (subflags & DC_EXEC) {
151 v->unitnumber = unit_num;
152 v->value = value.GetCost();
153 veh_id = v->index;
156 if (refitting) {
157 /* Refit only one vehicle. If we purchased an engine, it may have gained free wagons. */
158 CommandCost cc;
159 std::tie(cc, refitted_capacity, refitted_mail_capacity, cargo_capacities) = CmdRefitVehicle(flags, v->index, cargo, 0, false, false, 1);
160 value.AddCost(cc);
161 } else {
162 /* Fill in non-refitted capacities */
163 if (e->type == VEH_TRAIN || e->type == VEH_ROAD) {
164 cargo_capacities = GetCapacityOfArticulatedParts(eid);
165 refitted_capacity = cargo_capacities[default_cargo];
166 refitted_mail_capacity = 0;
167 } else {
168 refitted_capacity = e->GetDisplayDefaultCapacity(&refitted_mail_capacity);
169 cargo_capacities[default_cargo] = refitted_capacity;
170 CargoID mail = GetCargoIDByLabel(CT_MAIL);
171 if (IsValidCargoID(mail)) cargo_capacities[mail] = refitted_mail_capacity;
175 if (flags & DC_EXEC) {
176 if (type == VEH_TRAIN && use_free_vehicles && !(flags & DC_AUTOREPLACE) && Train::From(v)->IsEngine()) {
177 /* Move any free wagons to the new vehicle. */
178 NormalizeTrainVehInDepot(Train::From(v));
181 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
182 InvalidateWindowClassesData(GetWindowClassForVehicleType(type), 0);
183 SetWindowDirty(WC_COMPANY, _current_company);
184 if (IsLocalCompany()) {
185 InvalidateAutoreplaceWindow(v->engine_type, v->group_id); // updates the auto replace window (must be called before incrementing num_engines)
189 if (subflags & DC_EXEC) {
190 GroupStatistics::CountEngine(v, 1);
191 GroupStatistics::UpdateAutoreplace(_current_company);
193 if (v->IsPrimaryVehicle()) {
194 GroupStatistics::CountVehicle(v, 1);
195 if (!(subflags & DC_AUTOREPLACE)) OrderBackup::Restore(v, client_id);
198 Company::Get(v->owner)->freeunits[v->type].UseID(v->unitnumber);
202 /* If we are not in DC_EXEC undo everything */
203 if (flags != subflags) {
204 Command<CMD_SELL_VEHICLE>::Do(DC_EXEC, v->index, false, false, INVALID_CLIENT_ID);
208 /* Only restore if we actually did some refitting */
209 if (flags != subflags) RestoreRandomSeeds(saved_seeds);
211 return { value, veh_id, refitted_capacity, refitted_mail_capacity, cargo_capacities };
215 * Sell a vehicle.
216 * @param flags for command.
217 * @param v_id vehicle ID being sold.
218 * @param sell_chain sell the vehicle and all vehicles following it in the chain.
219 * @param backup_order make a backup of the vehicle's order (if an engine).
220 * @param client_id User.
221 * @return the cost of this operation or an error.
223 CommandCost CmdSellVehicle(DoCommandFlag flags, VehicleID v_id, bool sell_chain, bool backup_order, ClientID client_id)
225 Vehicle *v = Vehicle::GetIfValid(v_id);
226 if (v == nullptr) return CMD_ERROR;
228 Vehicle *front = v->First();
230 CommandCost ret = CheckOwnership(front->owner);
231 if (ret.Failed()) return ret;
233 if (front->vehstatus & VS_CRASHED) return_cmd_error(STR_ERROR_VEHICLE_IS_DESTROYED);
235 if (!front->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAIN_MUST_BE_STOPPED_INSIDE_DEPOT + front->type);
237 /* Can we actually make the order backup, i.e. are there enough orders? */
238 if (backup_order &&
239 front->orders != nullptr &&
240 !front->orders->IsShared() &&
241 !Order::CanAllocateItem(front->orders->GetNumOrders())) {
242 /* Only happens in exceptional cases when there aren't enough orders anyhow.
243 * Thus it should be safe to just drop the orders in that case. */
244 backup_order = false;
247 if (v->type == VEH_TRAIN) {
248 ret = CmdSellRailWagon(flags, v, sell_chain, backup_order, client_id);
249 } else {
250 ret = CommandCost(EXPENSES_NEW_VEHICLES, -front->value);
252 if (flags & DC_EXEC) {
253 if (front->IsPrimaryVehicle() && backup_order) OrderBackup::Backup(front, client_id);
254 delete front;
258 return ret;
262 * Helper to run the refit cost callback.
263 * @param v The vehicle we are refitting, can be nullptr.
264 * @param engine_type Which engine to refit
265 * @param new_cid Cargo type we are refitting to.
266 * @param new_subtype New cargo subtype.
267 * @param[out] auto_refit_allowed The refit is allowed as an auto-refit.
268 * @return Price for refitting
270 static int GetRefitCostFactor(const Vehicle *v, EngineID engine_type, CargoID new_cid, uint8_t new_subtype, bool *auto_refit_allowed)
272 /* Prepare callback param with info about the new cargo type. */
273 const Engine *e = Engine::Get(engine_type);
275 /* Is this vehicle a NewGRF vehicle? */
276 if (e->GetGRF() != nullptr) {
277 const CargoSpec *cs = CargoSpec::Get(new_cid);
278 uint32_t param1 = (cs->classes << 16) | (new_subtype << 8) | e->GetGRF()->cargo_map[new_cid];
280 uint16_t cb_res = GetVehicleCallback(CBID_VEHICLE_REFIT_COST, param1, 0, engine_type, v);
281 if (cb_res != CALLBACK_FAILED) {
282 *auto_refit_allowed = HasBit(cb_res, 14);
283 int factor = GB(cb_res, 0, 14);
284 if (factor >= 0x2000) factor -= 0x4000; // Treat as signed integer.
285 return factor;
289 *auto_refit_allowed = e->info.refit_cost == 0;
290 return (v == nullptr || v->cargo_type != new_cid) ? e->info.refit_cost : 0;
294 * Learn the price of refitting a certain engine
295 * @param v The vehicle we are refitting, can be nullptr.
296 * @param engine_type Which engine to refit
297 * @param new_cid Cargo type we are refitting to.
298 * @param new_subtype New cargo subtype.
299 * @param[out] auto_refit_allowed The refit is allowed as an auto-refit.
300 * @return Price for refitting
302 static CommandCost GetRefitCost(const Vehicle *v, EngineID engine_type, CargoID new_cid, uint8_t new_subtype, bool *auto_refit_allowed)
304 ExpensesType expense_type;
305 const Engine *e = Engine::Get(engine_type);
306 Price base_price;
307 int cost_factor = GetRefitCostFactor(v, engine_type, new_cid, new_subtype, auto_refit_allowed);
308 switch (e->type) {
309 case VEH_SHIP:
310 base_price = PR_BUILD_VEHICLE_SHIP;
311 expense_type = EXPENSES_SHIP_RUN;
312 break;
314 case VEH_ROAD:
315 base_price = PR_BUILD_VEHICLE_ROAD;
316 expense_type = EXPENSES_ROADVEH_RUN;
317 break;
319 case VEH_AIRCRAFT:
320 base_price = PR_BUILD_VEHICLE_AIRCRAFT;
321 expense_type = EXPENSES_AIRCRAFT_RUN;
322 break;
324 case VEH_TRAIN:
325 base_price = (e->u.rail.railveh_type == RAILVEH_WAGON) ? PR_BUILD_VEHICLE_WAGON : PR_BUILD_VEHICLE_TRAIN;
326 cost_factor <<= 1;
327 expense_type = EXPENSES_TRAIN_RUN;
328 break;
330 default: NOT_REACHED();
332 if (cost_factor < 0) {
333 return CommandCost(expense_type, -GetPrice(base_price, -cost_factor, e->GetGRF(), -10));
334 } else {
335 return CommandCost(expense_type, GetPrice(base_price, cost_factor, e->GetGRF(), -10));
339 /** Helper structure for RefitVehicle() */
340 struct RefitResult {
341 Vehicle *v; ///< Vehicle to refit
342 uint capacity; ///< New capacity of vehicle
343 uint mail_capacity; ///< New mail capacity of aircraft
344 uint8_t subtype; ///< cargo subtype to refit to
348 * Refits a vehicle (chain).
349 * This is the vehicle-type independent part of the CmdRefitXXX functions.
350 * @param v The vehicle to refit.
351 * @param only_this Whether to only refit this vehicle, or to check the rest of them.
352 * @param num_vehicles Number of vehicles to refit (not counting articulated parts). Zero means the whole chain.
353 * @param new_cid Cargotype to refit to
354 * @param new_subtype Cargo subtype to refit to. 0xFF means to try keeping the same subtype according to GetBestFittingSubType().
355 * @param flags Command flags
356 * @param auto_refit Refitting is done as automatic refitting outside a depot.
357 * @return Refit cost + refittet capacity + mail capacity (aircraft).
359 static std::tuple<CommandCost, uint, uint16_t, CargoArray> RefitVehicle(Vehicle *v, bool only_this, uint8_t num_vehicles, CargoID new_cid, uint8_t new_subtype, DoCommandFlag flags, bool auto_refit)
361 CommandCost cost(v->GetExpenseType(false));
362 uint total_capacity = 0;
363 uint total_mail_capacity = 0;
364 num_vehicles = num_vehicles == 0 ? UINT8_MAX : num_vehicles;
365 CargoArray cargo_capacities{};
367 VehicleSet vehicles_to_refit;
368 if (!only_this) {
369 GetVehicleSet(vehicles_to_refit, v, num_vehicles);
370 /* In this case, we need to check the whole chain. */
371 v = v->First();
374 std::vector<RefitResult> refit_result;
376 v->InvalidateNewGRFCacheOfChain();
377 uint8_t actual_subtype = new_subtype;
378 for (; v != nullptr; v = (only_this ? nullptr : v->Next())) {
379 /* Reset actual_subtype for every new vehicle */
380 if (!v->IsArticulatedPart()) actual_subtype = new_subtype;
382 if (v->type == VEH_TRAIN && std::find(vehicles_to_refit.begin(), vehicles_to_refit.end(), v->index) == vehicles_to_refit.end() && !only_this) continue;
384 const Engine *e = v->GetEngine();
385 if (!e->CanCarryCargo()) continue;
387 /* If the vehicle is not refittable, or does not allow automatic refitting,
388 * count its capacity nevertheless if the cargo matches */
389 bool refittable = HasBit(e->info.refit_mask, new_cid) && (!auto_refit || HasBit(e->info.misc_flags, EF_AUTO_REFIT));
390 if (!refittable && v->cargo_type != new_cid) {
391 uint amount = e->DetermineCapacity(v, nullptr);
392 if (amount > 0) cargo_capacities[v->cargo_type] += amount;
393 continue;
396 /* Determine best fitting subtype if requested */
397 if (actual_subtype == 0xFF) {
398 actual_subtype = GetBestFittingSubType(v, v, new_cid);
401 /* Back up the vehicle's cargo type */
402 CargoID temp_cid = v->cargo_type;
403 uint8_t temp_subtype = v->cargo_subtype;
404 if (refittable) {
405 v->cargo_type = new_cid;
406 v->cargo_subtype = actual_subtype;
409 uint16_t mail_capacity = 0;
410 uint amount = e->DetermineCapacity(v, &mail_capacity);
411 total_capacity += amount;
412 /* mail_capacity will always be zero if the vehicle is not an aircraft. */
413 total_mail_capacity += mail_capacity;
415 cargo_capacities[new_cid] += amount;
416 CargoID mail = GetCargoIDByLabel(CT_MAIL);
417 if (IsValidCargoID(mail)) cargo_capacities[mail] += mail_capacity;
419 if (!refittable) continue;
421 /* Restore the original cargo type */
422 v->cargo_type = temp_cid;
423 v->cargo_subtype = temp_subtype;
425 bool auto_refit_allowed;
426 CommandCost refit_cost = GetRefitCost(v, v->engine_type, new_cid, actual_subtype, &auto_refit_allowed);
427 if (auto_refit && (flags & DC_QUERY_COST) == 0 && !auto_refit_allowed) {
428 /* Sorry, auto-refitting not allowed, subtract the cargo amount again from the total.
429 * When querrying cost/capacity (for example in order refit GUI), we always assume 'allowed'.
430 * It is not predictable. */
431 total_capacity -= amount;
432 total_mail_capacity -= mail_capacity;
434 if (v->cargo_type == new_cid) {
435 /* Add the old capacity nevertheless, if the cargo matches */
436 total_capacity += v->cargo_cap;
437 if (v->type == VEH_AIRCRAFT) total_mail_capacity += v->Next()->cargo_cap;
439 continue;
441 cost.AddCost(refit_cost);
443 /* Record the refitting.
444 * Do not execute the refitting immediately, so DetermineCapacity and GetRefitCost do the same in test and exec run.
445 * (weird NewGRFs)
446 * Note:
447 * - If the capacity of vehicles depends on other vehicles in the chain, the actual capacity is
448 * set after RefitVehicle() via ConsistChanged() and friends. The estimation via _returned_refit_capacity will be wrong.
449 * - We have to call the refit cost callback with the pre-refit configuration of the chain because we want refit and
450 * autorefit to behave the same, and we need its result for auto_refit_allowed.
452 refit_result.push_back({v, amount, mail_capacity, actual_subtype});
455 if (flags & DC_EXEC) {
456 /* Store the result */
457 for (RefitResult &result : refit_result) {
458 Vehicle *u = result.v;
459 u->refit_cap = (u->cargo_type == new_cid) ? std::min<uint16_t>(result.capacity, u->refit_cap) : 0;
460 if (u->cargo.TotalCount() > u->refit_cap) u->cargo.Truncate(u->cargo.TotalCount() - u->refit_cap);
461 u->cargo_type = new_cid;
462 u->cargo_cap = result.capacity;
463 u->cargo_subtype = result.subtype;
464 if (u->type == VEH_AIRCRAFT) {
465 Vehicle *w = u->Next();
466 assert(w != nullptr);
467 w->refit_cap = std::min<uint16_t>(w->refit_cap, result.mail_capacity);
468 w->cargo_cap = result.mail_capacity;
469 if (w->cargo.TotalCount() > w->refit_cap) w->cargo.Truncate(w->cargo.TotalCount() - w->refit_cap);
474 refit_result.clear();
475 return { cost, total_capacity, total_mail_capacity, cargo_capacities };
479 * Refits a vehicle to the specified cargo type.
480 * @param flags type of operation
481 * @param veh_id vehicle ID to refit
482 * @param new_cid New cargo type to refit to.
483 * @param new_subtype New cargo subtype to refit to. 0xFF means to try keeping the same subtype according to GetBestFittingSubType().
484 * @param auto_refit Automatic refitting.
485 * @param only_this Refit only this vehicle. Used only for cloning vehicles.
486 * @param num_vehicles Number of vehicles to refit (not counting articulated parts). Zero means all vehicles.
487 * Only used if "refit only this vehicle" is false.
488 * @return the cost of this operation or an error
490 std::tuple<CommandCost, uint, uint16_t, CargoArray> CmdRefitVehicle(DoCommandFlag flags, VehicleID veh_id, CargoID new_cid, uint8_t new_subtype, bool auto_refit, bool only_this, uint8_t num_vehicles)
492 Vehicle *v = Vehicle::GetIfValid(veh_id);
493 if (v == nullptr) return { CMD_ERROR, 0, 0, {} };
495 /* Don't allow disasters and sparks and such to be refitted.
496 * We cannot check for IsPrimaryVehicle as autoreplace also refits in free wagon chains. */
497 if (!IsCompanyBuildableVehicleType(v->type)) return { CMD_ERROR, 0, 0, {} };
499 Vehicle *front = v->First();
501 CommandCost ret = CheckOwnership(front->owner);
502 if (ret.Failed()) return { ret, 0, 0, {} };
504 bool free_wagon = v->type == VEH_TRAIN && Train::From(front)->IsFreeWagon(); // used by autoreplace/renew
506 /* Don't allow shadows and such to be refitted. */
507 if (v != front && (v->type == VEH_SHIP || v->type == VEH_AIRCRAFT)) return { CMD_ERROR, 0, 0, {} };
509 /* Allow auto-refitting only during loading and normal refitting only in a depot. */
510 if ((flags & DC_QUERY_COST) == 0 && // used by the refit GUI, including the order refit GUI.
511 !free_wagon && // used by autoreplace/renew
512 (!auto_refit || !front->current_order.IsType(OT_LOADING)) && // refit inside stations
513 !front->IsStoppedInDepot()) { // refit inside depots
514 return { CommandCost(STR_ERROR_TRAIN_MUST_BE_STOPPED_INSIDE_DEPOT + front->type), 0, 0, {} };
517 if (front->vehstatus & VS_CRASHED) return { CommandCost(STR_ERROR_VEHICLE_IS_DESTROYED), 0, 0, {} };
519 /* Check cargo */
520 if (new_cid >= NUM_CARGO) return { CMD_ERROR, 0, 0, {} };
522 /* For ships and aircraft there is always only one. */
523 only_this |= front->type == VEH_SHIP || front->type == VEH_AIRCRAFT;
525 auto [cost, refit_capacity, mail_capacity, cargo_capacities] = RefitVehicle(v, only_this, num_vehicles, new_cid, new_subtype, flags, auto_refit);
527 if (flags & DC_EXEC) {
528 /* Update the cached variables */
529 switch (v->type) {
530 case VEH_TRAIN:
531 Train::From(front)->ConsistChanged(auto_refit ? CCF_AUTOREFIT : CCF_REFIT);
532 break;
533 case VEH_ROAD:
534 RoadVehUpdateCache(RoadVehicle::From(front), auto_refit);
535 if (_settings_game.vehicle.roadveh_acceleration_model != AM_ORIGINAL) RoadVehicle::From(front)->CargoChanged();
536 break;
538 case VEH_SHIP:
539 v->InvalidateNewGRFCacheOfChain();
540 Ship::From(v)->UpdateCache();
541 break;
543 case VEH_AIRCRAFT:
544 v->InvalidateNewGRFCacheOfChain();
545 UpdateAircraftCache(Aircraft::From(v), true);
546 break;
548 default: NOT_REACHED();
550 front->MarkDirty();
552 if (!free_wagon) {
553 InvalidateWindowData(WC_VEHICLE_DETAILS, front->index);
554 InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
556 SetWindowDirty(WC_VEHICLE_DEPOT, front->tile);
557 } else {
558 /* Always invalidate the cache; querycost might have filled it. */
559 v->InvalidateNewGRFCacheOfChain();
562 return { cost, refit_capacity, mail_capacity, cargo_capacities };
566 * Start/Stop a vehicle
567 * @param flags type of operation
568 * @param veh_id vehicle to start/stop, don't forget to change CcStartStopVehicle if you modify this!
569 * @param evaluate_startstop_cb Shall the start/stop newgrf callback be evaluated (only valid with DC_AUTOREPLACE for network safety)
570 * @return the cost of this operation or an error
572 CommandCost CmdStartStopVehicle(DoCommandFlag flags, VehicleID veh_id, bool evaluate_startstop_cb)
574 /* Disable the effect of p2 bit 0, when DC_AUTOREPLACE is not set */
575 if ((flags & DC_AUTOREPLACE) == 0) evaluate_startstop_cb = true;
577 Vehicle *v = Vehicle::GetIfValid(veh_id);
578 if (v == nullptr || !v->IsPrimaryVehicle()) return CMD_ERROR;
580 CommandCost ret = CheckOwnership(v->owner);
581 if (ret.Failed()) return ret;
583 if (v->vehstatus & VS_CRASHED) return_cmd_error(STR_ERROR_VEHICLE_IS_DESTROYED);
585 switch (v->type) {
586 case VEH_TRAIN:
587 if ((v->vehstatus & VS_STOPPED) && Train::From(v)->gcache.cached_power == 0) return_cmd_error(STR_ERROR_TRAIN_START_NO_POWER);
588 break;
590 case VEH_SHIP:
591 case VEH_ROAD:
592 break;
594 case VEH_AIRCRAFT: {
595 Aircraft *a = Aircraft::From(v);
596 /* cannot stop airplane when in flight, or when taking off / landing */
597 if (a->state >= STARTTAKEOFF && a->state < TERM7) return_cmd_error(STR_ERROR_AIRCRAFT_IS_IN_FLIGHT);
598 if (HasBit(a->flags, VAF_HELI_DIRECT_DESCENT)) return_cmd_error(STR_ERROR_AIRCRAFT_IS_IN_FLIGHT);
599 break;
602 default: return CMD_ERROR;
605 if (evaluate_startstop_cb) {
606 /* Check if this vehicle can be started/stopped. Failure means 'allow'. */
607 uint16_t callback = GetVehicleCallback(CBID_VEHICLE_START_STOP_CHECK, 0, 0, v->engine_type, v);
608 StringID error = STR_NULL;
609 if (callback != CALLBACK_FAILED) {
610 if (v->GetGRF()->grf_version < 8) {
611 /* 8 bit result 0xFF means 'allow' */
612 if (callback < 0x400 && GB(callback, 0, 8) != 0xFF) error = GetGRFStringID(v->GetGRFID(), 0xD000 + callback);
613 } else {
614 if (callback < 0x400) {
615 error = GetGRFStringID(v->GetGRFID(), 0xD000 + callback);
616 } else {
617 switch (callback) {
618 case 0x400: // allow
619 break;
621 default: // unknown reason -> disallow
622 error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
623 break;
628 if (error != STR_NULL) return_cmd_error(error);
631 if (flags & DC_EXEC) {
632 if (v->IsStoppedInDepot() && (flags & DC_AUTOREPLACE) == 0) DeleteVehicleNews(veh_id, STR_NEWS_TRAIN_IS_WAITING + v->type);
634 v->vehstatus ^= VS_STOPPED;
635 if (v->type != VEH_TRAIN) v->cur_speed = 0; // trains can stop 'slowly'
637 /* Unbunching data is no longer valid. */
638 v->ResetDepotUnbunching();
640 v->MarkDirty();
641 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
642 SetWindowDirty(WC_VEHICLE_DEPOT, v->tile);
643 SetWindowClassesDirty(GetWindowClassForVehicleType(v->type));
644 InvalidateWindowData(WC_VEHICLE_VIEW, v->index);
646 return CommandCost();
650 * Starts or stops a lot of vehicles
651 * @param flags type of operation
652 * @param tile Tile of the depot where the vehicles are started/stopped (only used for depots)
653 * @param do_start set = start vehicles, unset = stop vehicles
654 * @param vehicle_list_window if set, then it's a vehicle list window, not a depot and Tile is ignored in this case
655 * @param vli VehicleListIdentifier
656 * @return the cost of this operation or an error
658 CommandCost CmdMassStartStopVehicle(DoCommandFlag flags, TileIndex tile, bool do_start, bool vehicle_list_window, const VehicleListIdentifier &vli)
660 VehicleList list;
662 if (!vli.Valid()) return CMD_ERROR;
663 if (!IsCompanyBuildableVehicleType(vli.vtype)) return CMD_ERROR;
665 if (vehicle_list_window) {
666 if (!GenerateVehicleSortList(&list, vli)) return CMD_ERROR;
667 } else {
668 if (!IsDepotTile(tile) || !IsTileOwner(tile, _current_company)) return CMD_ERROR;
669 /* Get the list of vehicles in the depot */
670 BuildDepotVehicleList(vli.vtype, tile, &list, nullptr);
673 for (const Vehicle *v : list) {
674 if (!!(v->vehstatus & VS_STOPPED) != do_start) continue;
676 if (!vehicle_list_window && !v->IsChainInDepot()) continue;
678 /* Just try and don't care if some vehicle's can't be stopped. */
679 Command<CMD_START_STOP_VEHICLE>::Do(flags, v->index, false);
682 return CommandCost();
686 * Sells all vehicles in a depot
687 * @param flags type of operation
688 * @param tile Tile of the depot where the depot is
689 * @param vehicle_type Vehicle type
690 * @return the cost of this operation or an error
692 CommandCost CmdDepotSellAllVehicles(DoCommandFlag flags, TileIndex tile, VehicleType vehicle_type)
694 VehicleList list;
696 CommandCost cost(EXPENSES_NEW_VEHICLES);
698 if (!IsCompanyBuildableVehicleType(vehicle_type)) return CMD_ERROR;
699 if (!IsDepotTile(tile) || !IsTileOwner(tile, _current_company)) return CMD_ERROR;
701 /* Get the list of vehicles in the depot */
702 BuildDepotVehicleList(vehicle_type, tile, &list, &list);
704 CommandCost last_error = CMD_ERROR;
705 bool had_success = false;
706 for (const Vehicle *v : list) {
707 CommandCost ret = Command<CMD_SELL_VEHICLE>::Do(flags, v->index, true, false, INVALID_CLIENT_ID);
708 if (ret.Succeeded()) {
709 cost.AddCost(ret);
710 had_success = true;
711 } else {
712 last_error = ret;
716 return had_success ? cost : last_error;
720 * Autoreplace all vehicles in the depot
721 * @param flags type of operation
722 * @param tile Tile of the depot where the vehicles are
723 * @param vehicle_type Type of vehicle
724 * @return the cost of this operation or an error
726 CommandCost CmdDepotMassAutoReplace(DoCommandFlag flags, TileIndex tile, VehicleType vehicle_type)
728 VehicleList list;
729 CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES);
731 if (!IsCompanyBuildableVehicleType(vehicle_type)) return CMD_ERROR;
732 if (!IsDepotTile(tile) || !IsTileOwner(tile, _current_company)) return CMD_ERROR;
734 /* Get the list of vehicles in the depot */
735 BuildDepotVehicleList(vehicle_type, tile, &list, &list, true);
737 for (const Vehicle *v : list) {
738 /* Ensure that the vehicle completely in the depot */
739 if (!v->IsChainInDepot()) continue;
741 CommandCost ret = Command<CMD_AUTOREPLACE_VEHICLE>::Do(flags, v->index);
743 if (ret.Succeeded()) cost.AddCost(ret);
745 return cost;
749 * Test if a name is unique among vehicle names.
750 * @param name Name to test.
751 * @return True ifffffff the name is unique.
753 bool IsUniqueVehicleName(const std::string &name)
755 for (const Vehicle *v : Vehicle::Iterate()) {
756 if (!v->name.empty() && v->name == name) return false;
759 return true;
763 * Clone the custom name of a vehicle, adding or incrementing a number.
764 * @param src Source vehicle, with a custom name.
765 * @param dst Destination vehicle.
767 static void CloneVehicleName(const Vehicle *src, Vehicle *dst)
769 std::string buf;
771 /* Find the position of the first digit in the last group of digits. */
772 size_t number_position;
773 for (number_position = src->name.length(); number_position > 0; number_position--) {
774 /* The design of UTF-8 lets this work simply without having to check
775 * for UTF-8 sequences. */
776 if (src->name[number_position - 1] < '0' || src->name[number_position - 1] > '9') break;
779 /* Format buffer and determine starting number. */
780 long num;
781 uint8_t padding = 0;
782 if (number_position == src->name.length()) {
783 /* No digit at the end, so start at number 2. */
784 buf = src->name;
785 buf += " ";
786 number_position = buf.length();
787 num = 2;
788 } else {
789 /* Found digits, parse them and start at the next number. */
790 buf = src->name.substr(0, number_position);
792 auto num_str = src->name.substr(number_position);
793 padding = (uint8_t)num_str.length();
795 std::istringstream iss(num_str);
796 iss >> num;
797 num++;
800 /* Check if this name is already taken. */
801 for (int max_iterations = 1000; max_iterations > 0; max_iterations--, num++) {
802 std::ostringstream oss;
804 /* Attach the number to the temporary name. */
805 oss << buf << std::setw(padding) << std::setfill('0') << std::internal << num;
807 /* Check the name is unique. */
808 auto new_name = oss.str();
809 if (IsUniqueVehicleName(new_name)) {
810 dst->name = new_name;
811 break;
815 /* All done. If we didn't find a name, it'll just use its default. */
819 * Clone a vehicle. If it is a train, it will clone all the cars too
820 * @param flags type of operation
821 * @param tile tile of the depot where the cloned vehicle is build
822 * @param veh_id the original vehicle's index
823 * @param share_orders shared orders, else copied orders
824 * @return the cost of this operation + the new vehicle ID or an error
826 std::tuple<CommandCost, VehicleID> CmdCloneVehicle(DoCommandFlag flags, TileIndex tile, VehicleID veh_id, bool share_orders)
828 CommandCost total_cost(EXPENSES_NEW_VEHICLES);
830 Vehicle *v = Vehicle::GetIfValid(veh_id);
831 if (v == nullptr || !v->IsPrimaryVehicle()) return { CMD_ERROR, INVALID_VEHICLE };
832 Vehicle *v_front = v;
833 Vehicle *w = nullptr;
834 Vehicle *w_front = nullptr;
835 Vehicle *w_rear = nullptr;
838 * v_front is the front engine in the original vehicle
839 * v is the car/vehicle of the original vehicle that is currently being copied
840 * w_front is the front engine of the cloned vehicle
841 * w is the car/vehicle currently being cloned
842 * w_rear is the rear end of the cloned train. It's used to add more cars and is only used by trains
845 CommandCost ret = CheckOwnership(v->owner);
846 if (ret.Failed()) return { ret, INVALID_VEHICLE };
848 if (v->type == VEH_TRAIN && (!v->IsFrontEngine() || Train::From(v)->crash_anim_pos >= 4400)) return { CMD_ERROR, INVALID_VEHICLE };
850 /* check that we can allocate enough vehicles */
851 if (!(flags & DC_EXEC)) {
852 int veh_counter = 0;
853 do {
854 veh_counter++;
855 } while ((v = v->Next()) != nullptr);
857 if (!Vehicle::CanAllocateItem(veh_counter)) {
858 return { CommandCost(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME), INVALID_VEHICLE };
862 v = v_front;
864 VehicleID new_veh_id = INVALID_VEHICLE;
865 do {
866 if (v->type == VEH_TRAIN && Train::From(v)->IsRearDualheaded()) {
867 /* we build the rear ends of multiheaded trains with the front ones */
868 continue;
871 /* In case we're building a multi headed vehicle and the maximum number of
872 * vehicles is almost reached (e.g. max trains - 1) not all vehicles would
873 * be cloned. When the non-primary engines were build they were seen as
874 * 'new' vehicles whereas they would immediately be joined with a primary
875 * engine. This caused the vehicle to be not build as 'the limit' had been
876 * reached, resulting in partially build vehicles and such. */
877 DoCommandFlag build_flags = flags;
878 if ((flags & DC_EXEC) && !v->IsPrimaryVehicle()) build_flags |= DC_AUTOREPLACE;
880 CommandCost cost;
881 std::tie(cost, new_veh_id, std::ignore, std::ignore, std::ignore) = Command<CMD_BUILD_VEHICLE>::Do(build_flags, tile, v->engine_type, false, INVALID_CARGO, INVALID_CLIENT_ID);
883 if (cost.Failed()) {
884 /* Can't build a part, then sell the stuff we already made; clear up the mess */
885 if (w_front != nullptr) Command<CMD_SELL_VEHICLE>::Do(flags, w_front->index, true, false, INVALID_CLIENT_ID);
886 return { cost, INVALID_VEHICLE };
889 total_cost.AddCost(cost);
891 if (flags & DC_EXEC) {
892 w = Vehicle::Get(new_veh_id);
894 if (v->type == VEH_TRAIN && HasBit(Train::From(v)->flags, VRF_REVERSE_DIRECTION)) {
895 SetBit(Train::From(w)->flags, VRF_REVERSE_DIRECTION);
898 if (v->type == VEH_TRAIN && !v->IsFrontEngine()) {
899 /* this s a train car
900 * add this unit to the end of the train */
901 CommandCost result = Command<CMD_MOVE_RAIL_VEHICLE>::Do(flags, w->index, w_rear->index, true);
902 if (result.Failed()) {
903 /* The train can't be joined to make the same consist as the original.
904 * Sell what we already made (clean up) and return an error. */
905 Command<CMD_SELL_VEHICLE>::Do(flags, w_front->index, true, false, INVALID_CLIENT_ID);
906 Command<CMD_SELL_VEHICLE>::Do(flags, w->index, true, false, INVALID_CLIENT_ID);
907 return { result, INVALID_VEHICLE }; // return error and the message returned from CMD_MOVE_RAIL_VEHICLE
909 } else {
910 /* this is a front engine or not a train. */
911 w_front = w;
912 w->service_interval = v->service_interval;
913 w->SetServiceIntervalIsCustom(v->ServiceIntervalIsCustom());
914 w->SetServiceIntervalIsPercent(v->ServiceIntervalIsPercent());
916 w_rear = w; // trains needs to know the last car in the train, so they can add more in next loop
918 } while (v->type == VEH_TRAIN && (v = v->GetNextVehicle()) != nullptr);
920 if ((flags & DC_EXEC) && v_front->type == VEH_TRAIN) {
921 /* for trains this needs to be the front engine due to the callback function */
922 new_veh_id = w_front->index;
925 if (flags & DC_EXEC) {
926 /* Cloned vehicles belong to the same group */
927 Command<CMD_ADD_VEHICLE_GROUP>::Do(flags, v_front->group_id, w_front->index, false, VehicleListIdentifier{});
931 /* Take care of refitting. */
932 w = w_front;
933 v = v_front;
935 /* Both building and refitting are influenced by newgrf callbacks, which
936 * makes it impossible to accurately estimate the cloning costs. In
937 * particular, it is possible for engines of the same type to be built with
938 * different numbers of articulated parts, so when refitting we have to
939 * loop over real vehicles first, and then the articulated parts of those
940 * vehicles in a different loop. */
941 do {
942 do {
943 if (flags & DC_EXEC) {
944 assert(w != nullptr);
946 /* Find out what's the best sub type */
947 uint8_t subtype = GetBestFittingSubType(v, w, v->cargo_type);
948 if (w->cargo_type != v->cargo_type || w->cargo_subtype != subtype) {
949 CommandCost cost = std::get<0>(Command<CMD_REFIT_VEHICLE>::Do(flags, w->index, v->cargo_type, subtype, false, true, 0));
950 if (cost.Succeeded()) total_cost.AddCost(cost);
953 if (w->IsGroundVehicle() && w->HasArticulatedPart()) {
954 w = w->GetNextArticulatedPart();
955 } else {
956 break;
958 } else {
959 const Engine *e = v->GetEngine();
960 CargoID initial_cargo = (e->CanCarryCargo() ? e->GetDefaultCargoType() : INVALID_CARGO);
962 if (v->cargo_type != initial_cargo && IsValidCargoID(initial_cargo)) {
963 bool dummy;
964 total_cost.AddCost(GetRefitCost(nullptr, v->engine_type, v->cargo_type, v->cargo_subtype, &dummy));
968 if (v->IsGroundVehicle() && v->HasArticulatedPart()) {
969 v = v->GetNextArticulatedPart();
970 } else {
971 break;
973 } while (v != nullptr);
975 if ((flags & DC_EXEC) && v->type == VEH_TRAIN) w = w->GetNextVehicle();
976 } while (v->type == VEH_TRAIN && (v = v->GetNextVehicle()) != nullptr);
978 if (flags & DC_EXEC) {
980 * Set the orders of the vehicle. Cannot do it earlier as we need
981 * the vehicle refitted before doing this, otherwise the moved
982 * cargo types might not match (passenger vs non-passenger)
984 CommandCost result = Command<CMD_CLONE_ORDER>::Do(flags, (share_orders ? CO_SHARE : CO_COPY), w_front->index, v_front->index);
985 if (result.Failed()) {
986 /* The vehicle has already been bought, so now it must be sold again. */
987 Command<CMD_SELL_VEHICLE>::Do(flags, w_front->index, true, false, INVALID_CLIENT_ID);
988 return { result, INVALID_VEHICLE };
991 /* Now clone the vehicle's name, if it has one. */
992 if (!v_front->name.empty()) CloneVehicleName(v_front, w_front);
994 /* Since we can't estimate the cost of cloning a vehicle accurately we must
995 * check whether the company has enough money manually. */
996 if (!CheckCompanyHasMoney(total_cost)) {
997 /* The vehicle has already been bought, so now it must be sold again. */
998 Command<CMD_SELL_VEHICLE>::Do(flags, w_front->index, true, false, INVALID_CLIENT_ID);
999 return { total_cost, INVALID_VEHICLE };
1003 return { total_cost, new_veh_id };
1007 * Send all vehicles of type to depots
1008 * @param flags the flags used for DoCommand()
1009 * @param service should the vehicles only get service in the depots
1010 * @param vli identifier of the vehicle list
1011 * @return 0 for success and CMD_ERROR if no vehicle is able to go to depot
1013 static CommandCost SendAllVehiclesToDepot(DoCommandFlag flags, bool service, const VehicleListIdentifier &vli)
1015 VehicleList list;
1017 if (!GenerateVehicleSortList(&list, vli)) return CMD_ERROR;
1019 /* Send all the vehicles to a depot */
1020 bool had_success = false;
1021 for (uint i = 0; i < list.size(); i++) {
1022 const Vehicle *v = list[i];
1023 CommandCost ret = Command<CMD_SEND_VEHICLE_TO_DEPOT>::Do(flags, v->index, (service ? DepotCommand::Service : DepotCommand::None) | DepotCommand::DontCancel, {});
1025 if (ret.Succeeded()) {
1026 had_success = true;
1028 /* Return 0 if DC_EXEC is not set this is a valid goto depot command)
1029 * In this case we know that at least one vehicle can be sent to a depot
1030 * and we will issue the command. We can now safely quit the loop, knowing
1031 * it will succeed at least once. With DC_EXEC we really need to send them to the depot */
1032 if (!(flags & DC_EXEC)) break;
1036 return had_success ? CommandCost() : CMD_ERROR;
1040 * Send a vehicle to the depot.
1041 * @param flags for command type
1042 * @param veh_id vehicle ID to send to the depot
1043 * @param depot_cmd DEPOT_ flags (see vehicle_type.h)
1044 * @param vli VehicleListIdentifier.
1045 * @return the cost of this operation or an error
1047 CommandCost CmdSendVehicleToDepot(DoCommandFlag flags, VehicleID veh_id, DepotCommand depot_cmd, const VehicleListIdentifier &vli)
1049 if (HasFlag(depot_cmd, DepotCommand::MassSend)) {
1050 /* Mass goto depot requested */
1051 if (!vli.Valid()) return CMD_ERROR;
1052 return SendAllVehiclesToDepot(flags, HasFlag(depot_cmd, DepotCommand::Service), vli);
1055 Vehicle *v = Vehicle::GetIfValid(veh_id);
1056 if (v == nullptr) return CMD_ERROR;
1057 if (!v->IsPrimaryVehicle()) return CMD_ERROR;
1059 return v->SendToDepot(flags, depot_cmd);
1063 * Give a custom name to your vehicle
1064 * @param flags type of operation
1065 * @param veh_id vehicle ID to name
1066 * @param text the new name or an empty string when resetting to the default
1067 * @return the cost of this operation or an error
1069 CommandCost CmdRenameVehicle(DoCommandFlag flags, VehicleID veh_id, const std::string &text)
1071 Vehicle *v = Vehicle::GetIfValid(veh_id);
1072 if (v == nullptr || !v->IsPrimaryVehicle()) return CMD_ERROR;
1074 CommandCost ret = CheckOwnership(v->owner);
1075 if (ret.Failed()) return ret;
1077 bool reset = text.empty();
1079 if (!reset) {
1080 if (Utf8StringLength(text) >= MAX_LENGTH_VEHICLE_NAME_CHARS) return CMD_ERROR;
1081 if (!(flags & DC_AUTOREPLACE) && !IsUniqueVehicleName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
1084 if (flags & DC_EXEC) {
1085 if (reset) {
1086 v->name.clear();
1087 } else {
1088 v->name = text;
1090 InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 1);
1091 MarkWholeScreenDirty();
1094 return CommandCost();
1099 * Change the service interval of a vehicle
1100 * @param flags type of operation
1101 * @param veh_id vehicle ID that is being service-interval-changed
1102 * @param serv_int new service interval
1103 * @param is_custom service interval is custom flag
1104 * @param is_percent service interval is percentage flag
1105 * @return the cost of this operation or an error
1107 CommandCost CmdChangeServiceInt(DoCommandFlag flags, VehicleID veh_id, uint16_t serv_int, bool is_custom, bool is_percent)
1109 Vehicle *v = Vehicle::GetIfValid(veh_id);
1110 if (v == nullptr || !v->IsPrimaryVehicle()) return CMD_ERROR;
1112 CommandCost ret = CheckOwnership(v->owner);
1113 if (ret.Failed()) return ret;
1115 const Company *company = Company::Get(v->owner);
1116 is_percent = is_custom ? is_percent : company->settings.vehicle.servint_ispercent;
1118 if (is_custom) {
1119 if (serv_int != GetServiceIntervalClamped(serv_int, is_percent)) return CMD_ERROR;
1120 } else {
1121 serv_int = CompanyServiceInterval(company, v->type);
1124 if (flags & DC_EXEC) {
1125 v->SetServiceInterval(serv_int);
1126 v->SetServiceIntervalIsCustom(is_custom);
1127 v->SetServiceIntervalIsPercent(is_percent);
1128 SetWindowDirty(WC_VEHICLE_DETAILS, v->index);
1131 return CommandCost();