Codechange: Un-bitstuff commands taking a ClientID (i.e. CMD_CLIENT_ID).
[openttd-github.git] / src / autoreplace_cmd.cpp
blob6a8937cb65a122068ff64026d0c7deb9de351fd9
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 autoreplace_cmd.cpp Deals with autoreplace execution but not the setup */
10 #include "stdafx.h"
11 #include "company_func.h"
12 #include "train.h"
13 #include "command_func.h"
14 #include "engine_func.h"
15 #include "vehicle_func.h"
16 #include "autoreplace_func.h"
17 #include "autoreplace_gui.h"
18 #include "articulated_vehicles.h"
19 #include "core/random_func.hpp"
20 #include "vehiclelist.h"
21 #include "road.h"
22 #include "ai/ai.hpp"
23 #include "news_func.h"
24 #include "strings_func.h"
25 #include "autoreplace_cmd.h"
26 #include "group_cmd.h"
27 #include "order_cmd.h"
28 #include "train_cmd.h"
29 #include "vehicle_cmd.h"
31 #include "table/strings.h"
33 #include "safeguards.h"
35 extern void ChangeVehicleViewports(VehicleID from_index, VehicleID to_index);
36 extern void ChangeVehicleNews(VehicleID from_index, VehicleID to_index);
37 extern void ChangeVehicleViewWindow(VehicleID from_index, VehicleID to_index);
39 /**
40 * Figure out if two engines got at least one type of cargo in common (refitting if needed)
41 * @param engine_a one of the EngineIDs
42 * @param engine_b the other EngineID
43 * @return true if they can both carry the same type of cargo (or at least one of them got no capacity at all)
45 static bool EnginesHaveCargoInCommon(EngineID engine_a, EngineID engine_b)
47 CargoTypes available_cargoes_a = GetUnionOfArticulatedRefitMasks(engine_a, true);
48 CargoTypes available_cargoes_b = GetUnionOfArticulatedRefitMasks(engine_b, true);
49 return (available_cargoes_a == 0 || available_cargoes_b == 0 || (available_cargoes_a & available_cargoes_b) != 0);
52 /**
53 * Checks some basic properties whether autoreplace is allowed
54 * @param from Origin engine
55 * @param to Destination engine
56 * @param company Company to check for
57 * @return true if autoreplace is allowed
59 bool CheckAutoreplaceValidity(EngineID from, EngineID to, CompanyID company)
61 assert(Engine::IsValidID(from) && Engine::IsValidID(to));
63 /* we can't replace an engine into itself (that would be autorenew) */
64 if (from == to) return false;
66 const Engine *e_from = Engine::Get(from);
67 const Engine *e_to = Engine::Get(to);
68 VehicleType type = e_from->type;
70 /* check that the new vehicle type is available to the company and its type is the same as the original one */
71 if (!IsEngineBuildable(to, type, company)) return false;
73 switch (type) {
74 case VEH_TRAIN: {
75 /* make sure the railtypes are compatible */
76 if ((GetRailTypeInfo(e_from->u.rail.railtype)->compatible_railtypes & GetRailTypeInfo(e_to->u.rail.railtype)->compatible_railtypes) == 0) return false;
78 /* make sure we do not replace wagons with engines or vice versa */
79 if ((e_from->u.rail.railveh_type == RAILVEH_WAGON) != (e_to->u.rail.railveh_type == RAILVEH_WAGON)) return false;
80 break;
83 case VEH_ROAD:
84 /* make sure the roadtypes are compatible */
85 if ((GetRoadTypeInfo(e_from->u.road.roadtype)->powered_roadtypes & GetRoadTypeInfo(e_to->u.road.roadtype)->powered_roadtypes) == ROADTYPES_NONE) return false;
87 /* make sure that we do not replace a tram with a normal road vehicles or vice versa */
88 if (HasBit(e_from->info.misc_flags, EF_ROAD_TRAM) != HasBit(e_to->info.misc_flags, EF_ROAD_TRAM)) return false;
89 break;
91 case VEH_AIRCRAFT:
92 /* make sure that we do not replace a plane with a helicopter or vice versa */
93 if ((e_from->u.air.subtype & AIR_CTOL) != (e_to->u.air.subtype & AIR_CTOL)) return false;
94 break;
96 default: break;
99 /* the engines needs to be able to carry the same cargo */
100 return EnginesHaveCargoInCommon(from, to);
104 * Check the capacity of all vehicles in a chain and spread cargo if needed.
105 * @param v The vehicle to check.
106 * @pre You can only do this if the consist is not loading or unloading. It
107 * must not carry reserved cargo, nor cargo to be unloaded or transferred.
109 void CheckCargoCapacity(Vehicle *v)
111 assert(v == nullptr || v->First() == v);
113 for (Vehicle *src = v; src != nullptr; src = src->Next()) {
114 assert(src->cargo.TotalCount() == src->cargo.ActionCount(VehicleCargoList::MTA_KEEP));
116 /* Do we need to more cargo away? */
117 if (src->cargo.TotalCount() <= src->cargo_cap) continue;
119 /* We need to move a particular amount. Try that on the other vehicles. */
120 uint to_spread = src->cargo.TotalCount() - src->cargo_cap;
121 for (Vehicle *dest = v; dest != nullptr && to_spread != 0; dest = dest->Next()) {
122 assert(dest->cargo.TotalCount() == dest->cargo.ActionCount(VehicleCargoList::MTA_KEEP));
123 if (dest->cargo.TotalCount() >= dest->cargo_cap || dest->cargo_type != src->cargo_type) continue;
125 uint amount = std::min(to_spread, dest->cargo_cap - dest->cargo.TotalCount());
126 src->cargo.Shift(amount, &dest->cargo);
127 to_spread -= amount;
130 /* Any left-overs will be thrown away, but not their feeder share. */
131 if (src->cargo_cap < src->cargo.TotalCount()) src->cargo.Truncate(src->cargo.TotalCount() - src->cargo_cap);
136 * Transfer cargo from a single (articulated )old vehicle to the new vehicle chain
137 * @param old_veh Old vehicle that will be sold
138 * @param new_head Head of the completely constructed new vehicle chain
139 * @param part_of_chain The vehicle is part of a train
140 * @pre You can only do this if both consists are not loading or unloading.
141 * They must not carry reserved cargo, nor cargo to be unloaded or
142 * transferred.
144 static void TransferCargo(Vehicle *old_veh, Vehicle *new_head, bool part_of_chain)
146 assert(!part_of_chain || new_head->IsPrimaryVehicle());
147 /* Loop through source parts */
148 for (Vehicle *src = old_veh; src != nullptr; src = src->Next()) {
149 assert(src->cargo.TotalCount() == src->cargo.ActionCount(VehicleCargoList::MTA_KEEP));
150 if (!part_of_chain && src->type == VEH_TRAIN && src != old_veh && src != Train::From(old_veh)->other_multiheaded_part && !src->IsArticulatedPart()) {
151 /* Skip vehicles, which do not belong to old_veh */
152 src = src->GetLastEnginePart();
153 continue;
155 if (src->cargo_type >= NUM_CARGO || src->cargo.TotalCount() == 0) continue;
157 /* Find free space in the new chain */
158 for (Vehicle *dest = new_head; dest != nullptr && src->cargo.TotalCount() > 0; dest = dest->Next()) {
159 assert(dest->cargo.TotalCount() == dest->cargo.ActionCount(VehicleCargoList::MTA_KEEP));
160 if (!part_of_chain && dest->type == VEH_TRAIN && dest != new_head && dest != Train::From(new_head)->other_multiheaded_part && !dest->IsArticulatedPart()) {
161 /* Skip vehicles, which do not belong to new_head */
162 dest = dest->GetLastEnginePart();
163 continue;
165 if (dest->cargo_type != src->cargo_type) continue;
167 uint amount = std::min(src->cargo.TotalCount(), dest->cargo_cap - dest->cargo.TotalCount());
168 if (amount <= 0) continue;
170 src->cargo.Shift(amount, &dest->cargo);
174 /* Update train weight etc., the old vehicle will be sold anyway */
175 if (part_of_chain && new_head->type == VEH_TRAIN) Train::From(new_head)->ConsistChanged(CCF_LOADUNLOAD);
179 * Tests whether refit orders that applied to v will also apply to the new vehicle type
180 * @param v The vehicle to be replaced
181 * @param engine_type The type we want to replace with
182 * @return true iff all refit orders stay valid
184 static bool VerifyAutoreplaceRefitForOrders(const Vehicle *v, EngineID engine_type)
186 CargoTypes union_refit_mask_a = GetUnionOfArticulatedRefitMasks(v->engine_type, false);
187 CargoTypes union_refit_mask_b = GetUnionOfArticulatedRefitMasks(engine_type, false);
189 const Vehicle *u = (v->type == VEH_TRAIN) ? v->First() : v;
190 for (const Order *o : u->Orders()) {
191 if (!o->IsRefit() || o->IsAutoRefit()) continue;
192 CargoID cargo_type = o->GetRefitCargo();
194 if (!HasBit(union_refit_mask_a, cargo_type)) continue;
195 if (!HasBit(union_refit_mask_b, cargo_type)) return false;
198 return true;
202 * Gets the index of the first refit order that is incompatible with the requested engine type
203 * @param v The vehicle to be replaced
204 * @param engine_type The type we want to replace with
205 * @return index of the incompatible order or -1 if none were found
207 static int GetIncompatibleRefitOrderIdForAutoreplace(const Vehicle *v, EngineID engine_type)
209 CargoTypes union_refit_mask = GetUnionOfArticulatedRefitMasks(engine_type, false);
211 const Order *o;
212 const Vehicle *u = (v->type == VEH_TRAIN) ? v->First() : v;
214 const OrderList *orders = u->orders.list;
215 if (orders == nullptr) return -1;
216 for (VehicleOrderID i = 0; i < orders->GetNumOrders(); i++) {
217 o = orders->GetOrderAt(i);
218 if (!o->IsRefit()) continue;
219 if (!HasBit(union_refit_mask, o->GetRefitCargo())) return i;
222 return -1;
226 * Function to find what type of cargo to refit to when autoreplacing
227 * @param *v Original vehicle that is being replaced.
228 * @param engine_type The EngineID of the vehicle that is being replaced to
229 * @param part_of_chain The vehicle is part of a train
230 * @return The cargo type to replace to
231 * CT_NO_REFIT is returned if no refit is needed
232 * 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
234 static CargoID GetNewCargoTypeForReplace(Vehicle *v, EngineID engine_type, bool part_of_chain)
236 CargoTypes available_cargo_types, union_mask;
237 GetArticulatedRefitMasks(engine_type, true, &union_mask, &available_cargo_types);
239 if (union_mask == 0) return CT_NO_REFIT; // Don't try to refit an engine with no cargo capacity
241 CargoID cargo_type;
242 if (IsArticulatedVehicleCarryingDifferentCargoes(v, &cargo_type)) return CT_INVALID; // We cannot refit to mixed cargoes in an automated way
244 if (cargo_type == CT_INVALID) {
245 if (v->type != VEH_TRAIN) return CT_NO_REFIT; // If the vehicle does not carry anything at all, every replacement is fine.
247 if (!part_of_chain) return CT_NO_REFIT;
249 /* the old engine didn't have cargo capacity, but the new one does
250 * now we will figure out what cargo the train is carrying and refit to fit this */
252 for (v = v->First(); v != nullptr; v = v->Next()) {
253 if (!v->GetEngine()->CanCarryCargo()) continue;
254 /* Now we found a cargo type being carried on the train and we will see if it is possible to carry to this one */
255 if (HasBit(available_cargo_types, v->cargo_type)) return v->cargo_type;
258 return CT_NO_REFIT; // We failed to find a cargo type on the old vehicle and we will not refit the new one
259 } else {
260 if (!HasBit(available_cargo_types, cargo_type)) return CT_INVALID; // We can't refit the vehicle to carry the cargo we want
262 if (part_of_chain && !VerifyAutoreplaceRefitForOrders(v, engine_type)) return CT_INVALID; // Some refit orders lose their effect
264 return cargo_type;
269 * Get the EngineID of the replacement for a vehicle
270 * @param v The vehicle to find a replacement for
271 * @param c The vehicle's owner (it's faster to forward the pointer than refinding it)
272 * @param always_replace Always replace, even if not old.
273 * @param[out] e the EngineID of the replacement. INVALID_ENGINE if no replacement is found
274 * @return Error if the engine to build is not available
276 static CommandCost GetNewEngineType(const Vehicle *v, const Company *c, bool always_replace, EngineID &e)
278 assert(v->type != VEH_TRAIN || !v->IsArticulatedPart());
280 e = INVALID_ENGINE;
282 if (v->type == VEH_TRAIN && Train::From(v)->IsRearDualheaded()) {
283 /* we build the rear ends of multiheaded trains with the front ones */
284 return CommandCost();
287 bool replace_when_old;
288 e = EngineReplacementForCompany(c, v->engine_type, v->group_id, &replace_when_old);
289 if (!always_replace && replace_when_old && !v->NeedsAutorenewing(c, false)) e = INVALID_ENGINE;
291 /* Autoreplace, if engine is available */
292 if (e != INVALID_ENGINE && IsEngineBuildable(e, v->type, _current_company)) {
293 return CommandCost();
296 /* Autorenew if needed */
297 if (v->NeedsAutorenewing(c)) e = v->engine_type;
299 /* Nothing to do or all is fine? */
300 if (e == INVALID_ENGINE || IsEngineBuildable(e, v->type, _current_company)) return CommandCost();
302 /* The engine we need is not available. Report error to user */
303 return CommandCost(STR_ERROR_RAIL_VEHICLE_NOT_AVAILABLE + v->type);
307 * Builds and refits a replacement vehicle
308 * 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)
309 * @param old_veh A single (articulated/multiheaded) vehicle that shall be replaced.
310 * @param new_vehicle Returns the newly build and refitted vehicle
311 * @param part_of_chain The vehicle is part of a train
312 * @return cost or error
314 static CommandCost BuildReplacementVehicle(Vehicle *old_veh, Vehicle **new_vehicle, bool part_of_chain)
316 *new_vehicle = nullptr;
318 /* Shall the vehicle be replaced? */
319 const Company *c = Company::Get(_current_company);
320 EngineID e;
321 CommandCost cost = GetNewEngineType(old_veh, c, true, e);
322 if (cost.Failed()) return cost;
323 if (e == INVALID_ENGINE) return CommandCost(); // neither autoreplace is set, nor autorenew is triggered
325 /* Does it need to be refitted */
326 CargoID refit_cargo = GetNewCargoTypeForReplace(old_veh, e, part_of_chain);
327 if (refit_cargo == CT_INVALID) {
328 if (!IsLocalCompany()) return CommandCost();
330 SetDParam(0, old_veh->index);
332 int order_id = GetIncompatibleRefitOrderIdForAutoreplace(old_veh, e);
333 if (order_id != -1) {
334 /* Orders contained a refit order that is incompatible with the new vehicle. */
335 SetDParam(1, STR_ERROR_AUTOREPLACE_INCOMPATIBLE_REFIT);
336 SetDParam(2, order_id + 1); // 1-based indexing for display
337 } else {
338 /* Current cargo is incompatible with the new vehicle. */
339 SetDParam(1, STR_ERROR_AUTOREPLACE_INCOMPATIBLE_CARGO);
340 SetDParam(2, CargoSpec::Get(old_veh->cargo_type)->name);
343 AddVehicleAdviceNewsItem(STR_NEWS_VEHICLE_AUTORENEW_FAILED, old_veh->index);
344 return CommandCost();
347 /* Build the new vehicle */
348 cost = Command<CMD_BUILD_VEHICLE>::Do(DC_EXEC | DC_AUTOREPLACE, old_veh->tile, e, true, CT_INVALID, INVALID_CLIENT_ID);
349 if (cost.Failed()) return cost;
351 Vehicle *new_veh = Vehicle::Get(_new_vehicle_id);
352 *new_vehicle = new_veh;
354 /* Refit the vehicle if needed */
355 if (refit_cargo != CT_NO_REFIT) {
356 byte subtype = GetBestFittingSubType(old_veh, new_veh, refit_cargo);
358 cost.AddCost(Command<CMD_REFIT_VEHICLE>::Do(DC_EXEC, 0, new_veh->index, refit_cargo | (subtype << 8), {}));
359 assert(cost.Succeeded()); // This should be ensured by GetNewCargoTypeForReplace()
362 /* Try to reverse the vehicle, but do not care if it fails as the new type might not be reversible */
363 if (new_veh->type == VEH_TRAIN && HasBit(Train::From(old_veh)->flags, VRF_REVERSE_DIRECTION)) {
364 Command<CMD_REVERSE_TRAIN_DIRECTION>::Do(DC_EXEC, 0, new_veh->index, true, {});
367 return cost;
371 * Issue a start/stop command
372 * @param v a vehicle
373 * @param evaluate_callback shall the start/stop callback be evaluated?
374 * @return success or error
376 static inline CommandCost CmdStartStopVehicle(const Vehicle *v, bool evaluate_callback)
378 return Command<CMD_START_STOP_VEHICLE>::Do(DC_EXEC | DC_AUTOREPLACE, 0, v->index, evaluate_callback ? 1 : 0, {});
382 * Issue a train vehicle move command
383 * @param v The vehicle to move
384 * @param after The vehicle to insert 'v' after, or nullptr to start new chain
385 * @param flags the command flags to use
386 * @param whole_chain move all vehicles following 'v' (true), or only 'v' (false)
387 * @return success or error
389 static inline CommandCost CmdMoveVehicle(const Vehicle *v, const Vehicle *after, DoCommandFlag flags, bool whole_chain)
391 return Command<CMD_MOVE_RAIL_VEHICLE>::Do(flags | DC_NO_CARGO_CAP_CHECK, 0, v->index | (whole_chain ? 1 : 0) << 20, after != nullptr ? after->index : INVALID_VEHICLE, {});
395 * Copy head specific things to the new vehicle chain after it was successfully constructed
396 * @param old_head The old front vehicle (no wagons attached anymore)
397 * @param new_head The new head of the completely replaced vehicle chain
398 * @param flags the command flags to use
400 static CommandCost CopyHeadSpecificThings(Vehicle *old_head, Vehicle *new_head, DoCommandFlag flags)
402 CommandCost cost = CommandCost();
404 /* Share orders */
405 if (cost.Succeeded() && old_head != new_head) cost.AddCost(Command<CMD_CLONE_ORDER>::Do(DC_EXEC, 0, new_head->index | CO_SHARE << 30, old_head->index, {}));
407 /* Copy group membership */
408 if (cost.Succeeded() && old_head != new_head) cost.AddCost(Command<CMD_ADD_VEHICLE_GROUP>::Do(DC_EXEC, 0, old_head->group_id, new_head->index, {}));
410 /* Perform start/stop check whether the new vehicle suits newgrf restrictions etc. */
411 if (cost.Succeeded()) {
412 /* Start the vehicle, might be denied by certain things */
413 assert((new_head->vehstatus & VS_STOPPED) != 0);
414 cost.AddCost(CmdStartStopVehicle(new_head, true));
416 /* Stop the vehicle again, but do not care about evil newgrfs allowing starting but not stopping :p */
417 if (cost.Succeeded()) cost.AddCost(CmdStartStopVehicle(new_head, false));
420 /* Last do those things which do never fail (resp. we do not care about), but which are not undo-able */
421 if (cost.Succeeded() && old_head != new_head && (flags & DC_EXEC) != 0) {
422 /* Copy other things which cannot be copied by a command and which shall not stay resetted from the build vehicle command */
423 new_head->CopyVehicleConfigAndStatistics(old_head);
425 /* Switch vehicle windows/news to the new vehicle, so they are not closed/deleted when the old vehicle is sold */
426 ChangeVehicleViewports(old_head->index, new_head->index);
427 ChangeVehicleViewWindow(old_head->index, new_head->index);
428 ChangeVehicleNews(old_head->index, new_head->index);
431 return cost;
435 * Replace a single unit in a free wagon chain
436 * @param single_unit vehicle to let autoreplace/renew operator on
437 * @param flags command flags
438 * @param nothing_to_do is set to 'false' when something was done (only valid when not failed)
439 * @return cost or error
441 static CommandCost ReplaceFreeUnit(Vehicle **single_unit, DoCommandFlag flags, bool *nothing_to_do)
443 Train *old_v = Train::From(*single_unit);
444 assert(!old_v->IsArticulatedPart() && !old_v->IsRearDualheaded());
446 CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES, 0);
448 /* Build and refit replacement vehicle */
449 Vehicle *new_v = nullptr;
450 cost.AddCost(BuildReplacementVehicle(old_v, &new_v, false));
452 /* Was a new vehicle constructed? */
453 if (cost.Succeeded() && new_v != nullptr) {
454 *nothing_to_do = false;
456 if ((flags & DC_EXEC) != 0) {
457 /* Move the new vehicle behind the old */
458 CmdMoveVehicle(new_v, old_v, DC_EXEC, false);
460 /* Take over cargo
461 * Note: We do only transfer cargo from the old to the new vehicle.
462 * I.e. we do not transfer remaining cargo to other vehicles.
463 * Else you would also need to consider moving cargo to other free chains,
464 * or doing the same in ReplaceChain(), which would be quite troublesome.
466 TransferCargo(old_v, new_v, false);
468 *single_unit = new_v;
470 AI::NewEvent(old_v->owner, new ScriptEventVehicleAutoReplaced(old_v->index, new_v->index));
473 /* Sell the old vehicle */
474 cost.AddCost(Command<CMD_SELL_VEHICLE>::Do(flags, 0, old_v->index, false, false, INVALID_CLIENT_ID));
476 /* If we are not in DC_EXEC undo everything */
477 if ((flags & DC_EXEC) == 0) {
478 Command<CMD_SELL_VEHICLE>::Do(DC_EXEC, 0, new_v->index, false, false, INVALID_CLIENT_ID);
482 return cost;
486 * Replace a whole vehicle chain
487 * @param chain vehicle chain to let autoreplace/renew operator on
488 * @param flags command flags
489 * @param wagon_removal remove wagons when the resulting chain occupies more tiles than the old did
490 * @param nothing_to_do is set to 'false' when something was done (only valid when not failed)
491 * @return cost or error
493 static CommandCost ReplaceChain(Vehicle **chain, DoCommandFlag flags, bool wagon_removal, bool *nothing_to_do)
495 Vehicle *old_head = *chain;
496 assert(old_head->IsPrimaryVehicle());
498 CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES, 0);
500 if (old_head->type == VEH_TRAIN) {
501 /* Store the length of the old vehicle chain, rounded up to whole tiles */
502 uint16 old_total_length = CeilDiv(Train::From(old_head)->gcache.cached_total_length, TILE_SIZE) * TILE_SIZE;
504 int num_units = 0; ///< Number of units in the chain
505 for (Train *w = Train::From(old_head); w != nullptr; w = w->GetNextUnit()) num_units++;
507 Train **old_vehs = CallocT<Train *>(num_units); ///< Will store vehicles of the old chain in their order
508 Train **new_vehs = CallocT<Train *>(num_units); ///< New vehicles corresponding to old_vehs or nullptr if no replacement
509 Money *new_costs = MallocT<Money>(num_units); ///< Costs for buying and refitting the new vehicles
511 /* Collect vehicles and build replacements
512 * Note: The replacement vehicles can only successfully build as long as the old vehicles are still in their chain */
513 int i;
514 Train *w;
515 for (w = Train::From(old_head), i = 0; w != nullptr; w = w->GetNextUnit(), i++) {
516 assert(i < num_units);
517 old_vehs[i] = w;
519 CommandCost ret = BuildReplacementVehicle(old_vehs[i], (Vehicle**)&new_vehs[i], true);
520 cost.AddCost(ret);
521 if (cost.Failed()) break;
523 new_costs[i] = ret.GetCost();
524 if (new_vehs[i] != nullptr) *nothing_to_do = false;
526 Train *new_head = (new_vehs[0] != nullptr ? new_vehs[0] : old_vehs[0]);
528 /* Note: When autoreplace has already failed here, old_vehs[] is not completely initialized. But it is also not needed. */
529 if (cost.Succeeded()) {
530 /* Separate the head, so we can start constructing the new chain */
531 Train *second = Train::From(old_head)->GetNextUnit();
532 if (second != nullptr) cost.AddCost(CmdMoveVehicle(second, nullptr, DC_EXEC | DC_AUTOREPLACE, true));
534 assert(Train::From(new_head)->GetNextUnit() == nullptr);
536 /* Append engines to the new chain
537 * We do this from back to front, so that the head of the temporary vehicle chain does not change all the time.
538 * That way we also have less trouble when exceeding the unitnumber limit.
539 * OTOH the vehicle attach callback is more expensive this way :s */
540 Train *last_engine = nullptr; ///< Shall store the last engine unit after this step
541 if (cost.Succeeded()) {
542 for (int i = num_units - 1; i > 0; i--) {
543 Train *append = (new_vehs[i] != nullptr ? new_vehs[i] : old_vehs[i]);
545 if (RailVehInfo(append->engine_type)->railveh_type == RAILVEH_WAGON) continue;
547 if (new_vehs[i] != nullptr) {
548 /* Move the old engine to a separate row with DC_AUTOREPLACE. Else
549 * moving the wagon in front may fail later due to unitnumber limit.
550 * (We have to attach wagons without DC_AUTOREPLACE.) */
551 CmdMoveVehicle(old_vehs[i], nullptr, DC_EXEC | DC_AUTOREPLACE, false);
554 if (last_engine == nullptr) last_engine = append;
555 cost.AddCost(CmdMoveVehicle(append, new_head, DC_EXEC, false));
556 if (cost.Failed()) break;
558 if (last_engine == nullptr) last_engine = new_head;
561 /* When wagon removal is enabled and the new engines without any wagons are already longer than the old, we have to fail */
562 if (cost.Succeeded() && wagon_removal && new_head->gcache.cached_total_length > old_total_length) cost = CommandCost(STR_ERROR_TRAIN_TOO_LONG_AFTER_REPLACEMENT);
564 /* Append/insert wagons into the new vehicle chain
565 * 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.
567 if (cost.Succeeded()) {
568 for (int i = num_units - 1; i > 0; i--) {
569 assert(last_engine != nullptr);
570 Vehicle *append = (new_vehs[i] != nullptr ? new_vehs[i] : old_vehs[i]);
572 if (RailVehInfo(append->engine_type)->railveh_type == RAILVEH_WAGON) {
573 /* Insert wagon after 'last_engine' */
574 CommandCost res = CmdMoveVehicle(append, last_engine, DC_EXEC, false);
576 /* When we allow removal of wagons, either the move failing due
577 * to the train becoming too long, or the train becoming longer
578 * would move the vehicle to the empty vehicle chain. */
579 if (wagon_removal && (res.Failed() ? res.GetErrorMessage() == STR_ERROR_TRAIN_TOO_LONG : new_head->gcache.cached_total_length > old_total_length)) {
580 CmdMoveVehicle(append, nullptr, DC_EXEC | DC_AUTOREPLACE, false);
581 break;
584 cost.AddCost(res);
585 if (cost.Failed()) break;
586 } else {
587 /* We have reached 'last_engine', continue with the next engine towards the front */
588 assert(append == last_engine);
589 last_engine = last_engine->GetPrevUnit();
594 /* Sell superfluous new vehicles that could not be inserted. */
595 if (cost.Succeeded() && wagon_removal) {
596 assert(new_head->gcache.cached_total_length <= _settings_game.vehicle.max_train_length * TILE_SIZE);
597 for (int i = 1; i < num_units; i++) {
598 Vehicle *wagon = new_vehs[i];
599 if (wagon == nullptr) continue;
600 if (wagon->First() == new_head) break;
602 assert(RailVehInfo(wagon->engine_type)->railveh_type == RAILVEH_WAGON);
604 /* Sell wagon */
605 [[maybe_unused]] CommandCost ret = Command<CMD_SELL_VEHICLE>::Do(DC_EXEC, 0, wagon->index, false, false, INVALID_CLIENT_ID);
606 assert(ret.Succeeded());
607 new_vehs[i] = nullptr;
609 /* Revert the money subtraction when the vehicle was built.
610 * This value is different from the sell value, esp. because of refitting */
611 cost.AddCost(-new_costs[i]);
615 /* The new vehicle chain is constructed, now take over orders and everything... */
616 if (cost.Succeeded()) cost.AddCost(CopyHeadSpecificThings(old_head, new_head, flags));
618 if (cost.Succeeded()) {
619 /* Success ! */
620 if ((flags & DC_EXEC) != 0 && new_head != old_head) {
621 *chain = new_head;
622 AI::NewEvent(old_head->owner, new ScriptEventVehicleAutoReplaced(old_head->index, new_head->index));
625 /* Transfer cargo of old vehicles and sell them */
626 for (int i = 0; i < num_units; i++) {
627 Vehicle *w = old_vehs[i];
628 /* Is the vehicle again part of the new chain?
629 * Note: We cannot test 'new_vehs[i] != nullptr' as wagon removal might cause to remove both */
630 if (w->First() == new_head) continue;
632 if ((flags & DC_EXEC) != 0) TransferCargo(w, new_head, true);
634 /* Sell the vehicle.
635 * Note: This might temporarily construct new trains, so use DC_AUTOREPLACE to prevent
636 * it from failing due to engine limits. */
637 cost.AddCost(Command<CMD_SELL_VEHICLE>::Do(flags | DC_AUTOREPLACE, 0, w->index, false, false, INVALID_CLIENT_ID));
638 if ((flags & DC_EXEC) != 0) {
639 old_vehs[i] = nullptr;
640 if (i == 0) old_head = nullptr;
644 if ((flags & DC_EXEC) != 0) CheckCargoCapacity(new_head);
647 /* If we are not in DC_EXEC undo everything, i.e. rearrange old vehicles.
648 * We do this from back to front, so that the head of the temporary vehicle chain does not change all the time.
649 * Note: The vehicle attach callback is disabled here :) */
650 if ((flags & DC_EXEC) == 0) {
651 /* Separate the head, so we can reattach the old vehicles */
652 Train *second = Train::From(old_head)->GetNextUnit();
653 if (second != nullptr) CmdMoveVehicle(second, nullptr, DC_EXEC | DC_AUTOREPLACE, true);
655 assert(Train::From(old_head)->GetNextUnit() == nullptr);
657 for (int i = num_units - 1; i > 0; i--) {
658 [[maybe_unused]] CommandCost ret = CmdMoveVehicle(old_vehs[i], old_head, DC_EXEC | DC_AUTOREPLACE, false);
659 assert(ret.Succeeded());
664 /* Finally undo buying of new vehicles */
665 if ((flags & DC_EXEC) == 0) {
666 for (int i = num_units - 1; i >= 0; i--) {
667 if (new_vehs[i] != nullptr) {
668 Command<CMD_SELL_VEHICLE>::Do(DC_EXEC, 0, new_vehs[i]->index, false, false, INVALID_CLIENT_ID);
669 new_vehs[i] = nullptr;
674 free(old_vehs);
675 free(new_vehs);
676 free(new_costs);
677 } else {
678 /* Build and refit replacement vehicle */
679 Vehicle *new_head = nullptr;
680 cost.AddCost(BuildReplacementVehicle(old_head, &new_head, true));
682 /* Was a new vehicle constructed? */
683 if (cost.Succeeded() && new_head != nullptr) {
684 *nothing_to_do = false;
686 /* The new vehicle is constructed, now take over orders and everything... */
687 cost.AddCost(CopyHeadSpecificThings(old_head, new_head, flags));
689 if (cost.Succeeded()) {
690 /* The new vehicle is constructed, now take over cargo */
691 if ((flags & DC_EXEC) != 0) {
692 TransferCargo(old_head, new_head, true);
693 *chain = new_head;
695 AI::NewEvent(old_head->owner, new ScriptEventVehicleAutoReplaced(old_head->index, new_head->index));
698 /* Sell the old vehicle */
699 cost.AddCost(Command<CMD_SELL_VEHICLE>::Do(flags, 0, old_head->index, false, false, INVALID_CLIENT_ID));
702 /* If we are not in DC_EXEC undo everything */
703 if ((flags & DC_EXEC) == 0) {
704 Command<CMD_SELL_VEHICLE>::Do(DC_EXEC, 0, new_head->index, false, false, INVALID_CLIENT_ID);
709 return cost;
713 * Autoreplaces a vehicle
714 * Trains are replaced as a whole chain, free wagons in depot are replaced on their own
715 * @param flags type of operation
716 * @param tile not used
717 * @param p1 Index of vehicle
718 * @param p2 not used
719 * @param text unused
720 * @return the cost of this operation or an error
722 CommandCost CmdAutoreplaceVehicle(DoCommandFlag flags, TileIndex tile, uint32 p1, uint32 p2, const std::string &text)
724 Vehicle *v = Vehicle::GetIfValid(p1);
725 if (v == nullptr) return CMD_ERROR;
727 CommandCost ret = CheckOwnership(v->owner);
728 if (ret.Failed()) return ret;
730 if (!v->IsChainInDepot()) return CMD_ERROR;
731 if (v->vehstatus & VS_CRASHED) return CMD_ERROR;
733 bool free_wagon = false;
734 if (v->type == VEH_TRAIN) {
735 Train *t = Train::From(v);
736 if (t->IsArticulatedPart() || t->IsRearDualheaded()) return CMD_ERROR;
737 free_wagon = !t->IsFrontEngine();
738 if (free_wagon && t->First()->IsFrontEngine()) return CMD_ERROR;
739 } else {
740 if (!v->IsPrimaryVehicle()) return CMD_ERROR;
743 const Company *c = Company::Get(_current_company);
744 bool wagon_removal = c->settings.renew_keep_length;
746 const Group *g = Group::GetIfValid(v->group_id);
747 if (g != nullptr) wagon_removal = HasBit(g->flags, GroupFlags::GF_REPLACE_WAGON_REMOVAL);
749 /* Test whether any replacement is set, before issuing a whole lot of commands that would end in nothing changed */
750 Vehicle *w = v;
751 bool any_replacements = false;
752 while (w != nullptr) {
753 EngineID e;
754 CommandCost cost = GetNewEngineType(w, c, false, e);
755 if (cost.Failed()) return cost;
756 any_replacements |= (e != INVALID_ENGINE);
757 w = (!free_wagon && w->type == VEH_TRAIN ? Train::From(w)->GetNextUnit() : nullptr);
760 CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES, 0);
761 bool nothing_to_do = true;
763 if (any_replacements) {
764 bool was_stopped = free_wagon || ((v->vehstatus & VS_STOPPED) != 0);
766 /* Stop the vehicle */
767 if (!was_stopped) cost.AddCost(CmdStartStopVehicle(v, true));
768 if (cost.Failed()) return cost;
770 assert(free_wagon || v->IsStoppedInDepot());
772 /* We have to construct the new vehicle chain to test whether it is valid.
773 * Vehicle construction needs random bits, so we have to save the random seeds
774 * to prevent desyncs and to replay newgrf callbacks during DC_EXEC */
775 SavedRandomSeeds saved_seeds;
776 SaveRandomSeeds(&saved_seeds);
777 if (free_wagon) {
778 cost.AddCost(ReplaceFreeUnit(&v, flags & ~DC_EXEC, &nothing_to_do));
779 } else {
780 cost.AddCost(ReplaceChain(&v, flags & ~DC_EXEC, wagon_removal, &nothing_to_do));
782 RestoreRandomSeeds(saved_seeds);
784 if (cost.Succeeded() && (flags & DC_EXEC) != 0) {
785 CommandCost ret;
786 if (free_wagon) {
787 ret = ReplaceFreeUnit(&v, flags, &nothing_to_do);
788 } else {
789 ret = ReplaceChain(&v, flags, wagon_removal, &nothing_to_do);
791 assert(ret.Succeeded() && ret.GetCost() == cost.GetCost());
794 /* Restart the vehicle */
795 if (!was_stopped) cost.AddCost(CmdStartStopVehicle(v, false));
798 if (cost.Succeeded() && nothing_to_do) cost = CommandCost(STR_ERROR_AUTOREPLACE_NOTHING_TO_DO);
799 return cost;
803 * Change engine renewal parameters
804 * @param flags operation to perform
805 * @param tile unused
806 * @param p1 packed data
807 * - bit 0 = replace when engine gets old?
808 * - bits 16-31 = engine group
809 * @param p2 packed data
810 * - bits 0-15 = old engine type
811 * - bits 16-31 = new engine type
812 * @param text unused
813 * @return the cost of this operation or an error
815 CommandCost CmdSetAutoReplace(DoCommandFlag flags, TileIndex tile, uint32 p1, uint32 p2, const std::string &text)
817 Company *c = Company::GetIfValid(_current_company);
818 if (c == nullptr) return CMD_ERROR;
820 EngineID old_engine_type = GB(p2, 0, 16);
821 EngineID new_engine_type = GB(p2, 16, 16);
822 GroupID id_g = GB(p1, 16, 16);
823 CommandCost cost;
825 if (Group::IsValidID(id_g) ? Group::Get(id_g)->owner != _current_company : !IsAllGroupID(id_g) && !IsDefaultGroupID(id_g)) return CMD_ERROR;
826 if (!Engine::IsValidID(old_engine_type)) return CMD_ERROR;
828 if (new_engine_type != INVALID_ENGINE) {
829 if (!Engine::IsValidID(new_engine_type)) return CMD_ERROR;
830 if (!CheckAutoreplaceValidity(old_engine_type, new_engine_type, _current_company)) return CMD_ERROR;
832 cost = AddEngineReplacementForCompany(c, old_engine_type, new_engine_type, id_g, HasBit(p1, 0), flags);
833 } else {
834 cost = RemoveEngineReplacementForCompany(c, old_engine_type, id_g, flags);
837 if (flags & DC_EXEC) {
838 GroupStatistics::UpdateAutoreplace(_current_company);
839 if (IsLocalCompany()) SetWindowDirty(WC_REPLACE_VEHICLE, Engine::Get(old_engine_type)->type);
841 const VehicleType vt = Engine::Get(old_engine_type)->type;
842 SetWindowDirty(GetWindowClassForVehicleType(vt), VehicleListIdentifier(VL_GROUP_LIST, vt, _current_company).Pack());
844 if ((flags & DC_EXEC) && IsLocalCompany()) InvalidateAutoreplaceWindow(old_engine_type, id_g);
846 return cost;