OpenTTD Source  12.0-beta2
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 
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 = std::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 = std::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 Vehicle *u = (v->type == VEH_TRAIN) ? v->First() : v;
185  for (const Order *o : u->Orders()) {
186  if (!o->IsRefit() || o->IsAutoRefit()) continue;
187  CargoID cargo_type = o->GetRefitCargo();
188 
189  if (!HasBit(union_refit_mask_a, cargo_type)) continue;
190  if (!HasBit(union_refit_mask_b, cargo_type)) return false;
191  }
192 
193  return true;
194 }
195 
203 {
204  CargoTypes union_refit_mask = GetUnionOfArticulatedRefitMasks(engine_type, false);
205 
206  const Order *o;
207  const Vehicle *u = (v->type == VEH_TRAIN) ? v->First() : v;
208 
209  const OrderList *orders = u->orders.list;
210  if (orders == nullptr) return -1;
211  for (VehicleOrderID i = 0; i < orders->GetNumOrders(); i++) {
212  o = orders->GetOrderAt(i);
213  if (!o->IsRefit()) continue;
214  if (!HasBit(union_refit_mask, o->GetRefitCargo())) return i;
215  }
216 
217  return -1;
218 }
219 
229 static CargoID GetNewCargoTypeForReplace(Vehicle *v, EngineID engine_type, bool part_of_chain)
230 {
231  CargoTypes available_cargo_types, union_mask;
232  GetArticulatedRefitMasks(engine_type, true, &union_mask, &available_cargo_types);
233 
234  if (union_mask == 0) return CT_NO_REFIT; // Don't try to refit an engine with no cargo capacity
235 
236  CargoID cargo_type;
237  if (IsArticulatedVehicleCarryingDifferentCargoes(v, &cargo_type)) return CT_INVALID; // We cannot refit to mixed cargoes in an automated way
238 
239  if (cargo_type == CT_INVALID) {
240  if (v->type != VEH_TRAIN) return CT_NO_REFIT; // If the vehicle does not carry anything at all, every replacement is fine.
241 
242  if (!part_of_chain) return CT_NO_REFIT;
243 
244  /* the old engine didn't have cargo capacity, but the new one does
245  * now we will figure out what cargo the train is carrying and refit to fit this */
246 
247  for (v = v->First(); v != nullptr; v = v->Next()) {
248  if (!v->GetEngine()->CanCarryCargo()) continue;
249  /* Now we found a cargo type being carried on the train and we will see if it is possible to carry to this one */
250  if (HasBit(available_cargo_types, v->cargo_type)) return v->cargo_type;
251  }
252 
253  return CT_NO_REFIT; // We failed to find a cargo type on the old vehicle and we will not refit the new one
254  } else {
255  if (!HasBit(available_cargo_types, cargo_type)) return CT_INVALID; // We can't refit the vehicle to carry the cargo we want
256 
257  if (part_of_chain && !VerifyAutoreplaceRefitForOrders(v, engine_type)) return CT_INVALID; // Some refit orders lose their effect
258 
259  return cargo_type;
260  }
261 }
262 
271 static CommandCost GetNewEngineType(const Vehicle *v, const Company *c, bool always_replace, EngineID &e)
272 {
273  assert(v->type != VEH_TRAIN || !v->IsArticulatedPart());
274 
275  e = INVALID_ENGINE;
276 
277  if (v->type == VEH_TRAIN && Train::From(v)->IsRearDualheaded()) {
278  /* we build the rear ends of multiheaded trains with the front ones */
279  return CommandCost();
280  }
281 
282  bool replace_when_old;
283  e = EngineReplacementForCompany(c, v->engine_type, v->group_id, &replace_when_old);
284  if (!always_replace && replace_when_old && !v->NeedsAutorenewing(c, false)) e = INVALID_ENGINE;
285 
286  /* Autoreplace, if engine is available */
288  return CommandCost();
289  }
290 
291  /* Autorenew if needed */
292  if (v->NeedsAutorenewing(c)) e = v->engine_type;
293 
294  /* Nothing to do or all is fine? */
295  if (e == INVALID_ENGINE || IsEngineBuildable(e, v->type, _current_company)) return CommandCost();
296 
297  /* The engine we need is not available. Report error to user */
298  return CommandCost(STR_ERROR_RAIL_VEHICLE_NOT_AVAILABLE + v->type);
299 }
300 
309 static CommandCost BuildReplacementVehicle(Vehicle *old_veh, Vehicle **new_vehicle, bool part_of_chain)
310 {
311  *new_vehicle = nullptr;
312 
313  /* Shall the vehicle be replaced? */
315  EngineID e;
316  CommandCost cost = GetNewEngineType(old_veh, c, true, e);
317  if (cost.Failed()) return cost;
318  if (e == INVALID_ENGINE) return CommandCost(); // neither autoreplace is set, nor autorenew is triggered
319 
320  /* Does it need to be refitted */
321  CargoID refit_cargo = GetNewCargoTypeForReplace(old_veh, e, part_of_chain);
322  if (refit_cargo == CT_INVALID) {
323  if (!IsLocalCompany()) return CommandCost();
324 
325  SetDParam(0, old_veh->index);
326 
327  int order_id = GetIncompatibleRefitOrderIdForAutoreplace(old_veh, e);
328  if (order_id != -1) {
329  /* Orders contained a refit order that is incompatible with the new vehicle. */
330  SetDParam(1, STR_ERROR_AUTOREPLACE_INCOMPATIBLE_REFIT);
331  SetDParam(2, order_id + 1); // 1-based indexing for display
332  } else {
333  /* Current cargo is incompatible with the new vehicle. */
334  SetDParam(1, STR_ERROR_AUTOREPLACE_INCOMPATIBLE_CARGO);
335  SetDParam(2, CargoSpec::Get(old_veh->cargo_type)->name);
336  }
337 
338  AddVehicleAdviceNewsItem(STR_NEWS_VEHICLE_AUTORENEW_FAILED, old_veh->index);
339  return CommandCost();
340  }
341 
342  /* Build the new vehicle */
343  cost = DoCommand(old_veh->tile, e | (CT_INVALID << 24), 0, DC_EXEC | DC_AUTOREPLACE, GetCmdBuildVeh(old_veh));
344  if (cost.Failed()) return cost;
345 
346  Vehicle *new_veh = Vehicle::Get(_new_vehicle_id);
347  *new_vehicle = new_veh;
348 
349  /* Refit the vehicle if needed */
350  if (refit_cargo != CT_NO_REFIT) {
351  byte subtype = GetBestFittingSubType(old_veh, new_veh, refit_cargo);
352 
353  cost.AddCost(DoCommand(0, new_veh->index, refit_cargo | (subtype << 8), DC_EXEC, GetCmdRefitVeh(new_veh)));
354  assert(cost.Succeeded()); // This should be ensured by GetNewCargoTypeForReplace()
355  }
356 
357  /* Try to reverse the vehicle, but do not care if it fails as the new type might not be reversible */
358  if (new_veh->type == VEH_TRAIN && HasBit(Train::From(old_veh)->flags, VRF_REVERSE_DIRECTION)) {
359  DoCommand(0, new_veh->index, true, DC_EXEC, CMD_REVERSE_TRAIN_DIRECTION);
360  }
361 
362  return cost;
363 }
364 
371 static inline CommandCost CmdStartStopVehicle(const Vehicle *v, bool evaluate_callback)
372 {
373  return DoCommand(0, v->index, evaluate_callback ? 1 : 0, DC_EXEC | DC_AUTOREPLACE, CMD_START_STOP_VEHICLE);
374 }
375 
384 static inline CommandCost CmdMoveVehicle(const Vehicle *v, const Vehicle *after, DoCommandFlag flags, bool whole_chain)
385 {
386  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);
387 }
388 
396 {
397  CommandCost cost = CommandCost();
398 
399  /* Share orders */
400  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));
401 
402  /* Copy group membership */
403  if (cost.Succeeded() && old_head != new_head) cost.AddCost(DoCommand(0, old_head->group_id, new_head->index, DC_EXEC, CMD_ADD_VEHICLE_GROUP));
404 
405  /* Perform start/stop check whether the new vehicle suits newgrf restrictions etc. */
406  if (cost.Succeeded()) {
407  /* Start the vehicle, might be denied by certain things */
408  assert((new_head->vehstatus & VS_STOPPED) != 0);
409  cost.AddCost(CmdStartStopVehicle(new_head, true));
410 
411  /* Stop the vehicle again, but do not care about evil newgrfs allowing starting but not stopping :p */
412  if (cost.Succeeded()) cost.AddCost(CmdStartStopVehicle(new_head, false));
413  }
414 
415  /* Last do those things which do never fail (resp. we do not care about), but which are not undo-able */
416  if (cost.Succeeded() && old_head != new_head && (flags & DC_EXEC) != 0) {
417  /* Copy other things which cannot be copied by a command and which shall not stay resetted from the build vehicle command */
418  new_head->CopyVehicleConfigAndStatistics(old_head);
419 
420  /* Switch vehicle windows/news to the new vehicle, so they are not closed/deleted when the old vehicle is sold */
421  ChangeVehicleViewports(old_head->index, new_head->index);
422  ChangeVehicleViewWindow(old_head->index, new_head->index);
423  ChangeVehicleNews(old_head->index, new_head->index);
424  }
425 
426  return cost;
427 }
428 
436 static CommandCost ReplaceFreeUnit(Vehicle **single_unit, DoCommandFlag flags, bool *nothing_to_do)
437 {
438  Train *old_v = Train::From(*single_unit);
439  assert(!old_v->IsArticulatedPart() && !old_v->IsRearDualheaded());
440 
442 
443  /* Build and refit replacement vehicle */
444  Vehicle *new_v = nullptr;
445  cost.AddCost(BuildReplacementVehicle(old_v, &new_v, false));
446 
447  /* Was a new vehicle constructed? */
448  if (cost.Succeeded() && new_v != nullptr) {
449  *nothing_to_do = false;
450 
451  if ((flags & DC_EXEC) != 0) {
452  /* Move the new vehicle behind the old */
453  CmdMoveVehicle(new_v, old_v, DC_EXEC, false);
454 
455  /* Take over cargo
456  * Note: We do only transfer cargo from the old to the new vehicle.
457  * I.e. we do not transfer remaining cargo to other vehicles.
458  * Else you would also need to consider moving cargo to other free chains,
459  * or doing the same in ReplaceChain(), which would be quite troublesome.
460  */
461  TransferCargo(old_v, new_v, false);
462 
463  *single_unit = new_v;
464 
465  AI::NewEvent(old_v->owner, new ScriptEventVehicleAutoReplaced(old_v->index, new_v->index));
466  }
467 
468  /* Sell the old vehicle */
469  cost.AddCost(DoCommand(0, old_v->index, 0, flags, GetCmdSellVeh(old_v)));
470 
471  /* If we are not in DC_EXEC undo everything */
472  if ((flags & DC_EXEC) == 0) {
473  DoCommand(0, new_v->index, 0, DC_EXEC, GetCmdSellVeh(new_v));
474  }
475  }
476 
477  return cost;
478 }
479 
488 static CommandCost ReplaceChain(Vehicle **chain, DoCommandFlag flags, bool wagon_removal, bool *nothing_to_do)
489 {
490  Vehicle *old_head = *chain;
491  assert(old_head->IsPrimaryVehicle());
492 
494 
495  if (old_head->type == VEH_TRAIN) {
496  /* Store the length of the old vehicle chain, rounded up to whole tiles */
497  uint16 old_total_length = CeilDiv(Train::From(old_head)->gcache.cached_total_length, TILE_SIZE) * TILE_SIZE;
498 
499  int num_units = 0;
500  for (Train *w = Train::From(old_head); w != nullptr; w = w->GetNextUnit()) num_units++;
501 
502  Train **old_vehs = CallocT<Train *>(num_units);
503  Train **new_vehs = CallocT<Train *>(num_units);
504  Money *new_costs = MallocT<Money>(num_units);
505 
506  /* Collect vehicles and build replacements
507  * Note: The replacement vehicles can only successfully build as long as the old vehicles are still in their chain */
508  int i;
509  Train *w;
510  for (w = Train::From(old_head), i = 0; w != nullptr; w = w->GetNextUnit(), i++) {
511  assert(i < num_units);
512  old_vehs[i] = w;
513 
514  CommandCost ret = BuildReplacementVehicle(old_vehs[i], (Vehicle**)&new_vehs[i], true);
515  cost.AddCost(ret);
516  if (cost.Failed()) break;
517 
518  new_costs[i] = ret.GetCost();
519  if (new_vehs[i] != nullptr) *nothing_to_do = false;
520  }
521  Train *new_head = (new_vehs[0] != nullptr ? new_vehs[0] : old_vehs[0]);
522 
523  /* Note: When autoreplace has already failed here, old_vehs[] is not completely initialized. But it is also not needed. */
524  if (cost.Succeeded()) {
525  /* Separate the head, so we can start constructing the new chain */
526  Train *second = Train::From(old_head)->GetNextUnit();
527  if (second != nullptr) cost.AddCost(CmdMoveVehicle(second, nullptr, DC_EXEC | DC_AUTOREPLACE, true));
528 
529  assert(Train::From(new_head)->GetNextUnit() == nullptr);
530 
531  /* Append engines to the new chain
532  * We do this from back to front, so that the head of the temporary vehicle chain does not change all the time.
533  * That way we also have less trouble when exceeding the unitnumber limit.
534  * OTOH the vehicle attach callback is more expensive this way :s */
535  Train *last_engine = nullptr;
536  if (cost.Succeeded()) {
537  for (int i = num_units - 1; i > 0; i--) {
538  Train *append = (new_vehs[i] != nullptr ? new_vehs[i] : old_vehs[i]);
539 
540  if (RailVehInfo(append->engine_type)->railveh_type == RAILVEH_WAGON) continue;
541 
542  if (new_vehs[i] != nullptr) {
543  /* Move the old engine to a separate row with DC_AUTOREPLACE. Else
544  * moving the wagon in front may fail later due to unitnumber limit.
545  * (We have to attach wagons without DC_AUTOREPLACE.) */
546  CmdMoveVehicle(old_vehs[i], nullptr, DC_EXEC | DC_AUTOREPLACE, false);
547  }
548 
549  if (last_engine == nullptr) last_engine = append;
550  cost.AddCost(CmdMoveVehicle(append, new_head, DC_EXEC, false));
551  if (cost.Failed()) break;
552  }
553  if (last_engine == nullptr) last_engine = new_head;
554  }
555 
556  /* When wagon removal is enabled and the new engines without any wagons are already longer than the old, we have to fail */
557  if (cost.Succeeded() && wagon_removal && new_head->gcache.cached_total_length > old_total_length) cost = CommandCost(STR_ERROR_TRAIN_TOO_LONG_AFTER_REPLACEMENT);
558 
559  /* Append/insert wagons into the new vehicle chain
560  * 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.
561  */
562  if (cost.Succeeded()) {
563  for (int i = num_units - 1; i > 0; i--) {
564  assert(last_engine != nullptr);
565  Vehicle *append = (new_vehs[i] != nullptr ? new_vehs[i] : old_vehs[i]);
566 
567  if (RailVehInfo(append->engine_type)->railveh_type == RAILVEH_WAGON) {
568  /* Insert wagon after 'last_engine' */
569  CommandCost res = CmdMoveVehicle(append, last_engine, DC_EXEC, false);
570 
571  /* When we allow removal of wagons, either the move failing due
572  * to the train becoming too long, or the train becoming longer
573  * would move the vehicle to the empty vehicle chain. */
574  if (wagon_removal && (res.Failed() ? res.GetErrorMessage() == STR_ERROR_TRAIN_TOO_LONG : new_head->gcache.cached_total_length > old_total_length)) {
575  CmdMoveVehicle(append, nullptr, DC_EXEC | DC_AUTOREPLACE, false);
576  break;
577  }
578 
579  cost.AddCost(res);
580  if (cost.Failed()) break;
581  } else {
582  /* We have reached 'last_engine', continue with the next engine towards the front */
583  assert(append == last_engine);
584  last_engine = last_engine->GetPrevUnit();
585  }
586  }
587  }
588 
589  /* Sell superfluous new vehicles that could not be inserted. */
590  if (cost.Succeeded() && wagon_removal) {
592  for (int i = 1; i < num_units; i++) {
593  Vehicle *wagon = new_vehs[i];
594  if (wagon == nullptr) continue;
595  if (wagon->First() == new_head) break;
596 
597  assert(RailVehInfo(wagon->engine_type)->railveh_type == RAILVEH_WAGON);
598 
599  /* Sell wagon */
600  [[maybe_unused]] CommandCost ret = DoCommand(0, wagon->index, 0, DC_EXEC, GetCmdSellVeh(wagon));
601  assert(ret.Succeeded());
602  new_vehs[i] = nullptr;
603 
604  /* Revert the money subtraction when the vehicle was built.
605  * This value is different from the sell value, esp. because of refitting */
606  cost.AddCost(-new_costs[i]);
607  }
608  }
609 
610  /* The new vehicle chain is constructed, now take over orders and everything... */
611  if (cost.Succeeded()) cost.AddCost(CopyHeadSpecificThings(old_head, new_head, flags));
612 
613  if (cost.Succeeded()) {
614  /* Success ! */
615  if ((flags & DC_EXEC) != 0 && new_head != old_head) {
616  *chain = new_head;
617  AI::NewEvent(old_head->owner, new ScriptEventVehicleAutoReplaced(old_head->index, new_head->index));
618  }
619 
620  /* Transfer cargo of old vehicles and sell them */
621  for (int i = 0; i < num_units; i++) {
622  Vehicle *w = old_vehs[i];
623  /* Is the vehicle again part of the new chain?
624  * Note: We cannot test 'new_vehs[i] != nullptr' as wagon removal might cause to remove both */
625  if (w->First() == new_head) continue;
626 
627  if ((flags & DC_EXEC) != 0) TransferCargo(w, new_head, true);
628 
629  /* Sell the vehicle.
630  * Note: This might temporarily construct new trains, so use DC_AUTOREPLACE to prevent
631  * it from failing due to engine limits. */
632  cost.AddCost(DoCommand(0, w->index, 0, flags | DC_AUTOREPLACE, GetCmdSellVeh(w)));
633  if ((flags & DC_EXEC) != 0) {
634  old_vehs[i] = nullptr;
635  if (i == 0) old_head = nullptr;
636  }
637  }
638 
639  if ((flags & DC_EXEC) != 0) CheckCargoCapacity(new_head);
640  }
641 
642  /* If we are not in DC_EXEC undo everything, i.e. rearrange old vehicles.
643  * We do this from back to front, so that the head of the temporary vehicle chain does not change all the time.
644  * Note: The vehicle attach callback is disabled here :) */
645  if ((flags & DC_EXEC) == 0) {
646  /* Separate the head, so we can reattach the old vehicles */
647  Train *second = Train::From(old_head)->GetNextUnit();
648  if (second != nullptr) CmdMoveVehicle(second, nullptr, DC_EXEC | DC_AUTOREPLACE, true);
649 
650  assert(Train::From(old_head)->GetNextUnit() == nullptr);
651 
652  for (int i = num_units - 1; i > 0; i--) {
653  [[maybe_unused]] CommandCost ret = CmdMoveVehicle(old_vehs[i], old_head, DC_EXEC | DC_AUTOREPLACE, false);
654  assert(ret.Succeeded());
655  }
656  }
657  }
658 
659  /* Finally undo buying of new vehicles */
660  if ((flags & DC_EXEC) == 0) {
661  for (int i = num_units - 1; i >= 0; i--) {
662  if (new_vehs[i] != nullptr) {
663  DoCommand(0, new_vehs[i]->index, 0, DC_EXEC, GetCmdSellVeh(new_vehs[i]));
664  new_vehs[i] = nullptr;
665  }
666  }
667  }
668 
669  free(old_vehs);
670  free(new_vehs);
671  free(new_costs);
672  } else {
673  /* Build and refit replacement vehicle */
674  Vehicle *new_head = nullptr;
675  cost.AddCost(BuildReplacementVehicle(old_head, &new_head, true));
676 
677  /* Was a new vehicle constructed? */
678  if (cost.Succeeded() && new_head != nullptr) {
679  *nothing_to_do = false;
680 
681  /* The new vehicle is constructed, now take over orders and everything... */
682  cost.AddCost(CopyHeadSpecificThings(old_head, new_head, flags));
683 
684  if (cost.Succeeded()) {
685  /* The new vehicle is constructed, now take over cargo */
686  if ((flags & DC_EXEC) != 0) {
687  TransferCargo(old_head, new_head, true);
688  *chain = new_head;
689 
690  AI::NewEvent(old_head->owner, new ScriptEventVehicleAutoReplaced(old_head->index, new_head->index));
691  }
692 
693  /* Sell the old vehicle */
694  cost.AddCost(DoCommand(0, old_head->index, 0, flags, GetCmdSellVeh(old_head)));
695  }
696 
697  /* If we are not in DC_EXEC undo everything */
698  if ((flags & DC_EXEC) == 0) {
699  DoCommand(0, new_head->index, 0, DC_EXEC, GetCmdSellVeh(new_head));
700  }
701  }
702  }
703 
704  return cost;
705 }
706 
717 CommandCost CmdAutoreplaceVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text)
718 {
719  Vehicle *v = Vehicle::GetIfValid(p1);
720  if (v == nullptr) return CMD_ERROR;
721 
722  CommandCost ret = CheckOwnership(v->owner);
723  if (ret.Failed()) return ret;
724 
725  if (!v->IsChainInDepot()) return CMD_ERROR;
726  if (v->vehstatus & VS_CRASHED) return CMD_ERROR;
727 
728  bool free_wagon = false;
729  if (v->type == VEH_TRAIN) {
730  Train *t = Train::From(v);
731  if (t->IsArticulatedPart() || t->IsRearDualheaded()) return CMD_ERROR;
732  free_wagon = !t->IsFrontEngine();
733  if (free_wagon && t->First()->IsFrontEngine()) return CMD_ERROR;
734  } else {
735  if (!v->IsPrimaryVehicle()) return CMD_ERROR;
736  }
737 
739  bool wagon_removal = c->settings.renew_keep_length;
740 
741  const Group *g = Group::GetIfValid(v->group_id);
742  if (g != nullptr) wagon_removal = HasBit(g->flags, GroupFlags::GF_REPLACE_WAGON_REMOVAL);
743 
744  /* Test whether any replacement is set, before issuing a whole lot of commands that would end in nothing changed */
745  Vehicle *w = v;
746  bool any_replacements = false;
747  while (w != nullptr) {
748  EngineID e;
749  CommandCost cost = GetNewEngineType(w, c, false, e);
750  if (cost.Failed()) return cost;
751  any_replacements |= (e != INVALID_ENGINE);
752  w = (!free_wagon && w->type == VEH_TRAIN ? Train::From(w)->GetNextUnit() : nullptr);
753  }
754 
756  bool nothing_to_do = true;
757 
758  if (any_replacements) {
759  bool was_stopped = free_wagon || ((v->vehstatus & VS_STOPPED) != 0);
760 
761  /* Stop the vehicle */
762  if (!was_stopped) cost.AddCost(CmdStartStopVehicle(v, true));
763  if (cost.Failed()) return cost;
764 
765  assert(free_wagon || v->IsStoppedInDepot());
766 
767  /* We have to construct the new vehicle chain to test whether it is valid.
768  * Vehicle construction needs random bits, so we have to save the random seeds
769  * to prevent desyncs and to replay newgrf callbacks during DC_EXEC */
770  SavedRandomSeeds saved_seeds;
771  SaveRandomSeeds(&saved_seeds);
772  if (free_wagon) {
773  cost.AddCost(ReplaceFreeUnit(&v, flags & ~DC_EXEC, &nothing_to_do));
774  } else {
775  cost.AddCost(ReplaceChain(&v, flags & ~DC_EXEC, wagon_removal, &nothing_to_do));
776  }
777  RestoreRandomSeeds(saved_seeds);
778 
779  if (cost.Succeeded() && (flags & DC_EXEC) != 0) {
780  CommandCost ret;
781  if (free_wagon) {
782  ret = ReplaceFreeUnit(&v, flags, &nothing_to_do);
783  } else {
784  ret = ReplaceChain(&v, flags, wagon_removal, &nothing_to_do);
785  }
786  assert(ret.Succeeded() && ret.GetCost() == cost.GetCost());
787  }
788 
789  /* Restart the vehicle */
790  if (!was_stopped) cost.AddCost(CmdStartStopVehicle(v, false));
791  }
792 
793  if (cost.Succeeded() && nothing_to_do) cost = CommandCost(STR_ERROR_AUTOREPLACE_NOTHING_TO_DO);
794  return cost;
795 }
796 
810 CommandCost CmdSetAutoReplace(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text)
811 {
813  if (c == nullptr) return CMD_ERROR;
814 
815  EngineID old_engine_type = GB(p2, 0, 16);
816  EngineID new_engine_type = GB(p2, 16, 16);
817  GroupID id_g = GB(p1, 16, 16);
818  CommandCost cost;
819 
820  if (Group::IsValidID(id_g) ? Group::Get(id_g)->owner != _current_company : !IsAllGroupID(id_g) && !IsDefaultGroupID(id_g)) return CMD_ERROR;
821  if (!Engine::IsValidID(old_engine_type)) return CMD_ERROR;
822 
823  if (new_engine_type != INVALID_ENGINE) {
824  if (!Engine::IsValidID(new_engine_type)) return CMD_ERROR;
825  if (!CheckAutoreplaceValidity(old_engine_type, new_engine_type, _current_company)) return CMD_ERROR;
826 
827  cost = AddEngineReplacementForCompany(c, old_engine_type, new_engine_type, id_g, HasBit(p1, 0), flags);
828  } else {
829  cost = RemoveEngineReplacementForCompany(c, old_engine_type, id_g, flags);
830  }
831 
832  if (flags & DC_EXEC) {
834  if (IsLocalCompany()) SetWindowDirty(WC_REPLACE_VEHICLE, Engine::Get(old_engine_type)->type);
835 
836  const VehicleType vt = Engine::Get(old_engine_type)->type;
838  }
839  if ((flags & DC_EXEC) && IsLocalCompany()) InvalidateAutoreplaceWindow(old_engine_type, id_g);
840 
841  return cost;
842 }
843 
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:523
CmdSetAutoReplace
CommandCost CmdSetAutoReplace(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text)
Change engine renewal parameters.
Definition: autoreplace_cmd.cpp:810
INVALID_ENGINE
static const EngineID INVALID_ENGINE
Constant denoting an invalid engine.
Definition: engine_type.h:175
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:111
TileIndex
uint32 TileIndex
The index/ID of a Tile.
Definition: tile_type.h:83
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:384
DoCommand
CommandCost DoCommand(const CommandContainer *container, DoCommandFlag flags)
Shorthand for calling the long DoCommand with a container.
Definition: command.cpp:450
CMD_REVERSE_TRAIN_DIRECTION
@ CMD_REVERSE_TRAIN_DIRECTION
turn a train around
Definition: command_type.h:222
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:3120
GB
static uint GB(const T x, const uint8 s, const uint8 n)
Fetch n bits from x, started at bit s.
Definition: bitmath_func.hpp:32
CMD_ADD_VEHICLE_GROUP
@ CMD_ADD_VEHICLE_GROUP
add a vehicle to a group
Definition: command_type.h:324
CMD_MOVE_RAIL_VEHICLE
@ CMD_MOVE_RAIL_VEHICLE
move a rail vehicle (in the depot)
Definition: command_type.h:220
train.h
AircraftVehicleInfo::subtype
byte subtype
Type of aircraft.
Definition: engine_type.h:102
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:395
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:23
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:271
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:594
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:1358
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:229
vehiclelist.h
Vehicle::vehstatus
byte vehstatus
Status.
Definition: vehicle_base.h:328
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:119
Vehicle::group_id
GroupID group_id
Index of group Pool array.
Definition: vehicle_base.h:337
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:13
GroundVehicle::IsRearDualheaded
bool IsRearDualheaded() const
Tell if we are dealing with the rear end of a multiheaded engine.
Definition: ground_vehicle.hpp:334
Vehicle::orders
union Vehicle::@49 orders
The orders currently assigned to the vehicle.
Engine
Definition: engine_base.h:27
VEH_ROAD
@ VEH_ROAD
Road vehicle type.
Definition: vehicle_type.h:25
Vehicle
Vehicle data structure.
Definition: vehicle_base.h:221
Vehicle::IsPrimaryVehicle
virtual bool IsPrimaryVehicle() const
Whether this is the primary vehicle in the chain.
Definition: vehicle_base.h:446
RoadVehicleInfo::roadtype
RoadType roadtype
Road type.
Definition: engine_type.h:126
Vehicle::owner
Owner owner
Which company owns the vehicle?
Definition: vehicle_base.h:285
CmdAutoreplaceVehicle
CommandCost CmdAutoreplaceVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text)
Autoreplaces a vehicle Trains are replaced as a whole chain, free wagons in depot are replaced on the...
Definition: autoreplace_cmd.cpp:717
Owner
Owner
Enum for all companies/owners.
Definition: company_type.h:18
DC_EXEC
@ DC_EXEC
execute the given command
Definition: command_type.h:348
CommandCost::GetErrorMessage
StringID GetErrorMessage() const
Returns the error message of a command.
Definition: command_type.h:140
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:346
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:309
CommandCost::Succeeded
bool Succeeded() const
Did this command succeed?
Definition: command_type.h:150
RestoreRandomSeeds
static void RestoreRandomSeeds(const SavedRandomSeeds &storage)
Restores previously saved seeds.
Definition: random_func.hpp:52
Vehicle::IsArticulatedPart
bool IsArticulatedPart() const
Check if the vehicle is an articulated part of an engine.
Definition: vehicle_base.h:906
ai.hpp
ChangeVehicleViewports
void ChangeVehicleViewports(VehicleID from_index, VehicleID to_index)
Switches viewports following vehicles, which get autoreplaced.
Definition: window.cpp:3427
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:72
CompanySettings::renew_keep_length
bool renew_keep_length
sell some wagons if after autoreplace the train is longer than before
Definition: settings_type.h:569
Vehicle::Orders
IterateWrapper Orders() const
Returns an iterable ensemble of orders of a vehicle.
Definition: vehicle_base.h:1036
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:40
RoadTypeInfo::powered_roadtypes
RoadTypes powered_roadtypes
bitmask to the OTHER roadtypes on which a vehicle of THIS roadtype generates power
Definition: road.h:119
CheckOwnership
CommandCost CheckOwnership(Owner owner, TileIndex tile)
Check whether the current owner owns something.
Definition: company_cmd.cpp:311
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:125
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:202
AI::NewEvent
static void NewEvent(CompanyID company, ScriptEvent *event)
Queue a new event for an AI.
Definition: ai_core.cpp:234
CommandCost
Common return value for all commands.
Definition: command_type.h:23
GetUnionOfArticulatedRefitMasks
CargoTypes GetUnionOfArticulatedRefitMasks(EngineID engine, bool include_initial_cargo_type)
Ors the refit_masks of all articulated parts.
Definition: articulated_vehicles.cpp:255
Vehicle::tile
TileIndex tile
Current tile index.
Definition: vehicle_base.h:242
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:299
VS_CRASHED
@ VS_CRASHED
Vehicle is crashed.
Definition: vehicle_base.h:38
Vehicle::cargo
VehicleCargoList cargo
The cargo this vehicle is carrying.
Definition: vehicle_base.h:320
CommandCost::Failed
bool Failed() const
Did this command fail?
Definition: command_type.h:159
WC_REPLACE_VEHICLE
@ WC_REPLACE_VEHICLE
Replace vehicle window; Window numbers:
Definition: window_type.h:210
GroundVehicle::gcache
GroundVehicleCache gcache
Cache of often calculated values.
Definition: ground_vehicle.hpp:80
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:179
Vehicle::IsFrontEngine
bool IsFrontEngine() const
Check if the vehicle is a front engine.
Definition: vehicle_base.h:897
_settings_game
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition: settings.cpp:53
CompanyProperties::settings
CompanySettings settings
settings specific for each company
Definition: company_base.h:104
DC_AUTOREPLACE
@ DC_AUTOREPLACE
autoreplace/autorenew is in progress, this shall disable vehicle limits when building,...
Definition: command_type.h:355
VS_STOPPED
@ VS_STOPPED
Vehicle is stopped by the player.
Definition: vehicle_base.h:32
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:283
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:725
GroupStatistics::UpdateAutoreplace
static void UpdateAutoreplace(CompanyID company)
Update autoreplace_defined and autoreplace_finished of all statistics of a company.
Definition: group_cmd.cpp:204
Train
'Train' is either a loco or a wagon.
Definition: train.h:86
CommandCost::GetCost
Money GetCost() const
The costs as made up to this moment.
Definition: command_type.h:82
CmdStartStopVehicle
static CommandCost CmdStartStopVehicle(const Vehicle *v, bool evaluate_callback)
Issue a start/stop command.
Definition: autoreplace_cmd.cpp:371
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:986
road.h
IsAllGroupID
static bool IsAllGroupID(GroupID id_g)
Checks if a GroupID stands for all vehicles of a company.
Definition: group.h:99
CheckCargoCapacity
void CheckCargoCapacity(Vehicle *v)
Check the capacity of all vehicles in a chain and spread cargo if needed.
Definition: autoreplace_cmd.cpp:104
Group::flags
uint8 flags
Group flags.
Definition: group.h:77
CommandCost::AddCost
void AddCost(const Money &cost)
Adds the given cost to the cost of the command.
Definition: command_type.h:62
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:143
OrderList::GetOrderAt
Order * GetOrderAt(int index) const
Get a certain order of the order chain.
Definition: order_cmd.cpp:356
RAILVEH_WAGON
@ RAILVEH_WAGON
simple wagon, not motorized
Definition: engine_type.h:29
Vehicle::list
OrderList * list
Pointer to the order list for this vehicle.
Definition: vehicle_base.h:332
CMD_START_STOP_VEHICLE
@ CMD_START_STOP_VEHICLE
start or stop a vehicle
Definition: command_type.h:315
GetWindowClassForVehicleType
static WindowClass GetWindowClassForVehicleType(VehicleType vt)
Get WindowClass for vehicle list of given vehicle type.
Definition: vehicle_gui.h:91
_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:607
Engine::CanCarryCargo
bool CanCarryCargo() const
Determines whether an engine can carry something.
Definition: engine.cpp:158
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:229
SpecializedVehicle< Train, Type >::From
static Train * From(Vehicle *v)
Converts a Vehicle to SpecializedVehicle with type checking.
Definition: vehicle_base.h:1164
Train::ConsistChanged
void ConsistChanged(ConsistChangeFlags allowed_changes)
Recalculates the cached stuff of a train.
Definition: train_cmd.cpp:106
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:356
OrderList
Shared order list linking together the linked list of orders and the list of vehicles sharing this or...
Definition: order_base.h:253
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:156
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:224
CargoSpec::name
StringID name
Name of this type of cargo.
Definition: cargotype.h:72
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:49
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:93
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:139
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:529
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:316
VehicleSettings::max_train_length
uint8 max_train_length
maximum length for trains
Definition: settings_type.h:476
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:144
EF_ROAD_TRAM
@ EF_ROAD_TRAM
Road vehicle is a tram/light rail vehicle.
Definition: engine_type.h:155
CeilDiv
static uint CeilDiv(uint a, uint b)
Computes ceil(a / b) for non-negative a and b.
Definition: math_func.hpp:254
CheckAutoreplaceValidity
bool CheckAutoreplaceValidity(EngineID from, EngineID to, CompanyID company)
Checks some basic properties whether autoreplace is allowed.
Definition: autoreplace_cmd.cpp:54
ReplaceChain
static CommandCost ReplaceChain(Vehicle **chain, DoCommandFlag flags, bool wagon_removal, bool *nothing_to_do)
Replace a whole vehicle chain.
Definition: autoreplace_cmd.cpp:488
articulated_vehicles.h
GameSettings::vehicle
VehicleSettings vehicle
options for vehicles
Definition: settings_type.h:584
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:1061
autoreplace_func.h
free
static void free(const void *ptr)
Version of the standard free that accepts const pointers.
Definition: stdafx.h:460
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:67
ROADTYPES_NONE
@ ROADTYPES_NONE
No roadtypes.
Definition: road_type.h:37
Company
Definition: company_base.h:115
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:33
IsEngineBuildable
bool IsEngineBuildable(EngineID engine, VehicleType type, CompanyID company)
Check if an engine is buildable.
Definition: engine.cpp:1115
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:317
OrderList::GetNumOrders
VehicleOrderID GetNumOrders() const
Get number of orders in the order list.
Definition: order_base.h:315
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:436
Engine::type
VehicleType type
Vehicle type, ie VEH_ROAD, VEH_TRAIN, etc.
Definition: engine_base.h:46
engine_func.h
news_func.h
CMD_CLONE_ORDER
@ CMD_CLONE_ORDER
clone (and share) an order
Definition: command_type.h:273