OpenTTD Source  13.2.1
autoreplace_cmd.cpp
Go to the documentation of this file.
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  */
7 
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"
30 
31 #include "table/strings.h"
32 
33 #include "safeguards.h"
34 
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);
38 
45 static bool EnginesHaveCargoInCommon(EngineID engine_a, EngineID engine_b)
46 {
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);
50 }
51 
60 {
61  assert(Engine::IsValidID(from) && Engine::IsValidID(to));
62 
63  /* we can't replace an engine into itself (that would be autorenew) */
64  if (from == to) return false;
65 
66  const Engine *e_from = Engine::Get(from);
67  const Engine *e_to = Engine::Get(to);
68  VehicleType type = e_from->type;
69 
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;
72 
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;
77 
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;
81  }
82 
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;
86 
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;
90 
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;
95 
96  default: break;
97  }
98 
99  /* the engines needs to be able to carry the same cargo */
100  return EnginesHaveCargoInCommon(from, to);
101 }
102 
110 {
111  assert(v == nullptr || v->First() == v);
112 
113  for (Vehicle *src = v; src != nullptr; src = src->Next()) {
114  assert(src->cargo.TotalCount() == src->cargo.ActionCount(VehicleCargoList::MTA_KEEP));
115 
116  /* Do we need to more cargo away? */
117  if (src->cargo.TotalCount() <= src->cargo_cap) continue;
118 
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;
124 
125  uint amount = std::min(to_spread, dest->cargo_cap - dest->cargo.TotalCount());
126  src->cargo.Shift(amount, &dest->cargo);
127  to_spread -= amount;
128  }
129 
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);
132  }
133 }
134 
144 static void TransferCargo(Vehicle *old_veh, Vehicle *new_head, bool part_of_chain)
145 {
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;
154  }
155  if (src->cargo_type >= NUM_CARGO || src->cargo.TotalCount() == 0) continue;
156 
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;
164  }
165  if (dest->cargo_type != src->cargo_type) continue;
166 
167  uint amount = std::min(src->cargo.TotalCount(), dest->cargo_cap - dest->cargo.TotalCount());
168  if (amount <= 0) continue;
169 
170  src->cargo.Shift(amount, &dest->cargo);
171  }
172  }
173 
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);
176 }
177 
184 static bool VerifyAutoreplaceRefitForOrders(const Vehicle *v, EngineID engine_type)
185 {
186  CargoTypes union_refit_mask_a = GetUnionOfArticulatedRefitMasks(v->engine_type, false);
187  CargoTypes union_refit_mask_b = GetUnionOfArticulatedRefitMasks(engine_type, false);
188 
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();
193 
194  if (!HasBit(union_refit_mask_a, cargo_type)) continue;
195  if (!HasBit(union_refit_mask_b, cargo_type)) return false;
196  }
197 
198  return true;
199 }
200 
208 {
209  CargoTypes union_refit_mask = GetUnionOfArticulatedRefitMasks(engine_type, false);
210 
211  const Order *o;
212  const Vehicle *u = (v->type == VEH_TRAIN) ? v->First() : v;
213 
214  const OrderList *orders = u->orders;
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;
220  }
221 
222  return -1;
223 }
224 
234 static CargoID GetNewCargoTypeForReplace(Vehicle *v, EngineID engine_type, bool part_of_chain)
235 {
236  CargoTypes available_cargo_types, union_mask;
237  GetArticulatedRefitMasks(engine_type, true, &union_mask, &available_cargo_types);
238 
239  if (union_mask == 0) return CT_NO_REFIT; // Don't try to refit an engine with no cargo capacity
240 
241  CargoID cargo_type;
242  if (IsArticulatedVehicleCarryingDifferentCargoes(v, &cargo_type)) return CT_INVALID; // We cannot refit to mixed cargoes in an automated way
243 
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.
246 
247  if (!part_of_chain) return CT_NO_REFIT;
248 
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 */
251 
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;
256  }
257 
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
261 
262  if (part_of_chain && !VerifyAutoreplaceRefitForOrders(v, engine_type)) return CT_INVALID; // Some refit orders lose their effect
263 
264  return cargo_type;
265  }
266 }
267 
276 static CommandCost GetNewEngineType(const Vehicle *v, const Company *c, bool always_replace, EngineID &e)
277 {
278  assert(v->type != VEH_TRAIN || !v->IsArticulatedPart());
279 
280  e = INVALID_ENGINE;
281 
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();
285  }
286 
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;
290 
291  /* Autoreplace, if engine is available */
293  return CommandCost();
294  }
295 
296  /* Autorenew if needed */
297  if (v->NeedsAutorenewing(c)) e = v->engine_type;
298 
299  /* Nothing to do or all is fine? */
300  if (e == INVALID_ENGINE || IsEngineBuildable(e, v->type, _current_company)) return CommandCost();
301 
302  /* The engine we need is not available. Report error to user */
303  return CommandCost(STR_ERROR_RAIL_VEHICLE_NOT_AVAILABLE + v->type);
304 }
305 
314 static CommandCost BuildReplacementVehicle(Vehicle *old_veh, Vehicle **new_vehicle, bool part_of_chain)
315 {
316  *new_vehicle = nullptr;
317 
318  /* Shall the vehicle be replaced? */
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
324 
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();
329 
330  SetDParam(0, old_veh->index);
331 
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);
341  }
342 
343  AddVehicleAdviceNewsItem(STR_NEWS_VEHICLE_AUTORENEW_FAILED, old_veh->index);
344  return CommandCost();
345  }
346 
347  /* Build the new vehicle */
348  VehicleID new_veh_id;
349  std::tie(cost, new_veh_id, std::ignore, std::ignore, std::ignore) = Command<CMD_BUILD_VEHICLE>::Do(DC_EXEC | DC_AUTOREPLACE, old_veh->tile, e, true, CT_INVALID, INVALID_CLIENT_ID);
350  if (cost.Failed()) return cost;
351 
352  Vehicle *new_veh = Vehicle::Get(new_veh_id);
353  *new_vehicle = new_veh;
354 
355  /* Refit the vehicle if needed */
356  if (refit_cargo != CT_NO_REFIT) {
357  byte subtype = GetBestFittingSubType(old_veh, new_veh, refit_cargo);
358 
359  cost.AddCost(std::get<0>(Command<CMD_REFIT_VEHICLE>::Do(DC_EXEC, new_veh->index, refit_cargo, subtype, false, false, 0)));
360  assert(cost.Succeeded()); // This should be ensured by GetNewCargoTypeForReplace()
361  }
362 
363  /* Try to reverse the vehicle, but do not care if it fails as the new type might not be reversible */
364  if (new_veh->type == VEH_TRAIN && HasBit(Train::From(old_veh)->flags, VRF_REVERSE_DIRECTION)) {
366  }
367 
368  return cost;
369 }
370 
377 static inline CommandCost DoCmdStartStopVehicle(const Vehicle *v, bool evaluate_callback)
378 {
379  return Command<CMD_START_STOP_VEHICLE>::Do(DC_EXEC | DC_AUTOREPLACE, v->index, evaluate_callback);
380 }
381 
390 static inline CommandCost CmdMoveVehicle(const Vehicle *v, const Vehicle *after, DoCommandFlag flags, bool whole_chain)
391 {
392  return Command<CMD_MOVE_RAIL_VEHICLE>::Do(flags | DC_NO_CARGO_CAP_CHECK, v->index, after != nullptr ? after->index : INVALID_VEHICLE, whole_chain);
393 }
394 
402 {
403  CommandCost cost = CommandCost();
404 
405  /* Share orders */
406  if (cost.Succeeded() && old_head != new_head) cost.AddCost(Command<CMD_CLONE_ORDER>::Do(DC_EXEC, CO_SHARE, new_head->index, old_head->index));
407 
408  /* Copy group membership */
409  if (cost.Succeeded() && old_head != new_head) cost.AddCost(std::get<0>(Command<CMD_ADD_VEHICLE_GROUP>::Do(DC_EXEC, old_head->group_id, new_head->index, false)));
410 
411  /* Perform start/stop check whether the new vehicle suits newgrf restrictions etc. */
412  if (cost.Succeeded()) {
413  /* Start the vehicle, might be denied by certain things */
414  assert((new_head->vehstatus & VS_STOPPED) != 0);
415  cost.AddCost(DoCmdStartStopVehicle(new_head, true));
416 
417  /* Stop the vehicle again, but do not care about evil newgrfs allowing starting but not stopping :p */
418  if (cost.Succeeded()) cost.AddCost(DoCmdStartStopVehicle(new_head, false));
419  }
420 
421  /* Last do those things which do never fail (resp. we do not care about), but which are not undo-able */
422  if (cost.Succeeded() && old_head != new_head && (flags & DC_EXEC) != 0) {
423  /* Copy other things which cannot be copied by a command and which shall not stay resetted from the build vehicle command */
424  new_head->CopyVehicleConfigAndStatistics(old_head);
426 
427  /* Switch vehicle windows/news to the new vehicle, so they are not closed/deleted when the old vehicle is sold */
428  ChangeVehicleViewports(old_head->index, new_head->index);
429  ChangeVehicleViewWindow(old_head->index, new_head->index);
430  ChangeVehicleNews(old_head->index, new_head->index);
431  }
432 
433  return cost;
434 }
435 
443 static CommandCost ReplaceFreeUnit(Vehicle **single_unit, DoCommandFlag flags, bool *nothing_to_do)
444 {
445  Train *old_v = Train::From(*single_unit);
446  assert(!old_v->IsArticulatedPart() && !old_v->IsRearDualheaded());
447 
449 
450  /* Build and refit replacement vehicle */
451  Vehicle *new_v = nullptr;
452  cost.AddCost(BuildReplacementVehicle(old_v, &new_v, false));
453 
454  /* Was a new vehicle constructed? */
455  if (cost.Succeeded() && new_v != nullptr) {
456  *nothing_to_do = false;
457 
458  if ((flags & DC_EXEC) != 0) {
459  /* Move the new vehicle behind the old */
460  CmdMoveVehicle(new_v, old_v, DC_EXEC, false);
461 
462  /* Take over cargo
463  * Note: We do only transfer cargo from the old to the new vehicle.
464  * I.e. we do not transfer remaining cargo to other vehicles.
465  * Else you would also need to consider moving cargo to other free chains,
466  * or doing the same in ReplaceChain(), which would be quite troublesome.
467  */
468  TransferCargo(old_v, new_v, false);
469 
470  *single_unit = new_v;
471 
472  AI::NewEvent(old_v->owner, new ScriptEventVehicleAutoReplaced(old_v->index, new_v->index));
473  }
474 
475  /* Sell the old vehicle */
476  cost.AddCost(Command<CMD_SELL_VEHICLE>::Do(flags, old_v->index, false, false, INVALID_CLIENT_ID));
477 
478  /* If we are not in DC_EXEC undo everything */
479  if ((flags & DC_EXEC) == 0) {
481  }
482  }
483 
484  return cost;
485 }
486 
495 static CommandCost ReplaceChain(Vehicle **chain, DoCommandFlag flags, bool wagon_removal, bool *nothing_to_do)
496 {
497  Vehicle *old_head = *chain;
498  assert(old_head->IsPrimaryVehicle());
499 
501 
502  if (old_head->type == VEH_TRAIN) {
503  /* Store the length of the old vehicle chain, rounded up to whole tiles */
504  uint16 old_total_length = CeilDiv(Train::From(old_head)->gcache.cached_total_length, TILE_SIZE) * TILE_SIZE;
505 
506  int num_units = 0;
507  for (Train *w = Train::From(old_head); w != nullptr; w = w->GetNextUnit()) num_units++;
508 
509  Train **old_vehs = CallocT<Train *>(num_units);
510  Train **new_vehs = CallocT<Train *>(num_units);
511  Money *new_costs = MallocT<Money>(num_units);
512 
513  /* Collect vehicles and build replacements
514  * Note: The replacement vehicles can only successfully build as long as the old vehicles are still in their chain */
515  int i;
516  Train *w;
517  for (w = Train::From(old_head), i = 0; w != nullptr; w = w->GetNextUnit(), i++) {
518  assert(i < num_units);
519  old_vehs[i] = w;
520 
521  CommandCost ret = BuildReplacementVehicle(old_vehs[i], (Vehicle**)&new_vehs[i], true);
522  cost.AddCost(ret);
523  if (cost.Failed()) break;
524 
525  new_costs[i] = ret.GetCost();
526  if (new_vehs[i] != nullptr) *nothing_to_do = false;
527  }
528  Train *new_head = (new_vehs[0] != nullptr ? new_vehs[0] : old_vehs[0]);
529 
530  /* Note: When autoreplace has already failed here, old_vehs[] is not completely initialized. But it is also not needed. */
531  if (cost.Succeeded()) {
532  /* Separate the head, so we can start constructing the new chain */
533  Train *second = Train::From(old_head)->GetNextUnit();
534  if (second != nullptr) cost.AddCost(CmdMoveVehicle(second, nullptr, DC_EXEC | DC_AUTOREPLACE, true));
535 
536  assert(Train::From(new_head)->GetNextUnit() == nullptr);
537 
538  /* Append engines to the new chain
539  * We do this from back to front, so that the head of the temporary vehicle chain does not change all the time.
540  * That way we also have less trouble when exceeding the unitnumber limit.
541  * OTOH the vehicle attach callback is more expensive this way :s */
542  Train *last_engine = nullptr;
543  if (cost.Succeeded()) {
544  for (int i = num_units - 1; i > 0; i--) {
545  Train *append = (new_vehs[i] != nullptr ? new_vehs[i] : old_vehs[i]);
546 
547  if (RailVehInfo(append->engine_type)->railveh_type == RAILVEH_WAGON) continue;
548 
549  if (new_vehs[i] != nullptr) {
550  /* Move the old engine to a separate row with DC_AUTOREPLACE. Else
551  * moving the wagon in front may fail later due to unitnumber limit.
552  * (We have to attach wagons without DC_AUTOREPLACE.) */
553  CmdMoveVehicle(old_vehs[i], nullptr, DC_EXEC | DC_AUTOREPLACE, false);
554  }
555 
556  if (last_engine == nullptr) last_engine = append;
557  cost.AddCost(CmdMoveVehicle(append, new_head, DC_EXEC, false));
558  if (cost.Failed()) break;
559  }
560  if (last_engine == nullptr) last_engine = new_head;
561  }
562 
563  /* When wagon removal is enabled and the new engines without any wagons are already longer than the old, we have to fail */
564  if (cost.Succeeded() && wagon_removal && new_head->gcache.cached_total_length > old_total_length) cost = CommandCost(STR_ERROR_TRAIN_TOO_LONG_AFTER_REPLACEMENT);
565 
566  /* Append/insert wagons into the new vehicle chain
567  * 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.
568  */
569  if (cost.Succeeded()) {
570  for (int i = num_units - 1; i > 0; i--) {
571  assert(last_engine != nullptr);
572  Vehicle *append = (new_vehs[i] != nullptr ? new_vehs[i] : old_vehs[i]);
573 
574  if (RailVehInfo(append->engine_type)->railveh_type == RAILVEH_WAGON) {
575  /* Insert wagon after 'last_engine' */
576  CommandCost res = CmdMoveVehicle(append, last_engine, DC_EXEC, false);
577 
578  /* When we allow removal of wagons, either the move failing due
579  * to the train becoming too long, or the train becoming longer
580  * would move the vehicle to the empty vehicle chain. */
581  if (wagon_removal && (res.Failed() ? res.GetErrorMessage() == STR_ERROR_TRAIN_TOO_LONG : new_head->gcache.cached_total_length > old_total_length)) {
582  CmdMoveVehicle(append, nullptr, DC_EXEC | DC_AUTOREPLACE, false);
583  break;
584  }
585 
586  cost.AddCost(res);
587  if (cost.Failed()) break;
588  } else {
589  /* We have reached 'last_engine', continue with the next engine towards the front */
590  assert(append == last_engine);
591  last_engine = last_engine->GetPrevUnit();
592  }
593  }
594  }
595 
596  /* Sell superfluous new vehicles that could not be inserted. */
597  if (cost.Succeeded() && wagon_removal) {
599  for (int i = 1; i < num_units; i++) {
600  Vehicle *wagon = new_vehs[i];
601  if (wagon == nullptr) continue;
602  if (wagon->First() == new_head) break;
603 
604  assert(RailVehInfo(wagon->engine_type)->railveh_type == RAILVEH_WAGON);
605 
606  /* Sell wagon */
607  [[maybe_unused]] CommandCost ret = Command<CMD_SELL_VEHICLE>::Do(DC_EXEC, wagon->index, false, false, INVALID_CLIENT_ID);
608  assert(ret.Succeeded());
609  new_vehs[i] = nullptr;
610 
611  /* Revert the money subtraction when the vehicle was built.
612  * This value is different from the sell value, esp. because of refitting */
613  cost.AddCost(-new_costs[i]);
614  }
615  }
616 
617  /* The new vehicle chain is constructed, now take over orders and everything... */
618  if (cost.Succeeded()) cost.AddCost(CopyHeadSpecificThings(old_head, new_head, flags));
619 
620  if (cost.Succeeded()) {
621  /* Success ! */
622  if ((flags & DC_EXEC) != 0 && new_head != old_head) {
623  *chain = new_head;
624  AI::NewEvent(old_head->owner, new ScriptEventVehicleAutoReplaced(old_head->index, new_head->index));
625  }
626 
627  /* Transfer cargo of old vehicles and sell them */
628  for (int i = 0; i < num_units; i++) {
629  Vehicle *w = old_vehs[i];
630  /* Is the vehicle again part of the new chain?
631  * Note: We cannot test 'new_vehs[i] != nullptr' as wagon removal might cause to remove both */
632  if (w->First() == new_head) continue;
633 
634  if ((flags & DC_EXEC) != 0) TransferCargo(w, new_head, true);
635 
636  /* Sell the vehicle.
637  * Note: This might temporarily construct new trains, so use DC_AUTOREPLACE to prevent
638  * it from failing due to engine limits. */
640  if ((flags & DC_EXEC) != 0) {
641  old_vehs[i] = nullptr;
642  if (i == 0) old_head = nullptr;
643  }
644  }
645 
646  if ((flags & DC_EXEC) != 0) CheckCargoCapacity(new_head);
647  }
648 
649  /* If we are not in DC_EXEC undo everything, i.e. rearrange old vehicles.
650  * We do this from back to front, so that the head of the temporary vehicle chain does not change all the time.
651  * Note: The vehicle attach callback is disabled here :) */
652  if ((flags & DC_EXEC) == 0) {
653  /* Separate the head, so we can reattach the old vehicles */
654  Train *second = Train::From(old_head)->GetNextUnit();
655  if (second != nullptr) CmdMoveVehicle(second, nullptr, DC_EXEC | DC_AUTOREPLACE, true);
656 
657  assert(Train::From(old_head)->GetNextUnit() == nullptr);
658 
659  for (int i = num_units - 1; i > 0; i--) {
660  [[maybe_unused]] CommandCost ret = CmdMoveVehicle(old_vehs[i], old_head, DC_EXEC | DC_AUTOREPLACE, false);
661  assert(ret.Succeeded());
662  }
663  }
664  }
665 
666  /* Finally undo buying of new vehicles */
667  if ((flags & DC_EXEC) == 0) {
668  for (int i = num_units - 1; i >= 0; i--) {
669  if (new_vehs[i] != nullptr) {
670  Command<CMD_SELL_VEHICLE>::Do(DC_EXEC, new_vehs[i]->index, false, false, INVALID_CLIENT_ID);
671  new_vehs[i] = nullptr;
672  }
673  }
674  }
675 
676  free(old_vehs);
677  free(new_vehs);
678  free(new_costs);
679  } else {
680  /* Build and refit replacement vehicle */
681  Vehicle *new_head = nullptr;
682  cost.AddCost(BuildReplacementVehicle(old_head, &new_head, true));
683 
684  /* Was a new vehicle constructed? */
685  if (cost.Succeeded() && new_head != nullptr) {
686  *nothing_to_do = false;
687 
688  /* The new vehicle is constructed, now take over orders and everything... */
689  cost.AddCost(CopyHeadSpecificThings(old_head, new_head, flags));
690 
691  if (cost.Succeeded()) {
692  /* The new vehicle is constructed, now take over cargo */
693  if ((flags & DC_EXEC) != 0) {
694  TransferCargo(old_head, new_head, true);
695  *chain = new_head;
696 
697  AI::NewEvent(old_head->owner, new ScriptEventVehicleAutoReplaced(old_head->index, new_head->index));
698  }
699 
700  /* Sell the old vehicle */
701  cost.AddCost(Command<CMD_SELL_VEHICLE>::Do(flags, old_head->index, false, false, INVALID_CLIENT_ID));
702  }
703 
704  /* If we are not in DC_EXEC undo everything */
705  if ((flags & DC_EXEC) == 0) {
707  }
708  }
709  }
710 
711  return cost;
712 }
713 
722 {
723  Vehicle *v = Vehicle::GetIfValid(veh_id);
724  if (v == nullptr) return CMD_ERROR;
725 
726  CommandCost ret = CheckOwnership(v->owner);
727  if (ret.Failed()) return ret;
728 
729  if (v->vehstatus & VS_CRASHED) return CMD_ERROR;
730 
731  bool free_wagon = false;
732  if (v->type == VEH_TRAIN) {
733  Train *t = Train::From(v);
734  if (t->IsArticulatedPart() || t->IsRearDualheaded()) return CMD_ERROR;
735  free_wagon = !t->IsFrontEngine();
736  if (free_wagon && t->First()->IsFrontEngine()) return CMD_ERROR;
737  } else {
738  if (!v->IsPrimaryVehicle()) return CMD_ERROR;
739  }
740  if (!v->IsChainInDepot()) return CMD_ERROR;
741 
743  bool wagon_removal = c->settings.renew_keep_length;
744 
745  const Group *g = Group::GetIfValid(v->group_id);
746  if (g != nullptr) wagon_removal = HasBit(g->flags, GroupFlags::GF_REPLACE_WAGON_REMOVAL);
747 
748  /* Test whether any replacement is set, before issuing a whole lot of commands that would end in nothing changed */
749  Vehicle *w = v;
750  bool any_replacements = false;
751  while (w != nullptr) {
752  EngineID e;
753  CommandCost cost = GetNewEngineType(w, c, false, e);
754  if (cost.Failed()) return cost;
755  any_replacements |= (e != INVALID_ENGINE);
756  w = (!free_wagon && w->type == VEH_TRAIN ? Train::From(w)->GetNextUnit() : nullptr);
757  }
758 
760  bool nothing_to_do = true;
761 
762  if (any_replacements) {
763  bool was_stopped = free_wagon || ((v->vehstatus & VS_STOPPED) != 0);
764 
765  /* Stop the vehicle */
766  if (!was_stopped) cost.AddCost(DoCmdStartStopVehicle(v, true));
767  if (cost.Failed()) return cost;
768 
769  assert(free_wagon || v->IsStoppedInDepot());
770 
771  /* We have to construct the new vehicle chain to test whether it is valid.
772  * Vehicle construction needs random bits, so we have to save the random seeds
773  * to prevent desyncs and to replay newgrf callbacks during DC_EXEC */
774  SavedRandomSeeds saved_seeds;
775  SaveRandomSeeds(&saved_seeds);
776  if (free_wagon) {
777  cost.AddCost(ReplaceFreeUnit(&v, flags & ~DC_EXEC, &nothing_to_do));
778  } else {
779  cost.AddCost(ReplaceChain(&v, flags & ~DC_EXEC, wagon_removal, &nothing_to_do));
780  }
781  RestoreRandomSeeds(saved_seeds);
782 
783  if (cost.Succeeded() && (flags & DC_EXEC) != 0) {
784  CommandCost ret;
785  if (free_wagon) {
786  ret = ReplaceFreeUnit(&v, flags, &nothing_to_do);
787  } else {
788  ret = ReplaceChain(&v, flags, wagon_removal, &nothing_to_do);
789  }
790  assert(ret.Succeeded() && ret.GetCost() == cost.GetCost());
791  }
792 
793  /* Restart the vehicle */
794  if (!was_stopped) cost.AddCost(DoCmdStartStopVehicle(v, false));
795  }
796 
797  if (cost.Succeeded() && nothing_to_do) cost = CommandCost(STR_ERROR_AUTOREPLACE_NOTHING_TO_DO);
798  return cost;
799 }
800 
810 CommandCost CmdSetAutoReplace(DoCommandFlag flags, GroupID id_g, EngineID old_engine_type, EngineID new_engine_type, bool when_old)
811 {
813  if (c == nullptr) return CMD_ERROR;
814 
815  CommandCost cost;
816 
817  if (Group::IsValidID(id_g) ? Group::Get(id_g)->owner != _current_company : !IsAllGroupID(id_g) && !IsDefaultGroupID(id_g)) return CMD_ERROR;
818  if (!Engine::IsValidID(old_engine_type)) return CMD_ERROR;
819  if (Group::IsValidID(id_g) && Group::Get(id_g)->vehicle_type != Engine::Get(old_engine_type)->type) return CMD_ERROR;
820 
821  if (new_engine_type != INVALID_ENGINE) {
822  if (!Engine::IsValidID(new_engine_type)) return CMD_ERROR;
823  if (!CheckAutoreplaceValidity(old_engine_type, new_engine_type, _current_company)) return CMD_ERROR;
824 
825  cost = AddEngineReplacementForCompany(c, old_engine_type, new_engine_type, id_g, when_old, flags);
826  } else {
827  cost = RemoveEngineReplacementForCompany(c, old_engine_type, id_g, flags);
828  }
829 
830  if (flags & DC_EXEC) {
832  if (IsLocalCompany()) SetWindowDirty(WC_REPLACE_VEHICLE, Engine::Get(old_engine_type)->type);
833 
834  const VehicleType vt = Engine::Get(old_engine_type)->type;
836  }
837  if ((flags & DC_EXEC) && IsLocalCompany()) InvalidateAutoreplaceWindow(old_engine_type, id_g);
838 
839  return cost;
840 }
841 
VEH_AIRCRAFT
@ VEH_AIRCRAFT
Aircraft vehicle type.
Definition: vehicle_type.h:27
VehicleCargoList::TotalCount
uint TotalCount() const
Returns sum of cargo, including reserved cargo.
Definition: cargopacket.h:361
Vehicle::IsChainInDepot
virtual bool IsChainInDepot() const
Check whether the whole vehicle chain is in the depot.
Definition: vehicle_base.h:537
INVALID_ENGINE
static const EngineID INVALID_ENGINE
Constant denoting an invalid engine.
Definition: engine_type.h:203
VehicleOrderID
byte VehicleOrderID
The index of an order within its current vehicle (not pool related)
Definition: order_type.h:15
Order::IsRefit
bool IsRefit() const
Is this order a refit order.
Definition: order_base.h:118
CmdMoveVehicle
static CommandCost CmdMoveVehicle(const Vehicle *v, const Vehicle *after, DoCommandFlag flags, bool whole_chain)
Issue a train vehicle move command.
Definition: autoreplace_cmd.cpp:390
order_cmd.h
Pool::PoolItem<&_engine_pool >::Get
static Titem * Get(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:337
SetWindowDirty
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
Definition: window.cpp:3156
INVALID_CLIENT_ID
@ INVALID_CLIENT_ID
Client is not part of anything.
Definition: network_type.h:48
train.h
AircraftVehicleInfo::subtype
byte subtype
Type of aircraft.
Definition: engine_type.h:103
command_func.h
CopyHeadSpecificThings
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.
Definition: autoreplace_cmd.cpp:401
Pool::PoolItem<&_vehicle_pool >::GetIfValid
static Titem * GetIfValid(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:348
CMD_ERROR
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
Definition: command_func.h:28
GetNewEngineType
static CommandCost GetNewEngineType(const Vehicle *v, const Company *c, bool always_replace, EngineID &e)
Get the EngineID of the replacement for a vehicle.
Definition: autoreplace_cmd.cpp:276
VehicleListIdentifier
The information about a vehicle list.
Definition: vehiclelist.h:29
Vehicle::Next
Vehicle * Next() const
Get the next vehicle of this vehicle.
Definition: vehicle_base.h:610
ChangeVehicleViewWindow
void ChangeVehicleViewWindow(VehicleID from_index, VehicleID to_index)
Report a change in vehicle IDs (due to autoreplace) to affected vehicle windows.
Definition: vehicle_gui.cpp:1482
GetArticulatedRefitMasks
void GetArticulatedRefitMasks(EngineID engine, bool include_initial_cargo_type, CargoTypes *union_mask, CargoTypes *intersection_mask)
Merges the refit_masks of all articulated parts.
Definition: articulated_vehicles.cpp:194
vehiclelist.h
Vehicle::vehstatus
byte vehstatus
Status.
Definition: vehicle_base.h:332
SavedRandomSeeds
Stores the state of all random number generators.
Definition: random_func.hpp:33
Pool::PoolItem::index
Tindex index
Index of this pool item.
Definition: pool_type.hpp:235
CargoSpec::Get
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo ID.
Definition: cargotype.h:118
Vehicle::group_id
GroupID group_id
Index of group Pool array.
Definition: vehicle_base.h:341
EngineReplacementForCompany
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.
Definition: autoreplace_func.h:39
HasBit
static bool HasBit(const T x, const uint8 y)
Checks if a bit in a value is set.
Definition: bitmath_func.hpp:103
SaveRandomSeeds
static void SaveRandomSeeds(SavedRandomSeeds *storage)
Saves the current seeds.
Definition: random_func.hpp:42
autoreplace_gui.h
TILE_SIZE
static const uint TILE_SIZE
Tile size in world coordinates.
Definition: tile_type.h:15
GroundVehicle::IsRearDualheaded
bool IsRearDualheaded() const
Tell if we are dealing with the rear end of a multiheaded engine.
Definition: ground_vehicle.hpp:334
Engine
Definition: engine_base.h:36
VEH_ROAD
@ VEH_ROAD
Road vehicle type.
Definition: vehicle_type.h:25
Vehicle
Vehicle data structure.
Definition: vehicle_base.h:224
Vehicle::IsPrimaryVehicle
virtual bool IsPrimaryVehicle() const
Whether this is the primary vehicle in the chain.
Definition: vehicle_base.h:460
RoadVehicleInfo::roadtype
RoadType roadtype
Road type.
Definition: engine_type.h:127
Vehicle::owner
Owner owner
Which company owns the vehicle?
Definition: vehicle_base.h:288
Owner
Owner
Enum for all companies/owners.
Definition: company_type.h:18
DC_EXEC
@ DC_EXEC
execute the given command
Definition: command_type.h:357
CommandCost::GetErrorMessage
StringID GetErrorMessage() const
Returns the error message of a command.
Definition: command_type.h:141
IsLocalCompany
static bool IsLocalCompany()
Is the current company the local company?
Definition: company_func.h:43
SetDParam
static void SetDParam(uint n, uint64 v)
Set a string parameter v at index n in the global string parameter array.
Definition: strings_func.h:196
DoCommandFlag
DoCommandFlag
List of flags for a command.
Definition: command_type.h:355
BuildReplacementVehicle
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...
Definition: autoreplace_cmd.cpp:314
CommandCost::Succeeded
bool Succeeded() const
Did this command succeed?
Definition: command_type.h:151
RestoreRandomSeeds
static void RestoreRandomSeeds(const SavedRandomSeeds &storage)
Restores previously saved seeds.
Definition: random_func.hpp:52
train_cmd.h
Vehicle::IsArticulatedPart
bool IsArticulatedPart() const
Check if the vehicle is an articulated part of an engine.
Definition: vehicle_base.h:922
ai.hpp
ChangeVehicleViewports
void ChangeVehicleViewports(VehicleID from_index, VehicleID to_index)
Switches viewports following vehicles, which get autoreplaced.
Definition: window.cpp:3478
GetRailTypeInfo
static const RailtypeInfo * GetRailTypeInfo(RailType railtype)
Returns a pointer to the Railtype information for a given railtype.
Definition: rail.h:304
Group
Group data.
Definition: group.h:74
CompanySettings::renew_keep_length
bool renew_keep_length
sell some wagons if after autoreplace the train is longer than before
Definition: settings_type.h:580
Vehicle::Orders
IterateWrapper Orders() const
Returns an iterable ensemble of orders of a vehicle.
Definition: vehicle_base.h:1052
EngineID
uint16 EngineID
Unique identification number of an engine.
Definition: engine_type.h:21
EnginesHaveCargoInCommon
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)
Definition: autoreplace_cmd.cpp:45
RoadTypeInfo::powered_roadtypes
RoadTypes powered_roadtypes
bitmask to the OTHER roadtypes on which a vehicle of THIS roadtype generates power
Definition: road.h:120
CheckOwnership
CommandCost CheckOwnership(Owner owner, TileIndex tile)
Check whether the current owner owns something.
Definition: company_cmd.cpp:316
GroundVehicleCache::cached_total_length
uint16 cached_total_length
Length of the whole vehicle (valid only for the first engine).
Definition: ground_vehicle.hpp:42
Order::GetRefitCargo
CargoID GetRefitCargo() const
Get the cargo to to refit to.
Definition: order_base.h:132
GetIncompatibleRefitOrderIdForAutoreplace
static int GetIncompatibleRefitOrderIdForAutoreplace(const Vehicle *v, EngineID engine_type)
Gets the index of the first refit order that is incompatible with the requested engine type.
Definition: autoreplace_cmd.cpp:207
AI::NewEvent
static void NewEvent(CompanyID company, ScriptEvent *event)
Queue a new event for an AI.
Definition: ai_core.cpp:236
CommandCost
Common return value for all commands.
Definition: command_type.h:24
GetUnionOfArticulatedRefitMasks
CargoTypes GetUnionOfArticulatedRefitMasks(EngineID engine, bool include_initial_cargo_type)
Ors the refit_masks of all articulated parts.
Definition: articulated_vehicles.cpp:220
CmdAutoreplaceVehicle
CommandCost CmdAutoreplaceVehicle(DoCommandFlag flags, VehicleID veh_id)
Autoreplaces a vehicle Trains are replaced as a whole chain, free wagons in depot are replaced on the...
Definition: autoreplace_cmd.cpp:721
DoCmdStartStopVehicle
static CommandCost DoCmdStartStopVehicle(const Vehicle *v, bool evaluate_callback)
Issue a start/stop command.
Definition: autoreplace_cmd.cpp:377
Vehicle::tile
TileIndex tile
Current tile index.
Definition: vehicle_base.h:245
INVALID_VEHICLE
static const VehicleID INVALID_VEHICLE
Constant representing a non-existing vehicle.
Definition: vehicle_type.h:55
Vehicle::engine_type
EngineID engine_type
The type of engine used for this vehicle.
Definition: vehicle_base.h:302
VS_CRASHED
@ VS_CRASHED
Vehicle is crashed.
Definition: vehicle_base.h:41
Vehicle::cargo
VehicleCargoList cargo
The cargo this vehicle is carrying.
Definition: vehicle_base.h:324
CommandCost::Failed
bool Failed() const
Did this command fail?
Definition: command_type.h:160
WC_REPLACE_VEHICLE
@ WC_REPLACE_VEHICLE
Replace vehicle window; Window numbers:
Definition: window_type.h:211
GroundVehicle::gcache
GroundVehicleCache gcache
Cache of often calculated values.
Definition: ground_vehicle.hpp:80
autoreplace_cmd.h
VerifyAutoreplaceRefitForOrders
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.
Definition: autoreplace_cmd.cpp:184
Vehicle::IsFrontEngine
bool IsFrontEngine() const
Check if the vehicle is a front engine.
Definition: vehicle_base.h:913
_settings_game
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition: settings.cpp:54
CompanyProperties::settings
CompanySettings settings
settings specific for each company
Definition: company_base.h:106
DC_AUTOREPLACE
@ DC_AUTOREPLACE
autoreplace/autorenew is in progress, this shall disable vehicle limits when building,...
Definition: command_type.h:364
VS_STOPPED
@ VS_STOPPED
Vehicle is stopped by the player.
Definition: vehicle_base.h:35
IsArticulatedVehicleCarryingDifferentCargoes
bool IsArticulatedVehicleCarryingDifferentCargoes(const Vehicle *v, CargoID *cargo_type)
Tests if all parts of an articulated vehicle are refitted to the same cargo.
Definition: articulated_vehicles.cpp:248
Vehicle::GetEngine
const Engine * GetEngine() const
Retrieves the engine of the vehicle.
Definition: vehicle.cpp:741
safeguards.h
Vehicle::CopyVehicleConfigAndStatistics
void CopyVehicleConfigAndStatistics(const Vehicle *src)
Copy certain configurations and statistics of a vehicle after successful autoreplace/renew The functi...
Definition: vehicle_base.h:741
GroupStatistics::UpdateAutoreplace
static void UpdateAutoreplace(CompanyID company)
Update autoreplace_defined and autoreplace_finished of all statistics of a company.
Definition: group_cmd.cpp:220
Train
'Train' is either a loco or a wagon.
Definition: train.h:89
vehicle_cmd.h
CommandCost::GetCost
Money GetCost() const
The costs as made up to this moment.
Definition: command_type.h:83
VRF_REVERSE_DIRECTION
@ VRF_REVERSE_DIRECTION
Reverse the visible direction of the vehicle.
Definition: train.h:28
ChangeVehicleNews
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:1000
road.h
IsAllGroupID
static bool IsAllGroupID(GroupID id_g)
Checks if a GroupID stands for all vehicles of a company.
Definition: group.h:101
CmdSetAutoReplace
CommandCost CmdSetAutoReplace(DoCommandFlag flags, GroupID id_g, EngineID old_engine_type, EngineID new_engine_type, bool when_old)
Change engine renewal parameters.
Definition: autoreplace_cmd.cpp:810
CheckCargoCapacity
void CheckCargoCapacity(Vehicle *v)
Check the capacity of all vehicles in a chain and spread cargo if needed.
Definition: autoreplace_cmd.cpp:109
Group::flags
uint8 flags
Group flags.
Definition: group.h:79
CommandCost::AddCost
void AddCost(const Money &cost)
Adds the given cost to the cost of the command.
Definition: command_type.h:63
stdafx.h
VehicleType
VehicleType
Available vehicle types.
Definition: vehicle_type.h:21
RemoveEngineReplacementForCompany
static CommandCost RemoveEngineReplacementForCompany(Company *c, EngineID engine, GroupID group, DoCommandFlag flags)
Remove an engine replacement for the company.
Definition: autoreplace_func.h:93
EngineInfo::misc_flags
byte misc_flags
Miscellaneous flags.
Definition: engine_type.h:153
OrderList::GetOrderAt
Order * GetOrderAt(int index) const
Get a certain order of the order chain.
Definition: order_cmd.cpp:357
RAILVEH_WAGON
@ RAILVEH_WAGON
simple wagon, not motorized
Definition: engine_type.h:29
group_cmd.h
GetWindowClassForVehicleType
static WindowClass GetWindowClassForVehicleType(VehicleType vt)
Get WindowClass for vehicle list of given vehicle type.
Definition: vehicle_gui.h:96
_current_company
CompanyID _current_company
Company currently doing an action.
Definition: company_cmd.cpp:47
vehicle_func.h
strings_func.h
Vehicle::First
Vehicle * First() const
Get the first vehicle of this vehicle chain.
Definition: vehicle_base.h:623
Engine::CanCarryCargo
bool CanCarryCargo() const
Determines whether an engine can carry something.
Definition: engine.cpp:164
GroupID
uint16 GroupID
Type for all group identifiers.
Definition: group_type.h:13
CCF_LOADUNLOAD
@ CCF_LOADUNLOAD
Valid changes while vehicle is loading/unloading.
Definition: train.h:49
GetNewCargoTypeForReplace
static CargoID GetNewCargoTypeForReplace(Vehicle *v, EngineID engine_type, bool part_of_chain)
Function to find what type of cargo to refit to when autoreplacing.
Definition: autoreplace_cmd.cpp:234
SpecializedVehicle< Train, Type >::From
static Train * From(Vehicle *v)
Converts a Vehicle to SpecializedVehicle with type checking.
Definition: vehicle_base.h:1183
Train::ConsistChanged
void ConsistChanged(ConsistChangeFlags allowed_changes)
Recalculates the cached stuff of a train.
Definition: train_cmd.cpp:108
DC_NO_CARGO_CAP_CHECK
@ DC_NO_CARGO_CAP_CHECK
when autoreplace/autorenew is in progress, this shall prevent truncating the amount of cargo in the v...
Definition: command_type.h:365
OrderList
Shared order list linking together the linked list of orders and the list of vehicles sharing this or...
Definition: order_base.h:260
Train::GetPrevUnit
Train * GetPrevUnit()
Get the previous real (non-articulated part and non rear part of dualheaded engine) vehicle in the co...
Definition: train.h:160
NUM_CARGO
@ NUM_CARGO
Maximal number of cargo types in a game.
Definition: cargo_type.h:65
GetRoadTypeInfo
static const RoadTypeInfo * GetRoadTypeInfo(RoadType roadtype)
Returns a pointer to the Roadtype information for a given roadtype.
Definition: road.h:225
CargoSpec::name
StringID name
Name of this type of cargo.
Definition: cargotype.h:71
RailVehicleInfo::railtype
RailType railtype
Railtype, mangled if elrail is disabled.
Definition: engine_type.h:46
company_func.h
EXPENSES_NEW_VEHICLES
@ EXPENSES_NEW_VEHICLES
New vehicles.
Definition: economy_type.h:159
VehicleID
uint32 VehicleID
The type all our vehicle IDs have.
Definition: vehicle_type.h:16
InvalidateAutoreplaceWindow
void InvalidateAutoreplaceWindow(EngineID e, GroupID id_g)
Rebuild the left autoreplace list if an engine is removed or added.
Definition: autoreplace_gui.cpp:52
AddVehicleAdviceNewsItem
static void AddVehicleAdviceNewsItem(StringID string, VehicleID vehicle)
Adds a vehicle-advice news item.
Definition: news_func.h:40
AIR_CTOL
@ AIR_CTOL
Conventional Take Off and Landing, i.e. planes.
Definition: engine_type.h:94
CommandHelper
Definition: command_func.h:94
random_func.hpp
Vehicle::NeedsAutorenewing
bool NeedsAutorenewing(const Company *c, bool use_renew_setting=true) const
Function to tell if a vehicle needs to be autorenewed.
Definition: vehicle.cpp:140
RailtypeInfo::compatible_railtypes
RailTypes compatible_railtypes
bitmask to the OTHER railtypes on which an engine of THIS railtype can physically travel
Definition: rail.h:188
CargoList< VehicleCargoList, CargoPacketList >::MTA_KEEP
@ MTA_KEEP
Keep the cargo in the vehicle.
Definition: cargopacket.h:217
OverflowSafeInt< int64 >
TransferCargo
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.
Definition: autoreplace_cmd.cpp:144
CargoID
byte CargoID
Cargo slots to indicate a cargo type within a game.
Definition: cargo_type.h:20
Vehicle::IsStoppedInDepot
bool IsStoppedInDepot() const
Check whether the vehicle is in the depot and stopped.
Definition: vehicle_base.h:543
AddEngineReplacementForCompany
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.
Definition: autoreplace_func.h:80
Vehicle::cargo_type
CargoID cargo_type
type of cargo this vehicle is carrying
Definition: vehicle_base.h:320
VehicleSettings::max_train_length
uint8 max_train_length
maximum length for trains
Definition: settings_type.h:487
Train::GetNextUnit
Train * GetNextUnit() const
Get the next real (non-articulated part and non rear part of dualheaded engine) vehicle in the consis...
Definition: train.h:148
EF_ROAD_TRAM
@ EF_ROAD_TRAM
Road vehicle is a tram/light rail vehicle.
Definition: engine_type.h:167
CeilDiv
static uint CeilDiv(uint a, uint b)
Computes ceil(a / b) for non-negative a and b.
Definition: math_func.hpp:280
CheckAutoreplaceValidity
bool CheckAutoreplaceValidity(EngineID from, EngineID to, CompanyID company)
Checks some basic properties whether autoreplace is allowed.
Definition: autoreplace_cmd.cpp:59
ReplaceChain
static CommandCost ReplaceChain(Vehicle **chain, DoCommandFlag flags, bool wagon_removal, bool *nothing_to_do)
Replace a whole vehicle chain.
Definition: autoreplace_cmd.cpp:495
articulated_vehicles.h
GameSettings::vehicle
VehicleSettings vehicle
options for vehicles
Definition: settings_type.h:595
VEH_TRAIN
@ VEH_TRAIN
Train vehicle type.
Definition: vehicle_type.h:24
Pool::PoolItem<&_engine_pool >::IsValidID
static bool IsValidID(size_t index)
Tests whether given index can be used to get valid (non-nullptr) Titem.
Definition: pool_type.hpp:326
BaseVehicle::type
VehicleType type
Type of vehicle.
Definition: vehicle_type.h:52
SpecializedVehicle::First
T * First() const
Get the first vehicle in the chain.
Definition: vehicle_base.h:1080
autoreplace_func.h
free
static void free(const void *ptr)
Version of the standard free that accepts const pointers.
Definition: stdafx.h:470
CT_INVALID
@ CT_INVALID
Invalid cargo type.
Definition: cargo_type.h:69
GF_REPLACE_WAGON_REMOVAL
@ GF_REPLACE_WAGON_REMOVAL
If set, autoreplace will perform wagon removal on vehicles in this group.
Definition: group.h:69
ROADTYPES_NONE
@ ROADTYPES_NONE
No roadtypes.
Definition: road_type.h:37
Company
Definition: company_base.h:117
Vehicle::orders
OrderList * orders
Pointer to the order list for this vehicle.
Definition: vehicle_base.h:336
CT_NO_REFIT
@ CT_NO_REFIT
Do not refit cargo of a vehicle (used in vehicle orders and auto-replace/auto-new).
Definition: cargo_type.h:68
Order
Definition: order_base.h:36
IsEngineBuildable
bool IsEngineBuildable(EngineID engine, VehicleType type, CompanyID company)
Check if an engine is buildable.
Definition: engine.cpp:1168
GetBestFittingSubType
byte GetBestFittingSubType(Vehicle *v_from, Vehicle *v_for, CargoID dest_cargo_type)
Get the best fitting subtype when 'cloning'/'replacing' v_from with v_for.
Definition: vehicle_gui.cpp:439
OrderList::GetNumOrders
VehicleOrderID GetNumOrders() const
Get number of orders in the order list.
Definition: order_base.h:322
ReplaceFreeUnit
static CommandCost ReplaceFreeUnit(Vehicle **single_unit, DoCommandFlag flags, bool *nothing_to_do)
Replace a single unit in a free wagon chain.
Definition: autoreplace_cmd.cpp:443
Engine::type
VehicleType type
Vehicle type, ie VEH_ROAD, VEH_TRAIN, etc.
Definition: engine_base.h:55
engine_func.h
GroupStatistics::AddProfitLastYear
static void AddProfitLastYear(const Vehicle *v)
Add a vehicle's last year profit to the profit sum of its group.
Definition: group_cmd.cpp:167
news_func.h