Go to the documentation of this file.
40 #include "table/strings.h"
52 static const byte _vehicle_initial_x_fract[4] = {10, 8, 4, 8};
53 static const byte _vehicle_initial_y_fract[4] = { 8, 4, 8, 10};
56 bool IsValidImageIndex<VEH_TRAIN>(uint8 image_index)
58 return image_index <
lengthof(_engine_sprite_base);
79 if (v->First() == v && !(v->vehstatus &
VS_CRASHED)) {
80 for (
const Train *u = v, *w = v->
Next(); w !=
nullptr; u = w, w = w->
Next()) {
83 std::max(
abs(u->x_pos - w->x_pos),
abs(u->y_pos - w->y_pos)) != u->CalcNextVehicleOffset()) ||
110 uint16 max_speed = UINT16_MAX;
119 bool train_can_tilt =
true;
120 int min_curve_speed_mod = INT_MAX;
122 for (
Train *u =
this; u !=
nullptr; u = u->
Next()) {
126 assert(u->First() ==
this);
129 u->gcache.first_engine =
this == u ?
INVALID_ENGINE : first_engine;
132 if (u->IsEngine()) first_engine = u->engine_type;
137 u->InvalidateNewGRFCache();
140 for (
Train *u =
this; u !=
nullptr; u = u->
Next()) {
144 u->InvalidateNewGRFCache();
147 for (
Train *u =
this; u !=
nullptr; u = u->
Next()) {
148 const Engine *e_u = u->GetEngine();
152 min_curve_speed_mod = std::min(min_curve_speed_mod, u->GetCurveSpeedModifier());
155 u->tcache.cached_override = GetWagonOverrideSpriteSet(u->engine_type, u->cargo_type, u->gcache.first_engine);
158 u->colourmap = PAL_NONE;
161 u->UpdateVisualEffect(
true);
171 if (!u->IsArticulatedPart()) {
174 if (rvi_u->
power > 0) {
188 if (speed != 0) max_speed = std::min(speed, max_speed);
195 if (u->cargo_cap > new_cap) u->cargo.Truncate(new_cap);
196 u->refit_cap = std::min(new_cap, u->refit_cap);
197 u->cargo_cap = new_cap;
206 if (e_u->
GetGRF() !=
nullptr && e_u->
GetGRF()->grf_version >= 8) {
222 u->gcache.cached_veh_length = veh_len;
230 u->InvalidateNewGRFCache();
280 default: NOT_REACHED();
291 stop = *station_length;
307 assert(this->
First() ==
this);
309 static const int absolute_max_speed = UINT16_MAX;
310 int max_speed = absolute_max_speed;
314 int curvecount[2] = {0, 0};
321 for (
const Vehicle *u =
this; u->
Next() !=
nullptr; u = u->
Next(), pos++) {
323 Direction next_dir = u->Next()->direction;
333 sum += pos - lastpos;
334 if (pos - lastpos == 1 && max_speed > 88) {
347 if (numcurve > 0 && max_speed > 88) {
348 if (curvecount[0] == 1 && curvecount[1] == 1) {
349 max_speed = absolute_max_speed;
352 max_speed = 232 - (13 -
Clamp(sum, 1, 12)) * (13 -
Clamp(sum, 1, 12));
356 if (max_speed != absolute_max_speed) {
363 max_speed += max_speed / 5;
369 max_speed =
Clamp(max_speed, 2, absolute_max_speed);
394 int distance_to_go = station_ahead /
TILE_SIZE - (station_length - stop_at) /
TILE_SIZE;
396 if (distance_to_go > 0) {
397 int st_max_speed = 120;
399 int delta_v = this->
cur_speed / (distance_to_go + 1);
400 if (max_speed > (this->
cur_speed - delta_v)) {
401 st_max_speed = this->
cur_speed - (delta_v / 10);
404 st_max_speed = std::max(st_max_speed, 25 * distance_to_go);
405 max_speed = std::min(max_speed, st_max_speed);
410 for (
const Train *u =
this; u !=
nullptr; u = u->
Next()) {
412 max_speed = std::min(max_speed, 61);
437 int Train::GetCursorImageOffset()
const
440 int reference_width = TRAININFO_DEFAULT_VEHICLE_WIDTH;
443 if (e->
GetGRF() !=
nullptr && is_custom_sprite(e->u.rail.image_index)) {
459 int reference_width = TRAININFO_DEFAULT_VEHICLE_WIDTH;
460 int vehicle_pitch = 0;
463 if (e->
GetGRF() !=
nullptr && is_custom_sprite(e->u.rail.image_index)) {
468 if (offset !=
nullptr) {
481 assert(IsValidImageIndex<VEH_TRAIN>(
spritenum));
499 if (result->IsValid())
return;
504 assert(IsValidImageIndex<VEH_TRAIN>(
spritenum));
519 GetCustomVehicleIcon(engine, dir, image_type, result);
520 if (result->IsValid()) {
521 if (e->
GetGRF() !=
nullptr) {
542 GetRailIcon(engine,
false, yf, image_type, &seqf);
543 GetRailIcon(engine,
true, yr, image_type, &seqr);
549 preferred_x =
Clamp(preferred_x,
557 GetRailIcon(engine,
false, y, image_type, &seq);
561 preferred_x =
Clamp(preferred_x,
583 GetRailIcon(engine,
false, y, image_type, &seq);
594 GetRailIcon(engine,
true, y, image_type, &seq);
601 yoffs = std::min(yoffs,
UnScaleGUI(rect.top));
638 v->
z_pos = GetSlopePixelZ(x, y);
671 if (w->tile ==
tile &&
673 w->engine_type == e->
index &&
690 if (v->IsFreeWagon() && v->tile == u->
tile &&
699 static void AddRearEngineToMultiheadedTrain(
Train *v)
717 u->railtype = v->railtype;
729 v->other_multiheaded_part = u;
730 u->other_multiheaded_part = v;
763 v->
z_pos = GetSlopePixelZ(x, y);
799 AddRearEngineToMultiheadedTrain(v);
813 static Train *FindGoodVehiclePos(
const Train *src)
819 if (dst->IsFreeWagon() && dst->tile ==
tile && !(dst->vehstatus &
VS_CRASHED)) {
824 if (t ==
nullptr)
return dst;
842 for (; t !=
nullptr; t = t->
Next()) list.push_back(t);
852 if (list.size() == 0)
return;
854 Train *prev =
nullptr;
856 for (
Train *t : list) {
857 if (prev !=
nullptr) {
859 }
else if (t->
Previous() !=
nullptr) {
912 if (u == t->other_multiheaded_part)
continue;
928 if (chain ==
nullptr)
return;
931 assert(chain->
Previous() ==
nullptr);
942 for (
Train *t = chain->
Next(); t !=
nullptr; t = t->
Next()) {
962 if ((src !=
nullptr && src->
IsEngine() ? 1 : 0) +
963 (dst !=
nullptr && dst->
IsEngine() ? 1 : 0) -
964 (original_src !=
nullptr && original_src->
IsEngine() ? 1 : 0) -
965 (original_dst !=
nullptr && original_dst->
IsEngine() ? 1 : 0) <= 0) {
993 while (t !=
nullptr) {
1013 while (t !=
nullptr) {
1045 if (head->
GetGRF()->grf_version < 8) {
1046 if (callback == 0xFD)
error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
1050 if (callback < 0x400) {
1060 error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
1094 if (ret.
Failed())
return ret;
1096 if (ret.
Failed())
return ret;
1113 if (*src_head == *dst_head) {
1116 *dst_head =
nullptr;
1117 }
else if (*dst_head ==
nullptr) {
1123 if (src == *src_head) {
1130 *src_head = move_chain ? nullptr :
1154 if (head ==
nullptr)
return;
1187 if (ret.
Failed())
return ret;
1201 if (ret.
Failed())
return ret;
1209 if (dst !=
nullptr) {
1219 if (dst !=
nullptr) {
1220 dst_head = dst->
First();
1231 if (move_chain && src_head == dst_head)
return CommandCost();
1253 Train *original_src_head = src_head;
1254 Train *original_dst_head = (dst_head == src_head ? nullptr : dst_head);
1259 bool original_src_head_front_engine = original_src_head->
IsFrontEngine();
1260 bool original_dst_head_front_engine = original_dst_head !=
nullptr && original_dst_head->
IsFrontEngine();
1328 if (original_src_head != src && dst_head == src) {
1387 Train *sell_head =
nullptr;
1390 ArrangeTrains(&sell_head,
nullptr, &new_head, v, sell_chain);
1407 for (
Train *part = sell_head; part !=
nullptr; part = part->
Next()) cost.
AddCost(-part->value);
1465 static const int _sign_table[] =
1477 this->
x_offs -= half_shorten * _sign_table[dir];
1478 this->
y_offs -= half_shorten * _sign_table[dir + 1];
1547 uint16 flag1 = *swap_flag1;
1548 uint16 flag2 = *swap_flag2;
1615 for (a = v; l != 0; l--) a = a->
Next();
1616 for (b = v; r != 0; r--) b = b->
Next();
1626 Swap(a->track, b->track);
1757 bool forced_state = force_bar;
1808 bool occupied =
false;
1859 uint length = CountVehiclesInChain(v);
1861 while (length > 2) {
1892 if (leave !=
nullptr) {
1908 uint length = CountVehiclesInChain(v);
1912 bool nomove = (dep ==
nullptr);
1914 while (length > 2) {
1917 if (base == dep)
break;
1920 if (last == dep) nomove =
true;
1935 static bool IsWholeTrainInsideDepot(
const Train *v)
1937 for (
const Train *u = v; u !=
nullptr; u = u->
Next()) {
1950 if (IsWholeTrainInsideDepot(v))
return;
1961 int r = CountVehiclesInChain(v) - 1;
1979 ClrBit(v->flags, VRF_REVERSING);
2045 if (ret.
Failed())
return ret;
2047 if (reverse_single_veh) {
2051 return_cmd_error(STR_ERROR_CAN_T_REVERSE_DIRECTION_RAIL_VEHICLE_MULTIPLE_UNITS);
2078 while (last->
Next() !=
nullptr) last = last->
Next();
2117 if (ret.
Failed())
return ret;
2153 default: NOT_REACHED();
2169 if (location !=
nullptr) *location = tfdd.
tile;
2171 if (reverse !=
nullptr) *reverse = tfdd.
reverse;
2179 static const SoundFx sfx[] = {
2189 SndPlayVehicleFx(sfx[RailVehInfo(this->
engine_type)->engclass],
this);
2210 case OT_GOTO_WAYPOINT:
2216 case OT_LEAVESTATION:
2261 for (
const Train *u = v; u !=
nullptr; u = u->
Next()) {
2274 if (v->force_proceed ==
TFP_NONE) {
2390 for (
const Train *u = v; u !=
nullptr; u = u->
Next()) {
2433 static const byte _initial_tile_subcoord[6][4][3] = {
2434 {{ 15, 8, 1 }, { 0, 0, 0 }, { 0, 8, 5 }, { 0, 0, 0 }},
2435 {{ 0, 0, 0 }, { 8, 0, 3 }, { 0, 0, 0 }, { 8, 15, 7 }},
2436 {{ 0, 0, 0 }, { 7, 0, 2 }, { 0, 7, 6 }, { 0, 0, 0 }},
2437 {{ 15, 8, 2 }, { 0, 0, 0 }, { 0, 0, 0 }, { 8, 15, 6 }},
2438 {{ 15, 7, 0 }, { 8, 0, 4 }, { 0, 0, 0 }, { 0, 0, 0 }},
2439 {{ 0, 0, 0 }, { 0, 0, 0 }, { 0, 8, 4 }, { 7, 15, 0 }},
2463 default: NOT_REACHED();
2508 if (enterdir !=
nullptr) *enterdir = ft.
m_exitdir;
2525 if (ft.m_err == CFollowTrackRail::EC_OWNER || ft.m_err == CFollowTrackRail::EC_NO_WAY) {
2535 while (
tile != stopped || cur_td != stopped_td) {
2570 default: NOT_REACHED();
2580 StationID old_last_station_visited;
2582 bool suppress_implicit_orders;
2603 this->v->
dest_tile = this->old_dest_tile;
2606 this->restored =
true;
2614 if (!this->restored) this->
Restore();
2626 if (skip_first) ++this->index;
2632 if (this->index >= this->v->
GetNumOrders()) this->index = 0;
2635 assert(order !=
nullptr);
2642 case OT_GOTO_STATION:
2643 case OT_GOTO_WAYPOINT:
2646 case OT_CONDITIONAL: {
2674 bool changed_signal =
false;
2679 if (got_reservation !=
nullptr) *got_reservation =
false;
2691 do_track_reservation =
true;
2692 changed_signal =
true;
2694 }
else if (!do_track_reservation) {
2702 if (do_track_reservation) {
2710 if (res_dest.okay) {
2712 if (got_reservation !=
nullptr) *got_reservation =
true;
2735 orders.SwitchToNextOrder(
false);
2740 orders.SwitchToNextOrder(
true);
2745 bool path_found =
true;
2748 Track next_track =
DoTrainPathfind(v, new_tile, dest_enterdir, tracks, path_found, do_track_reservation, &res_dest, &final_dest);
2749 if (new_tile == tile) best_track = next_track;
2754 if (!do_track_reservation)
return best_track;
2771 if (got_reservation !=
nullptr) *got_reservation =
true;
2780 if (got_reservation !=
nullptr) *got_reservation =
true;
2793 if (orders.SwitchToNextOrder(
true)) {
2796 DoTrainPathfind(v, next_tile, exitdir, reachable, path_found,
true, &cur_dest,
nullptr);
2798 res_dest = cur_dest;
2799 if (res_dest.okay)
continue;
2803 if (got_reservation !=
nullptr) *got_reservation =
false;
2804 changed_signal =
false;
2812 if (got_reservation !=
nullptr) *got_reservation =
false;
2813 changed_signal =
false;
2860 Vehicle *other_train =
nullptr;
2867 if (other_train !=
nullptr && other_train->
index != v->
index) {
2872 if (origin.
okay && (v->
tile != origin.
tile || first_tile_okay)) {
2891 bool res_made =
false;
2892 ChooseTrainTrack(v, new_tile, exitdir, reachable,
true, &res_made, mark_as_stuck);
2909 static bool CheckReverseTrain(
const Train *v)
2923 default: NOT_REACHED();
2953 }
while ((v = v->
Next()) !=
nullptr);
2970 default: NOT_REACHED();
2990 if (!(st->had_vehicle_of_type &
HVOT_TRAIN)) {
2994 STR_NEWS_FIRST_TRAIN_ARRIVAL,
3013 static inline bool CheckCompatibleRail(
const Train *v,
TileIndex tile)
3030 {256 / 4, 256 / 2, 256 / 4, 2},
3031 {256 / 4, 256 / 2, 256 / 4, 2},
3032 {0, 256 / 2, 256 / 4, 2},
3046 if (old_z < v->z_pos) {
3050 if (spd <= v->gcache.cached_max_track_speed) v->
cur_speed = spd;
3062 if (!IsPbsSignal(GetSignalType(tile,
TrackdirToTrack(trackdir))))
return true;
3071 for (
const Train *u =
this; u !=
nullptr; u = u->
Next()) {
3100 for (
const Train *v =
this; v !=
nullptr; v = v->
Next()) {
3174 if (coll == tcc->
v)
return nullptr;
3183 uint hash = (y_diff + 7) | (x_diff + 7);
3184 if (hash & ~15)
return nullptr;
3188 if (x_diff * x_diff + y_diff * y_diff > min_diff * min_diff)
return nullptr;
3227 if (tcc.
num == 0)
return false;
3232 ModifyStationRatingAround(v->
tile, v->
owner, -160, 30);
3263 bool direction_changed =
false;
3266 for (prev = v->
Previous(); v != nomove; prev = v, v = v->
Next()) {
3268 bool update_signals_crossing =
false;
3320 if (!CheckCompatibleRail(v, gp.
new_tile))
goto invalid_rail;
3323 if (prev ==
nullptr) {
3346 if ((red_signals & chosen_track) && v->force_proceed ==
TFP_NONE) {
3369 if (!
HasVehicleOnPos(o_tile, &exitdir, &CheckTrainAtSignal))
return false;
3382 goto reverse_train_direction;
3394 chosen_track = bits;
3396 chosen_track = prev->track;
3414 chosen_track = _connecting_track[enterdir][exitdir];
3416 chosen_track &= bits;
3426 const byte *b = _initial_tile_subcoord[
FIND_FIRST_BIT(chosen_track)][enterdir];
3427 gp.x = (gp.x & ~0xF) | b[0];
3428 gp.
y = (gp.
y & ~0xF) | b[1];
3454 v->track = chosen_track;
3460 update_signals_crossing =
true;
3468 direction_changed =
true;
3519 if (prev ==
nullptr) {
3524 if (update_signals_crossing) {
3526 if (TrainMovedChangeSignals(gp.
new_tile, enterdir)) {
3545 if (v->
Next() ==
nullptr) {
3561 if (prev !=
nullptr)
error(
"Disconnecting train");
3563 reverse_train_direction:
3590 *trackbits |= train_tbits;
3597 static bool IsRailStationPlatformOccupied(
TileIndex tile)
3626 for (; v->
Next() !=
nullptr; v = v->
Next()) u = v;
3670 bool occupied = IsRailStationPlatformOccupied(tile);
3690 static const DirDiff delta[] = {
3708 }
while ((v = v->
Next()) !=
nullptr);
3725 if (state <= 200 &&
Chance16R(1, 7, r)) {
3726 int index = (r * 10 >> 16);
3740 }
while ((u = u->
Next()) !=
nullptr);
3746 bool ret = v->
Next() !=
nullptr;
3756 225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, 15
3771 uint x = v->
x_pos & 0xF;
3772 uint y = v->
y_pos & 0xF;
3777 case DIR_N : x = ~x + ~y + 25;
break;
3778 case DIR_NW: x = y; FALLTHROUGH;
3779 case DIR_NE: x = ~x + 16;
break;
3780 case DIR_E : x = ~x + y + 9;
break;
3781 case DIR_SE: x = y;
break;
3782 case DIR_S : x = x + y - 7;
break;
3783 case DIR_W : x = ~y + x + 9;
break;
3802 if (break_speed < v->cur_speed) v->
cur_speed = break_speed;
3855 !CheckCompatibleRail(v, tile)) {
3879 if (break_speed < v->cur_speed) v->
cur_speed = break_speed;
3921 static bool TrainLocoHandler(
Train *v,
bool mode)
3928 if (v->force_proceed !=
TFP_NONE) {
3998 if (v->force_proceed ==
TFP_NONE)
return true;
4036 if (j < adv_spd || v->cur_speed == 0)
break;
4040 if ((order_type == OT_GOTO_WAYPOINT || order_type == OT_GOTO_STATION) &&
4050 for (
Train *u = v; u !=
nullptr; u = u->
Next()) {
4068 const Train *v =
this;
4072 if (e->u.rail.running_cost_class == INVALID_PRICE)
continue;
4075 if (cost_factor == 0)
continue;
4080 cost +=
GetPrice(e->u.rail.running_cost_class, cost_factor, e->
GetGRF());
4101 if (!TrainLocoHandler(
this,
false))
return false;
4103 return TrainLocoHandler(
this,
true);
4131 default: NOT_REACHED();
4169 CheckVehicleBreakdown(
this);
int GetDisplayImageWidth(Point *offset=nullptr) const
Get the width of a train vehicle image in the GUI.
@ VSE_START
Vehicle starting, i.e. leaving, the station.
This class will save the current order of a vehicle and restore it on destruction.
bool lost_vehicle_warn
if a vehicle can't find its destination, show a warning
T * GetNextVehicle() const
Get the next real (non-articulated part) vehicle in the consist.
@ VETS_STATION_ID_OFFSET
Shift the VehicleEnterTileStatus this many bits to the right to get the station ID when VETS_ENTERED_...
static DiagDirection VehicleExitDir(Direction direction, TrackBits track)
Determine the side in which the vehicle will leave the tile.
bool IsPrimaryVehicle() const override
Whether this is the primary vehicle in the chain.
void SetTrainGroupID(Train *v, GroupID grp)
Affect the groupID of a train to new_g.
bool m_is_station
last turn passed station
@ EF_RAIL_TILTS
Rail vehicle tilts in curves.
@ TRACK_BIT_MASK
Bitmask for the first 6 bits.
void DeleteNewGRFInspectWindow(GrfSpecFeature feature, uint index)
Delete inspect window for a given feature and index.
static Trackdir FindFirstTrackdir(TrackdirBits trackdirs)
Returns first Trackdir from TrackdirBits or INVALID_TRACKDIR.
bool okay
True if tile is a safe waiting position, false otherwise.
@ VRF_TOGGLE_REVERSE
Used for vehicle var 0xFE bit 8 (toggled each time the train is reversed, accurate for first vehicle ...
StationFacility facilities
The facilities that this station has.
@ TRACK_BIT_WORMHOLE
Bitflag for a wormhole (used for tunnels)
static const EngineID INVALID_ENGINE
Constant denoting an invalid engine.
byte VehicleOrderID
The index of an order within its current vehicle (not pool related)
FindDepotData NPFTrainFindNearestDepot(const Train *v, int max_penalty)
Used when user sends train to the nearest depot or if train needs servicing using NPF.
uint32 GetGRFID() const
Retrieve the GRF ID of the NewGRF the engine is tied to.
uint StoredCount() const
Returns sum of cargo on board the vehicle (ie not only reserved).
NPFSettings npf
pathfinder settings for the new pathfinder
static bool HasReservedTracks(TileIndex tile, TrackBits tracks)
Check whether some of tracks is reserved on a tile.
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 MakeDummy()
Makes this order a Dummy order.
@ PROP_TRAIN_SPEED
Max. speed: 1 unit = 1/1.6 mph = 1 km-ish/h.
@ TRACK_BIT_NONE
No track.
byte wait_for_pbs_path
how long to wait for a path reservation.
uint16 GetMaxWeight() const override
Calculates the weight value that this vehicle will have when fully loaded with its current cargo.
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 ArrangeTrains(Train **dst_head, Train *dst, Train **src_head, Train *src, bool move_chain)
Arrange the trains in the wanted way.
static bool Chance16(const uint a, const uint b)
Flips a coin with given probability.
static CommandCost CheckNewTrain(Train *original_dst, Train *dst, Train *original_src, Train *src)
Check/validate whether we may actually build a new train.
@ CCF_CAPACITY
Allow vehicles to change capacity.
bool IsType(OrderType type) const
Check whether this order is of the given type.
int Height() const
Get height of Rect.
static Titem * Get(size_t index)
Returns Titem with given index.
static TileIndexDiff TileOffsByDiagDir(DiagDirection dir)
Convert a DiagDirection to a TileIndexDiff.
Direction
Defines the 8 directions on the map.
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
VehicleSpriteSeq sprite_seq
Vehicle appearance.
uint GetPlatformLength(TileIndex tile, DiagDirection dir) const override
Determines the REMAINING length of a platform, starting at (and including) the given tile.
Money GetPrice(Price index, uint cost_factor, const GRFFile *grf_file, int shift)
Determine a certain price.
static uint GB(const T x, const uint8 s, const uint8 n)
Fetch n bits from x, started at bit s.
@ NT_ARRIVAL_OTHER
First vehicle arrived for competitor.
Money value
Value of the vehicle.
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.
uint8 train_acceleration_model
realistic acceleration for trains
@ DIRDIFF_45LEFT
Angle of 45 degrees left.
static Direction ChangeDir(Direction d, DirDiff delta)
Change a direction by a given difference.
static BridgeType GetBridgeType(TileIndex t)
Determines the type of bridge on a tile.
int GetAcceleration() const
Calculates the acceleration of the vehicle under its current conditions.
static CommandCost CmdBuildRailWagon(DoCommandFlag flags, TileIndex tile, const Engine *e, Vehicle **ret)
Build a railroad wagon.
Helper container to find a depot.
static Trackdir RemoveFirstTrackdir(TrackdirBits *trackdirs)
Removes first Trackdir from TrackdirBits and returns it.
TrackdirBits
Enumeration of bitmasks for the TrackDirs.
static bool IsRailWaypointTile(TileIndex t)
Is this tile a station tile and a rail waypoint?
TileIndex m_old_tile
the origin (vehicle moved from) before move
bool forbid_90_deg
forbid trains to make 90 deg turns
@ ODTFB_SERVICE
This depot order is because of the servicing limit.
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
static void MaybeBarCrossingWithSound(TileIndex tile)
Bars crossing and plays ding-ding sound if not barred already.
bool cached_tilt
train can tilt; feature provides a bonus in curves
@ PROP_TRAIN_RUNNING_COST_FACTOR
Yearly runningcost (if dualheaded: sum of both vehicles)
byte small_turn
Speed change due to a small turn.
Money GetRunningCost() const override
Get running cost for the train consist.
bool HasVehicleOnPos(TileIndex tile, void *data, VehicleFromPosProc *proc)
Checks whether a vehicle is on a specific location.
int GetCurrentMaxSpeed() const override
Calculates the maximum speed of the vehicle under its current conditions.
void CheckOrders(const Vehicle *v)
Check the orders of a vehicle, to see if there are invalid orders and stuff.
@ GVF_SUPPRESS_IMPLICIT_ORDERS
Disable insertion and removal of automatic orders until the vehicle completes the real order.
uint16 reliability_spd_dec
Speed of reliability decay between services (per day).
EngineID first_engine
Cached EngineID of the front vehicle. INVALID_ENGINE for the front vehicle itself.
void LeaveStation()
Perform all actions when leaving a station.
void ClearFreeWagon()
Clear a vehicle from being a free wagon.
static FindDepotData FindClosestTrainDepot(Train *v, int max_distance)
Try to find a depot nearby.
Vehicle * Next() const
Get the next vehicle of this vehicle.
Year _cur_year
Current year, starting at 0.
T * Next() const
Get next vehicle in the chain.
void CheckConsistencyOfArticulatedVehicle(const Vehicle *v)
Checks whether the specs of freshly build articulated vehicles are consistent with the information sp...
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.
@ DIRDIFF_SAME
Both directions faces to the same direction.
byte y_extent
y-extent of vehicle bounding box
Axis
Allow incrementing of DiagDirDiff variables.
DestinationID GetDestination() const
Gets the destination of this order.
bool NeedsAutomaticServicing() const
Checks if the current order should be interrupted for a service-in-depot order.
int cached_curve_speed_mod
curve speed modifier of the entire train
VehicleOrderID ProcessConditionalOrder(const Order *order, const Vehicle *v)
Process a conditional order and determine the next order.
static void UpdateStatusAfterSwap(Train *v)
Updates some variables after swapping the vehicle.
void Set(SpriteID sprite)
Assign a single sprite to the sequence.
static Axis DiagDirToAxis(DiagDirection d)
Convert a DiagDirection to the axis.
static bool IsDiagonalDirection(Direction dir)
Checks if a given Direction is diagonal.
bool reverse
True if reversing is necessary for the train to get to this depot.
static CommandCost CheckTrainAttachment(Train *t)
Check whether the train parts can be attached.
@ RAIL_TILE_SIGNALS
Normal rail tile with signals.
@ SAT_TRAIN_ARRIVES
Trigger platform when train arrives.
byte random_bits
Bits used for determining which randomized variational spritegroups to use when drawing.
std::string name
Name of vehicle.
static void NormaliseTrainHead(Train *head)
Normalise the head of the train again, i.e.
@ DIAGDIR_END
Used for iterations.
void ClearFrontEngine()
Remove the front engine state.
@ VPF_YAPF
Yet Another PathFinder.
@ TRACK_BEGIN
Used for iterations.
bool SwitchToNextOrder(bool skip_first)
Set the current vehicle order to the next order in the order list.
@ VS_DEFPAL
Use default vehicle palette.
uint16 DepotID
Type for the unique identifier of depots.
bool YapfTrainCheckReverse(const Train *v)
Returns true if it is better to reverse the train before leaving station using YAPF.
Tindex index
Index of this pool item.
void SetNext(Vehicle *next)
Set the next vehicle of this vehicle.
@ VRF_POWEREDWAGON
Wagon is powered.
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo ID.
uint16 crash_anim_pos
Crash animation counter.
byte acceleration
used by train & aircraft
static void MakeTrainBackup(TrainList &list, Train *t)
Make a backup of a train into a train list.
void AddArticulatedParts(Vehicle *first)
Add the remaining articulated parts to the given vehicle.
static bool HasPowerOnRail(RailType enginetype, RailType tiletype)
Checks if an engine of the given RailType got power on a tile with a given RailType.
@ TRACK_X
Track along the x-axis (north-east to south-west)
PBSTileInfo FollowTrainReservation(const Train *v, Vehicle **train_on_res)
Follow a train reservation to the last tile.
@ OSL_PLATFORM_MIDDLE
Stop at the middle of the platform.
GroupID group_id
Index of group Pool array.
void Free()
'Free' the order
static void InsertInConsist(Train *dst, Train *chain)
Inserts a chain into the train at dst.
int UpdateSpeed()
This function looks at the vehicle and updates its speed (cur_speed and subspeed) variables.
AccelStatus GetAccelerationStatus() const
Checks the current acceleration status of this vehicle.
static T KillFirstBit(T value)
Clear the first bit in an integer.
DifficultySettings difficulty
settings related to the difficulty
static bool HasBit(const T x, const uint8 y)
Checks if a bit in a value is set.
static void CountVehicle(const Vehicle *v, int delta)
Update num_vehicle when adding or removing a vehicle.
static constexpr TileIndex INVALID_TILE
The very nice invalid tile marker.
static int UnScaleGUI(int value)
Short-hand to apply GUI zoom level.
@ SIGNAL_STATE_GREEN
The signal is green.
This struct contains all the info that is needed to draw and construct tracks.
static Trackdir DiagDirToDiagTrackdir(DiagDirection diagdir)
Maps a (4-way) direction to the diagonal trackdir that runs in that direction.
static T ClrBit(T &x, const uint8 y)
Clears a bit in a variable.
static bool IsCompatibleTrainStationTile(TileIndex test_tile, TileIndex station_tile)
Check if a tile is a valid continuation to a railstation tile.
bool wagon_speed_limits
enable wagon speed limits
void HideFillingPercent(TextEffectID *te_id)
Hide vehicle loading indicators.
static bool TracksOverlap(TrackBits bits)
Checks if the given tracks overlap, ie form a crossing.
Vehicle * next
pointer to the next vehicle in the chain
const GRFFile * GetGRF() const
Retrieve the NewGRF the vehicle is tied to.
static bool IsValidDiagDirection(DiagDirection d)
Checks if an integer value is a valid DiagDirection.
static void SetCrossingReservation(TileIndex t, bool b)
Set the reservation state of the rail crossing.
static void RestoreTrainBackup(TrainList &list)
Restore the train from the backup list.
void InvalidateNewGRFInspectWindow(GrfSpecFeature feature, uint index)
Invalidate the inspect window for a given feature and index.
static const uint TILE_SIZE
Tile size in world coordinates.
@ VRF_EL_ENGINE_ALLOWED_NORMAL_RAIL
Electric train engine is allowed to run on normal rail. */.
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 AddVehicleNewsItem(StringID string, NewsType type, VehicleID vehicle, StationID station=INVALID_STATION)
Adds a newsitem referencing a vehicle.
byte running_ticks
Number of ticks this vehicle was not stopped this day.
static TrackBits GetTrackBits(TileIndex tile)
Gets the track bits of the given tile.
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.
static Station * Get(size_t index)
Gets station with given index.
static DirDiff DirDifference(Direction d0, Direction d1)
Calculate the difference between two directions.
ClientSettings _settings_client
The current settings for this game.
static bool HasSignals(TileIndex t)
Checks if a rail tile has signals.
void VehicleEnterDepot(Vehicle *v)
Vehicle entirely entered the depot, update its status, orders, vehicle windows, service it,...
void VehicleLengthChanged(const Vehicle *u)
Logs a bug in GRF and shows a warning message if this is for the first time this happened.
@ WC_VEHICLE_TIMETABLE
Vehicle timetable; Window numbers:
static uint TileY(TileIndex tile)
Get the Y component of a tile.
uint16 power
Power of engine (hp); For multiheaded engines the sum of both engine powers.
Date GetLifeLengthInDays() const
Returns the vehicle's (not model's!) life length in days.
bool NPFTrainCheckReverse(const Train *v)
Returns true if it is better to reverse the train before leaving station using NPF.
static bool Rail90DegTurnDisallowed(RailType rt1, RailType rt2, bool def=_settings_game.pf.forbid_90_deg)
Test if 90 degree turns are disallowed between two railtypes.
bool IsRearDualheaded() const
Tell if we are dealing with the rear end of a multiheaded engine.
@ VS_TRAIN_SLOWING
Train is slowing down.
@ WC_COMPANY
Company view; Window numbers:
@ EV_EXPLOSION_SMALL
Various explosions.
static void NormaliseDualHeads(Train *t)
Normalise the dual heads in the train, i.e.
EngineImageType
Visualisation contexts of vehicles and engines.
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.
uint16 cur_speed
current speed
@ RAILTYPES_NONE
No rail types.
@ VETS_ENTERED_STATION
The vehicle entered a station.
CargoID GetDefaultCargoType() const
Determines the default cargo type of an engine.
void Draw(int x, int y, PaletteID default_pal, bool force_pal) const
Draw the sprite sequence.
Owner owner
Which company owns the vehicle?
bool TryPathReserve(Train *v, bool mark_as_stuck, bool first_tile_okay)
Try to reserve a path to a safe position.
Owner
Enum for all companies/owners.
uint16 speed
maximum travel speed (1 unit = 1/1.6 mph = 1 km-ish/h)
@ EV_EXPLOSION_LARGE
Various explosions.
uint16 GetVehicleCallback(CallbackID callback, uint32 param1, uint32 param2, EngineID engine, const Vehicle *v)
Evaluate a newgrf callback for vehicles.
@ DC_EXEC
execute the given command
~VehicleOrderSaver()
Restore the saved order to the vehicle, if Restore() has not already been called.
static Vehicle * FindTrainCollideEnum(Vehicle *v, void *data)
Collision test function.
@ CBM_VEHICLE_ARTIC_ENGINE
Add articulated engines (trains and road vehicles)
static const AccelerationSlowdownParams _accel_slowdown[]
Speed update fractions for each acceleration type.
void DeleteVehicleOrders(Vehicle *v, bool keep_orderlist, bool reset_order_indices)
Delete all orders from a vehicle.
static void SetDParam(uint n, uint64 v)
Set a string parameter v at index n in the global string parameter array.
OrderStopLocation
Where to stop the trains.
DoCommandFlag
List of flags for a command.
void VehicleServiceInDepot(Vehicle *v)
Service a vehicle and all subsequent vehicles in the consist.
void SetWagon()
Set a vehicle to be a wagon.
static DiagDirection GetRailDepotDirection(TileIndex t)
Returns the direction the depot is facing to.
static bool HasPbsSignalOnTrackdir(TileIndex tile, Trackdir td)
Is a pbs signal present along the trackdir?
static PBSTileInfo ExtendTrainReservation(const Train *v, TrackBits *new_tracks, DiagDirection *enterdir)
Extend a train path as far as possible.
@ TRACK_BIT_UPPER
Upper track.
bool m_is_bridge
last turn passed bridge ramp
static TrackBits TrackToTrackBits(Track track)
Maps a Track to the corresponding TrackBits value.
bool TryReserveRailTrack(TileIndex tile, Track t, bool trigger_stations)
Try to reserve a specific track on a tile.
static uint TileX(TileIndex tile)
Get the X component of a tile.
static void SwapTrainFlags(uint16 *swap_flag1, uint16 *swap_flag2)
Swap the two up/down flags in two ways:
void ShowErrorMessage(StringID summary_msg, StringID detailed_msg, WarningLevel wl, int x=0, int y=0, const GRFFile *textref_stack_grffile=nullptr, uint textref_stack_size=0, const uint32 *textref_stack=nullptr)
Display an error message in a window.
@ SIGTYPE_PBS
normal pbs signal
TrackStatus GetTileTrackStatus(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
Returns information about trackdirs and signal states.
bool IsArticulatedPart() const
Check if the vehicle is an articulated part of an engine.
@ TRACK_BIT_RIGHT
Right track.
static bool CheckTrainCollision(Train *v)
Checks whether the specified train has a collision with another vehicle.
void MakeGoToDepot(DepotID destination, OrderDepotTypeFlags order, OrderNonStopFlags non_stop_type=ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS, OrderDepotActionFlags action=ODATF_SERVICE_ONLY, CargoID cargo=CT_NO_REFIT)
Makes this order a Go To Depot order.
@ PFE_GL_TRAINS
Time spent processing trains.
OrderType GetType() const
Get the type of order of this order.
static Vehicle * TrainOnTileEnum(Vehicle *v, void *)
Check if the vehicle is a train.
uint16 GetMaxSpeed() const
Get the maxmimum speed in km-ish/h a vehicle is allowed to reach on the way to the destination.
uint32 SpriteID
The number of a sprite, without mapping bits and colourtables.
@ GVF_GOINGDOWN_BIT
Vehicle is currently going downhill. (Cached track information for acceleration)
OrderStopLocation GetStopLocation() const
Where must we stop at the platform?
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.
void MarkDirty() override
Goods at the consist have changed, update the graphics, cargo, and acceleration.
void RemoveVehicleFromGroup(const Vehicle *v)
Decrease the num_vehicle variable before delete an front engine from a group.
@ CBM_VEHICLE_LENGTH
Vehicle length (trains and road vehicles)
@ GBUG_VEH_CAPACITY
Capacity of vehicle changes when not refitting or arranging.
byte wait_oneway_signal
waitingtime in days before a oneway signal
void SetSignalsOnBothDir(TileIndex tile, Track track, Owner owner)
Update signals at segments that are at both ends of given (existent or non-existent) track.
bool ambient
Play ambient, industry and town sounds.
const GRFFile * GetGRF() const
Retrieve the NewGRF the engine is tied to.
int traininfo_vehicle_pitch
Vertical offset for drawing train images in depot GUI and vehicle details.
@ NT_ARRIVAL_COMPANY
First vehicle arrived for company.
static const RailtypeInfo * GetRailTypeInfo(RailType railtype)
Returns a pointer to the Railtype information for a given railtype.
void SetWindowWidgetDirty(WindowClass cls, WindowNumber number, byte widget_index)
Mark a particular widget in a particular window as dirty (in need of repainting)
static void NormaliseSubtypes(Train *chain)
Normalise the sub types of the parts in this chain.
@ ENGINE_EXCLUSIVE_PREVIEW
This vehicle is in the exclusive preview stage, either being used or being offered to a company.
@ VRF_LEAVING_STATION
Train is just leaving a station.
uint Crash(bool flooded=false) override
The train vehicle crashed! Update its status and other parts around it.
@ ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS
The vehicle will not stop at any stations it passes except the destination.
static const BridgeSpec * GetBridgeSpec(BridgeType i)
Get the specification of a bridge type.
OrderNonStopFlags GetNonStopType() const
At which stations must we stop?
bool UpdateOrderDest(Vehicle *v, const Order *order, int conditional_depth, bool pbs_look_ahead)
Update the vehicle's destination tile from an order.
void BeginLoading()
Prepare everything to begin the loading when arriving at a station.
PathfinderSettings pf
settings for all pathfinders
static TrackdirBits TrackdirReachesTrackdirs(Trackdir trackdir)
Maps a trackdir to the trackdirs that can be reached from it (ie, when entering the next tile.
byte breakdown_ctr
Counter for managing breakdown events.
@ VS_HIDDEN
Vehicle is not visible.
uint16 EngineID
Unique identification number of an engine.
void UnreserveRailTrack(TileIndex tile, Track t)
Lift the reservation of a specific track on a tile.
uint best_length
The distance towards the depot in penalty, or UINT_MAX if not found.
std::vector< Train * > TrainList
Helper type for lists/vectors of trains.
void OnNewDay() override
Update day counters of the train vehicle.
byte wait_twoway_signal
waitingtime in days before a twoway signal
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.
Information about a rail vehicle.
@ TRANSPORT_RAIL
Transport by train.
CommandCost CheckOwnership(Owner owner, TileIndex tile)
Check whether the current owner owns something.
uint16 cached_total_length
Length of the whole vehicle (valid only for the first engine).
TileIndex dest_tile
Heading for this tile.
static DiagDirection DirToDiagDir(Direction dir)
Convert a Direction to a DiagDirection.
void HandlePathfindingResult(bool path_found)
Handle the pathfinding result, especially the lost status.
static const uint16 _breakdown_speeds[16]
Maximum speeds for train that is broken down or approaching line end.
static Track TrackBitsToTrack(TrackBits tracks)
Converts TrackBits to Track.
#define return_cmd_error(errcode)
Returns from a function with a specific StringID as error.
bool IsWaitingPositionFree(const Train *v, TileIndex tile, Trackdir trackdir, bool forbid_90deg)
Check if a safe position is free.
static uint MapSize()
Get the size of the map.
static void NewEvent(CompanyID company, ScriptEvent *event)
Queue a new event for an AI.
static bool IsBridgeTile(TileIndex t)
checks if there is a bridge on this tile
CommandCost CmdMoveRailVehicle(DoCommandFlag flags, VehicleID src_veh, VehicleID dest_veh, bool move_chain)
Move a rail vehicle around inside the depot.
Common return value for all commands.
@ TRACK_Y
Track along the y-axis (north-west to south-east)
Iterable ensemble of each set bit in a value.
static bool CheckTrainStayInDepot(Train *v)
Will the train stay in the depot the next tick?
@ VRF_TRAIN_STUCK
Train can't get a path reservation.
Trackdir GetVehicleTrackdir() const override
Get the tracks of the train vehicle.
Date _date
Current date in days (day counter)
void UpdateTrainGroupID(Train *v)
Recalculates the groupID of a train.
@ WC_VEHICLE_VIEW
Vehicle view; Window numbers:
void UpdateDeltaXY() override
Updates the x and y offsets and the size of the sprite used for this vehicle.
SoundSettings sound
sound effect settings
void AddToShared(Vehicle *shared_chain)
Adds this vehicle to a shared vehicle chain.
FindDepotData YapfTrainFindNearestDepot(const Train *v, int max_distance)
Used when user sends train to the nearest depot or if train needs servicing using YAPF.
void SetMultiheaded()
Set a vehicle as a multiheaded engine.
TileArea train_station
Tile area the train 'station' part covers.
Track NPFTrainChooseTrack(const Train *v, bool &path_found, bool reserve_track, struct PBSTileInfo *target)
Finds the best path for given train using NPF.
static const VehicleOrderID INVALID_VEH_ORDER_ID
Invalid vehicle order index (sentinel)
@ DIRDIFF_90LEFT
Angle of 90 degrees left.
static TrackdirBits TrackBitsToTrackdirBits(TrackBits bits)
Converts TrackBits to TrackdirBits while allowing both directions.
@ GVF_GOINGUP_BIT
Vehicle is currently going uphill. (Cached track information for acceleration)
static RailTileType GetRailTileType(TileIndex t)
Returns the RailTileType (normal with or without signals, waypoint or depot).
int32 TileIndexDiff
An offset value between two tiles.
void SubtractMoneyFromCompanyFract(CompanyID company, const CommandCost &cst)
Subtract money from a company, including the money fraction.
TileIndex tile
Current tile index.
static void DeleteLastWagon(Train *v)
Deletes/Clears the last wagon of a crashed train.
@ SIGNAL_STATE_RED
The signal is red.
static const VehicleID INVALID_VEHICLE
Constant representing a non-existing vehicle.
static DiagDirection TrackdirToExitdir(Trackdir trackdir)
Maps a trackdir to the (4-way) direction the tile is exited when following that trackdir.
EngineID engine_type
The type of engine used for this vehicle.
This struct contains information about the end of a reserved path.
byte path_backoff_interval
ticks between checks for a free path.
uint8 cached_veh_length
Length of this vehicle in units of 1/VEHICLE_LENGTH of normal length. It is cached because this can b...
@ VS_CRASHED
Vehicle is crashed.
@ VETS_CANNOT_ENTER
The vehicle cannot enter the tile.
Sprite sequence for a vehicle part.
static T SB(T &x, const uint8 s, const uint8 n, const U d)
Set n bits in x starting at bit s to d.
@ SND_41_DEPARTURE_MAGLEV
65 == 0x41 Station departure: maglev engine
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).
StationID last_station_visited
The last station we stopped at.
ClientID
'Unique' identifier to be given to clients
UnitID GetFreeUnitNumber(VehicleType type)
Get an unused unit number for a vehicle (if allowed).
uint32 maximum_go_to_depot_penalty
What is the maximum penalty that may be endured for going to a depot.
void SetDestination(DestinationID destination)
Sets the destination of this order.
VehicleCargoList cargo
The cargo this vehicle is carrying.
void CheckTrainsLengths()
Checks if lengths of all rail vehicles are valid.
bool Failed() const
Did this command fail?
@ CCF_ARRANGE
Valid changes for arranging the consist in a depot.
Order current_order
The current order (+ status, like: loading)
uint16 cached_max_track_speed
Maximum consist speed (in internal units) limited by track type (valid only for the first engine).
void Restore()
Restore the saved order to the vehicle.
bool IsChainInDepot() const override
Check whether the whole vehicle chain is in the depot.
Trackdir trackdir
The reserved trackdir on the tile.
static bool HasSignalOnTrackdir(TileIndex tile, Trackdir trackdir)
Checks for the presence of signals along the given trackdir on the given rail tile.
void NormalizeTrainVehInDepot(const Train *u)
Move all free vehicles in the depot to the train.
GroundVehicleCache gcache
Cache of often calculated values.
static int ScaleSpriteTrad(int value)
Scale traditional pixel dimensions to GUI zoom level, for drawing sprites.
@ RAILTYPES_RAIL
Non-electrified rails.
void SetFrontEngine()
Set front engine state.
@ HVOT_TRAIN
Station has seen a train.
bool IsFrontEngine() const
Check if the vehicle is a front engine.
@ ODATFB_NEAREST_DEPOT
Send the vehicle to the nearest depot.
static bool HasDepotReservation(TileIndex t)
Get the reservation state of the depot.
GameSettings _settings_game
Game settings of a running game or the scenario editor.
static void CheckIfTrainNeedsService(Train *v)
Check whether a train needs service, and if so, find a depot or service it.
static Track DiagDirToDiagTrack(DiagDirection diagdir)
Maps a (4-way) direction to the diagonal track incidating with that diagdir.
@ DC_AUTOREPLACE
autoreplace/autorenew is in progress, this shall disable vehicle limits when building,...
@ WC_VEHICLE_DETAILS
Vehicle details; Window numbers:
static void NewEvent(class ScriptEvent *event)
Queue a new event for a Game Script.
static bool HandleCrashedTrain(Train *v)
Handle a crashed train.
static TrackdirBits TrackdirCrossesTrackdirs(Trackdir trackdir)
Maps a trackdir to all trackdirs that make 90 deg turns with it.
static bool IsCrossingBarred(TileIndex t)
Check if the level crossing is barred.
@ VS_STOPPED
Vehicle is stopped by the player.
uint32 GetGRFID() const
Retrieve the GRF ID of the NewGRF the vehicle is tied to.
void ShowVisualEffect() const
Draw visual effects (smoke and/or sparks) for a vehicle chain.
static void SetSignalStateByTrackdir(TileIndex tile, Trackdir trackdir, SignalState state)
Sets the state of the signal along the given trackdir.
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
const Engine * GetEngine() const
Retrieves the engine of the vehicle.
@ TRACK_BIT_X
X-axis track.
VehicleEnterTileStatus VehicleEnterTile(Vehicle *v, TileIndex tile, int x, int y)
Call the tile callback function for a vehicle entering a tile.
static bool TrainApproachingLineEnd(Train *v, bool signal, bool reverse)
Train is approaching line end, slow down and possibly reverse.
static TrackBits DiagdirReachesTracks(DiagDirection diagdir)
Returns all tracks that can be reached when entering a tile from a given (diagonal) direction.
static bool IsRailDepotTile(TileIndex t)
Is this tile rail tile and a rail depot?
void CopyVehicleConfigAndStatistics(const Vehicle *src)
Copy certain configurations and statistics of a vehicle after successful autoreplace/renew The functi...
void SetLastSpeed()
Update the GUI variant of the current speed of the vehicle.
@ SIGSEG_PBS
Segment is a PBS segment.
TileIndex new_tile
Tile of the vehicle after moving.
uint16 reliability_spd_dec
Reliability decrease speed.
StationID last_loading_station
Last station the vehicle has stopped at and could possibly leave from with any cargo loaded.
'Train' is either a loco or a wagon.
static Direction DiagDirToDir(DiagDirection dir)
Convert a DiagDirection to a Direction.
Money GetCost() const
The costs as made up to this moment.
static const GroupID DEFAULT_GROUP
Ungrouped vehicles are in this group.
byte FreightWagonMult(CargoID cargo)
Return the cargo weight multiplier to use for a rail vehicle.
static TileIndex TileAddByDiagDir(TileIndex tile, DiagDirection dir)
Adds a DiagDir to a tile.
static DiagDirection ReverseDiagDir(DiagDirection d)
Returns the reverse direction of the given DiagDirection.
static bool HasOnewaySignalBlockingTrackdir(TileIndex tile, Trackdir td)
Is a one-way signal blocking the trackdir? A one-way signal on the trackdir against will block,...
static bool IsBridge(TileIndex t)
Checks if this is a bridge, instead of a tunnel.
Money profit_this_year
Profit this year << 8, low 8 bits are fract.
StringID GetGRFStringID(uint32 grfid, StringID stringid)
Returns the index for this stringid associated with its grfID.
static bool IsTileOwner(TileIndex tile, Owner owner)
Checks if a tile belongs to the given owner.
fluid_settings_t * settings
FluidSynth settings handle.
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.
uint16 callback_mask
Bitmask of vehicle callbacks that have to be called.
uint16 GetVehicleCallbackParent(CallbackID callback, uint32 param1, uint32 param2, EngineID engine, const Vehicle *v, const Vehicle *parent)
Evaluate a newgrf callback for vehicles with a different vehicle for parent scope.
bool _networking
are we in networking mode?
@ INVALID_DIAGDIR
Flag for an invalid DiagDirection.
@ VRF_REVERSE_DIRECTION
Reverse the visible direction of the vehicle.
CommandCost CmdReverseTrainDirection(DoCommandFlag flags, VehicleID veh_id, bool reverse_single_veh)
Reverse train.
@ MP_TUNNELBRIDGE
Tunnel entry/exit and bridge heads.
static void CheckNextTrainTile(Train *v)
Check if the train is on the last reserved tile and try to extend the path then.
bool TrainOnCrossing(TileIndex tile)
Check if a level crossing tile has a train on it.
@ INVALID_TRACKDIR
Flag for an invalid trackdir.
CommandCost CmdForceTrainProceed(DoCommandFlag flags, VehicleID veh_id)
Force a train through a red signal.
bool disaster
Play disaster and accident sounds.
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.
Coordinates of a point in 2D.
static bool HasCrossingReservation(TileIndex t)
Get the reservation state of the rail crossing.
DirDiff
Enumeration for the difference between two directions.
void CheckCargoCapacity(Vehicle *v)
Check the capacity of all vehicles in a chain and spread cargo if needed.
void MarkBridgeDirty(TileIndex begin, TileIndex end, DiagDirection direction, uint bridge_height)
Mark bridge tiles dirty.
DiagDirection
Enumeration for diagonal directions.
@ WC_TRAINS_LIST
Trains list; Window numbers:
ConsistChangeFlags
Flags for Train::ConsistChanged.
void HandleLoading(bool mode=false)
Handle the loading of the vehicle; when not it skips through dummy orders and does nothing in all oth...
SigSegState
State of the signal segment.
EffectVehicle * CreateEffectVehicleRel(const Vehicle *v, int x, int y, int z, EffectVehicleType type)
Create an effect vehicle above a particular vehicle.
@ SND_0E_LEVEL_CROSSING
12 == 0x0C Train passes through level crossing
uint traininfo_vehicle_width
Width (in pixels) of a 8/8 train vehicle in depot GUI and vehicle details.
Data structure for storing engine speed changes of an acceleration type.
static bool IsRailStationTile(TileIndex t)
Is this tile a station tile and a rail station?
void AddCost(const Money &cost)
Adds the given cost to the cost of the command.
@ TRACK_BIT_LOWER
Lower track.
bool show_track_reservation
highlight reserved tracks.
static void AffectSpeedByZChange(Train *v, int old_z)
Modify the speed of the vehicle due to a change in altitude.
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.
uint16 vehicle_flags
Used for gradual loading and other miscellaneous things (.
static bool IsOnewaySignal(TileIndex t, Track track)
One-way signals can't be passed the 'wrong' way.
MutableSpriteCache sprite_cache
Cache of sprites and values related to recalculating them, see MutableSpriteCache.
uint16 pow_wag_power
Extra power applied to consist if wagon should be powered.
SoundFx
Sound effects from baseset.
byte misc_flags
Miscellaneous flags.
int8 y_offs
y offset for vehicle sprite
SpriteID colourmap
NOSAVE: cached colour mapping.
static DiagDirection AxisToDiagDir(Axis a)
Converts an Axis to a DiagDirection.
static void RemoveFromConsist(Train *part, bool chain=false)
Remove the given wagon from its consist.
@ OSL_PLATFORM_NEAR_END
Stop at the near end of the platform.
RailTypes powered_railtypes
bitmask to the OTHER railtypes on which an engine of THIS railtype generates power
static bool IsTileType(TileIndex tile, TileType type)
Checks if a tile is a given tiletype.
@ RAILVEH_WAGON
simple wagon, not motorized
static void SetDepotReservation(TileIndex t, bool b)
Set the reservation state of the depot.
@ WC_VEHICLE_REFIT
Vehicle refit; Window numbers:
static DiagDirection GetTunnelBridgeDirection(TileIndex t)
Get the direction pointing to the other end.
void ReserveTrackUnderConsist() const
Tries to reserve track under whole train consist.
static void UpdateLevelCrossingTile(TileIndex tile, bool sound, bool force_barred)
Sets a level crossing tile to the correct state.
void IncrementRealOrderIndex()
Advanced cur_real_order_index to the next real order, keeps care of the wrap-around and invalidates t...
static Owner GetTileOwner(TileIndex tile)
Returns the owner of a tile.
@ VF_BUILT_AS_PROTOTYPE
Vehicle is a prototype (accepted as exclusive preview).
Trackdir m_old_td
the trackdir (the vehicle was on) before move
@ VIWD_CONSIST_CHANGED
Vehicle composition was changed.
Direction direction
facing
int GetCurveSpeedLimit() const
Computes train speed limit caused by curves.
Temporary data storage for testing collisions.
static TrackdirBits DiagdirReachesTrackdirs(DiagDirection diagdir)
Returns all trackdirs that can be reached when entering a tile from a given (diagonal) direction.
@ TRACK_BIT_DEPOT
Bitflag for a depot.
uint8 pathfinder_for_trains
the pathfinder to use for trains
@ RAILTYPE_RAIL
Standard non-electric rails.
VehicleOrderID cur_real_order_index
The index to the current real (non-implicit) order.
@ ONSF_NO_STOP_AT_DESTINATION_STATION
The vehicle will stop at any station it passes except the destination.
static bool TrainCanLeaveTile(const Train *v)
Determines whether train would like to leave the tile.
TileIndex tile
Tile the path ends, INVALID_TILE if no valid path was found.
bool ProcessOrders(Vehicle *v)
Handle the orders of a vehicle and determine the next place to go to if needed.
static Direction ReverseDir(Direction d)
Return the reverse of a direction.
byte x_extent
x-extent of vehicle bounding box
uint16 wait_counter
Ticks waiting in front of a signal, ticks being stuck or a counter for forced proceeding through sign...
uint8 acceleration_type
Acceleration type of this rail type.
static const uint CALLBACK_FAILED
Different values for Callback result evaluations.
uint32 StringID
Numeric value that represents a string, independent of the selected language.
@ TRACKDIR_BIT_NONE
No track build.
static bool IsCompatibleRail(RailType enginetype, RailType tiletype)
Checks if an engine of the given RailType can drive on a tile with a given RailType.
VehicleCache vcache
Cache of often used vehicle values.
CompanyID _current_company
Company currently doing an action.
int UpdateInclination(bool new_tile, bool update_delta)
Checks if the vehicle is in a slope and sets the required flags in that case.
std::vector< Train * > TrainList
Helper type for lists/vectors of trains.
@ NT_ACCIDENT
An accident or disaster has occurred.
@ PROP_TRAIN_WEIGHT
Weight in t (if dualheaded: for each single vehicle)
static void AdvanceWagonsBeforeSwap(Train *v)
Advances wagons for train reversing, needed for variable length wagons.
static T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
static const uint VEHICLE_LENGTH
The length of a vehicle in tile units.
static const PaletteID PALETTE_CRASH
Recolour sprite greying of crashed vehicles.
@ PROP_TRAIN_SHORTEN_FACTOR
Shorter vehicles.
uint16 max_speed
Maximum speed (1 unit = 1/1.6 mph = 1 km-ish/h)
byte tick_counter
Increased by one for each tick.
@ OSL_PLATFORM_FAR_END
Stop at the far end of the platform.
@ SND_0A_DEPARTURE_TRAIN
8 == 0x08 Station departure: diesel and electric engine
uint16 cargo_cap
total capacity
@ TRACK_BIT_LEFT
Left track.
uint32 cached_power
Total power of the consist (valid only for the first engine).
UnitID max_trains
max trains in game per company
static bool IsPlainRail(TileIndex t)
Returns whether this is plain rails, with or without signals.
int8 x_offs
x offset for vehicle sprite
byte subspeed
fractional speed
static DiagDirection DiagdirBetweenTiles(TileIndex tile_from, TileIndex tile_to)
Determines the DiagDirection to get from one tile to another.
@ FACIL_TRAIN
Station with train station.
static Train * From(Vehicle *v)
Converts a Vehicle to SpecializedVehicle with type checking.
@ DIRDIFF_45RIGHT
Angle of 45 degrees right.
void ConsistChanged(ConsistChangeFlags allowed_changes)
Recalculates the cached stuff of a train.
byte z_extent
z-extent of vehicle bounding box
void SetEngine()
Set engine status.
static Axis GetRailStationAxis(TileIndex t)
Get the rail direction of a rail station.
byte VehicleRandomBits()
Get a value for a vehicle's random_bits.
byte z_up
Fraction to remove when moving up.
static void AdvanceWagonsAfterSwap(Train *v)
Advances wagons for train reversing, needed for variable length wagons.
void UpdateAcceleration()
Update acceleration of the train from the cached power and weight.
static bool IsTunnel(TileIndex t)
Is this a tunnel (entrance)?
TileIndex tile
The base tile of the area.
uint32 PaletteID
The number of the palette.
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.
@ DC_NO_CARGO_CAP_CHECK
when autoreplace/autorenew is in progress, this shall prevent truncating the amount of cargo in the v...
static bool CheckLevelCrossing(TileIndex tile)
Check if a level crossing should be barred.
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...
bool NPFTrainFindNearestSafeTile(const Train *v, TileIndex tile, Trackdir trackdir, bool override_railtype)
Try to extend the reserved path of a train to the nearest safe tile using NPF.
void FreeTrainTrackReservation(const Train *v)
Free the reserved path in front of a vehicle.
bool IsEngine() const
Check if a vehicle is an engine (can be first in a consist).
static void SetTunnelBridgeReservation(TileIndex t, bool b)
Set the reservation state of the rail tunnel/bridge.
static SignalState GetSignalStateByTrackdir(TileIndex tile, Trackdir trackdir)
Gets the state of the signal along the given trackdir.
void SetFreeWagon()
Set a vehicle as a free wagon.
@ RAILVEH_MULTIHEAD
indicates a combination of two locomotives
uint32 current_order_time
How many ticks have passed since this order started.
void MarkTileDirtyByTile(TileIndex tile, int bridge_level_offset, int tile_height_override)
Mark a tile given by its index dirty for repaint.
@ SND_13_TRAIN_COLLISION
15 == 0x11 Train+train crash
@ SND_47_DEPARTURE_MONORAIL
71 == 0x47 Station departure: monorail engine
static TileIndexDiff TileDiffXY(int x, int y)
Calculates an offset for the given coordinate(-offset).
byte user_def_data
Property 0x25: "User-defined bit mask" Used only for (very few) NewGRF vehicles.
static RailType GetRailType(TileIndex t)
Gets the rail type of the given tile.
Position information of a vehicle after it moved.
@ WC_VEHICLE_DEPOT
Depot view; Window numbers:
static TrackdirBits TrackStatusToRedSignals(TrackStatus ts)
Returns the red-signal-information of a TrackStatus.
@ VE_DISABLE_WAGON_POWER
Flag to disable wagon power.
@ MP_STATION
A tile of a station.
@ SND_04_DEPARTURE_STEAM
2 == 0x02 Station departure: steam engine
static StationID GetStationIndex(TileIndex t)
Get StationID from a tile.
static Axis GetCrossingRailAxis(TileIndex t)
Get the rail axis of a level crossing.
Year build_year
Year the vehicle has been built.
void FindVehicleOnPos(TileIndex tile, void *data, VehicleFromPosProc *proc)
Find a vehicle from a specific location.
static bool CanAllocateItem(size_t n=1)
Helper functions so we can use PoolItem::Function() instead of _poolitem_pool.Function()
bool UsesWagonOverride(const Vehicle *v)
Check if a wagon is currently using a wagon override.
CommandCost CmdBuildRailVehicle(DoCommandFlag flags, TileIndex tile, const Engine *e, Vehicle **ret)
Build a railroad vehicle.
bool FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse) override
Locate the closest depot for this consist, and return the information to the caller.
@ DIAGDIR_BEGIN
Used for iterations.
static const int DAYS_IN_YEAR
days per year
static 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...
static TrackdirBits TrackStatusToTrackdirBits(TrackStatus ts)
Returns the present-trackdir-information of a TrackStatus.
RailType railtype
Railtype, mangled if elrail is disabled.
static Vehicle * TrainApproachingCrossingEnum(Vehicle *v, void *data)
Checks if a train is approaching a rail-road crossing.
TileIndex tile
The tile of the depot.
bool reverse_at_signals
whether to reverse at signals at all
@ DIRDIFF_90RIGHT
Angle of 90 degrees right.
TileIndex xy
Base tile of the station.
uint num
Total number of victims if train collided.
UnitID unitnumber
unit number, for display purposes only
bool line_reverse_mode
reversing at stations or not
@ SIGSEG_FULL
Occupied by a train.
static Train * GetIfValid(size_t index)
Returns vehicle if the index is a valid index for this vehicle type.
static 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...
Train * v
Vehicle we are testing for collision.
uint16 cached_max_speed
Maximum speed of the consist (minimum of the max speed of all vehicles in the consist).
static Track GetRailDepotTrack(TileIndex t)
Returns the track of a depot, ignoring direction.
static Track FindFirstTrack(TrackBits tracks)
Returns first Track from TrackBits or INVALID_TRACK.
static Pool::IterateWrapper< Train > Iterate(size_t from=0)
Returns an iterable ensemble of all valid vehicles of type T.
static bool IsLevelCrossingTile(TileIndex t)
Return whether a tile is a level crossing tile.
int cached_max_curve_speed
max consist speed limited by curves
uint8 original_image_index
Original vehicle image index, thus the image index of the overridden vehicle.
TileIndex old_tile
Current tile of the vehicle.
int8 x_bb_offs
x offset of vehicle bounding box
@ EXPENSES_NEW_VEHICLES
New vehicles.
TileIndex m_new_tile
the new tile (the vehicle has entered)
byte large_turn
Speed change due to a large turn.
bool PlayVehicleSound(const Vehicle *v, VehicleSoundEvent event, bool force)
Checks whether a NewGRF wants to play a different vehicle sound effect.
static T abs(const T a)
Returns the absolute value of (scalar) variable.
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 GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const override
Get the sprite to display the train.
void TriggerStationRandomisation(Station *st, TileIndex trigger_tile, StationRandomTrigger trigger, CargoID cargo_type)
Trigger station randomisation.
uint32 VehicleID
The type all our vehicle IDs have.
void CDECL error(const char *s,...)
Error handling for fatal non-user errors.
OrderDepotTypeFlags GetDepotOrderType() const
What caused us going to the depot?
void InvalidateNewGRFCache()
Invalidates cached NewGRF variables.
byte shorten_factor
length on main map for this type is 8 - shorten_factor
static void AddVehicleAdviceNewsItem(StringID string, VehicleID vehicle)
Adds a vehicle-advice news item.
TrackBits
Bitfield corresponding to Track.
void UpdateAdjacentLevelCrossingTilesOnLevelCrossingRemoval(TileIndex tile, Axis road_axis)
Update adjacent level crossing tiles in this multi-track crossing, due to removal of a level crossing...
byte day_counter
Increased by one for each day.
void FindVehicleOnPosXY(int x, int y, void *data, VehicleFromPosProc *proc)
Find a vehicle from a specific location.
int TicksToLeaveDepot(const Train *v)
Compute number of ticks when next wagon will leave a depot.
static T ToggleBit(T &x, const uint8 y)
Toggles a bit in a variable.
static T SetBit(T &x, const uint8 y)
Set a bit in a variable.
#define lengthof(x)
Return the length of an fixed size array.
bool Follow(TileIndex old_tile, Trackdir old_td)
main follower routine.
static TrackBits DiagDirToDiagTrackBits(DiagDirection diagdir)
Maps a (4-way) direction to the diagonal track bits incidating with that diagdir.
static void Backup(const Vehicle *v, uint32 user)
Create an order backup for the given vehicle.
YAPFSettings yapf
pathfinder settings for the yet another pathfinder
@ EXPENSES_TRAIN_RUN
Running costs trains.
void AgeVehicle(Vehicle *v)
Update age of a vehicle.
byte progress
The percentage (if divided by 256) this vehicle already crossed the tile unit.
RailTypes compatible_railtypes
bitmask to the OTHER railtypes on which an engine of THIS railtype can physically travel
uint DetermineCapacity(const Vehicle *v, uint16 *mail_capacity=nullptr) const
Determines capacity of a given vehicle from scratch.
DiagDirection m_exitdir
exit direction (leaving the old tile)
byte CargoID
Cargo slots to indicate a cargo type within a game.
bool IsStoppedInDepot() const
Check whether the vehicle is in the depot and stopped.
void CloseWindowById(WindowClass cls, WindowNumber number, bool force)
Close a window by its class and window number (if it is open).
static bool IsPlainRailTile(TileIndex t)
Checks whether the tile is a rail tile or rail tile with signals.
static uint TrainCrashed(Train *v)
Marks train as crashed and creates an AI event.
TrackdirBits m_new_td_bits
the new set of available trackdirs
@ TFP_SIGNAL
Ignore next signal, after the signal ignore being stuck.
@ CCF_LENGTH
Allow vehicles to change length.
@ EF_RAIL_FLIPS
Rail vehicle has old depot-flip handling.
void CargoChanged()
Recalculates the cached weight of a vehicle and its parts.
static bool Chance16R(const uint a, const uint b, uint32 &r)
Flips a coin with a given probability and saves the randomize-number in a variable.
RailType GetTileRailType(TileIndex tile)
Return the rail type of tile, or INVALID_RAILTYPE if this is no rail tile.
CommandCost CmdSellRailWagon(DoCommandFlag flags, Vehicle *t, bool sell_chain, bool backup_order, ClientID user)
Sell a (single) train wagon/engine.
TileIndex GetOrderStationLocation(StationID station) override
Get the location of the next station to visit.
CargoID cargo_type
type of cargo this vehicle is carrying
static bool TrainCheckIfLineEnds(Train *v, bool reverse=true)
Checks for line end.
uint8 max_train_length
maximum length for trains
byte spritenum
currently displayed sprite index 0xfd == custom sprite, 0xfe == custom second head sprite 0xff == res...
Train * GetNextUnit() const
Get the next real (non-articulated part and non rear part of dualheaded engine) vehicle in the consis...
static Axis GetCrossingRoadAxis(TileIndex t)
Get the road axis of a level crossing.
static TileIndex GetOtherTunnelBridgeEnd(TileIndex t)
Determines type of the wormhole and returns its other end.
static Trackdir ReverseTrackdir(Trackdir trackdir)
Maps a trackdir to the reverse trackdir.
T * GetLastEnginePart()
Get the last part of an articulated engine.
bool IsWagon() const
Check if a vehicle is a wagon.
byte running_cost
Running cost of engine; For multiheaded engines the sum of both running costs.
@ TRACK_BIT_Y
Y-axis track.
@ CBID_VEHICLE_LENGTH
Vehicle length, returns the amount of 1/8's the vehicle is shorter for trains and RVs.
int CalcNextVehicleOffset() const
Calculate the offset from this vehicle's center to the following center taking the vehicle lengths in...
@ CCF_TRACK
Valid changes while vehicle is driving, and possibly changing tracks.
VehicleSettings vehicle
options for vehicles
void ErrorUnknownCallbackResult(uint32 grfid, uint16 cbid, uint16 cb_res)
Record that a NewGRF returned an unknown/invalid callback result.
T * Previous() const
Get previous vehicle in the chain.
Trackdir
Enumeration for tracks and directions.
static bool TrainApproachingCrossing(TileIndex tile)
Finds a vehicle approaching rail-road crossing.
byte cargo_subtype
Used for livery refits (NewGRF variations)
@ TFP_NONE
Normal operation.
bool IsFreeWagon() const
Check if the vehicle is a free wagon (got no engine in front of it).
@ TFP_STUCK
Proceed till next signal, but ignore being stuck till then. This includes force leaving depots.
static TrackBits TrackCrossesTracks(Track track)
Maps a track to all tracks that make 90 deg turns with it.
@ VEH_TRAIN
Train vehicle type.
static Vehicle * CollectTrackbitsFromCrashedVehiclesEnum(Vehicle *v, void *data)
Collect trackbits of all crashed train vehicles on a tile.
uint32 maximum_go_to_depot_penalty
What is the maximum penalty that may be endured for going to a depot.
uint GetAdvanceDistance()
Determines the vehicle "progress" needed for moving a step.
byte capacity
Cargo capacity of vehicle; For multiheaded engines the capacity of each single engine.
Order * GetOrder(int index) const
Returns order 'index' of a vehicle or nullptr when it doesn't exists.
VehicleType type
Type of vehicle.
bool Tick() override
Update train vehicle data for a tick.
uint16 reliability
Reliability.
Train * First() const
Get the first vehicle in the chain.
static void SetCrossingBarred(TileIndex t, bool barred)
Set the bar state of a level crossing.
void UpdatePosition()
Update the position of the vehicle.
static void Swap(T &a, T &b)
Type safe swap operation.
byte flags
Flags of the engine.
@ AS_BRAKE
We want to stop.
int Width() const
Get width of Rect.
Track
These are used to specify a single track.
bool HandleBreakdown()
Handle all of the aspects of a vehicle breakdown This includes adding smoke and sounds,...
void DecreaseVehicleValue(Vehicle *v)
Decrease the value of a vehicle.
int8 y_bb_offs
y offset of vehicle bounding box
int y
x and y position of the vehicle after moving
static void ChangeTrainDirRandomly(Train *v)
Rotate all vehicles of a (crashed) train chain randomly to animate the crash.
static TrackBits TrackdirBitsToTrackBits(TrackdirBits bits)
Discards all directional information from a TrackdirBits value.
@ PROP_TRAIN_CARGO_AGE_PERIOD
Number of ticks before carried cargo is aged.
void MarkDirtyAdjacentLevelCrossingTiles(TileIndex tile, Axis road_axis)
Find adjacent level crossing tiles in this multi-track crossing and mark them dirty.
uint8 freight_trains
value to multiply the weight of cargo by
Specification of a rectangle with absolute coordinates of all edges.
uint Crash(bool flooded) override
Common code executed for crashed ground vehicles.
@ PM_PAUSED_ERROR
A game paused because a (critical) error.
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.
#define FIND_FIRST_BIT(x)
Returns the first non-zero bit in a 6-bit value (from right).
VehicleOrderID GetNumOrders() const
Get the number of orders this vehicle has.
T * Last()
Get the last vehicle in the chain.
uint DoUpdateSpeed(uint accel, int min_speed, int max_speed)
Update the speed of the vehicle.
OrderList * orders
Pointer to the order list for this vehicle.
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting)
void GetBounds(Rect *bounds) const
Determine shared bounds of all sprites.
OrderDepotActionFlags GetDepotActionType() const
What are we going to do when in the depot.
bool reserve_paths
always reserve paths regardless of signal type.
bool TrainController(Train *v, Vehicle *nomove, bool reverse=true)
Move a vehicle chain one movement stop forwards.
Vehicle * first
NOSAVE: pointer to the first vehicle in the chain.
static bool IsValidTrackdir(Trackdir trackdir)
Checks if a Trackdir is valid for non-road vehicles.
void UpdateViewport(bool force_update, bool update_delta)
Update vehicle sprite- and position caches.
TextEffectID fill_percent_te_id
a text-effect id to a loading indicator object
@ SRT_TRAIN_ARRIVES
Trigger platform when train arrives.
uint16 cargo_age_period
Number of ticks before carried cargo is aged.
uint32 cached_weight
Total weight of the consist (valid only for the first engine).
byte curve_speed
Multiplier for curve maximum speed advantage.
static void MarkTrainAsStuck(Train *v)
Mark a train as stuck and stop it if it isn't stopped right now.
static const int DAY_TICKS
1 day is 74 ticks; _date_fract used to be uint16 and incremented by 885.
void ReverseTrainSwapVeh(Train *v, int l, int r)
Swap vehicles l and r in consist v, and reverse their direction.
Track follower helper template class (can serve pathfinders and vehicle controllers).
int m_tiles_skipped
number of skipped tunnel or station tiles
static DepotID GetDepotIndex(TileIndex t)
Get the index of which depot is attached to the tile.
T * GetFirstEnginePart()
Get the first part of an articulated engine.
bool m_is_tunnel
last turn passed tunnel
CommandCost TunnelBridgeIsFree(TileIndex tile, TileIndex endtile, const Vehicle *ignore)
Finds vehicle in tunnel / bridge.
static Track TrackdirToTrack(Trackdir trackdir)
Returns the Track that a given Trackdir represents.
static const StringID INVALID_STRING_ID
Constant representing an invalid string (16bit in case it is used in savegames)
@ WC_VEHICLE_ORDERS
Vehicle orders; Window numbers:
GUISettings gui
settings related to the GUI
@ PROP_TRAIN_USER_DATA
User defined data for vehicle variable 0x42.
uint16 reliability
Current reliability of the engine.
@ WL_CRITICAL
Critical errors, the MessageBox is shown in all cases.
void PlayLeaveStationSound(bool force=false) const override
Play a sound for a train leaving the station.
uint16 refit_cap
Capacity left over from before last refit.
bool IsMultiheaded() const
Check if the vehicle is a multiheaded engine.
Date date_of_last_service
Last date the vehicle had a service at a depot.
GetNewVehiclePosResult GetNewVehiclePos(const Vehicle *v)
Get position information of a vehicle when moving one pixel in the direction it is facing.
@ CBID_TRAIN_ALLOW_WAGON_ATTACH
Determine whether a wagon can be attached to an already existing train.
static TileIndex TileVirtXY(uint x, uint y)
Get a tile from the virtual XY-coordinate.
static TileIndex TrainApproachingCrossingTile(const Train *v)
Determines whether train is approaching a rail-road crossing (thus making it barred)
void ReverseTrainDirection(Train *v)
Turn a train around.
byte z_down
Fraction to add when moving down.
@ VETS_ENTERED_WORMHOLE
The vehicle either entered a bridge, tunnel or depot tile (this includes the last tile of the bridge/...
@ INVALID_TRACK
Flag for an invalid track.