OpenTTD Source  1.11.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  for (VehicleOrderID i = 0; i < orders->GetNumOrders(); i++) {
211  o = orders->GetOrderAt(i);
212  if (!o->IsRefit()) continue;
213  if (!HasBit(union_refit_mask, o->GetRefitCargo())) return i;
214  }
215 
216  return -1;
217 }
218 
228 static CargoID GetNewCargoTypeForReplace(Vehicle *v, EngineID engine_type, bool part_of_chain)
229 {
230  CargoTypes available_cargo_types, union_mask;
231  GetArticulatedRefitMasks(engine_type, true, &union_mask, &available_cargo_types);
232 
233  if (union_mask == 0) return CT_NO_REFIT; // Don't try to refit an engine with no cargo capacity
234 
235  CargoID cargo_type;
236  if (IsArticulatedVehicleCarryingDifferentCargoes(v, &cargo_type)) return CT_INVALID; // We cannot refit to mixed cargoes in an automated way
237 
238  if (cargo_type == CT_INVALID) {
239  if (v->type != VEH_TRAIN) return CT_NO_REFIT; // If the vehicle does not carry anything at all, every replacement is fine.
240 
241  if (!part_of_chain) return CT_NO_REFIT;
242 
243  /* the old engine didn't have cargo capacity, but the new one does
244  * now we will figure out what cargo the train is carrying and refit to fit this */
245 
246  for (v = v->First(); v != nullptr; v = v->Next()) {
247  if (!v->GetEngine()->CanCarryCargo()) continue;
248  /* Now we found a cargo type being carried on the train and we will see if it is possible to carry to this one */
249  if (HasBit(available_cargo_types, v->cargo_type)) return v->cargo_type;
250  }
251 
252  return CT_NO_REFIT; // We failed to find a cargo type on the old vehicle and we will not refit the new one
253  } else {
254  if (!HasBit(available_cargo_types, cargo_type)) return CT_INVALID; // We can't refit the vehicle to carry the cargo we want
255 
256  if (part_of_chain && !VerifyAutoreplaceRefitForOrders(v, engine_type)) return CT_INVALID; // Some refit orders lose their effect
257 
258  return cargo_type;
259  }
260 }
261 
270 static CommandCost GetNewEngineType(const Vehicle *v, const Company *c, bool always_replace, EngineID &e)
271 {
272  assert(v->type != VEH_TRAIN || !v->IsArticulatedPart());
273 
274  e = INVALID_ENGINE;
275 
276  if (v->type == VEH_TRAIN && Train::From(v)->IsRearDualheaded()) {
277  /* we build the rear ends of multiheaded trains with the front ones */
278  return CommandCost();
279  }
280 
281  bool replace_when_old;
282  e = EngineReplacementForCompany(c, v->engine_type, v->group_id, &replace_when_old);
283  if (!always_replace && replace_when_old && !v->NeedsAutorenewing(c, false)) e = INVALID_ENGINE;
284 
285  /* Autoreplace, if engine is available */
287  return CommandCost();
288  }
289 
290  /* Autorenew if needed */
291  if (v->NeedsAutorenewing(c)) e = v->engine_type;
292 
293  /* Nothing to do or all is fine? */
294  if (e == INVALID_ENGINE || IsEngineBuildable(e, v->type, _current_company)) return CommandCost();
295 
296  /* The engine we need is not available. Report error to user */
297  return CommandCost(STR_ERROR_RAIL_VEHICLE_NOT_AVAILABLE + v->type);
298 }
299 
308 static CommandCost BuildReplacementVehicle(Vehicle *old_veh, Vehicle **new_vehicle, bool part_of_chain)
309 {
310  *new_vehicle = nullptr;
311 
312  /* Shall the vehicle be replaced? */
314  EngineID e;
315  CommandCost cost = GetNewEngineType(old_veh, c, true, e);
316  if (cost.Failed()) return cost;
317  if (e == INVALID_ENGINE) return CommandCost(); // neither autoreplace is set, nor autorenew is triggered
318 
319  /* Does it need to be refitted */
320  CargoID refit_cargo = GetNewCargoTypeForReplace(old_veh, e, part_of_chain);
321  if (refit_cargo == CT_INVALID) {
322  if (!IsLocalCompany()) return CommandCost();
323 
324  SetDParam(0, old_veh->index);
325 
326  int order_id = GetIncompatibleRefitOrderIdForAutoreplace(old_veh, e);
327  if (order_id != -1) {
328  /* Orders contained a refit order that is incompatible with the new vehicle. */
329  SetDParam(1, STR_ERROR_AUTOREPLACE_INCOMPATIBLE_REFIT);
330  SetDParam(2, order_id + 1); // 1-based indexing for display
331  } else {
332  /* Current cargo is incompatible with the new vehicle. */
333  SetDParam(1, STR_ERROR_AUTOREPLACE_INCOMPATIBLE_CARGO);
334  SetDParam(2, CargoSpec::Get(old_veh->cargo_type)->name);
335  }
336 
337  AddVehicleAdviceNewsItem(STR_NEWS_VEHICLE_AUTORENEW_FAILED, old_veh->index);
338  return CommandCost();
339  }
340 
341  /* Build the new vehicle */
342  cost = DoCommand(old_veh->tile, e | (CT_INVALID << 24), 0, DC_EXEC | DC_AUTOREPLACE, GetCmdBuildVeh(old_veh));
343  if (cost.Failed()) return cost;
344 
345  Vehicle *new_veh = Vehicle::Get(_new_vehicle_id);
346  *new_vehicle = new_veh;
347 
348  /* Refit the vehicle if needed */
349  if (refit_cargo != CT_NO_REFIT) {
350  byte subtype = GetBestFittingSubType(old_veh, new_veh, refit_cargo);
351 
352  cost.AddCost(DoCommand(0, new_veh->index, refit_cargo | (subtype << 8), DC_EXEC, GetCmdRefitVeh(new_veh)));
353  assert(cost.Succeeded()); // This should be ensured by GetNewCargoTypeForReplace()
354  }
355 
356  /* Try to reverse the vehicle, but do not care if it fails as the new type might not be reversible */
357  if (new_veh->type == VEH_TRAIN && HasBit(Train::From(old_veh)->flags, VRF_REVERSE_DIRECTION)) {
358  DoCommand(0, new_veh->index, true, DC_EXEC, CMD_REVERSE_TRAIN_DIRECTION);
359  }
360 
361  return cost;
362 }
363 
370 static inline CommandCost CmdStartStopVehicle(const Vehicle *v, bool evaluate_callback)
371 {
372  return DoCommand(0, v->index, evaluate_callback ? 1 : 0, DC_EXEC | DC_AUTOREPLACE, CMD_START_STOP_VEHICLE);
373 }
374 
383 static inline CommandCost CmdMoveVehicle(const Vehicle *v, const Vehicle *after, DoCommandFlag flags, bool whole_chain)
384 {
385  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);
386 }
387 
395 {
396  CommandCost cost = CommandCost();
397 
398  /* Share orders */
399  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));
400 
401  /* Copy group membership */
402  if (cost.Succeeded() && old_head != new_head) cost.AddCost(DoCommand(0, old_head->group_id, new_head->index, DC_EXEC, CMD_ADD_VEHICLE_GROUP));
403 
404  /* Perform start/stop check whether the new vehicle suits newgrf restrictions etc. */
405  if (cost.Succeeded()) {
406  /* Start the vehicle, might be denied by certain things */
407  assert((new_head->vehstatus & VS_STOPPED) != 0);
408  cost.AddCost(CmdStartStopVehicle(new_head, true));
409 
410  /* Stop the vehicle again, but do not care about evil newgrfs allowing starting but not stopping :p */
411  if (cost.Succeeded()) cost.AddCost(CmdStartStopVehicle(new_head, false));
412  }
413 
414  /* Last do those things which do never fail (resp. we do not care about), but which are not undo-able */
415  if (cost.Succeeded() && old_head != new_head && (flags & DC_EXEC) != 0) {
416  /* Copy other things which cannot be copied by a command and which shall not stay resetted from the build vehicle command */
417  new_head->CopyVehicleConfigAndStatistics(old_head);
418 
419  /* Switch vehicle windows/news to the new vehicle, so they are not closed/deleted when the old vehicle is sold */
420  ChangeVehicleViewports(old_head->index, new_head->index);
421  ChangeVehicleViewWindow(old_head->index, new_head->index);
422  ChangeVehicleNews(old_head->index, new_head->index);
423  }
424 
425  return cost;
426 }
427 
435 static CommandCost ReplaceFreeUnit(Vehicle **single_unit, DoCommandFlag flags, bool *nothing_to_do)
436 {
437  Train *old_v = Train::From(*single_unit);
438  assert(!old_v->IsArticulatedPart() && !old_v->IsRearDualheaded());
439 
441 
442  /* Build and refit replacement vehicle */
443  Vehicle *new_v = nullptr;
444  cost.AddCost(BuildReplacementVehicle(old_v, &new_v, false));
445 
446  /* Was a new vehicle constructed? */
447  if (cost.Succeeded() && new_v != nullptr) {
448  *nothing_to_do = false;
449 
450  if ((flags & DC_EXEC) != 0) {
451  /* Move the new vehicle behind the old */
452  CmdMoveVehicle(new_v, old_v, DC_EXEC, false);
453 
454  /* Take over cargo
455  * Note: We do only transfer cargo from the old to the new vehicle.
456  * I.e. we do not transfer remaining cargo to other vehicles.
457  * Else you would also need to consider moving cargo to other free chains,
458  * or doing the same in ReplaceChain(), which would be quite troublesome.
459  */
460  TransferCargo(old_v, new_v, false);
461 
462  *single_unit = new_v;
463 
464  AI::NewEvent(old_v->owner, new ScriptEventVehicleAutoReplaced(old_v->index, new_v->index));
465  }
466 
467  /* Sell the old vehicle */
468  cost.AddCost(DoCommand(0, old_v->index, 0, flags, GetCmdSellVeh(old_v)));
469 
470  /* If we are not in DC_EXEC undo everything */
471  if ((flags & DC_EXEC) == 0) {
472  DoCommand(0, new_v->index, 0, DC_EXEC, GetCmdSellVeh(new_v));
473  }
474  }
475 
476  return cost;
477 }
478 
487 static CommandCost ReplaceChain(Vehicle **chain, DoCommandFlag flags, bool wagon_removal, bool *nothing_to_do)
488 {
489  Vehicle *old_head = *chain;
490  assert(old_head->IsPrimaryVehicle());
491 
493 
494  if (old_head->type == VEH_TRAIN) {
495  /* Store the length of the old vehicle chain, rounded up to whole tiles */
496  uint16 old_total_length = CeilDiv(Train::From(old_head)->gcache.cached_total_length, TILE_SIZE) * TILE_SIZE;
497 
498  int num_units = 0;
499  for (Train *w = Train::From(old_head); w != nullptr; w = w->GetNextUnit()) num_units++;
500 
501  Train **old_vehs = CallocT<Train *>(num_units);
502  Train **new_vehs = CallocT<Train *>(num_units);
503  Money *new_costs = MallocT<Money>(num_units);
504 
505  /* Collect vehicles and build replacements
506  * Note: The replacement vehicles can only successfully build as long as the old vehicles are still in their chain */
507  int i;
508  Train *w;
509  for (w = Train::From(old_head), i = 0; w != nullptr; w = w->GetNextUnit(), i++) {
510  assert(i < num_units);
511  old_vehs[i] = w;
512 
513  CommandCost ret = BuildReplacementVehicle(old_vehs[i], (Vehicle**)&new_vehs[i], true);
514  cost.AddCost(ret);
515  if (cost.Failed()) break;
516 
517  new_costs[i] = ret.GetCost();
518  if (new_vehs[i] != nullptr) *nothing_to_do = false;
519  }
520  Train *new_head = (new_vehs[0] != nullptr ? new_vehs[0] : old_vehs[0]);
521 
522  /* Note: When autoreplace has already failed here, old_vehs[] is not completely initialized. But it is also not needed. */
523  if (cost.Succeeded()) {
524  /* Separate the head, so we can start constructing the new chain */
525  Train *second = Train::From(old_head)->GetNextUnit();
526  if (second != nullptr) cost.AddCost(CmdMoveVehicle(second, nullptr, DC_EXEC | DC_AUTOREPLACE, true));
527 
528  assert(Train::From(new_head)->GetNextUnit() == nullptr);
529 
530  /* Append engines to the new chain
531  * We do this from back to front, so that the head of the temporary vehicle chain does not change all the time.
532  * That way we also have less trouble when exceeding the unitnumber limit.
533  * OTOH the vehicle attach callback is more expensive this way :s */
534  Train *last_engine = nullptr;
535  if (cost.Succeeded()) {
536  for (int i = num_units - 1; i > 0; i--) {
537  Train *append = (new_vehs[i] != nullptr ? new_vehs[i] : old_vehs[i]);
538 
539  if (RailVehInfo(append->engine_type)->railveh_type == RAILVEH_WAGON) continue;
540 
541  if (new_vehs[i] != nullptr) {
542  /* Move the old engine to a separate row with DC_AUTOREPLACE. Else
543  * moving the wagon in front may fail later due to unitnumber limit.
544  * (We have to attach wagons without DC_AUTOREPLACE.) */
545  CmdMoveVehicle(old_vehs[i], nullptr, DC_EXEC | DC_AUTOREPLACE, false);
546  }
547 
548  if (last_engine == nullptr) last_engine = append;
549  cost.AddCost(CmdMoveVehicle(append, new_head, DC_EXEC, false));
550  if (cost.Failed()) break;
551  }
552  if (last_engine == nullptr) last_engine = new_head;
553  }
554 
555  /* When wagon removal is enabled and the new engines without any wagons are already longer than the old, we have to fail */
556  if (cost.Succeeded() && wagon_removal && new_head->gcache.cached_total_length > old_total_length) cost = CommandCost(STR_ERROR_TRAIN_TOO_LONG_AFTER_REPLACEMENT);
557 
558  /* Append/insert wagons into the new vehicle chain
559  * 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.
560  */
561  if (cost.Succeeded()) {
562  for (int i = num_units - 1; i > 0; i--) {
563  assert(last_engine != nullptr);
564  Vehicle *append = (new_vehs[i] != nullptr ? new_vehs[i] : old_vehs[i]);
565 
566  if (RailVehInfo(append->engine_type)->railveh_type == RAILVEH_WAGON) {
567  /* Insert wagon after 'last_engine' */
568  CommandCost res = CmdMoveVehicle(append, last_engine, DC_EXEC, false);
569 
570  /* When we allow removal of wagons, either the move failing due
571  * to the train becoming too long, or the train becoming longer
572  * would move the vehicle to the empty vehicle chain. */
573  if (wagon_removal && (res.Failed() ? res.GetErrorMessage() == STR_ERROR_TRAIN_TOO_LONG : new_head->gcache.cached_total_length > old_total_length)) {
574  CmdMoveVehicle(append, nullptr, DC_EXEC | DC_AUTOREPLACE, false);
575  break;
576  }
577 
578  cost.AddCost(res);
579  if (cost.Failed()) break;
580  } else {
581  /* We have reached 'last_engine', continue with the next engine towards the front */
582  assert(append == last_engine);
583  last_engine = last_engine->GetPrevUnit();
584  }
585  }
586  }
587 
588  /* Sell superfluous new vehicles that could not be inserted. */
589  if (cost.Succeeded() && wagon_removal) {
591  for (int i = 1; i < num_units; i++) {
592  Vehicle *wagon = new_vehs[i];
593  if (wagon == nullptr) continue;
594  if (wagon->First() == new_head) break;
595 
596  assert(RailVehInfo(wagon->engine_type)->railveh_type == RAILVEH_WAGON);
597 
598  /* Sell wagon */
599  CommandCost ret = DoCommand(0, wagon->index, 0, DC_EXEC, GetCmdSellVeh(wagon));
600  assert(ret.Succeeded());
601  new_vehs[i] = nullptr;
602 
603  /* Revert the money subtraction when the vehicle was built.
604  * This value is different from the sell value, esp. because of refitting */
605  cost.AddCost(-new_costs[i]);
606  }
607  }
608 
609  /* The new vehicle chain is constructed, now take over orders and everything... */
610  if (cost.Succeeded()) cost.AddCost(CopyHeadSpecificThings(old_head, new_head, flags));
611 
612  if (cost.Succeeded()) {
613  /* Success ! */
614  if ((flags & DC_EXEC) != 0 && new_head != old_head) {
615  *chain = new_head;
616  }
617 
618  /* Transfer cargo of old vehicles and sell them */
619  for (int i = 0; i < num_units; i++) {
620  Vehicle *w = old_vehs[i];
621  /* Is the vehicle again part of the new chain?
622  * Note: We cannot test 'new_vehs[i] != nullptr' as wagon removal might cause to remove both */
623  if (w->First() == new_head) continue;
624 
625  if ((flags & DC_EXEC) != 0) TransferCargo(w, new_head, true);
626 
627  /* Sell the vehicle.
628  * Note: This might temporarily construct new trains, so use DC_AUTOREPLACE to prevent
629  * it from failing due to engine limits. */
630  cost.AddCost(DoCommand(0, w->index, 0, flags | DC_AUTOREPLACE, GetCmdSellVeh(w)));
631  if ((flags & DC_EXEC) != 0) {
632  old_vehs[i] = nullptr;
633  if (i == 0) {
634  AI::NewEvent(old_head->owner, new ScriptEventVehicleAutoReplaced(old_head->index, new_head->index));
635  old_head = nullptr;
636  }
637  }
638  }
639 
640  if ((flags & DC_EXEC) != 0) CheckCargoCapacity(new_head);
641  }
642 
643  /* If we are not in DC_EXEC undo everything, i.e. rearrange old vehicles.
644  * We do this from back to front, so that the head of the temporary vehicle chain does not change all the time.
645  * Note: The vehicle attach callback is disabled here :) */
646  if ((flags & DC_EXEC) == 0) {
647  /* Separate the head, so we can reattach the old vehicles */
648  Train *second = Train::From(old_head)->GetNextUnit();
649  if (second != nullptr) CmdMoveVehicle(second, nullptr, DC_EXEC | DC_AUTOREPLACE, true);
650 
651  assert(Train::From(old_head)->GetNextUnit() == nullptr);
652 
653  for (int i = num_units - 1; i > 0; i--) {
654  CommandCost ret = CmdMoveVehicle(old_vehs[i], old_head, DC_EXEC | DC_AUTOREPLACE, false);
655  assert(ret.Succeeded());
656  }
657  }
658  }
659 
660  /* Finally undo buying of new vehicles */
661  if ((flags & DC_EXEC) == 0) {
662  for (int i = num_units - 1; i >= 0; i--) {
663  if (new_vehs[i] != nullptr) {
664  DoCommand(0, new_vehs[i]->index, 0, DC_EXEC, GetCmdSellVeh(new_vehs[i]));
665  new_vehs[i] = nullptr;
666  }
667  }
668  }
669 
670  free(old_vehs);
671  free(new_vehs);
672  free(new_costs);
673  } else {
674  /* Build and refit replacement vehicle */
675  Vehicle *new_head = nullptr;
676  cost.AddCost(BuildReplacementVehicle(old_head, &new_head, true));
677 
678  /* Was a new vehicle constructed? */
679  if (cost.Succeeded() && new_head != nullptr) {
680  *nothing_to_do = false;
681 
682  /* The new vehicle is constructed, now take over orders and everything... */
683  cost.AddCost(CopyHeadSpecificThings(old_head, new_head, flags));
684 
685  if (cost.Succeeded()) {
686  /* The new vehicle is constructed, now take over cargo */
687  if ((flags & DC_EXEC) != 0) {
688  TransferCargo(old_head, new_head, true);
689  *chain = new_head;
690 
691  AI::NewEvent(old_head->owner, new ScriptEventVehicleAutoReplaced(old_head->index, new_head->index));
692  }
693 
694  /* Sell the old vehicle */
695  cost.AddCost(DoCommand(0, old_head->index, 0, flags, GetCmdSellVeh(old_head)));
696  }
697 
698  /* If we are not in DC_EXEC undo everything */
699  if ((flags & DC_EXEC) == 0) {
700  DoCommand(0, new_head->index, 0, DC_EXEC, GetCmdSellVeh(new_head));
701  }
702  }
703  }
704 
705  return cost;
706 }
707 
718 CommandCost CmdAutoreplaceVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
719 {
720  Vehicle *v = Vehicle::GetIfValid(p1);
721  if (v == nullptr) return CMD_ERROR;
722 
723  CommandCost ret = CheckOwnership(v->owner);
724  if (ret.Failed()) return ret;
725 
726  if (!v->IsChainInDepot()) return CMD_ERROR;
727  if (v->vehstatus & VS_CRASHED) return CMD_ERROR;
728 
729  bool free_wagon = false;
730  if (v->type == VEH_TRAIN) {
731  Train *t = Train::From(v);
732  if (t->IsArticulatedPart() || t->IsRearDualheaded()) return CMD_ERROR;
733  free_wagon = !t->IsFrontEngine();
734  if (free_wagon && t->First()->IsFrontEngine()) return CMD_ERROR;
735  } else {
736  if (!v->IsPrimaryVehicle()) return CMD_ERROR;
737  }
738 
740  bool wagon_removal = c->settings.renew_keep_length;
741 
742  /* Test whether any replacement is set, before issuing a whole lot of commands that would end in nothing changed */
743  Vehicle *w = v;
744  bool any_replacements = false;
745  while (w != nullptr) {
746  EngineID e;
747  CommandCost cost = GetNewEngineType(w, c, false, e);
748  if (cost.Failed()) return cost;
749  any_replacements |= (e != INVALID_ENGINE);
750  w = (!free_wagon && w->type == VEH_TRAIN ? Train::From(w)->GetNextUnit() : nullptr);
751  }
752 
754  bool nothing_to_do = true;
755 
756  if (any_replacements) {
757  bool was_stopped = free_wagon || ((v->vehstatus & VS_STOPPED) != 0);
758 
759  /* Stop the vehicle */
760  if (!was_stopped) cost.AddCost(CmdStartStopVehicle(v, true));
761  if (cost.Failed()) return cost;
762 
763  assert(free_wagon || v->IsStoppedInDepot());
764 
765  /* We have to construct the new vehicle chain to test whether it is valid.
766  * Vehicle construction needs random bits, so we have to save the random seeds
767  * to prevent desyncs and to replay newgrf callbacks during DC_EXEC */
768  SavedRandomSeeds saved_seeds;
769  SaveRandomSeeds(&saved_seeds);
770  if (free_wagon) {
771  cost.AddCost(ReplaceFreeUnit(&v, flags & ~DC_EXEC, &nothing_to_do));
772  } else {
773  cost.AddCost(ReplaceChain(&v, flags & ~DC_EXEC, wagon_removal, &nothing_to_do));
774  }
775  RestoreRandomSeeds(saved_seeds);
776 
777  if (cost.Succeeded() && (flags & DC_EXEC) != 0) {
778  CommandCost ret;
779  if (free_wagon) {
780  ret = ReplaceFreeUnit(&v, flags, &nothing_to_do);
781  } else {
782  ret = ReplaceChain(&v, flags, wagon_removal, &nothing_to_do);
783  }
784  assert(ret.Succeeded() && ret.GetCost() == cost.GetCost());
785  }
786 
787  /* Restart the vehicle */
788  if (!was_stopped) cost.AddCost(CmdStartStopVehicle(v, false));
789  }
790 
791  if (cost.Succeeded() && nothing_to_do) cost = CommandCost(STR_ERROR_AUTOREPLACE_NOTHING_TO_DO);
792  return cost;
793 }
794 
808 CommandCost CmdSetAutoReplace(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
809 {
811  if (c == nullptr) return CMD_ERROR;
812 
813  EngineID old_engine_type = GB(p2, 0, 16);
814  EngineID new_engine_type = GB(p2, 16, 16);
815  GroupID id_g = GB(p1, 16, 16);
816  CommandCost cost;
817 
818  if (Group::IsValidID(id_g) ? Group::Get(id_g)->owner != _current_company : !IsAllGroupID(id_g) && !IsDefaultGroupID(id_g)) return CMD_ERROR;
819  if (!Engine::IsValidID(old_engine_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, HasBit(p1, 0), 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:360
Vehicle::IsChainInDepot
virtual bool IsChainInDepot() const
Check whether the whole vehicle chain is in the depot.
Definition: vehicle_base.h:521
INVALID_ENGINE
static const EngineID INVALID_ENGINE
Constant denoting an invalid engine.
Definition: engine_type.h:174
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:108
TileIndex
uint32 TileIndex
The index/ID of a Tile.
Definition: tile_type.h:78
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:383
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:329
SetWindowDirty
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
Definition: window.cpp:3220
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:101
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:394
Pool::PoolItem<&_vehicle_pool >::GetIfValid
static Titem * GetIfValid(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:340
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:270
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:592
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:1354
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:326
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:227
CargoSpec::Get
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo ID.
Definition: cargotype.h:117
Vehicle::group_id
GroupID group_id
Index of group Pool array.
Definition: vehicle_base.h:335
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
Engine
Definition: engine_base.h:21
VEH_ROAD
@ VEH_ROAD
Road vehicle type.
Definition: vehicle_type.h:25
Vehicle
Vehicle data structure.
Definition: vehicle_base.h:222
Vehicle::IsPrimaryVehicle
virtual bool IsPrimaryVehicle() const
Whether this is the primary vehicle in the chain.
Definition: vehicle_base.h:444
RoadVehicleInfo::roadtype
RoadType roadtype
Road type.
Definition: engine_type.h:125
Vehicle::owner
Owner owner
Which company owns the vehicle?
Definition: vehicle_base.h:283
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:199
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:308
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:904
ai.hpp
ChangeVehicleViewports
void ChangeVehicleViewports(VehicleID from_index, VehicleID to_index)
Switches viewports following vehicles, which get autoreplaced.
Definition: window.cpp:3552
GetRailTypeInfo
static const RailtypeInfo * GetRailTypeInfo(RailType railtype)
Returns a pointer to the Railtype information for a given railtype.
Definition: rail.h:304
CompanySettings::renew_keep_length
bool renew_keep_length
sell some wagons if after autoreplace the train is longer than before
Definition: settings_type.h:543
Vehicle::Orders
IterateWrapper Orders() const
Returns an iterable ensemble of orders of a vehicle.
Definition: vehicle_base.h:1034
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:310
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:122
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
CmdSetAutoReplace
CommandCost CmdSetAutoReplace(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Change engine renewal parameters.
Definition: autoreplace_cmd.cpp:808
Vehicle::tile
TileIndex tile
Current tile index.
Definition: vehicle_base.h:240
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:297
VS_CRASHED
@ VS_CRASHED
Vehicle is crashed.
Definition: vehicle_base.h:37
Vehicle::cargo
VehicleCargoList cargo
The cargo this vehicle is carrying.
Definition: vehicle_base.h:318
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:211
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:895
_settings_game
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition: settings.cpp:80
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:31
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:723
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:85
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:370
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:983
road.h
IsAllGroupID
static bool IsAllGroupID(GroupID id_g)
Checks if a GroupID stands for all vehicles of a company.
Definition: group.h:93
CheckCargoCapacity
void CheckCargoCapacity(Vehicle *v)
Check the capacity of all vehicles in a chain and spread cargo if needed.
Definition: autoreplace_cmd.cpp:104
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:142
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:330
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:605
Engine::CanCarryCargo
bool CanCarryCargo() const
Determines whether an engine can carry something.
Definition: engine.cpp:169
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:228
SpecializedVehicle< Train, Type >::From
static Train * From(Vehicle *v)
Converts a Vehicle to SpecializedVehicle with type checking.
Definition: vehicle_base.h:1162
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:250
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:155
Vehicle::orders
union Vehicle::@51 orders
The orders currently assigned to the vehicle.
NUM_CARGO
@ NUM_CARGO
Maximal number of cargo types in a game.
Definition: cargo_type.h:64
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:70
company_func.h
CmdAutoreplaceVehicle
CommandCost CmdAutoreplaceVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Autoreplaces a vehicle Trains are replaced as a whole chain, free wagons in depot are replaced on the...
Definition: autoreplace_cmd.cpp:718
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:92
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:216
OverflowSafeInt< int64, INT64_MAX, INT64_MIN >
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:527
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:314
VehicleSettings::max_train_length
uint8 max_train_length
maximum length for trains
Definition: settings_type.h:450
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:143
EF_ROAD_TRAM
@ EF_ROAD_TRAM
Road vehicle is a tram/light rail vehicle.
Definition: engine_type.h:154
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:487
articulated_vehicles.h
GameSettings::vehicle
VehicleSettings vehicle
options for vehicles
Definition: settings_type.h:558
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:318
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:1059
autoreplace_func.h
free
static void free(const void *ptr)
Version of the standard free that accepts const pointers.
Definition: stdafx.h:454
CT_INVALID
@ CT_INVALID
Invalid cargo type.
Definition: cargo_type.h:68
ROADTYPES_NONE
@ ROADTYPES_NONE
No roadtypes.
Definition: road_type.h:37
Company
Definition: company_base.h:110
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:67
Order
Definition: order_base.h:32
Company::settings
CompanySettings settings
settings specific for each company
Definition: company_base.h:122
IsEngineBuildable
bool IsEngineBuildable(EngineID engine, VehicleType type, CompanyID company)
Check if an engine is buildable.
Definition: engine.cpp:1123
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:312
OrderList::GetNumOrders
VehicleOrderID GetNumOrders() const
Get number of orders in the order list.
Definition: order_base.h:312
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:435
Engine::type
VehicleType type
Vehicle type, ie VEH_ROAD, VEH_TRAIN, etc.
Definition: engine_base.h:40
engine_func.h
news_func.h
CMD_CLONE_ORDER
@ CMD_CLONE_ORDER
clone (and share) an order
Definition: command_type.h:273