OpenTTD Source
12.0-beta2
|
Go to the documentation of this file.
38 #include "table/strings.h"
50 static const byte _vehicle_initial_x_fract[4] = {10, 8, 4, 8};
51 static const byte _vehicle_initial_y_fract[4] = { 8, 4, 8, 10};
54 bool IsValidImageIndex<VEH_TRAIN>(uint8 image_index)
56 return image_index <
lengthof(_engine_sprite_base);
77 if (v->First() == v && !(v->vehstatus &
VS_CRASHED)) {
78 for (
const Train *u = v, *w = v->
Next(); w !=
nullptr; u = w, w = w->
Next()) {
81 std::max(
abs(u->x_pos - w->x_pos),
abs(u->y_pos - w->y_pos)) != u->CalcNextVehicleOffset()) ||
108 uint16 max_speed = UINT16_MAX;
117 bool train_can_tilt =
true;
118 int min_curve_speed_mod = INT_MAX;
120 for (
Train *u =
this; u !=
nullptr; u = u->
Next()) {
124 assert(u->First() ==
this);
127 u->gcache.first_engine =
this == u ?
INVALID_ENGINE : first_engine;
128 u->railtype = rvi_u->railtype;
130 if (u->IsEngine()) first_engine = u->engine_type;
135 u->InvalidateNewGRFCache();
138 for (
Train *u =
this; u !=
nullptr; u = u->
Next()) {
142 u->InvalidateNewGRFCache();
145 for (
Train *u =
this; u !=
nullptr; u = u->
Next()) {
146 const Engine *e_u = u->GetEngine();
150 min_curve_speed_mod = std::min(min_curve_speed_mod, u->GetCurveSpeedModifier());
153 u->tcache.cached_override = GetWagonOverrideSpriteSet(u->engine_type, u->cargo_type, u->gcache.first_engine);
156 u->colourmap = PAL_NONE;
159 u->UpdateVisualEffect(
true);
169 if (!u->IsArticulatedPart()) {
172 if (rvi_u->
power > 0) {
186 if (speed != 0) max_speed = std::min(speed, max_speed);
193 if (u->cargo_cap > new_cap) u->cargo.Truncate(new_cap);
194 u->refit_cap = std::min(new_cap, u->refit_cap);
195 u->cargo_cap = new_cap;
204 if (e_u->
GetGRF() !=
nullptr && e_u->
GetGRF()->grf_version >= 8) {
220 u->gcache.cached_veh_length = veh_len;
228 u->InvalidateNewGRFCache();
278 default: NOT_REACHED();
289 stop = *station_length;
305 assert(this->
First() ==
this);
307 static const int absolute_max_speed = UINT16_MAX;
308 int max_speed = absolute_max_speed;
312 int curvecount[2] = {0, 0};
319 for (
const Vehicle *u =
this; u->
Next() !=
nullptr; u = u->
Next(), pos++) {
321 Direction next_dir = u->Next()->direction;
331 sum += pos - lastpos;
332 if (pos - lastpos == 1 && max_speed > 88) {
345 if (numcurve > 0 && max_speed > 88) {
346 if (curvecount[0] == 1 && curvecount[1] == 1) {
347 max_speed = absolute_max_speed;
350 max_speed = 232 - (13 -
Clamp(sum, 1, 12)) * (13 -
Clamp(sum, 1, 12));
354 if (max_speed != absolute_max_speed) {
361 max_speed += max_speed / 5;
367 max_speed =
Clamp(max_speed, 2, absolute_max_speed);
392 int distance_to_go = station_ahead /
TILE_SIZE - (station_length - stop_at) /
TILE_SIZE;
394 if (distance_to_go > 0) {
395 int st_max_speed = 120;
397 int delta_v = this->
cur_speed / (distance_to_go + 1);
398 if (max_speed > (this->
cur_speed - delta_v)) {
399 st_max_speed = this->
cur_speed - (delta_v / 10);
402 st_max_speed = std::max(st_max_speed, 25 * distance_to_go);
403 max_speed = std::min(max_speed, st_max_speed);
408 for (
const Train *u =
this; u !=
nullptr; u = u->
Next()) {
410 max_speed = std::min(max_speed, 61);
442 int reference_width = TRAININFO_DEFAULT_VEHICLE_WIDTH;
443 int vehicle_pitch = 0;
446 if (e->
GetGRF() !=
nullptr && is_custom_sprite(e->u.rail.image_index)) {
451 if (offset !=
nullptr) {
460 assert(IsValidImageIndex<VEH_TRAIN>(
spritenum));
483 assert(IsValidImageIndex<VEH_TRAIN>(
spritenum));
498 GetCustomVehicleIcon(engine, dir, image_type, result);
500 if (e->
GetGRF() !=
nullptr) {
521 GetRailIcon(engine,
false, yf, image_type, &seqf);
522 GetRailIcon(engine,
true, yr, image_type, &seqr);
528 preferred_x =
Clamp(preferred_x,
536 GetRailIcon(engine,
false, y, image_type, &seq);
540 preferred_x =
Clamp(preferred_x,
562 GetRailIcon(engine,
false, y, image_type, &seq);
567 width =
UnScaleGUI(rect.right - rect.left + 1);
568 height =
UnScaleGUI(rect.bottom - rect.top + 1);
573 GetRailIcon(engine,
true, y, image_type, &seq);
578 height = std::max<uint>(height,
UnScaleGUI(rect.bottom - rect.top + 1));
579 xoffs = xoffs -
ScaleGUITrad(TRAININFO_DEFAULT_VEHICLE_WIDTH) / 2;
580 yoffs = std::min(yoffs,
UnScaleGUI(rect.top));
617 v->
z_pos = GetSlopePixelZ(x, y);
631 v->railtype = rvi->railtype;
642 _new_vehicle_id = v->
index;
652 if (w->tile ==
tile &&
654 w->engine_type == e->
index &&
671 if (v->IsFreeWagon() && v->tile == u->
tile &&
680 static void AddRearEngineToMultiheadedTrain(
Train *v)
698 u->railtype = v->railtype;
710 v->other_multiheaded_part = u;
711 u->other_multiheaded_part = v;
745 v->
z_pos = GetSlopePixelZ(x, y);
762 v->railtype = rvi->railtype;
763 _new_vehicle_id = v->
index;
782 AddRearEngineToMultiheadedTrain(v);
800 static Train *FindGoodVehiclePos(
const Train *src)
806 if (dst->IsFreeWagon() && dst->tile ==
tile && !(dst->vehstatus &
VS_CRASHED)) {
811 if (t ==
nullptr)
return dst;
829 for (; t !=
nullptr; t = t->
Next())
list.push_back(t);
839 if (
list.size() == 0)
return;
841 Train *prev =
nullptr;
844 if (prev !=
nullptr) {
846 }
else if (t->
Previous() !=
nullptr) {
899 if (u == t->other_multiheaded_part)
continue;
915 if (chain ==
nullptr)
return;
918 assert(chain->
Previous() ==
nullptr);
929 for (
Train *t = chain->
Next(); t !=
nullptr; t = t->
Next()) {
949 if ((src !=
nullptr && src->
IsEngine() ? 1 : 0) +
950 (dst !=
nullptr && dst->
IsEngine() ? 1 : 0) -
951 (original_src !=
nullptr && original_src->
IsEngine() ? 1 : 0) -
952 (original_dst !=
nullptr && original_dst->
IsEngine() ? 1 : 0) <= 0) {
980 while (t !=
nullptr) {
1000 while (t !=
nullptr) {
1032 if (head->
GetGRF()->grf_version < 8) {
1033 if (callback == 0xFD)
error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
1037 if (callback < 0x400) {
1047 error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
1081 if (ret.
Failed())
return ret;
1083 if (ret.
Failed())
return ret;
1100 if (*src_head == *dst_head) {
1103 *dst_head =
nullptr;
1104 }
else if (*dst_head ==
nullptr) {
1110 if (src == *src_head) {
1117 *src_head = move_chain ? nullptr :
1141 if (head ==
nullptr)
return;
1175 bool move_chain =
HasBit(p1, 20);
1181 if (ret.
Failed())
return ret;
1195 if (ret.
Failed())
return ret;
1203 if (dst !=
nullptr) {
1213 if (dst !=
nullptr) {
1214 dst_head = dst->
First();
1225 if (move_chain && src_head == dst_head)
return CommandCost();
1247 Train *original_src_head = src_head;
1248 Train *original_dst_head = (dst_head == src_head ? nullptr : dst_head);
1253 bool original_src_head_front_engine = original_src_head->
IsFrontEngine();
1254 bool original_dst_head_front_engine = original_dst_head !=
nullptr && original_dst_head->
IsFrontEngine();
1321 if (original_src_head != src && dst_head == src) {
1368 bool sell_chain =
HasBit(data, 0);
1382 Train *sell_head =
nullptr;
1385 ArrangeTrains(&sell_head,
nullptr, &new_head, v, sell_chain);
1402 for (
Train *part = sell_head; part !=
nullptr; part = part->
Next()) cost.
AddCost(-part->value);
1452 static const int _sign_table[] =
1465 this->
y_offs -= half_shorten * _sign_table[this->direction + 1];
1469 switch (this->direction) {
1534 uint16 flag1 = *swap_flag1;
1535 uint16 flag2 = *swap_flag2;
1602 for (a = v; l != 0; l--) a = a->
Next();
1603 for (b = v; r != 0; r--) b = b->
Next();
1613 Swap(a->track, b->track);
1702 if (new_state && sound) {
1736 uint length = CountVehiclesInChain(v);
1738 while (length > 2) {
1769 if (leave !=
nullptr) {
1785 uint length = CountVehiclesInChain(v);
1789 bool nomove = (dep ==
nullptr);
1791 while (length > 2) {
1794 if (base == dep)
break;
1797 if (last == dep) nomove =
true;
1829 int r = CountVehiclesInChain(v) - 1;
1847 ClrBit(v->flags, VRF_REVERSING);
1915 if (ret.
Failed())
return ret;
1921 return_cmd_error(STR_ERROR_CAN_T_REVERSE_DIRECTION_RAIL_VEHICLE_MULTIPLE_UNITS);
1948 while (last->
Next() !=
nullptr) last = last->
Next();
1990 if (ret.
Failed())
return ret;
2026 default: NOT_REACHED();
2042 if (location !=
nullptr) *location = tfdd.
tile;
2044 if (reverse !=
nullptr) *reverse = tfdd.
reverse;
2052 static const SoundFx sfx[] = {
2063 SndPlayVehicleFx(sfx[RailVehInfo(engtype)->engclass],
this);
2084 case OT_GOTO_WAYPOINT:
2090 case OT_LEAVESTATION:
2135 for (
const Train *u = v; u !=
nullptr; u = u->
Next()) {
2148 if (v->force_proceed ==
TFP_NONE) {
2264 for (
const Train *u = v; u !=
nullptr; u = u->
Next()) {
2307 static const byte _initial_tile_subcoord[6][4][3] = {
2308 {{ 15, 8, 1 }, { 0, 0, 0 }, { 0, 8, 5 }, { 0, 0, 0 }},
2309 {{ 0, 0, 0 }, { 8, 0, 3 }, { 0, 0, 0 }, { 8, 15, 7 }},
2310 {{ 0, 0, 0 }, { 7, 0, 2 }, { 0, 7, 6 }, { 0, 0, 0 }},
2311 {{ 15, 8, 2 }, { 0, 0, 0 }, { 0, 0, 0 }, { 8, 15, 6 }},
2312 {{ 15, 7, 0 }, { 8, 0, 4 }, { 0, 0, 0 }, { 0, 0, 0 }},
2313 {{ 0, 0, 0 }, { 0, 0, 0 }, { 0, 8, 4 }, { 7, 15, 0 }},
2334 default: NOT_REACHED();
2379 if (enterdir !=
nullptr) *enterdir = ft.
m_exitdir;
2396 if (ft.m_err == CFollowTrackRail::EC_OWNER || ft.m_err == CFollowTrackRail::EC_NO_WAY) {
2406 while (
tile != stopped || cur_td != stopped_td) {
2441 default: NOT_REACHED();
2451 StationID old_last_station_visited;
2453 bool suppress_implicit_orders;
2469 this->v->
dest_tile = this->old_dest_tile;
2483 if (skip_first) ++this->index;
2489 if (this->index >= this->v->
GetNumOrders()) this->index = 0;
2492 assert(order !=
nullptr);
2499 case OT_GOTO_STATION:
2500 case OT_GOTO_WAYPOINT:
2503 case OT_CONDITIONAL: {
2531 bool changed_signal =
false;
2535 if (got_reservation !=
nullptr) *got_reservation =
false;
2547 do_track_reservation =
true;
2548 changed_signal =
true;
2550 }
else if (!do_track_reservation) {
2558 if (do_track_reservation) {
2566 if (res_dest.okay) {
2568 if (got_reservation !=
nullptr) *got_reservation =
true;
2591 orders.SwitchToNextOrder(
false);
2596 orders.SwitchToNextOrder(
true);
2601 bool path_found =
true;
2604 Track next_track =
DoTrainPathfind(v, new_tile, dest_enterdir, tracks, path_found, do_track_reservation, &res_dest);
2605 if (new_tile == tile) best_track = next_track;
2610 if (!do_track_reservation)
return best_track;
2627 if (got_reservation !=
nullptr) *got_reservation =
true;
2636 if (got_reservation !=
nullptr) *got_reservation =
true;
2649 if (orders.SwitchToNextOrder(
true)) {
2652 DoTrainPathfind(v, next_tile, exitdir, reachable, path_found,
true, &cur_dest);
2654 res_dest = cur_dest;
2655 if (res_dest.okay)
continue;
2659 if (got_reservation !=
nullptr) *got_reservation =
false;
2660 changed_signal =
false;
2668 if (got_reservation !=
nullptr) *got_reservation =
false;
2669 changed_signal =
false;
2707 Vehicle *other_train =
nullptr;
2714 if (other_train !=
nullptr && other_train->
index != v->
index) {
2719 if (origin.
okay && (v->
tile != origin.
tile || first_tile_okay)) {
2738 bool res_made =
false;
2739 ChooseTrainTrack(v, new_tile, exitdir, reachable,
true, &res_made, mark_as_stuck);
2756 static bool CheckReverseTrain(
const Train *v)
2770 default: NOT_REACHED();
2800 }
while ((v = v->
Next()) !=
nullptr);
2817 default: NOT_REACHED();
2837 if (!(st->had_vehicle_of_type &
HVOT_TRAIN)) {
2841 STR_NEWS_FIRST_TRAIN_ARRIVAL,
2860 static inline bool CheckCompatibleRail(
const Train *v,
TileIndex tile)
2877 {256 / 4, 256 / 2, 256 / 4, 2},
2878 {256 / 4, 256 / 2, 256 / 4, 2},
2879 {0, 256 / 2, 256 / 4, 2},
2893 if (old_z < v->z_pos) {
2897 if (spd <= v->gcache.cached_max_track_speed) v->
cur_speed = spd;
2909 if (!IsPbsSignal(GetSignalType(tile,
TrackdirToTrack(trackdir))))
return true;
2918 for (
const Train *u =
this; u !=
nullptr; u = u->
Next()) {
2947 for (
const Train *v =
this; v !=
nullptr; v = v->
Next()) {
3021 if (coll == tcc->
v)
return nullptr;
3030 uint hash = (y_diff + 7) | (x_diff + 7);
3031 if (hash & ~15)
return nullptr;
3035 if (x_diff * x_diff + y_diff * y_diff > min_diff * min_diff)
return nullptr;
3074 if (tcc.
num == 0)
return false;
3079 ModifyStationRatingAround(v->
tile, v->
owner, -160, 30);
3110 bool direction_changed =
false;
3113 for (prev = v->
Previous(); v != nomove; prev = v, v = v->
Next()) {
3115 bool update_signals_crossing =
false;
3167 if (!CheckCompatibleRail(v, gp.
new_tile))
goto invalid_rail;
3170 if (prev ==
nullptr) {
3193 if ((red_signals & chosen_track) && v->force_proceed ==
TFP_NONE) {
3216 if (!
HasVehicleOnPos(o_tile, &exitdir, &CheckTrainAtSignal))
return false;
3229 goto reverse_train_direction;
3241 chosen_track = bits;
3243 chosen_track = prev->track;
3261 chosen_track = _connecting_track[enterdir][exitdir];
3263 chosen_track &= bits;
3273 const byte *b = _initial_tile_subcoord[
FIND_FIRST_BIT(chosen_track)][enterdir];
3274 gp.x = (gp.x & ~0xF) | b[0];
3275 gp.
y = (gp.
y & ~0xF) | b[1];
3301 v->track = chosen_track;
3307 update_signals_crossing =
true;
3315 direction_changed =
true;
3366 if (prev ==
nullptr) {
3371 if (update_signals_crossing) {
3373 if (TrainMovedChangeSignals(gp.
new_tile, enterdir)) {
3392 if (v->
Next() ==
nullptr) {
3408 if (prev !=
nullptr)
error(
"Disconnecting train");
3410 reverse_train_direction:
3437 *trackbits |= train_tbits;
3459 for (; v->
Next() !=
nullptr; v = v->
Next()) u = v;
3516 static const DirDiff delta[] = {
3534 }
while ((v = v->
Next()) !=
nullptr);
3551 if (state <= 200 &&
Chance16R(1, 7, r)) {
3552 int index = (r * 10 >> 16);
3566 }
while ((u = u->
Next()) !=
nullptr);
3572 bool ret = v->
Next() !=
nullptr;
3582 225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, 15
3597 uint x = v->
x_pos & 0xF;
3598 uint y = v->
y_pos & 0xF;
3603 case DIR_N : x = ~x + ~y + 25;
break;
3604 case DIR_NW: x = y; FALLTHROUGH;
3605 case DIR_NE: x = ~x + 16;
break;
3606 case DIR_E : x = ~x + y + 9;
break;
3607 case DIR_SE: x = y;
break;
3608 case DIR_S : x = x + y - 7;
break;
3609 case DIR_W : x = ~y + x + 9;
break;
3628 if (break_speed < v->cur_speed) v->
cur_speed = break_speed;
3681 !CheckCompatibleRail(v, tile)) {
3705 if (break_speed < v->cur_speed) v->
cur_speed = break_speed;
3747 static bool TrainLocoHandler(
Train *v,
bool mode)
3754 if (v->force_proceed !=
TFP_NONE) {
3824 if (v->force_proceed ==
TFP_NONE)
return true;
3862 if (j < adv_spd || v->cur_speed == 0)
break;
3866 if ((order_type == OT_GOTO_WAYPOINT || order_type == OT_GOTO_STATION) &&
3876 for (
Train *u = v; u !=
nullptr; u = u->
Next()) {
3894 const Train *v =
this;
3898 if (e->u.rail.running_cost_class == INVALID_PRICE)
continue;
3901 if (cost_factor == 0)
continue;
3906 cost +=
GetPrice(e->u.rail.running_cost_class, cost_factor, e->
GetGRF());
3927 if (!TrainLocoHandler(
this,
false))
return false;
3929 return TrainLocoHandler(
this,
true);
3957 default: NOT_REACHED();
3995 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_...
void GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const
Get the sprite to display the train.
static DiagDirection VehicleExitDir(Direction direction, TrackBits track)
Determine the side in which the vehicle will leave the tile.
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.
bool PlayVehicleSound(const Vehicle *v, VehicleSoundEvent event)
Checks whether a NewGRF wants to play a different vehicle sound effect.
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.
uint32 TileIndex
The index/ID of a Tile.
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.
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.
CommandCost DoCommand(const CommandContainer *container, DoCommandFlag flags)
Shorthand for calling the long DoCommand with a container.
@ CCF_CAPACITY
Allow vehicles to change capacity.
bool IsType(OrderType type) const
Check whether this order is of the given type.
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.
@ CMD_MOVE_RAIL_VEHICLE
move a rail vehicle (in the depot)
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.
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.
bool HasVehicleOnPos(TileIndex tile, void *data, VehicleFromPosProc *proc)
Checks whether a vehicle is on a specific location.
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.
@ TRANSPORT_RAIL
Transport by train.
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
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.
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 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.
bool FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
Locate the closest depot for this consist, and return the information to the caller.
static bool IsValidDiagDirection(DiagDirection d)
Checks if an integer value is a valid DiagDirection.
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.
CommandCost CmdBuildRailVehicle(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **ret)
Build a railroad vehicle.
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.
union Vehicle::@49 orders
The orders currently assigned to the vehicle.
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.
Trackdir GetVehicleTrackdir() const
Get the tracks of the train vehicle.
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
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 Succeeded() const
Did this command succeed?
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.
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?
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.
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.
int GetCurrentMaxSpeed() const
Calculates the maximum speed of the vehicle under its current conditions.
@ VRF_LEAVING_STATION
Train is just leaving a station.
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.
@ SIGTYPE_PBS
normal pbs signal
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.
byte wait_twoway_signal
waitingtime in days before a twoway signal
Information about a rail vehicle.
CommandCost CheckOwnership(Owner owner, TileIndex tile)
Check whether the current owner owns something.
bool IsValid() const
Check whether the sequence contains any sprites.
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 void NewEvent(CompanyID company, ScriptEvent *event)
Queue a new event for an AI.
static Track DoTrainPathfind(const Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool &path_found, bool do_track_reservation, PBSTileInfo *dest)
Perform pathfinding for a train.
static bool IsBridgeTile(TileIndex t)
checks if there is a bridge on this tile
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.
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:
SoundSettings sound
sound effect settings
void AddToShared(Vehicle *shared_chain)
Adds this vehicle to a shared vehicle chain.
bool DoCommandP(const CommandContainer *container, bool my_cmd)
Shortcut for the long DoCommandP when having a container with the data.
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)
@ CMD_PAUSE
pause the game
@ DIRDIFF_90LEFT
Angle of 90 degrees left.
byte callback_mask
Bitmask of vehicle callbacks that have to be called.
uint Crash(bool flooded=false)
The train vehicle crashed! Update its status and other parts around it.
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).
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.
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.
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?
CommandCost CmdMoveRailVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text)
Move a rail vehicle around inside the depot.
CommandCost CmdSellRailWagon(DoCommandFlag flags, Vehicle *t, uint16 data, uint32 user)
Sell a (single) train wagon/engine.
@ 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).
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.
GroundVehicleCache gcache
Cache of often calculated values.
@ 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.
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.
static const uint32 MAKE_ORDER_BACKUP_FLAG
Flag to pass to the vehicle construction command when an order should be preserved.
Money GetCost() const
The costs as made up to this moment.
TileIndex GetOrderStationLocation(StationID station)
Get the location of the next station to visit.
static const GroupID DEFAULT_GROUP
Ungrouped vehicles are in this group.
Track YapfTrainChooseTrack(const Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool &path_found, bool reserve_track, struct PBSTileInfo *target)
Finds the best path for given train using YAPF.
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 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.
void MarkDirty()
Goods at the consist have changed, update the graphics, cargo, and acceleration.
@ 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.
@ INVALID_TRACKDIR
Flag for an invalid trackdir.
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.
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.
OrderList * list
Pointer to the order list for this vehicle.
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.
void PlayLeaveStationSound() const
Play a sound for a train leaving the station.
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.
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.
void OnNewDay()
Update day counters of the train vehicle.
@ 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.
void UpdateDeltaXY()
Updates the x and y offsets and the size of the sprite used for this vehicle.
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.
byte VehicleRandomBits()
Get a value for a vehicle's random_bits.
static int ScaleGUITrad(int value)
Scale traditional pixel dimensions to GUI zoom level.
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...
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
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.
@ NT_ACCIDENT
An accident or disaster has occurred.
@ 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.
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 void BarCrossing(TileIndex t)
Bar a level crossing.
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
@ NT_ARRIVAL_COMPANY
First vehicle arrived for company.
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.
CommandCost CmdForceTrainProceed(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text)
Force a train through a red signal.
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 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.
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.
bool IsPrimaryVehicle() const
Whether this is the primary vehicle in the chain.
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 Tick()
Update train vehicle data for a tick.
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.
Money GetRunningCost() const
Get running cost for the train consist.
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.
static CommandCost CmdBuildRailWagon(TileIndex tile, DoCommandFlag flags, const Engine *e, Vehicle **ret)
Build a railroad wagon.
@ CCF_LENGTH
Allow vehicles to change length.
static const TileIndex INVALID_TILE
The very nice invalid tile marker.
@ EF_RAIL_FLIPS
Rail vehicle can be flipped in the depot.
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.
void UpdateLevelCrossing(TileIndex tile, bool sound)
Sets correct crossing state.
RailType GetTileRailType(TileIndex tile)
Return the rail type of tile, or INVALID_RAILTYPE if this is no rail tile.
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.
static void NormalizeTrainVehInDepot(const Train *u)
Move all free vehicles in the depot to the train.
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.
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.
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.
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.
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.
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.
CommandCost CmdReverseTrainDirection(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text)
Reverse train.
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.
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.