OpenTTD
autoreplace_cmd.cpp
Go to the documentation of this file.
1 /* $Id$ */
2 
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  */
9 
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 "core/random_func.hpp"
22 #include "vehiclelist.h"
23 #include "road.h"
24 #include "ai/ai.hpp"
25 
26 #include "table/strings.h"
27 
28 #include "safeguards.h"
29 
30 extern void ChangeVehicleViewports(VehicleID from_index, VehicleID to_index);
31 extern void ChangeVehicleNews(VehicleID from_index, VehicleID to_index);
32 extern void ChangeVehicleViewWindow(VehicleID from_index, VehicleID to_index);
33 
40 static bool EnginesHaveCargoInCommon(EngineID engine_a, EngineID engine_b)
41 {
42  CargoTypes available_cargoes_a = GetUnionOfArticulatedRefitMasks(engine_a, true);
43  CargoTypes available_cargoes_b = GetUnionOfArticulatedRefitMasks(engine_b, true);
44  return (available_cargoes_a == 0 || available_cargoes_b == 0 || (available_cargoes_a & available_cargoes_b) != 0);
45 }
46 
55 {
56  assert(Engine::IsValidID(from) && Engine::IsValidID(to));
57 
58  /* we can't replace an engine into itself (that would be autorenew) */
59  if (from == to) return false;
60 
61  const Engine *e_from = Engine::Get(from);
62  const Engine *e_to = Engine::Get(to);
63  VehicleType type = e_from->type;
64 
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;
67 
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;
72 
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;
76  }
77 
78  case VEH_ROAD:
79  /* make sure the roadtypes are compatible */
80  if ((GetRoadTypeInfo(e_from->u.road.roadtype)->powered_roadtypes & GetRoadTypeInfo(e_to->u.road.roadtype)->powered_roadtypes) == ROADTYPES_NONE) return false;
81 
82  /* make sure that we do not replace a tram with a normal road vehicles or vice versa */
83  if (HasBit(e_from->info.misc_flags, EF_ROAD_TRAM) != HasBit(e_to->info.misc_flags, EF_ROAD_TRAM)) return false;
84  break;
85 
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;
90 
91  default: break;
92  }
93 
94  /* the engines needs to be able to carry the same cargo */
95  return EnginesHaveCargoInCommon(from, to);
96 }
97 
105 {
106  assert(v == nullptr || v->First() == v);
107 
108  for (Vehicle *src = v; src != nullptr; src = src->Next()) {
109  assert(src->cargo.TotalCount() == src->cargo.ActionCount(VehicleCargoList::MTA_KEEP));
110 
111  /* Do we need to more cargo away? */
112  if (src->cargo.TotalCount() <= src->cargo_cap) continue;
113 
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;
119 
120  uint amount = min(to_spread, dest->cargo_cap - dest->cargo.TotalCount());
121  src->cargo.Shift(amount, &dest->cargo);
122  to_spread -= amount;
123  }
124 
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);
127  }
128 }
129 
139 static void TransferCargo(Vehicle *old_veh, Vehicle *new_head, bool part_of_chain)
140 {
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;
149  }
150  if (src->cargo_type >= NUM_CARGO || src->cargo.TotalCount() == 0) continue;
151 
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;
159  }
160  if (dest->cargo_type != src->cargo_type) continue;
161 
162  uint amount = min(src->cargo.TotalCount(), dest->cargo_cap - dest->cargo.TotalCount());
163  if (amount <= 0) continue;
164 
165  src->cargo.Shift(amount, &dest->cargo);
166  }
167  }
168 
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);
171 }
172 
179 static bool VerifyAutoreplaceRefitForOrders(const Vehicle *v, EngineID engine_type)
180 {
181  CargoTypes union_refit_mask_a = GetUnionOfArticulatedRefitMasks(v->engine_type, false);
182  CargoTypes union_refit_mask_b = GetUnionOfArticulatedRefitMasks(engine_type, false);
183 
184  const Order *o;
185  const Vehicle *u = (v->type == VEH_TRAIN) ? v->First() : v;
186  FOR_VEHICLE_ORDERS(u, o) {
187  if (!o->IsRefit() || o->IsAutoRefit()) continue;
188  CargoID cargo_type = o->GetRefitCargo();
189 
190  if (!HasBit(union_refit_mask_a, cargo_type)) continue;
191  if (!HasBit(union_refit_mask_b, cargo_type)) return false;
192  }
193 
194  return true;
195 }
196 
206 static CargoID GetNewCargoTypeForReplace(Vehicle *v, EngineID engine_type, bool part_of_chain)
207 {
208  CargoTypes available_cargo_types, union_mask;
209  GetArticulatedRefitMasks(engine_type, true, &union_mask, &available_cargo_types);
210 
211  if (union_mask == 0) return CT_NO_REFIT; // Don't try to refit an engine with no cargo capacity
212 
213  CargoID cargo_type;
214  if (IsArticulatedVehicleCarryingDifferentCargoes(v, &cargo_type)) return CT_INVALID; // We cannot refit to mixed cargoes in an automated way
215 
216  if (cargo_type == CT_INVALID) {
217  if (v->type != VEH_TRAIN) return CT_NO_REFIT; // If the vehicle does not carry anything at all, every replacement is fine.
218 
219  if (!part_of_chain) return CT_NO_REFIT;
220 
221  /* the old engine didn't have cargo capacity, but the new one does
222  * now we will figure out what cargo the train is carrying and refit to fit this */
223 
224  for (v = v->First(); v != nullptr; v = v->Next()) {
225  if (!v->GetEngine()->CanCarryCargo()) continue;
226  /* Now we found a cargo type being carried on the train and we will see if it is possible to carry to this one */
227  if (HasBit(available_cargo_types, v->cargo_type)) return v->cargo_type;
228  }
229 
230  return CT_NO_REFIT; // We failed to find a cargo type on the old vehicle and we will not refit the new one
231  } else {
232  if (!HasBit(available_cargo_types, cargo_type)) return CT_INVALID; // We can't refit the vehicle to carry the cargo we want
233 
234  if (part_of_chain && !VerifyAutoreplaceRefitForOrders(v, engine_type)) return CT_INVALID; // Some refit orders lose their effect
235 
236  return cargo_type;
237  }
238 }
239 
248 static CommandCost GetNewEngineType(const Vehicle *v, const Company *c, bool always_replace, EngineID &e)
249 {
250  assert(v->type != VEH_TRAIN || !v->IsArticulatedPart());
251 
252  e = INVALID_ENGINE;
253 
254  if (v->type == VEH_TRAIN && Train::From(v)->IsRearDualheaded()) {
255  /* we build the rear ends of multiheaded trains with the front ones */
256  return CommandCost();
257  }
258 
259  bool replace_when_old;
260  e = EngineReplacementForCompany(c, v->engine_type, v->group_id, &replace_when_old);
261  if (!always_replace && replace_when_old && !v->NeedsAutorenewing(c, false)) e = INVALID_ENGINE;
262 
263  /* Autoreplace, if engine is available */
265  return CommandCost();
266  }
267 
268  /* Autorenew if needed */
269  if (v->NeedsAutorenewing(c)) e = v->engine_type;
270 
271  /* Nothing to do or all is fine? */
272  if (e == INVALID_ENGINE || IsEngineBuildable(e, v->type, _current_company)) return CommandCost();
273 
274  /* The engine we need is not available. Report error to user */
275  return CommandCost(STR_ERROR_RAIL_VEHICLE_NOT_AVAILABLE + v->type);
276 }
277 
286 static CommandCost BuildReplacementVehicle(Vehicle *old_veh, Vehicle **new_vehicle, bool part_of_chain)
287 {
288  *new_vehicle = nullptr;
289 
290  /* Shall the vehicle be replaced? */
292  EngineID e;
293  CommandCost cost = GetNewEngineType(old_veh, c, true, e);
294  if (cost.Failed()) return cost;
295  if (e == INVALID_ENGINE) return CommandCost(); // neither autoreplace is set, nor autorenew is triggered
296 
297  /* Does it need to be refitted */
298  CargoID refit_cargo = GetNewCargoTypeForReplace(old_veh, e, part_of_chain);
299  if (refit_cargo == CT_INVALID) return CommandCost(); // incompatible cargoes
300 
301  /* Build the new vehicle */
302  cost = DoCommand(old_veh->tile, e | (CT_INVALID << 24), 0, DC_EXEC | DC_AUTOREPLACE, GetCmdBuildVeh(old_veh));
303  if (cost.Failed()) return cost;
304 
305  Vehicle *new_veh = Vehicle::Get(_new_vehicle_id);
306  *new_vehicle = new_veh;
307 
308  /* Refit the vehicle if needed */
309  if (refit_cargo != CT_NO_REFIT) {
310  byte subtype = GetBestFittingSubType(old_veh, new_veh, refit_cargo);
311 
312  cost.AddCost(DoCommand(0, new_veh->index, refit_cargo | (subtype << 8), DC_EXEC, GetCmdRefitVeh(new_veh)));
313  assert(cost.Succeeded()); // This should be ensured by GetNewCargoTypeForReplace()
314  }
315 
316  /* Try to reverse the vehicle, but do not care if it fails as the new type might not be reversible */
317  if (new_veh->type == VEH_TRAIN && HasBit(Train::From(old_veh)->flags, VRF_REVERSE_DIRECTION)) {
318  DoCommand(0, new_veh->index, true, DC_EXEC, CMD_REVERSE_TRAIN_DIRECTION);
319  }
320 
321  return cost;
322 }
323 
330 static inline CommandCost CmdStartStopVehicle(const Vehicle *v, bool evaluate_callback)
331 {
332  return DoCommand(0, v->index, evaluate_callback ? 1 : 0, DC_EXEC | DC_AUTOREPLACE, CMD_START_STOP_VEHICLE);
333 }
334 
343 static inline CommandCost CmdMoveVehicle(const Vehicle *v, const Vehicle *after, DoCommandFlag flags, bool whole_chain)
344 {
345  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);
346 }
347 
355 {
356  CommandCost cost = CommandCost();
357 
358  /* Share orders */
359  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));
360 
361  /* Copy group membership */
362  if (cost.Succeeded() && old_head != new_head) cost.AddCost(DoCommand(0, old_head->group_id, new_head->index, DC_EXEC, CMD_ADD_VEHICLE_GROUP));
363 
364  /* Perform start/stop check whether the new vehicle suits newgrf restrictions etc. */
365  if (cost.Succeeded()) {
366  /* Start the vehicle, might be denied by certain things */
367  assert((new_head->vehstatus & VS_STOPPED) != 0);
368  cost.AddCost(CmdStartStopVehicle(new_head, true));
369 
370  /* Stop the vehicle again, but do not care about evil newgrfs allowing starting but not stopping :p */
371  if (cost.Succeeded()) cost.AddCost(CmdStartStopVehicle(new_head, false));
372  }
373 
374  /* Last do those things which do never fail (resp. we do not care about), but which are not undo-able */
375  if (cost.Succeeded() && old_head != new_head && (flags & DC_EXEC) != 0) {
376  /* Copy other things which cannot be copied by a command and which shall not stay resetted from the build vehicle command */
377  new_head->CopyVehicleConfigAndStatistics(old_head);
378 
379  /* Switch vehicle windows/news to the new vehicle, so they are not closed/deleted when the old vehicle is sold */
380  ChangeVehicleViewports(old_head->index, new_head->index);
381  ChangeVehicleViewWindow(old_head->index, new_head->index);
382  ChangeVehicleNews(old_head->index, new_head->index);
383  }
384 
385  return cost;
386 }
387 
395 static CommandCost ReplaceFreeUnit(Vehicle **single_unit, DoCommandFlag flags, bool *nothing_to_do)
396 {
397  Train *old_v = Train::From(*single_unit);
398  assert(!old_v->IsArticulatedPart() && !old_v->IsRearDualheaded());
399 
401 
402  /* Build and refit replacement vehicle */
403  Vehicle *new_v = nullptr;
404  cost.AddCost(BuildReplacementVehicle(old_v, &new_v, false));
405 
406  /* Was a new vehicle constructed? */
407  if (cost.Succeeded() && new_v != nullptr) {
408  *nothing_to_do = false;
409 
410  if ((flags & DC_EXEC) != 0) {
411  /* Move the new vehicle behind the old */
412  CmdMoveVehicle(new_v, old_v, DC_EXEC, false);
413 
414  /* Take over cargo
415  * Note: We do only transfer cargo from the old to the new vehicle.
416  * I.e. we do not transfer remaining cargo to other vehicles.
417  * Else you would also need to consider moving cargo to other free chains,
418  * or doing the same in ReplaceChain(), which would be quite troublesome.
419  */
420  TransferCargo(old_v, new_v, false);
421 
422  *single_unit = new_v;
423 
424  AI::NewEvent(old_v->owner, new ScriptEventVehicleAutoReplaced(old_v->index, new_v->index));
425  }
426 
427  /* Sell the old vehicle */
428  cost.AddCost(DoCommand(0, old_v->index, 0, flags, GetCmdSellVeh(old_v)));
429 
430  /* If we are not in DC_EXEC undo everything */
431  if ((flags & DC_EXEC) == 0) {
432  DoCommand(0, new_v->index, 0, DC_EXEC, GetCmdSellVeh(new_v));
433  }
434  }
435 
436  return cost;
437 }
438 
447 static CommandCost ReplaceChain(Vehicle **chain, DoCommandFlag flags, bool wagon_removal, bool *nothing_to_do)
448 {
449  Vehicle *old_head = *chain;
450  assert(old_head->IsPrimaryVehicle());
451 
453 
454  if (old_head->type == VEH_TRAIN) {
455  /* Store the length of the old vehicle chain, rounded up to whole tiles */
456  uint16 old_total_length = CeilDiv(Train::From(old_head)->gcache.cached_total_length, TILE_SIZE) * TILE_SIZE;
457 
458  int num_units = 0;
459  for (Train *w = Train::From(old_head); w != nullptr; w = w->GetNextUnit()) num_units++;
460 
461  Train **old_vehs = CallocT<Train *>(num_units);
462  Train **new_vehs = CallocT<Train *>(num_units);
463  Money *new_costs = MallocT<Money>(num_units);
464 
465  /* Collect vehicles and build replacements
466  * Note: The replacement vehicles can only successfully build as long as the old vehicles are still in their chain */
467  int i;
468  Train *w;
469  for (w = Train::From(old_head), i = 0; w != nullptr; w = w->GetNextUnit(), i++) {
470  assert(i < num_units);
471  old_vehs[i] = w;
472 
473  CommandCost ret = BuildReplacementVehicle(old_vehs[i], (Vehicle**)&new_vehs[i], true);
474  cost.AddCost(ret);
475  if (cost.Failed()) break;
476 
477  new_costs[i] = ret.GetCost();
478  if (new_vehs[i] != nullptr) *nothing_to_do = false;
479  }
480  Train *new_head = (new_vehs[0] != nullptr ? new_vehs[0] : old_vehs[0]);
481 
482  /* Note: When autoreplace has already failed here, old_vehs[] is not completely initialized. But it is also not needed. */
483  if (cost.Succeeded()) {
484  /* Separate the head, so we can start constructing the new chain */
485  Train *second = Train::From(old_head)->GetNextUnit();
486  if (second != nullptr) cost.AddCost(CmdMoveVehicle(second, nullptr, DC_EXEC | DC_AUTOREPLACE, true));
487 
488  assert(Train::From(new_head)->GetNextUnit() == nullptr);
489 
490  /* Append engines to the new chain
491  * We do this from back to front, so that the head of the temporary vehicle chain does not change all the time.
492  * That way we also have less trouble when exceeding the unitnumber limit.
493  * OTOH the vehicle attach callback is more expensive this way :s */
494  Train *last_engine = nullptr;
495  if (cost.Succeeded()) {
496  for (int i = num_units - 1; i > 0; i--) {
497  Train *append = (new_vehs[i] != nullptr ? new_vehs[i] : old_vehs[i]);
498 
499  if (RailVehInfo(append->engine_type)->railveh_type == RAILVEH_WAGON) continue;
500 
501  if (new_vehs[i] != nullptr) {
502  /* Move the old engine to a separate row with DC_AUTOREPLACE. Else
503  * moving the wagon in front may fail later due to unitnumber limit.
504  * (We have to attach wagons without DC_AUTOREPLACE.) */
505  CmdMoveVehicle(old_vehs[i], nullptr, DC_EXEC | DC_AUTOREPLACE, false);
506  }
507 
508  if (last_engine == nullptr) last_engine = append;
509  cost.AddCost(CmdMoveVehicle(append, new_head, DC_EXEC, false));
510  if (cost.Failed()) break;
511  }
512  if (last_engine == nullptr) last_engine = new_head;
513  }
514 
515  /* When wagon removal is enabled and the new engines without any wagons are already longer than the old, we have to fail */
516  if (cost.Succeeded() && wagon_removal && new_head->gcache.cached_total_length > old_total_length) cost = CommandCost(STR_ERROR_TRAIN_TOO_LONG_AFTER_REPLACEMENT);
517 
518  /* Append/insert wagons into the new vehicle chain
519  * 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.
520  */
521  if (cost.Succeeded()) {
522  for (int i = num_units - 1; i > 0; i--) {
523  assert(last_engine != nullptr);
524  Vehicle *append = (new_vehs[i] != nullptr ? new_vehs[i] : old_vehs[i]);
525 
526  if (RailVehInfo(append->engine_type)->railveh_type == RAILVEH_WAGON) {
527  /* Insert wagon after 'last_engine' */
528  CommandCost res = CmdMoveVehicle(append, last_engine, DC_EXEC, false);
529 
530  /* When we allow removal of wagons, either the move failing due
531  * to the train becoming too long, or the train becoming longer
532  * would move the vehicle to the empty vehicle chain. */
533  if (wagon_removal && (res.Failed() ? res.GetErrorMessage() == STR_ERROR_TRAIN_TOO_LONG : new_head->gcache.cached_total_length > old_total_length)) {
534  CmdMoveVehicle(append, nullptr, DC_EXEC | DC_AUTOREPLACE, false);
535  break;
536  }
537 
538  cost.AddCost(res);
539  if (cost.Failed()) break;
540  } else {
541  /* We have reached 'last_engine', continue with the next engine towards the front */
542  assert(append == last_engine);
543  last_engine = last_engine->GetPrevUnit();
544  }
545  }
546  }
547 
548  /* Sell superfluous new vehicles that could not be inserted. */
549  if (cost.Succeeded() && wagon_removal) {
551  for (int i = 1; i < num_units; i++) {
552  Vehicle *wagon = new_vehs[i];
553  if (wagon == nullptr) continue;
554  if (wagon->First() == new_head) break;
555 
556  assert(RailVehInfo(wagon->engine_type)->railveh_type == RAILVEH_WAGON);
557 
558  /* Sell wagon */
559  CommandCost ret = DoCommand(0, wagon->index, 0, DC_EXEC, GetCmdSellVeh(wagon));
560  assert(ret.Succeeded());
561  new_vehs[i] = nullptr;
562 
563  /* Revert the money subtraction when the vehicle was built.
564  * This value is different from the sell value, esp. because of refitting */
565  cost.AddCost(-new_costs[i]);
566  }
567  }
568 
569  /* The new vehicle chain is constructed, now take over orders and everything... */
570  if (cost.Succeeded()) cost.AddCost(CopyHeadSpecificThings(old_head, new_head, flags));
571 
572  if (cost.Succeeded()) {
573  /* Success ! */
574  if ((flags & DC_EXEC) != 0 && new_head != old_head) {
575  *chain = new_head;
576  }
577 
578  /* Transfer cargo of old vehicles and sell them */
579  for (int i = 0; i < num_units; i++) {
580  Vehicle *w = old_vehs[i];
581  /* Is the vehicle again part of the new chain?
582  * Note: We cannot test 'new_vehs[i] != nullptr' as wagon removal might cause to remove both */
583  if (w->First() == new_head) continue;
584 
585  if ((flags & DC_EXEC) != 0) TransferCargo(w, new_head, true);
586 
587  /* Sell the vehicle.
588  * Note: This might temporarily construct new trains, so use DC_AUTOREPLACE to prevent
589  * it from failing due to engine limits. */
590  cost.AddCost(DoCommand(0, w->index, 0, flags | DC_AUTOREPLACE, GetCmdSellVeh(w)));
591  if ((flags & DC_EXEC) != 0) {
592  old_vehs[i] = nullptr;
593  if (i == 0) {
594  AI::NewEvent(old_head->owner, new ScriptEventVehicleAutoReplaced(old_head->index, new_head->index));
595  old_head = nullptr;
596  }
597  }
598  }
599 
600  if ((flags & DC_EXEC) != 0) CheckCargoCapacity(new_head);
601  }
602 
603  /* If we are not in DC_EXEC undo everything, i.e. rearrange old vehicles.
604  * We do this from back to front, so that the head of the temporary vehicle chain does not change all the time.
605  * Note: The vehicle attach callback is disabled here :) */
606  if ((flags & DC_EXEC) == 0) {
607  /* Separate the head, so we can reattach the old vehicles */
608  Train *second = Train::From(old_head)->GetNextUnit();
609  if (second != nullptr) CmdMoveVehicle(second, nullptr, DC_EXEC | DC_AUTOREPLACE, true);
610 
611  assert(Train::From(old_head)->GetNextUnit() == nullptr);
612 
613  for (int i = num_units - 1; i > 0; i--) {
614  CommandCost ret = CmdMoveVehicle(old_vehs[i], old_head, DC_EXEC | DC_AUTOREPLACE, false);
615  assert(ret.Succeeded());
616  }
617  }
618  }
619 
620  /* Finally undo buying of new vehicles */
621  if ((flags & DC_EXEC) == 0) {
622  for (int i = num_units - 1; i >= 0; i--) {
623  if (new_vehs[i] != nullptr) {
624  DoCommand(0, new_vehs[i]->index, 0, DC_EXEC, GetCmdSellVeh(new_vehs[i]));
625  new_vehs[i] = nullptr;
626  }
627  }
628  }
629 
630  free(old_vehs);
631  free(new_vehs);
632  free(new_costs);
633  } else {
634  /* Build and refit replacement vehicle */
635  Vehicle *new_head = nullptr;
636  cost.AddCost(BuildReplacementVehicle(old_head, &new_head, true));
637 
638  /* Was a new vehicle constructed? */
639  if (cost.Succeeded() && new_head != nullptr) {
640  *nothing_to_do = false;
641 
642  /* The new vehicle is constructed, now take over orders and everything... */
643  cost.AddCost(CopyHeadSpecificThings(old_head, new_head, flags));
644 
645  if (cost.Succeeded()) {
646  /* The new vehicle is constructed, now take over cargo */
647  if ((flags & DC_EXEC) != 0) {
648  TransferCargo(old_head, new_head, true);
649  *chain = new_head;
650 
651  AI::NewEvent(old_head->owner, new ScriptEventVehicleAutoReplaced(old_head->index, new_head->index));
652  }
653 
654  /* Sell the old vehicle */
655  cost.AddCost(DoCommand(0, old_head->index, 0, flags, GetCmdSellVeh(old_head)));
656  }
657 
658  /* If we are not in DC_EXEC undo everything */
659  if ((flags & DC_EXEC) == 0) {
660  DoCommand(0, new_head->index, 0, DC_EXEC, GetCmdSellVeh(new_head));
661  }
662  }
663  }
664 
665  return cost;
666 }
667 
678 CommandCost CmdAutoreplaceVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
679 {
680  Vehicle *v = Vehicle::GetIfValid(p1);
681  if (v == nullptr) return CMD_ERROR;
682 
683  CommandCost ret = CheckOwnership(v->owner);
684  if (ret.Failed()) return ret;
685 
686  if (!v->IsChainInDepot()) return CMD_ERROR;
687  if (v->vehstatus & VS_CRASHED) return CMD_ERROR;
688 
689  bool free_wagon = false;
690  if (v->type == VEH_TRAIN) {
691  Train *t = Train::From(v);
692  if (t->IsArticulatedPart() || t->IsRearDualheaded()) return CMD_ERROR;
693  free_wagon = !t->IsFrontEngine();
694  if (free_wagon && t->First()->IsFrontEngine()) return CMD_ERROR;
695  } else {
696  if (!v->IsPrimaryVehicle()) return CMD_ERROR;
697  }
698 
700  bool wagon_removal = c->settings.renew_keep_length;
701 
702  /* Test whether any replacement is set, before issuing a whole lot of commands that would end in nothing changed */
703  Vehicle *w = v;
704  bool any_replacements = false;
705  while (w != nullptr) {
706  EngineID e;
707  CommandCost cost = GetNewEngineType(w, c, false, e);
708  if (cost.Failed()) return cost;
709  any_replacements |= (e != INVALID_ENGINE);
710  w = (!free_wagon && w->type == VEH_TRAIN ? Train::From(w)->GetNextUnit() : nullptr);
711  }
712 
714  bool nothing_to_do = true;
715 
716  if (any_replacements) {
717  bool was_stopped = free_wagon || ((v->vehstatus & VS_STOPPED) != 0);
718 
719  /* Stop the vehicle */
720  if (!was_stopped) cost.AddCost(CmdStartStopVehicle(v, true));
721  if (cost.Failed()) return cost;
722 
723  assert(free_wagon || v->IsStoppedInDepot());
724 
725  /* We have to construct the new vehicle chain to test whether it is valid.
726  * Vehicle construction needs random bits, so we have to save the random seeds
727  * to prevent desyncs and to replay newgrf callbacks during DC_EXEC */
728  SavedRandomSeeds saved_seeds;
729  SaveRandomSeeds(&saved_seeds);
730  if (free_wagon) {
731  cost.AddCost(ReplaceFreeUnit(&v, flags & ~DC_EXEC, &nothing_to_do));
732  } else {
733  cost.AddCost(ReplaceChain(&v, flags & ~DC_EXEC, wagon_removal, &nothing_to_do));
734  }
735  RestoreRandomSeeds(saved_seeds);
736 
737  if (cost.Succeeded() && (flags & DC_EXEC) != 0) {
738  CommandCost ret;
739  if (free_wagon) {
740  ret = ReplaceFreeUnit(&v, flags, &nothing_to_do);
741  } else {
742  ret = ReplaceChain(&v, flags, wagon_removal, &nothing_to_do);
743  }
744  assert(ret.Succeeded() && ret.GetCost() == cost.GetCost());
745  }
746 
747  /* Restart the vehicle */
748  if (!was_stopped) cost.AddCost(CmdStartStopVehicle(v, false));
749  }
750 
751  if (cost.Succeeded() && nothing_to_do) cost = CommandCost(STR_ERROR_AUTOREPLACE_NOTHING_TO_DO);
752  return cost;
753 }
754 
768 CommandCost CmdSetAutoReplace(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
769 {
771  if (c == nullptr) return CMD_ERROR;
772 
773  EngineID old_engine_type = GB(p2, 0, 16);
774  EngineID new_engine_type = GB(p2, 16, 16);
775  GroupID id_g = GB(p1, 16, 16);
776  CommandCost cost;
777 
778  if (Group::IsValidID(id_g) ? Group::Get(id_g)->owner != _current_company : !IsAllGroupID(id_g) && !IsDefaultGroupID(id_g)) return CMD_ERROR;
779  if (!Engine::IsValidID(old_engine_type)) return CMD_ERROR;
780 
781  if (new_engine_type != INVALID_ENGINE) {
782  if (!Engine::IsValidID(new_engine_type)) return CMD_ERROR;
783  if (!CheckAutoreplaceValidity(old_engine_type, new_engine_type, _current_company)) return CMD_ERROR;
784 
785  cost = AddEngineReplacementForCompany(c, old_engine_type, new_engine_type, id_g, HasBit(p1, 0), flags);
786  } else {
787  cost = RemoveEngineReplacementForCompany(c, old_engine_type, id_g, flags);
788  }
789 
790  if (flags & DC_EXEC) {
792  if (IsLocalCompany()) SetWindowDirty(WC_REPLACE_VEHICLE, Engine::Get(old_engine_type)->type);
793 
794  const VehicleType vt = Engine::Get(old_engine_type)->type;
796  }
797  if ((flags & DC_EXEC) && IsLocalCompany()) InvalidateAutoreplaceWindow(old_engine_type, id_g);
798 
799  return cost;
800 }
801 
bool IsEngineBuildable(EngineID engine, VehicleType type, CompanyID company)
Check if an engine is buildable.
Definition: engine.cpp:1078
bool CheckAutoreplaceValidity(EngineID from, EngineID to, CompanyID company)
Checks some basic properties whether autoreplace is allowed.
Owner
Enum for all companies/owners.
Definition: company_type.h:20
VehicleSettings vehicle
options for vehicles
static CommandCost GetNewEngineType(const Vehicle *v, const Company *c, bool always_replace, EngineID &e)
Get the EngineID of the replacement for a vehicle.
static bool IsLocalCompany()
Is the current company the local company?
Definition: company_func.h:45
Vehicle is stopped by the player.
Definition: vehicle_base.h:33
VehicleCargoList cargo
The cargo this vehicle is carrying.
Definition: vehicle_base.h:309
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition: settings.cpp:81
static Titem * GetIfValid(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:257
static const RailtypeInfo * GetRailTypeInfo(RailType railtype)
Returns a pointer to the Railtype information for a given railtype.
Definition: rail.h:306
The information about a vehicle list.
Definition: vehiclelist.h:31
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
Definition: window.cpp:3199
Functions related to the autoreplace GUIs.
Functions and type for generating vehicle lists.
Train vehicle type.
Definition: vehicle_type.h:26
static Titem * Get(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:246
bool CanCarryCargo() const
Determines whether an engine can carry something.
Definition: engine.cpp:173
Conventional Take Off and Landing, i.e. planes.
Definition: engine_type.h:94
Base for the train class.
Stores the state of all random number generators.
Definition: random_func.hpp:35
Train * GetPrevUnit()
Get the previous real (non-articulated part and non rear part of dualheaded engine) vehicle in the co...
Definition: train.h:157
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
Definition: command_func.h:25
Replace vehicle window; Window numbers:
Definition: window_type.h:213
Maximal number of cargo types in a game.
Definition: cargo_type.h:66
bool IsStoppedInDepot() const
Check whether the vehicle is in the depot and stopped.
Definition: vehicle_base.h:516
VehicleType
Available vehicle types.
Definition: vehicle_type.h:23
Road specific functions.
Train * GetNextUnit() const
Get the next real (non-articulated part and non rear part of dualheaded engine) vehicle in the consis...
Definition: train.h:145
static void RestoreRandomSeeds(const SavedRandomSeeds &storage)
Restores previously saved seeds.
Definition: random_func.hpp:54
byte GetBestFittingSubType(Vehicle *v_from, Vehicle *v_for, CargoID dest_cargo_type)
Get the best fitting subtype when &#39;cloning&#39;/&#39;replacing&#39; v_from with v_for.
Functions related to vehicles.
CargoTypes GetUnionOfArticulatedRefitMasks(EngineID engine, bool include_initial_cargo_type)
Ors the refit_masks of all articulated parts.
static CommandCost AddEngineReplacementForCompany(Company *c, EngineID old_engine, EngineID new_engine, GroupID group, bool replace_when_old, DoCommandFlag flags)
Add an engine replacement for the company.
Vehicle data structure.
Definition: vehicle_base.h:212
void ChangeVehicleViewWindow(VehicleID from_index, VehicleID to_index)
Report a change in vehicle IDs (due to autoreplace) to affected vehicle windows.
static bool EnginesHaveCargoInCommon(EngineID engine_a, EngineID engine_b)
Figure out if two engines got at least one type of cargo in common (refitting if needed) ...
Tindex index
Index of this pool item.
Definition: pool_type.hpp:147
T * First() const
Get the first vehicle in the chain.
uint TotalCount() const
Returns sum of cargo, including reserved cargo.
Definition: cargopacket.h:375
clone (and share) an order
Definition: command_type.h:272
Money GetCost() const
The costs as made up to this moment.
Definition: command_type.h:84
RailTypes compatible_railtypes
bitmask to the OTHER railtypes on which an engine of THIS railtype can physically travel ...
Definition: rail.h:190
bool IsArticulatedVehicleCarryingDifferentCargoes(const Vehicle *v, CargoID *cargo_type)
Tests if all parts of an articulated vehicle are refitted to the same cargo.
Common return value for all commands.
Definition: command_type.h:25
static const VehicleID INVALID_VEHICLE
Constant representing a non-existing vehicle.
Definition: vehicle_type.h:57
byte vehstatus
Status.
Definition: vehicle_base.h:317
static Train * From(Vehicle *v)
Converts a Vehicle to SpecializedVehicle with type checking.
CompanySettings settings
settings specific for each company
Definition: company_base.h:129
const Engine * GetEngine() const
Retrieves the engine of the vehicle.
Definition: vehicle.cpp:745
static const uint TILE_SIZE
Tile size in world coordinates.
Definition: tile_type.h:15
void AddCost(const Money &cost)
Adds the given cost to the cost of the command.
Definition: command_type.h:64
Do not refit cargo of a vehicle (used in vehicle orders and auto-replace/auto-new).
Definition: cargo_type.h:69
when autoreplace/autorenew is in progress, this shall prevent truncating the amount of cargo in the v...
Definition: command_type.h:354
RoadType roadtype
Road type.
Definition: engine_type.h:127
bool IsAutoRefit() const
Is this order a auto-refit order.
Definition: order_base.h:117
Pseudo random number generator.
start or stop a vehicle
Definition: command_type.h:313
Invalid cargo type.
Definition: cargo_type.h:70
static bool IsAllGroupID(GroupID id_g)
Checks if a GroupID stands for all vehicles of a company.
Definition: group.h:95
static const RoadTypeInfo * GetRoadTypeInfo(RoadType roadtype)
Returns a pointer to the Roadtype information for a given roadtype.
Definition: road.h:226
Vehicle is crashed.
Definition: vehicle_base.h:39
static CommandCost BuildReplacementVehicle(Vehicle *old_veh, Vehicle **new_vehicle, bool part_of_chain)
Builds and refits a replacement vehicle Important: The old vehicle is still in the original vehicle c...
virtual bool IsPrimaryVehicle() const
Whether this is the primary vehicle in the chain.
Definition: vehicle_base.h:433
RoadTypes powered_roadtypes
bitmask to the OTHER roadtypes on which a vehicle of THIS roadtype generates power ...
Definition: road.h:121
CommandCost DoCommand(const CommandContainer *container, DoCommandFlag flags)
Shorthand for calling the long DoCommand with a container.
Definition: command.cpp:443
byte subtype
Type of aircraft.
Definition: engine_type.h:103
void ChangeVehicleViewports(VehicleID from_index, VehicleID to_index)
Switches viewports following vehicles, which get autoreplaced.
Definition: window.cpp:3531
void ConsistChanged(ConsistChangeFlags allowed_changes)
Recalculates the cached stuff of a train.
Definition: train_cmd.cpp:109
bool IsRefit() const
Is this order a refit order.
Definition: order_base.h:110
Functions related to engines.
uint32 VehicleID
The type all our vehicle IDs have.
Definition: vehicle_type.h:18
StringID GetErrorMessage() const
Returns the error message of a command.
Definition: command_type.h:142
DoCommandFlag
List of flags for a command.
Definition: command_type.h:344
simple wagon, not motorized
Definition: engine_type.h:31
bool Succeeded() const
Did this command succeed?
Definition: command_type.h:152
Definition of base types and functions in a cross-platform compatible way.
bool IsArticulatedPart() const
Check if the vehicle is an articulated part of an engine.
Definition: vehicle_base.h:892
A number of safeguards to prevent using unsafe methods.
static uint CeilDiv(uint a, uint b)
Computes ceil(a / b) for non-negative a and b.
Definition: math_func.hpp:316
uint16 GroupID
Type for all group identifiers.
Definition: group_type.h:15
VehicleType type
Vehicle type, ie VEH_ROAD, VEH_TRAIN, etc.
Definition: engine_base.h:42
static CargoID GetNewCargoTypeForReplace(Vehicle *v, EngineID engine_type, bool part_of_chain)
Function to find what type of cargo to refit to when autoreplacing.
CargoID cargo_type
type of cargo this vehicle is carrying
Definition: vehicle_base.h:305
bool IsFrontEngine() const
Check if the vehicle is a front engine.
Definition: vehicle_base.h:883
byte misc_flags
Miscellaneous flags.
Definition: engine_type.h:144
TileIndex tile
Current tile index.
Definition: vehicle_base.h:230
CommandCost CheckOwnership(Owner owner, TileIndex tile)
Check whether the current owner owns something.
static EngineID EngineReplacementForCompany(const Company *c, EngineID engine, GroupID group, bool *replace_when_old=nullptr)
Retrieve the engine replacement for the given company and original engine type.
bool IsRearDualheaded() const
Tell if we are dealing with the rear end of a multiheaded engine.
Owner owner
Which company owns the vehicle?
Definition: vehicle_base.h:273
bool renew_keep_length
sell some wagons if after autoreplace the train is longer than before
static T min(const T a, const T b)
Returns the minimum of two values.
Definition: math_func.hpp:42
CommandCost CmdSetAutoReplace(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Change engine renewal parameters.
Vehicle * First() const
Get the first vehicle of this vehicle chain.
Definition: vehicle_base.h:594
bool Failed() const
Did this command fail?
Definition: command_type.h:161
void ChangeVehicleNews(VehicleID from_index, VehicleID to_index)
Report a change in vehicle IDs (due to autoreplace) to affected vehicle news.
Definition: news_gui.cpp:931
void CheckCargoCapacity(Vehicle *v)
Check the capacity of all vehicles in a chain and spread cargo if needed.
void InvalidateAutoreplaceWindow(EngineID e, GroupID id_g)
Rebuild the left autoreplace list if an engine is removed or added.
static void NewEvent(CompanyID company, ScriptEvent *event)
Queue a new event for an AI.
Definition: ai_core.cpp:238
autoreplace/autorenew is in progress, this shall disable vehicle limits when building, and ignore certain restrictions when undoing things (like vehicle attach callback)
Definition: command_type.h:353
static bool VerifyAutoreplaceRefitForOrders(const Vehicle *v, EngineID engine_type)
Tests whether refit orders that applied to v will also apply to the new vehicle type.
&#39;Train&#39; is either a loco or a wagon.
Definition: train.h:87
execute the given command
Definition: command_type.h:346
static const EngineID INVALID_ENGINE
Constant denoting an invalid engine.
Definition: engine_type.h:176
static void TransferCargo(Vehicle *old_veh, Vehicle *new_head, bool part_of_chain)
Transfer cargo from a single (articulated )old vehicle to the new vehicle chain.
static CommandCost CmdStartStopVehicle(const Vehicle *v, bool evaluate_callback)
Issue a start/stop command.
Functions related to companies.
Functions related to articulated vehicles.
add a vehicle to a group
Definition: command_type.h:322
bool NeedsAutorenewing(const Company *c, bool use_renew_setting=true) const
Function to tell if a vehicle needs to be autorenewed.
Definition: vehicle.cpp:142
uint16 EngineID
Unique identification number of an engine.
Definition: engine_type.h:23
uint32 TileIndex
The index/ID of a Tile.
Definition: tile_type.h:80
Vehicle * Next() const
Get the next vehicle of this vehicle.
Definition: vehicle_base.h:581
turn a train around
Definition: command_type.h:224
void GetArticulatedRefitMasks(EngineID engine, bool include_initial_cargo_type, CargoTypes *union_mask, CargoTypes *intersection_mask)
Merges the refit_masks of all articulated parts.
static void UpdateAutoreplace(CompanyID company)
Update autoreplace_defined and autoreplace_finished of all statistics of a company.
Definition: group_cmd.cpp:212
static uint GB(const T x, const uint8 s, const uint8 n)
Fetch n bits from x, started at bit s.
uint16 cached_total_length
Length of the whole vehicle (valid only for the first engine).
VehicleType type
Type of vehicle.
Definition: vehicle_type.h:54
Valid changes while vehicle is loading/unloading.
Definition: train.h:51
Reverse the visible direction of the vehicle.
Definition: train.h:30
void CopyVehicleConfigAndStatistics(const Vehicle *src)
Copy certain configurations and statistics of a vehicle after successful autoreplace/renew The functi...
Definition: vehicle_base.h:712
Functions related to commands.
CompanyID _current_company
Company currently doing an action.
Definition: company_cmd.cpp:47
static bool IsValidID(size_t index)
Tests whether given index can be used to get valid (non-nullptr) Titem.
Definition: pool_type.hpp:235
static WindowClass GetWindowClassForVehicleType(VehicleType vt)
Get WindowClass for vehicle list of given vehicle type.
Definition: vehicle_gui.h:93
Aircraft vehicle type.
Definition: vehicle_type.h:29
static void free(const void *ptr)
Version of the standard free that accepts const pointers.
Definition: depend.cpp:131
CommandCost CmdAutoreplaceVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Autoreplaces a vehicle Trains are replaced as a whole chain, free wagons in depot are replaced on the...
EngineID engine_type
The type of engine used for this vehicle.
Definition: vehicle_base.h:288
static bool HasBit(const T x, const uint8 y)
Checks if a bit in a value is set.
Base functions for all AIs.
static void SaveRandomSeeds(SavedRandomSeeds *storage)
Saves the current seeds.
Definition: random_func.hpp:44
static CommandCost CmdMoveVehicle(const Vehicle *v, const Vehicle *after, DoCommandFlag flags, bool whole_chain)
Issue a train vehicle move command.
static CommandCost ReplaceFreeUnit(Vehicle **single_unit, DoCommandFlag flags, bool *nothing_to_do)
Replace a single unit in a free wagon chain.
byte CargoID
Cargo slots to indicate a cargo type within a game.
Definition: cargo_type.h:22
Road vehicle is a tram/light rail vehicle.
Definition: engine_type.h:156
New vehicles.
Definition: economy_type.h:152
virtual bool IsChainInDepot() const
Check whether the whole vehicle chain is in the depot.
Definition: vehicle_base.h:510
static CommandCost ReplaceChain(Vehicle **chain, DoCommandFlag flags, bool wagon_removal, bool *nothing_to_do)
Replace a whole vehicle chain.
move a rail vehicle (in the depot)
Definition: command_type.h:222
static CommandCost RemoveEngineReplacementForCompany(Company *c, EngineID engine, GroupID group, DoCommandFlag flags)
Remove an engine replacement for the company.
static CommandCost CopyHeadSpecificThings(Vehicle *old_head, Vehicle *new_head, DoCommandFlag flags)
Copy head specific things to the new vehicle chain after it was successfully constructed.
Functions related to autoreplacing.
Road vehicle type.
Definition: vehicle_type.h:27
No roadtypes.
Definition: road_type.h:42
GroupID group_id
Index of group Pool array.
Definition: vehicle_base.h:326
GroundVehicleCache gcache
Cache of often calculated values.
CargoID GetRefitCargo() const
Get the cargo to to refit to.
Definition: order_base.h:124
uint8 max_train_length
maximum length for trains