OpenTTD Source: src/autoreplace_cmd.cpp Source File

OpenTTD Source 15.3

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 <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
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/bitmath_func.hpp"
20#include "core/random_func.hpp"
21#include "vehiclelist.h"
22#include "road.h"
23#include "ai/ai.hpp"
24#include "news_func.h"
25#include "strings_func.h"
26#include "autoreplace_cmd.h"
27#include "group_cmd.h"
28#include "order_cmd.h"
29#include "train_cmd.h"
30#include "vehicle_cmd.h"
31
32#include "table/strings.h"
33
34#include "safeguards.h"
35
36extern void ChangeVehicleViewports(VehicleID from_index, VehicleID to_index);
37extern void ChangeVehicleNews(VehicleID from_index, VehicleID to_index);
38extern void ChangeVehicleViewWindow(VehicleID from_index, VehicleID to_index);
39
46 static bool EnginesHaveCargoInCommon(EngineID engine_a, EngineID engine_b)
47{
48 CargoTypes available_cargoes_a = GetUnionOfArticulatedRefitMasks(engine_a, true);
49 CargoTypes available_cargoes_b = GetUnionOfArticulatedRefitMasks(engine_b, true);
50 return (available_cargoes_a == 0 || available_cargoes_b == 0 || (available_cargoes_a & available_cargoes_b) != 0);
51}
52
60 bool CheckAutoreplaceValidity(EngineID from, EngineID to, CompanyID company)
61{
62 assert(Engine::IsValidID(from) && Engine::IsValidID(to));
63
64 const Engine *e_from = Engine::Get(from);
65 const Engine *e_to = Engine::Get(to);
66 VehicleType type = e_from->type;
67
68 /* check that the new vehicle type is available to the company and its type is the same as the original one */
69 if (!IsEngineBuildable(to, type, company)) return false;
70
71 switch (type) {
72 case VEH_TRAIN: {
73 /* make sure the railtypes are compatible */
74 if (!GetAllCompatibleRailTypes(e_from->VehInfo<RailVehicleInfo>().railtypes).Any(GetAllCompatibleRailTypes(e_to->VehInfo<RailVehicleInfo>().railtypes))) return false;
75
76 /* make sure we do not replace wagons with engines or vice versa */
77 if ((e_from->VehInfo<RailVehicleInfo>().railveh_type == RAILVEH_WAGON) != (e_to->VehInfo<RailVehicleInfo>().railveh_type == RAILVEH_WAGON)) return false;
78 break;
79 }
80
81 case VEH_ROAD:
82 /* make sure the roadtypes are compatible */
83 if (!GetRoadTypeInfo(e_from->VehInfo<RoadVehicleInfo>().roadtype)->powered_roadtypes.Any(GetRoadTypeInfo(e_to->VehInfo<RoadVehicleInfo>().roadtype)->powered_roadtypes)) return false;
84
85 /* make sure that we do not replace a tram with a normal road vehicles or vice versa */
86 if (e_from->info.misc_flags.Test(EngineMiscFlag::RoadIsTram) != e_to->info.misc_flags.Test(EngineMiscFlag::RoadIsTram)) return false;
87 break;
88
89 case VEH_AIRCRAFT:
90 /* make sure that we do not replace a plane with a helicopter or vice versa */
91 if ((e_from->VehInfo<AircraftVehicleInfo>().subtype & AIR_CTOL) != (e_to->VehInfo<AircraftVehicleInfo>().subtype & AIR_CTOL)) return false;
92 break;
93
94 default: break;
95 }
96
97 /* the engines needs to be able to carry the same cargo */
98 return EnginesHaveCargoInCommon(from, to);
99}
100
107 void CheckCargoCapacity(Vehicle *v)
108{
109 assert(v == nullptr || v->First() == v);
110
111 for (Vehicle *src = v; src != nullptr; src = src->Next()) {
112 assert(src->cargo.TotalCount() == src->cargo.ActionCount(VehicleCargoList::MTA_KEEP));
113
114 /* Do we need to more cargo away? */
115 if (src->cargo.TotalCount() <= src->cargo_cap) continue;
116
117 /* We need to move a particular amount. Try that on the other vehicles. */
118 uint to_spread = src->cargo.TotalCount() - src->cargo_cap;
119 for (Vehicle *dest = v; dest != nullptr && to_spread != 0; dest = dest->Next()) {
120 assert(dest->cargo.TotalCount() == dest->cargo.ActionCount(VehicleCargoList::MTA_KEEP));
121 if (dest->cargo.TotalCount() >= dest->cargo_cap || dest->cargo_type != src->cargo_type) continue;
122
123 uint amount = std::min(to_spread, dest->cargo_cap - dest->cargo.TotalCount());
124 src->cargo.Shift(amount, &dest->cargo);
125 to_spread -= amount;
126 }
127
128 /* Any left-overs will be thrown away, but not their feeder share. */
129 if (src->cargo_cap < src->cargo.TotalCount()) src->cargo.Truncate(src->cargo.TotalCount() - src->cargo_cap);
130 }
131}
132
142 static void TransferCargo(Vehicle *old_veh, Vehicle *new_head, bool part_of_chain)
143{
144 assert(!part_of_chain || new_head->IsPrimaryVehicle());
145 /* Loop through source parts */
146 for (Vehicle *src = old_veh; src != nullptr; src = src->Next()) {
147 assert(src->cargo.TotalCount() == src->cargo.ActionCount(VehicleCargoList::MTA_KEEP));
148 if (!part_of_chain && src->type == VEH_TRAIN && src != old_veh && src != Train::From(old_veh)->other_multiheaded_part && !src->IsArticulatedPart()) {
149 /* Skip vehicles, which do not belong to old_veh */
150 src = src->GetLastEnginePart();
151 continue;
152 }
153 if (src->cargo_type >= NUM_CARGO || src->cargo.TotalCount() == 0) continue;
154
155 /* Find free space in the new chain */
156 for (Vehicle *dest = new_head; dest != nullptr && src->cargo.TotalCount() > 0; dest = dest->Next()) {
157 assert(dest->cargo.TotalCount() == dest->cargo.ActionCount(VehicleCargoList::MTA_KEEP));
158 if (!part_of_chain && dest->type == VEH_TRAIN && dest != new_head && dest != Train::From(new_head)->other_multiheaded_part && !dest->IsArticulatedPart()) {
159 /* Skip vehicles, which do not belong to new_head */
160 dest = dest->GetLastEnginePart();
161 continue;
162 }
163 if (dest->cargo_type != src->cargo_type) continue;
164
165 uint amount = std::min(src->cargo.TotalCount(), dest->cargo_cap - dest->cargo.TotalCount());
166 if (amount <= 0) continue;
167
168 src->cargo.Shift(amount, &dest->cargo);
169 }
170 }
171
172 /* Update train weight etc., the old vehicle will be sold anyway */
173 if (part_of_chain && new_head->type == VEH_TRAIN) Train::From(new_head)->ConsistChanged(CCF_LOADUNLOAD);
174}
175
182 static bool VerifyAutoreplaceRefitForOrders(const Vehicle *v, EngineID engine_type)
183{
184 CargoTypes union_refit_mask_a = GetUnionOfArticulatedRefitMasks(v->engine_type, false);
185 CargoTypes union_refit_mask_b = GetUnionOfArticulatedRefitMasks(engine_type, false);
186
187 const Vehicle *u = (v->type == VEH_TRAIN) ? v->First() : v;
188 for (const Order &o : u->Orders()) {
189 if (!o.IsRefit() || o.IsAutoRefit()) continue;
190 CargoType cargo_type = o.GetRefitCargo();
191
192 if (!HasBit(union_refit_mask_a, cargo_type)) continue;
193 if (!HasBit(union_refit_mask_b, cargo_type)) return false;
194 }
195
196 return true;
197}
198
205 static int GetIncompatibleRefitOrderIdForAutoreplace(const Vehicle *v, EngineID engine_type)
206{
207 CargoTypes union_refit_mask = GetUnionOfArticulatedRefitMasks(engine_type, false);
208
209 const Vehicle *u = (v->type == VEH_TRAIN) ? v->First() : v;
210
211 const OrderList *orders = u->orders;
212 if (orders == nullptr) return -1;
213 for (VehicleOrderID i = 0; i < orders->GetNumOrders(); i++) {
214 const Order *o = orders->GetOrderAt(i);
215 if (!o->IsRefit()) continue;
216 if (!HasBit(union_refit_mask, o->GetRefitCargo())) return i;
217 }
218
219 return -1;
220}
221
231 static CargoType GetNewCargoTypeForReplace(Vehicle *v, EngineID engine_type, bool part_of_chain)
232{
233 CargoTypes available_cargo_types, union_mask;
234 GetArticulatedRefitMasks(engine_type, true, &union_mask, &available_cargo_types);
235
236 if (union_mask == 0) return CARGO_NO_REFIT; // Don't try to refit an engine with no cargo capacity
237
238 CargoType cargo_type;
239 CargoTypes cargo_mask = GetCargoTypesOfArticulatedVehicle(v, &cargo_type);
240 if (!HasAtMostOneBit(cargo_mask)) {
241 CargoTypes new_engine_default_cargoes = GetCargoTypesOfArticulatedParts(engine_type);
242 if ((cargo_mask & new_engine_default_cargoes) == cargo_mask) {
243 return CARGO_NO_REFIT; // engine_type is already a mixed cargo type which matches the incoming vehicle by default, no refit required
244 }
245
246 return INVALID_CARGO; // We cannot refit to mixed cargoes in an automated way
247 }
248
249 if (!IsValidCargoType(cargo_type)) {
250 if (v->type != VEH_TRAIN) return CARGO_NO_REFIT; // If the vehicle does not carry anything at all, every replacement is fine.
251
252 if (!part_of_chain) return CARGO_NO_REFIT;
253
254 /* the old engine didn't have cargo capacity, but the new one does
255 * now we will figure out what cargo the train is carrying and refit to fit this */
256
257 for (v = v->First(); v != nullptr; v = v->Next()) {
258 if (!v->GetEngine()->CanCarryCargo()) continue;
259 /* Now we found a cargo type being carried on the train and we will see if it is possible to carry to this one */
260 if (HasBit(available_cargo_types, v->cargo_type)) return v->cargo_type;
261 }
262
263 return CARGO_NO_REFIT; // We failed to find a cargo type on the old vehicle and we will not refit the new one
264 } else {
265 if (!HasBit(available_cargo_types, cargo_type)) return INVALID_CARGO; // We can't refit the vehicle to carry the cargo we want
266
267 if (part_of_chain && !VerifyAutoreplaceRefitForOrders(v, engine_type)) return INVALID_CARGO; // Some refit orders lose their effect
268
269 return cargo_type;
270 }
271}
272
281 static CommandCost GetNewEngineType(const Vehicle *v, const Company *c, bool always_replace, EngineID &e)
282{
283 assert(v->type != VEH_TRAIN || !v->IsArticulatedPart());
284
285 e = EngineID::Invalid();
286
287 if (v->type == VEH_TRAIN && Train::From(v)->IsRearDualheaded()) {
288 /* we build the rear ends of multiheaded trains with the front ones */
289 return CommandCost();
290 }
291
292 bool replace_when_old;
293 e = EngineReplacementForCompany(c, v->engine_type, v->group_id, &replace_when_old);
294 if (!always_replace && replace_when_old && !v->NeedsAutorenewing(c, false)) e = EngineID::Invalid();
295
296 /* Autoreplace, if engine is available */
297 if (e != EngineID::Invalid() && IsEngineBuildable(e, v->type, _current_company)) {
298 return CommandCost();
299 }
300
301 /* Autorenew if needed */
302 if (v->NeedsAutorenewing(c)) e = v->engine_type;
303
304 /* Nothing to do or all is fine? */
305 if (e == EngineID::Invalid() || IsEngineBuildable(e, v->type, _current_company)) return CommandCost();
306
307 /* The engine we need is not available. Report error to user */
308 return CommandCost(STR_ERROR_RAIL_VEHICLE_NOT_AVAILABLE + v->type);
309}
310
320 static CommandCost BuildReplacementVehicle(Vehicle *old_veh, Vehicle **new_vehicle, bool part_of_chain, DoCommandFlags flags)
321{
322 *new_vehicle = nullptr;
323
324 /* Shall the vehicle be replaced? */
325 const Company *c = Company::Get(_current_company);
326 EngineID e;
327 CommandCost cost = GetNewEngineType(old_veh, c, true, e);
328 if (cost.Failed()) return cost;
329 if (e == EngineID::Invalid()) return CommandCost(); // neither autoreplace is set, nor autorenew is triggered
330
331 /* Does it need to be refitted */
332 CargoType refit_cargo = GetNewCargoTypeForReplace(old_veh, e, part_of_chain);
333 if (!IsValidCargoType(refit_cargo)) {
334 if (!IsLocalCompany() || !flags.Test(DoCommandFlag::Execute)) return CommandCost();
335
336 VehicleID old_veh_id = (old_veh->type == VEH_TRAIN) ? Train::From(old_veh)->First()->index : old_veh->index;
337 EncodedString headline;
338
339 int order_id = GetIncompatibleRefitOrderIdForAutoreplace(old_veh, e);
340 if (order_id != -1) {
341 /* Orders contained a refit order that is incompatible with the new vehicle. */
342 headline = GetEncodedString(STR_NEWS_VEHICLE_AUTORENEW_FAILED,
343 old_veh_id,
344 STR_ERROR_AUTOREPLACE_INCOMPATIBLE_REFIT,
345 order_id + 1); // 1-based indexing for display
346 } else {
347 /* Current cargo is incompatible with the new vehicle. */
348 headline = GetEncodedString(STR_NEWS_VEHICLE_AUTORENEW_FAILED,
349 old_veh_id,
350 STR_ERROR_AUTOREPLACE_INCOMPATIBLE_CARGO,
351 CargoSpec::Get(old_veh->cargo_type)->name);
352 }
353
354 AddVehicleAdviceNewsItem(AdviceType::AutorenewFailed, std::move(headline), old_veh_id);
355 return CommandCost();
356 }
357
358 /* Build the new vehicle */
359 VehicleID new_veh_id;
360 std::tie(cost, new_veh_id, std::ignore, std::ignore, std::ignore) = Command<CMD_BUILD_VEHICLE>::Do({DoCommandFlag::Execute, DoCommandFlag::AutoReplace}, old_veh->tile, e, true, INVALID_CARGO, INVALID_CLIENT_ID);
361 if (cost.Failed()) return cost;
362
363 Vehicle *new_veh = Vehicle::Get(new_veh_id);
364 *new_vehicle = new_veh;
365
366 /* Refit the vehicle if needed */
367 if (refit_cargo != CARGO_NO_REFIT) {
368 uint8_t subtype = GetBestFittingSubType(old_veh, new_veh, refit_cargo);
369
370 cost.AddCost(std::get<0>(Command<CMD_REFIT_VEHICLE>::Do(DoCommandFlag::Execute, new_veh->index, refit_cargo, subtype, false, false, 0)));
371 assert(cost.Succeeded()); // This should be ensured by GetNewCargoTypeForReplace()
372 }
373
374 /* Try to reverse the vehicle, but do not care if it fails as the new type might not be reversible */
375 if (new_veh->type == VEH_TRAIN && Train::From(old_veh)->flags.Test(VehicleRailFlag::Flipped)) {
376 /* Only copy the reverse state if neither old or new vehicle implements reverse-on-build probability callback. */
377 if (!TestVehicleBuildProbability(old_veh, old_veh->engine_type, BuildProbabilityType::Reversed).has_value() &&
378 !TestVehicleBuildProbability(new_veh, new_veh->engine_type, BuildProbabilityType::Reversed).has_value()) {
379 Command<CMD_REVERSE_TRAIN_DIRECTION>::Do(DoCommandFlag::Execute, new_veh->index, true);
380 }
381 }
382
383 return cost;
384}
385
392 static inline CommandCost DoCmdStartStopVehicle(const Vehicle *v, bool evaluate_callback)
393{
394 return Command<CMD_START_STOP_VEHICLE>::Do({DoCommandFlag::Execute, DoCommandFlag::AutoReplace}, v->index, evaluate_callback);
395}
396
405 static inline CommandCost CmdMoveVehicle(const Vehicle *v, const Vehicle *after, DoCommandFlags flags, bool whole_chain)
406{
407 return Command<CMD_MOVE_RAIL_VEHICLE>::Do(flags.Set(DoCommandFlag::NoCargoCapacityCheck), v->index, after != nullptr ? after->index : VehicleID::Invalid(), whole_chain);
408}
409
416 static CommandCost CopyHeadSpecificThings(Vehicle *old_head, Vehicle *new_head, DoCommandFlags flags)
417{
418 CommandCost cost = CommandCost();
419
420 /* Share orders */
421 if (cost.Succeeded() && old_head != new_head) cost.AddCost(Command<CMD_CLONE_ORDER>::Do(DoCommandFlag::Execute, CO_SHARE, new_head->index, old_head->index));
422
423 /* Copy group membership */
424 if (cost.Succeeded() && old_head != new_head) cost.AddCost(std::get<0>(Command<CMD_ADD_VEHICLE_GROUP>::Do(DoCommandFlag::Execute, old_head->group_id, new_head->index, false, VehicleListIdentifier{})));
425
426 /* Perform start/stop check whether the new vehicle suits newgrf restrictions etc. */
427 if (cost.Succeeded()) {
428 /* Start the vehicle, might be denied by certain things */
429 assert(new_head->vehstatus.Test(VehState::Stopped));
430 cost.AddCost(DoCmdStartStopVehicle(new_head, true));
431
432 /* Stop the vehicle again, but do not care about evil newgrfs allowing starting but not stopping :p */
433 if (cost.Succeeded()) cost.AddCost(DoCmdStartStopVehicle(new_head, false));
434 }
435
436 /* Last do those things which do never fail (resp. we do not care about), but which are not undo-able */
437 if (cost.Succeeded() && old_head != new_head && flags.Test(DoCommandFlag::Execute)) {
438 /* Copy other things which cannot be copied by a command and which shall not stay reset from the build vehicle command */
439 new_head->CopyVehicleConfigAndStatistics(old_head);
440 GroupStatistics::AddProfitLastYear(new_head);
441
442 /* Switch vehicle windows/news to the new vehicle, so they are not closed/deleted when the old vehicle is sold */
443 ChangeVehicleViewports(old_head->index, new_head->index);
444 ChangeVehicleViewWindow(old_head->index, new_head->index);
445 ChangeVehicleNews(old_head->index, new_head->index);
446 }
447
448 return cost;
449}
450
458 static CommandCost ReplaceFreeUnit(Vehicle **single_unit, DoCommandFlags flags, bool *nothing_to_do)
459{
460 Train *old_v = Train::From(*single_unit);
461 assert(!old_v->IsArticulatedPart() && !old_v->IsRearDualheaded());
462
463 CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES, (Money)0);
464
465 /* Build and refit replacement vehicle */
466 Vehicle *new_v = nullptr;
467 cost.AddCost(BuildReplacementVehicle(old_v, &new_v, false, flags));
468
469 /* Was a new vehicle constructed? */
470 if (cost.Succeeded() && new_v != nullptr) {
471 *nothing_to_do = false;
472
473 if (flags.Test(DoCommandFlag::Execute)) {
474 /* Move the new vehicle behind the old */
475 CmdMoveVehicle(new_v, old_v, DoCommandFlag::Execute, false);
476
477 /* Take over cargo
478 * Note: We do only transfer cargo from the old to the new vehicle.
479 * I.e. we do not transfer remaining cargo to other vehicles.
480 * Else you would also need to consider moving cargo to other free chains,
481 * or doing the same in ReplaceChain(), which would be quite troublesome.
482 */
483 TransferCargo(old_v, new_v, false);
484
485 *single_unit = new_v;
486
487 AI::NewEvent(old_v->owner, new ScriptEventVehicleAutoReplaced(old_v->index, new_v->index));
488 }
489
490 /* Sell the old vehicle */
491 cost.AddCost(Command<CMD_SELL_VEHICLE>::Do(flags, old_v->index, false, false, INVALID_CLIENT_ID));
492
493 /* If we are not in DoCommandFlag::Execute undo everything */
494 if (!flags.Test(DoCommandFlag::Execute)) {
495 Command<CMD_SELL_VEHICLE>::Do(DoCommandFlag::Execute, new_v->index, false, false, INVALID_CLIENT_ID);
496 }
497 }
498
499 return cost;
500}
501
503 struct ReplaceChainItem {
504 Vehicle *old_veh;
505 Vehicle *new_veh;
506 Money cost;
507
508 ReplaceChainItem(Vehicle *old_veh, Vehicle *new_veh, Money cost) : old_veh(old_veh), new_veh(new_veh), cost(cost) { }
509
514 Vehicle *GetVehicle() const { return new_veh == nullptr ? old_veh : new_veh; }
515};
516
525 static CommandCost ReplaceChain(Vehicle **chain, DoCommandFlags flags, bool wagon_removal, bool *nothing_to_do)
526{
527 Vehicle *old_head = *chain;
528 assert(old_head->IsPrimaryVehicle());
529
530 CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES, (Money)0);
531
532 if (old_head->type == VEH_TRAIN) {
533 /* Store the length of the old vehicle chain, rounded up to whole tiles */
534 uint16_t old_total_length = CeilDiv(Train::From(old_head)->gcache.cached_total_length, TILE_SIZE) * TILE_SIZE;
535
536 std::vector<ReplaceChainItem> replacements;
537
538 /* Collect vehicles and build replacements
539 * Note: The replacement vehicles can only successfully build as long as the old vehicles are still in their chain */
540 for (Train *w = Train::From(old_head); w != nullptr; w = w->GetNextUnit()) {
541 ReplaceChainItem &replacement = replacements.emplace_back(w, nullptr, 0);
542
543 CommandCost ret = BuildReplacementVehicle(replacement.old_veh, &replacement.new_veh, true, flags);
544 replacement.cost = ret.GetCost();
545 cost.AddCost(std::move(ret));
546 if (cost.Failed()) break;
547
548 if (replacement.new_veh != nullptr) *nothing_to_do = false;
549 }
550 Vehicle *new_head = replacements.front().GetVehicle();
551
552 /* Note: When autoreplace has already failed here, old_vehs[] is not completely initialized. But it is also not needed. */
553 if (cost.Succeeded()) {
554 /* Separate the head, so we can start constructing the new chain */
555 Train *second = Train::From(old_head)->GetNextUnit();
556 if (second != nullptr) cost.AddCost(CmdMoveVehicle(second, nullptr, {DoCommandFlag::Execute, DoCommandFlag::AutoReplace}, true));
557
558 assert(Train::From(new_head)->GetNextUnit() == nullptr);
559
560 /* Append engines to the new chain
561 * We do this from back to front, so that the head of the temporary vehicle chain does not change all the time.
562 * That way we also have less trouble when exceeding the unitnumber limit.
563 * OTOH the vehicle attach callback is more expensive this way :s */
564 Vehicle *last_engine = nullptr;
565 if (cost.Succeeded()) {
566 for (auto it = std::rbegin(replacements); it != std::rend(replacements); ++it) {
567 Vehicle *append = it->GetVehicle();
568
569 if (RailVehInfo(append->engine_type)->railveh_type == RAILVEH_WAGON) continue;
570
571 if (it->new_veh != nullptr) {
572 /* Move the old engine to a separate row with DoCommandFlag::AutoReplace. Else
573 * moving the wagon in front may fail later due to unitnumber limit.
574 * (We have to attach wagons without DoCommandFlag::AutoReplace.) */
575 CmdMoveVehicle(it->old_veh, nullptr, {DoCommandFlag::Execute, DoCommandFlag::AutoReplace}, false);
576 }
577
578 if (last_engine == nullptr) last_engine = append;
579 cost.AddCost(CmdMoveVehicle(append, new_head, DoCommandFlag::Execute, false));
580 if (cost.Failed()) break;
581 }
582 if (last_engine == nullptr) last_engine = new_head;
583 }
584
585 /* When wagon removal is enabled and the new engines without any wagons are already longer than the old, we have to fail */
586 if (cost.Succeeded() && wagon_removal && Train::From(new_head)->gcache.cached_total_length > old_total_length) cost = CommandCost(STR_ERROR_TRAIN_TOO_LONG_AFTER_REPLACEMENT);
587
588 /* Append/insert wagons into the new vehicle chain
589 * 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.
590 */
591 if (cost.Succeeded()) {
592 for (auto it = std::rbegin(replacements); it != std::rend(replacements); ++it) {
593 assert(last_engine != nullptr);
594 Vehicle *append = it->GetVehicle();
595
596 if (RailVehInfo(append->engine_type)->railveh_type == RAILVEH_WAGON) {
597 /* Insert wagon after 'last_engine' */
598 CommandCost res = CmdMoveVehicle(append, last_engine, DoCommandFlag::Execute, false);
599
600 /* When we allow removal of wagons, either the move failing due
601 * to the train becoming too long, or the train becoming longer
602 * would move the vehicle to the empty vehicle chain. */
603 if (wagon_removal && (res.Failed() ? res.GetErrorMessage() == STR_ERROR_TRAIN_TOO_LONG : Train::From(new_head)->gcache.cached_total_length > old_total_length)) {
604 CmdMoveVehicle(append, nullptr, {DoCommandFlag::Execute, DoCommandFlag::AutoReplace}, false);
605 break;
606 }
607
608 cost.AddCost(std::move(res));
609 if (cost.Failed()) break;
610 } else {
611 /* We have reached 'last_engine', continue with the next engine towards the front */
612 assert(append == last_engine);
613 last_engine = Train::From(last_engine)->GetPrevUnit();
614 }
615 }
616 }
617
618 /* Sell superfluous new vehicles that could not be inserted. */
619 if (cost.Succeeded() && wagon_removal) {
620 assert(Train::From(new_head)->gcache.cached_total_length <= _settings_game.vehicle.max_train_length * TILE_SIZE);
621 for (auto it = std::next(std::begin(replacements)); it != std::end(replacements); ++it) {
622 Vehicle *wagon = it->new_veh;
623 if (wagon == nullptr) continue;
624 if (wagon->First() == new_head) break;
625
626 assert(RailVehInfo(wagon->engine_type)->railveh_type == RAILVEH_WAGON);
627
628 /* Sell wagon */
629 [[maybe_unused]] CommandCost ret = Command<CMD_SELL_VEHICLE>::Do(DoCommandFlag::Execute, wagon->index, false, false, INVALID_CLIENT_ID);
630 assert(ret.Succeeded());
631 it->new_veh = nullptr;
632
633 /* Revert the money subtraction when the vehicle was built.
634 * This value is different from the sell value, esp. because of refitting */
635 cost.AddCost(-it->cost);
636 }
637 }
638
639 /* The new vehicle chain is constructed, now take over orders and everything... */
640 if (cost.Succeeded()) cost.AddCost(CopyHeadSpecificThings(old_head, new_head, flags));
641
642 if (cost.Succeeded()) {
643 /* Success ! */
644 if (flags.Test(DoCommandFlag::Execute) && new_head != old_head) {
645 *chain = new_head;
646 AI::NewEvent(old_head->owner, new ScriptEventVehicleAutoReplaced(old_head->index, new_head->index));
647 }
648
649 /* Transfer cargo of old vehicles and sell them */
650 for (auto it = std::begin(replacements); it != std::end(replacements); ++it) {
651 Vehicle *w = it->old_veh;
652 /* Is the vehicle again part of the new chain?
653 * Note: We cannot test 'new_vehs[i] != nullptr' as wagon removal might cause to remove both */
654 if (w->First() == new_head) continue;
655
656 if (flags.Test(DoCommandFlag::Execute)) TransferCargo(w, new_head, true);
657
658 /* Sell the vehicle.
659 * Note: This might temporarily construct new trains, so use DoCommandFlag::AutoReplace to prevent
660 * it from failing due to engine limits. */
661 cost.AddCost(Command<CMD_SELL_VEHICLE>::Do(DoCommandFlags{flags}.Set(DoCommandFlag::AutoReplace), w->index, false, false, INVALID_CLIENT_ID));
662 if (flags.Test(DoCommandFlag::Execute)) {
663 it->old_veh = nullptr;
664 if (it == std::begin(replacements)) old_head = nullptr;
665 }
666 }
667
668 if (flags.Test(DoCommandFlag::Execute)) CheckCargoCapacity(new_head);
669 }
670
671 /* If we are not in DoCommandFlag::Execute undo everything, i.e. rearrange old vehicles.
672 * We do this from back to front, so that the head of the temporary vehicle chain does not change all the time.
673 * Note: The vehicle attach callback is disabled here :) */
674 if (!flags.Test(DoCommandFlag::Execute)) {
675 /* Separate the head, so we can reattach the old vehicles */
676 second = Train::From(old_head)->GetNextUnit();
677 if (second != nullptr) CmdMoveVehicle(second, nullptr, {DoCommandFlag::Execute, DoCommandFlag::AutoReplace}, true);
678
679 assert(Train::From(old_head)->GetNextUnit() == nullptr);
680
681 for (auto it = std::rbegin(replacements); it != std::rend(replacements); ++it) {
682 [[maybe_unused]] CommandCost ret = CmdMoveVehicle(it->old_veh, old_head, {DoCommandFlag::Execute, DoCommandFlag::AutoReplace}, false);
683 assert(ret.Succeeded());
684 }
685 }
686 }
687
688 /* Finally undo buying of new vehicles */
689 if (!flags.Test(DoCommandFlag::Execute)) {
690 for (auto it = std::rbegin(replacements); it != std::rend(replacements); ++it) {
691 if (it->new_veh != nullptr) {
692 Command<CMD_SELL_VEHICLE>::Do(DoCommandFlag::Execute, it->new_veh->index, false, false, INVALID_CLIENT_ID);
693 it->new_veh = nullptr;
694 }
695 }
696 }
697 } else {
698 /* Build and refit replacement vehicle */
699 Vehicle *new_head = nullptr;
700 cost.AddCost(BuildReplacementVehicle(old_head, &new_head, true, flags));
701
702 /* Was a new vehicle constructed? */
703 if (cost.Succeeded() && new_head != nullptr) {
704 *nothing_to_do = false;
705
706 /* The new vehicle is constructed, now take over orders and everything... */
707 cost.AddCost(CopyHeadSpecificThings(old_head, new_head, flags));
708
709 if (cost.Succeeded()) {
710 /* The new vehicle is constructed, now take over cargo */
711 if (flags.Test(DoCommandFlag::Execute)) {
712 TransferCargo(old_head, new_head, true);
713 *chain = new_head;
714
715 AI::NewEvent(old_head->owner, new ScriptEventVehicleAutoReplaced(old_head->index, new_head->index));
716 }
717
718 /* Sell the old vehicle */
719 cost.AddCost(Command<CMD_SELL_VEHICLE>::Do(flags, old_head->index, false, false, INVALID_CLIENT_ID));
720 }
721
722 /* If we are not in DoCommandFlag::Execute undo everything */
723 if (!flags.Test(DoCommandFlag::Execute)) {
724 Command<CMD_SELL_VEHICLE>::Do(DoCommandFlag::Execute, new_head->index, false, false, INVALID_CLIENT_ID);
725 }
726 }
727 }
728
729 return cost;
730}
731
739 CommandCost CmdAutoreplaceVehicle(DoCommandFlags flags, VehicleID veh_id)
740{
741 Vehicle *v = Vehicle::GetIfValid(veh_id);
742 if (v == nullptr) return CMD_ERROR;
743
744 CommandCost ret = CheckOwnership(v->owner);
745 if (ret.Failed()) return ret;
746
747 if (v->vehstatus.Test(VehState::Crashed)) return CMD_ERROR;
748
749 bool free_wagon = false;
750 if (v->type == VEH_TRAIN) {
751 Train *t = Train::From(v);
752 if (t->IsArticulatedPart() || t->IsRearDualheaded()) return CMD_ERROR;
753 free_wagon = !t->IsFrontEngine();
754 if (free_wagon && t->First()->IsFrontEngine()) return CMD_ERROR;
755 } else {
756 if (!v->IsPrimaryVehicle()) return CMD_ERROR;
757 }
758 if (!v->IsChainInDepot()) return CMD_ERROR;
759
760 const Company *c = Company::Get(_current_company);
761 bool wagon_removal = c->settings.renew_keep_length;
762
763 const Group *g = Group::GetIfValid(v->group_id);
764 if (g != nullptr) wagon_removal = g->flags.Test(GroupFlag::ReplaceWagonRemoval);
765
766 /* Test whether any replacement is set, before issuing a whole lot of commands that would end in nothing changed */
767 Vehicle *w = v;
768 bool any_replacements = false;
769 while (w != nullptr) {
770 EngineID e;
771 CommandCost cost = GetNewEngineType(w, c, false, e);
772 if (cost.Failed()) return cost;
773 any_replacements |= (e != EngineID::Invalid());
774 w = (!free_wagon && w->type == VEH_TRAIN ? Train::From(w)->GetNextUnit() : nullptr);
775 }
776
777 CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES, (Money)0);
778 bool nothing_to_do = true;
779
780 if (any_replacements) {
781 bool was_stopped = free_wagon || v->vehstatus.Test(VehState::Stopped);
782
783 /* Stop the vehicle */
784 if (!was_stopped) cost.AddCost(DoCmdStartStopVehicle(v, true));
785 if (cost.Failed()) return cost;
786
787 assert(free_wagon || v->IsStoppedInDepot());
788
789 /* We have to construct the new vehicle chain to test whether it is valid.
790 * Vehicle construction needs random bits, so we have to save the random seeds
791 * to prevent desyncs and to replay newgrf callbacks during DoCommandFlag::Execute */
792 SavedRandomSeeds saved_seeds;
793 SaveRandomSeeds(&saved_seeds);
794 if (free_wagon) {
795 cost.AddCost(ReplaceFreeUnit(&v, DoCommandFlags{flags}.Reset(DoCommandFlag::Execute), &nothing_to_do));
796 } else {
797 cost.AddCost(ReplaceChain(&v, DoCommandFlags{flags}.Reset(DoCommandFlag::Execute), wagon_removal, &nothing_to_do));
798 }
799 RestoreRandomSeeds(saved_seeds);
800
801 if (cost.Succeeded() && flags.Test(DoCommandFlag::Execute)) {
802 if (free_wagon) {
803 ret = ReplaceFreeUnit(&v, flags, &nothing_to_do);
804 } else {
805 ret = ReplaceChain(&v, flags, wagon_removal, &nothing_to_do);
806 }
807 assert(ret.Succeeded() && ret.GetCost() == cost.GetCost());
808 }
809
810 /* Restart the vehicle */
811 if (!was_stopped) cost.AddCost(DoCmdStartStopVehicle(v, false));
812 }
813
814 if (cost.Succeeded() && nothing_to_do) cost = CommandCost(STR_ERROR_AUTOREPLACE_NOTHING_TO_DO);
815 return cost;
816}
817
827 CommandCost CmdSetAutoReplace(DoCommandFlags flags, GroupID id_g, EngineID old_engine_type, EngineID new_engine_type, bool when_old)
828{
829 Company *c = Company::GetIfValid(_current_company);
830 if (c == nullptr) return CMD_ERROR;
831
832 CommandCost cost;
833
834 if (Group::IsValidID(id_g) ? Group::Get(id_g)->owner != _current_company : !IsAllGroupID(id_g) && !IsDefaultGroupID(id_g)) return CMD_ERROR;
835 if (!Engine::IsValidID(old_engine_type)) return CMD_ERROR;
836 if (Group::IsValidID(id_g) && Group::Get(id_g)->vehicle_type != Engine::Get(old_engine_type)->type) return CMD_ERROR;
837
838 if (new_engine_type != EngineID::Invalid()) {
839 if (!Engine::IsValidID(new_engine_type)) return CMD_ERROR;
840 if (!CheckAutoreplaceValidity(old_engine_type, new_engine_type, _current_company)) return CMD_ERROR;
841
842 cost = AddEngineReplacementForCompany(c, old_engine_type, new_engine_type, id_g, when_old, flags);
843 } else {
844 cost = RemoveEngineReplacementForCompany(c, old_engine_type, id_g, flags);
845 }
846
847 if (flags.Test(DoCommandFlag::Execute)) {
848 GroupStatistics::UpdateAutoreplace(_current_company);
849 if (IsLocalCompany()) SetWindowDirty(WC_REPLACE_VEHICLE, Engine::Get(old_engine_type)->type);
850
851 const VehicleType vt = Engine::Get(old_engine_type)->type;
852 SetWindowDirty(GetWindowClassForVehicleType(vt), VehicleListIdentifier(VL_GROUP_LIST, vt, _current_company).ToWindowNumber());
853 }
854 if (flags.Test(DoCommandFlag::Execute) && IsLocalCompany()) InvalidateAutoreplaceWindow(old_engine_type, id_g);
855
856 return cost;
857}
858
ai.hpp
Base functions for all AIs.
GetUnionOfArticulatedRefitMasks
CargoTypes GetUnionOfArticulatedRefitMasks(EngineID engine, bool include_initial_cargo_type)
Ors the refit_masks of all articulated parts.
Definition articulated_vehicles.cpp:248
GetCargoTypesOfArticulatedVehicle
CargoTypes GetCargoTypesOfArticulatedVehicle(const Vehicle *v, CargoType *cargo_type)
Get cargo mask of all cargoes carried by an articulated vehicle.
Definition articulated_vehicles.cpp:262
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:222
GetCargoTypesOfArticulatedParts
CargoTypes GetCargoTypesOfArticulatedParts(EngineID engine)
Get the cargo mask of the parts of a given engine.
Definition articulated_vehicles.cpp:166
articulated_vehicles.h
Functions related to articulated vehicles.
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:205
DoCmdStartStopVehicle
static CommandCost DoCmdStartStopVehicle(const Vehicle *v, bool evaluate_callback)
Issue a start/stop command.
Definition autoreplace_cmd.cpp:392
CheckCargoCapacity
void CheckCargoCapacity(Vehicle *v)
Check the capacity of all vehicles in a chain and spread cargo if needed.
Definition autoreplace_cmd.cpp:107
GetNewCargoTypeForReplace
static CargoType 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:231
ChangeVehicleViewports
void ChangeVehicleViewports(VehicleID from_index, VehicleID to_index)
Switches viewports following vehicles, which get autoreplaced.
Definition window.cpp:3513
CmdMoveVehicle
static CommandCost CmdMoveVehicle(const Vehicle *v, const Vehicle *after, DoCommandFlags flags, bool whole_chain)
Issue a train vehicle move command.
Definition autoreplace_cmd.cpp:405
CmdSetAutoReplace
CommandCost CmdSetAutoReplace(DoCommandFlags flags, GroupID id_g, EngineID old_engine_type, EngineID new_engine_type, bool when_old)
Change engine renewal parameters.
Definition autoreplace_cmd.cpp:827
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:1083
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:1589
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:46
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:182
CheckAutoreplaceValidity
bool CheckAutoreplaceValidity(EngineID from, EngineID to, CompanyID company)
Checks some basic properties whether autoreplace is allowed.
Definition autoreplace_cmd.cpp:60
CopyHeadSpecificThings
static CommandCost CopyHeadSpecificThings(Vehicle *old_head, Vehicle *new_head, DoCommandFlags flags)
Copy head specific things to the new vehicle chain after it was successfully constructed.
Definition autoreplace_cmd.cpp:416
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:281
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:142
ReplaceFreeUnit
static CommandCost ReplaceFreeUnit(Vehicle **single_unit, DoCommandFlags flags, bool *nothing_to_do)
Replace a single unit in a free wagon chain.
Definition autoreplace_cmd.cpp:458
BuildReplacementVehicle
static CommandCost BuildReplacementVehicle(Vehicle *old_veh, Vehicle **new_vehicle, bool part_of_chain, DoCommandFlags flags)
Builds and refits a replacement vehicle Important: The old vehicle is still in the original vehicle c...
Definition autoreplace_cmd.cpp:320
ReplaceChain
static CommandCost ReplaceChain(Vehicle **chain, DoCommandFlags flags, bool wagon_removal, bool *nothing_to_do)
Replace a whole vehicle chain.
Definition autoreplace_cmd.cpp:525
CmdAutoreplaceVehicle
CommandCost CmdAutoreplaceVehicle(DoCommandFlags flags, VehicleID veh_id)
Autoreplaces a vehicle Trains are replaced as a whole chain, free wagons in depot are replaced on the...
Definition autoreplace_cmd.cpp:739
autoreplace_cmd.h
Command definitions related to autoreplace.
autoreplace_func.h
Functions related to autoreplacing.
AddEngineReplacementForCompany
CommandCost AddEngineReplacementForCompany(Company *c, EngineID old_engine, EngineID new_engine, GroupID group, bool replace_when_old, DoCommandFlags flags)
Add an engine replacement for the company.
Definition autoreplace_func.h:80
EngineReplacementForCompany
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
RemoveEngineReplacementForCompany
CommandCost RemoveEngineReplacementForCompany(Company *c, EngineID engine, GroupID group, DoCommandFlags flags)
Remove an engine replacement for the company.
Definition autoreplace_func.h:93
InvalidateAutoreplaceWindow
void InvalidateAutoreplaceWindow(EngineID e, GroupID id_g)
Rebuild the left autoreplace list if an engine is removed or added.
Definition autoreplace_gui.cpp:54
autoreplace_gui.h
Functions related to the autoreplace GUIs.
bitmath_func.hpp
Functions related to bit mathematics.
HasBit
constexpr bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
Definition bitmath_func.hpp:103
HasAtMostOneBit
constexpr bool HasAtMostOneBit(T value)
Test whether value has at most 1 bit set.
Definition bitmath_func.hpp:266
CargoType
uint8_t CargoType
Cargo slots to indicate a cargo type within a game.
Definition cargo_type.h:21
IsValidCargoType
bool IsValidCargoType(CargoType cargo)
Test whether cargo type is not INVALID_CARGO.
Definition cargo_type.h:104
NUM_CARGO
static const CargoType NUM_CARGO
Maximum number of cargo types in a game.
Definition cargo_type.h:73
CARGO_NO_REFIT
static const CargoType CARGO_NO_REFIT
Do not refit cargo of a vehicle (used in vehicle orders and auto-replace/auto-renew).
Definition cargo_type.h:77
AI::NewEvent
static void NewEvent(CompanyID company, ScriptEvent *event)
Queue a new event for an AI.
Definition ai_core.cpp:235
BaseBitSet::Test
constexpr bool Test(Tvalue_type value) const
Test if the value-th bit is set.
Definition base_bitset_type.hpp:141
BaseBitSet::Reset
constexpr Timpl & Reset()
Reset all bits.
Definition base_bitset_type.hpp:83
BaseBitSet::Set
constexpr Timpl & Set()
Set all bits.
Definition base_bitset_type.hpp:40
BaseBitSet::Any
constexpr bool Any(const Timpl &other) const
Test if any of the given values are set.
Definition base_bitset_type.hpp:170
CargoList< VehicleCargoList, CargoPacketList >::MTA_KEEP
@ MTA_KEEP
Keep the cargo in the vehicle.
Definition cargopacket.h:290
CommandCost
Common return value for all commands.
Definition command_type.h:24
CommandCost::Succeeded
bool Succeeded() const
Did this command succeed?
Definition command_type.h:168
CommandCost::AddCost
void AddCost(const Money &cost)
Adds the given cost to the cost of the command.
Definition command_type.h:98
CommandCost::GetCost
Money GetCost() const
The costs as made up to this moment.
Definition command_type.h:118
CommandCost::Failed
bool Failed() const
Did this command fail?
Definition command_type.h:177
CommandCost::GetErrorMessage
StringID GetErrorMessage() const
Returns the error message of a command.
Definition command_type.h:148
EncodedString
Container for an encoded string, created by GetEncodedString.
Definition strings_type.h:98
Engine
Definition engine_base.h:38
Engine::type
VehicleType type
Vehicle type, ie VEH_ROAD, VEH_TRAIN, etc.
Definition engine_base.h:62
Engine::CanCarryCargo
bool CanCarryCargo() const
Determines whether an engine can carry something.
Definition engine.cpp:167
EnumBitSet
Enum-as-bit-set wrapper.
Definition enum_type.hpp:177
OverflowSafeInt< int64_t >
RoadTypeInfo::powered_roadtypes
RoadTypes powered_roadtypes
bitmask to the OTHER roadtypes on which a vehicle of THIS roadtype generates power
Definition road.h:96
VehicleCargoList::TotalCount
uint TotalCount() const
Returns sum of cargo, including reserved cargo.
Definition cargopacket.h:434
command_func.h
Functions related to commands.
CMD_ERROR
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
Definition command_func.h:28
DoCommandFlag::Execute
@ Execute
execute the given command
DoCommandFlag::NoCargoCapacityCheck
@ NoCargoCapacityCheck
when autoreplace/autorenew is in progress, this shall prevent truncating the amount of cargo in the v...
DoCommandFlag::AutoReplace
@ AutoReplace
autoreplace/autorenew is in progress, this shall disable vehicle limits when building,...
CheckOwnership
CommandCost CheckOwnership(Owner owner, TileIndex tile)
Check whether the current owner owns something.
Definition company_cmd.cpp:381
_current_company
CompanyID _current_company
Company currently doing an action.
Definition company_cmd.cpp:56
company_func.h
Functions related to companies.
IsLocalCompany
bool IsLocalCompany()
Is the current company the local company?
Definition company_func.h:47
EXPENSES_NEW_VEHICLES
@ EXPENSES_NEW_VEHICLES
New vehicles.
Definition economy_type.h:180
IsEngineBuildable
bool IsEngineBuildable(EngineID engine, VehicleType type, CompanyID company)
Check if an engine is buildable.
Definition engine.cpp:1246
engine_func.h
Functions related to engines.
AIR_CTOL
@ AIR_CTOL
Conventional Take Off and Landing, i.e. planes.
Definition engine_type.h:127
EngineMiscFlag::RoadIsTram
@ RoadIsTram
Road vehicle is a tram/light rail vehicle.
RAILVEH_WAGON
@ RAILVEH_WAGON
simple wagon, not motorized
Definition engine_type.h:34
GroupFlag::ReplaceWagonRemoval
@ ReplaceWagonRemoval
If set, autoreplace will perform wagon removal on vehicles in this group.
IsAllGroupID
bool IsAllGroupID(GroupID id_g)
Checks if a GroupID stands for all vehicles of a company.
Definition group.h:103
group_cmd.h
Command definitions related to engine groups.
CeilDiv
constexpr uint CeilDiv(uint a, uint b)
Computes ceil(a / b) for non-negative a and b.
Definition math_func.hpp:310
INVALID_CLIENT_ID
@ INVALID_CLIENT_ID
Client is not part of anything.
Definition network_type.h:44
TestVehicleBuildProbability
std::optional< bool > TestVehicleBuildProbability(Vehicle *v, EngineID engine, BuildProbabilityType type)
Test for vehicle build probability type.
Definition newgrf_engine.cpp:1251
news_func.h
Functions related to news.
AddVehicleAdviceNewsItem
void AddVehicleAdviceNewsItem(AdviceType advice_type, EncodedString &&headline, VehicleID vehicle)
Adds a vehicle-advice news item.
Definition news_func.h:40
AdviceType::AutorenewFailed
@ AutorenewFailed
Autorenew or autoreplace failed.
order_cmd.h
Command definitions related to orders.
VehicleOrderID
uint8_t VehicleOrderID
The index of an order within its current vehicle (not pool related)
Definition order_type.h:18
GetAllCompatibleRailTypes
RailTypes GetAllCompatibleRailTypes(RailTypes railtypes)
Returns all compatible railtypes for a set of railtypes.
Definition rail.h:312
random_func.hpp
Pseudo random number generator.
SaveRandomSeeds
void SaveRandomSeeds(SavedRandomSeeds *storage)
Saves the current seeds.
Definition random_func.hpp:55
RestoreRandomSeeds
void RestoreRandomSeeds(const SavedRandomSeeds &storage)
Restores previously saved seeds.
Definition random_func.hpp:65
road.h
Road specific functions.
GetRoadTypeInfo
const RoadTypeInfo * GetRoadTypeInfo(RoadType roadtype)
Returns a pointer to the Roadtype information for a given roadtype.
Definition road.h:215
safeguards.h
A number of safeguards to prevent using unsafe methods.
_settings_game
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition settings.cpp:61
stdafx.h
Definition of base types and functions in a cross-platform compatible way.
GetEncodedString
EncodedString GetEncodedString(StringID str)
Encode a string with no parameters into an encoded string.
Definition strings.cpp:90
strings_func.h
Functions related to OTTD's strings.
AircraftVehicleInfo
Information about a aircraft vehicle.
Definition engine_type.h:132
AircraftVehicleInfo::subtype
uint8_t subtype
Type of aircraft.
Definition engine_type.h:136
BaseVehicle::type
VehicleType type
Type of vehicle.
Definition vehicle_type.h:51
CargoSpec::Get
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo type.
Definition cargotype.h:137
CargoSpec::name
StringID name
Name of this type of cargo.
Definition cargotype.h:91
CommandHelper
Definition command_func.h:84
CompanyProperties::settings
CompanySettings settings
settings specific for each company
Definition company_base.h:124
CompanySettings::renew_keep_length
bool renew_keep_length
sell some wagons if after autoreplace the train is longer than before
Definition settings_type.h:614
Company
Definition company_base.h:127
EngineInfo::misc_flags
EngineMiscFlags misc_flags
Miscellaneous flags.
Definition engine_type.h:209
GameSettings::vehicle
VehicleSettings vehicle
options for vehicles
Definition settings_type.h:641
GroundVehicle::IsRearDualheaded
bool IsRearDualheaded() const
Tell if we are dealing with the rear end of a multiheaded engine.
Definition ground_vehicle.hpp:336
GroupStatistics::AddProfitLastYear
static void AddProfitLastYear(const Vehicle *v)
Add a vehicle's last year profit to the profit sum of its group.
Definition group_cmd.cpp:187
GroupStatistics::UpdateAutoreplace
static void UpdateAutoreplace(CompanyID company)
Update autoreplace_defined and autoreplace_finished of all statistics of a company.
Definition group_cmd.cpp:240
Group
Group data.
Definition group.h:73
Group::flags
GroupFlags flags
Group flags.
Definition group.h:78
OrderList
Shared order list linking together the linked list of orders and the list of vehicles sharing this or...
Definition order_base.h:274
OrderList::GetNumOrders
VehicleOrderID GetNumOrders() const
Get number of orders in the order list.
Definition order_base.h:372
OrderList::GetOrderAt
const Order * GetOrderAt(VehicleOrderID index) const
Get a certain order of the order chain.
Definition order_base.h:338
Order
Definition order_base.h:33
Order::GetRefitCargo
CargoType GetRefitCargo() const
Get the cargo to to refit to.
Definition order_base.h:127
Order::IsRefit
bool IsRefit() const
Is this order a refit order.
Definition order_base.h:113
PoolID< uint32_t, struct VehicleIDTag, 0xFF000, 0xFFFFF >
Pool::PoolItem<&_engine_pool >::Get
static Titem * Get(auto index)
Returns Titem with given index.
Definition pool_type.hpp:387
Pool::PoolItem::index
Tindex index
Index of this pool item.
Definition pool_type.hpp:286
Pool::PoolItem<&_engine_pool >::IsValidID
static bool IsValidID(auto index)
Tests whether given index can be used to get valid (non-nullptr) Titem.
Definition pool_type.hpp:376
Pool::PoolItem<&_vehicle_pool >::GetIfValid
static Titem * GetIfValid(auto index)
Returns Titem with given index.
Definition pool_type.hpp:398
RailVehicleInfo
Information about a rail vehicle.
Definition engine_type.h:74
RailVehicleInfo::railtypes
RailTypes railtypes
Railtypes, mangled if elrail is disabled.
Definition engine_type.h:78
ReplaceChainItem
Struct for recording vehicle chain replacement information.
Definition autoreplace_cmd.cpp:503
ReplaceChainItem::GetVehicle
Vehicle * GetVehicle() const
Get vehicle to use for this position.
Definition autoreplace_cmd.cpp:514
ReplaceChainItem::new_veh
Vehicle * new_veh
Replacement vehicle, or nullptr if no replacement.
Definition autoreplace_cmd.cpp:505
ReplaceChainItem::ReplaceChainItem
ReplaceChainItem(Vehicle *old_veh, Vehicle *new_veh, Money cost)
Cost of buying and refitting replacement.
Definition autoreplace_cmd.cpp:508
ReplaceChainItem::old_veh
Vehicle * old_veh
Old vehicle to replace.
Definition autoreplace_cmd.cpp:504
RoadVehicleInfo
Information about a road vehicle.
Definition engine_type.h:146
RoadVehicleInfo::roadtype
RoadType roadtype
Road type.
Definition engine_type.h:160
SavedRandomSeeds
Stores the state of all random number generators.
Definition random_func.hpp:46
SpecializedVehicle::From
static T * From(Vehicle *v)
Converts a Vehicle to SpecializedVehicle with type checking.
Definition vehicle_base.h:1134
SpecializedVehicle::First
T * First() const
Get the first vehicle in the chain.
Definition vehicle_base.h:1031
Train
'Train' is either a loco or a wagon.
Definition train.h:91
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:150
VehicleListIdentifier
The information about a vehicle list.
Definition vehiclelist.h:32
VehicleSettings::max_train_length
uint8_t max_train_length
maximum length for trains
Definition settings_type.h:518
Vehicle
Vehicle data structure.
Definition vehicle_base.h:205
Vehicle::engine_type
EngineID engine_type
The type of engine used for this vehicle.
Definition vehicle_base.h:278
Vehicle::GetEngine
const Engine * GetEngine() const
Retrieves the engine of the vehicle.
Definition vehicle.cpp:718
Vehicle::IsStoppedInDepot
bool IsStoppedInDepot() const
Check whether the vehicle is in the depot and stopped.
Definition vehicle_base.h:515
Vehicle::IsChainInDepot
virtual bool IsChainInDepot() const
Check whether the whole vehicle chain is in the depot.
Definition vehicle_base.h:509
Vehicle::cargo
VehicleCargoList cargo
The cargo this vehicle is carrying.
Definition vehicle_base.h:296
Vehicle::group_id
GroupID group_id
Index of group Pool array.
Definition vehicle_base.h:321
Vehicle::vehstatus
VehStates vehstatus
Status.
Definition vehicle_base.h:309
Vehicle::IsArticulatedPart
bool IsArticulatedPart() const
Check if the vehicle is an articulated part of an engine.
Definition vehicle_base.h:922
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:156
Vehicle::cargo_type
CargoType cargo_type
type of cargo this vehicle is carrying
Definition vehicle_base.h:297
Vehicle::First
Vehicle * First() const
Get the first vehicle of this vehicle chain.
Definition vehicle_base.h:600
Vehicle::Next
Vehicle * Next() const
Get the next vehicle of this vehicle.
Definition vehicle_base.h:587
Vehicle::orders
OrderList * orders
Pointer to the order list for this vehicle.
Definition vehicle_base.h:314
Vehicle::IsPrimaryVehicle
virtual bool IsPrimaryVehicle() const
Whether this is the primary vehicle in the chain.
Definition vehicle_base.h:432
Vehicle::IsFrontEngine
bool IsFrontEngine() const
Check if the vehicle is a front engine.
Definition vehicle_base.h:913
Vehicle::tile
TileIndex tile
Current tile index.
Definition vehicle_base.h:225
Vehicle::CopyVehicleConfigAndStatistics
void CopyVehicleConfigAndStatistics(Vehicle *src)
Copy certain configurations and statistics of a vehicle after successful autoreplace/renew The functi...
Definition vehicle_base.h:733
Vehicle::owner
Owner owner
Which company owns the vehicle?
Definition vehicle_base.h:270
TILE_SIZE
static constexpr uint TILE_SIZE
Tile size in world coordinates.
Definition tile_type.h:15
train.h
Base for the train class.
CCF_LOADUNLOAD
static constexpr ConsistChangeFlags CCF_LOADUNLOAD
Valid changes while vehicle is loading/unloading.
Definition train.h:53
Flipped
@ Flipped
Reverse the visible direction of the vehicle.
Definition train.h:28
train_cmd.h
Command definitions related to trains.
VehState::Crashed
@ Crashed
Vehicle is crashed.
VehState::Stopped
@ Stopped
Vehicle is stopped by the player.
vehicle_cmd.h
Command definitions for vehicles.
vehicle_func.h
Functions related to vehicles.
GetBestFittingSubType
uint8_t GetBestFittingSubType(Vehicle *v_from, Vehicle *v_for, CargoType dest_cargo_type)
Get the best fitting subtype when 'cloning'/'replacing' v_from with v_for.
Definition vehicle_gui.cpp:600
GetWindowClassForVehicleType
WindowClass GetWindowClassForVehicleType(VehicleType vt)
Get WindowClass for vehicle list of given vehicle type.
Definition vehicle_gui.h:97
VehicleType
VehicleType
Available vehicle types.
Definition vehicle_type.h:22
VEH_ROAD
@ VEH_ROAD
Road vehicle type.
Definition vehicle_type.h:26
VEH_AIRCRAFT
@ VEH_AIRCRAFT
Aircraft vehicle type.
Definition vehicle_type.h:28
VEH_TRAIN
@ VEH_TRAIN
Train vehicle type.
Definition vehicle_type.h:25
vehiclelist.h
Functions and type for generating vehicle lists.
VL_GROUP_LIST
@ VL_GROUP_LIST
Index is the group.
Definition vehiclelist.h:27
SetWindowDirty
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
Definition window.cpp:3179
WC_REPLACE_VEHICLE
@ WC_REPLACE_VEHICLE
Replace vehicle window; Window numbers:
Definition window_type.h:223