Feature: Purchase land multiple tiles at a time
[openttd-github.git] / src / vehicle_cmd.cpp
blob373a92cdbf175359a39e7cf418c0ea198dd61544
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> 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 && cargo != CT_INVALID) 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 (default_cargo == CT_INVALID) return { CMD_ERROR, INVALID_VEHICLE, 0, 0 };
107 bool refitting = cargo != CT_INVALID && 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, use_free_vehicles, &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 refitted_mail_capacity = 0;
148 if (value.Succeeded()) {
149 if (subflags & DC_EXEC) {
150 v->unitnumber = unit_num;
151 v->value = value.GetCost();
152 veh_id = v->index;
155 if (refitting) {
156 /* Refit only one vehicle. If we purchased an engine, it may have gained free wagons. */
157 CommandCost cc;
158 std::tie(cc, refitted_capacity, refitted_mail_capacity) = CmdRefitVehicle(flags, v->index, cargo, 0, false, false, 1);
159 value.AddCost(cc);
160 } else {
161 /* Fill in non-refitted capacities */
162 refitted_capacity = e->GetDisplayDefaultCapacity(&refitted_mail_capacity);
165 if (flags & DC_EXEC) {
166 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
167 InvalidateWindowClassesData(GetWindowClassForVehicleType(type), 0);
168 SetWindowDirty(WC_COMPANY, _current_company);
169 if (IsLocalCompany()) {
170 InvalidateAutoreplaceWindow(v->engine_type, v->group_id); // updates the auto replace window (must be called before incrementing num_engines)
174 if (subflags & DC_EXEC) {
175 GroupStatistics::CountEngine(v, 1);
176 GroupStatistics::UpdateAutoreplace(_current_company);
178 if (v->IsPrimaryVehicle()) {
179 GroupStatistics::CountVehicle(v, 1);
180 if (!(subflags & DC_AUTOREPLACE)) OrderBackup::Restore(v, client_id);
185 /* If we are not in DC_EXEC undo everything */
186 if (flags != subflags) {
187 Command<CMD_SELL_VEHICLE>::Do(DC_EXEC, v->index, false, false, INVALID_CLIENT_ID);
191 /* Only restore if we actually did some refitting */
192 if (flags != subflags) RestoreRandomSeeds(saved_seeds);
194 return { value, veh_id, refitted_capacity, refitted_mail_capacity };
198 * Sell a vehicle.
199 * @param flags for command.
200 * @param v_id vehicle ID being sold.
201 * @param sell_chain sell the vehicle and all vehicles following it in the chain.
202 * @param backup_order make a backup of the vehicle's order (if an engine).
203 * @param client_id User.
204 * @return the cost of this operation or an error.
206 CommandCost CmdSellVehicle(DoCommandFlag flags, VehicleID v_id, bool sell_chain, bool backup_order, ClientID client_id)
208 Vehicle *v = Vehicle::GetIfValid(v_id);
209 if (v == nullptr) return CMD_ERROR;
211 Vehicle *front = v->First();
213 CommandCost ret = CheckOwnership(front->owner);
214 if (ret.Failed()) return ret;
216 if (front->vehstatus & VS_CRASHED) return_cmd_error(STR_ERROR_VEHICLE_IS_DESTROYED);
218 if (!front->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAIN_MUST_BE_STOPPED_INSIDE_DEPOT + front->type);
220 /* Can we actually make the order backup, i.e. are there enough orders? */
221 if (backup_order &&
222 front->orders != nullptr &&
223 !front->orders->IsShared() &&
224 !Order::CanAllocateItem(front->orders->GetNumOrders())) {
225 /* Only happens in exceptional cases when there aren't enough orders anyhow.
226 * Thus it should be safe to just drop the orders in that case. */
227 backup_order = false;
230 if (v->type == VEH_TRAIN) {
231 ret = CmdSellRailWagon(flags, v, sell_chain, backup_order, client_id);
232 } else {
233 ret = CommandCost(EXPENSES_NEW_VEHICLES, -front->value);
235 if (flags & DC_EXEC) {
236 if (front->IsPrimaryVehicle() && backup_order) OrderBackup::Backup(front, client_id);
237 delete front;
241 return ret;
245 * Helper to run the refit cost callback.
246 * @param v The vehicle we are refitting, can be nullptr.
247 * @param engine_type Which engine to refit
248 * @param new_cid Cargo type we are refitting to.
249 * @param new_subtype New cargo subtype.
250 * @param[out] auto_refit_allowed The refit is allowed as an auto-refit.
251 * @return Price for refitting
253 static int GetRefitCostFactor(const Vehicle *v, EngineID engine_type, CargoID new_cid, byte new_subtype, bool *auto_refit_allowed)
255 /* Prepare callback param with info about the new cargo type. */
256 const Engine *e = Engine::Get(engine_type);
258 /* Is this vehicle a NewGRF vehicle? */
259 if (e->GetGRF() != nullptr) {
260 const CargoSpec *cs = CargoSpec::Get(new_cid);
261 uint32 param1 = (cs->classes << 16) | (new_subtype << 8) | e->GetGRF()->cargo_map[new_cid];
263 uint16 cb_res = GetVehicleCallback(CBID_VEHICLE_REFIT_COST, param1, 0, engine_type, v);
264 if (cb_res != CALLBACK_FAILED) {
265 *auto_refit_allowed = HasBit(cb_res, 14);
266 int factor = GB(cb_res, 0, 14);
267 if (factor >= 0x2000) factor -= 0x4000; // Treat as signed integer.
268 return factor;
272 *auto_refit_allowed = e->info.refit_cost == 0;
273 return (v == nullptr || v->cargo_type != new_cid) ? e->info.refit_cost : 0;
277 * Learn the price of refitting a certain engine
278 * @param v The vehicle we are refitting, can be nullptr.
279 * @param engine_type Which engine to refit
280 * @param new_cid Cargo type we are refitting to.
281 * @param new_subtype New cargo subtype.
282 * @param[out] auto_refit_allowed The refit is allowed as an auto-refit.
283 * @return Price for refitting
285 static CommandCost GetRefitCost(const Vehicle *v, EngineID engine_type, CargoID new_cid, byte new_subtype, bool *auto_refit_allowed)
287 ExpensesType expense_type;
288 const Engine *e = Engine::Get(engine_type);
289 Price base_price;
290 int cost_factor = GetRefitCostFactor(v, engine_type, new_cid, new_subtype, auto_refit_allowed);
291 switch (e->type) {
292 case VEH_SHIP:
293 base_price = PR_BUILD_VEHICLE_SHIP;
294 expense_type = EXPENSES_SHIP_RUN;
295 break;
297 case VEH_ROAD:
298 base_price = PR_BUILD_VEHICLE_ROAD;
299 expense_type = EXPENSES_ROADVEH_RUN;
300 break;
302 case VEH_AIRCRAFT:
303 base_price = PR_BUILD_VEHICLE_AIRCRAFT;
304 expense_type = EXPENSES_AIRCRAFT_RUN;
305 break;
307 case VEH_TRAIN:
308 base_price = (e->u.rail.railveh_type == RAILVEH_WAGON) ? PR_BUILD_VEHICLE_WAGON : PR_BUILD_VEHICLE_TRAIN;
309 cost_factor <<= 1;
310 expense_type = EXPENSES_TRAIN_RUN;
311 break;
313 default: NOT_REACHED();
315 if (cost_factor < 0) {
316 return CommandCost(expense_type, -GetPrice(base_price, -cost_factor, e->GetGRF(), -10));
317 } else {
318 return CommandCost(expense_type, GetPrice(base_price, cost_factor, e->GetGRF(), -10));
322 /** Helper structure for RefitVehicle() */
323 struct RefitResult {
324 Vehicle *v; ///< Vehicle to refit
325 uint capacity; ///< New capacity of vehicle
326 uint mail_capacity; ///< New mail capacity of aircraft
327 byte subtype; ///< cargo subtype to refit to
331 * Refits a vehicle (chain).
332 * This is the vehicle-type independent part of the CmdRefitXXX functions.
333 * @param v The vehicle to refit.
334 * @param only_this Whether to only refit this vehicle, or to check the rest of them.
335 * @param num_vehicles Number of vehicles to refit (not counting articulated parts). Zero means the whole chain.
336 * @param new_cid Cargotype to refit to
337 * @param new_subtype Cargo subtype to refit to. 0xFF means to try keeping the same subtype according to GetBestFittingSubType().
338 * @param flags Command flags
339 * @param auto_refit Refitting is done as automatic refitting outside a depot.
340 * @return Refit cost + refittet capacity + mail capacity (aircraft).
342 static std::tuple<CommandCost, uint, uint16> RefitVehicle(Vehicle *v, bool only_this, uint8 num_vehicles, CargoID new_cid, byte new_subtype, DoCommandFlag flags, bool auto_refit)
344 CommandCost cost(v->GetExpenseType(false));
345 uint total_capacity = 0;
346 uint total_mail_capacity = 0;
347 num_vehicles = num_vehicles == 0 ? UINT8_MAX : num_vehicles;
349 VehicleSet vehicles_to_refit;
350 if (!only_this) {
351 GetVehicleSet(vehicles_to_refit, v, num_vehicles);
352 /* In this case, we need to check the whole chain. */
353 v = v->First();
356 std::vector<RefitResult> refit_result;
358 v->InvalidateNewGRFCacheOfChain();
359 byte actual_subtype = new_subtype;
360 for (; v != nullptr; v = (only_this ? nullptr : v->Next())) {
361 /* Reset actual_subtype for every new vehicle */
362 if (!v->IsArticulatedPart()) actual_subtype = new_subtype;
364 if (v->type == VEH_TRAIN && std::find(vehicles_to_refit.begin(), vehicles_to_refit.end(), v->index) == vehicles_to_refit.end() && !only_this) continue;
366 const Engine *e = v->GetEngine();
367 if (!e->CanCarryCargo()) continue;
369 /* If the vehicle is not refittable, or does not allow automatic refitting,
370 * count its capacity nevertheless if the cargo matches */
371 bool refittable = HasBit(e->info.refit_mask, new_cid) && (!auto_refit || HasBit(e->info.misc_flags, EF_AUTO_REFIT));
372 if (!refittable && v->cargo_type != new_cid) continue;
374 /* Determine best fitting subtype if requested */
375 if (actual_subtype == 0xFF) {
376 actual_subtype = GetBestFittingSubType(v, v, new_cid);
379 /* Back up the vehicle's cargo type */
380 CargoID temp_cid = v->cargo_type;
381 byte temp_subtype = v->cargo_subtype;
382 if (refittable) {
383 v->cargo_type = new_cid;
384 v->cargo_subtype = actual_subtype;
387 uint16 mail_capacity = 0;
388 uint amount = e->DetermineCapacity(v, &mail_capacity);
389 total_capacity += amount;
390 /* mail_capacity will always be zero if the vehicle is not an aircraft. */
391 total_mail_capacity += mail_capacity;
393 if (!refittable) continue;
395 /* Restore the original cargo type */
396 v->cargo_type = temp_cid;
397 v->cargo_subtype = temp_subtype;
399 bool auto_refit_allowed;
400 CommandCost refit_cost = GetRefitCost(v, v->engine_type, new_cid, actual_subtype, &auto_refit_allowed);
401 if (auto_refit && (flags & DC_QUERY_COST) == 0 && !auto_refit_allowed) {
402 /* Sorry, auto-refitting not allowed, subtract the cargo amount again from the total.
403 * When querrying cost/capacity (for example in order refit GUI), we always assume 'allowed'.
404 * It is not predictable. */
405 total_capacity -= amount;
406 total_mail_capacity -= mail_capacity;
408 if (v->cargo_type == new_cid) {
409 /* Add the old capacity nevertheless, if the cargo matches */
410 total_capacity += v->cargo_cap;
411 if (v->type == VEH_AIRCRAFT) total_mail_capacity += v->Next()->cargo_cap;
413 continue;
415 cost.AddCost(refit_cost);
417 /* Record the refitting.
418 * Do not execute the refitting immediately, so DetermineCapacity and GetRefitCost do the same in test and exec run.
419 * (weird NewGRFs)
420 * Note:
421 * - If the capacity of vehicles depends on other vehicles in the chain, the actual capacity is
422 * set after RefitVehicle() via ConsistChanged() and friends. The estimation via _returned_refit_capacity will be wrong.
423 * - We have to call the refit cost callback with the pre-refit configuration of the chain because we want refit and
424 * autorefit to behave the same, and we need its result for auto_refit_allowed.
426 refit_result.push_back({v, amount, mail_capacity, actual_subtype});
429 if (flags & DC_EXEC) {
430 /* Store the result */
431 for (RefitResult &result : refit_result) {
432 Vehicle *u = result.v;
433 u->refit_cap = (u->cargo_type == new_cid) ? std::min<uint16>(result.capacity, u->refit_cap) : 0;
434 if (u->cargo.TotalCount() > u->refit_cap) u->cargo.Truncate(u->cargo.TotalCount() - u->refit_cap);
435 u->cargo_type = new_cid;
436 u->cargo_cap = result.capacity;
437 u->cargo_subtype = result.subtype;
438 if (u->type == VEH_AIRCRAFT) {
439 Vehicle *w = u->Next();
440 w->refit_cap = std::min<uint16>(w->refit_cap, result.mail_capacity);
441 w->cargo_cap = result.mail_capacity;
442 if (w->cargo.TotalCount() > w->refit_cap) w->cargo.Truncate(w->cargo.TotalCount() - w->refit_cap);
447 refit_result.clear();
448 return { cost, total_capacity, total_mail_capacity };
452 * Refits a vehicle to the specified cargo type.
453 * @param flags type of operation
454 * @param veh_id vehicle ID to refit
455 * @param new_cid New cargo type to refit to.
456 * @param new_subtype New cargo subtype to refit to. 0xFF means to try keeping the same subtype according to GetBestFittingSubType().
457 * @param auto_refit Automatic refitting.
458 * @param only_this Refit only this vehicle. Used only for cloning vehicles.
459 * @param num_vehicles Number of vehicles to refit (not counting articulated parts). Zero means all vehicles.
460 * Only used if "refit only this vehicle" is false.
461 * @return the cost of this operation or an error
463 std::tuple<CommandCost, uint, uint16> CmdRefitVehicle(DoCommandFlag flags, VehicleID veh_id, CargoID new_cid, byte new_subtype, bool auto_refit, bool only_this, uint8 num_vehicles)
465 Vehicle *v = Vehicle::GetIfValid(veh_id);
466 if (v == nullptr) return { CMD_ERROR, 0, 0 };
468 /* Don't allow disasters and sparks and such to be refitted.
469 * We cannot check for IsPrimaryVehicle as autoreplace also refits in free wagon chains. */
470 if (!IsCompanyBuildableVehicleType(v->type)) return { CMD_ERROR, 0, 0 };
472 Vehicle *front = v->First();
474 CommandCost ret = CheckOwnership(front->owner);
475 if (ret.Failed()) return { ret, 0, 0 };
477 bool free_wagon = v->type == VEH_TRAIN && Train::From(front)->IsFreeWagon(); // used by autoreplace/renew
479 /* Don't allow shadows and such to be refitted. */
480 if (v != front && (v->type == VEH_SHIP || v->type == VEH_AIRCRAFT)) return { CMD_ERROR, 0, 0 };
482 /* Allow auto-refitting only during loading and normal refitting only in a depot. */
483 if ((flags & DC_QUERY_COST) == 0 && // used by the refit GUI, including the order refit GUI.
484 !free_wagon && // used by autoreplace/renew
485 (!auto_refit || !front->current_order.IsType(OT_LOADING)) && // refit inside stations
486 !front->IsStoppedInDepot()) { // refit inside depots
487 return { CommandCost(STR_ERROR_TRAIN_MUST_BE_STOPPED_INSIDE_DEPOT + front->type), 0, 0};
490 if (front->vehstatus & VS_CRASHED) return { CommandCost(STR_ERROR_VEHICLE_IS_DESTROYED), 0, 0};
492 /* Check cargo */
493 if (new_cid >= NUM_CARGO) return { CMD_ERROR, 0, 0 };
495 /* For ships and aircraft there is always only one. */
496 only_this |= front->type == VEH_SHIP || front->type == VEH_AIRCRAFT;
498 auto [cost, refit_capacity, mail_capacity] = RefitVehicle(v, only_this, num_vehicles, new_cid, new_subtype, flags, auto_refit);
500 if (flags & DC_EXEC) {
501 /* Update the cached variables */
502 switch (v->type) {
503 case VEH_TRAIN:
504 Train::From(front)->ConsistChanged(auto_refit ? CCF_AUTOREFIT : CCF_REFIT);
505 break;
506 case VEH_ROAD:
507 RoadVehUpdateCache(RoadVehicle::From(front), auto_refit);
508 if (_settings_game.vehicle.roadveh_acceleration_model != AM_ORIGINAL) RoadVehicle::From(front)->CargoChanged();
509 break;
511 case VEH_SHIP:
512 v->InvalidateNewGRFCacheOfChain();
513 Ship::From(v)->UpdateCache();
514 break;
516 case VEH_AIRCRAFT:
517 v->InvalidateNewGRFCacheOfChain();
518 UpdateAircraftCache(Aircraft::From(v), true);
519 break;
521 default: NOT_REACHED();
523 front->MarkDirty();
525 if (!free_wagon) {
526 InvalidateWindowData(WC_VEHICLE_DETAILS, front->index);
527 InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
529 SetWindowDirty(WC_VEHICLE_DEPOT, front->tile);
530 } else {
531 /* Always invalidate the cache; querycost might have filled it. */
532 v->InvalidateNewGRFCacheOfChain();
535 return { cost, refit_capacity, mail_capacity };
539 * Start/Stop a vehicle
540 * @param flags type of operation
541 * @param veh_id vehicle to start/stop, don't forget to change CcStartStopVehicle if you modify this!
542 * @param evaluate_startstop_cb Shall the start/stop newgrf callback be evaluated (only valid with DC_AUTOREPLACE for network safety)
543 * @return the cost of this operation or an error
545 CommandCost CmdStartStopVehicle(DoCommandFlag flags, VehicleID veh_id, bool evaluate_startstop_cb)
547 /* Disable the effect of p2 bit 0, when DC_AUTOREPLACE is not set */
548 if ((flags & DC_AUTOREPLACE) == 0) evaluate_startstop_cb = true;
550 Vehicle *v = Vehicle::GetIfValid(veh_id);
551 if (v == nullptr || !v->IsPrimaryVehicle()) return CMD_ERROR;
553 CommandCost ret = CheckOwnership(v->owner);
554 if (ret.Failed()) return ret;
556 if (v->vehstatus & VS_CRASHED) return_cmd_error(STR_ERROR_VEHICLE_IS_DESTROYED);
558 switch (v->type) {
559 case VEH_TRAIN:
560 if ((v->vehstatus & VS_STOPPED) && Train::From(v)->gcache.cached_power == 0) return_cmd_error(STR_ERROR_TRAIN_START_NO_POWER);
561 break;
563 case VEH_SHIP:
564 case VEH_ROAD:
565 break;
567 case VEH_AIRCRAFT: {
568 Aircraft *a = Aircraft::From(v);
569 /* cannot stop airplane when in flight, or when taking off / landing */
570 if (a->state >= STARTTAKEOFF && a->state < TERM7) return_cmd_error(STR_ERROR_AIRCRAFT_IS_IN_FLIGHT);
571 if (HasBit(a->flags, VAF_HELI_DIRECT_DESCENT)) return_cmd_error(STR_ERROR_AIRCRAFT_IS_IN_FLIGHT);
572 break;
575 default: return CMD_ERROR;
578 if (evaluate_startstop_cb) {
579 /* Check if this vehicle can be started/stopped. Failure means 'allow'. */
580 uint16 callback = GetVehicleCallback(CBID_VEHICLE_START_STOP_CHECK, 0, 0, v->engine_type, v);
581 StringID error = STR_NULL;
582 if (callback != CALLBACK_FAILED) {
583 if (v->GetGRF()->grf_version < 8) {
584 /* 8 bit result 0xFF means 'allow' */
585 if (callback < 0x400 && GB(callback, 0, 8) != 0xFF) error = GetGRFStringID(v->GetGRFID(), 0xD000 + callback);
586 } else {
587 if (callback < 0x400) {
588 error = GetGRFStringID(v->GetGRFID(), 0xD000 + callback);
589 } else {
590 switch (callback) {
591 case 0x400: // allow
592 break;
594 default: // unknown reason -> disallow
595 error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
596 break;
601 if (error != STR_NULL) return_cmd_error(error);
604 if (flags & DC_EXEC) {
605 if (v->IsStoppedInDepot() && (flags & DC_AUTOREPLACE) == 0) DeleteVehicleNews(veh_id, STR_NEWS_TRAIN_IS_WAITING + v->type);
607 v->vehstatus ^= VS_STOPPED;
608 if (v->type != VEH_TRAIN) v->cur_speed = 0; // trains can stop 'slowly'
609 v->MarkDirty();
610 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
611 SetWindowDirty(WC_VEHICLE_DEPOT, v->tile);
612 SetWindowClassesDirty(GetWindowClassForVehicleType(v->type));
613 InvalidateWindowData(WC_VEHICLE_VIEW, v->index);
615 return CommandCost();
619 * Starts or stops a lot of vehicles
620 * @param flags type of operation
621 * @param tile Tile of the depot where the vehicles are started/stopped (only used for depots)
622 * @param do_start set = start vehicles, unset = stop vehicles
623 * @param vehicle_list_window if set, then it's a vehicle list window, not a depot and Tile is ignored in this case
624 * @param vli VehicleListIdentifier
625 * @return the cost of this operation or an error
627 CommandCost CmdMassStartStopVehicle(DoCommandFlag flags, TileIndex tile, bool do_start, bool vehicle_list_window, const VehicleListIdentifier &vli)
629 VehicleList list;
631 if (!vli.Valid()) return CMD_ERROR;
632 if (!IsCompanyBuildableVehicleType(vli.vtype)) return CMD_ERROR;
634 if (vehicle_list_window) {
635 if (!GenerateVehicleSortList(&list, vli)) return CMD_ERROR;
636 } else {
637 if (!IsDepotTile(tile) || !IsTileOwner(tile, _current_company)) return CMD_ERROR;
638 /* Get the list of vehicles in the depot */
639 BuildDepotVehicleList(vli.vtype, tile, &list, nullptr);
642 for (uint i = 0; i < list.size(); i++) {
643 const Vehicle *v = list[i];
645 if (!!(v->vehstatus & VS_STOPPED) != do_start) continue;
647 if (!vehicle_list_window && !v->IsChainInDepot()) continue;
649 /* Just try and don't care if some vehicle's can't be stopped. */
650 Command<CMD_START_STOP_VEHICLE>::Do(flags, v->index, false);
653 return CommandCost();
657 * Sells all vehicles in a depot
658 * @param flags type of operation
659 * @param tile Tile of the depot where the depot is
660 * @param vehicle_type Vehicle type
661 * @return the cost of this operation or an error
663 CommandCost CmdDepotSellAllVehicles(DoCommandFlag flags, TileIndex tile, VehicleType vehicle_type)
665 VehicleList list;
667 CommandCost cost(EXPENSES_NEW_VEHICLES);
669 if (!IsCompanyBuildableVehicleType(vehicle_type)) return CMD_ERROR;
670 if (!IsDepotTile(tile) || !IsTileOwner(tile, _current_company)) return CMD_ERROR;
672 /* Get the list of vehicles in the depot */
673 BuildDepotVehicleList(vehicle_type, tile, &list, &list);
675 CommandCost last_error = CMD_ERROR;
676 bool had_success = false;
677 for (uint i = 0; i < list.size(); i++) {
678 CommandCost ret = Command<CMD_SELL_VEHICLE>::Do(flags, list[i]->index, true, false, INVALID_CLIENT_ID);
679 if (ret.Succeeded()) {
680 cost.AddCost(ret);
681 had_success = true;
682 } else {
683 last_error = ret;
687 return had_success ? cost : last_error;
691 * Autoreplace all vehicles in the depot
692 * @param flags type of operation
693 * @param tile Tile of the depot where the vehicles are
694 * @param vehicle_type Type of vehicle
695 * @return the cost of this operation or an error
697 CommandCost CmdDepotMassAutoReplace(DoCommandFlag flags, TileIndex tile, VehicleType vehicle_type)
699 VehicleList list;
700 CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES);
702 if (!IsCompanyBuildableVehicleType(vehicle_type)) return CMD_ERROR;
703 if (!IsDepotTile(tile) || !IsTileOwner(tile, _current_company)) return CMD_ERROR;
705 /* Get the list of vehicles in the depot */
706 BuildDepotVehicleList(vehicle_type, tile, &list, &list, true);
708 for (uint i = 0; i < list.size(); i++) {
709 const Vehicle *v = list[i];
711 /* Ensure that the vehicle completely in the depot */
712 if (!v->IsChainInDepot()) continue;
714 CommandCost ret = Command<CMD_AUTOREPLACE_VEHICLE>::Do(flags, v->index);
716 if (ret.Succeeded()) cost.AddCost(ret);
718 return cost;
722 * Test if a name is unique among vehicle names.
723 * @param name Name to test.
724 * @return True ifffffff the name is unique.
726 static bool IsUniqueVehicleName(const std::string &name)
728 for (const Vehicle *v : Vehicle::Iterate()) {
729 if (!v->name.empty() && v->name == name) return false;
732 return true;
736 * Clone the custom name of a vehicle, adding or incrementing a number.
737 * @param src Source vehicle, with a custom name.
738 * @param dst Destination vehicle.
740 static void CloneVehicleName(const Vehicle *src, Vehicle *dst)
742 std::string buf;
744 /* Find the position of the first digit in the last group of digits. */
745 size_t number_position;
746 for (number_position = src->name.length(); number_position > 0; number_position--) {
747 /* The design of UTF-8 lets this work simply without having to check
748 * for UTF-8 sequences. */
749 if (src->name[number_position - 1] < '0' || src->name[number_position - 1] > '9') break;
752 /* Format buffer and determine starting number. */
753 long num;
754 byte padding = 0;
755 if (number_position == src->name.length()) {
756 /* No digit at the end, so start at number 2. */
757 buf = src->name;
758 buf += " ";
759 number_position = buf.length();
760 num = 2;
761 } else {
762 /* Found digits, parse them and start at the next number. */
763 buf = src->name.substr(0, number_position);
765 auto num_str = src->name.substr(number_position);
766 padding = (byte)num_str.length();
768 std::istringstream iss(num_str);
769 iss >> num;
770 num++;
773 /* Check if this name is already taken. */
774 for (int max_iterations = 1000; max_iterations > 0; max_iterations--, num++) {
775 std::ostringstream oss;
777 /* Attach the number to the temporary name. */
778 oss << buf << std::setw(padding) << std::setfill('0') << std::internal << num;
780 /* Check the name is unique. */
781 auto new_name = oss.str();
782 if (IsUniqueVehicleName(new_name)) {
783 dst->name = new_name;
784 break;
788 /* All done. If we didn't find a name, it'll just use its default. */
792 * Clone a vehicle. If it is a train, it will clone all the cars too
793 * @param flags type of operation
794 * @param tile tile of the depot where the cloned vehicle is build
795 * @param veh_id the original vehicle's index
796 * @param share_orders shared orders, else copied orders
797 * @return the cost of this operation + the new vehicle ID or an error
799 std::tuple<CommandCost, VehicleID> CmdCloneVehicle(DoCommandFlag flags, TileIndex tile, VehicleID veh_id, bool share_orders)
801 CommandCost total_cost(EXPENSES_NEW_VEHICLES);
803 Vehicle *v = Vehicle::GetIfValid(veh_id);
804 if (v == nullptr || !v->IsPrimaryVehicle()) return { CMD_ERROR, INVALID_VEHICLE };
805 Vehicle *v_front = v;
806 Vehicle *w = nullptr;
807 Vehicle *w_front = nullptr;
808 Vehicle *w_rear = nullptr;
811 * v_front is the front engine in the original vehicle
812 * v is the car/vehicle of the original vehicle that is currently being copied
813 * w_front is the front engine of the cloned vehicle
814 * w is the car/vehicle currently being cloned
815 * w_rear is the rear end of the cloned train. It's used to add more cars and is only used by trains
818 CommandCost ret = CheckOwnership(v->owner);
819 if (ret.Failed()) return { ret, INVALID_VEHICLE };
821 if (v->type == VEH_TRAIN && (!v->IsFrontEngine() || Train::From(v)->crash_anim_pos >= 4400)) return { CMD_ERROR, INVALID_VEHICLE };
823 /* check that we can allocate enough vehicles */
824 if (!(flags & DC_EXEC)) {
825 int veh_counter = 0;
826 do {
827 veh_counter++;
828 } while ((v = v->Next()) != nullptr);
830 if (!Vehicle::CanAllocateItem(veh_counter)) {
831 return { CommandCost(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME), INVALID_VEHICLE };
835 v = v_front;
837 VehicleID new_veh_id = INVALID_VEHICLE;
838 do {
839 if (v->type == VEH_TRAIN && Train::From(v)->IsRearDualheaded()) {
840 /* we build the rear ends of multiheaded trains with the front ones */
841 continue;
844 /* In case we're building a multi headed vehicle and the maximum number of
845 * vehicles is almost reached (e.g. max trains - 1) not all vehicles would
846 * be cloned. When the non-primary engines were build they were seen as
847 * 'new' vehicles whereas they would immediately be joined with a primary
848 * engine. This caused the vehicle to be not build as 'the limit' had been
849 * reached, resulting in partially build vehicles and such. */
850 DoCommandFlag build_flags = flags;
851 if ((flags & DC_EXEC) && !v->IsPrimaryVehicle()) build_flags |= DC_AUTOREPLACE;
853 CommandCost cost;
854 std::tie(cost, new_veh_id, std::ignore, std::ignore) = Command<CMD_BUILD_VEHICLE>::Do(build_flags, tile, v->engine_type, false, CT_INVALID, INVALID_CLIENT_ID);
856 if (cost.Failed()) {
857 /* Can't build a part, then sell the stuff we already made; clear up the mess */
858 if (w_front != nullptr) Command<CMD_SELL_VEHICLE>::Do(flags, w_front->index, true, false, INVALID_CLIENT_ID);
859 return { cost, INVALID_VEHICLE };
862 total_cost.AddCost(cost);
864 if (flags & DC_EXEC) {
865 w = Vehicle::Get(new_veh_id);
867 if (v->type == VEH_TRAIN && HasBit(Train::From(v)->flags, VRF_REVERSE_DIRECTION)) {
868 SetBit(Train::From(w)->flags, VRF_REVERSE_DIRECTION);
871 if (v->type == VEH_TRAIN && !v->IsFrontEngine()) {
872 /* this s a train car
873 * add this unit to the end of the train */
874 CommandCost result = Command<CMD_MOVE_RAIL_VEHICLE>::Do(flags, w->index, w_rear->index, true);
875 if (result.Failed()) {
876 /* The train can't be joined to make the same consist as the original.
877 * Sell what we already made (clean up) and return an error. */
878 Command<CMD_SELL_VEHICLE>::Do(flags, w_front->index, true, false, INVALID_CLIENT_ID);
879 Command<CMD_SELL_VEHICLE>::Do(flags, w->index, true, false, INVALID_CLIENT_ID);
880 return { result, INVALID_VEHICLE }; // return error and the message returned from CMD_MOVE_RAIL_VEHICLE
882 } else {
883 /* this is a front engine or not a train. */
884 w_front = w;
885 w->service_interval = v->service_interval;
886 w->SetServiceIntervalIsCustom(v->ServiceIntervalIsCustom());
887 w->SetServiceIntervalIsPercent(v->ServiceIntervalIsPercent());
889 w_rear = w; // trains needs to know the last car in the train, so they can add more in next loop
891 } while (v->type == VEH_TRAIN && (v = v->GetNextVehicle()) != nullptr);
893 if ((flags & DC_EXEC) && v_front->type == VEH_TRAIN) {
894 /* for trains this needs to be the front engine due to the callback function */
895 new_veh_id = w_front->index;
898 if (flags & DC_EXEC) {
899 /* Cloned vehicles belong to the same group */
900 Command<CMD_ADD_VEHICLE_GROUP>::Do(flags, v_front->group_id, w_front->index, false);
904 /* Take care of refitting. */
905 w = w_front;
906 v = v_front;
908 /* Both building and refitting are influenced by newgrf callbacks, which
909 * makes it impossible to accurately estimate the cloning costs. In
910 * particular, it is possible for engines of the same type to be built with
911 * different numbers of articulated parts, so when refitting we have to
912 * loop over real vehicles first, and then the articulated parts of those
913 * vehicles in a different loop. */
914 do {
915 do {
916 if (flags & DC_EXEC) {
917 assert(w != nullptr);
919 /* Find out what's the best sub type */
920 byte subtype = GetBestFittingSubType(v, w, v->cargo_type);
921 if (w->cargo_type != v->cargo_type || w->cargo_subtype != subtype) {
922 CommandCost cost = std::get<0>(Command<CMD_REFIT_VEHICLE>::Do(flags, w->index, v->cargo_type, subtype, false, true, 0));
923 if (cost.Succeeded()) total_cost.AddCost(cost);
926 if (w->IsGroundVehicle() && w->HasArticulatedPart()) {
927 w = w->GetNextArticulatedPart();
928 } else {
929 break;
931 } else {
932 const Engine *e = v->GetEngine();
933 CargoID initial_cargo = (e->CanCarryCargo() ? e->GetDefaultCargoType() : (CargoID)CT_INVALID);
935 if (v->cargo_type != initial_cargo && initial_cargo != CT_INVALID) {
936 bool dummy;
937 total_cost.AddCost(GetRefitCost(nullptr, v->engine_type, v->cargo_type, v->cargo_subtype, &dummy));
941 if (v->IsGroundVehicle() && v->HasArticulatedPart()) {
942 v = v->GetNextArticulatedPart();
943 } else {
944 break;
946 } while (v != nullptr);
948 if ((flags & DC_EXEC) && v->type == VEH_TRAIN) w = w->GetNextVehicle();
949 } while (v->type == VEH_TRAIN && (v = v->GetNextVehicle()) != nullptr);
951 if (flags & DC_EXEC) {
953 * Set the orders of the vehicle. Cannot do it earlier as we need
954 * the vehicle refitted before doing this, otherwise the moved
955 * cargo types might not match (passenger vs non-passenger)
957 CommandCost result = Command<CMD_CLONE_ORDER>::Do(flags, (share_orders ? CO_SHARE : CO_COPY), w_front->index, v_front->index);
958 if (result.Failed()) {
959 /* The vehicle has already been bought, so now it must be sold again. */
960 Command<CMD_SELL_VEHICLE>::Do(flags, w_front->index, true, false, INVALID_CLIENT_ID);
961 return { total_cost, INVALID_VEHICLE };
964 /* Now clone the vehicle's name, if it has one. */
965 if (!v_front->name.empty()) CloneVehicleName(v_front, w_front);
967 /* Since we can't estimate the cost of cloning a vehicle accurately we must
968 * check whether the company has enough money manually. */
969 if (!CheckCompanyHasMoney(total_cost)) {
970 /* The vehicle has already been bought, so now it must be sold again. */
971 Command<CMD_SELL_VEHICLE>::Do(flags, w_front->index, true, false, INVALID_CLIENT_ID);
972 return { total_cost, INVALID_VEHICLE };
976 return { total_cost, new_veh_id };
980 * Send all vehicles of type to depots
981 * @param flags the flags used for DoCommand()
982 * @param service should the vehicles only get service in the depots
983 * @param vli identifier of the vehicle list
984 * @return 0 for success and CMD_ERROR if no vehicle is able to go to depot
986 static CommandCost SendAllVehiclesToDepot(DoCommandFlag flags, bool service, const VehicleListIdentifier &vli)
988 VehicleList list;
990 if (!GenerateVehicleSortList(&list, vli)) return CMD_ERROR;
992 /* Send all the vehicles to a depot */
993 bool had_success = false;
994 for (uint i = 0; i < list.size(); i++) {
995 const Vehicle *v = list[i];
996 CommandCost ret = Command<CMD_SEND_VEHICLE_TO_DEPOT>::Do(flags, v->index, (service ? DepotCommand::Service : DepotCommand::None) | DepotCommand::DontCancel, {});
998 if (ret.Succeeded()) {
999 had_success = true;
1001 /* Return 0 if DC_EXEC is not set this is a valid goto depot command)
1002 * In this case we know that at least one vehicle can be sent to a depot
1003 * and we will issue the command. We can now safely quit the loop, knowing
1004 * it will succeed at least once. With DC_EXEC we really need to send them to the depot */
1005 if (!(flags & DC_EXEC)) break;
1009 return had_success ? CommandCost() : CMD_ERROR;
1013 * Send a vehicle to the depot.
1014 * @param flags for command type
1015 * @param veh_id vehicle ID to send to the depot
1016 * @param depot_cmd DEPOT_ flags (see vehicle_type.h)
1017 * @param vli VehicleListIdentifier.
1018 * @return the cost of this operation or an error
1020 CommandCost CmdSendVehicleToDepot(DoCommandFlag flags, VehicleID veh_id, DepotCommand depot_cmd, const VehicleListIdentifier &vli)
1022 if ((depot_cmd & DepotCommand::MassSend) != DepotCommand::None) {
1023 /* Mass goto depot requested */
1024 if (!vli.Valid()) return CMD_ERROR;
1025 return SendAllVehiclesToDepot(flags, (depot_cmd & DepotCommand::Service) != DepotCommand::None, vli);
1028 Vehicle *v = Vehicle::GetIfValid(veh_id);
1029 if (v == nullptr) return CMD_ERROR;
1030 if (!v->IsPrimaryVehicle()) return CMD_ERROR;
1032 return v->SendToDepot(flags, depot_cmd);
1036 * Give a custom name to your vehicle
1037 * @param flags type of operation
1038 * @param veh_id vehicle ID to name
1039 * @param text the new name or an empty string when resetting to the default
1040 * @return the cost of this operation or an error
1042 CommandCost CmdRenameVehicle(DoCommandFlag flags, VehicleID veh_id, const std::string &text)
1044 Vehicle *v = Vehicle::GetIfValid(veh_id);
1045 if (v == nullptr || !v->IsPrimaryVehicle()) return CMD_ERROR;
1047 CommandCost ret = CheckOwnership(v->owner);
1048 if (ret.Failed()) return ret;
1050 bool reset = text.empty();
1052 if (!reset) {
1053 if (Utf8StringLength(text) >= MAX_LENGTH_VEHICLE_NAME_CHARS) return CMD_ERROR;
1054 if (!(flags & DC_AUTOREPLACE) && !IsUniqueVehicleName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
1057 if (flags & DC_EXEC) {
1058 if (reset) {
1059 v->name.clear();
1060 } else {
1061 v->name = text;
1063 InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 1);
1064 MarkWholeScreenDirty();
1067 return CommandCost();
1072 * Change the service interval of a vehicle
1073 * @param flags type of operation
1074 * @param veh_id vehicle ID that is being service-interval-changed
1075 * @param serv_int new service interval
1076 * @param is_custom service interval is custom flag
1077 * @param is_percent service interval is percentage flag
1078 * @return the cost of this operation or an error
1080 CommandCost CmdChangeServiceInt(DoCommandFlag flags, VehicleID veh_id, uint16 serv_int, bool is_custom, bool is_percent)
1082 Vehicle *v = Vehicle::GetIfValid(veh_id);
1083 if (v == nullptr || !v->IsPrimaryVehicle()) return CMD_ERROR;
1085 CommandCost ret = CheckOwnership(v->owner);
1086 if (ret.Failed()) return ret;
1088 const Company *company = Company::Get(v->owner);
1089 is_percent = is_custom ? is_percent : company->settings.vehicle.servint_ispercent;
1091 if (is_custom) {
1092 if (serv_int != GetServiceIntervalClamped(serv_int, is_percent)) return CMD_ERROR;
1093 } else {
1094 serv_int = CompanyServiceInterval(company, v->type);
1097 if (flags & DC_EXEC) {
1098 v->SetServiceInterval(serv_int);
1099 v->SetServiceIntervalIsCustom(is_custom);
1100 v->SetServiceIntervalIsPercent(is_percent);
1101 SetWindowDirty(WC_VEHICLE_DETAILS, v->index);
1104 return CommandCost();