Make it possible to stop road vehicles from slowing down in curves so "diagonal"...
[openttd-joker.git] / src / vehicle_cmd.cpp
blobb395e6532044646a0f734af5535dcf406e83ba1c
1 /* $Id$ */
3 /*
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/>.
8 */
10 /** @file vehicle_cmd.cpp Commands for vehicles. */
12 #include "stdafx.h"
13 #include "roadveh.h"
14 #include "news_func.h"
15 #include "airport.h"
16 #include "cmd_helper.h"
17 #include "command_func.h"
18 #include "company_func.h"
19 #include "train.h"
20 #include "aircraft.h"
21 #include "newgrf_text.h"
22 #include "vehicle_func.h"
23 #include "string_func.h"
24 #include "depot_map.h"
25 #include "vehiclelist.h"
26 #include "engine_func.h"
27 #include "articulated_vehicles.h"
28 #include "autoreplace_gui.h"
29 #include "group.h"
30 #include "order_backup.h"
31 #include "ship.h"
32 #include "newgrf.h"
33 #include "company_base.h"
34 #include "tbtr_template_vehicle.h"
35 #include "tbtr_template_vehicle_func.h"
37 #include "table/strings.h"
39 #include "safeguards.h"
41 /* Tables used in vehicle.h to find the right command for a certain vehicle type */
42 const uint32 _veh_build_proc_table[] = {
43 CMD_BUILD_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_TRAIN),
44 CMD_BUILD_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_ROAD_VEHICLE),
45 CMD_BUILD_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_SHIP),
46 CMD_BUILD_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_AIRCRAFT),
49 const uint32 _veh_sell_proc_table[] = {
50 CMD_SELL_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_SELL_TRAIN),
51 CMD_SELL_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_SELL_ROAD_VEHICLE),
52 CMD_SELL_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_SELL_SHIP),
53 CMD_SELL_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_SELL_AIRCRAFT),
56 const uint32 _veh_refit_proc_table[] = {
57 CMD_REFIT_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_REFIT_TRAIN),
58 CMD_REFIT_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_REFIT_ROAD_VEHICLE),
59 CMD_REFIT_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_REFIT_SHIP),
60 CMD_REFIT_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_REFIT_AIRCRAFT),
63 const uint32 _send_to_depot_proc_table[] = {
64 CMD_SEND_VEHICLE_TO_DEPOT | CMD_MSG(STR_ERROR_CAN_T_SEND_TRAIN_TO_DEPOT),
65 CMD_SEND_VEHICLE_TO_DEPOT | CMD_MSG(STR_ERROR_CAN_T_SEND_ROAD_VEHICLE_TO_DEPOT),
66 CMD_SEND_VEHICLE_TO_DEPOT | CMD_MSG(STR_ERROR_CAN_T_SEND_SHIP_TO_DEPOT),
67 CMD_SEND_VEHICLE_TO_DEPOT | CMD_MSG(STR_ERROR_CAN_T_SEND_AIRCRAFT_TO_HANGAR),
71 CommandCost CmdBuildRailVehicle(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **v);
72 CommandCost CmdBuildRoadVehicle(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **v);
73 CommandCost CmdBuildShip (TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **v);
74 CommandCost CmdBuildAircraft (TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **v);
76 /**
77 * Build a vehicle.
78 * @param tile tile of depot where the vehicle is built
79 * @param flags for command
80 * @param p1 various bitstuffed data
81 * bits 0-15: vehicle type being built.
82 * bits 16-31: vehicle type specific bits passed on to the vehicle build functions.
83 * @param p2 User
84 * @param text unused
85 * @return the cost of this operation or an error
87 CommandCost CmdBuildVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
89 /* Elementary check for valid location. */
90 if (!IsDepotTile(tile) || !IsTileOwner(tile, _current_company)) return CommandError();
92 VehicleType type = GetDepotVehicleType(tile);
94 /* Validate the engine type. */
95 EngineID eid = GB(p1, 0, 16);
96 if (!IsEngineBuildable(eid, type, _current_company)) return CommandError(STR_ERROR_RAIL_VEHICLE_NOT_AVAILABLE + type);
98 const Engine *e = Engine::Get(eid);
99 CommandCost value(EXPENSES_NEW_VEHICLES, e->GetCost());
101 /* Engines without valid cargo should not be available */
102 if (e->GetDefaultCargoType() == CT_INVALID) return CommandError();
104 /* Check whether the number of vehicles we need to build can be built according to pool space. */
105 uint num_vehicles;
106 switch (type) {
107 case VEH_TRAIN: num_vehicles = (e->u.rail.railveh_type == RAILVEH_MULTIHEAD ? 2 : 1) + CountArticulatedParts(eid, false); break;
108 case VEH_ROAD: num_vehicles = 1 + CountArticulatedParts(eid, false); break;
109 case VEH_SHIP: num_vehicles = 1; break;
110 case VEH_AIRCRAFT: num_vehicles = e->u.air.subtype & AIR_CTOL ? 2 : 3; break;
111 default: NOT_REACHED(); // Safe due to IsDepotTile()
113 if (!Vehicle::CanAllocateItem(num_vehicles)) return CommandError(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
115 /* Check whether we can allocate a unit number. Autoreplace does not allocate
116 * an unit number as it will (always) reuse the one of the replaced vehicle
117 * and (train) wagons don't have an unit number in any scenario. */
118 UnitID unit_num = (flags & DC_AUTOREPLACE || (type == VEH_TRAIN && e->u.rail.railveh_type == RAILVEH_WAGON)) ? 0 : GetFreeUnitNumber(type);
119 if (unit_num == UINT16_MAX) return CommandError(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
121 Vehicle *v;
122 switch (type) {
123 case VEH_TRAIN: value.AddCost(CmdBuildRailVehicle(tile, flags, e, GB(p1, 16, 16), &v)); break;
124 case VEH_ROAD: value.AddCost(CmdBuildRoadVehicle(tile, flags, e, GB(p1, 16, 16), &v)); break;
125 case VEH_SHIP: value.AddCost(CmdBuildShip (tile, flags, e, GB(p1, 16, 16), &v)); break;
126 case VEH_AIRCRAFT: value.AddCost(CmdBuildAircraft (tile, flags, e, GB(p1, 16, 16), &v)); break;
127 default: NOT_REACHED(); // Safe due to IsDepotTile()
130 if (value.Succeeded() && flags & DC_EXEC) {
131 v->unitnumber = unit_num;
132 v->value = value.GetCost();
134 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
135 InvalidateWindowClassesData(GetWindowClassForVehicleType(type), 0);
136 SetWindowDirty(WC_COMPANY, _current_company);
137 if (IsLocalCompany()) {
138 InvalidateAutoreplaceWindow(v->engine_type, v->group_id); // updates the auto replace window (must be called before incrementing num_engines)
141 GroupStatistics::CountEngine(v, 1);
142 GroupStatistics::UpdateAutoreplace(_current_company);
144 if (v->IsPrimaryVehicle()) {
145 GroupStatistics::CountVehicle(v, 1);
146 OrderBackup::Restore(v, p2);
150 return value;
153 CommandCost CmdSellRailWagon(DoCommandFlag flags, Vehicle *v, uint16 data, uint32 user);
156 * Sell a vehicle.
157 * @param tile unused.
158 * @param flags for command.
159 * @param p1 various bitstuffed data.
160 * bits 0-19: vehicle ID being sold.
161 * bits 20-30: vehicle type specific bits passed on to the vehicle build functions.
162 * bit 31: make a backup of the vehicle's order (if an engine).
163 * @param p2 User.
164 * @param text unused.
165 * @return the cost of this operation or an error.
167 CommandCost CmdSellVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
169 Vehicle *v = Vehicle::GetIfValid(GB(p1, 0, 20));
170 if (v == nullptr) return CommandError();
172 Vehicle *front = v->First();
174 CommandCost ret = CheckOwnership(front->owner);
175 if (ret.Failed()) return ret;
177 if (front->vehstatus & VS_CRASHED) return CommandError(STR_ERROR_VEHICLE_IS_DESTROYED);
179 /* Do this check only if the vehicle to be moved is non-virtual */
180 if ( !HasBit(p1, 21) )
181 if (!front->IsStoppedInDepot()) return CommandError(STR_ERROR_TRAIN_MUST_BE_STOPPED_INSIDE_DEPOT + front->type);
183 /* Can we actually make the order backup, i.e. are there enough orders? */
184 if (p1 & MAKE_ORDER_BACKUP_FLAG &&
185 front->HasOrdersList() &&
186 !front->HasSharedOrdersList() &&
187 !Order::CanAllocateItem(front->GetNumOrders())) {
188 /* Only happens in exceptional cases when there aren't enough orders anyhow.
189 * Thus it should be safe to just drop the orders in that case. */
190 p1 &= ~MAKE_ORDER_BACKUP_FLAG;
193 if (v->type == VEH_TRAIN) {
194 ret = CmdSellRailWagon(flags, v, GB(p1, 20, 12), p2);
195 } else {
196 ret = CommandCost(EXPENSES_NEW_VEHICLES, -front->value);
198 if (flags & DC_EXEC) {
199 if (front->IsPrimaryVehicle() && p1 & MAKE_ORDER_BACKUP_FLAG) OrderBackup::Backup(front, p2);
200 delete front;
204 return ret;
208 * Helper to run the refit cost callback.
209 * @param v The vehicle we are refitting, can be nullptr.
210 * @param engine_type Which engine to refit
211 * @param new_cid Cargo type we are refitting to.
212 * @param new_subtype New cargo subtype.
213 * @param [out] auto_refit_allowed The refit is allowed as an auto-refit.
214 * @return Price for refitting
216 static int GetRefitCostFactor(const Vehicle *v, EngineID engine_type, CargoID new_cid, byte new_subtype, bool *auto_refit_allowed)
218 /* Prepare callback param with info about the new cargo type. */
219 const Engine *e = Engine::Get(engine_type);
221 /* Is this vehicle a NewGRF vehicle? */
222 if (e->GetGRF() != nullptr) {
223 const CargoSpec *cs = CargoSpec::Get(new_cid);
224 uint32 param1 = (cs->classes << 16) | (new_subtype << 8) | e->GetGRF()->cargo_map[new_cid];
226 uint16 cb_res = GetVehicleCallback(CBID_VEHICLE_REFIT_COST, param1, 0, engine_type, v);
227 if (cb_res != CALLBACK_FAILED) {
228 *auto_refit_allowed = HasBit(cb_res, 14);
229 int factor = GB(cb_res, 0, 14);
230 if (factor >= 0x2000) factor -= 0x4000; // Treat as signed integer.
231 return factor;
235 *auto_refit_allowed = e->info.refit_cost == 0;
236 return (v == nullptr || v->cargo_type != new_cid) ? e->info.refit_cost : 0;
240 * Learn the price of refitting a certain engine
241 * @param v The vehicle we are refitting, can be nullptr.
242 * @param engine_type Which engine to refit
243 * @param new_cid Cargo type we are refitting to.
244 * @param new_subtype New cargo subtype.
245 * @param [out] auto_refit_allowed The refit is allowed as an auto-refit.
246 * @return Price for refitting
248 static CommandCost GetRefitCost(const Vehicle *v, EngineID engine_type, CargoID new_cid, byte new_subtype, bool *auto_refit_allowed)
250 ExpensesType expense_type;
251 const Engine *e = Engine::Get(engine_type);
252 Price base_price;
253 int cost_factor = GetRefitCostFactor(v, engine_type, new_cid, new_subtype, auto_refit_allowed);
254 switch (e->type) {
255 case VEH_SHIP:
256 base_price = PR_BUILD_VEHICLE_SHIP;
257 expense_type = EXPENSES_SHIP_RUN;
258 break;
260 case VEH_ROAD:
261 base_price = PR_BUILD_VEHICLE_ROAD;
262 expense_type = EXPENSES_ROADVEH_RUN;
263 break;
265 case VEH_AIRCRAFT:
266 base_price = PR_BUILD_VEHICLE_AIRCRAFT;
267 expense_type = EXPENSES_AIRCRAFT_RUN;
268 break;
270 case VEH_TRAIN:
271 base_price = (e->u.rail.railveh_type == RAILVEH_WAGON) ? PR_BUILD_VEHICLE_WAGON : PR_BUILD_VEHICLE_TRAIN;
272 cost_factor <<= 1;
273 expense_type = EXPENSES_TRAIN_RUN;
274 break;
276 default: NOT_REACHED();
278 if (cost_factor < 0) {
279 return CommandCost(expense_type, -GetPrice(base_price, -cost_factor, e->GetGRF(), -10));
280 } else {
281 return CommandCost(expense_type, GetPrice(base_price, cost_factor, e->GetGRF(), -10));
285 /** Helper structure for RefitVehicle() */
286 struct RefitResult {
287 Vehicle *v; ///< Vehicle to refit
288 uint capacity; ///< New capacity of vehicle
289 uint mail_capacity; ///< New mail capacity of aircraft
290 byte subtype; ///< cargo subtype to refit to
294 * Refits a vehicle (chain).
295 * This is the vehicle-type independent part of the CmdRefitXXX functions.
296 * @param v The vehicle to refit.
297 * @param only_this Whether to only refit this vehicle, or to check the rest of them.
298 * @param num_vehicles Number of vehicles to refit (not counting articulated parts). Zero means the whole chain.
299 * @param new_cid Cargotype to refit to
300 * @param new_subtype Cargo subtype to refit to. 0xFF means to try keeping the same subtype according to GetBestFittingSubType().
301 * @param flags Command flags
302 * @param auto_refit Refitting is done as automatic refitting outside a depot.
303 * @return Refit cost.
305 static CommandCost RefitVehicle(Vehicle *v, bool only_this, uint8 num_vehicles, CargoID new_cid, byte new_subtype, DoCommandFlag flags, bool auto_refit)
307 CommandCost cost(v->GetExpenseType(false));
308 uint total_capacity = 0;
309 uint total_mail_capacity = 0;
310 num_vehicles = num_vehicles == 0 ? UINT8_MAX : num_vehicles;
312 VehicleSet vehicles_to_refit;
313 if (!only_this) {
314 GetVehicleSet(vehicles_to_refit, v, num_vehicles);
315 /* In this case, we need to check the whole chain. */
316 v = v->First();
319 static SmallVector<RefitResult, 16> refit_result;
320 refit_result.Clear();
322 v->InvalidateNewGRFCacheOfChain();
323 byte actual_subtype = new_subtype;
324 for (; v != nullptr; v = (only_this ? nullptr : v->Next())) {
325 /* Reset actual_subtype for every new vehicle */
326 if (!v->IsArticulatedPart()) actual_subtype = new_subtype;
328 if (v->type == VEH_TRAIN && !vehicles_to_refit.Contains(v->index) && !only_this) continue;
330 const Engine *e = v->GetEngine();
331 if (!e->CanCarryCargo()) continue;
333 /* If the vehicle is not refittable, or does not allow automatic refitting,
334 * count its capacity nevertheless if the cargo matches */
335 bool refittable = HasBit(e->info.refit_mask, new_cid) && (!auto_refit || HasBit(e->info.misc_flags, EF_AUTO_REFIT));
336 if (!refittable && v->cargo_type != new_cid) continue;
338 /* Determine best fitting subtype if requested */
339 if (actual_subtype == 0xFF) {
340 actual_subtype = GetBestFittingSubType(v, v, new_cid);
343 /* Back up the vehicle's cargo type */
344 CargoID temp_cid = v->cargo_type;
345 byte temp_subtype = v->cargo_subtype;
346 if (refittable) {
347 v->cargo_type = new_cid;
348 v->cargo_subtype = actual_subtype;
351 uint16 mail_capacity = 0;
352 uint amount = e->DetermineCapacity(v, &mail_capacity);
353 total_capacity += amount;
354 /* mail_capacity will always be zero if the vehicle is not an aircraft. */
355 total_mail_capacity += mail_capacity;
357 if (!refittable) continue;
359 /* Restore the original cargo type */
360 v->cargo_type = temp_cid;
361 v->cargo_subtype = temp_subtype;
363 bool auto_refit_allowed;
364 CommandCost refit_cost = GetRefitCost(v, v->engine_type, new_cid, actual_subtype, &auto_refit_allowed);
365 if (auto_refit && (flags & DC_QUERY_COST) == 0 && !auto_refit_allowed) {
366 /* Sorry, auto-refitting not allowed, subtract the cargo amount again from the total.
367 * When querrying cost/capacity (for example in order refit GUI), we always assume 'allowed'.
368 * It is not predictable. */
369 total_capacity -= amount;
370 total_mail_capacity -= mail_capacity;
372 if (v->cargo_type == new_cid) {
373 /* Add the old capacity nevertheless, if the cargo matches */
374 total_capacity += v->cargo_cap;
375 if (v->type == VEH_AIRCRAFT) total_mail_capacity += v->Next()->cargo_cap;
377 continue;
379 cost.AddCost(refit_cost);
381 /* Record the refitting.
382 * Do not execute the refitting immediately, so DetermineCapacity and GetRefitCost do the same in test and exec run.
383 * (weird NewGRFs)
384 * Note:
385 * - If the capacity of vehicles depends on other vehicles in the chain, the actual capacity is
386 * set after RefitVehicle() via ConsistChanged() and friends. The estimation via _returned_refit_capacity will be wrong.
387 * - We have to call the refit cost callback with the pre-refit configuration of the chain because we want refit and
388 * autorefit to behave the same, and we need its result for auto_refit_allowed.
390 RefitResult *result = refit_result.Append();
391 result->v = v;
392 result->capacity = amount;
393 result->mail_capacity = mail_capacity;
394 result->subtype = actual_subtype;
397 if (flags & DC_EXEC) {
398 /* Store the result */
399 for (RefitResult *result = refit_result.Begin(); result != refit_result.End(); result++) {
400 Vehicle *u = result->v;
401 u->refit_cap = (u->cargo_type == new_cid) ? min(result->capacity, u->refit_cap) : 0;
402 if (u->cargo.TotalCount() > u->refit_cap) u->cargo.Truncate(u->cargo.TotalCount() - u->refit_cap);
403 u->cargo_type = new_cid;
404 u->cargo_cap = result->capacity;
405 u->cargo_subtype = result->subtype;
406 if (u->type == VEH_AIRCRAFT) {
407 Vehicle *w = u->Next();
408 w->refit_cap = min(w->refit_cap, result->mail_capacity);
409 w->cargo_cap = result->mail_capacity;
410 if (w->cargo.TotalCount() > w->refit_cap) w->cargo.Truncate(w->cargo.TotalCount() - w->refit_cap);
415 refit_result.Clear();
416 _returned_refit_capacity = total_capacity;
417 _returned_mail_refit_capacity = total_mail_capacity;
418 return cost;
422 * Refits a vehicle to the specified cargo type.
423 * @param tile unused
424 * @param flags type of operation
425 * @param p1 vehicle ID to refit
426 * @param p2 various bitstuffed elements
427 * - p2 = (bit 0-4) - New cargo type to refit to.
428 * - p2 = (bit 6) - Automatic refitting.
429 * - p2 = (bit 5) - Is a virtual train (used by template replacement to allow refitting without stopped-in-depot checks)
430 * - p2 = (bit 7) - Refit only this vehicle. Used only for cloning vehicles.
431 * - p2 = (bit 8-15) - New cargo subtype to refit to. 0xFF means to try keeping the same subtype according to GetBestFittingSubType().
432 * - p2 = (bit 16-23) - Number of vehicles to refit (not counting articulated parts). Zero means all vehicles.
433 * Only used if "refit only this vehicle" is false.
434 * @param text unused
435 * @return the cost of this operation or an error
437 CommandCost CmdRefitVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
439 Vehicle *v = Vehicle::GetIfValid(p1);
440 if (v == nullptr) return CommandError();
442 /* Don't allow disasters and sparks and such to be refitted.
443 * We cannot check for IsPrimaryVehicle as autoreplace also refits in free wagon chains. */
444 if (!IsCompanyBuildableVehicleType(v->type)) return CommandError();
446 Vehicle *front = v->First();
448 CommandCost ret = CheckOwnership(front->owner);
449 if (ret.Failed()) return ret;
451 bool auto_refit = HasBit(p2, 6);
452 bool is_virtual_train = HasBit(p2, 5);
453 bool free_wagon = v->type == VEH_TRAIN && Train::From(front)->IsFreeWagon(); // used by autoreplace/renew
455 /* Don't allow shadows and such to be refitted. */
456 if (v != front && (v->type == VEH_SHIP || v->type == VEH_AIRCRAFT)) return CommandError();
458 /* Allow auto-refitting only during loading and normal refitting only in a depot. */
459 if (!is_virtual_train) {
460 if ((flags & DC_QUERY_COST) == 0 && // used by the refit GUI, including the order refit GUI.
461 !free_wagon && // used by autoreplace/renew
462 (!auto_refit || !front->current_order.IsType(OT_LOADING)) && // refit inside stations
463 !front->IsStoppedInDepot()) { // refit inside depots
464 return CommandError(STR_ERROR_TRAIN_MUST_BE_STOPPED_INSIDE_DEPOT + front->type);
467 if (front->vehstatus & VS_CRASHED) return CommandError(STR_ERROR_VEHICLE_IS_DESTROYED);
470 /* Check cargo */
471 CargoID new_cid = GB(p2, 0, 5);
472 byte new_subtype = GB(p2, 8, 8);
473 if (new_cid >= NUM_CARGO) return CommandError();
475 /* For ships and aircrafts there is always only one. */
476 bool only_this = HasBit(p2, 7) || front->type == VEH_SHIP || front->type == VEH_AIRCRAFT;
477 uint8 num_vehicles = GB(p2, 16, 8);
479 CommandCost cost = RefitVehicle(v, only_this, num_vehicles, new_cid, new_subtype, flags, auto_refit);
481 if (flags & DC_EXEC) {
482 /* Update the cached variables */
483 switch (v->type) {
484 case VEH_TRAIN:
485 Train::From(front)->ConsistChanged(auto_refit ? CCF_AUTOREFIT : CCF_REFIT);
486 break;
487 case VEH_ROAD:
488 RoadVehUpdateCache(RoadVehicle::From(front), auto_refit);
489 if (_settings_game.vehicle.roadveh_acceleration_model != AM_ORIGINAL) RoadVehicle::From(front)->CargoChanged();
490 break;
492 case VEH_SHIP:
493 v->InvalidateNewGRFCacheOfChain();
494 Ship::From(v)->UpdateCache();
495 break;
497 case VEH_AIRCRAFT:
498 v->InvalidateNewGRFCacheOfChain();
499 UpdateAircraftCache(Aircraft::From(v), true);
500 break;
502 default: NOT_REACHED();
504 front->MarkDirty();
506 if (!free_wagon) {
507 InvalidateWindowData(WC_VEHICLE_DETAILS, front->index);
508 InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
510 /* virtual vehicles get their cargo changed by the TemplateCreateWindow, so set this dirty instead of a depot window */
511 if ( HasBit(v->subtype, GVSF_VIRTUAL) ) SetWindowClassesDirty(WC_CREATE_TEMPLATE);
512 else SetWindowDirty(WC_VEHICLE_DEPOT, front->tile);
513 } else {
514 /* Always invalidate the cache; querycost might have filled it. */
515 v->InvalidateNewGRFCacheOfChain();
518 return cost;
522 * Start/Stop a vehicle
523 * @param tile unused
524 * @param flags type of operation
525 * @param p1 vehicle to start/stop, don't forget to change CcStartStopVehicle if you modify this!
526 * @param p2 bit 0: Shall the start/stop newgrf callback be evaluated (only valid with DC_AUTOREPLACE for network safety)
527 * @param text unused
528 * @return the cost of this operation or an error
530 CommandCost CmdStartStopVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
532 /* Disable the effect of p2 bit 0, when DC_AUTOREPLACE is not set */
533 if ((flags & DC_AUTOREPLACE) == 0) SetBit(p2, 0);
535 Vehicle *v = Vehicle::GetIfValid(p1);
536 if (v == nullptr || !v->IsPrimaryVehicle()) return CommandError();
538 CommandCost ret = CheckOwnership(v->owner);
539 if (ret.Failed()) return ret;
541 if (v->vehstatus & VS_CRASHED) return CommandError(STR_ERROR_VEHICLE_IS_DESTROYED);
543 switch (v->type) {
544 case VEH_TRAIN:
545 if ((v->vehstatus & VS_STOPPED) && Train::From(v)->gcache.cached_power == 0) return CommandError(STR_ERROR_TRAIN_START_NO_POWER);
546 break;
548 case VEH_SHIP:
549 case VEH_ROAD:
550 break;
552 case VEH_AIRCRAFT: {
553 Aircraft *a = Aircraft::From(v);
554 /* cannot stop airplane when in flight, or when taking off / landing */
555 if (!(v->vehstatus & VS_CRASHED) && a->state >= STARTTAKEOFF && a->state < TERM7) return CommandError(STR_ERROR_AIRCRAFT_IS_IN_FLIGHT);
556 break;
559 default: return CommandError();
562 if (HasBit(p2, 0)) {
563 /* Check if this vehicle can be started/stopped. Failure means 'allow'. */
564 uint16 callback = GetVehicleCallback(CBID_VEHICLE_START_STOP_CHECK, 0, 0, v->engine_type, v);
565 StringID error = STR_NULL;
566 if (callback != CALLBACK_FAILED) {
567 if (v->GetGRF()->grf_version < 8) {
568 /* 8 bit result 0xFF means 'allow' */
569 if (callback < 0x400 && GB(callback, 0, 8) != 0xFF) error = GetGRFStringID(v->GetGRFID(), 0xD000 + callback);
570 } else {
571 if (callback < 0x400) {
572 error = GetGRFStringID(v->GetGRFID(), 0xD000 + callback);
573 } else {
574 switch (callback) {
575 case 0x400: // allow
576 break;
578 default: // unknown reason -> disallow
579 error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
580 break;
585 if (error != STR_NULL) return CommandError(error);
588 if (flags & DC_EXEC) {
589 if (v->IsStoppedInDepot() && (flags & DC_AUTOREPLACE) == 0) DeleteVehicleNews(p1, STR_NEWS_TRAIN_IS_WAITING + v->type);
591 v->vehstatus ^= VS_STOPPED;
592 if (v->type != VEH_TRAIN) v->cur_speed = 0; // trains can stop 'slowly'
593 v->MarkDirty();
594 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
595 SetWindowDirty(WC_VEHICLE_DEPOT, v->tile);
596 SetWindowClassesDirty(GetWindowClassForVehicleType(v->type));
598 v->MarkSeparationInvalid();
600 return CommandCost();
604 * Starts or stops a lot of vehicles
605 * @param tile Tile of the depot where the vehicles are started/stopped (only used for depots)
606 * @param flags type of operation
607 * @param p1 bitmask
608 * - bit 0 set = start vehicles, unset = stop vehicles
609 * - bit 1 if set, then it's a vehicle list window, not a depot and Tile is ignored in this case
610 * @param p2 packed VehicleListIdentifier
611 * @param text unused
612 * @return the cost of this operation or an error
614 CommandCost CmdMassStartStopVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
616 VehicleList list;
617 bool do_start = HasBit(p1, 0);
618 bool vehicle_list_window = HasBit(p1, 1);
620 VehicleListIdentifier vli;
621 if (!vli.UnpackIfValid(p2)) return CommandError();
622 if (!IsCompanyBuildableVehicleType(vli.vtype)) return CommandError();
624 if (vehicle_list_window) {
625 if (!GenerateVehicleSortList(&list, vli)) return CommandError();
626 } else {
627 /* Get the list of vehicles in the depot */
628 BuildDepotVehicleList(vli.vtype, tile, &list, nullptr);
631 for (uint i = 0; i < list.Length(); i++) {
632 const Vehicle *v = list[i];
634 if (!!(v->vehstatus & VS_STOPPED) != do_start) continue;
636 if (!vehicle_list_window && !v->IsChainInDepot()) continue;
638 /* Just try and don't care if some vehicle's can't be stopped. */
639 DoCommand(tile, v->index, 0, flags, CMD_START_STOP_VEHICLE);
642 return CommandCost();
646 * Sells all vehicles in a group
647 * @param unused
648 * @param flags type of operation
649 * @param p1 Vehicle type
650 * @param p2 GroupID
651 * @param text unused
652 * @return the cost of this operation or an error
654 CommandCost CmdGroupSellAllVehicles(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
656 //assert(Group::IsValidID(p2));
658 CommandCost cost(EXPENSES_NEW_VEHICLES);
659 VehicleType vehicle_type = Extract<VehicleType, 0, 3>(p1);
660 GroupID group_id = p2;
662 bool is_all_group = (p2 == ALL_GROUP);
663 bool is_default_group = (p2 == DEFAULT_GROUP);
665 if (!IsCompanyBuildableVehicleType(vehicle_type)) return CommandError();
667 uint sell_command = GetCmdSellVeh(vehicle_type);
668 CommandCost last_error = CommandError();
669 bool had_success = false;
671 std::vector<const Vehicle*> vehicles;
672 const Vehicle* v;
673 FOR_ALL_VEHICLES(v) {
674 if (!HasBit(v->subtype, GVSF_VIRTUAL) && v->type == vehicle_type && v->IsPrimaryVehicle() &&
675 v->owner == _current_company && (GroupIsInGroup(v->group_id, group_id) || is_all_group)) {
676 vehicles.push_back(v);
680 for (auto vehicle = vehicles.begin(); vehicle != vehicles.end(); vehicle++) {
681 CommandCost ret = DoCommand((*vehicle)->tile, (*vehicle)->index | (1 << 20), 0, flags, sell_command);
683 if (ret.Succeeded()) {
684 cost.AddCost(ret);
685 had_success = true;
687 else {
688 last_error = ret;
692 return had_success ? cost : last_error;
696 * Sells all vehicles in a depot
697 * @param tile Tile of the depot where the depot is
698 * @param flags type of operation
699 * @param p1 Vehicle type
700 * @param p2 unused
701 * @param text unused
702 * @return the cost of this operation or an error
704 CommandCost CmdDepotSellAllVehicles(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
706 VehicleList list;
708 CommandCost cost(EXPENSES_NEW_VEHICLES);
709 VehicleType vehicle_type = Extract<VehicleType, 0, 3>(p1);
711 if (!IsCompanyBuildableVehicleType(vehicle_type)) return CommandError();
713 uint sell_command = GetCmdSellVeh(vehicle_type);
715 /* Get the list of vehicles in the depot */
716 BuildDepotVehicleList(vehicle_type, tile, &list, &list);
718 CommandCost last_error = CommandError();
719 bool had_success = false;
720 for (uint i = 0; i < list.Length(); i++) {
721 CommandCost ret = DoCommand(tile, list[i]->index | (1 << 20), 0, flags, sell_command);
722 if (ret.Succeeded()) {
723 cost.AddCost(ret);
724 had_success = true;
725 } else {
726 last_error = ret;
730 return had_success ? cost : last_error;
734 * Autoreplace all vehicles in the depot
735 * @param tile Tile of the depot where the vehicles are
736 * @param flags type of operation
737 * @param p1 Type of vehicle
738 * @param p2 unused
739 * @param text unused
740 * @return the cost of this operation or an error
742 CommandCost CmdDepotMassAutoReplace(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
744 VehicleList list;
745 CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES);
746 VehicleType vehicle_type = Extract<VehicleType, 0, 3>(p1);
748 if (!IsCompanyBuildableVehicleType(vehicle_type)) return CommandError();
749 if (!IsDepotTile(tile) || !IsTileOwner(tile, _current_company)) return CommandError();
751 /* Get the list of vehicles in the depot */
752 BuildDepotVehicleList(vehicle_type, tile, &list, &list, true);
754 for (uint i = 0; i < list.Length(); i++) {
755 const Vehicle *v = list[i];
757 /* Ensure that the vehicle completely in the depot */
758 if (!v->IsChainInDepot()) continue;
760 CommandCost ret = DoCommand(0, v->index, 0, flags, CMD_AUTOREPLACE_VEHICLE);
762 if (ret.Succeeded()) cost.AddCost(ret);
764 return cost;
768 * Test if a name is unique among vehicle names.
769 * @param name Name to test.
770 * @return True ifffffff the name is unique.
772 static bool IsUniqueVehicleName(const char *name)
774 const Vehicle *v;
776 FOR_ALL_VEHICLES(v) {
777 if (v->name != nullptr && strcmp(v->name, name) == 0) return false;
780 return true;
784 * Clone the custom name of a vehicle, adding or incrementing a number.
785 * @param src Source vehicle, with a custom name.
786 * @param dst Destination vehicle.
788 static void CloneVehicleName(const Vehicle *src, Vehicle *dst)
790 char buf[256];
792 /* Find the position of the first digit in the last group of digits. */
793 size_t number_position;
794 for (number_position = strlen(src->name); number_position > 0; number_position--) {
795 /* The design of UTF-8 lets this work simply without having to check
796 * for UTF-8 sequences. */
797 if (src->name[number_position - 1] < '0' || src->name[number_position - 1] > '9') break;
800 /* Format buffer and determine starting number. */
801 int num;
802 byte padding = 0;
803 if (number_position == strlen(src->name)) {
804 /* No digit at the end, so start at number 2. */
805 strecpy(buf, src->name, lastof(buf));
806 strecat(buf, " ", lastof(buf));
807 number_position = strlen(buf);
808 num = 2;
809 } else {
810 /* Found digits, parse them and start at the next number. */
811 strecpy(buf, src->name, lastof(buf));
812 buf[number_position] = '\0';
813 char *endptr;
814 num = strtol(&src->name[number_position], &endptr, 10) + 1;
815 padding = endptr - &src->name[number_position];
818 /* Check if this name is already taken. */
819 for (int max_iterations = 1000; max_iterations > 0; max_iterations--, num++) {
820 /* Attach the number to the temporary name. */
821 seprintf(&buf[number_position], lastof(buf), "%0*d", padding, num);
823 /* Check the name is unique. */
824 if (IsUniqueVehicleName(buf)) {
825 dst->name = stredup(buf);
826 break;
830 /* All done. If we didn't find a name, it'll just use its default. */
833 inline void SetupTemplateVehicleFromVirtual(TemplateVehicle *tmp, TemplateVehicle *prev, Train *virt)
835 if (prev) {
836 prev->SetNext(tmp);
837 tmp->SetPrev(prev);
838 tmp->SetFirst(prev->First());
840 tmp->railtype = virt->railtype;
841 tmp->owner = virt->owner;
842 tmp->value = virt->value;
844 // set the subtype but also clear the virtual flag while doing it
845 tmp->subtype = virt->subtype & ~(1 << GVSF_VIRTUAL);
846 // set the cargo type and capacity
847 tmp->cargo_type = virt->cargo_type;
848 tmp->cargo_subtype = virt->cargo_subtype;
849 tmp->cargo_cap = virt->cargo_cap;
851 const GroundVehicleCache *gcache = virt->GetGroundVehicleCache();
852 tmp->max_speed = virt->GetDisplayMaxSpeed();
853 tmp->power = gcache->cached_power;
854 tmp->weight = gcache->cached_weight;
855 tmp->max_te = gcache->cached_max_te;
857 tmp->spritenum = virt->spritenum;
858 virt->GetImage(DIR_W, EIT_IN_DEPOT, &tmp->sprite_seq);
859 tmp->image_width = virt->GetDisplayImageWidth(&tmp->image_offset);
863 * Toggles 'reuse depot vehicles' on a template vehicle.
864 * @param tile unused
865 * @param flags type of operation
866 * @param p1 the template vehicle's index
867 * @param p2 unused
868 * @param text unused
869 * @return the cost of this operation or an error
871 CommandCost CmdToggleReuseDepotVehicles(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
873 // Identify template to toggle
874 TemplateVehicle *template_vehicle = TemplateVehicle::GetIfValid(p1);
876 if (template_vehicle == nullptr)
877 return CommandError();
879 bool should_execute = (flags & DC_EXEC) != 0;
881 if (should_execute) {
882 template_vehicle->ToggleReuseDepotVehicles();
884 InvalidateWindowClassesData(WC_TEMPLATEGUI_MAIN, 0);
887 return CommandCost();
891 * Toggles 'keep remaining vehicles' on a template vehicle.
892 * @param tile unused
893 * @param flags type of operation
894 * @param p1 the template vehicle's index
895 * @param p2 unused
896 * @param text unused
897 * @return the cost of this operation or an error
899 CommandCost CmdToggleKeepRemainingVehicles(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
901 // Identify template to toggle
902 TemplateVehicle *template_vehicle = TemplateVehicle::GetIfValid(p1);
904 if (template_vehicle == nullptr)
905 return CommandError();
907 bool should_execute = (flags & DC_EXEC) != 0;
909 if (should_execute) {
910 template_vehicle->ToggleKeepRemainingVehicles();
912 InvalidateWindowClassesData(WC_TEMPLATEGUI_MAIN, 0);
915 return CommandCost();
919 * Toggles 'refit as template' on a template vehicle.
920 * @param tile unused
921 * @param flags type of operation
922 * @param p1 the template vehicle's index
923 * @param p2 unused
924 * @param text unused
925 * @return the cost of this operation or an error
927 CommandCost CmdToggleRefitAsTemplate(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
929 // Identify template to toggle
930 TemplateVehicle *template_vehicle = TemplateVehicle::GetIfValid(p1);
932 if (template_vehicle == nullptr)
933 return CommandError();
935 bool should_execute = (flags & DC_EXEC) != 0;
937 if (should_execute) {
938 template_vehicle->ToggleRefitAsTemplate();
940 InvalidateWindowClassesData(WC_TEMPLATEGUI_MAIN, 0);
943 return CommandCost();
947 * Create a virtual train from a template vehicle.
948 * @param tile unused
949 * @param flags type of operation
950 * @param p1 the original vehicle's index
951 * @param p2 unused
952 * @param text unused
953 * @return the cost of this operation or an error
955 CommandCost CmdVirtualTrainFromTemplateVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
957 VehicleID template_vehicle_id = p1;
959 TemplateVehicle* tv = TemplateVehicle::GetIfValid(template_vehicle_id);
961 if (tv == nullptr)
962 return CommandError();
964 if (tv->owner != _current_company) {
965 return CommandError();
968 bool should_execute = (flags & DC_EXEC) != 0;
970 if (should_execute) {
971 StringID err = INVALID_STRING_ID;
972 Train* train = VirtualTrainFromTemplateVehicle(tv, err);
974 if (train == nullptr)
975 return CommandError(err);
978 return CommandCost();
981 CommandCost CmdDeleteVirtualTrain(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text);
983 Train* VirtualTrainFromTemplateVehicle(TemplateVehicle* tv, StringID &err)
985 CommandCost c;
986 Train *tmp, *head, *tail;
988 assert(tv->owner == _current_company);
990 head = CmdBuildVirtualRailVehicle(tv->engine_type, true, err);
991 if ( !head ) return nullptr;
993 tail = head;
994 tv = tv->GetNextUnit();
995 while ( tv ) {
996 tmp = CmdBuildVirtualRailVehicle(tv->engine_type, true, err);
997 if (!tmp) {
998 CmdDeleteVirtualTrain(INVALID_TILE, DC_EXEC, head->index, 0, nullptr);
999 return nullptr;
1002 tmp->cargo_type = tv->cargo_type;
1003 tmp->cargo_subtype = tv->cargo_subtype;
1004 CmdMoveRailVehicle(INVALID_TILE, DC_EXEC, (1 << 21) | tmp->index, tail->index, 0);
1005 tail = tmp;
1007 tv = tv->GetNextUnit();
1010 _new_vehicle_id = head->index;
1012 return head;
1016 * Create a virtual train from a regular train.
1017 * @param tile unused
1018 * @param flags type of operation
1019 * @param p1 the train index
1020 * @param p2 unused
1021 * @param text unused
1022 * @return the cost of this operation or an error
1024 CommandCost CmdVirtualTrainFromTrain(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1026 VehicleID vehicle_id = p1;
1027 Vehicle* vehicle = Vehicle::GetIfValid(vehicle_id);
1029 if (vehicle == nullptr || vehicle->type != VEH_TRAIN)
1030 return CommandError();
1032 Train* train = Train::From(vehicle);
1034 bool should_execute = (flags & DC_EXEC) != 0;
1036 if (should_execute) {
1037 CommandCost c;
1038 Train *tmp, *head, *tail;
1039 StringID err = INVALID_STRING_ID;
1041 head = CmdBuildVirtualRailVehicle(train->engine_type, false, err);
1042 if (!head) return CommandError(err);
1044 tail = head;
1045 train = train->GetNextUnit();
1046 while ( train ) {
1047 tmp = CmdBuildVirtualRailVehicle(train->engine_type, false, err);
1048 if (!tmp) {
1049 CmdDeleteVirtualTrain(tile, flags, head->index, 0, nullptr);
1050 return CommandError(err);
1053 tmp->cargo_type = train->cargo_type;
1054 tmp->cargo_subtype = train->cargo_subtype;
1055 CmdMoveRailVehicle(0, DC_EXEC, (1 << 21) | tmp->index, tail->index, 0);
1056 tail = tmp;
1058 train = train->GetNextUnit();
1061 _new_vehicle_id = head->index;
1064 return CommandCost();
1068 * Create a virtual train from a template vehicle.
1069 * @param tile unused
1070 * @param flags type of operation
1071 * @param p1 the vehicle's index
1072 * @param p2 unused
1073 * @param text unused
1074 * @return the cost of this operation or an error
1076 CommandCost CmdDeleteVirtualTrain(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1078 VehicleID vehicle_id = p1;
1080 Vehicle* vehicle = Vehicle::GetIfValid(vehicle_id);
1082 if (vehicle == nullptr || vehicle->type != VEH_TRAIN)
1083 return CommandError();
1085 Train* train = Train::From(vehicle);
1087 bool should_execute = (flags & DC_EXEC) != 0;
1089 if (should_execute) {
1090 delete train;
1093 return CommandCost();
1097 * Replace a template vehicle with another one based on a virtual train.
1098 * @param tile unused
1099 * @param flags type of operation
1100 * @param p1 the template vehicle's index
1101 * @param p2 the virtual train's index
1102 * @param text unused
1103 * @return the cost of this operation or an error
1105 CommandCost CmdReplaceTemplateVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1107 VehicleID template_vehicle_id = p1;
1108 VehicleID virtual_train_id = p2;
1110 TemplateVehicle* template_vehicle = TemplateVehicle::GetIfValid(template_vehicle_id);
1111 Vehicle* vehicle = Vehicle::GetIfValid(virtual_train_id);
1113 if (vehicle == nullptr || vehicle->type != VEH_TRAIN)
1114 return CommandError();
1116 Train* train = Train::From(vehicle);
1118 bool should_execute = (flags & DC_EXEC) != 0;
1120 if (should_execute) {
1121 VehicleID old_ID = INVALID_VEHICLE;
1122 bool old_keep_remaining_vehicles = true;
1123 bool old_reuse_depot_vehicles = true;
1124 bool old_refit_as_template = true;
1126 if (template_vehicle != nullptr) {
1127 old_ID = template_vehicle->index;
1128 old_keep_remaining_vehicles = template_vehicle->keep_remaining_vehicles;
1129 old_reuse_depot_vehicles = template_vehicle->reuse_depot_vehicles;
1130 old_refit_as_template = template_vehicle->refit_as_template;
1132 delete template_vehicle;
1134 template_vehicle = nullptr;
1137 template_vehicle = TemplateVehicleFromVirtualTrain(train);
1139 if (template_vehicle == nullptr) {
1140 return CommandError();
1142 else {
1143 template_vehicle->keep_remaining_vehicles = old_keep_remaining_vehicles;
1144 template_vehicle->reuse_depot_vehicles = old_reuse_depot_vehicles;
1145 template_vehicle->refit_as_template = old_refit_as_template;
1148 // Make sure our replacements still point to the correct thing.
1149 if (old_ID != template_vehicle->index) {
1150 TemplateReplacement* tr;
1151 FOR_ALL_TEMPLATE_REPLACEMENTS(tr) {
1152 if (tr->GetTemplateVehicleID() == old_ID) {
1153 tr->SetTemplate(template_vehicle->index);
1158 InvalidateWindowClassesData(WC_TEMPLATEGUI_MAIN, 0);
1161 return CommandCost();
1165 * Clone a vehicle to create a template vehicle.
1166 * @param tile unused
1167 * @param flags type of operation
1168 * @param p1 the original vehicle's index
1169 * @param p2 unused
1170 * @param text unused
1171 * @return the cost of this operation or an error
1173 CommandCost CmdTemplateVehicleFromTrain(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1175 // create a new template from the clicked vehicle
1176 TemplateVehicle *tv;
1178 Vehicle *t = Vehicle::GetIfValid(p1);
1180 Train *clicked = Train::GetIfValid(t->index);
1181 if (!clicked)
1182 return CommandError();
1184 Train *init_clicked = clicked;
1186 int len = CountVehiclesInChain(clicked);
1187 if (!TemplateVehicle::CanAllocateItem(len))
1188 return CommandError();
1190 for (Train *v = clicked; v != nullptr; v = v->GetNextUnit()) {
1191 if (!IsEngineBuildable(v->engine_type, VEH_TRAIN, _current_company)) {
1192 return CommandError(STR_ERROR_RAIL_VEHICLE_NOT_AVAILABLE + VEH_TRAIN);
1196 bool should_execute = (flags & DC_EXEC) != 0;
1198 if (should_execute) {
1199 TemplateVehicle *tmp, *prev=0;
1200 for (; clicked; clicked=clicked->Next()) {
1201 tmp = new TemplateVehicle(clicked->engine_type);
1202 SetupTemplateVehicleFromVirtual(tmp, prev, clicked);
1203 prev = tmp;
1206 tmp->First()->SetRealLength(CeilDiv(init_clicked->gcache.cached_total_length * 10, TILE_SIZE));
1207 tv = tmp->First();
1209 if (!tv) return CommandError();
1211 InvalidateWindowClassesData(WC_TEMPLATEGUI_MAIN, 0);
1214 return CommandCost();
1218 * Delete a template vehicle.
1219 * @param tile unused
1220 * @param flags type of operation
1221 * @param p1 the template vehicle's index
1222 * @param p2 unused
1223 * @param text unused
1224 * @return the cost of this operation or an error
1226 CommandCost CmdDeleteTemplateVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1228 // Identify template to delete
1229 TemplateVehicle *del = TemplateVehicle::GetIfValid(p1);
1231 if (del == nullptr)
1232 return CommandError();
1234 bool should_execute = (flags & DC_EXEC) != 0;
1236 if (should_execute) {
1237 // Remove corresponding template replacements if existing
1238 TemplateReplacement *tr;
1239 FOR_ALL_TEMPLATE_REPLACEMENTS(tr) {
1240 if (tr->Template() == del->index) {
1241 delete tr;
1245 delete del;
1247 InvalidateWindowClassesData(WC_CREATE_TEMPLATE, 0);
1248 InvalidateWindowClassesData(WC_TEMPLATEGUI_MAIN, 0);
1251 return CommandCost();
1255 * Issues a template replacement for a vehicle group
1256 * @param tile unused
1257 * @param flags type of operation
1258 * @param p1 the group index
1259 * @param p2 the template vehicle's index
1260 * @param text unused
1261 * @return the cost of this operation or an error
1263 CommandCost CmdIssueTemplateReplacement(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1265 bool should_execute = (flags & DC_EXEC) != 0;
1267 GroupID group_id = p1;
1268 TemplateID template_id = p2;
1270 if (should_execute) {
1271 bool succeeded = IssueTemplateReplacement(group_id, template_id);
1273 if (!succeeded)
1274 return CommandError();
1276 InvalidateWindowClassesData(WC_TEMPLATEGUI_MAIN, 0);
1279 return CommandCost();
1283 * Deletes a template replacement from a vehicle group
1284 * @param tile unused
1285 * @param flags type of operation
1286 * @param p1 the group index
1287 * @param p2 unused
1288 * @param text unused
1289 * @return the cost of this operation or an error
1291 CommandCost CmdDeleteTemplateReplacement(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1293 bool should_execute = (flags & DC_EXEC) != 0;
1295 GroupID group_id = p1;
1297 if (should_execute) {
1298 TemplateReplacement* tr = GetTemplateReplacementByGroupID(group_id);
1299 if (tr != nullptr)
1300 delete tr;
1302 InvalidateWindowClassesData(WC_TEMPLATEGUI_MAIN, 0);
1305 return CommandCost();
1309 * Clone a vehicle. If it is a train, it will clone all the cars too
1310 * @param tile tile of the depot where the cloned vehicle is build
1311 * @param flags type of operation
1312 * @param p1 the original vehicle's index
1313 * @param p2 1 = shared orders, else copied orders
1314 * @param text unused
1315 * @return the cost of this operation or an error
1317 CommandCost CmdCloneVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1319 CommandCost total_cost(EXPENSES_NEW_VEHICLES);
1321 Vehicle *v = Vehicle::GetIfValid(p1);
1322 if (v == nullptr || !v->IsPrimaryVehicle()) return CommandError();
1323 Vehicle *v_front = v;
1324 Vehicle *w = nullptr;
1325 Vehicle *w_front = nullptr;
1326 Vehicle *w_rear = nullptr;
1329 * v_front is the front engine in the original vehicle
1330 * v is the car/vehicle of the original vehicle that is currently being copied
1331 * w_front is the front engine of the cloned vehicle
1332 * w is the car/vehicle currently being cloned
1333 * w_rear is the rear end of the cloned train. It's used to add more cars and is only used by trains
1336 CommandCost ret = CheckOwnership(v->owner);
1337 if (ret.Failed()) return ret;
1339 if (v->type == VEH_TRAIN && (!v->IsFrontEngine() || Train::From(v)->crash_anim_pos >= 4400)) return CommandError();
1341 /* check that we can allocate enough vehicles */
1342 if (!(flags & DC_EXEC)) {
1343 int veh_counter = 0;
1344 do {
1345 veh_counter++;
1346 } while ((v = v->Next()) != nullptr);
1348 if (!Vehicle::CanAllocateItem(veh_counter)) {
1349 return CommandError(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
1353 v = v_front;
1355 do {
1356 if (v->type == VEH_TRAIN && Train::From(v)->IsRearDualheaded()) {
1357 /* we build the rear ends of multiheaded trains with the front ones */
1358 continue;
1361 /* In case we're building a multi headed vehicle and the maximum number of
1362 * vehicles is almost reached (e.g. max trains - 1) not all vehicles would
1363 * be cloned. When the non-primary engines were build they were seen as
1364 * 'new' vehicles whereas they would immediately be joined with a primary
1365 * engine. This caused the vehicle to be not build as 'the limit' had been
1366 * reached, resulting in partially build vehicles and such. */
1367 DoCommandFlag build_flags = flags;
1368 if ((flags & DC_EXEC) && !v->IsPrimaryVehicle()) build_flags |= DC_AUTOREPLACE;
1370 CommandCost cost = DoCommand(tile, v->engine_type | (1 << 16), 0, build_flags, GetCmdBuildVeh(v));
1372 if (cost.Failed()) {
1373 /* Can't build a part, then sell the stuff we already made; clear up the mess */
1374 if (w_front != nullptr) DoCommand(w_front->tile, w_front->index | (1 << 20), 0, flags, GetCmdSellVeh(w_front));
1375 return cost;
1378 total_cost.AddCost(cost);
1380 if (flags & DC_EXEC) {
1381 w = Vehicle::Get(_new_vehicle_id);
1383 if (v->type == VEH_TRAIN && HasBit(Train::From(v)->flags, VRF_REVERSE_DIRECTION)) {
1384 SetBit(Train::From(w)->flags, VRF_REVERSE_DIRECTION);
1387 if (v->type == VEH_TRAIN && !v->IsFrontEngine()) {
1388 /* this s a train car
1389 * add this unit to the end of the train */
1390 CommandCost result = DoCommand(0, w->index | 1 << 20, w_rear->index, flags, CMD_MOVE_RAIL_VEHICLE);
1391 if (result.Failed()) {
1392 /* The train can't be joined to make the same consist as the original.
1393 * Sell what we already made (clean up) and return an error. */
1394 DoCommand(w_front->tile, w_front->index | 1 << 20, 0, flags, GetCmdSellVeh(w_front));
1395 DoCommand(w_front->tile, w->index | 1 << 20, 0, flags, GetCmdSellVeh(w));
1396 return result; // return error and the message returned from CMD_MOVE_RAIL_VEHICLE
1398 } else {
1399 /* this is a front engine or not a train. */
1400 w_front = w;
1401 w->service_interval = v->service_interval;
1402 w->SetServiceIntervalIsCustom(v->ServiceIntervalIsCustom());
1403 w->SetServiceIntervalIsPercent(v->ServiceIntervalIsPercent());
1405 w_rear = w; // trains needs to know the last car in the train, so they can add more in next loop
1407 } while (v->type == VEH_TRAIN && (v = v->GetNextVehicle()) != nullptr);
1409 if ((flags & DC_EXEC) && v_front->type == VEH_TRAIN) {
1410 /* for trains this needs to be the front engine due to the callback function */
1411 _new_vehicle_id = w_front->index;
1414 if (flags & DC_EXEC) {
1415 /* Cloned vehicles belong to the same group */
1416 DoCommand(0, v_front->group_id, w_front->index, flags, CMD_ADD_VEHICLE_GROUP);
1420 /* Take care of refitting. */
1421 w = w_front;
1422 v = v_front;
1424 /* Both building and refitting are influenced by newgrf callbacks, which
1425 * makes it impossible to accurately estimate the cloning costs. In
1426 * particular, it is possible for engines of the same type to be built with
1427 * different numbers of articulated parts, so when refitting we have to
1428 * loop over real vehicles first, and then the articulated parts of those
1429 * vehicles in a different loop. */
1430 do {
1431 do {
1432 if (flags & DC_EXEC) {
1433 assert(w != nullptr);
1435 /* Find out what's the best sub type */
1436 byte subtype = GetBestFittingSubType(v, w, v->cargo_type);
1437 if (w->cargo_type != v->cargo_type || w->cargo_subtype != subtype) {
1438 CommandCost cost = DoCommand(0, w->index, v->cargo_type | 1U << 7 | (subtype << 8), flags, GetCmdRefitVeh(v));
1439 if (cost.Succeeded()) total_cost.AddCost(cost);
1442 if (w->IsGroundVehicle() && w->HasArticulatedPart()) {
1443 w = w->GetNextArticulatedPart();
1444 } else {
1445 break;
1447 } else {
1448 const Engine *e = v->GetEngine();
1449 CargoID initial_cargo = (e->CanCarryCargo() ? e->GetDefaultCargoType() : (CargoID)CT_INVALID);
1451 if (v->cargo_type != initial_cargo && initial_cargo != CT_INVALID) {
1452 bool dummy;
1453 total_cost.AddCost(GetRefitCost(nullptr, v->engine_type, v->cargo_type, v->cargo_subtype, &dummy));
1457 if (v->IsGroundVehicle() && v->HasArticulatedPart()) {
1458 v = v->GetNextArticulatedPart();
1459 } else {
1460 break;
1462 } while (v != nullptr);
1464 if ((flags & DC_EXEC) && v->type == VEH_TRAIN) w = w->GetNextVehicle();
1465 } while (v->type == VEH_TRAIN && (v = v->GetNextVehicle()) != nullptr);
1467 if (flags & DC_EXEC) {
1469 * Set the orders of the vehicle. Cannot do it earlier as we need
1470 * the vehicle refitted before doing this, otherwise the moved
1471 * cargo types might not match (passenger vs non-passenger)
1473 DoCommand(0, w_front->index | (p2 & 1 ? CO_SHARE : CO_COPY) << 30, v_front->index, flags, CMD_CLONE_ORDER);
1475 /* Now clone the vehicle's name, if it has one. */
1476 if (v_front->name != nullptr) CloneVehicleName(v_front, w_front);
1479 /* Since we can't estimate the cost of cloning a vehicle accurately we must
1480 * check whether the company has enough money manually. */
1481 if (!CheckCompanyHasMoney(total_cost)) {
1482 if (flags & DC_EXEC) {
1483 /* The vehicle has already been bought, so now it must be sold again. */
1484 DoCommand(w_front->tile, w_front->index | 1 << 20, 0, flags, GetCmdSellVeh(w_front));
1486 return total_cost;
1489 return total_cost;
1493 * Send all vehicles of type to depots
1494 * @param flags the flags used for DoCommand()
1495 * @param service should the vehicles only get service in the depots
1496 * @param vli identifier of the vehicle list
1497 * @return 0 for success and CommandError() if no vehicle is able to go to depot
1499 static CommandCost SendAllVehiclesToDepot(DoCommandFlag flags, bool service, const VehicleListIdentifier &vli)
1501 VehicleList list;
1503 if (!GenerateVehicleSortList(&list, vli)) return CommandError();
1505 /* Send all the vehicles to a depot */
1506 bool had_success = false;
1507 for (uint i = 0; i < list.Length(); i++) {
1508 const Vehicle *v = list[i];
1509 CommandCost ret = DoCommand(v->tile, v->index | (service ? DEPOT_SERVICE : 0U) | DEPOT_DONT_CANCEL, 0, flags, GetCmdSendToDepot(vli.vtype));
1511 if (ret.Succeeded()) {
1512 had_success = true;
1514 /* Return 0 if DC_EXEC is not set this is a valid goto depot command)
1515 * In this case we know that at least one vehicle can be sent to a depot
1516 * and we will issue the command. We can now safely quit the loop, knowing
1517 * it will succeed at least once. With DC_EXEC we really need to send them to the depot */
1518 if (!(flags & DC_EXEC)) break;
1522 return had_success ? CommandCost() : CommandError();
1526 * Send a vehicle to the depot.
1527 * @param tile unused
1528 * @param flags for command type
1529 * @param p1 bitmask
1530 * - p1 0-20: bitvehicle ID to send to the depot
1531 * - p1 bits 25-8 - DEPOT_ flags (see vehicle_type.h)
1532 * @param p2 packed VehicleListIdentifier.
1533 * @param text unused
1534 * @return the cost of this operation or an error
1536 CommandCost CmdSendVehicleToDepot(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1538 if (p1 & DEPOT_MASS_SEND) {
1539 /* Mass goto depot requested */
1540 VehicleListIdentifier vli;
1541 if (!vli.UnpackIfValid(p2)) return CommandError();
1542 return SendAllVehiclesToDepot(flags, (p1 & DEPOT_SERVICE) != 0, vli);
1545 Vehicle *v = Vehicle::GetIfValid(GB(p1, 0, 20));
1546 if (v == nullptr) return CommandError();
1547 if (!v->IsPrimaryVehicle()) return CommandError();
1549 return v->SendToDepot(flags, (DepotCommand)(p1 & DEPOT_COMMAND_MASK));
1553 * Sets the vehicle unit number
1554 * @param tile unused
1555 * @param flags type of operation
1556 * @param p1 vehicle ID to set number on
1557 * @param p2 vehicle unit number
1558 * @param text unused
1559 * @return the cost of this operation or an error
1561 CommandCost CmdSetVehicleUnitNumber(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1563 Vehicle *v = Vehicle::GetIfValid(p1);
1564 if (v == nullptr || !v->IsPrimaryVehicle()) return CommandError();
1566 CommandCost ret = CheckOwnership(v->owner);
1567 if (ret.Failed()) return ret;
1569 if (flags & DC_EXEC) {
1570 v->unitnumber = (UnitID)p2;
1573 return CommandCost();
1577 * Give a custom name to your vehicle
1578 * @param tile unused
1579 * @param flags type of operation
1580 * @param p1 vehicle ID to name
1581 * @param p2 unused
1582 * @param text the new name or an empty string when resetting to the default
1583 * @return the cost of this operation or an error
1585 CommandCost CmdRenameVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1587 Vehicle *v = Vehicle::GetIfValid(p1);
1588 if (v == nullptr || !v->IsPrimaryVehicle()) return CommandError();
1590 CommandCost ret = CheckOwnership(v->owner);
1591 if (ret.Failed()) return ret;
1593 bool reset = StrEmpty(text);
1595 if (!reset) {
1596 if (Utf8StringLength(text) >= MAX_LENGTH_VEHICLE_NAME_CHARS) return CommandError();
1597 if (!(flags & DC_AUTOREPLACE) && !IsUniqueVehicleName(text)) return CommandError(STR_ERROR_NAME_MUST_BE_UNIQUE);
1600 if (flags & DC_EXEC) {
1601 free(v->name);
1602 v->name = reset ? nullptr : stredup(text);
1603 InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 1);
1604 MarkWholeScreenDirty();
1607 return CommandCost();
1612 * Change the service interval of a vehicle
1613 * @param tile unused
1614 * @param flags type of operation
1615 * @param p1 vehicle ID that is being service-interval-changed
1616 * @param p2 bitmask
1617 * - p2 = (bit 0-15) - new service interval
1618 * - p2 = (bit 16) - service interval is custom flag
1619 * - p2 = (bit 17) - service interval is percentage flag
1620 * @param text unused
1621 * @return the cost of this operation or an error
1623 CommandCost CmdChangeServiceInt(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1625 Vehicle *v = Vehicle::GetIfValid(p1);
1626 if (v == nullptr || !v->IsPrimaryVehicle()) return CommandError();
1628 CommandCost ret = CheckOwnership(v->owner);
1629 if (ret.Failed()) return ret;
1631 const Company *company = Company::Get(v->owner);
1632 bool iscustom = HasBit(p2, 16);
1633 bool ispercent = iscustom ? HasBit(p2, 17) : company->settings.vehicle.servint_ispercent;
1635 uint16 serv_int;
1636 if (iscustom) {
1637 serv_int = GB(p2, 0, 16);
1638 if (serv_int != GetServiceIntervalClamped(serv_int, ispercent)) return CommandError();
1639 } else {
1640 serv_int = CompanyServiceInterval(company, v->type);
1643 if (flags & DC_EXEC) {
1644 v->SetServiceInterval(serv_int);
1645 v->SetServiceIntervalIsCustom(iscustom);
1646 v->SetServiceIntervalIsPercent(ispercent);
1647 SetWindowDirty(WC_VEHICLE_DETAILS, v->index);
1650 return CommandCost();