42#include "table/strings.h"
54static const uint8_t _vehicle_initial_x_fract[4] = {10, 8, 4, 8};
55static const uint8_t _vehicle_initial_y_fract[4] = { 8, 4, 8, 10};
58bool IsValidImageIndex<VEH_TRAIN>(uint8_t image_index)
60 return image_index <
lengthof(_engine_sprite_base);
81 if (v->First() == v && !(v->vehstatus &
VS_CRASHED)) {
82 for (
const Train *u = v, *w = v->
Next(); w !=
nullptr; u = w, w = w->Next()) {
85 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;
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 ?
INVALID_ENGINE : 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;
232 u->InvalidateNewGRFCache();
282 default: NOT_REACHED();
293 stop = *station_length;
309 assert(this->
First() ==
this);
311 static const int absolute_max_speed = UINT16_MAX;
312 int max_speed = absolute_max_speed;
316 int curvecount[2] = {0, 0};
323 for (
const Train *u =
this; u->
Next() !=
nullptr; u = u->Next(), pos += u->gcache.cached_veh_length) {
325 Direction next_dir = u->Next()->direction;
335 sum += pos - lastpos;
336 if (pos - lastpos <=
static_cast<int>(
VEHICLE_LENGTH) && max_speed > 88) {
349 if (numcurve > 0 && max_speed > 88) {
350 if (curvecount[0] == 1 && curvecount[1] == 1) {
351 max_speed = absolute_max_speed;
355 max_speed = 232 - (13 -
Clamp(sum, 1, 12)) * (13 -
Clamp(sum, 1, 12));
359 if (max_speed != absolute_max_speed) {
366 max_speed += max_speed / 5;
372 max_speed =
Clamp(max_speed, 2, absolute_max_speed);
375 return static_cast<uint16_t
>(max_speed);
397 int distance_to_go = station_ahead /
TILE_SIZE - (station_length - stop_at) /
TILE_SIZE;
399 if (distance_to_go > 0) {
400 int st_max_speed = 120;
402 int delta_v = this->
cur_speed / (distance_to_go + 1);
403 if (max_speed > (this->
cur_speed - delta_v)) {
404 st_max_speed = this->
cur_speed - (delta_v / 10);
407 st_max_speed = std::max(st_max_speed, 25 * distance_to_go);
408 max_speed = std::min(max_speed, st_max_speed);
413 for (
const Train *u =
this; u !=
nullptr; u = u->
Next()) {
415 max_speed = std::min(max_speed, 61);
440int Train::GetCursorImageOffset()
const
443 int reference_width = TRAININFO_DEFAULT_VEHICLE_WIDTH;
446 if (e->
GetGRF() !=
nullptr && is_custom_sprite(e->u.rail.image_index)) {
462 int reference_width = TRAININFO_DEFAULT_VEHICLE_WIDTH;
463 int vehicle_pitch = 0;
466 if (e->
GetGRF() !=
nullptr && is_custom_sprite(e->u.rail.image_index)) {
471 if (offset !=
nullptr) {
484 assert(IsValidImageIndex<VEH_TRAIN>(spritenum));
485 return ((direction + _engine_sprite_add[spritenum]) & _engine_sprite_and[spritenum]) + _engine_sprite_base[spritenum];
507 assert(IsValidImageIndex<VEH_TRAIN>(
spritenum));
519 uint8_t spritenum = e->u.rail.image_index;
521 if (is_custom_sprite(spritenum)) {
522 GetCustomVehicleIcon(engine, dir, image_type, result);
524 if (e->
GetGRF() !=
nullptr) {
530 spritenum =
Engine::Get(engine)->original_image_index;
533 if (rear_head) spritenum++;
535 result->
Set(GetDefaultTrainSprite(spritenum,
DIR_W));
545 GetRailIcon(engine,
false, yf, image_type, &seqf);
546 GetRailIcon(engine,
true, yr, image_type, &seqr);
552 preferred_x =
Clamp(preferred_x,
560 GetRailIcon(engine,
false, y, image_type, &seq);
564 preferred_x =
Clamp(preferred_x,
586 GetRailIcon(engine,
false, y, image_type, &seq);
597 GetRailIcon(engine,
true, y, image_type, &seq);
604 yoffs = std::min(yoffs,
UnScaleGUI(rect.top));
677 if (w->tile == tile &&
679 w->engine_type == e->
index &&
697 if (v->IsFreeWagon() && v->tile == u->
tile &&
706static void AddRearEngineToMultiheadedTrain(
Train *v)
724 u->railtype = v->railtype;
738 v->other_multiheaded_part = u;
739 u->other_multiheaded_part = v;
811 AddRearEngineToMultiheadedTrain(v);
825static Train *FindGoodVehiclePos(
const Train *src)
831 if (dst->IsFreeWagon() && dst->tile == tile && !(dst->vehstatus &
VS_CRASHED)) {
836 if (t ==
nullptr)
return dst;
854 for (; t !=
nullptr; t = t->
Next()) list.push_back(t);
864 if (list.empty())
return;
866 Train *prev =
nullptr;
868 for (
Train *t : list) {
869 if (prev !=
nullptr) {
871 }
else if (t->
Previous() !=
nullptr) {
904 assert(dst !=
nullptr && (dst->
Next() ==
nullptr || !dst->
Next()->IsArticulatedPart()));
906 chain->
Last()->SetNext(dst->
Next());
922 for (u = t; u->
Next() !=
nullptr && !u->
Next()->IsEngine(); u = u->
Next()) {}
924 if (u == t->other_multiheaded_part)
continue;
940 if (chain ==
nullptr)
return;
943 assert(chain->
Previous() ==
nullptr);
954 for (
Train *t = chain->
Next(); t !=
nullptr; t = t->
Next()) {
974 if ((src !=
nullptr && src->
IsEngine() ? 1 : 0) +
975 (dst !=
nullptr && dst->
IsEngine() ? 1 : 0) -
976 (original_src !=
nullptr && original_src->
IsEngine() ? 1 : 0) -
977 (original_dst !=
nullptr && original_dst->
IsEngine() ? 1 : 0) <= 0) {
985 return CommandCost(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
1005 while (t !=
nullptr) {
1011 if (allowed_len < 0)
return CommandCost(STR_ERROR_TRAIN_TOO_LONG);
1025 while (t !=
nullptr) {
1057 if (head->
GetGRF()->grf_version < 8) {
1058 if (callback == 0xFD) error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
1062 if (callback < 0x400) {
1072 error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
1088 if (allowed_len < 0)
return CommandCost(STR_ERROR_TRAIN_TOO_LONG);
1106 if (ret.
Failed())
return ret;
1108 if (ret.
Failed())
return ret;
1125 if (*src_head == *dst_head) {
1128 *dst_head =
nullptr;
1129 }
else if (*dst_head ==
nullptr) {
1135 if (src == *src_head) {
1142 *src_head = move_chain ? nullptr :
1166 if (head ==
nullptr)
return;
1199 if (ret.
Failed())
return ret;
1213 if (ret.
Failed())
return ret;
1221 if (dst !=
nullptr) {
1231 if (dst !=
nullptr) {
1232 dst_head = dst->
First();
1243 if (move_chain && src_head == dst_head)
return CommandCost();
1252 if (dst_head !=
nullptr && !dst_head->
IsStoppedInDepot())
return CommandCost(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
1265 Train *original_src_head = src_head;
1266 Train *original_dst_head = (dst_head == src_head ? nullptr : dst_head);
1271 bool original_src_head_front_engine = original_src_head->
IsFrontEngine();
1272 bool original_dst_head_front_engine = original_dst_head !=
nullptr && original_dst_head->
IsFrontEngine();
1281 ret =
ValidateTrains(original_dst_head, dst_head, original_src_head, src_head,
true);
1345 if (original_src_head != src && dst_head == src) {
1364 if (src_head !=
nullptr) src_head->
First()->MarkDirty();
1365 if (dst_head !=
nullptr) dst_head->
First()->MarkDirty();
1404 Train *new_head = first;
1405 Train *sell_head =
nullptr;
1408 ArrangeTrains(&sell_head,
nullptr, &new_head, v, sell_chain);
1421 return CommandCost(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
1425 for (
Train *part = sell_head; part !=
nullptr; part = part->
Next()) cost.
AddCost(-part->value);
1432 if (v == first && !sell_chain && new_head !=
nullptr && new_head->
IsFrontEngine()) {
1485 static const int _sign_table[] =
1497 this->
x_offs -= half_shorten * _sign_table[dir];
1498 this->
y_offs -= half_shorten * _sign_table[dir + 1];
1567 uint16_t flag1 = *swap_flag1;
1568 uint16_t flag2 = *swap_flag2;
1635 for (a = v; l != 0; l--) a = a->
Next();
1636 for (b = v; r != 0; r--) b = b->
Next();
1646 Swap(a->track, b->track);
1777 bool forced_state = force_bar;
1828 bool occupied =
false;
1877 Train *first = base;
1879 uint length = CountVehiclesInChain(v);
1881 while (length > 2) {
1883 first = first->
Next();
1912 if (leave !=
nullptr) {
1926 Train *first = base;
1928 uint length = CountVehiclesInChain(v);
1932 bool nomove = (dep ==
nullptr);
1934 while (length > 2) {
1937 if (base == dep)
break;
1940 if (last == dep) nomove =
true;
1943 first = first->
Next();
1948 for (
int i = 0; i < differential; i++)
TrainController(first, (nomove ? last->
Next() :
nullptr));
1955static bool IsWholeTrainInsideDepot(
const Train *v)
1957 for (
const Train *u = v; u !=
nullptr; u = u->
Next()) {
1970 if (IsWholeTrainInsideDepot(v))
return;
1981 int r = CountVehiclesInChain(v) - 1;
1999 ClrBit(v->flags, VRF_REVERSING);
2065 if (ret.
Failed())
return ret;
2067 if (reverse_single_veh) {
2071 return CommandCost(STR_ERROR_CAN_T_REVERSE_DIRECTION_RAIL_VEHICLE_MULTIPLE_UNITS);
2077 return CommandCost(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
2098 while (last->
Next() !=
nullptr) last = last->
Next();
2140 if (ret.
Failed())
return ret;
2184 static const SoundFx sfx[] = {
2194 SndPlayVehicleFx(sfx[RailVehInfo(this->
engine_type)->engclass],
this);
2215 case OT_GOTO_WAYPOINT:
2221 case OT_LEAVESTATION:
2252 ChooseTrainTrack(v, ft.
new_tile, ft.
exitdir, tracks,
false,
nullptr,
false);
2266 for (
const Train *u = v; u !=
nullptr; u = u->
Next()) {
2282 if (v->force_proceed ==
TFP_NONE) {
2399 for (
const Train *u = v; u !=
nullptr; u = u->
Next()) {
2407 while (ft.
Follow(tile, td)) {
2447static const uint8_t _initial_tile_subcoord[6][4][3] = {
2448{{ 15, 8, 1 }, { 0, 0, 0 }, { 0, 8, 5 }, { 0, 0, 0 }},
2449{{ 0, 0, 0 }, { 8, 0, 3 }, { 0, 0, 0 }, { 8, 15, 7 }},
2450{{ 0, 0, 0 }, { 7, 0, 2 }, { 0, 7, 6 }, { 0, 0, 0 }},
2451{{ 15, 8, 2 }, { 0, 0, 0 }, { 0, 0, 0 }, { 8, 15, 6 }},
2452{{ 15, 7, 0 }, { 8, 0, 4 }, { 0, 0, 0 }, { 0, 0, 0 }},
2453{{ 0, 0, 0 }, { 0, 0, 0 }, { 0, 8, 4 }, { 7, 15, 0 }},
2472 return YapfTrainChooseTrack(v, tile, enterdir, tracks, path_found, do_track_reservation, dest, final_dest);
2486 std::vector<std::pair<TileIndex, Trackdir>> signals_set_to_red;
2490 while (ft.
Follow(tile, cur_td)) {
2518 if (enterdir !=
nullptr) *enterdir = ft.
exitdir;
2531 signals_set_to_red.emplace_back(tile, rev_td);
2543 signals_set_to_red.emplace_back(tile, rev_td);
2549 if (ft.err == CFollowTrackRail::EC_OWNER || ft.err == CFollowTrackRail::EC_NO_WAY) {
2559 while (tile != stopped || cur_td != stopped_td) {
2560 if (!ft.
Follow(tile, cur_td))
break;
2575 for (
auto [sig_tile, td] : signals_set_to_red) {
2604 StationID old_last_station_visited;
2606 bool suppress_implicit_orders;
2627 this->v->
dest_tile = this->old_dest_tile;
2630 this->restored =
true;
2638 if (!this->restored) this->
Restore();
2650 if (skip_first) ++this->index;
2656 if (this->index >= this->v->
GetNumOrders()) this->index = 0;
2659 assert(order !=
nullptr);
2666 case OT_GOTO_STATION:
2667 case OT_GOTO_WAYPOINT:
2670 case OT_CONDITIONAL: {
2698 bool changed_signal =
false;
2703 if (got_reservation !=
nullptr) *got_reservation =
false;
2715 do_track_reservation =
true;
2716 changed_signal =
true;
2718 }
else if (!do_track_reservation) {
2726 if (do_track_reservation) {
2734 if (res_dest.okay) {
2736 if (got_reservation !=
nullptr) *got_reservation =
true;
2759 orders.SwitchToNextOrder(
false);
2763 v->tile == v->dest_tile))) {
2764 orders.SwitchToNextOrder(
true);
2769 bool path_found =
true;
2772 Track next_track =
DoTrainPathfind(v, new_tile, dest_enterdir, tracks, path_found, do_track_reservation, &res_dest, &final_dest);
2773 if (new_tile == tile) best_track = next_track;
2778 if (!do_track_reservation)
return best_track;
2795 if (got_reservation !=
nullptr) *got_reservation =
true;
2804 if (got_reservation !=
nullptr) *got_reservation =
true;
2817 if (orders.SwitchToNextOrder(
true)) {
2820 DoTrainPathfind(v, next_tile, exitdir, reachable, path_found,
true, &cur_dest,
nullptr);
2822 res_dest = cur_dest;
2823 if (res_dest.okay)
continue;
2827 if (got_reservation !=
nullptr) *got_reservation =
false;
2828 changed_signal =
false;
2836 if (got_reservation !=
nullptr) *got_reservation =
false;
2837 changed_signal =
false;
2884 Vehicle *other_train =
nullptr;
2891 if (other_train !=
nullptr && other_train->
index != v->
index) {
2896 if (origin.
okay && (v->
tile != origin.
tile || first_tile_okay)) {
2915 bool res_made =
false;
2916 ChooseTrainTrack(v, new_tile, exitdir, reachable,
true, &res_made, mark_as_stuck);
2933static bool CheckReverseTrain(
const Train *v)
2972 }
while ((v = v->
Next()) !=
nullptr);
2989 default: NOT_REACHED();
3009 if (!(st->had_vehicle_of_type &
HVOT_TRAIN)) {
3013 STR_NEWS_FIRST_TRAIN_ARRIVAL,
3032static inline bool CheckCompatibleRail(
const Train *v,
TileIndex tile)
3049 {256 / 4, 256 / 2, 256 / 4, 2},
3050 {256 / 4, 256 / 2, 256 / 4, 2},
3051 {0, 256 / 2, 256 / 4, 2},
3065 if (old_z < v->z_pos) {
3069 if (spd <= v->gcache.cached_max_track_speed) v->
cur_speed = spd;
3081 if (!IsPbsSignal(GetSignalType(tile,
TrackdirToTrack(trackdir))))
return true;
3090 for (
const Train *u =
this; u !=
nullptr; u = u->
Next()) {
3119 for (
const Train *v =
this; v !=
nullptr; v = v->
Next()) {
3155 victims = v->
Crash();
3157 Game::NewEvent(
new ScriptEventVehicleCrashed(v->
index, v->
tile, ScriptEventVehicleCrashed::CRASH_TRAIN, victims));
3193 if (coll == tcc->
v)
return nullptr;
3202 uint hash = (y_diff + 7) | (x_diff + 7);
3203 if (hash & ~15)
return nullptr;
3207 if (x_diff * x_diff + y_diff * y_diff > min_diff * min_diff)
return nullptr;
3246 if (tcc.
num == 0)
return false;
3251 ModifyStationRatingAround(v->
tile, v->
owner, -160, 30);
3282 bool direction_changed =
false;
3285 for (prev = v->
Previous(); v != nomove; prev = v, v = v->
Next()) {
3287 bool update_signals_crossing =
false;
3339 if (!CheckCompatibleRail(v, gp.
new_tile))
goto invalid_rail;
3342 if (prev ==
nullptr) {
3365 if ((red_signals & chosen_track) && v->force_proceed ==
TFP_NONE) {
3388 if (!
HasVehicleOnPos(o_tile, &exitdir, &CheckTrainAtSignal))
return false;
3401 goto reverse_train_direction;
3413 chosen_track = bits;
3415 chosen_track = prev->track;
3433 chosen_track = _connecting_track[enterdir][exitdir];
3435 chosen_track &= bits;
3445 const uint8_t *b = _initial_tile_subcoord[
FindFirstBit(chosen_track)][enterdir];
3446 gp.x = (gp.x & ~0xF) | b[0];
3447 gp.
y = (gp.
y & ~0xF) | b[1];
3473 v->track = chosen_track;
3479 update_signals_crossing =
true;
3487 direction_changed =
true;
3538 if (prev ==
nullptr) {
3543 if (update_signals_crossing) {
3545 if (TrainMovedChangeSignals(gp.
new_tile, enterdir)) {
3564 if (v->
Next() ==
nullptr) {
3580 if (prev !=
nullptr) FatalError(
"Disconnecting train");
3582reverse_train_direction:
3609 *trackbits |= train_tbits;
3616static bool IsRailStationPlatformOccupied(
TileIndex tile)
3645 for (; v->
Next() !=
nullptr; v = v->
Next()) u = v;
3689 bool occupied = IsRailStationPlatformOccupied(tile);
3709 static const DirDiff delta[] = {
3727 }
while ((v = v->
Next()) !=
nullptr);
3744 if (state <= 200 &&
Chance16R(1, 7, r)) {
3745 int index = (r * 10 >> 16);
3759 }
while ((u = u->
Next()) !=
nullptr);
3765 bool ret = v->
Next() !=
nullptr;
3775 225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, 15
3790 uint x = v->
x_pos & 0xF;
3791 uint y = v->
y_pos & 0xF;
3796 case DIR_N : x = ~x + ~y + 25;
break;
3797 case DIR_NW: x = y; [[fallthrough]];
3798 case DIR_NE: x = ~x + 16;
break;
3799 case DIR_E : x = ~x + y + 9;
break;
3800 case DIR_SE: x = y;
break;
3801 case DIR_S : x = x + y - 7;
break;
3802 case DIR_W : x = ~y + x + 9;
break;
3821 if (break_speed < v->cur_speed) v->
cur_speed = break_speed;
3874 !CheckCompatibleRail(v, tile)) {
3898 if (break_speed < v->cur_speed) v->
cur_speed = break_speed;
3940static bool TrainLocoHandler(
Train *v,
bool mode)
3947 if (v->force_proceed !=
TFP_NONE) {
4017 if (v->force_proceed ==
TFP_NONE)
return true;
4055 if (j < adv_spd || v->cur_speed == 0)
break;
4059 if ((order_type == OT_GOTO_WAYPOINT || order_type == OT_GOTO_STATION) &&
4069 for (
Train *u = v; u !=
nullptr; u = u->
Next()) {
4087 const Train *v =
this;
4091 if (e->u.rail.running_cost_class == INVALID_PRICE)
continue;
4094 if (cost_factor == 0)
continue;
4099 cost +=
GetPrice(e->u.rail.running_cost_class, cost_factor, e->
GetGRF());
4120 if (!TrainLocoHandler(
this,
false))
return false;
4122 return TrainLocoHandler(
this,
true);
4189 CheckVehicleBreakdown(
this);
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.
debug_inline constexpr bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
constexpr T AssignBit(T &x, const uint8_t y, bool value)
Assigns a bit in a variable.
constexpr T SetBit(T &x, const uint8_t y)
Set a bit in a variable.
constexpr uint8_t FindFirstBit(T x)
Search the first set bit in a value.
debug_inline 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 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.
uint8_t CargoID
Cargo slots to indicate a cargo type within a game.
bool IsValidCargoID(CargoID t)
Test whether cargo type is not INVALID_CARGO.
static void NewEvent(CompanyID company, ScriptEvent *event)
Queue a new event for an AI.
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?
static void NewEvent(class ScriptEvent *event)
Queue a new event for a Game Script.
This struct contains all the info that is needed to draw and construct tracks.
RailTypes powered_railtypes
bitmask to the OTHER railtypes on which an engine of THIS railtype generates power
RailTypes compatible_railtypes
bitmask to the OTHER railtypes on which an engine of THIS railtype can physically travel
uint8_t curve_speed
Multiplier for curve maximum speed advantage.
uint8_t acceleration_type
Acceleration type of this rail type.
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
days per year
static Date date
Current date in days (day counter).
uint StoredCount() const
Returns sum of cargo on board the vehicle (ie not only reserved).
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.
Functions related to commands.
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
DoCommandFlag
List of flags for a command.
@ DC_AUTOREPLACE
autoreplace/autorenew is in progress, this shall disable vehicle limits when building,...
@ DC_NO_CARGO_CAP_CHECK
when autoreplace/autorenew is in progress, this shall prevent truncating the amount of cargo in the v...
@ DC_EXEC
execute the given command
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.
Owner
Enum for all companies/owners.
DepotID GetDepotIndex(Tile t)
Get the index of which depot is attached to the tile.
uint16_t 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.
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.
Direction
Defines the 8 directions on the map.
Axis
Allow incrementing of DiagDirDiff variables.
DiagDirection
Enumeration for diagonal directions.
@ DIAGDIR_END
Used for iterations.
@ DIAGDIR_BEGIN
Used for iterations.
@ INVALID_DIAGDIR
Flag for an invalid DiagDirection.
DirDiff
Allow incrementing of Direction variables.
@ DIRDIFF_90LEFT
Angle of 90 degrees left.
@ DIRDIFF_45LEFT
Angle of 45 degrees left.
@ DIRDIFF_45RIGHT
Angle of 45 degrees right.
@ DIRDIFF_SAME
Both directions faces to the same direction.
@ DIRDIFF_90RIGHT
Angle of 90 degrees right.
Money GetPrice(Price index, uint cost_factor, const GRFFile *grf_file, int shift)
Determine a certain price.
@ EXPENSES_TRAIN_RUN
Running costs trains.
@ EXPENSES_NEW_VEHICLES
New vehicles.
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.
static const EngineID INVALID_ENGINE
Constant denoting an invalid engine.
uint16_t EngineID
Unique identification number of an engine.
@ ENGINE_EXCLUSIVE_PREVIEW
This vehicle is in the exclusive preview stage, either being used or being offered to a company.
@ EF_RAIL_TILTS
Rail vehicle tilts in curves.
@ EF_RAIL_FLIPS
Rail vehicle has old depot-flip handling.
@ RAILVEH_WAGON
simple wagon, not motorized
@ RAILVEH_MULTIHEAD
indicates a combination of two locomotives
Functions related to errors.
void ShowErrorMessage(StringID summary_msg, int x, int y, CommandCost cc)
Display an error message in a window.
@ WL_CRITICAL
Critical errors, the MessageBox is shown in all cases.
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 const GroupID DEFAULT_GROUP
Ungrouped vehicles are in this group.
TrackStatus GetTileTrackStatus(TileIndex tile, TransportType mode, uint 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.
DiagDirection DiagdirBetweenTiles(TileIndex tile_from, TileIndex tile_to)
Determines the DiagDirection to get from one tile to another.
TileIndex TileAddByDiagDir(TileIndex tile, DiagDirection dir)
Adds a DiagDir to a tile.
TileIndexDiff TileOffsByAxis(Axis axis)
Convert an Axis to a TileIndexDiff.
static debug_inline uint TileY(TileIndex tile)
Get the Y component of a tile.
static debug_inline uint TileX(TileIndex tile)
Get the X component of a tile.
TileIndexDiff TileOffsByDiagDir(DiagDirection dir)
Convert a DiagDirection to a TileIndexDiff.
static debug_inline TileIndex TileVirtXY(uint x, uint y)
Get a tile from the virtual XY-coordinate.
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.
constexpr void Swap(T &a, T &b)
Type safe swap operation.
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.
@ SAT_TRAIN_ARRIVES
Trigger platform when train arrives.
@ 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.
@ CBM_VEHICLE_LENGTH
Vehicle length (trains and road vehicles)
@ CBM_VEHICLE_ARTIC_ENGINE
Add articulated engines (trains and road vehicles)
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.
@ GBUG_VEH_CAPACITY
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)
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.
bool TestVehicleBuildProbability(Vehicle *v, EngineID engine, BuildProbabilityType type)
Test for vehicle build probablity type.
uint16_t GetVehicleCallback(CallbackID callback, uint32_t param1, uint32_t param2, EngineID engine, const Vehicle *v)
Evaluate a newgrf callback for vehicles.
@ 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(Station *st, TileIndex trigger_tile, StationRandomTrigger trigger, CargoID cargo_type)
Trigger station randomisation.
Header file for NewGRF stations.
@ SRT_TRAIN_ARRIVES
Trigger platform when train arrives.
StringID GetGRFStringID(uint32_t grfid, StringID stringid)
Returns the index for this stringid associated with its grfID.
Header of Action 04 "universal holder" structure and functions.
Functions related to news.
void AddVehicleAdviceNewsItem(StringID string, VehicleID vehicle)
Adds a vehicle-advice news item.
void AddVehicleNewsItem(StringID string, NewsType type, VehicleID vehicle, StationID station=INVALID_STATION)
Adds a newsitem referencing a vehicle.
@ NT_ARRIVAL_COMPANY
First vehicle arrived for company.
@ NT_ARRIVAL_OTHER
First vehicle arrived for competitor.
@ NT_ACCIDENT
An accident or disaster has occurred.
@ PM_PAUSED_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.
@ ODATFB_NEAREST_DEPOT
Send the vehicle to the nearest depot.
OrderStopLocation
Where to stop the trains.
@ OSL_PLATFORM_MIDDLE
Stop at the middle of the platform.
@ OSL_PLATFORM_FAR_END
Stop at the far end of the platform.
@ OSL_PLATFORM_NEAR_END
Stop at the near end of the platform.
uint8_t VehicleOrderID
The index of an order within its current vehicle (not pool related)
@ ONSF_NO_STOP_AT_DESTINATION_STATION
The vehicle will stop at any station it passes except the destination.
@ ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS
The vehicle will not stop at any stations it passes except the destination.
@ ODTFB_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.
PBSTileInfo FollowTrainReservation(const Train *v, Vehicle **train_on_res)
Follow a train reservation to the last tile.
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.
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.
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.
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? A one-way signal on the trackdir against will block,...
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.
static debug_inline RailTileType GetRailTileType(Tile t)
Returns the RailTileType (normal with or without signals, waypoint or depot).
TrackBits GetTrackBits(Tile tile)
Gets the track bits of the given tile.
static debug_inline bool IsRailDepotTile(Tile t)
Is this tile rail tile and a rail depot?
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 HasPbsSignalOnTrackdir(Tile tile, Trackdir td)
Is a pbs signal present along the trackdir?
bool IsOnewaySignal(Tile t, Track track)
One-way signals can't be passed the 'wrong' way.
void SetDepotReservation(Tile t, bool b)
Set the reservation state of the depot.
static debug_inline bool IsPlainRail(Tile t)
Returns whether this is plain rails, with or without signals.
bool HasDepotReservation(Tile t)
Get the reservation state of the depot.
@ RAIL_TILE_SIGNALS
Normal rail tile with signals.
bool HasSignals(Tile t)
Checks if a rail tile has signals.
static debug_inline bool IsPlainRailTile(Tile t)
Checks whether the tile is a rail tile or rail tile with signals.
SignalState GetSignalStateByTrackdir(Tile tile, Trackdir trackdir)
Gets the state of the signal along the given trackdir.
@ RAILTYPES_RAIL
Non-electrified rails.
@ RAILTYPES_NONE
No rail types.
@ 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.
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
Functions to cache sprites in memory.
static const PaletteID PALETTE_CRASH
Recolour sprite greying of crashed vehicles.
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.
@ FACIL_TRAIN
Station with train station.
Definition of base types and functions in a cross-platform compatible way.
#define lengthof(array)
Return the length of an fixed size array.
void SetDParam(size_t n, uint64_t v)
Set a string parameter v at index n in the global string parameter array.
Functions related to OTTD's strings.
uint32_t StringID
Numeric value that represents a string, independent of the selected language.
static const StringID INVALID_STRING_ID
Constant representing an invalid string (16bit in case it is used in savegames)
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.
uint16_t vehicle_flags
Used for gradual loading and other miscellaneous things (.
void ResetDepotUnbunching()
Resets all the data used for depot unbunching.
StationFacility facilities
The facilities that this station has.
TileIndex xy
Base tile of the station.
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)
Track follower helper template class (can serve pathfinders and vehicle controllers).
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 ID.
SoundSettings sound
sound effect settings
GUISettings gui
settings related to the GUI
Structure to return information about the closest depot location, and whether it could be found.
bool line_reverse_mode
reversing at stations or not
uint16_t cargo_age_period
Number of ticks before carried cargo is aged.
uint8_t misc_flags
Miscellaneous flags.
uint16_t callback_mask
Bitmask of vehicle callbacks that have to be called.
CargoID GetDefaultCargoType() const
Determines the default cargo type of an engine.
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.
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.
uint16_t reliability
Current reliability of the engine.
uint8_t flags
Flags of the engine.
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.
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.
bool lost_vehicle_warn
if a vehicle can't find its destination, show a warning
bool show_track_reservation
highlight reserved tracks.
PathfinderSettings pf
settings for all pathfinders
DifficultySettings difficulty
settings related to the difficulty
VehicleSettings vehicle
options for vehicles
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.
uint32_t cached_weight
Total weight of the consist (valid only for the first engine).
EngineID first_engine
Cached EngineID of the front vehicle. INVALID_ENGINE 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...
uint16_t cached_max_track_speed
Maximum consist speed (in internal units) limited by track type (valid only for the first engine).
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.
GroundVehicleCache gcache
Cache of often calculated values.
void CargoChanged()
Recalculates the cached weight of a vehicle and its parts.
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.
bool IsFreeWagon() const
Check if the vehicle is a free wagon (got no engine in front of it).
uint DoUpdateSpeed(uint accel, int min_speed, int max_speed)
Update the speed of the vehicle.
int GetAcceleration() const
Calculates the acceleration of the vehicle under its current conditions.
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 debug_inline 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.
OrderDepotTypeFlags GetDepotOrderType() const
What caused us going to the depot?
uint16_t GetMaxSpeed() const
Get the maxmimum speed in km-ish/h a vehicle is allowed to reach on the way to the destination.
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 MakeGoToDepot(DepotID destination, OrderDepotTypeFlags order, OrderNonStopFlags non_stop_type=ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS, OrderDepotActionFlags action=ODATF_SERVICE_ONLY, CargoID cargo=CARGO_NO_REFIT)
Makes this order a Go To Depot 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...
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.
uint8_t path_backoff_interval
ticks between checks for a free path.
uint8_t wait_for_pbs_path
how long to wait for a path reservation.
uint8_t wait_oneway_signal
waitingtime in days before a oneway signal
bool reserve_paths
always reserve paths regardless of signal type.
YAPFSettings yapf
pathfinder settings for the yet another pathfinder
bool reverse_at_signals
whether to reverse at signals at all
bool forbid_90_deg
forbid trains to make 90 deg turns
uint8_t wait_twoway_signal
waitingtime in days before a twoway signal
Coordinates of a point in 2D.
Tindex index
Index of this pool item.
static bool CanAllocateItem(size_t n=1)
Helper functions so we can use PoolItem::Function() instead of _poolitem_pool.Function()
static Titem * Get(size_t index)
Returns Titem with given 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
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)
uint8_t capacity
Cargo capacity of vehicle; For multiheaded engines the capacity of each single engine.
RailType railtype
Railtype, mangled if elrail is disabled.
uint8_t pow_wag_weight
Extra weight applied to consist if wagon should be powered.
Specification of a rectangle with absolute coordinates of all edges.
int Width() const
Get width of Rect.
int Height() const
Get height of Rect.
Iterable ensemble of each set bit in a value.
bool ambient
Play ambient, industry and town sounds.
bool disaster
Play disaster and accident sounds.
static Station * Get(size_t index)
Gets station with given index.
static T * GetIfValid(size_t index)
Returns vehicle if the index is a valid index for this vehicle type.
T * Next() const
Get next vehicle in the chain.
static Pool::IterateWrapper< T > Iterate(size_t from=0)
Returns an iterable ensemble of all valid vehicles of type T.
T * Previous() const
Get previous vehicle in the chain.
static T * From(Vehicle *v)
Converts a Vehicle to SpecializedVehicle with type checking.
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 * 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.
uint GetPlatformLength(TileIndex tile, DiagDirection dir) const override
Determines the REMAINING length of a platform, starting at (and including) the given tile.
uint16_t cached_max_curve_speed
max consist speed limited by curves
int16_t cached_curve_speed_mod
curve speed modifier of the entire train
bool cached_tilt
train can tilt; feature provides a bonus in curves
Temporary data storage for testing collisions.
Train * v
Vehicle we are testing for collision.
uint num
Total number of victims if train collided.
'Train' is either a loco or a wagon.
void PlayLeaveStationSound(bool force=false) const override
Play a sound for a train 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.
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.
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...
void UpdateDeltaXY() override
Updates the x and y offsets and the size of the sprite used for this vehicle.
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! Update its status and other parts around it.
AccelStatus GetAccelerationStatus() const
Checks the current acceleration status of this vehicle.
void OnNewEconomyDay() override
Economy day handler.
void ConsistChanged(ConsistChangeFlags allowed_changes)
Recalculates the cached stuff of a train.
Money GetRunningCost() const override
Get running cost for the train consist.
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.
uint16_t cached_max_speed
Maximum speed of the consist (minimum of the max speed of all vehicles in the consist).
UnitID max_trains
max trains in game per company
uint8_t train_acceleration_model
realistic acceleration for trains
bool wagon_speed_limits
enable wagon speed limits
uint8_t freight_trains
value to multiply the weight of cargo by
uint8_t max_train_length
maximum length for trains
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.
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.
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.
uint8_t x_extent
x-extent of vehicle bounding box
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.
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.
uint8_t z_extent
z-extent of vehicle bounding box
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.
int8_t y_offs
y offset for vehicle sprite
debug_inline bool IsFrontEngine() const
Check if the vehicle is a front engine.
uint8_t acceleration
used by train & aircraft
int8_t x_bb_offs
x offset of vehicle bounding box
Order current_order
The current order (+ status, like: loading)
CargoID cargo_type
type of cargo this vehicle is carrying
void HandlePathfindingResult(bool path_found)
Handle the pathfinding result, especially the lost status.
Vehicle * Next() const
Get the next vehicle of this vehicle.
int8_t x_offs
x offset for vehicle sprite
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.
uint8_t y_extent
y-extent of vehicle bounding box
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.
int8_t y_bb_offs
y offset of vehicle bounding box
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 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.
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.
uint32_t maximum_go_to_depot_penalty
What is the maximum penalty that may be endured for going to a depot.
@ VETS_CANNOT_ENTER
The vehicle cannot enter the tile.
@ VETS_ENTERED_WORMHOLE
The vehicle either entered a bridge, tunnel or depot tile (this includes the last tile of the bridge/...
@ VETS_ENTERED_STATION
The vehicle entered a station.
@ VETS_STATION_ID_OFFSET
Shift the VehicleEnterTileStatus this many bits to the right to get the station ID when VETS_ENTERED_...
VehicleEnterTileStatus VehicleEnterTile(Vehicle *v, TileIndex tile, int x, int y)
Call the tile callback function for a vehicle entering a tile.
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.
static debug_inline bool IsTileType(Tile tile, TileType type)
Checks if a tile is a given tiletype.
static const uint TILE_SIZE
Tile size in world coordinates.
constexpr TileIndex INVALID_TILE
The very nice invalid tile marker.
@ MP_STATION
A tile of a station.
@ MP_TUNNELBRIDGE
Tunnel entry/exit and bridge heads.
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.
TrackdirBits TrackStatusToTrackdirBits(TrackStatus ts)
Returns the present-trackdir-information of a TrackStatus.
Track TrackBitsToTrack(TrackBits tracks)
Converts TrackBits to Track.
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...
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 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 (4-way) direction to the diagonal track bits incidating with that diagdir.
Trackdir DiagDirToDiagTrackdir(DiagDirection diagdir)
Maps a (4-way) direction to the diagonal trackdir that runs in that direction.
TrackdirBits TrackStatusToRedSignals(TrackStatus ts)
Returns the red-signal-information of a TrackStatus.
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 (4-way) direction to the diagonal track incidating with that diagdir.
TrackBits TrackdirBitsToTrackBits(TrackdirBits bits)
Discards all directional information from a TrackdirBits value.
TrackBits
Allow incrementing of Track variables.
@ 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
Allow incrementing of Trackdir variables.
@ 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)
@ VRF_POWEREDWAGON
Wagon is powered.
@ VRF_LEAVING_STATION
Train is just leaving a station.
@ VRF_TOGGLE_REVERSE
Used for vehicle var 0xFE bit 8 (toggled each time the train is reversed, accurate for first vehicle ...
@ VRF_REVERSE_DIRECTION
Reverse the visible direction of the vehicle.
@ VRF_EL_ENGINE_ALLOWED_NORMAL_RAIL
Electric train engine is allowed to run on normal rail. */.
@ VRF_TRAIN_STUCK
Train can't get a path reservation.
void FreeTrainTrackReservation(const Train *v)
Free the reserved path in front of a vehicle.
ConsistChangeFlags
Flags for Train::ConsistChanged.
@ CCF_CAPACITY
Allow vehicles to change capacity.
@ CCF_ARRANGE
Valid changes for arranging the consist in a depot.
@ CCF_LENGTH
Allow vehicles to change length.
@ CCF_TRACK
Valid changes while vehicle is driving, and possibly changing tracks.
int GetTrainStopLocation(StationID station_id, TileIndex tile, const Train *v, 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.
@ 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 void AffectSpeedByZChange(Train *v, int old_z)
Modify the speed of the vehicle due to a change in altitude.
CommandCost CmdBuildRailVehicle(DoCommandFlag flags, TileIndex tile, const Engine *e, Vehicle **ret)
Build a railroad 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.
void UpdateLevelCrossing(TileIndex tile, bool sound, bool force_bar)
Update a level crossing to barred or open (crossing may include multiple adjacent tiles).
static void MakeTrainBackup(TrainList &list, Train *t)
Make a backup of a train into a train list.
static void CheckNextTrainTile(Train *v)
Check if the train is on the last reserved tile and try to extend the path then.
static void ArrangeTrains(Train **dst_head, Train *dst, Train **src_head, Train *src, bool move_chain)
Arrange the trains in the wanted way.
bool TryPathReserve(Train *v, bool mark_as_stuck, bool first_tile_okay)
Try to reserve a path to a safe position.
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 bool TrainApproachingLineEnd(Train *v, bool signal, bool reverse)
Train is approaching line end, slow down and possibly reverse.
static bool CheckTrainCollision(Train *v)
Checks whether the specified train has a collision with another vehicle.
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:
CommandCost CmdMoveRailVehicle(DoCommandFlag flags, VehicleID src_veh, VehicleID dest_veh, bool move_chain)
Move a rail vehicle around inside the depot.
static void UpdateLevelCrossingTile(TileIndex tile, bool sound, bool force_barred)
Sets a level crossing tile to the correct state.
static Vehicle * CollectTrackbitsFromCrashedVehiclesEnum(Vehicle *v, void *data)
Collect trackbits of all crashed train vehicles on a tile.
static bool HandleCrashedTrain(Train *v)
Handle a crashed train.
void NormalizeTrainVehInDepot(const Train *u)
Move all free vehicles in the depot to the train.
static bool CheckLevelCrossing(TileIndex tile)
Check if a level crossing should be barred.
uint8_t FreightWagonMult(CargoID cargo)
Return the cargo weight multiplier to use for a rail vehicle.
static CommandCost CheckNewTrain(Train *original_dst, Train *dst, Train *original_src, Train *src)
Check/validate whether we may actually build a new train.
static void AdvanceWagonsBeforeSwap(Train *v)
Advances wagons for train reversing, needed for variable length wagons.
static void AdvanceWagonsAfterSwap(Train *v)
Advances wagons for train reversing, needed for variable length wagons.
static bool TrainCheckIfLineEnds(Train *v, bool reverse=true)
Checks for line end.
void ReverseTrainDirection(Train *v)
Turn a train around.
void FreeTrainTrackReservation(const Train *v)
Free the reserved path in front of a vehicle.
CommandCost CmdSellRailWagon(DoCommandFlag flags, Vehicle *t, bool sell_chain, bool backup_order, ClientID user)
Sell a (single) train wagon/engine.
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.
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 CommandCost CmdBuildRailWagon(DoCommandFlag flags, TileIndex tile, const Engine *e, Vehicle **ret)
Build a railroad wagon.
static Vehicle * FindTrainCollideEnum(Vehicle *v, void *data)
Collision test function.
CommandCost CmdForceTrainProceed(DoCommandFlag flags, VehicleID veh_id)
Force a train through a red signal.
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.
void CheckTrainsLengths()
Checks if lengths of all rail vehicles are valid.
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.
static TileIndex TrainApproachingCrossingTile(const Train *v)
Determines whether train is approaching a rail-road crossing (thus making it barred)
static void RemoveFromConsist(Train *part, bool chain=false)
Remove the given wagon from its consist.
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 TrainCanLeaveTile(const Train *v)
Determines whether train would like to leave the tile.
static Vehicle * TrainOnTileEnum(Vehicle *v, void *)
Check if the vehicle is a train.
int GetTrainStopLocation(StationID station_id, TileIndex tile, const Train *v, 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 void TrainEnterStation(Train *v, StationID station)
Trains enters a station, send out a news item if it is the first train, and start loading.
static void MarkTrainAsStuck(Train *v)
Mark a train as stuck and stop it if it isn't stopped right now.
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.
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.
std::vector< Train * > TrainList
Helper type for lists/vectors of trains.
static void UpdateStatusAfterSwap(Train *v)
Updates some variables after swapping the vehicle.
static Vehicle * TrainApproachingCrossingEnum(Vehicle *v, void *data)
Checks if a train is approaching a rail-road crossing.
CommandCost CmdReverseTrainDirection(DoCommandFlag flags, VehicleID veh_id, bool reverse_single_veh)
Reverse train.
Command definitions related to trains.
Sprites to use for 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 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 FindVehicleOnPosXY(int x, int y, void *data, VehicleFromPosProc *proc)
Find a vehicle from a specific location.
GetNewVehiclePosResult GetNewVehiclePos(const Vehicle *v)
Get position information of a vehicle when moving one pixel in the direction it is facing.
bool HasVehicleOnPos(TileIndex tile, void *data, VehicleFromPosProc *proc)
Checks whether a vehicle is on a specific location.
void FindVehicleOnPos(TileIndex tile, void *data, VehicleFromPosProc *proc)
Find a vehicle from a specific location.
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 ShowNewGrfVehicleError(EngineID engine, StringID part1, StringID part2, GRFBugs bug_type, bool critical)
Displays a "NewGrf Bug" error message for a engine, and pauses the game if not networking.
void AgeVehicle(Vehicle *v)
Update age of a vehicle.
@ VF_BUILT_AS_PROTOTYPE
Vehicle is a prototype (accepted as exclusive preview).
@ VS_TRAIN_SLOWING
Train is slowing down.
@ VS_STOPPED
Vehicle is stopped by the player.
@ VS_HIDDEN
Vehicle is not visible.
@ VS_CRASHED
Vehicle is crashed.
@ VS_DEFPAL
Use default vehicle palette.
@ VE_DISABLE_WAGON_POWER
Flag to disable wagon power.
Functions related to vehicles.
@ VIWD_CONSIST_CHANGED
Vehicle composition was changed.
EngineImageType
Visualisation contexts of vehicles and engines.
@ VEH_TRAIN
Train vehicle type.
uint32_t VehicleID
The type all our vehicle IDs have.
static const VehicleID INVALID_VEHICLE
Constant representing a non-existing vehicle.
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...
@ WC_VEHICLE_ORDERS
Vehicle orders; Window numbers:
@ WC_VEHICLE_DEPOT
Depot view; Window numbers:
@ WC_TRAINS_LIST
Trains list; Window numbers:
@ WC_VEHICLE_REFIT
Vehicle refit; Window numbers:
@ WC_VEHICLE_DETAILS
Vehicle details; Window numbers:
@ WC_COMPANY
Company view; Window numbers:
@ WC_VEHICLE_VIEW
Vehicle view; Window numbers:
@ WC_VEHICLE_TIMETABLE
Vehicle timetable; Window numbers:
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.