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