41#include "table/strings.h"
62 return image_index <
lengthof(_engine_sprite_base);
87 std::max(
abs(u->x_pos - w->x_pos),
abs(u->y_pos - w->y_pos)) != u->CalcNextVehicleOffset()) ||
112 uint16_t max_speed = UINT16_MAX;
118 this->
gcache.cached_total_length = 0;
121 bool train_can_tilt =
true;
122 int16_t min_curve_speed_mod = INT16_MAX;
124 for (
Train *u =
this; u !=
nullptr; u = u->Next()) {
128 assert(u->First() ==
this);
131 u->gcache.first_engine =
this == u ? EngineID::Invalid() : first_engine;
134 if (u->IsEngine()) first_engine = u->engine_type;
139 u->InvalidateNewGRFCache();
142 for (
Train *u =
this; u !=
nullptr; u = u->Next()) {
146 u->InvalidateNewGRFCache();
149 for (
Train *u =
this; u !=
nullptr; u = u->Next()) {
150 const Engine *e_u = u->GetEngine();
154 min_curve_speed_mod = std::min(min_curve_speed_mod, u->GetCurveSpeedModifier());
157 u->tcache.cached_override = GetWagonOverrideSpriteSet(u->engine_type, u->cargo_type, u->gcache.first_engine);
160 u->colourmap = PAL_NONE;
163 u->UpdateVisualEffect(
true);
173 if (!u->IsArticulatedPart()) {
176 if (rvi_u->
power > 0) {
190 if (speed != 0) max_speed = std::min(speed, max_speed);
197 if (u->cargo_cap > new_cap) u->cargo.Truncate(new_cap);
198 u->refit_cap = std::min(new_cap, u->refit_cap);
199 u->cargo_cap = new_cap;
208 if (e_u->
GetGRF() !=
nullptr && e_u->
GetGRF()->grf_version >= 8) {
224 u->gcache.cached_veh_length = veh_len;
230 this->
gcache.cached_total_length += u->gcache.cached_veh_length;
232 u->InvalidateNewGRFCache();
236 this->
vcache.cached_max_speed = max_speed;
237 this->
tcache.cached_tilt = train_can_tilt;
238 this->
tcache.cached_curve_speed_mod = min_curve_speed_mod;
286 default: NOT_REACHED();
297 stop = *station_length;
314 assert(this->
First() ==
this);
316 static const int absolute_max_speed = UINT16_MAX;
317 int max_speed = absolute_max_speed;
319 if (
_settings_game.vehicle.train_acceleration_model == AM_ORIGINAL)
return max_speed;
321 int curvecount[2] = {0, 0};
328 for (
const Train *u =
this; u->Next() !=
nullptr; u = u->Next(), pos += u->gcache.cached_veh_length) {
330 Direction next_dir = u->Next()->direction;
340 sum += pos - lastpos;
341 if (pos - lastpos <=
static_cast<int>(
VEHICLE_LENGTH) && max_speed > 88) {
354 if (numcurve > 0 && max_speed > 88) {
355 if (curvecount[0] == 1 && curvecount[1] == 1) {
356 max_speed = absolute_max_speed;
360 max_speed = 232 - (13 -
Clamp(sum, 1, 12)) * (13 -
Clamp(sum, 1, 12));
364 if (max_speed != absolute_max_speed) {
369 if (this->
tcache.cached_tilt) {
371 max_speed += max_speed / 5;
376 max_speed += (max_speed * this->
tcache.cached_curve_speed_mod) / 256;
377 max_speed =
Clamp(max_speed, 2, absolute_max_speed);
380 return static_cast<uint16_t
>(max_speed);
390 int max_speed =
_settings_game.vehicle.train_acceleration_model == AM_ORIGINAL ?
391 this->
gcache.cached_max_track_speed :
392 this->
tcache.cached_max_curve_speed;
403 int distance_to_go = station_ahead /
TILE_SIZE - (station_length - stop_at) /
TILE_SIZE;
405 if (distance_to_go > 0) {
406 int st_max_speed = 120;
408 int delta_v = this->
cur_speed / (distance_to_go + 1);
409 if (max_speed > (this->
cur_speed - delta_v)) {
410 st_max_speed = this->
cur_speed - (delta_v / 10);
413 st_max_speed = std::max(st_max_speed, 25 * distance_to_go);
414 max_speed = std::min(max_speed, st_max_speed);
419 for (
const Train *u =
this; u !=
nullptr; u = u->Next()) {
421 constexpr int DEPOT_SPEED_LIMIT = 61;
422 max_speed = std::min(max_speed, DEPOT_SPEED_LIMIT);
432 max_speed = std::min<int>(max_speed, this->
current_order.GetMaxSpeed());
436 constexpr int BACKWARDS_NO_CAB_SPEED_LIMIT = 32;
437 max_speed = std::min<int>(max_speed, BACKWARDS_NO_CAB_SPEED_LIMIT);
440 return std::min<int>(max_speed, this->
gcache.cached_max_track_speed);
448 uint power = this->
gcache.cached_power;
449 uint weight = this->
gcache.cached_weight;
461 int reference_width = TRAININFO_DEFAULT_VEHICLE_WIDTH;
480 int reference_width = TRAININFO_DEFAULT_VEHICLE_WIDTH;
481 int vehicle_pitch = 0;
489 if (offset !=
nullptr) {
518 if (IsCustomVehicleSpriteNum(
spritenum)) {
520 GetCustomVehicleSprite(
this,
direction, image_type, result);
529 if (this->
cargo.StoredCount() >= this->cargo_cap / 2U) sprite += _wagon_full_adder[
spritenum];
540 if (IsCustomVehicleSpriteNum(spritenum)) {
541 GetCustomVehicleIcon(engine, dir, image_type, result);
543 if (e->
GetGRF() !=
nullptr) {
549 spritenum =
Engine::Get(engine)->original_image_index;
552 if (rear_head) spritenum++;
567 GetRailIcon(engine,
false, yf, image_type, &seqf);
568 GetRailIcon(engine,
true, yr, image_type, &seqr);
574 preferred_x =
Clamp(preferred_x,
575 left -
UnScaleGUI(rectf.left) + vehicle_width / 2,
576 right -
UnScaleGUI(rectr.right) - (vehicle_width - vehicle_width / 2));
579 seqr.
Draw(preferred_x + (vehicle_width - vehicle_width / 2), yr, pal, pal ==
PALETTE_CRASH);
582 GetRailIcon(engine,
false, y, image_type, &seq);
586 preferred_x =
Clamp(preferred_x,
608 GetRailIcon(engine,
false, y, image_type, &seq);
622 GetRailIcon(engine,
true, y, image_type, &seq);
626 width = vehicle_width +
UnScaleGUI(rect.right) - xoffs;
628 xoffs = xoffs - vehicle_width / 2;
629 yoffs = std::min(yoffs,
UnScaleGUI(rect.top));
640 std::vector<VehicleID> free_wagons;
647 free_wagons.push_back(v->index);
651 std::ranges::sort(free_wagons);
725 if (vehicle == v->index)
continue;
729 if (w->
First() == v)
continue;
754static void AddRearEngineToMultiheadedTrain(
Train *v)
862 AddRearEngineToMultiheadedTrain(v);
876static Train *FindGoodVehiclePos(
const Train *src)
887 if (t ==
nullptr)
return dst;
904 for (; t !=
nullptr; t = t->
Next()) list.push_back(t);
914 if (list.empty())
return;
916 Train *prev =
nullptr;
918 for (
Train *t : list) {
919 if (prev !=
nullptr) {
921 }
else if (t->
Previous() !=
nullptr) {
941 while (tail->
Next() !=
nullptr) tail = tail->
Next();
999 if (chain ==
nullptr)
return;
1002 assert(chain->
Previous() ==
nullptr);
1013 for (
Train *t = chain->
Next(); t !=
nullptr; t = t->
Next()) {
1033 if ((src !=
nullptr && src->
IsEngine() ? 1 : 0) +
1034 (dst !=
nullptr && dst->
IsEngine() ? 1 : 0) -
1035 (original_src !=
nullptr && original_src->
IsEngine() ? 1 : 0) -
1036 (original_dst !=
nullptr && original_dst->
IsEngine() ? 1 : 0) <= 0) {
1044 return CommandCost(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
1064 while (t !=
nullptr) {
1070 if (allowed_len < 0)
return CommandCost(STR_ERROR_TRAIN_TOO_LONG);
1084 while (t !=
nullptr) {
1103 std::array<int32_t, 1> regs100;
1117 if (head->
GetGRF()->grf_version < 8) {
1118 if (callback == 0xFD) error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
1122 if (callback < 0x400) {
1136 error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
1152 if (allowed_len < 0)
return CommandCost(STR_ERROR_TRAIN_TOO_LONG);
1170 if (ret.
Failed())
return ret;
1172 if (ret.
Failed())
return ret;
1189 if (*src_head == *dst_head) {
1192 *dst_head =
nullptr;
1193 }
else if (*dst_head ==
nullptr) {
1199 if (src == *src_head) {
1206 *src_head = move_chain ? nullptr :
1230 if (head ==
nullptr)
return;
1263 if (ret.
Failed())
return ret;
1270 if (dest_veh == VehicleID::Invalid()) {
1277 if (ret.
Failed())
return ret;
1285 if (dst !=
nullptr) {
1295 if (dst !=
nullptr) {
1296 dst_head = dst->
First();
1307 if (move_chain && src_head == dst_head)
return CommandCost();
1316 if (dst_head !=
nullptr && !dst_head->
IsStoppedInDepot())
return CommandCost(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
1329 Train *original_src_head = src_head;
1330 Train *original_dst_head = (dst_head == src_head ? nullptr : dst_head);
1335 bool original_src_head_front_engine = original_src_head->
IsFrontEngine();
1336 bool original_dst_head_front_engine = original_dst_head !=
nullptr && original_dst_head->
IsFrontEngine();
1345 ret =
ValidateTrains(original_dst_head, dst_head, original_src_head, src_head,
true);
1409 if (original_src_head != src && dst_head == src) {
1468 Train *new_head = first;
1469 Train *sell_head =
nullptr;
1472 ArrangeTrains(&sell_head,
nullptr, &new_head, v, sell_chain);
1485 return CommandCost(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
1489 for (
Train *part = sell_head; part !=
nullptr; part = part->
Next()) cost.
AddCost(-part->value);
1496 if (v == first && !sell_chain && new_head !=
nullptr && new_head->
IsFrontEngine()) {
1532 this->
bounds = {{-1, -1, 0}, {3, 3, 6}, {}};
1537 int flip_offs = flipped && (this->
gcache.cached_veh_length & 1);
1561 this->
bounds.origin.x = -(this->
gcache.cached_veh_length + 1) / 2 + flip_offs;
1562 this->
bounds.extent.x = this->
gcache.cached_veh_length;
1563 this->
bounds.offset.x = 1;
1567 this->
bounds.origin.y = -(this->
gcache.cached_veh_length + 1) / 2 + flip_offs;
1568 this->
bounds.extent.y = this->
gcache.cached_veh_length;
1569 this->
bounds.offset.y = 1;
1575 this->
bounds.origin.x = -(this->
gcache.cached_veh_length) / 2 - flip_offs;
1576 this->
bounds.extent.x = this->
gcache.cached_veh_length;
1581 this->
bounds.origin.y = -(this->
gcache.cached_veh_length) / 2 - flip_offs;
1582 this->
bounds.extent.y = this->
gcache.cached_veh_length;
1622 uint16_t flag1 = *swap_flag1;
1623 uint16_t flag2 = *swap_flag2;
1691 for (a = v; l != 0; l--) a = a->
Next();
1692 for (b = v; r != 0; r--) b = b->
Next();
1832 bool forced_state = force_bar;
1878 bool occupied =
false;
1926 Train *base = moving_front;
1927 Train *first = base;
1929 uint length = CountVehiclesInChain(moving_front->
First());
1931 while (length > 2) {
1955 Train *dep = moving_front;
1962 if (leave !=
nullptr) {
1975 Train *base = moving_front;
1976 Train *first = base;
1978 uint length = CountVehiclesInChain(moving_front->
First());
1982 bool nomove = (dep ==
nullptr);
1984 while (length > 2) {
1987 if (base == dep)
break;
1990 if (last == dep) nomove =
true;
2005static bool IsWholeTrainInsideDepot(
const Train *v)
2007 for (
const Train *u = v; u !=
nullptr; u = u->
Next()) {
2021 if (IsWholeTrainInsideDepot(consist))
return;
2036 for (
Train *u = consist; u !=
nullptr; u = u->
Next()) {
2048 int r = CountVehiclesInChain(consist) - 1;
2130 if (ret.
Failed())
return ret;
2132 if (reverse_single_veh) {
2136 return CommandCost(STR_ERROR_CAN_T_REVERSE_DIRECTION_RAIL_VEHICLE_MULTIPLE_UNITS);
2142 return CommandCost(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
2226 if (ret.
Failed())
return ret;
2264 static const SoundFx sfx[] = {
2297 case OT_GOTO_WAYPOINT:
2303 case OT_LEAVESTATION:
2320 CFollowTrackRail ft(consist);
2321 if (!ft.
Follow(moving_front->
tile, td))
return;
2332 ChooseTrainTrack(consist, ft.
new_tile, ft.
exitdir, tracks,
false,
nullptr,
false);
2346 for (
const Train *u = v; u !=
nullptr; u = u->
Next()) {
2479 for (
const Train *u = consist; u !=
nullptr; u = u->
Next()) {
2487 while (ft.
Follow(tile, td)) {
2543 return YapfTrainChooseTrack(v, tile, enterdir, tracks, path_found, do_track_reservation, dest, final_dest);
2558 CFollowTrackRail ft(v);
2560 std::vector<std::pair<TileIndex, Trackdir>> signals_set_to_red;
2564 while (ft.
Follow(tile, cur_td)) {
2592 if (enterdir !=
nullptr) *enterdir = ft.
exitdir;
2605 signals_set_to_red.emplace_back(tile, rev_td);
2617 signals_set_to_red.emplace_back(tile, rev_td);
2623 if (ft.err == CFollowTrackRail::EC_OWNER || ft.err == CFollowTrackRail::EC_NO_WAY) {
2633 while (tile != stopped || cur_td != stopped_td) {
2634 if (!ft.
Follow(tile, cur_td))
break;
2649 for (
auto [sig_tile, td] : signals_set_to_red) {
2673class VehicleOrderSaver {
2678 StationID old_last_station_visited;
2680 bool suppress_implicit_orders;
2684 VehicleOrderSaver(
Train *_v) :
2701 this->v->
dest_tile = this->old_dest_tile;
2704 this->restored =
true;
2712 if (!this->restored) this->
Restore();
2724 if (skip_first) ++this->index;
2730 if (this->index >= this->v->
GetNumOrders()) this->index = 0;
2733 assert(order !=
nullptr);
2740 case OT_GOTO_STATION:
2741 case OT_GOTO_WAYPOINT:
2744 case OT_CONDITIONAL: {
2771 bool do_track_reservation =
_settings_game.pf.reserve_paths || force_res;
2772 bool changed_signal =
false;
2777 if (got_reservation !=
nullptr) *got_reservation =
false;
2789 do_track_reservation =
true;
2790 changed_signal =
true;
2792 }
else if (!do_track_reservation) {
2802 if (do_track_reservation) {
2810 if (res_dest.okay) {
2812 if (got_reservation !=
nullptr) *got_reservation =
true;
2835 orders.SwitchToNextOrder(
false);
2840 orders.SwitchToNextOrder(
true);
2845 bool path_found =
true;
2848 Track next_track =
DoTrainPathfind(consist, new_tile, dest_enterdir, tracks, path_found, do_track_reservation, &res_dest, &final_dest);
2849 if (new_tile == tile) best_track = next_track;
2854 if (!do_track_reservation)
return best_track;
2871 if (got_reservation !=
nullptr) *got_reservation =
true;
2880 if (got_reservation !=
nullptr) *got_reservation =
true;
2893 if (orders.SwitchToNextOrder(
true)) {
2896 DoTrainPathfind(consist, next_tile, exitdir, reachable, path_found,
true, &cur_dest,
nullptr);
2898 res_dest = cur_dest;
2899 if (res_dest.okay)
continue;
2903 if (got_reservation !=
nullptr) *got_reservation =
false;
2904 changed_signal =
false;
2912 if (got_reservation !=
nullptr) *got_reservation =
false;
2913 changed_signal =
false;
2962 Vehicle *other_train =
nullptr;
2969 if (other_train !=
nullptr && other_train->index != consist->index) {
2974 if (origin.
okay && (moving_front->
tile != origin.
tile || first_tile_okay)) {
2993 bool res_made =
false;
2994 ChooseTrainTrack(consist, new_tile, exitdir, reachable,
true, &res_made, mark_as_stuck);
3055 }
while ((v = v->
Next()) !=
nullptr);
3072 default: NOT_REACHED();
3092 if (!(st->had_vehicle_of_type &
HVOT_TRAIN)) {
3100 AI::NewEvent(consist->
owner,
new ScriptEventStationFirstVehicle(st->index, consist->index));
3101 Game::NewEvent(
new ScriptEventStationFirstVehicle(st->index, consist->index));
3138 {256 / 4, 256 / 2, 256 / 4, 2},
3139 {256 / 4, 256 / 2, 256 / 4, 2},
3140 {0, 256 / 2, 256 / 4, 2},
3150 if (z_diff == 0 ||
_settings_game.vehicle.train_acceleration_model != AM_ORIGINAL)
return;
3158 if (spd <= consist->gcache.cached_max_track_speed) consist->
cur_speed = spd;
3179 for (
const Train *u =
this; u !=
nullptr; u = u->
Next()) {
3208 for (
const Train *v =
this; v !=
nullptr; v = v->
Next()) {
3244 victims = v->
Crash();
3246 AI::NewEvent(v->
owner,
new ScriptEventVehicleCrashed(v->index, tile, ScriptEventVehicleCrashed::CRASH_TRAIN, victims, v->
owner));
3247 Game::NewEvent(
new ScriptEventVehicleCrashed(v->index, tile, ScriptEventVehicleCrashed::CRASH_TRAIN, victims, v->
owner));
3275 if (v->
First() == moving_front->
First())
return 0;
3284 uint hash = (y_diff + 7) | (x_diff + 7);
3285 if (hash & ~15)
return 0;
3289 if (x_diff * x_diff + y_diff * y_diff > min_diff * min_diff)
return 0;
3315 uint num_victims = 0;
3332 if (num_victims == 0)
return false;
3352 bool direction_changed =
false;
3357 bool update_signals_crossing =
false;
3481 goto reverse_train_direction;
3493 chosen_track = bits;
3495 chosen_track = prev->
track;
3513 chosen_track = _connecting_track[enterdir][exitdir];
3515 chosen_track &= bits;
3544 v->
track = chosen_track;
3550 update_signals_crossing =
true;
3553 if (prev ==
nullptr &&
_settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) {
3558 direction_changed =
true;
3609 if (prev ==
nullptr) {
3614 if (update_signals_crossing) {
3616 if (TrainMovedChangeSignals(gp.
new_tile, enterdir)) {
3651 if (prev !=
nullptr) FatalError(
"Disconnecting train");
3653reverse_train_direction:
3664static bool IsRailStationPlatformOccupied(
TileIndex tile)
3692 Train *new_last = v;
3693 for (; v->
Next() !=
nullptr; v = v->
Next()) new_last = v;
3707 Owner owner = v->
owner;
3730 remaining_trackbits |= train_tbits;
3743 bool occupied = IsRailStationPlatformOccupied(tile);
3763 static const DirDiff delta[] = {
3781 }
while ((v = v->
Next()) !=
nullptr);
3798 if (state <= 200 &&
Chance16R(1, 7, r)) {
3799 int index = (r * 10 >> 16);
3813 }
while ((u = u->
Next()) !=
nullptr);
3819 bool ret = v->
Next() !=
nullptr;
3829 225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, 15
3844 uint x = moving_front->
x_pos & 0xF;
3845 uint y = moving_front->
y_pos & 0xF;
3880 if (break_speed < consist->cur_speed) consist->
cur_speed = break_speed;
3958 if (break_speed < consist->cur_speed) consist->
cur_speed = break_speed;
4123 if (j < adv_spd || consist->cur_speed == 0)
break;
4127 if ((order_type == OT_GOTO_WAYPOINT || order_type == OT_GOTO_STATION) &&
4137 for (
Train *u = consist; u !=
nullptr; u = u->
Next()) {
4155 const Train *v =
this;
4162 if (cost_factor == 0)
continue;
4214 uint max_penalty =
_settings_game.pf.yapf.maximum_go_to_depot_penalty;
4316 weight += RailVehInfo(this->
gcache.first_engine)->pow_wag_weight;
Base functions for all AIs.
void AddArticulatedParts(Vehicle *first)
Add the remaining articulated parts to the given vehicle.
void CheckConsistencyOfArticulatedVehicle(const Vehicle *v)
Checks whether the specs of freshly build articulated vehicles are consistent with the information sp...
Functions related to articulated vehicles.
void CheckCargoCapacity(Vehicle *v)
Check the capacity of all vehicles in a chain and spread cargo if needed.
@ BuiltAsPrototype
Vehicle is a prototype (accepted as exclusive preview).
@ DrivingBackwards
Vehicle is driving backwards.
constexpr T AssignBit(T &x, const uint8_t y, bool value)
Assigns a bit in a variable.
static constexpr uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
constexpr T SetBit(T &x, const uint8_t y)
Set a bit in a variable.
constexpr bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
constexpr T ToggleBit(T &x, const uint8_t y)
Toggles a bit in a variable.
constexpr T KillFirstBit(T value)
Clear the first bit in an integer.
constexpr T ClrBit(T &x, const uint8_t y)
Clears a bit in a variable.
const BridgeSpec * GetBridgeSpec(BridgeType i)
Get the specification of a bridge type.
bool IsBridgeTile(Tile t)
checks if there is a bridge on this tile
BridgeType GetBridgeType(Tile t)
Determines the type of bridge on a tile.
bool IsBridge(Tile t)
Checks if this is a bridge, instead of a tunnel.
bool IsValidCargoType(CargoType cargo)
Test whether cargo type is not INVALID_CARGO.
CargoType
Cargo slots to indicate a cargo type within a game.
static void NewEvent(CompanyID company, ScriptEvent *event)
Queue a new event for an AI.
constexpr bool Test(Tvalue_type value) const
Test if the value-th bit is set.
constexpr Timpl & Flip()
Flip all bits.
constexpr Timpl & Reset()
Reset all bits.
constexpr Timpl & Set()
Set all bits.
Common return value for all commands.
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?
uint32_t GetGRFID() const
Retrieve the GRF ID of the NewGRF the engine is tied to.
uint16_t reliability_spd_dec
Speed of reliability decay between services (per day).
const GRFFile * GetGRF() const
Retrieve the NewGRF the engine is tied to.
uint DetermineCapacity(const Vehicle *v, uint16_t *mail_capacity=nullptr) const
Determines capacity of a given vehicle from scratch.
EngineFlags flags
Flags of the engine.
uint8_t original_image_index
Original vehicle image index, thus the image index of the overridden vehicle.
TimerGameCalendar::Date GetLifeLengthInDays() const
Returns the vehicle's (not model's!) life length in days.
CargoType GetDefaultCargoType() const
Determines the default cargo type of an engine.
uint16_t reliability
Current reliability of the engine.
static void NewEvent(class ScriptEvent *event)
Queue a new event for the game script.
This struct contains all the info that is needed to draw and construct tracks.
uint8_t curve_speed
Multiplier for curve maximum speed advantage.
static constexpr TimerGameTick::Ticks DAY_TICKS
1 day is 74 ticks; TimerGameCalendar::date_fract used to be uint16_t and incremented by 885.
static Date date
Current date in days (day counter).
static Year year
Current year, starting at 0.
static constexpr int DAYS_IN_YEAR
static Date date
Current date in days (day counter).
This class will save the current order of a vehicle and restore it on destruction.
void Restore()
Restore the saved order to the vehicle.
~VehicleOrderSaver()
Restore the saved order to the vehicle, if Restore() has not already been called.
bool SwitchToNextOrder(bool skip_first)
Set the current vehicle order to the next order in the order list.
Iterate over all vehicles near a given world coordinate.
Iterate over all vehicles on a tile.
Functions related to commands.
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,...
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 _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
CompanyID _current_company
Company currently doing an action.
void SubtractMoneyFromCompanyFract(CompanyID company, const CommandCost &cst)
Subtract money from a company, including the money fraction.
Functions related to companies.
DepotID GetDepotIndex(Tile t)
Get the index of which depot is attached to the tile.
PoolID< uint16_t, struct DepotIDTag, 64000, 0xFFFF > DepotID
Type for the unique identifier of depots.
DirDiff DirDifference(Direction d0, Direction d1)
Calculate the difference between two directions.
Direction DiagDirToDir(DiagDirection dir)
Convert a DiagDirection to a Direction.
DiagDirection ReverseDiagDir(DiagDirection d)
Returns the reverse direction of the given DiagDirection.
DiagDirections AxisToDiagDirs(Axis a)
Converts an Axis to DiagDirections.
Direction ReverseDir(Direction d)
Return the reverse of a direction.
bool IsValidDiagDirection(DiagDirection d)
Checks if an integer value is a valid DiagDirection.
Direction ChangeDir(Direction d, DirDiff delta)
Change a direction by a given difference.
DiagDirection AxisToDiagDir(Axis a)
Converts an Axis to a DiagDirection.
bool IsDiagonalDirection(Direction dir)
Checks if a given Direction is diagonal.
Axis DiagDirToAxis(DiagDirection d)
Convert a DiagDirection to the axis.
DiagDirection DirToDiagDir(Direction dir)
Convert a Direction to a DiagDirection.
DirDiff
Enumeration for the difference between two directions.
@ Left45
Angle of 45 degrees left.
@ Left90
Angle of 90 degrees left.
@ Same
Both directions faces to the same direction.
@ Right45
Angle of 45 degrees right.
@ Right90
Angle of 90 degrees right.
EnumIndexArray< T, DiagDirection, DiagDirection::End > DiagDirectionIndexArray
Array with DiagDirection as index.
Direction
Defines the 8 directions on the map.
Axis
Enumeration for the two axis X and Y.
DiagDirection
Enumeration for diagonal directions.
@ Begin
Used for iterations.
@ Invalid
Flag for an invalid DiagDirection.
EnumBitSet< DiagDirection, uint8_t > DiagDirections
Bitset of DiagDirection elements.
Money GetPrice(Price index, uint cost_factor, const GRFFile *grf_file, int shift)
Determine a certain price.
@ TrainRun
Running costs trains.
@ NewVehicles
New vehicles.
@ Invalid
Invalid base price.
EffectVehicle * CreateEffectVehicleRel(const Vehicle *v, int x, int y, int z, EffectVehicleType type)
Create an effect vehicle above a particular vehicle.
Functions related to effect vehicles.
@ EV_EXPLOSION_SMALL
Various explosions.
@ EV_EXPLOSION_LARGE
Various explosions.
@ RailFlips
Rail vehicle has old depot-flip handling.
@ RailTilts
Rail vehicle tilts in curves.
@ VE_DISABLE_WAGON_POWER
Flag to disable wagon power.
PoolID< uint16_t, struct EngineIDTag, 64000, 0xFFFF > EngineID
Unique identification number of an engine.
@ ExclusivePreview
This vehicle is in the exclusive preview stage, either being used or being offered to a company.
@ Multihead
indicates a combination of two locomotives
@ Wagon
simple wagon, not motorized
constexpr std::underlying_type_t< enum_type > to_underlying(enum_type e)
Implementation of std::to_underlying (from C++23).
Functions related to errors.
@ Critical
Critical errors, the MessageBox is shown in all cases.
void ShowErrorMessage(EncodedString &&summary_msg, int x, int y, CommandCost &cc)
Display an error message in a window.
Error reporting related functions.
fluid_settings_t * settings
FluidSynth settings handle.
Types for recording game performance data.
@ PFE_GL_TRAINS
Time spent processing trains.
Base functions for all Games.
uint32_t SpriteID
The number of a sprite, without mapping bits and colourtables.
uint32_t PaletteID
The number of the palette.
@ AS_BRAKE
We want to stop.
@ GVF_SUPPRESS_IMPLICIT_ORDERS
Disable insertion and removal of automatic orders until the vehicle completes the real order.
@ GVF_GOINGDOWN_BIT
Vehicle is currently going downhill. (Cached track information for acceleration).
@ GVF_GOINGUP_BIT
Vehicle is currently going uphill. (Cached track information for acceleration).
void UpdateTrainGroupID(Train *v)
Recalculates the groupID of a train.
void SetTrainGroupID(Train *v, GroupID grp)
Affect the groupID of a train to new_g.
void MarkTileDirtyByTile(TileIndex tile, int bridge_level_offset, int tile_height_override)
Mark a tile given by its index dirty for repaint.
static constexpr GroupID DEFAULT_GROUP
Ungrouped vehicles are in this group.
TrackStatus GetTileTrackStatus(TileIndex tile, TransportType mode, RoadTramType sub_mode, DiagDirection side)
Returns information about trackdirs and signal states.
int GetSlopePixelZ(int x, int y, bool ground_vehicle)
Return world Z coordinate of a given point of a tile.
#define Rect
Macro that prevents name conflicts between included headers.
#define Point
Macro that prevents name conflicts between included headers.
DiagDirection DiagdirBetweenTiles(TileIndex tile_from, TileIndex tile_to)
Determines the DiagDirection to get from one tile to another.
static TileIndex TileVirtXY(uint x, uint y)
Get a tile from the virtual XY-coordinate.
TileIndex TileAddByDiagDir(TileIndex tile, DiagDirection dir)
Adds a DiagDir to a tile.
TileIndexDiff TileOffsByAxis(Axis axis)
Convert an Axis to a TileIndexDiff.
static uint TileY(TileIndex tile)
Get the Y component of a tile.
static uint TileX(TileIndex tile)
Get the X component of a tile.
TileIndexDiff TileOffsByDiagDir(DiagDirection dir)
Convert a DiagDirection to a TileIndexDiff.
int32_t TileIndexDiff
An offset value between two tiles.
constexpr T abs(const T a)
Returns the absolute value of (scalar) variable.
constexpr uint CeilDiv(uint a, uint b)
Computes ceil(a / b) for non-negative a and b.
constexpr T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Miscellaneous command definitions.
void HideFillingPercent(TextEffectID *te_id)
Hide vehicle loading indicators.
bool _networking
are we in networking mode?
Basic functions/variables used all over the place.
ClientID
'Unique' identifier to be given to clients
Base for the NewGRF implementation.
@ ArticEngine
Add articulated engines (trains and road vehicles).
@ Length
Vehicle length (trains and road vehicles).
@ CBID_VEHICLE_LENGTH
Vehicle length, returns the amount of 1/8's the vehicle is shorter for trains and RVs.
@ CBID_TRAIN_ALLOW_WAGON_ATTACH
Determine whether a wagon can be attached to an already existing train.
static const uint CALLBACK_FAILED
Different values for Callback result evaluations.
void ErrorUnknownCallbackResult(uint32_t grfid, uint16_t cbid, uint16_t cb_res)
Record that a NewGRF returned an unknown/invalid callback result.
@ VehCapacity
Capacity of vehicle changes when not refitting or arranging.
Functions/types related to NewGRF debugging.
void InvalidateNewGRFInspectWindow(GrfSpecFeature feature, uint index)
Invalidate the inspect window for a given feature and index.
void DeleteNewGRFInspectWindow(GrfSpecFeature feature, uint index)
Delete inspect window for a given feature and index.
uint16_t GetVehicleCallbackParent(CallbackID callback, uint32_t param1, uint32_t param2, EngineID engine, const Vehicle *v, const Vehicle *parent, std::span< int32_t > regs100)
Evaluate a newgrf callback for vehicles with a different vehicle for parent scope.
bool UsesWagonOverride(const Vehicle *v)
Check if a wagon is currently using a wagon override.
uint16_t GetVehicleCallback(CallbackID callback, uint32_t param1, uint32_t param2, EngineID engine, const Vehicle *v, std::span< int32_t > regs100)
Evaluate a newgrf callback for vehicles.
std::optional< bool > TestVehicleBuildProbability(Vehicle *v, BuildProbabilityType type)
Test for vehicle build probability type.
@ Reversed
Change the rail vehicle should be reversed when purchased.
@ PROP_TRAIN_SHORTEN_FACTOR
Shorter vehicles.
@ PROP_TRAIN_USER_DATA
User defined data for vehicle variable 0x42.
@ PROP_TRAIN_WEIGHT
Weight in t (if dualheaded: for each single vehicle).
@ PROP_TRAIN_CARGO_AGE_PERIOD
Number of ticks before carried cargo is aged.
@ PROP_TRAIN_RUNNING_COST_FACTOR
Yearly runningcost (if dualheaded: sum of both vehicles).
@ PROP_TRAIN_SPEED
Max. speed: 1 unit = 1/1.6 mph = 1 km-ish/h.
bool PlayVehicleSound(const Vehicle *v, VehicleSoundEvent event, bool force)
Checks whether a NewGRF wants to play a different vehicle sound effect.
Functions related to NewGRF provided sounds.
@ VSE_START
Vehicle starting, i.e. leaving, the station.
void TriggerStationRandomisation(BaseStation *st, TileIndex trigger_tile, StationRandomTrigger trigger, CargoType cargo_type)
Trigger station randomisation.
Header file for NewGRF stations.
StringID GetGRFStringID(uint32_t grfid, GRFStringID stringid)
Returns the index for this stringid associated with its grfID.
Header of Action 04 "universal holder" structure and functions.
StrongType::Typedef< uint32_t, struct GRFStringIDTag, StrongType::Compare, StrongType::Integer > GRFStringID
Type for GRF-internal string IDs.
static constexpr GRFStringID GRFSTR_MISC_GRF_TEXT
Miscellaneous GRF text range.
Functions related to news.
void AddVehicleNewsItem(EncodedString &&headline, NewsType type, VehicleID vehicle, StationID station=StationID::Invalid())
Adds a newsitem referencing a vehicle.
void AddVehicleAdviceNewsItem(AdviceType advice_type, EncodedString &&headline, VehicleID vehicle)
Adds a vehicle-advice news item.
@ ArrivalCompany
First vehicle arrived for company.
@ ArrivalOther
First vehicle arrived for competitor.
@ Accident
An accident or disaster has occurred.
@ TrainStuck
The train got stuck and needs to be unstuck manually.
@ Error
A game paused because a (critical) error.
Functions related to order backups.
bool ProcessOrders(Vehicle *v)
Handle the orders of a vehicle and determine the next place to go to if needed.
bool UpdateOrderDest(Vehicle *v, const Order *order, int conditional_depth, bool pbs_look_ahead)
Update the vehicle's destination tile from an order.
void CheckOrders(const Vehicle *v)
Check the orders of a vehicle, to see if there are invalid orders and stuff.
void DeleteVehicleOrders(Vehicle *v, bool keep_orderlist, bool reset_order_indices)
Delete all orders from a vehicle.
VehicleOrderID ProcessConditionalOrder(const Order *order, const Vehicle *v)
Process a conditional order and determine the next order.
OrderStopLocation
Where to stop the trains.
@ NearEnd
Stop at the near end of the platform.
@ FarEnd
Stop at the far end of the platform.
@ Middle
Stop at the middle of the platform.
@ NonStop
The vehicle will not stop at any stations it passes except the destination, aka non-stop.
@ GoVia
The vehicle will stop at any station it passes except the destination, aka via.
uint8_t VehicleOrderID
The index of an order within its current vehicle (not pool related).
@ NearestDepot
Send the vehicle to the nearest depot.
@ Service
This depot order is because of the servicing limit.
static const VehicleOrderID INVALID_VEH_ORDER_ID
Invalid vehicle order index (sentinel).
void SetRailStationPlatformReservation(TileIndex start, DiagDirection dir, bool b)
Set the reservation for a complete station platform.
TrackBits GetReservedTrackbits(TileIndex t)
Get the reserved trackbits for any tile, regardless of type.
bool TryReserveRailTrack(TileIndex tile, Track t, bool trigger_stations)
Try to reserve a specific track on a tile.
bool IsWaitingPositionFree(const Train *v, TileIndex tile, Trackdir trackdir, bool forbid_90deg)
Check if a safe position is free.
void UnreserveRailTrack(TileIndex tile, Track t)
Lift the reservation of a specific track on a tile.
PBSTileInfo FollowTrainReservation(const Train *consist, Vehicle **train_on_res)
Follow a train reservation to the last tile.
bool IsSafeWaitingPosition(const Train *v, TileIndex tile, Trackdir trackdir, bool include_line_end, bool forbid_90deg)
Determine whether a certain track on a tile is a safe position to end a path.
bool HasReservedTracks(TileIndex tile, TrackBits tracks)
Check whether some of tracks is reserved on a tile.
RailType GetTileRailType(Tile tile)
Return the rail type of tile, or INVALID_RAILTYPE if this is no rail tile.
int TicksToLeaveDepot(const Train *v)
Compute number of ticks when next wagon will leave a depot.
RailTypes GetAllPoweredRailTypes(RailTypes railtypes)
Returns all powered railtypes for a set of railtypes.
bool IsCompatibleRail(RailType enginetype, RailType tiletype)
Checks if an engine of the given RailType can drive on a tile with a given RailType.
bool HasPowerOnRail(RailType enginetype, RailType tiletype)
Checks if an engine of the given RailType got power on a tile with a given RailType.
bool Rail90DegTurnDisallowed(RailType rt1, RailType rt2, bool def=_settings_game.pf.forbid_90_deg)
Test if 90 degree turns are disallowed between two railtypes.
const RailTypeInfo * GetRailTypeInfo(RailType railtype)
Returns a pointer to the Railtype information for a given railtype.
RailTypes GetAllCompatibleRailTypes(RailTypes railtypes)
Returns all compatible railtypes for a set of railtypes.
std::vector< Train * > TrainList
Helper type for lists/vectors of trains.
bool HasOnewaySignalBlockingTrackdir(Tile tile, Trackdir td)
Is a one-way signal blocking the trackdir?
static RailTileType GetRailTileType(Tile t)
Returns the RailTileType (normal with or without signals, waypoint or depot).
static bool IsPlainRail(Tile t)
Returns whether this is plain rails, with or without signals.
RailType GetRailType(Tile t)
Gets the rail type of the given tile.
bool HasSignalOnTrackdir(Tile tile, Trackdir trackdir)
Checks for the presence of signals along the given trackdir on the given rail tile.
TrackBits GetTrackBits(Tile tile)
Gets the track bits of the given tile.
static bool IsPlainRailTile(Tile t)
Checks whether the tile is a rail tile or rail tile with signals.
bool IsPbsSignal(SignalType s)
Checks whether the given signal is a path based signal.
@ Signals
Normal rail tile with signals.
Track GetRailDepotTrack(Tile t)
Returns the track of a depot, ignoring direction.
DiagDirection GetRailDepotDirection(Tile t)
Returns the direction the depot is facing to.
void SetSignalStateByTrackdir(Tile tile, Trackdir trackdir, SignalState state)
Sets the state of the signal along the given trackdir.
bool HasSignalOnTrack(Tile tile, Track track)
Checks for the presence of signals (either way) on the given track on the given rail tile.
bool HasPbsSignalOnTrackdir(Tile tile, Trackdir td)
Is a pbs signal present along the trackdir?
bool IsOnewaySignal(Tile t, Track track)
Is the signal at the given track on a tile a one way signal?
SignalType GetSignalType(Tile t, Track track)
Get the signal type for a track on a tile.
void SetDepotReservation(Tile t, bool b)
Set the reservation state of the depot.
bool HasDepotReservation(Tile t)
Get the reservation state of the depot.
bool HasSignals(Tile t)
Checks if a rail tile has signals.
SignalState GetSignalStateByTrackdir(Tile tile, Trackdir trackdir)
Gets the state of the signal along the given trackdir.
static bool IsRailDepotTile(Tile t)
Is this tile rail tile and a rail depot?
bool HasBlockSignalOnTrackdir(Tile tile, Trackdir td)
Check whether a block signal is present along the trackdir.
@ RAILTYPE_RAIL
Standard non-electric rails.
Pseudo random number generator.
bool Chance16(const uint32_t a, const uint32_t b, const std::source_location location=std::source_location::current())
Flips a coin with given probability.
bool Chance16R(const uint32_t a, const uint32_t b, uint32_t &r, const std::source_location location=std::source_location::current())
Flips a coin with a given probability and saves the randomize-number in a variable.
void UpdateLevelCrossing(TileIndex tile, bool sound=true, bool force_bar=false)
Update a level crossing to barred or open (crossing may include multiple adjacent tiles).
bool HasCrossingReservation(Tile t)
Get the reservation state of the rail crossing.
bool IsLevelCrossingTile(Tile t)
Return whether a tile is a level crossing tile.
Axis GetCrossingRoadAxis(Tile t)
Get the road axis of a level crossing.
void SetCrossingBarred(Tile t, bool barred)
Set the bar state of a level crossing.
Axis GetCrossingRailAxis(Tile t)
Get the rail axis of a level crossing.
bool IsCrossingBarred(Tile t)
Check if the level crossing is barred.
void SetCrossingReservation(Tile t, bool b)
Set the reservation state of the rail crossing.
A number of safeguards to prevent using unsafe methods.
GameSettings _settings_game
Game settings of a running game or the scenario editor.
ClientSettings _settings_client
The current settings for this game.
@ EndOfLineOnly
Trains can only flip when the track ends.
@ None
Trains cannot flip anywhere and must back up if the track ends.
SigSegState UpdateSignalsOnSegment(TileIndex tile, DiagDirection side, Owner owner)
Update signals, starting at one side of a tile Will check tile next to this at opposite side too.
void UpdateSignalsInBuffer()
Update signals in buffer Called from 'outside'.
void AddSideToSignalBuffer(TileIndex tile, DiagDirection side, Owner owner)
Add side of tile to signal update buffer.
void SetSignalsOnBothDir(TileIndex tile, Track track, Owner owner)
Update signals at segments that are at both ends of given (existent or non-existent) track.
SigSegState
State of the signal segment.
@ SIGSEG_PBS
Segment is a PBS segment.
@ SIGSEG_FULL
Occupied by a train.
@ SIGTYPE_PBS
normal pbs signal
@ SIGNAL_STATE_RED
The signal is red.
@ SIGNAL_STATE_GREEN
The signal is green.
Functions related to sound.
SoundFx
Sound effects from baseset.
@ SND_04_DEPARTURE_STEAM
2 == 0x02 Station departure: steam engine
@ SND_41_DEPARTURE_MAGLEV
65 == 0x41 Station departure: maglev engine
@ SND_13_TRAIN_COLLISION
15 == 0x11 Train+train crash
@ SND_0E_LEVEL_CROSSING
12 == 0x0C Train passes through level crossing
@ SND_0A_DEPARTURE_TRAIN
8 == 0x08 Station departure: diesel and electric engine
@ SND_47_DEPARTURE_MONORAIL
71 == 0x47 Station departure: monorail engine
static const PaletteID PALETTE_CRASH
Recolour sprite greying of crashed vehicles.
void ModifyStationRatingAround(TileIndex tile, Owner owner, int amount, uint radius)
Forcibly modify station ratings near a given tile.
bool IsRailWaypointTile(Tile t)
Is this tile a station tile and a rail waypoint?
bool IsCompatibleTrainStationTile(Tile test_tile, Tile station_tile)
Check if a tile is a valid continuation to a railstation tile.
bool IsRailStationTile(Tile t)
Is this tile a station tile and a rail station?
StationID GetStationIndex(Tile t)
Get StationID from a tile.
Axis GetRailStationAxis(Tile t)
Get the rail direction of a rail station.
@ HVOT_TRAIN
Station has seen a train.
@ Train
Station with train station.
@ VehicleArrives
Trigger platform when train arrives.
@ VehicleArrives
Trigger platform when train arrives.
Definition of base types and functions in a cross-platform compatible way.
#define lengthof(array)
Return the length of an fixed size array.
EncodedString GetEncodedString(StringID str)
Encode a string with no parameters into an encoded string.
Functions related to OTTD's strings.
uint32_t StringID
Numeric value that represents a string, independent of the selected language.
Data structure for storing engine speed changes of an acceleration type.
uint8_t large_turn
Speed change due to a large turn.
uint8_t z_up
Fraction to remove when moving up.
uint8_t small_turn
Speed change due to a small turn.
uint8_t z_down
Fraction to add when moving down.
std::string name
Name of vehicle.
TimerGameTick::Ticks current_order_time
How many ticks have passed since this order started.
VehicleOrderID cur_real_order_index
The index to the current real (non-implicit) order.
VehicleFlags vehicle_flags
Used for gradual loading and other miscellaneous things (.
void ResetDepotUnbunching()
Resets all the data used for depot unbunching.
TileIndex xy
Base tile of the station.
StationFacilities facilities
The facilities that this station has.
TileArea train_station
Tile area the train 'station' part covers.
VehicleType type
Type of vehicle.
uint16_t speed
maximum travel speed (1 unit = 1/1.6 mph = 1 km-ish/h)
bool Follow(TileIndex old_tile, Trackdir old_td)
Main follower routine.
bool is_tunnel
last turn passed tunnel
bool is_bridge
last turn passed bridge ramp
int tiles_skipped
number of skipped tunnel or station tiles
DiagDirection exitdir
exit direction (leaving the old tile)
TrackdirBits new_td_bits
the new set of available trackdirs
TileIndex new_tile
the new tile (the vehicle has entered)
Trackdir old_td
the trackdir (the vehicle was on) before move
bool is_station
last turn passed station
TileIndex old_tile
the origin (vehicle moved from) before move
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo type.
Structure to return information about the closest depot location, and whether it could be found.
uint16_t cargo_age_period
Number of ticks before carried cargo is aged.
EngineMiscFlags misc_flags
Miscellaneous flags.
VehicleCallbackMasks callback_mask
Bitmask of vehicle callbacks that have to be called.
Helper container to find a depot.
uint best_length
The distance towards the depot in penalty, or UINT_MAX if not found.
bool reverse
True if reversing is necessary for the train to get to this depot.
TileIndex tile
The tile of the depot.
Dynamic data of a loaded NewGRF.
uint traininfo_vehicle_width
Width (in pixels) of a 8/8 train vehicle in depot GUI and vehicle details.
int traininfo_vehicle_pitch
Vertical offset for drawing train images in depot GUI and vehicle details.
Position information of a vehicle after it moved.
TileIndex new_tile
Tile of the vehicle after moving.
int y
x and y position of the vehicle after moving
TileIndex old_tile
Current tile of the vehicle.
EngineID first_engine
Cached EngineID of the front vehicle. EngineID::Invalid() for the front vehicle itself.
uint32_t cached_power
Total power of the consist (valid only for the first engine).
uint16_t cached_total_length
Length of the whole vehicle (valid only for the first engine).
uint8_t cached_veh_length
Length of this vehicle in units of 1/VEHICLE_LENGTH of normal length. It is cached because this can b...
bool IsChainInDepot() const override
Check whether the whole vehicle chain is in the depot.
void SetFreeWagon()
Set a vehicle as a free wagon.
int UpdateInclination(bool new_tile, bool update_delta)
Checks if the vehicle is in a slope and sets the required flags in that case.
bool CanLeadTrain() const
Check if this vehicle can lead a train.
GroundVehicleCache gcache
void SetMultiheaded()
Set a vehicle as a multiheaded engine.
bool IsEngine() const
Check if a vehicle is an engine (can be first in a consist).
bool IsRearDualheaded() const
Tell if we are dealing with the rear end of a multiheaded engine.
bool IsMultiheaded() const
Check if the vehicle is a multiheaded engine.
void SetEngine()
Set engine status.
void SetWagon()
Set a vehicle to be a wagon.
void SetFrontEngine()
Set front engine state.
void ClearFreeWagon()
Clear a vehicle from being a free wagon.
bool IsWagon() const
Check if a vehicle is a wagon.
uint Crash(bool flooded) override
Common code executed for crashed ground vehicles.
uint DoUpdateSpeed(uint accel, int min_speed, int max_speed)
int GetAcceleration() const
void ClearFrontEngine()
Remove the front engine state.
void SetLastSpeed()
Update the GUI variant of the current speed of the vehicle.
static void CountVehicle(const Vehicle *v, int delta)
Update num_vehicle when adding or removing a vehicle.
static uint Size()
Get the size of the map.
VehicleSpriteSeq sprite_seq
Vehicle appearance.
static void Backup(const Vehicle *v, uint32_t user)
Create an order backup for the given vehicle.
If you change this, keep in mind that it is also saved in 2 other places:
OrderDepotTypeFlags GetDepotOrderType() const
What caused us going to the depot?
DestinationID GetDestination() const
Gets the destination of this order.
bool IsType(OrderType type) const
Check whether this order is of the given type.
OrderStopLocation GetStopLocation() const
Where must we stop at the platform?
OrderType GetType() const
Get the type of order of this order.
void MakeDummy()
Makes this order a Dummy order.
void SetDestination(DestinationID destination)
Sets the destination of this order.
OrderDepotActionFlags GetDepotActionType() const
What are we going to do when in the depot.
void Free()
'Free' the order
bool ShouldStopAtStation(const Vehicle *v, StationID station) const
Check whether the given vehicle should stop at the given station based on this order and the non-stop...
void MakeGoToDepot(DestinationID destination, OrderDepotTypeFlags order, OrderNonStopFlags non_stop_type=OrderNonStopFlag::NonStop, OrderDepotActionFlags action={}, CargoType cargo=CARGO_NO_REFIT)
Makes this order a Go To Depot order.
OrderNonStopFlags GetNonStopType() const
At which stations must we stop?
TileIndex tile
The base tile of the area.
This struct contains information about the end of a reserved path.
Trackdir trackdir
The reserved trackdir on the tile.
TileIndex tile
Tile the path ends, INVALID_TILE if no valid path was found.
bool okay
True if tile is a safe waiting position, false otherwise.
static Pool::IterateWrapper< Vehicle > Iterate(size_t from=0)
static Engine * Get(auto index)
static bool CanAllocateItem(size_t n=1)
static T * Create(Targs &&... args)
static Vehicle * GetIfValid(auto index)
Information about a rail vehicle.
uint16_t power
Power of engine (hp); For multiheaded engines the sum of both engine powers.
uint8_t user_def_data
Property 0x25: "User-defined bit mask" Used only for (very few) NewGRF vehicles.
uint8_t running_cost
Running cost of engine; For multiheaded engines the sum of both running costs.
uint8_t shorten_factor
length on main map for this type is 8 - shorten_factor
RailTypes railtypes
Railtypes, mangled if elrail is disabled.
uint16_t pow_wag_power
Extra power applied to consist if wagon should be powered.
uint16_t max_speed
Maximum speed (1 unit = 1/1.6 mph = 1 km-ish/h).
RailVehicleType railveh_type
Type of rail vehicle.
uint8_t capacity
Cargo capacity of vehicle; For multiheaded engines the capacity of each single engine.
int Width() const
Get width of Rect.
int Height() const
Get height of Rect.
static Station * Get(auto index)
T * GetMovingFront() const
Get the moving front of the vehicle chain.
T * GetMovingPrev() const
Get the previous vehicle in the vehicle chain, relative to its current movement.
T * Next() const
Get next vehicle in the chain.
T * Previous() const
Get previous vehicle in the chain.
static Train * From(Vehicle *v)
T * First() const
Get the first vehicle in the chain.
T * GetNextVehicle() const
Get the next real (non-articulated part) vehicle in the consist.
void UpdateViewport(bool force_update, bool update_delta)
Update vehicle sprite- and position caches.
T * GetMovingNext() const
Get the next vehicle in the vehicle chain, relative to its current movement.
T * GetLastEnginePart()
Get the last part of an articulated engine.
T * GetFirstEnginePart()
Get the first part of an articulated engine.
T * Last()
Get the last vehicle in the chain.
T * GetMovingBack() const
Get the moving back of the vehicle chain.
uint GetPlatformLength(TileIndex tile, DiagDirection dir) const override
Determines the REMAINING length of a platform, starting at (and including) the given tile.
TrackdirBits signals
Red signals on the tile.
TrackdirBits trackdirs
Trackdirs present on the tile.
uint16_t cached_max_curve_speed
max consist speed limited by curves
'Train' is either a loco or a wagon.
void PlayLeaveStationSound(bool force=false) const override
Play the sound associated with leaving the station.
void UpdateAcceleration()
Update acceleration of the train from the cached power and weight.
void OnNewCalendarDay() override
Calendar day handler.
Train * GetNextUnit() const
Get the next real (non-articulated part and non rear part of dualheaded engine) vehicle in the consis...
Trackdir GetVehicleTrackdir() const override
Get the tracks of the train vehicle.
void GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const override
Get the sprite to display the train.
Train * other_multiheaded_part
Link between the two ends of a multiheaded engine.
RailTypes railtypes
On which rail types the train can run.
uint16_t crash_anim_pos
Crash animation counter.
bool Tick() override
Update train vehicle data for a tick.
void ReserveTrackUnderConsist() const
Tries to reserve track under whole train consist.
TileIndex GetOrderStationLocation(StationID station) override
Get the location of the next station to visit.
TrainForceProceeding force_proceed
How the train should behave when it encounters next obstacle.
int GetDisplayImageWidth(Point *offset=nullptr) const
Get the width of a train vehicle image in the GUI.
ClosestDepot FindClosestDepot() override
Find the closest depot for this vehicle and tell us the location, DestinationID and whether we should...
TrackBits track
On which track the train currently is.
void UpdateDeltaXY() override
Updates the x and y offsets and the size of the sprite used for this vehicle.
VehicleRailFlags flags
Which flags has this train currently set.
int CalcNextVehicleOffset() const
Calculate the offset from this vehicle's center to the following center taking the vehicle lengths in...
uint16_t GetMaxWeight() const override
Calculates the weight value that this vehicle will have when fully loaded with its current cargo.
uint16_t GetCurveSpeedLimit() const
Computes train speed limit caused by curves.
bool IsPrimaryVehicle() const override
Whether this is the primary vehicle in the chain.
void MarkDirty() override
Goods at the consist have changed, update the graphics, cargo, and acceleration.
int UpdateSpeed()
This function looks at the vehicle and updates its speed (cur_speed and subspeed) variables.
uint Crash(bool flooded=false) override
The train vehicle crashed!
VehicleAccelerationModel GetAccelerationType() const
Allows to know the acceleration type of a vehicle.
Train(VehicleID index)
Create new Train object.
AccelStatus GetAccelerationStatus() const
Checks the current acceleration status of this vehicle.
TrainCache tcache
Set of cached variables, recalculated on load and each time a vehicle is added to/removed from the co...
void OnNewEconomyDay() override
Economy day handler.
int GetCursorImageOffset() const
Get the offset for train image when it is used as cursor.
void ConsistChanged(ConsistChangeFlags allowed_changes)
Recalculates the cached stuff of a train.
Money GetRunningCost() const override
Get running cost for the train consist.
RailTypes compatible_railtypes
With which rail types the train is compatible.
uint16_t wait_counter
Ticks waiting in front of a signal, ticks being stuck or a counter for forced proceeding through sign...
int GetCurrentMaxSpeed() const override
Calculates the maximum speed of the vehicle under its current conditions.
Sprite sequence for a vehicle part.
bool IsValid() const
Check whether the sequence contains any sprites.
void GetBounds(Rect *bounds) const
Determine shared bounds of all sprites.
void Set(SpriteID sprite)
Assign a single sprite to the sequence.
void Draw(int x, int y, PaletteID default_pal, bool force_pal) const
Draw the sprite sequence.
EngineID engine_type
The type of engine used for this vehicle.
int32_t z_pos
z coordinate.
Direction direction
facing
const Engine * GetEngine() const
Retrieves the engine of the vehicle.
Direction GetMovingDirection() const
Get the moving direction of this vehicle chain.
void IncrementRealOrderIndex()
Advanced cur_real_order_index to the next real order, keeps care of the wrap-around and invalidates t...
bool IsStoppedInDepot() const
Check whether the vehicle is in the depot and stopped.
bool IsMovingFront() const
Is this vehicle the moving front of the vehicle chain?
Order * GetOrder(int index) const
Returns order 'index' of a vehicle or nullptr when it doesn't exists.
void LeaveStation()
Perform all actions when leaving a station.
void AddToShared(Vehicle *shared_chain)
Adds this vehicle to a shared vehicle chain.
VehicleCargoList cargo
The cargo this vehicle is carrying.
TimerGameEconomy::Date date_of_last_service
Last economy date the vehicle had a service at a depot.
uint16_t cargo_cap
total capacity
StationID last_loading_station
Last station the vehicle has stopped at and could possibly leave from with any cargo loaded.
VehicleOrderID GetNumOrders() const
Get the number of orders this vehicle has.
void SetMovingDirection(Direction d)
Set the movement direction of this vehicle chain.
uint16_t random_bits
Bits used for randomized variational spritegroups.
void ReleaseUnitNumber()
Release the vehicle's unit number.
uint8_t day_counter
Increased by one for each day.
void HandleLoading(bool mode=false)
Handle the loading of the vehicle; when not it skips through dummy orders and does nothing in all oth...
Money profit_this_year
Profit this year << 8, low 8 bits are fract.
SpriteID colourmap
NOSAVE: cached colour mapping.
uint8_t breakdown_ctr
Counter for managing breakdown events.
uint GetAdvanceDistance()
Determines the vehicle "progress" needed for moving a step.
GroupID group_id
Index of group Pool array.
VehStates vehstatus
Status.
TimerGameCalendar::Date date_of_last_service_newgrf
Last calendar date the vehicle had a service at a depot, unchanged by the date cheat to protect again...
uint8_t subspeed
fractional speed
bool IsArticulatedPart() const
Check if the vehicle is an articulated part of an engine.
void LeaveUnbunchingDepot()
Leave an unbunching depot and calculate the next departure time for shared order vehicles.
CargoType cargo_type
type of cargo this vehicle is carrying
uint8_t acceleration
used by train & aircraft
Vehicle * First() const
Get the first vehicle of this vehicle chain.
Order current_order
The current order (+ status, like: loading).
void HandlePathfindingResult(bool path_found)
Handle the pathfinding result, especially the lost status.
Vehicle * Next() const
Get the next vehicle of this vehicle.
int32_t y_pos
y coordinate.
int32_t x_pos
x coordinate.
const GRFFile * GetGRF() const
Retrieve the NewGRF the vehicle is tied to.
OrderList * orders
Pointer to the order list for this vehicle.
Money value
Value of the vehicle.
uint16_t refit_cap
Capacity left over from before last refit.
void InvalidateNewGRFCache()
Invalidates cached NewGRF variables.
VehicleCache vcache
Cache of often used vehicle values.
uint32_t GetGRFID() const
Retrieve the GRF ID of the NewGRF the vehicle is tied to.
SpriteBounds bounds
Bounding box of vehicle.
void BeginLoading()
Prepare everything to begin the loading when arriving at a station.
uint8_t spritenum
currently displayed sprite index 0xfd == custom sprite, 0xfe == custom second head sprite 0xff == res...
uint16_t cur_speed
current speed
uint8_t cargo_subtype
Used for livery refits (NewGRF variations).
bool IsFrontEngine() const
Check if the vehicle is a front engine.
bool IsWaitingForUnbunching() const
Check whether a vehicle inside a depot is waiting for unbunching.
TextEffectID fill_percent_te_id
a text-effect id to a loading indicator object
void SetNext(Vehicle *next)
Set the next vehicle of this vehicle.
TimerGameCalendar::Date max_age
Maximum age.
MutableSpriteCache sprite_cache
Cache of sprites and values related to recalculating them, see MutableSpriteCache.
uint16_t reliability
Reliability.
bool HandleBreakdown()
Handle all of the aspects of a vehicle breakdown This includes adding smoke and sounds,...
uint8_t progress
The percentage (if divided by 256) this vehicle already crossed the tile unit.
uint16_t reliability_spd_dec
Reliability decrease speed.
uint8_t tick_counter
Increased by one for each tick.
TileIndex tile
Current tile index.
TileIndex dest_tile
Heading for this tile.
void CopyVehicleConfigAndStatistics(Vehicle *src)
Copy certain configurations and statistics of a vehicle after successful autoreplace/renew The functi...
void UpdatePosition()
Update the position of the vehicle.
StationID last_station_visited
The last station we stopped at.
bool IsDrivingBackwards() const
Is this vehicle moving backwards?
void ShowVisualEffect() const
Draw visual effects (smoke and/or sparks) for a vehicle chain.
TimerGameCalendar::Year build_year
Year the vehicle has been built.
Owner owner
Which company owns the vehicle?
UnitID unitnumber
unit number, for display purposes only
bool NeedsAutomaticServicing() const
Checks if the current order should be interrupted for a service-in-depot order.
uint8_t running_ticks
Number of ticks this vehicle was not stopped this day.
@ EnteredStation
The vehicle entered a station.
@ CannotEnter
The vehicle cannot enter the tile.
@ EnteredWormhole
The vehicle either entered a bridge, tunnel or depot tile (this includes the last tile of the bridge/...
VehicleEnterTileStates VehicleEnterTile(Vehicle *v, TileIndex tile, int x, int y)
Call the tile callback function for a vehicle entering a tile.
static bool IsTileType(Tile tile, TileType type)
Checks if a tile is a given tiletype.
bool IsTileOwner(Tile tile, Owner owner)
Checks if a tile belongs to the given owner.
Owner GetTileOwner(Tile tile)
Returns the owner of a tile.
StrongType::Typedef< uint32_t, struct TileIndexTag, StrongType::Compare, StrongType::Integer, StrongType::Compatible< int32_t >, StrongType::Compatible< int64_t > > TileIndex
The index/ID of a Tile.
constexpr TileIndex INVALID_TILE
The very nice invalid tile marker.
static constexpr uint TILE_SIZE
Tile size in world coordinates.
@ TunnelBridge
Tunnel entry/exit and bridge heads.
@ Station
A tile of a station or airport.
@ Railway
A tile with railway.
Definition of the game-calendar-timer.
Definition of the game-economy-timer.
Trackdir RemoveFirstTrackdir(TrackdirBits *trackdirs)
Removes first Trackdir from TrackdirBits and returns it.
Track TrackdirToTrack(Trackdir trackdir)
Returns the Track that a given Trackdir represents.
TrackBits TrackToTrackBits(Track track)
Maps a Track to the corresponding TrackBits value.
TrackdirBits TrackBitsToTrackdirBits(TrackBits bits)
Converts TrackBits to TrackdirBits while allowing both directions.
DiagDirection VehicleExitDir(Direction direction, TrackBits track)
Determine the side in which the vehicle will leave the tile.
Track TrackBitsToTrack(TrackBits tracks)
Converts TrackBits to Track.
TrackBits TrackCrossesTracks(Track track)
Maps a track to all tracks that make 90 deg turns with it.
Trackdir ReverseTrackdir(Trackdir trackdir)
Maps a trackdir to the reverse trackdir.
bool TracksOverlap(TrackBits bits)
Checks if the given tracks overlap, ie form a crossing.
Trackdir TrackDirectionToTrackdir(Track track, Direction dir)
Maps a track and a full (8-way) direction to the trackdir that represents the track running in the gi...
TrackBits AxisToTrackBits(Axis a)
Maps an Axis to the corresponding TrackBits value.
bool IsValidTrackdir(Trackdir trackdir)
Checks if a Trackdir is valid for non-road vehicles.
Trackdir FindFirstTrackdir(TrackdirBits trackdirs)
Returns first Trackdir from TrackdirBits or INVALID_TRACKDIR.
TrackdirBits TrackdirCrossesTrackdirs(Trackdir trackdir)
Maps a trackdir to all trackdirs that make 90 deg turns with it.
TrackdirBits TrackdirReachesTrackdirs(Trackdir trackdir)
Maps a trackdir to the trackdirs that can be reached from it (ie, when entering the next tile.
TrackdirBits DiagdirReachesTrackdirs(DiagDirection diagdir)
Returns all trackdirs that can be reached when entering a tile from a given (diagonal) direction.
Track FindFirstTrack(TrackBits tracks)
Returns first Track from TrackBits or INVALID_TRACK.
Trackdir TrackEnterdirToTrackdir(Track track, DiagDirection diagdir)
Maps a track and an (4-way) dir to the trackdir that represents the track with the entry in the given...
TrackBits DiagdirReachesTracks(DiagDirection diagdir)
Returns all tracks that can be reached when entering a tile from a given (diagonal) direction.
TrackBits DiagDirToDiagTrackBits(DiagDirection diagdir)
Maps a DiagDirection to the associated diagonal TrackBits.
Trackdir DiagDirToDiagTrackdir(DiagDirection diagdir)
Maps a (4-way) direction to the diagonal trackdir that runs in that direction.
DiagDirection TrackdirToExitdir(Trackdir trackdir)
Maps a trackdir to the (4-way) direction the tile is exited when following that trackdir.
Track DiagDirToDiagTrack(DiagDirection diagdir)
Maps a DiagDirection to the associated diagonal Track.
TrackBits TrackdirBitsToTrackBits(TrackdirBits bits)
Discards all directional information from a TrackdirBits value.
TrackBits
Bitfield corresponding to Track.
@ TRACK_BIT_WORMHOLE
Bitflag for a wormhole (used for tunnels).
@ TRACK_BIT_UPPER
Upper track.
@ TRACK_BIT_DEPOT
Bitflag for a depot.
@ TRACK_BIT_LEFT
Left track.
@ TRACK_BIT_Y
Y-axis track.
@ TRACK_BIT_NONE
No track.
@ TRACK_BIT_X
X-axis track.
@ TRACK_BIT_MASK
Bitmask for the first 6 bits.
@ TRACK_BIT_LOWER
Lower track.
@ TRACK_BIT_RIGHT
Right track.
Trackdir
Enumeration for tracks and directions.
@ INVALID_TRACKDIR
Flag for an invalid trackdir.
TrackdirBits
Enumeration of bitmasks for the TrackDirs.
@ TRACKDIR_BIT_NONE
No track build.
Track
These are used to specify a single track.
@ INVALID_TRACK
Flag for an invalid track.
@ TRACK_Y
Track along the y-axis (north-west to south-east).
@ TRACK_BEGIN
Used for iterations.
@ TRACK_X
Track along the x-axis (north-east to south-west).
@ Capacity
Allow vehicles to change capacity.
@ Length
Allow vehicles to change length.
EnumBitSet< ConsistChangeFlag, uint8_t > ConsistChangeFlags
Bitset of the ConsistChangeFlag elements.
static constexpr ConsistChangeFlags CCF_TRACK
Valid changes while vehicle is driving, and possibly changing tracks.
bool TryPathReserve(Train *v, bool mark_as_stuck=false, bool first_tile_okay=false)
Try to reserve a path to a safe position.
int GetTrainStopLocation(StationID station_id, TileIndex tile, const Train *moving_front, int *station_ahead, int *station_length)
Get the stop location of (the center) of the front vehicle of a train at a platform of a station.
void FreeTrainTrackReservation(const Train *v)
Free the reserved path in front of a vehicle.
@ Reversed
Used for vehicle var 0xFE bit 8 (toggled each time the train is reversed, accurate for first vehicle ...
@ LeavingStation
Train is just leaving a station.
@ PoweredWagon
Wagon is powered.
@ Reversing
Train is slowing down to reverse.
@ Stuck
Train can't get a path reservation.
@ AllowedOnNormalRail
Electric train engine is allowed to run on normal rail. */.
@ Flipped
Reverse the visible direction of the vehicle.
TrainForceProceeding
Modes for ignoring signals.
@ TFP_SIGNAL
Ignore next signal, after the signal ignore being stuck.
@ TFP_NONE
Normal operation.
@ TFP_STUCK
Proceed till next signal, but ignore being stuck till then. This includes force leaving depots.
static constexpr ConsistChangeFlags CCF_ARRANGE
Valid changes for arranging the consist in a depot.
static CommandCost CmdBuildRailWagon(DoCommandFlags flags, TileIndex tile, const Engine *e, Vehicle **ret)
Build a railroad wagon.
void FreeTrainTrackReservation(const Train *consist)
Free the reserved path in front of a vehicle.
static void NormaliseTrainHead(Train *head)
Normalise the head of the train again, i.e.
static CommandCost ValidateTrains(Train *original_dst, Train *dst, Train *original_src, Train *src, bool check_limit)
Validate whether we are going to create valid trains.
static bool CheckTrainStayInDepot(Train *v)
Will the train stay in the depot the next tick?
static FindDepotData FindClosestTrainDepot(Train *v, int max_distance)
Try to find a depot nearby.
CommandCost CmdForceTrainProceed(DoCommandFlags flags, VehicleID veh_id)
Force a train through a red signal.
void UpdateLevelCrossing(TileIndex tile, bool sound, bool force_bar)
Update a level crossing to barred or open (crossing may include multiple adjacent tiles).
int GetTrainStopLocation(StationID station_id, TileIndex tile, const Train *moving_front, int *station_ahead, int *station_length)
Get the stop location of (the center) of the front vehicle of a train at a platform of a station.
static bool CheckCompatibleRail(const Train *v, TileIndex tile, bool check_railtype)
Check if the vehicle is compatible with the specified tile.
static void AdvanceWagonsBeforeSwap(Train *moving_front)
Advances wagons for train reversing, needed for variable length wagons.
static void MakeTrainBackup(TrainList &list, Train *t)
Make a backup of a train into a train list.
static void ArrangeTrains(Train **dst_head, Train *dst, Train **src_head, Train *src, bool move_chain)
Arrange the trains in the wanted way.
static bool TryReserveSafeTrack(const Train *v, TileIndex tile, Trackdir td, bool override_railtype)
Try to reserve any path to a safe tile, ignoring the vehicle's destination.
static const uint16_t _breakdown_speeds[16]
Maximum speeds for train that is broken down or approaching line end.
static void InsertInConsist(Train *dst, Train *chain)
Inserts a chain into the train at dst.
void UpdateAdjacentLevelCrossingTilesOnLevelCrossingRemoval(TileIndex tile, Axis road_axis)
Update adjacent level crossing tiles in this multi-track crossing, due to removal of a level crossing...
static void SwapTrainFlags(uint16_t *swap_flag1, uint16_t *swap_flag2)
Swap the two up/down flags in two ways:
static constexpr DiagDirectionIndexArray< uint8_t > _vehicle_initial_y_fract
Initial y subtile coordinate of rail vehicles for each direction.
static void MarkTrainAsStuck(Train *consist)
Mark a train as stuck and stop it if it isn't stopped right now.
static void UpdateLevelCrossingTile(TileIndex tile, bool sound, bool force_barred)
Sets a level crossing tile to the correct state.
static constexpr DiagDirectionIndexArray< uint8_t > _vehicle_initial_x_fract
Initial x subtile coordinate of rail vehicles for each direction.
static void CheckNextTrainTile(Train *v)
Check if the train is on the last reserved tile and try to extend the path then.
static bool HandleCrashedTrain(Train *v)
Handle a crashed train.
void NormalizeTrainVehInDepot(const Train *u)
Move all free vehicles in the depot to the train.
CommandCost CmdReverseTrainDirection(DoCommandFlags flags, VehicleID veh_id, bool reverse_single_veh)
Reverse train.
static bool CheckLevelCrossing(TileIndex tile)
Check if a level crossing should be barred.
static CommandCost CheckNewTrain(Train *original_dst, Train *dst, Train *original_src, Train *src)
Check/validate whether we may actually build a new train.
CommandCost CmdBuildRailVehicle(DoCommandFlags flags, TileIndex tile, const Engine *e, Vehicle **ret)
Build a railroad vehicle.
static void UpdateStatusAfterSwap(Train *v, bool reverse=true)
Updates some variables after swapping the vehicle.
uint8_t FreightWagonMult(CargoType cargo)
Return the cargo weight multiplier to use for a rail vehicle.
static uint CheckTrainCollision(Vehicle *v, Train *moving_front)
Collision test function.
bool TryPathReserve(Train *consist, bool mark_as_stuck, bool first_tile_okay)
Try to reserve a path to a safe position.
static uint TrainCrashed(Train *v)
Marks train as crashed and creates an AI event.
static void NormaliseDualHeads(Train *t)
Normalise the dual heads in the train, i.e.
static CommandCost CheckTrainAttachment(Train *t)
Check whether the train parts can be attached.
static const AccelerationSlowdownParams _accel_slowdown[]
Speed update fractions for each acceleration type.
CommandCost CmdMoveRailVehicle(DoCommandFlags flags, VehicleID src_veh, VehicleID dest_veh, bool move_chain)
Move a rail vehicle around inside the depot.
static Track DoTrainPathfind(const Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool &path_found, bool do_track_reservation, PBSTileInfo *dest, TileIndex *final_dest)
Perform pathfinding for a train.
static void TrainEnterStation(Train *consist, StationID station)
Trains enters a station, send out a news item if it is the first train, and start loading.
static bool TrainLocoHandler(Train *consist, bool mode)
Per-tick handler of each front engine.
static bool TrainCanLeaveTile(const Train *moving_front)
Determines whether train would like to leave the tile.
static void AffectSpeedByZChange(Train *consist, int z_diff)
Modify the speed of the vehicle due to a change in altitude.
static void ClearPathReservation(const Train *v, TileIndex tile, Trackdir track_dir)
Clear the reservation of tile that was just left by a wagon on track_dir.
static void ReverseTrainDirection(Train *consist)
Turn a train around.
static bool IsTrain(const Vehicle *v)
Check if the vehicle is a train.
void CheckTrainsLengths()
Checks if lengths of all rail vehicles are valid.
static bool CheckReverseTrain(const Train *consist)
Can the train reverse?
static void MaybeBarCrossingWithSound(TileIndex tile)
Bars crossing and plays ding-ding sound if not barred already.
bool TrainOnCrossing(TileIndex tile)
Check if a level crossing tile has a train on it.
static void ChangeTrainDirRandomly(Train *v)
Rotate all vehicles of a (crashed) train chain randomly to animate the crash.
void MarkDirtyAdjacentLevelCrossingTiles(TileIndex tile, Axis road_axis)
Find adjacent level crossing tiles in this multi-track crossing and mark them dirty.
static void NormaliseSubtypes(Train *chain)
Normalise the sub types of the parts in this chain.
bool TrainController(Train *v, Vehicle *nomove, bool reverse=true)
Move a vehicle chain one movement stop forwards.
CommandCost CmdSellRailWagon(DoCommandFlags flags, Vehicle *t, bool sell_chain, bool backup_order, ClientID user)
Sell a (single) train wagon/engine.
bool IsValidImageIndex< VehicleType::Train >(uint8_t image_index)
Helper to check whether an image index is valid for a particular vehicle.
static TrainForceProceeding DetermineNextTrainForceProceeding(const Train *t)
Determine to what force_proceed should be changed.
static void RemoveFromConsist(Train *part, bool chain=false)
Remove the given wagon from its consist.
static bool TrainCheckIfLineEnds(Train *v, bool reverse=true)
Checks for line end.
static void RestoreTrainBackup(TrainList &list)
Restore the train from the backup list.
static void DeleteLastWagon(Train *v)
Deletes/Clears the last wagon of a crashed train.
static bool TrainApproachingLineEnd(Train *moving_front, bool signal, bool reverse)
Train is approaching line end, slow down and possibly reverse.
static bool TrainApproachingCrossing(TileIndex tile)
Finds a vehicle approaching rail-road crossing.
void ReverseTrainSwapVeh(Train *v, int l, int r)
Swap vehicles l and r in consist v, and reverse their direction.
static PBSTileInfo ExtendTrainReservation(const Train *v, TrackBits *new_tracks, DiagDirection *enterdir)
Extend a train path as far as possible.
static TileIndex TrainApproachingCrossingTile(const Train *v)
Determines whether train is approaching a rail-road crossing (thus making it barred).
static void AdvanceWagonsAfterSwap(Train *moving_front)
Advances wagons for train reversing, needed for variable length wagons.
void GetTrainSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type)
Get the size of the sprite of a train sprite heading west, or both heads (used for lists).
static void CheckIfTrainNeedsService(Train *v)
Check whether a train needs service, and if so, find a depot or service it.
static bool TrainApproachingCrossingEnum(const Vehicle *v, TileIndex tile)
Checks if a train is approaching a rail-road crossing.
static std::vector< VehicleID > GetFreeWagonsInDepot(TileIndex tile)
Get a list of free wagons in a depot.
Command definitions related to trains.
Sprites to use for trains.
static const uint8_t _engine_sprite_and[]
For how many directions do we have sprites?
static const uint8_t _engine_sprite_add[]
Non-zero for multihead trains.
@ TRANSPORT_RAIL
Transport by train.
bool IsTunnel(Tile t)
Is this a tunnel (entrance)?
void MarkBridgeDirty(TileIndex begin, TileIndex end, DiagDirection direction, uint bridge_height)
Mark bridge tiles dirty.
DiagDirection GetTunnelBridgeDirection(Tile t)
Get the direction pointing to the other end.
TileIndex GetOtherTunnelBridgeEnd(Tile t)
Determines type of the wormhole and returns its other end.
void SetTunnelBridgeReservation(Tile t, bool b)
Set the reservation state of the rail tunnel/bridge.
void ShowNewGrfVehicleError(EngineID engine, StringID part1, StringID part2, GRFBug bug_type, bool critical)
Displays a "NewGrf Bug" error message for a engine, and pauses the game if not networking.
void VehicleEnterDepot(Vehicle *v)
Vehicle entirely entered the depot, update its status, orders, vehicle windows, service it,...
UnitID GetFreeUnitNumber(VehicleType type)
Get an unused unit number for a vehicle (if allowed).
void VehicleLengthChanged(const Vehicle *u)
Logs a bug in GRF and shows a warning message if this is for the first time this happened.
void VehicleServiceInDepot(Vehicle *v)
Service a vehicle and all subsequent vehicles in the consist.
void CheckVehicleBreakdown(Vehicle *v)
Periodic check for a vehicle to maybe break down.
GetNewVehiclePosResult GetNewVehiclePos(const Vehicle *v)
Get position information of a vehicle when moving one pixel in the direction it is facing.
void DecreaseVehicleValue(Vehicle *v)
Decrease the value of a vehicle.
void EconomyAgeVehicle(Vehicle *v)
Update economy age of a vehicle.
CommandCost TunnelBridgeIsFree(TileIndex tile, TileIndex endtile, const Vehicle *ignore)
Finds vehicle in tunnel / bridge.
void AgeVehicle(Vehicle *v)
Update age of a vehicle.
Direction VehicleEnterTileCoordinates(GetNewVehiclePosResult &gp, DiagDirection enterdir, Track track)
Lookup new subposition coordinates and direction to use when entering a new tile, applying the subcoo...
@ Crashed
Vehicle is crashed.
@ TrainSlowing
Train is slowing down.
@ Hidden
Vehicle is not visible.
@ DefaultPalette
Use default vehicle palette.
@ Stopped
Vehicle is stopped by the player.
Functions related to vehicles.
bool IsValidImageIndex(uint8_t image_index)
Helper to check whether an image index is valid for a particular vehicle.
@ CUSTOM_VEHICLE_SPRITENUM_REVERSED
Vehicle sprite from NewGRF with reverse driving direction (from articulation callback).
bool HasVehicleOnTile(TileIndex tile, UnaryPred &&predicate)
Loop over vehicles on a tile, and check whether a predicate is true for any of them.
@ VIWD_CONSIST_CHANGED
Vehicle composition was changed.
EngineImageType
Visualisation contexts of vehicles and engines.
PoolID< uint32_t, struct VehicleIDTag, 0xFF000, 0xFFFFF > VehicleID
The type all our vehicle IDs have.
@ Train
Train vehicle type.
static const uint VEHICLE_LENGTH
The length of a vehicle in tile units.
Functions related to (drawing on) viewports.
void CloseWindowById(WindowClass cls, WindowNumber number, bool force, int data)
Close a window by its class and window number (if it is open).
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting).
void InvalidateWindowData(WindowClass cls, WindowNumber number, int data, bool gui_scope)
Mark window data of the window of a given class and specific window number as invalid (in need of re-...
void SetWindowWidgetDirty(WindowClass cls, WindowNumber number, WidgetID widget_index)
Mark a particular widget in a particular window as dirty (in need of repainting).
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting).
void InvalidateWindowClassesData(WindowClass cls, int data, bool gui_scope)
Mark window data of all windows of a given class as invalid (in need of re-computing) Note that by de...
FindDepotData YapfTrainFindNearestDepot(const Train *v, int max_distance)
Used when user sends train to the nearest depot or if train needs servicing using YAPF.
bool YapfTrainFindNearestSafeTile(const Train *v, TileIndex tile, Trackdir td, bool override_railtype)
Try to extend the reserved path of a train to the nearest safe tile using YAPF.
bool YapfTrainCheckReverse(const Train *v)
Returns true if it is better to reverse the train before leaving station using YAPF.
Track YapfTrainChooseTrack(const Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool &path_found, bool reserve_track, struct PBSTileInfo *target, TileIndex *dest)
Finds the best path for given train using YAPF.
Base includes/functions for YAPF.
Functions related to zooming.
int ScaleSpriteTrad(int value)
Scale traditional pixel dimensions to GUI zoom level, for drawing sprites.
int UnScaleGUI(int value)
Short-hand to apply GUI zoom level.