Increase the number of road and tram subtypes to 32.
[openttd-joker.git] / src / autoreplace_cmd.cpp
bloba638ad71ef1b6a50a7b77ac094c85edeca9d517f
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 autoreplace_cmd.cpp Deals with autoreplace execution but not the setup */
12 #include "stdafx.h"
13 #include "company_func.h"
14 #include "train.h"
15 #include "command_func.h"
16 #include "engine_func.h"
17 #include "vehicle_func.h"
18 #include "autoreplace_func.h"
19 #include "autoreplace_gui.h"
20 #include "articulated_vehicles.h"
21 #include "tracerestrict.h"
22 #include "core/random_func.hpp"
23 #include "road.h"
25 #include "table/strings.h"
27 #include "safeguards.h"
29 extern void ChangeVehicleViewports(VehicleID from_index, VehicleID to_index);
30 extern void ChangeVehicleNews(VehicleID from_index, VehicleID to_index);
31 extern void ChangeVehicleViewWindow(VehicleID from_index, VehicleID to_index);
33 /**
34 * Figure out if two engines got at least one type of cargo in common (refitting if needed)
35 * @param engine_a one of the EngineIDs
36 * @param engine_b the other EngineID
37 * @param type the type of the engines
38 * @return true if they can both carry the same type of cargo (or at least one of them got no capacity at all)
40 static bool EnginesHaveCargoInCommon(EngineID engine_a, EngineID engine_b)
42 uint32 available_cargoes_a = GetUnionOfArticulatedRefitMasks(engine_a, true);
43 uint32 available_cargoes_b = GetUnionOfArticulatedRefitMasks(engine_b, true);
44 return (available_cargoes_a == 0 || available_cargoes_b == 0 || (available_cargoes_a & available_cargoes_b) != 0);
47 /**
48 * Checks some basic properties whether autoreplace is allowed
49 * @param from Origin engine
50 * @param to Destination engine
51 * @param company Company to check for
52 * @return true if autoreplace is allowed
54 bool CheckAutoreplaceValidity(EngineID from, EngineID to, CompanyID company)
56 assert(Engine::IsValidID(from) && Engine::IsValidID(to));
58 /* we can't replace an engine into itself (that would be autorenew) */
59 //if (from == to) return false;
61 const Engine *e_from = Engine::Get(from);
62 const Engine *e_to = Engine::Get(to);
63 VehicleType type = e_from->type;
65 /* check that the new vehicle type is available to the company and its type is the same as the original one */
66 if (!IsEngineBuildable(to, type, company)) return false;
68 switch (type) {
69 case VEH_TRAIN: {
70 /* make sure the railtypes are compatible */
71 if ((GetRailTypeInfo(e_from->u.rail.railtype)->compatible_railtypes & GetRailTypeInfo(e_to->u.rail.railtype)->compatible_railtypes) == 0) return false;
73 /* make sure we do not replace wagons with engines or vice versa */
74 if ((e_from->u.rail.railveh_type == RAILVEH_WAGON) != (e_to->u.rail.railveh_type == RAILVEH_WAGON)) return false;
75 break;
78 case VEH_ROAD:
79 /* make sure that we do not replace a tram with a normal road vehicles or vice versa */
80 if (HasBit(e_from->info.misc_flags, EF_ROAD_TRAM) != HasBit(e_to->info.misc_flags, EF_ROAD_TRAM)) return false;
82 /* make sure the roadtypes are compatible */
83 if ((GetRoadTypeInfo(e_from->GetRoadType())->powered_roadtypes & GetRoadTypeInfo(e_to->GetRoadType())->powered_roadtypes) == 0) return false;
84 break;
86 case VEH_AIRCRAFT:
87 /* make sure that we do not replace a plane with a helicopter or vice versa */
88 if ((e_from->u.air.subtype & AIR_CTOL) != (e_to->u.air.subtype & AIR_CTOL)) return false;
89 break;
91 default: break;
94 /* the engines needs to be able to carry the same cargo */
95 return EnginesHaveCargoInCommon(from, to);
98 /**
99 * Check the capacity of all vehicles in a chain and spread cargo if needed.
100 * @param v The vehicle to check.
101 * @pre You can only do this if the consist is not loading or unloading. It
102 * must not carry reserved cargo, nor cargo to be unloaded or transferred.
104 void CheckCargoCapacity(Vehicle *v)
106 assert(v == nullptr || v->First() == v);
108 for (Vehicle *src = v; src != nullptr; src = src->Next()) {
109 assert(src->cargo.TotalCount() == src->cargo.ActionCount(VehicleCargoList::MTA_KEEP));
111 /* Do we need to more cargo away? */
112 if (src->cargo.TotalCount() <= src->cargo_cap) continue;
114 /* We need to move a particular amount. Try that on the other vehicles. */
115 uint to_spread = src->cargo.TotalCount() - src->cargo_cap;
116 for (Vehicle *dest = v; dest != nullptr && to_spread != 0; dest = dest->Next()) {
117 assert(dest->cargo.TotalCount() == dest->cargo.ActionCount(VehicleCargoList::MTA_KEEP));
118 if (dest->cargo.TotalCount() >= dest->cargo_cap || dest->cargo_type != src->cargo_type) continue;
120 uint amount = min(to_spread, dest->cargo_cap - dest->cargo.TotalCount());
121 src->cargo.Shift(amount, &dest->cargo);
122 to_spread -= amount;
125 /* Any left-overs will be thrown away, but not their feeder share. */
126 if (src->cargo_cap < src->cargo.TotalCount()) src->cargo.Truncate(src->cargo.TotalCount() - src->cargo_cap);
131 * Transfer cargo from a single (articulated )old vehicle to the new vehicle chain
132 * @param old_veh Old vehicle that will be sold
133 * @param new_head Head of the completely constructed new vehicle chain
134 * @param part_of_chain The vehicle is part of a train
135 * @pre You can only do this if both consists are not loading or unloading.
136 * They must not carry reserved cargo, nor cargo to be unloaded or
137 * transferred.
139 static void TransferCargo(Vehicle *old_veh, Vehicle *new_head, bool part_of_chain)
141 assert(!part_of_chain || new_head->IsPrimaryVehicle());
142 /* Loop through source parts */
143 for (Vehicle *src = old_veh; src != nullptr; src = src->Next()) {
144 assert(src->cargo.TotalCount() == src->cargo.ActionCount(VehicleCargoList::MTA_KEEP));
145 if (!part_of_chain && src->type == VEH_TRAIN && src != old_veh && src != Train::From(old_veh)->other_multiheaded_part && !src->IsArticulatedPart()) {
146 /* Skip vehicles, which do not belong to old_veh */
147 src = src->GetLastEnginePart();
148 continue;
150 if (src->cargo_type >= NUM_CARGO || src->cargo.TotalCount() == 0) continue;
152 /* Find free space in the new chain */
153 for (Vehicle *dest = new_head; dest != nullptr && src->cargo.TotalCount() > 0; dest = dest->Next()) {
154 assert(dest->cargo.TotalCount() == dest->cargo.ActionCount(VehicleCargoList::MTA_KEEP));
155 if (!part_of_chain && dest->type == VEH_TRAIN && dest != new_head && dest != Train::From(new_head)->other_multiheaded_part && !dest->IsArticulatedPart()) {
156 /* Skip vehicles, which do not belong to new_head */
157 dest = dest->GetLastEnginePart();
158 continue;
160 if (dest->cargo_type != src->cargo_type) continue;
162 uint amount = min(src->cargo.TotalCount(), dest->cargo_cap - dest->cargo.TotalCount());
163 if (amount <= 0) continue;
165 src->cargo.Shift(amount, &dest->cargo);
169 /* Update train weight etc., the old vehicle will be sold anyway */
170 if (part_of_chain && new_head->type == VEH_TRAIN) Train::From(new_head)->ConsistChanged(CCF_LOADUNLOAD);
174 * Tests whether refit orders that applied to v will also apply to the new vehicle type
175 * @param v The vehicle to be replaced
176 * @param engine_type The type we want to replace with
177 * @return true iff all refit orders stay valid
179 static bool VerifyAutoreplaceRefitForOrders(const Vehicle *v, EngineID engine_type)
182 uint32 union_refit_mask_a = GetUnionOfArticulatedRefitMasks(v->engine_type, false);
183 uint32 union_refit_mask_b = GetUnionOfArticulatedRefitMasks(engine_type, false);
185 const Order *o;
186 const Vehicle *u = (v->type == VEH_TRAIN) ? v->First() : v;
187 FOR_VEHICLE_ORDERS(u, o) {
188 if (!o->IsRefit() || o->IsAutoRefit()) continue;
189 CargoID cargo_type = o->GetRefitCargo();
191 if (!HasBit(union_refit_mask_a, cargo_type)) continue;
192 if (!HasBit(union_refit_mask_b, cargo_type)) return false;
195 return true;
199 * Function to find what type of cargo to refit to when autoreplacing
200 * @param *v Original vehicle that is being replaced.
201 * @param engine_type The EngineID of the vehicle that is being replaced to
202 * @param part_of_chain The vehicle is part of a train
203 * @return The cargo type to replace to
204 * CT_NO_REFIT is returned if no refit is needed
205 * CT_INVALID is returned when both old and new vehicle got cargo capacity and refitting the new one to the old one's cargo type isn't possible
207 static CargoID GetNewCargoTypeForReplace(Vehicle *v, EngineID engine_type, bool part_of_chain)
209 uint32 available_cargo_types, union_mask;
210 GetArticulatedRefitMasks(engine_type, true, &union_mask, &available_cargo_types);
212 if (union_mask == 0) return CT_NO_REFIT; // Don't try to refit an engine with no cargo capacity
214 CargoID cargo_type;
215 if (IsArticulatedVehicleCarryingDifferentCargoes(v, &cargo_type)) return CT_INVALID; // We cannot refit to mixed cargoes in an automated way
217 if (cargo_type == CT_INVALID) {
218 if (v->type != VEH_TRAIN) return CT_NO_REFIT; // If the vehicle does not carry anything at all, every replacement is fine.
220 if (!part_of_chain) return CT_NO_REFIT;
222 /* the old engine didn't have cargo capacity, but the new one does
223 * now we will figure out what cargo the train is carrying and refit to fit this */
225 for (v = v->First(); v != nullptr; v = v->Next()) {
226 if (!v->GetEngine()->CanCarryCargo()) continue;
227 /* Now we found a cargo type being carried on the train and we will see if it is possible to carry to this one */
228 if (HasBit(available_cargo_types, v->cargo_type)) return v->cargo_type;
231 return CT_NO_REFIT; // We failed to find a cargo type on the old vehicle and we will not refit the new one
232 } else {
233 if (!HasBit(available_cargo_types, cargo_type)) return CT_INVALID; // We can't refit the vehicle to carry the cargo we want
235 if (part_of_chain && !VerifyAutoreplaceRefitForOrders(v, engine_type)) return CT_INVALID; // Some refit orders lose their effect
237 return cargo_type;
242 * Get the EngineID of the replacement for a vehicle
243 * @param v The vehicle to find a replacement for
244 * @param c The vehicle's owner (it's faster to forward the pointer than refinding it)
245 * @param always_replace Always replace, even if not old.
246 * @param same_type_only Only replace with same engine type.
247 * @param [out] e the EngineID of the replacement. INVALID_ENGINE if no replacement is found
248 * @return Error if the engine to build is not available
250 static CommandCost GetNewEngineType(const Vehicle *v, const Company *c, bool always_replace, bool same_type_only, EngineID &e)
252 assert(v->type != VEH_TRAIN || !v->IsArticulatedPart());
254 e = INVALID_ENGINE;
256 if (v->type == VEH_TRAIN && Train::From(v)->IsRearDualheaded()) {
257 /* we build the rear ends of multiheaded trains with the front ones */
258 return CommandCost();
261 if (!same_type_only) {
262 bool replace_when_old;
263 e = EngineReplacementForCompany(c, v->engine_type, v->group_id, &replace_when_old);
264 if (!always_replace && replace_when_old && !v->NeedsAutorenewing(c, false)) e = INVALID_ENGINE;
267 /* Autoreplace, if engine is available */
268 if (e != INVALID_ENGINE && IsEngineBuildable(e, v->type, _current_company)) {
269 return CommandCost();
272 /* Autorenew if needed */
273 if (v->NeedsAutorenewing(c)) e = v->engine_type;
275 /* Nothing to do or all is fine? */
276 if (e == INVALID_ENGINE || IsEngineBuildable(e, v->type, _current_company)) return CommandCost();
278 /* The engine we need is not available. Report error to user */
279 return CommandCost(STR_ERROR_RAIL_VEHICLE_NOT_AVAILABLE + v->type);
283 * Builds and refits a replacement vehicle
284 * Important: The old vehicle is still in the original vehicle chain (used for determining the cargo when the old vehicle did not carry anything, but the new one does)
285 * @param old_veh A single (articulated/multiheaded) vehicle that shall be replaced.
286 * @param new_vehicle Returns the newly build and refitted vehicle
287 * @param part_of_chain The vehicle is part of a train
288 * @param same_type_only Only replace with same engine type.
289 * @return cost or error
291 static CommandCost BuildReplacementVehicle(Vehicle *old_veh, Vehicle **new_vehicle, bool part_of_chain, bool same_type_only)
293 *new_vehicle = nullptr;
295 /* Shall the vehicle be replaced? */
296 const Company *c = Company::Get(_current_company);
297 EngineID e;
298 CommandCost cost = GetNewEngineType(old_veh, c, true, same_type_only, e);
299 if (cost.Failed()) return cost;
300 if (e == INVALID_ENGINE) return CommandCost(); // neither autoreplace is set, nor autorenew is triggered
302 /* Does it need to be refitted */
303 CargoID refit_cargo = GetNewCargoTypeForReplace(old_veh, e, part_of_chain);
304 if (refit_cargo == CT_INVALID) return CommandCost(); // incompatible cargoes
306 /* Build the new vehicle */
307 cost = DoCommand(old_veh->tile, e, 0, DC_EXEC | DC_AUTOREPLACE, GetCmdBuildVeh(old_veh));
308 if (cost.Failed()) return cost;
310 Vehicle *new_veh = Vehicle::Get(_new_vehicle_id);
311 *new_vehicle = new_veh;
313 /* Refit the vehicle if needed */
314 if (refit_cargo != CT_NO_REFIT) {
315 byte subtype = GetBestFittingSubType(old_veh, new_veh, refit_cargo);
317 cost.AddCost(DoCommand(0, new_veh->index, refit_cargo | (subtype << 8), DC_EXEC, GetCmdRefitVeh(new_veh)));
318 assert(cost.Succeeded()); // This should be ensured by GetNewCargoTypeForReplace()
321 /* Try to reverse the vehicle, but do not care if it fails as the new type might not be reversible */
322 if (new_veh->type == VEH_TRAIN && HasBit(Train::From(old_veh)->flags, VRF_REVERSE_DIRECTION)) {
323 DoCommand(0, new_veh->index, true, DC_EXEC, CMD_REVERSE_TRAIN_DIRECTION);
326 return cost;
330 * Issue a start/stop command
331 * @param v a vehicle
332 * @param evaluate_callback shall the start/stop callback be evaluated?
333 * @return success or error
335 static inline CommandCost CmdStartStopVehicle(const Vehicle *v, bool evaluate_callback)
337 return DoCommand(0, v->index, evaluate_callback ? 1 : 0, DC_EXEC | DC_AUTOREPLACE, CMD_START_STOP_VEHICLE);
341 * Issue a train vehicle move command
342 * @param v The vehicle to move
343 * @param after The vehicle to insert 'v' after, or nullptr to start new chain
344 * @param flags the command flags to use
345 * @param whole_chain move all vehicles following 'v' (true), or only 'v' (false)
346 * @return success or error
348 static inline CommandCost CmdMoveVehicle(const Vehicle *v, const Vehicle *after, DoCommandFlag flags, bool whole_chain)
350 return DoCommand(0, v->index | (whole_chain ? 1 : 0) << 20, after != nullptr ? after->index : INVALID_VEHICLE, flags | DC_NO_CARGO_CAP_CHECK, CMD_MOVE_RAIL_VEHICLE);
354 * Copy head specific things to the new vehicle chain after it was successfully constructed
355 * @param old_head The old front vehicle (no wagons attached anymore)
356 * @param new_head The new head of the completely replaced vehicle chain
357 * @param flags the command flags to use
359 CommandCost CopyHeadSpecificThings(Vehicle *old_head, Vehicle *new_head, DoCommandFlag flags)
361 CommandCost cost = CommandCost();
363 /* Share orders */
364 if (cost.Succeeded() && old_head != new_head) cost.AddCost(DoCommand(0, new_head->index | CO_SHARE << 30, old_head->index, DC_EXEC, CMD_CLONE_ORDER));
366 /* Copy group membership */
367 if (cost.Succeeded() && old_head != new_head) cost.AddCost(DoCommand(0, old_head->group_id, new_head->index, DC_EXEC, CMD_ADD_VEHICLE_GROUP));
369 /* Perform start/stop check whether the new vehicle suits newgrf restrictions etc. */
370 if (cost.Succeeded()) {
371 /* Start the vehicle, might be denied by certain things */
372 assert((new_head->vehstatus & VS_STOPPED) != 0);
373 cost.AddCost(CmdStartStopVehicle(new_head, true));
375 /* Stop the vehicle again, but do not care about evil newgrfs allowing starting but not stopping :p */
376 if (cost.Succeeded()) cost.AddCost(CmdStartStopVehicle(new_head, false));
379 /* Last do those things which do never fail (resp. we do not care about), but which are not undo-able */
380 if (cost.Succeeded() && old_head != new_head && (flags & DC_EXEC) != 0) {
381 /* Copy other things which cannot be copied by a command and which shall not stay resetted from the build vehicle command */
382 new_head->CopyVehicleConfigAndStatistics(old_head);
384 /* Switch vehicle windows/news to the new vehicle, so they are not closed/deleted when the old vehicle is sold */
385 ChangeVehicleViewports(old_head->index, new_head->index);
386 ChangeVehicleViewWindow(old_head->index, new_head->index);
387 ChangeVehicleNews(old_head->index, new_head->index);
390 return cost;
394 * Replace a single unit in a free wagon chain
395 * @param single_unit vehicle to let autoreplace/renew operator on
396 * @param flags command flags
397 * @param nothing_to_do is set to 'false' when something was done (only valid when not failed)
398 * @param same_type_only Only replace with same engine type.
399 * @return cost or error
401 static CommandCost ReplaceFreeUnit(Vehicle **single_unit, DoCommandFlag flags, bool *nothing_to_do, bool same_type_only)
403 Train *old_v = Train::From(*single_unit);
404 assert(!old_v->IsArticulatedPart() && !old_v->IsRearDualheaded());
406 CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES, 0);
408 /* Build and refit replacement vehicle */
409 Vehicle *new_v = nullptr;
410 cost.AddCost(BuildReplacementVehicle(old_v, &new_v, false, same_type_only));
412 /* Was a new vehicle constructed? */
413 if (cost.Succeeded() && new_v != nullptr) {
414 *nothing_to_do = false;
416 if ((flags & DC_EXEC) != 0) {
417 /* Move the new vehicle behind the old */
418 CmdMoveVehicle(new_v, old_v, DC_EXEC, false);
420 /* Take over cargo
421 * Note: We do only transfer cargo from the old to the new vehicle.
422 * I.e. we do not transfer remaining cargo to other vehicles.
423 * Else you would also need to consider moving cargo to other free chains,
424 * or doing the same in ReplaceChain(), which would be quite troublesome.
426 TransferCargo(old_v, new_v, false);
428 *single_unit = new_v;
431 /* Sell the old vehicle */
432 cost.AddCost(DoCommand(0, old_v->index, 0, flags, GetCmdSellVeh(old_v)));
434 /* If we are not in DC_EXEC undo everything */
435 if ((flags & DC_EXEC) == 0) {
436 DoCommand(0, new_v->index, 0, DC_EXEC, GetCmdSellVeh(new_v));
440 return cost;
444 * Replace a whole vehicle chain
445 * @param chain vehicle chain to let autoreplace/renew operator on
446 * @param flags command flags
447 * @param wagon_removal remove wagons when the resulting chain occupies more tiles than the old did
448 * @param nothing_to_do is set to 'false' when something was done (only valid when not failed)
449 * @param same_type_only Only replace with same engine type.
450 * @return cost or error
452 static CommandCost ReplaceChain(Vehicle **chain, DoCommandFlag flags, bool wagon_removal, bool *nothing_to_do, bool same_type_only)
454 Vehicle *old_head = *chain;
455 assert(old_head->IsPrimaryVehicle());
457 CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES, 0);
459 if (old_head->type == VEH_TRAIN) {
460 /* Store the length of the old vehicle chain, rounded up to whole tiles */
461 uint16 old_total_length = CeilDiv(Train::From(old_head)->gcache.cached_total_length, TILE_SIZE) * TILE_SIZE;
463 int num_units = 0; ///< Number of units in the chain
464 for (Train *w = Train::From(old_head); w != nullptr; w = w->GetNextUnit()) num_units++;
466 Train **old_vehs = CallocT<Train *>(num_units); ///< Will store vehicles of the old chain in their order
467 Train **new_vehs = CallocT<Train *>(num_units); ///< New vehicles corresponding to old_vehs or nullptr if no replacement
468 Money *new_costs = MallocT<Money>(num_units); ///< Costs for buying and refitting the new vehicles
470 /* Collect vehicles and build replacements
471 * Note: The replacement vehicles can only successfully build as long as the old vehicles are still in their chain */
472 int i;
473 Train *w;
474 for (w = Train::From(old_head), i = 0; w != nullptr; w = w->GetNextUnit(), i++) {
475 assert(i < num_units);
476 old_vehs[i] = w;
478 CommandCost ret = BuildReplacementVehicle(old_vehs[i], (Vehicle**)&new_vehs[i], true, same_type_only);
479 cost.AddCost(ret);
480 if (cost.Failed()) break;
482 new_costs[i] = ret.GetCost();
483 if (new_vehs[i] != nullptr) *nothing_to_do = false;
485 Train *new_head = (new_vehs[0] != nullptr ? new_vehs[0] : old_vehs[0]);
487 /* Note: When autoreplace has already failed here, old_vehs[] is not completely initialized. But it is also not needed. */
488 if (cost.Succeeded()) {
489 /* Separate the head, so we can start constructing the new chain */
490 Train *second = Train::From(old_head)->GetNextUnit();
491 if (second != nullptr) cost.AddCost(CmdMoveVehicle(second, nullptr, DC_EXEC | DC_AUTOREPLACE, true));
493 assert(Train::From(new_head)->GetNextUnit() == nullptr);
495 /* Append engines to the new chain
496 * We do this from back to front, so that the head of the temporary vehicle chain does not change all the time.
497 * That way we also have less trouble when exceeding the unitnumber limit.
498 * OTOH the vehicle attach callback is more expensive this way :s */
499 Train *last_engine = nullptr; ///< Shall store the last engine unit after this step
500 if (cost.Succeeded()) {
501 for (int i = num_units - 1; i > 0; i--) {
502 Train *append = (new_vehs[i] != nullptr ? new_vehs[i] : old_vehs[i]);
504 if (RailVehInfo(append->engine_type)->railveh_type == RAILVEH_WAGON) continue;
506 if (new_vehs[i] != nullptr) {
507 /* Move the old engine to a separate row with DC_AUTOREPLACE. Else
508 * moving the wagon in front may fail later due to unitnumber limit.
509 * (We have to attach wagons without DC_AUTOREPLACE.) */
510 CmdMoveVehicle(old_vehs[i], nullptr, DC_EXEC | DC_AUTOREPLACE, false);
513 if (last_engine == nullptr) last_engine = append;
514 cost.AddCost(CmdMoveVehicle(append, new_head, DC_EXEC, false));
515 if (cost.Failed()) break;
517 if (last_engine == nullptr) last_engine = new_head;
520 /* When wagon removal is enabled and the new engines without any wagons are already longer than the old, we have to fail */
521 if (cost.Succeeded() && wagon_removal && new_head->gcache.cached_total_length > old_total_length) cost = CommandCost(STR_ERROR_TRAIN_TOO_LONG_AFTER_REPLACEMENT);
523 /* Append/insert wagons into the new vehicle chain
524 * We do this from back to front, so we can stop when wagon removal or maximum train length (i.e. from mammoth-train setting) is triggered.
526 if (cost.Succeeded()) {
527 for (int i = num_units - 1; i > 0; i--) {
528 assert(last_engine != nullptr);
529 Vehicle *append = (new_vehs[i] != nullptr ? new_vehs[i] : old_vehs[i]);
531 if (RailVehInfo(append->engine_type)->railveh_type == RAILVEH_WAGON) {
532 /* Insert wagon after 'last_engine' */
533 CommandCost res = CmdMoveVehicle(append, last_engine, DC_EXEC, false);
535 /* When we allow removal of wagons, either the move failing due
536 * to the train becoming too long, or the train becoming longer
537 * would move the vehicle to the empty vehicle chain. */
538 if (wagon_removal && (res.Failed() ? res.GetErrorMessage() == STR_ERROR_TRAIN_TOO_LONG : new_head->gcache.cached_total_length > old_total_length)) {
539 CmdMoveVehicle(append, nullptr, DC_EXEC | DC_AUTOREPLACE, false);
540 break;
543 cost.AddCost(res);
544 if (cost.Failed()) break;
545 } else {
546 /* We have reached 'last_engine', continue with the next engine towards the front */
547 assert(append == last_engine);
548 last_engine = last_engine->GetPrevUnit();
553 /* Sell superfluous new vehicles that could not be inserted. */
554 if (cost.Succeeded() && wagon_removal) {
555 assert(new_head->gcache.cached_total_length <= _settings_game.vehicle.max_train_length * TILE_SIZE);
556 for (int i = 1; i < num_units; i++) {
557 Vehicle *wagon = new_vehs[i];
558 if (wagon == nullptr) continue;
559 if (wagon->First() == new_head) break;
561 assert(RailVehInfo(wagon->engine_type)->railveh_type == RAILVEH_WAGON);
563 /* Sell wagon */
564 CommandCost ret = DoCommand(0, wagon->index, 0, DC_EXEC, GetCmdSellVeh(wagon));
565 assert(ret.Succeeded());
566 new_vehs[i] = nullptr;
568 /* Revert the money subtraction when the vehicle was built.
569 * This value is different from the sell value, esp. because of refitting */
570 cost.AddCost(-new_costs[i]);
574 /* The new vehicle chain is constructed, now take over orders and everything... */
575 if (cost.Succeeded()) cost.AddCost(CopyHeadSpecificThings(old_head, new_head, flags));
577 if (cost.Succeeded()) {
578 /* Success ! */
579 if ((flags & DC_EXEC) != 0 && new_head != old_head) {
580 *chain = new_head;
581 if (HasBit(Train::From(old_head)->flags, VRF_HAVE_SLOT)) {
582 TraceRestrictTransferVehicleOccupantInAllSlots(old_head->index, new_head->index);
583 ClrBit(Train::From(old_head)->flags, VRF_HAVE_SLOT);
584 SetBit(Train::From(new_head)->flags, VRF_HAVE_SLOT);
588 /* Transfer cargo of old vehicles and sell them */
589 for (int i = 0; i < num_units; i++) {
590 Vehicle *w = old_vehs[i];
591 /* Is the vehicle again part of the new chain?
592 * Note: We cannot test 'new_vehs[i] != nullptr' as wagon removal might cause to remove both */
593 if (w->First() == new_head) continue;
595 if ((flags & DC_EXEC) != 0) TransferCargo(w, new_head, true);
597 /* Sell the vehicle.
598 * Note: This might temporarly construct new trains, so use DC_AUTOREPLACE to prevent
599 * it from failing due to engine limits. */
600 cost.AddCost(DoCommand(0, w->index, 0, flags | DC_AUTOREPLACE, GetCmdSellVeh(w)));
601 if ((flags & DC_EXEC) != 0) {
602 old_vehs[i] = nullptr;
603 if (i == 0) old_head = nullptr;
607 if ((flags & DC_EXEC) != 0) CheckCargoCapacity(new_head);
610 /* If we are not in DC_EXEC undo everything, i.e. rearrange old vehicles.
611 * We do this from back to front, so that the head of the temporary vehicle chain does not change all the time.
612 * Note: The vehicle attach callback is disabled here :) */
613 if ((flags & DC_EXEC) == 0) {
614 /* Separate the head, so we can reattach the old vehicles */
615 Train *second = Train::From(old_head)->GetNextUnit();
616 if (second != nullptr) CmdMoveVehicle(second, nullptr, DC_EXEC | DC_AUTOREPLACE, true);
618 assert(Train::From(old_head)->GetNextUnit() == nullptr);
620 for (int i = num_units - 1; i > 0; i--) {
621 CommandCost ret = CmdMoveVehicle(old_vehs[i], old_head, DC_EXEC | DC_AUTOREPLACE, false);
622 assert(ret.Succeeded());
627 /* Finally undo buying of new vehicles */
628 if ((flags & DC_EXEC) == 0) {
629 for (int i = num_units - 1; i >= 0; i--) {
630 if (new_vehs[i] != nullptr) {
631 DoCommand(0, new_vehs[i]->index, 0, DC_EXEC, GetCmdSellVeh(new_vehs[i]));
632 new_vehs[i] = nullptr;
637 free(old_vehs);
638 free(new_vehs);
639 free(new_costs);
640 } else {
641 /* Build and refit replacement vehicle */
642 Vehicle *new_head = nullptr;
643 cost.AddCost(BuildReplacementVehicle(old_head, &new_head, true, same_type_only));
645 /* Was a new vehicle constructed? */
646 if (cost.Succeeded() && new_head != nullptr) {
647 *nothing_to_do = false;
649 /* The new vehicle is constructed, now take over orders and everything... */
650 cost.AddCost(CopyHeadSpecificThings(old_head, new_head, flags));
652 if (cost.Succeeded()) {
653 /* The new vehicle is constructed, now take over cargo */
654 if ((flags & DC_EXEC) != 0) {
655 TransferCargo(old_head, new_head, true);
656 *chain = new_head;
659 /* Sell the old vehicle */
660 cost.AddCost(DoCommand(0, old_head->index, 0, flags, GetCmdSellVeh(old_head)));
663 /* If we are not in DC_EXEC undo everything */
664 if ((flags & DC_EXEC) == 0) {
665 DoCommand(0, new_head->index, 0, DC_EXEC, GetCmdSellVeh(new_head));
670 return cost;
674 * Autoreplaces a vehicle
675 * Trains are replaced as a whole chain, free wagons in depot are replaced on their own
676 * @param tile not used
677 * @param flags type of operation
678 * @param p1 Index of vehicle
679 * @param p2 packed data
680 * - bit 0 = Autoreplace with same type only
681 * @param text unused
682 * @return the cost of this operation or an error
684 CommandCost CmdAutoreplaceVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
686 Vehicle *v = Vehicle::GetIfValid(p1);
687 if (v == nullptr) return CommandError();
689 CommandCost ret = CheckOwnership(v->owner);
690 if (ret.Failed()) return ret;
692 if (!v->IsChainInDepot()) return CommandError();
693 if (v->vehstatus & VS_CRASHED) return CommandError();
695 bool free_wagon = false;
696 if (v->type == VEH_TRAIN) {
697 Train *t = Train::From(v);
698 if (t->IsArticulatedPart() || t->IsRearDualheaded()) return CommandError();
699 free_wagon = !t->IsFrontEngine();
700 if (free_wagon && t->First()->IsFrontEngine()) return CommandError();
701 } else {
702 if (!v->IsPrimaryVehicle()) return CommandError();
705 const Company *c = Company::Get(_current_company);
706 bool wagon_removal = c->settings.renew_keep_length;
707 bool same_type_only = HasBit(p2, 0);
709 /* Test whether any replacement is set, before issuing a whole lot of commands that would end in nothing changed */
710 Vehicle *w = v;
711 bool any_replacements = false;
712 while (w != nullptr) {
713 EngineID e;
714 CommandCost cost = GetNewEngineType(w, c, false, same_type_only, e);
715 if (cost.Failed()) return cost;
716 any_replacements |= (e != INVALID_ENGINE);
717 w = (!free_wagon && w->type == VEH_TRAIN ? Train::From(w)->GetNextUnit() : nullptr);
720 CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES, 0);
721 bool nothing_to_do = true;
723 if (any_replacements) {
724 bool was_stopped = free_wagon || ((v->vehstatus & VS_STOPPED) != 0);
726 /* Stop the vehicle */
727 if (!was_stopped) cost.AddCost(CmdStartStopVehicle(v, true));
728 if (cost.Failed()) return cost;
730 assert(free_wagon || v->IsStoppedInDepot());
732 /* We have to construct the new vehicle chain to test whether it is valid.
733 * Vehicle construction needs random bits, so we have to save the random seeds
734 * to prevent desyncs and to replay newgrf callbacks during DC_EXEC */
735 SavedRandomSeeds saved_seeds;
736 SaveRandomSeeds(&saved_seeds);
737 if (free_wagon) {
738 cost.AddCost(ReplaceFreeUnit(&v, flags & ~DC_EXEC, &nothing_to_do, same_type_only));
739 } else {
740 cost.AddCost(ReplaceChain(&v, flags & ~DC_EXEC, wagon_removal, &nothing_to_do, same_type_only));
742 RestoreRandomSeeds(saved_seeds);
744 if (cost.Succeeded() && (flags & DC_EXEC) != 0) {
745 CommandCost ret;
746 if (free_wagon) {
747 ret = ReplaceFreeUnit(&v, flags, &nothing_to_do, same_type_only);
748 } else {
749 ret = ReplaceChain(&v, flags, wagon_removal, &nothing_to_do, same_type_only);
751 assert(ret.Succeeded() && ret.GetCost() == cost.GetCost());
754 /* Restart the vehicle */
755 if (!was_stopped) cost.AddCost(CmdStartStopVehicle(v, false));
758 if (cost.Succeeded() && nothing_to_do) cost = CommandCost(STR_ERROR_AUTOREPLACE_NOTHING_TO_DO);
759 return cost;
763 * Change engine renewal parameters
764 * @param tile unused
765 * @param flags operation to perform
766 * @param p1 packed data
767 * - bit 0 = replace when engine gets old?
768 * - bits 16-31 = engine group
769 * @param p2 packed data
770 * - bits 0-15 = old engine type
771 * - bits 16-31 = new engine type
772 * @param text unused
773 * @return the cost of this operation or an error
775 CommandCost CmdSetAutoReplace(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
777 Company *c = Company::GetIfValid(_current_company);
778 if (c == nullptr) return CommandError();
780 EngineID old_engine_type = GB(p2, 0, 16);
781 EngineID new_engine_type = GB(p2, 16, 16);
782 GroupID id_g = GB(p1, 16, 16);
783 CommandCost cost;
785 if (Group::IsValidID(id_g) ? Group::Get(id_g)->owner != _current_company : !IsAllGroupID(id_g) && !IsDefaultGroupID(id_g)) return CommandError();
786 if (!Engine::IsValidID(old_engine_type)) return CommandError();
788 if (new_engine_type != INVALID_ENGINE) {
789 if (!Engine::IsValidID(new_engine_type)) return CommandError();
790 if (!CheckAutoreplaceValidity(old_engine_type, new_engine_type, _current_company)) return CommandError();
792 cost = AddEngineReplacementForCompany(c, old_engine_type, new_engine_type, id_g, HasBit(p1, 0), flags);
793 } else {
794 cost = RemoveEngineReplacementForCompany(c, old_engine_type, id_g, flags);
797 if (flags & DC_EXEC) {
798 GroupStatistics::UpdateAutoreplace(_current_company);
799 if (IsLocalCompany()) SetWindowDirty(WC_REPLACE_VEHICLE, Engine::Get(old_engine_type)->type);
801 if ((flags & DC_EXEC) && IsLocalCompany()) InvalidateAutoreplaceWindow(old_engine_type, id_g);
803 return cost;