OpenTTD Source
20240917-master-g9ab0a47812
|
Go to the documentation of this file.
42 #include "table/strings.h"
54 static const uint8_t _vehicle_initial_x_fract[4] = {10, 8, 4, 8};
55 static const uint8_t _vehicle_initial_y_fract[4] = { 8, 4, 8, 10};
58 bool IsValidImageIndex<VEH_TRAIN>(uint8_t image_index)
60 return image_index <
lengthof(_engine_sprite_base);
81 if (v->First() == v && !(v->vehstatus &
VS_CRASHED)) {
82 for (
const Train *u = v, *w = v->
Next(); w !=
nullptr; u = w, w = w->
Next()) {
85 std::max(
abs(u->x_pos - w->x_pos),
abs(u->y_pos - w->y_pos)) != u->CalcNextVehicleOffset()) ||
112 uint16_t max_speed = UINT16_MAX;
121 bool train_can_tilt =
true;
122 int16_t min_curve_speed_mod = INT16_MAX;
124 for (
Train *u =
this; u !=
nullptr; u = u->
Next()) {
128 assert(u->First() ==
this);
131 u->gcache.first_engine =
this == u ?
INVALID_ENGINE : first_engine;
134 if (u->IsEngine()) first_engine = u->engine_type;
139 u->InvalidateNewGRFCache();
142 for (
Train *u =
this; u !=
nullptr; u = u->
Next()) {
146 u->InvalidateNewGRFCache();
149 for (
Train *u =
this; u !=
nullptr; u = u->
Next()) {
150 const Engine *e_u = u->GetEngine();
154 min_curve_speed_mod = std::min(min_curve_speed_mod, u->GetCurveSpeedModifier());
157 u->tcache.cached_override = GetWagonOverrideSpriteSet(u->engine_type, u->cargo_type, u->gcache.first_engine);
160 u->colourmap = PAL_NONE;
163 u->UpdateVisualEffect(
true);
173 if (!u->IsArticulatedPart()) {
176 if (rvi_u->
power > 0) {
190 if (speed != 0) max_speed = std::min(speed, max_speed);
197 if (u->cargo_cap > new_cap) u->cargo.Truncate(new_cap);
198 u->refit_cap = std::min(new_cap, u->refit_cap);
199 u->cargo_cap = new_cap;
208 if (e_u->
GetGRF() !=
nullptr && e_u->
GetGRF()->grf_version >= 8) {
224 u->gcache.cached_veh_length = veh_len;
232 u->InvalidateNewGRFCache();
282 default: NOT_REACHED();
293 stop = *station_length;
309 assert(this->
First() ==
this);
311 static const int absolute_max_speed = UINT16_MAX;
312 int max_speed = absolute_max_speed;
316 int curvecount[2] = {0, 0};
325 Direction next_dir = u->Next()->direction;
335 sum += pos - lastpos;
336 if (pos - lastpos <=
static_cast<int>(
VEHICLE_LENGTH) && max_speed > 88) {
349 if (numcurve > 0 && max_speed > 88) {
350 if (curvecount[0] == 1 && curvecount[1] == 1) {
351 max_speed = absolute_max_speed;
355 max_speed = 232 - (13 -
Clamp(sum, 1, 12)) * (13 -
Clamp(sum, 1, 12));
359 if (max_speed != absolute_max_speed) {
366 max_speed += max_speed / 5;
372 max_speed =
Clamp(max_speed, 2, absolute_max_speed);
375 return static_cast<uint16_t
>(max_speed);
397 int distance_to_go = station_ahead /
TILE_SIZE - (station_length - stop_at) /
TILE_SIZE;
399 if (distance_to_go > 0) {
400 int st_max_speed = 120;
402 int delta_v = this->
cur_speed / (distance_to_go + 1);
403 if (max_speed > (this->
cur_speed - delta_v)) {
404 st_max_speed = this->
cur_speed - (delta_v / 10);
407 st_max_speed = std::max(st_max_speed, 25 * distance_to_go);
408 max_speed = std::min(max_speed, st_max_speed);
413 for (
const Train *u =
this; u !=
nullptr; u = u->
Next()) {
415 max_speed = std::min(max_speed, 61);
440 int Train::GetCursorImageOffset()
const
443 int reference_width = TRAININFO_DEFAULT_VEHICLE_WIDTH;
446 if (e->
GetGRF() !=
nullptr && is_custom_sprite(e->u.rail.image_index)) {
462 int reference_width = TRAININFO_DEFAULT_VEHICLE_WIDTH;
463 int vehicle_pitch = 0;
466 if (e->
GetGRF() !=
nullptr && is_custom_sprite(e->u.rail.image_index)) {
471 if (offset !=
nullptr) {
484 assert(IsValidImageIndex<VEH_TRAIN>(
spritenum));
502 if (result->IsValid())
return;
507 assert(IsValidImageIndex<VEH_TRAIN>(
spritenum));
519 uint8_t
spritenum = e->u.rail.image_index;
522 GetCustomVehicleIcon(engine, dir, image_type, result);
523 if (result->IsValid()) {
524 if (e->
GetGRF() !=
nullptr) {
545 GetRailIcon(engine,
false, yf, image_type, &seqf);
546 GetRailIcon(engine,
true, yr, image_type, &seqr);
552 preferred_x =
Clamp(preferred_x,
560 GetRailIcon(engine,
false, y, image_type, &seq);
564 preferred_x =
Clamp(preferred_x,
586 GetRailIcon(engine,
false, y, image_type, &seq);
597 GetRailIcon(engine,
true, y, image_type, &seq);
604 yoffs = std::min(yoffs,
UnScaleGUI(rect.top));
677 if (w->tile ==
tile &&
679 w->engine_type == e->
index &&
697 if (v->IsFreeWagon() && v->tile == u->
tile &&
706 static void AddRearEngineToMultiheadedTrain(
Train *v)
724 u->railtype = v->railtype;
738 v->other_multiheaded_part = u;
739 u->other_multiheaded_part = v;
811 AddRearEngineToMultiheadedTrain(v);
825 static Train *FindGoodVehiclePos(
const Train *src)
831 if (dst->IsFreeWagon() && dst->tile ==
tile && !(dst->vehstatus &
VS_CRASHED)) {
836 if (t ==
nullptr)
return dst;
854 for (; t !=
nullptr; t = t->
Next()) list.push_back(t);
864 if (list.empty())
return;
866 Train *prev =
nullptr;
868 for (
Train *t : list) {
869 if (prev !=
nullptr) {
871 }
else if (t->
Previous() !=
nullptr) {
924 if (u == t->other_multiheaded_part)
continue;
940 if (chain ==
nullptr)
return;
943 assert(chain->
Previous() ==
nullptr);
954 for (
Train *t = chain->
Next(); t !=
nullptr; t = t->
Next()) {
974 if ((src !=
nullptr && src->
IsEngine() ? 1 : 0) +
975 (dst !=
nullptr && dst->
IsEngine() ? 1 : 0) -
976 (original_src !=
nullptr && original_src->
IsEngine() ? 1 : 0) -
977 (original_dst !=
nullptr && original_dst->
IsEngine() ? 1 : 0) <= 0) {
1005 while (t !=
nullptr) {
1025 while (t !=
nullptr) {
1057 if (head->
GetGRF()->grf_version < 8) {
1058 if (callback == 0xFD) error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
1062 if (callback < 0x400) {
1072 error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
1106 if (ret.
Failed())
return ret;
1108 if (ret.
Failed())
return ret;
1125 if (*src_head == *dst_head) {
1128 *dst_head =
nullptr;
1129 }
else if (*dst_head ==
nullptr) {
1135 if (src == *src_head) {
1142 *src_head = move_chain ? nullptr :
1166 if (head ==
nullptr)
return;
1199 if (ret.
Failed())
return ret;
1213 if (ret.
Failed())
return ret;
1221 if (dst !=
nullptr) {
1231 if (dst !=
nullptr) {
1232 dst_head = dst->
First();
1243 if (move_chain && src_head == dst_head)
return CommandCost();
1265 Train *original_src_head = src_head;
1266 Train *original_dst_head = (dst_head == src_head ? nullptr : dst_head);
1271 bool original_src_head_front_engine = original_src_head->
IsFrontEngine();
1272 bool original_dst_head_front_engine = original_dst_head !=
nullptr && original_dst_head->
IsFrontEngine();
1281 ret =
ValidateTrains(original_dst_head, dst_head, original_src_head, src_head,
true);
1345 if (original_src_head != src && dst_head == src) {
1405 Train *sell_head =
nullptr;
1408 ArrangeTrains(&sell_head,
nullptr, &new_head, v, sell_chain);
1425 for (
Train *part = sell_head; part !=
nullptr; part = part->
Next()) cost.
AddCost(-part->value);
1485 static const int _sign_table[] =
1497 this->
x_offs -= half_shorten * _sign_table[dir];
1498 this->
y_offs -= half_shorten * _sign_table[dir + 1];
1567 uint16_t flag1 = *swap_flag1;
1568 uint16_t flag2 = *swap_flag2;
1635 for (a = v; l != 0; l--) a = a->
Next();
1636 for (b = v; r != 0; r--) b = b->
Next();
1646 Swap(a->track, b->track);
1777 bool forced_state = force_bar;
1828 bool occupied =
false;
1879 uint length = CountVehiclesInChain(v);
1881 while (length > 2) {
1912 if (leave !=
nullptr) {
1928 uint length = CountVehiclesInChain(v);
1932 bool nomove = (dep ==
nullptr);
1934 while (length > 2) {
1937 if (base == dep)
break;
1940 if (last == dep) nomove =
true;
1955 static bool IsWholeTrainInsideDepot(
const Train *v)
1957 for (
const Train *u = v; u !=
nullptr; u = u->
Next()) {
1970 if (IsWholeTrainInsideDepot(v))
return;
1981 int r = CountVehiclesInChain(v) - 1;
1999 ClrBit(v->flags, VRF_REVERSING);
2065 if (ret.
Failed())
return ret;
2067 if (reverse_single_veh) {
2071 return_cmd_error(STR_ERROR_CAN_T_REVERSE_DIRECTION_RAIL_VEHICLE_MULTIPLE_UNITS);
2098 while (last->
Next() !=
nullptr) last = last->
Next();
2140 if (ret.
Failed())
return ret;
2189 static const SoundFx sfx[] = {
2199 SndPlayVehicleFx(sfx[RailVehInfo(this->
engine_type)->engclass],
this);
2220 case OT_GOTO_WAYPOINT:
2226 case OT_LEAVESTATION:
2271 for (
const Train *u = v; u !=
nullptr; u = u->
Next()) {
2287 if (v->force_proceed ==
TFP_NONE) {
2404 for (
const Train *u = v; u !=
nullptr; u = u->
Next()) {
2452 static const uint8_t _initial_tile_subcoord[6][4][3] = {
2453 {{ 15, 8, 1 }, { 0, 0, 0 }, { 0, 8, 5 }, { 0, 0, 0 }},
2454 {{ 0, 0, 0 }, { 8, 0, 3 }, { 0, 0, 0 }, { 8, 15, 7 }},
2455 {{ 0, 0, 0 }, { 7, 0, 2 }, { 0, 7, 6 }, { 0, 0, 0 }},
2456 {{ 15, 8, 2 }, { 0, 0, 0 }, { 0, 0, 0 }, { 8, 15, 6 }},
2457 {{ 15, 7, 0 }, { 8, 0, 4 }, { 0, 0, 0 }, { 0, 0, 0 }},
2458 {{ 0, 0, 0 }, { 0, 0, 0 }, { 0, 8, 4 }, { 7, 15, 0 }},
2491 std::vector<std::pair<TileIndex, Trackdir>> signals_set_to_red;
2523 if (enterdir !=
nullptr) *enterdir = ft.
m_exitdir;
2536 signals_set_to_red.emplace_back(
tile, rev_td);
2548 signals_set_to_red.emplace_back(
tile, rev_td);
2554 if (ft.m_err == CFollowTrackRail::EC_OWNER || ft.m_err == CFollowTrackRail::EC_NO_WAY) {
2564 while (
tile != stopped || cur_td != stopped_td) {
2580 for (
auto [sig_tile, td] : signals_set_to_red) {
2609 StationID old_last_station_visited;
2611 bool suppress_implicit_orders;
2632 this->v->
dest_tile = this->old_dest_tile;
2635 this->restored =
true;
2643 if (!this->restored) this->
Restore();
2655 if (skip_first) ++this->index;
2661 if (this->index >= this->v->
GetNumOrders()) this->index = 0;
2664 assert(order !=
nullptr);
2671 case OT_GOTO_STATION:
2672 case OT_GOTO_WAYPOINT:
2675 case OT_CONDITIONAL: {
2703 bool changed_signal =
false;
2708 if (got_reservation !=
nullptr) *got_reservation =
false;
2720 do_track_reservation =
true;
2721 changed_signal =
true;
2723 }
else if (!do_track_reservation) {
2731 if (do_track_reservation) {
2739 if (res_dest.okay) {
2741 if (got_reservation !=
nullptr) *got_reservation =
true;
2764 orders.SwitchToNextOrder(
false);
2769 orders.SwitchToNextOrder(
true);
2774 bool path_found =
true;
2777 Track next_track =
DoTrainPathfind(v, new_tile, dest_enterdir, tracks, path_found, do_track_reservation, &res_dest, &final_dest);
2778 if (new_tile == tile) best_track = next_track;
2783 if (!do_track_reservation)
return best_track;
2800 if (got_reservation !=
nullptr) *got_reservation =
true;
2809 if (got_reservation !=
nullptr) *got_reservation =
true;
2822 if (orders.SwitchToNextOrder(
true)) {
2825 DoTrainPathfind(v, next_tile, exitdir, reachable, path_found,
true, &cur_dest,
nullptr);
2827 res_dest = cur_dest;
2828 if (res_dest.okay)
continue;
2832 if (got_reservation !=
nullptr) *got_reservation =
false;
2833 changed_signal =
false;
2841 if (got_reservation !=
nullptr) *got_reservation =
false;
2842 changed_signal =
false;
2889 Vehicle *other_train =
nullptr;
2896 if (other_train !=
nullptr && other_train->
index != v->
index) {
2901 if (origin.
okay && (v->
tile != origin.
tile || first_tile_okay)) {
2920 bool res_made =
false;
2921 ChooseTrainTrack(v, new_tile, exitdir, reachable,
true, &res_made, mark_as_stuck);
2938 static bool CheckReverseTrain(
const Train *v)
2977 }
while ((v = v->
Next()) !=
nullptr);
2994 default: NOT_REACHED();
3014 if (!(st->had_vehicle_of_type &
HVOT_TRAIN)) {
3018 STR_NEWS_FIRST_TRAIN_ARRIVAL,
3037 static inline bool CheckCompatibleRail(
const Train *v,
TileIndex tile)
3054 {256 / 4, 256 / 2, 256 / 4, 2},
3055 {256 / 4, 256 / 2, 256 / 4, 2},
3056 {0, 256 / 2, 256 / 4, 2},
3070 if (old_z < v->z_pos) {
3074 if (spd <= v->gcache.cached_max_track_speed) v->
cur_speed = spd;
3086 if (!IsPbsSignal(GetSignalType(tile,
TrackdirToTrack(trackdir))))
return true;
3095 for (
const Train *u =
this; u !=
nullptr; u = u->
Next()) {
3124 for (
const Train *v =
this; v !=
nullptr; v = v->
Next()) {
3160 victims = v->
Crash();
3162 Game::NewEvent(
new ScriptEventVehicleCrashed(v->
index, v->
tile, ScriptEventVehicleCrashed::CRASH_TRAIN, victims));
3198 if (coll == tcc->
v)
return nullptr;
3207 uint hash = (y_diff + 7) | (x_diff + 7);
3208 if (hash & ~15)
return nullptr;
3212 if (x_diff * x_diff + y_diff * y_diff > min_diff * min_diff)
return nullptr;
3251 if (tcc.
num == 0)
return false;
3256 ModifyStationRatingAround(v->
tile, v->
owner, -160, 30);
3287 bool direction_changed =
false;
3290 for (prev = v->
Previous(); v != nomove; prev = v, v = v->
Next()) {
3292 bool update_signals_crossing =
false;
3344 if (!CheckCompatibleRail(v, gp.
new_tile))
goto invalid_rail;
3347 if (prev ==
nullptr) {
3370 if ((red_signals & chosen_track) && v->force_proceed ==
TFP_NONE) {
3393 if (!
HasVehicleOnPos(o_tile, &exitdir, &CheckTrainAtSignal))
return false;
3406 goto reverse_train_direction;
3418 chosen_track = bits;
3420 chosen_track = prev->track;
3438 chosen_track = _connecting_track[enterdir][exitdir];
3440 chosen_track &= bits;
3450 const uint8_t *b = _initial_tile_subcoord[
FindFirstBit(chosen_track)][enterdir];
3451 gp.x = (gp.x & ~0xF) | b[0];
3452 gp.
y = (gp.
y & ~0xF) | b[1];
3478 v->track = chosen_track;
3484 update_signals_crossing =
true;
3492 direction_changed =
true;
3543 if (prev ==
nullptr) {
3548 if (update_signals_crossing) {
3550 if (TrainMovedChangeSignals(gp.
new_tile, enterdir)) {
3569 if (v->
Next() ==
nullptr) {
3585 if (prev !=
nullptr) FatalError(
"Disconnecting train");
3587 reverse_train_direction:
3614 *trackbits |= train_tbits;
3621 static bool IsRailStationPlatformOccupied(
TileIndex tile)
3650 for (; v->
Next() !=
nullptr; v = v->
Next()) u = v;
3694 bool occupied = IsRailStationPlatformOccupied(tile);
3714 static const DirDiff delta[] = {
3732 }
while ((v = v->
Next()) !=
nullptr);
3749 if (state <= 200 &&
Chance16R(1, 7, r)) {
3750 int index = (r * 10 >> 16);
3764 }
while ((u = u->
Next()) !=
nullptr);
3770 bool ret = v->
Next() !=
nullptr;
3780 225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, 15
3795 uint x = v->
x_pos & 0xF;
3796 uint y = v->
y_pos & 0xF;
3801 case DIR_N : x = ~x + ~y + 25;
break;
3802 case DIR_NW: x = y; [[fallthrough]];
3803 case DIR_NE: x = ~x + 16;
break;
3804 case DIR_E : x = ~x + y + 9;
break;
3805 case DIR_SE: x = y;
break;
3806 case DIR_S : x = x + y - 7;
break;
3807 case DIR_W : x = ~y + x + 9;
break;
3826 if (break_speed < v->cur_speed) v->
cur_speed = break_speed;
3879 !CheckCompatibleRail(v, tile)) {
3903 if (break_speed < v->cur_speed) v->
cur_speed = break_speed;
3945 static bool TrainLocoHandler(
Train *v,
bool mode)
3952 if (v->force_proceed !=
TFP_NONE) {
4022 if (v->force_proceed ==
TFP_NONE)
return true;
4060 if (j < adv_spd || v->cur_speed == 0)
break;
4064 if ((order_type == OT_GOTO_WAYPOINT || order_type == OT_GOTO_STATION) &&
4074 for (
Train *u = v; u !=
nullptr; u = u->
Next()) {
4092 const Train *v =
this;
4096 if (e->u.rail.running_cost_class == INVALID_PRICE)
continue;
4099 if (cost_factor == 0)
continue;
4104 cost +=
GetPrice(e->u.rail.running_cost_class, cost_factor, e->
GetGRF());
4125 if (!TrainLocoHandler(
this,
false))
return false;
4127 return TrainLocoHandler(
this,
true);
4194 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_...
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 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
TrackBits DiagdirReachesTracks(DiagDirection diagdir)
Returns all tracks that can be reached when entering a tile from a given (diagonal) direction.
@ EF_RAIL_TILTS
Rail vehicle tilts in curves.
static debug_inline uint TileY(TileIndex tile)
Get the Y component of a tile.
debug_inline bool IsFrontEngine() const
Check if the vehicle is a front engine.
void DeleteNewGRFInspectWindow(GrfSpecFeature feature, uint index)
Delete inspect window for a given feature and index.
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.
void OnNewCalendarDay() override
Calendar day handler.
uint16_t pow_wag_power
Extra power applied to consist if wagon should be powered.
static const EngineID INVALID_ENGINE
Constant denoting an invalid engine.
uint8_t pow_wag_weight
Extra weight applied to consist if wagon should be powered.
uint8_t misc_flags
Miscellaneous flags.
uint8_t curve_speed
Multiplier for curve maximum speed advantage.
int8_t x_bb_offs
x offset of vehicle bounding box
@ SIGTYPE_PBS
normal pbs signal
uint StoredCount() const
Returns sum of cargo on board the vehicle (ie not only reserved).
Direction ReverseDir(Direction d)
Return the reverse of a direction.
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 FindFirstTrack(TrackBits tracks)
Returns first Track from TrackBits or INVALID_TRACK.
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.
constexpr T SetBit(T &x, const uint8_t y)
Set a bit in a variable.
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.
uint16_t crash_anim_pos
Crash animation counter.
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.
@ FACIL_TRAIN
Station with train station.
static const uint16_t _breakdown_speeds[16]
Maximum speeds for train that is broken down or approaching line end.
uint8_t VehicleOrderID
The index of an order within its current vehicle (not pool related)
Money GetPrice(Price index, uint cost_factor, const GRFFile *grf_file, int shift)
Determine a certain price.
uint16_t reliability_spd_dec
Reliability decrease speed.
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.
@ DIRDIFF_45LEFT
Angle of 45 degrees left.
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 SigSegState UpdateSignalsInBuffer(Owner owner)
Updates blocks in _globset buffer.
TileIndex m_old_tile
the origin (vehicle moved from) before move
constexpr void Swap(T &a, T &b)
Type safe swap operation.
bool forbid_90_deg
forbid trains to make 90 deg turns
void ShowErrorMessage(StringID summary_msg, int x, int y, CommandCost cc)
Display an error message in a window.
@ 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.
TrackdirBits TrackStatusToTrackdirBits(TrackStatus ts)
Returns the present-trackdir-information of a TrackStatus.
static void MaybeBarCrossingWithSound(TileIndex tile)
Bars crossing and plays ding-ding sound if not barred already.
@ TRACK_BIT_X
X-axis track.
uint8_t max_train_length
maximum length for trains
const RailTypeInfo * GetRailTypeInfo(RailType railtype)
Returns a pointer to the Railtype information for a given railtype.
bool cached_tilt
train can tilt; feature provides a bonus in curves
uint16_t cargo_cap
total capacity
@ PROP_TRAIN_RUNNING_COST_FACTOR
Yearly runningcost (if dualheaded: sum of both vehicles)
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.
EngineID first_engine
Cached EngineID of the front vehicle. INVALID_ENGINE for the front vehicle itself.
bool Chance16R(const uint32_t a, const uint32_t b, uint32_t &r, const std::source_location location=std::source_location::current())
Flips a coin with a given probability and saves the randomize-number in a variable.
@ RAILTYPE_RAIL
Standard non-electric rails.
@ PM_PAUSED_ERROR
A game paused because a (critical) error.
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.
uint16_t reliability_spd_dec
Speed of reliability decay between services (per day).
Vehicle * Next() const
Get the next vehicle of this vehicle.
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.
bool IsOnewaySignal(Tile t, Track track)
One-way signals can't be passed the 'wrong' way.
TrackBits GetReservedTrackbits(TileIndex t)
Get the reserved trackbits for any tile, regardless of type.
@ DIRDIFF_SAME
Both directions faces to the same direction.
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.
Track TrackdirToTrack(Trackdir trackdir)
Returns the Track that a given Trackdir represents.
DiagDirection TrackdirToExitdir(Trackdir trackdir)
Maps a trackdir to the (4-way) direction the tile is exited when following that trackdir.
VehicleOrderID ProcessConditionalOrder(const Order *order, const Vehicle *v)
Process a conditional order and determine the next order.
static debug_inline bool IsPlainRail(Tile t)
Returns whether this is plain rails, with or without signals.
static void UpdateStatusAfterSwap(Train *v)
Updates some variables after swapping the vehicle.
TimerGameCalendar::Date GetLifeLengthInDays() const
Returns the vehicle's (not model's!) life length in days.
@ NT_ACCIDENT
An accident or disaster has occurred.
uint32_t StringID
Numeric value that represents a string, independent of the selected language.
uint8_t FreightWagonMult(CargoID cargo)
Return the cargo weight multiplier to use for a rail vehicle.
void Set(SpriteID sprite)
Assign a single sprite to the sequence.
uint32_t cached_weight
Total weight of the consist (valid only for the first engine).
void CloseWindowById(WindowClass cls, WindowNumber number, bool force, int data)
Close a window by its class and window number (if it is open).
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.
void SetTunnelBridgeReservation(Tile t, bool b)
Set the reservation state of the rail tunnel/bridge.
@ RAIL_TILE_SIGNALS
Normal rail tile with signals.
@ SAT_TRAIN_ARRIVES
Trigger platform when train arrives.
uint8_t spritenum
currently displayed sprite index 0xfd == custom sprite, 0xfe == custom second head sprite 0xff == res...
uint8_t y_extent
y-extent of vehicle bounding box
std::string name
Name of vehicle.
constexpr static debug_inline uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
static void NormaliseTrainHead(Train *head)
Normalise the head of the train again, i.e.
void ClearFrontEngine()
Remove the front engine state.
bool SwitchToNextOrder(bool skip_first)
Set the current vehicle order to the next order in the order list.
Owner
Enum for all companies/owners.
@ VS_DEFPAL
Use default vehicle palette.
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.
void AddVehicleAdviceNewsItem(StringID string, VehicleID vehicle)
Adds a vehicle-advice news item.
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo ID.
uint32_t GetGRFID() const
Retrieve the GRF ID of the NewGRF the vehicle is tied to.
Axis DiagDirToAxis(DiagDirection d)
Convert a DiagDirection to the axis.
@ VEH_TRAIN
Train vehicle type.
bool HasDepotReservation(Tile t)
Get the reservation state of the depot.
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.
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.
Trackdir FindFirstTrackdir(TrackdirBits trackdirs)
Returns first Trackdir from TrackdirBits or INVALID_TRACKDIR.
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.
uint8_t shorten_factor
length on main map for this type is 8 - shorten_factor
AccelStatus GetAccelerationStatus() const
Checks the current acceleration status of this vehicle.
DifficultySettings difficulty
settings related to the difficulty
static void CountVehicle(const Vehicle *v, int delta)
Update num_vehicle when adding or removing a vehicle.
constexpr TileIndex INVALID_TILE
The very nice invalid tile marker.
@ SIGNAL_STATE_GREEN
The signal is green.
uint16_t vehicle_flags
Used for gradual loading and other miscellaneous things (.
This struct contains all the info that is needed to draw and construct tracks.
bool wagon_speed_limits
enable wagon speed limits
void HideFillingPercent(TextEffectID *te_id)
Hide vehicle loading indicators.
Vehicle * next
pointer to the next vehicle in the chain
const GRFFile * GetGRF() const
Retrieve the NewGRF the vehicle is tied to.
bool IsCompatibleTrainStationTile(Tile test_tile, Tile station_tile)
Check if a tile is a valid continuation to a railstation tile.
uint8_t running_cost
Running cost of engine; For multiheaded engines the sum of both running costs.
bool IsRailStationTile(Tile t)
Is this tile a station tile and a rail station?
int16_t cached_curve_speed_mod
curve speed modifier of the entire train
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. */.
DiagDirection
Enumeration for diagonal directions.
uint8_t capacity
Cargo capacity of vehicle; For multiheaded engines the capacity of each single engine.
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.
bool IsLevelCrossingTile(Tile t)
Return whether a tile is a level crossing tile.
constexpr uint CeilDiv(uint a, uint b)
Computes ceil(a / b) for non-negative a and b.
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.
ClientSettings _settings_client
The current settings for this game.
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.
TimerGameTick::Ticks current_order_time
How many ticks have passed since this order started.
@ WC_VEHICLE_TIMETABLE
Vehicle timetable; Window numbers:
uint16_t GetVehicleCallbackParent(CallbackID callback, uint32_t param1, uint32_t param2, EngineID engine, const Vehicle *v, const Vehicle *parent)
Evaluate a newgrf callback for vehicles with a different vehicle for parent scope.
uint16_t speed
maximum travel speed (1 unit = 1/1.6 mph = 1 km-ish/h)
uint8_t wait_for_pbs_path
how long to wait for a path reservation.
uint8_t path_backoff_interval
ticks between checks for a free path.
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.
Direction ChangeDir(Direction d, DirDiff delta)
Change a direction by a given difference.
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.
RailType GetRailType(Tile t)
Gets the rail type of the given tile.
@ 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.
@ EV_EXPLOSION_LARGE
Various explosions.
@ DC_EXEC
execute the given command
int GetSlopePixelZ(int x, int y, bool ground_vehicle)
Return world Z coordinate of a given point of a tile.
uint32_t GetGRFID() const
Retrieve the GRF ID of the NewGRF the engine is tied to.
uint32_t PaletteID
The number of the palette.
~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.
OrderStopLocation
Where to stop the trains.
bool IsRailWaypointTile(Tile t)
Is this tile a station tile and a rail waypoint?
bool Chance16(const uint32_t a, const uint32_t b, const std::source_location location=std::source_location::current())
Flips a coin with given probability.
Axis GetRailStationAxis(Tile t)
Get the rail direction of a rail station.
DoCommandFlag
List of flags for a command.
void VehicleServiceInDepot(Vehicle *v)
Service a vehicle and all subsequent vehicles in the consist.
constexpr T KillFirstBit(T value)
Clear the first bit in an integer.
void SetWagon()
Set a vehicle to be a wagon.
static PBSTileInfo ExtendTrainReservation(const Train *v, TrackBits *new_tracks, DiagDirection *enterdir)
Extend a train path as far as possible.
@ TRACK_BIT_MASK
Bitmask for the first 6 bits.
TrackdirBits TrackStatusToRedSignals(TrackStatus ts)
Returns the red-signal-information of a TrackStatus.
uint8_t subspeed
fractional speed
bool m_is_bridge
last turn passed bridge ramp
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.
bool TracksOverlap(TrackBits bits)
Checks if the given tracks overlap, ie form a crossing.
int32_t x_pos
x coordinate.
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.
static bool CheckTrainCollision(Train *v)
Checks whether the specified train has a collision with another vehicle.
@ PFE_GL_TRAINS
Time spent processing trains.
void SetCrossingReservation(Tile t, bool b)
Set the reservation state of the rail crossing.
OrderType GetType() const
Get the type of order of this order.
TrackBits DiagDirToDiagTrackBits(DiagDirection diagdir)
Maps a (4-way) direction to the diagonal track bits incidating with that diagdir.
uint8_t flags
Flags of the engine.
static Vehicle * TrainOnTileEnum(Vehicle *v, void *)
Check if the vehicle is a train.
@ GVF_GOINGDOWN_BIT
Vehicle is currently going downhill. (Cached track information for acceleration)
OrderStopLocation GetStopLocation() const
Where must we stop at the platform?
uint8_t small_turn
Speed change due to a small turn.
@ TRACK_BIT_NONE
No track.
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.
@ CBM_VEHICLE_LENGTH
Vehicle length (trains and road vehicles)
@ GBUG_VEH_CAPACITY
Capacity of vehicle changes when not refitting or arranging.
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.
RailTypes compatible_railtypes
bitmask to the OTHER railtypes on which an engine of THIS railtype can physically travel
const GRFFile * GetGRF() const
Retrieve the NewGRF the engine is tied to.
@ EXPENSES_TRAIN_RUN
Running costs trains.
int traininfo_vehicle_pitch
Vertical offset for drawing train images in depot GUI and vehicle details.
TimerGameEconomy::Date date_of_last_service
Last economy date the vehicle had a service at a depot.
DiagDirection GetRailDepotDirection(Tile t)
Returns the direction the depot is facing to.
static void NormaliseSubtypes(Train *chain)
Normalise the sub types of the parts in this chain.
uint8_t train_acceleration_model
realistic acceleration for trains
@ ENGINE_EXCLUSIVE_PREVIEW
This vehicle is in the exclusive preview stage, either being used or being offered to a company.
uint16_t cached_max_speed
Maximum speed of the consist (minimum of the max speed of all vehicles in the consist).
uint DetermineCapacity(const Vehicle *v, uint16_t *mail_capacity=nullptr) const
Determines capacity of a given vehicle from scratch.
@ 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.
OrderNonStopFlags GetNonStopType() const
At which stations must we stop?
uint8_t z_up
Fraction to remove when moving up.
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
@ VS_HIDDEN
Vehicle is not visible.
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.
DirDiff DirDifference(Direction d0, Direction d1)
Calculate the difference between two directions.
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.
CommandCost CheckOwnership(Owner owner, TileIndex tile)
Check whether the current owner owns something.
TileIndex dest_tile
Heading for this tile.
void HandlePathfindingResult(bool path_found)
Handle the pathfinding result, especially the lost status.
#define return_cmd_error(errcode)
Returns from a function with a specific StringID as error.
uint16_t callback_mask
Bitmask of vehicle callbacks that have to be called.
TrackdirBits TrackBitsToTrackdirBits(TrackBits bits)
Converts TrackBits to TrackdirBits while allowing both directions.
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.
CommandCost CmdMoveRailVehicle(DoCommandFlag flags, VehicleID src_veh, VehicleID dest_veh, bool move_chain)
Move a rail vehicle around inside the depot.
uint8_t freight_trains
value to multiply the weight of cargo by
Common return value for all commands.
bool IsBridge(Tile t)
Checks if this is a bridge, instead of a tunnel.
const BridgeSpec * GetBridgeSpec(BridgeType i)
Get the specification of a bridge type.
Iterable ensemble of each set bit in a value.
static bool CheckTrainStayInDepot(Train *v)
Will the train stay in the depot the next tick?
Track GetRailDepotTrack(Tile t)
Returns the track of a depot, ignoring direction.
@ VRF_TRAIN_STUCK
Train can't get a path reservation.
Trackdir GetVehicleTrackdir() const override
Get the tracks of the train vehicle.
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.
uint8_t z_down
Fraction to add when moving down.
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.
bool IsWaitingForUnbunching() const
Check whether a vehicle inside a depot is waiting for unbunching.
TileArea train_station
Tile area the train 'station' part covers.
Track TrackBitsToTrack(TrackBits tracks)
Converts TrackBits to Track.
static const VehicleOrderID INVALID_VEH_ORDER_ID
Invalid vehicle order index (sentinel)
@ NT_ARRIVAL_COMPANY
First vehicle arrived for company.
@ DIRDIFF_90LEFT
Angle of 90 degrees left.
uint16_t cached_max_track_speed
Maximum consist speed (in internal units) limited by track type (valid only for the first engine).
TrackBits
Allow incrementing of Track variables.
@ INVALID_DIAGDIR
Flag for an invalid DiagDirection.
@ GVF_GOINGUP_BIT
Vehicle is currently going uphill. (Cached track information for acceleration)
TrackBits TrackCrossesTracks(Track track)
Maps a track to all tracks that make 90 deg turns with it.
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.
bool HasReservedTracks(TileIndex tile, TrackBits tracks)
Check whether some of tracks is reserved on a tile.
static const VehicleID INVALID_VEHICLE
Constant representing a non-existing vehicle.
uint16_t random_bits
Bits used for randomized variational spritegroups.
EngineID engine_type
The type of engine used for this vehicle.
@ DIAGDIR_BEGIN
Used for iterations.
bool IsTunnel(Tile t)
Is this a tunnel (entrance)?
This struct contains information about the end of a reserved path.
@ VS_CRASHED
Vehicle is crashed.
@ VETS_CANNOT_ENTER
The vehicle cannot enter the tile.
bool TestVehicleBuildProbability(Vehicle *v, EngineID engine, BuildProbabilityType type)
Test for vehicle build probablity type.
Sprite sequence for a vehicle part.
@ 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).
@ TRACKDIR_BIT_NONE
No track build.
StationID last_station_visited
The last station we stopped at.
UnitID GetFreeUnitNumber(VehicleType type)
Get an unused unit number for a vehicle (if allowed).
DiagDirection ReverseDiagDir(DiagDirection d)
Returns the reverse direction of the given DiagDirection.
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)
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.
Direction DiagDirToDir(DiagDirection dir)
Convert a DiagDirection to a Direction.
void NormalizeTrainVehInDepot(const Train *u)
Move all free vehicles in the depot to the train.
@ TRACK_BIT_LEFT
Left track.
@ EXPENSES_NEW_VEHICLES
New vehicles.
GroundVehicleCache gcache
Cache of often calculated values.
TrackdirBits TrackdirReachesTrackdirs(Trackdir trackdir)
Maps a trackdir to the trackdirs that can be reached from it (ie, when entering the next tile.
DiagDirection AxisToDiagDir(Axis a)
Converts an Axis to a DiagDirection.
void SetFrontEngine()
Set front engine state.
uint16_t cur_speed
current speed
Trackdir ReverseTrackdir(Trackdir trackdir)
Maps a trackdir to the reverse trackdir.
@ ODATFB_NEAREST_DEPOT
Send the vehicle to the nearest depot.
TrackdirBits DiagdirReachesTrackdirs(DiagDirection diagdir)
Returns all trackdirs that can be reached when entering a tile from a given (diagonal) direction.
TileIndexDiff TileDiffXY(int x, int y)
Calculates an offset for the given coordinate(-offset).
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.
TimerGameCalendar::Year build_year
Year the vehicle has been built.
uint16_t GetMaxWeight() const override
Calculates the weight value that this vehicle will have when fully loaded with its current cargo.
@ DC_AUTOREPLACE
autoreplace/autorenew is in progress, this shall disable vehicle limits when building,...
@ WC_VEHICLE_DETAILS
Vehicle details; Window numbers:
bool IsBridgeTile(Tile t)
checks if there is a bridge on this tile
static void NewEvent(class ScriptEvent *event)
Queue a new event for a Game Script.
static bool HandleCrashedTrain(Train *v)
Handle a crashed train.
TrackBits TrackdirBitsToTrackBits(TrackdirBits bits)
Discards all directional information from a TrackdirBits value.
@ VS_STOPPED
Vehicle is stopped by the player.
void ShowVisualEffect() const
Draw visual effects (smoke and/or sparks) for a vehicle chain.
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.
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.
DiagDirection VehicleExitDir(Direction direction, TrackBits track)
Determine the side in which the vehicle will leave the tile.
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_t cached_max_curve_speed
max consist speed limited by curves
#define lengthof(array)
Return the length of an fixed size array.
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.
Money GetCost() const
The costs as made up to this moment.
uint8_t wait_oneway_signal
waitingtime in days before a oneway signal
static const GroupID DEFAULT_GROUP
Ungrouped vehicles are in this group.
Trackdir RemoveFirstTrackdir(TrackdirBits *trackdirs)
Removes first Trackdir from TrackdirBits and returns it.
DiagDirection DirToDiagDir(Direction dir)
Convert a Direction to a DiagDirection.
Money profit_this_year
Profit this year << 8, low 8 bits are fract.
bool IsCrossingBarred(Tile t)
Check if the level crossing is barred.
void CopyVehicleConfigAndStatistics(Vehicle *src)
Copy certain configurations and statistics of a vehicle after successful autoreplace/renew The functi...
fluid_settings_t * settings
FluidSynth settings handle.
int8_t y_bb_offs
y offset of vehicle bounding box
bool IsCompatibleRail(RailType enginetype, RailType tiletype)
Checks if an engine of the given RailType can drive on a tile with a given RailType.
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.
SignalState GetSignalStateByTrackdir(Tile tile, Trackdir trackdir)
Gets the state of the signal along the given trackdir.
bool _networking
are we in networking mode?
Owner GetTileOwner(Tile tile)
Returns the owner of a tile.
@ VRF_REVERSE_DIRECTION
Reverse the visible direction of the vehicle.
CommandCost CmdReverseTrainDirection(DoCommandFlag flags, VehicleID veh_id, bool reverse_single_veh)
Reverse train.
uint32_t VehicleID
The type all our vehicle IDs have.
@ 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.
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.
int32_t TileIndexDiff
An offset value between two tiles.
Coordinates of a point in 2D.
DirDiff
Allow incrementing of Direction variables.
void CheckCargoCapacity(Vehicle *v)
Check the capacity of all vehicles in a chain and spread cargo if needed.
uint8_t running_ticks
Number of ticks this vehicle was not stopped this day.
void MarkBridgeDirty(TileIndex begin, TileIndex end, DiagDirection direction, uint bridge_height)
Mark bridge tiles dirty.
@ WC_TRAINS_LIST
Trains list; Window numbers:
static debug_inline RailTileType GetRailTileType(Tile t)
Returns the RailTileType (normal with or without signals, waypoint or depot).
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.
bool HasOnewaySignalBlockingTrackdir(Tile tile, Trackdir td)
Is a one-way signal blocking the trackdir? A one-way signal on the trackdir against will block,...
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.
StringID GetGRFStringID(uint32_t grfid, StringID stringid)
Returns the index for this stringid associated with its grfID.
Data structure for storing engine speed changes of an acceleration type.
void AddCost(const Money &cost)
Adds the given cost to the cost of the command.
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.
uint8_t user_def_data
Property 0x25: "User-defined bit mask" Used only for (very few) NewGRF vehicles.
@ NT_ARRIVAL_OTHER
First vehicle arrived for competitor.
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.
MutableSpriteCache sprite_cache
Cache of sprites and values related to recalculating them, see MutableSpriteCache.
SoundFx
Sound effects from baseset.
uint32_t SpriteID
The number of a sprite, without mapping bits and colourtables.
DepotID GetDepotIndex(Tile t)
Get the index of which depot is attached to the tile.
void AddVehicleNewsItem(StringID string, NewsType type, VehicleID vehicle, StationID station=INVALID_STATION)
Adds a newsitem referencing a vehicle.
uint16_t reliability
Current reliability of the engine.
uint8_t progress
The percentage (if divided by 256) this vehicle already crossed the tile unit.
SpriteID colourmap
NOSAVE: cached colour mapping.
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.
@ RAILVEH_WAGON
simple wagon, not motorized
void ResetDepotUnbunching()
Resets all the data used for depot unbunching.
@ WC_VEHICLE_REFIT
Vehicle refit; Window numbers:
void ReserveTrackUnderConsist() const
Tries to reserve track under whole train consist.
static debug_inline bool IsPlainRailTile(Tile t)
Checks whether the tile is a rail tile or rail tile with signals.
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...
int32_t z_pos
z coordinate.
@ VF_BUILT_AS_PROTOTYPE
Vehicle is a prototype (accepted as exclusive preview).
bool IsDiagonalDirection(Direction dir)
Checks if a given Direction is diagonal.
TrackBits GetTrackBits(Tile tile)
Gets the track bits of the given tile.
Trackdir m_old_td
the trackdir (the vehicle was on) before move
@ TRACK_BIT_WORMHOLE
Bitflag for a wormhole (used for tunnels)
@ VIWD_CONSIST_CHANGED
Vehicle composition was changed.
Direction direction
facing
@ TRACK_BEGIN
Used for iterations.
TileIndexDiff TileOffsByDiagDir(DiagDirection dir)
Convert a DiagDirection to a TileIndexDiff.
Temporary data storage for testing collisions.
RailTypes powered_railtypes
bitmask to the OTHER railtypes on which an engine of THIS railtype generates power
@ TRACK_BIT_UPPER
Upper track.
constexpr T AssignBit(T &x, const uint8_t y, bool value)
Assigns a bit in a variable.
VehicleOrderID cur_real_order_index
The index to the current real (non-implicit) order.
uint8_t tick_counter
Increased by one for each tick.
@ 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.
uint8_t acceleration
used by train & aircraft
void OnNewEconomyDay() override
Economy day handler.
static const uint CALLBACK_FAILED
Different values for Callback result evaluations.
uint16_t DepotID
Type for the unique identifier of depots.
@ HVOT_TRAIN
Station has seen a train.
bool IsValidDiagDirection(DiagDirection d)
Checks if an integer value is a valid DiagDirection.
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.
Track
These are used to specify a single track.
@ 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 const uint VEHICLE_LENGTH
The length of a vehicle in tile units.
DiagDirection DiagdirBetweenTiles(TileIndex tile_from, TileIndex tile_to)
Determines the DiagDirection to get from one tile to another.
static const PaletteID PALETTE_CRASH
Recolour sprite greying of crashed vehicles.
@ PROP_TRAIN_SHORTEN_FACTOR
Shorter vehicles.
uint8_t day_counter
Increased by one for each day.
TimerGameCalendar::Date max_age
Maximum age.
@ OSL_PLATFORM_FAR_END
Stop at the far end of the platform.
@ SND_0A_DEPARTURE_TRAIN
8 == 0x08 Station departure: diesel and electric engine
@ TRACK_BIT_RIGHT
Right track.
ClientID
'Unique' identifier to be given to clients
UnitID max_trains
max trains in game per company
Trackdir
Enumeration for tracks and directions.
Axis GetCrossingRoadAxis(Tile t)
Get the road axis of a level crossing.
static debug_inline bool IsRailDepotTile(Tile t)
Is this tile rail tile and a rail depot?
void SetCrossingBarred(Tile t, bool barred)
Set the bar state of a level crossing.
int8_t x_offs
x offset for vehicle sprite
static Train * From(Vehicle *v)
Converts a Vehicle to SpecializedVehicle with type checking.
Axis
Allow incrementing of DiagDirDiff variables.
@ DIRDIFF_45RIGHT
Angle of 45 degrees right.
constexpr T abs(const T a)
Returns the absolute value of (scalar) variable.
@ TRANSPORT_RAIL
Transport by train.
void ConsistChanged(ConsistChangeFlags allowed_changes)
Recalculates the cached stuff of a train.
void SetEngine()
Set engine status.
void SetDepotReservation(Tile t, bool b)
Set the reservation state of the depot.
static debug_inline uint Size()
Get the size of the map.
TimerGameCalendar::Date date_of_last_service_newgrf
Last calendar date the vehicle had a service at a depot, unchanged by the date cheat to protect again...
void SetDParam(size_t n, uint64_t v)
Set a string parameter v at index n in the global string parameter array.
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.
StationID GetStationIndex(Tile t)
Get StationID from a tile.
TileIndex tile
The base tile of the area.
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...
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).
void SetFreeWagon()
Set a vehicle as a free wagon.
@ RAILVEH_MULTIHEAD
indicates a combination of two locomotives
bool HasSignals(Tile t)
Checks if a rail tile has signals.
void MarkTileDirtyByTile(TileIndex tile, int bridge_level_offset, int tile_height_override)
Mark a tile given by its index dirty for repaint.
uint16_t reliability
Reliability.
@ SND_13_TRAIN_COLLISION
15 == 0x11 Train+train crash
void AddSideToSignalBuffer(TileIndex tile, DiagDirection side, Owner owner)
Add side of tile to signal update buffer.
@ SND_47_DEPARTURE_MONORAIL
71 == 0x47 Station departure: monorail engine
RailType GetTileRailType(Tile tile)
Return the rail type of tile, or INVALID_RAILTYPE if this is no rail tile.
Position information of a vehicle after it moved.
@ WC_VEHICLE_DEPOT
Depot view; Window numbers:
int ScaleSpriteTrad(int value)
Scale traditional pixel dimensions to GUI zoom level, for drawing sprites.
@ 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
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.
uint16_t cargo_age_period
Number of ticks before carried cargo is aged.
CommandCost CmdBuildRailVehicle(DoCommandFlag flags, TileIndex tile, const Engine *e, Vehicle **ret)
Build a railroad vehicle.
uint8_t CargoID
Cargo slots to indicate a cargo type within a game.
@ DIAGDIR_END
Used for iterations.
Direction
Defines the 8 directions on the map.
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.
@ TRACK_BIT_Y
Y-axis track.
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.
Track DiagDirToDiagTrack(DiagDirection diagdir)
Maps a (4-way) direction to the diagonal track incidating with that diagdir.
static Train * GetIfValid(size_t index)
Returns vehicle if the index is a valid index for this vehicle type.
Train * v
Vehicle we are testing for collision.
bool HasCrossingReservation(Tile t)
Get the reservation state of the rail crossing.
static Pool::IterateWrapper< Train > Iterate(size_t from=0)
Returns an iterable ensemble of all valid vehicles of type T.
TileIndex GetOtherTunnelBridgeEnd(Tile t)
Determines type of the wormhole and returns its other end.
uint16_t GetMaxSpeed() const
Get the maxmimum speed in km-ish/h a vehicle is allowed to reach on the way to the destination.
TileIndex old_tile
Current tile of the vehicle.
TileIndex m_new_tile
the new tile (the vehicle has entered)
int32_t y_pos
y coordinate.
Structure to return information about the closest depot location, and whether it could be found.
bool PlayVehicleSound(const Vehicle *v, VehicleSoundEvent event, bool force)
Checks whether a NewGRF wants to play a different vehicle sound effect.
uint16_t power
Power of engine (hp); For multiheaded engines the sum of both engine powers.
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 ErrorUnknownCallbackResult(uint32_t grfid, uint16_t cbid, uint16_t cb_res)
Record that a NewGRF returned an unknown/invalid callback result.
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.
ClosestDepot FindClosestDepot() override
Find the closest depot for this vehicle and tell us the location, DestinationID and whether we should...
uint32_t cached_power
Total power of the consist (valid only for the first engine).
OrderDepotTypeFlags GetDepotOrderType() const
What caused us going to the depot?
void InvalidateNewGRFCache()
Invalidates cached NewGRF variables.
uint8_t wait_twoway_signal
waitingtime in days before a twoway signal
void UpdateAdjacentLevelCrossingTilesOnLevelCrossingRemoval(TileIndex tile, Axis road_axis)
Update adjacent level crossing tiles in this multi-track crossing, due to removal of a level crossing...
int UnScaleGUI(int value)
Short-hand to apply GUI zoom level.
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.
uint16_t max_speed
Maximum speed (1 unit = 1/1.6 mph = 1 km-ish/h)
bool Follow(TileIndex old_tile, Trackdir old_td)
main follower routine.
YAPFSettings yapf
pathfinder settings for the yet another pathfinder
void ReleaseUnitNumber()
Release the vehicle's unit number.
uint16_t GetCurveSpeedLimit() const
Computes train speed limit caused by curves.
void AgeVehicle(Vehicle *v)
Update age of a vehicle.
DiagDirection m_exitdir
exit direction (leaving the old tile)
bool IsStoppedInDepot() const
Check whether the vehicle is in the depot and stopped.
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_NONE
Normal operation.
@ 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.
Axis GetCrossingRailAxis(Tile t)
Get the rail axis of a level crossing.
uint8_t x_extent
x-extent of vehicle bounding box
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
@ TRACK_BIT_LOWER
Lower track.
uint8_t original_image_index
Original vehicle image index, thus the image index of the overridden vehicle.
static debug_inline TileIndex TileVirtXY(uint x, uint y)
Get a tile from the virtual XY-coordinate.
bool IsValidCargoID(CargoID t)
Test whether cargo type is not INVALID_CARGO.
static void Backup(const Vehicle *v, uint32_t user)
Create an order backup for the given vehicle.
static bool TrainCheckIfLineEnds(Train *v, bool reverse=true)
Checks for line end.
Train * GetNextUnit() const
Get the next real (non-articulated part and non rear part of dualheaded engine) vehicle in the consis...
T * GetLastEnginePart()
Get the last part of an articulated engine.
bool IsWagon() const
Check if a vehicle is a wagon.
@ TFP_STUCK
Proceed till next signal, but ignore being stuck till then. This includes force leaving depots.
static Date date
Current date in days (day counter).
@ 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
uint16_t EngineID
Unique identification number of an engine.
T * Previous() const
Get previous vehicle in the chain.
static bool TrainApproachingCrossing(TileIndex tile)
Finds a vehicle approaching rail-road crossing.
bool IsFreeWagon() const
Check if the vehicle is a free wagon (got no engine in front of it).
static constexpr TimerGameTick::Ticks DAY_TICKS
1 day is 74 ticks; TimerGameCalendar::date_fract used to be uint16_t and incremented by 885.
static debug_inline bool IsTileType(Tile tile, TileType type)
Checks if a tile is a given tiletype.
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 Vehicle * CollectTrackbitsFromCrashedVehiclesEnum(Vehicle *v, void *data)
Collect trackbits of all crashed train vehicles on a tile.
TrackdirBits TrackdirCrossesTrackdirs(Trackdir trackdir)
Maps a trackdir to all trackdirs that make 90 deg turns with it.
uint GetAdvanceDistance()
Determines the vehicle "progress" needed for moving a step.
Order * GetOrder(int index) const
Returns order 'index' of a vehicle or nullptr when it doesn't exists.
VehicleType type
Type of vehicle.
static void SwapTrainFlags(uint16_t *swap_flag1, uint16_t *swap_flag2)
Swap the two up/down flags in two ways:
constexpr T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
TrackdirBits
Allow incrementing of Trackdir variables.
bool Tick() override
Update train vehicle data for a tick.
static debug_inline uint TileX(TileIndex tile)
Get the X component of a tile.
Train * First() const
Get the first vehicle in the chain.
bool HasPbsSignalOnTrackdir(Tile tile, Trackdir td)
Is a pbs signal present along the trackdir?
@ TRACK_Y
Track along the y-axis (north-west to south-east)
void UpdatePosition()
Update the position of the vehicle.
bool HasPowerOnRail(RailType enginetype, RailType tiletype)
Checks if an engine of the given RailType got power on a tile with a given RailType.
@ AS_BRAKE
We want to stop.
int Width() const
Get width of Rect.
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.
int y
x and y position of the vehicle after moving
bool IsValidTrackdir(Trackdir trackdir)
Checks if a Trackdir is valid for non-road vehicles.
void EconomyAgeVehicle(Vehicle *v)
Update economy age of a vehicle.
uint16_t GetVehicleCallback(CallbackID callback, uint32_t param1, uint32_t param2, EngineID engine, const Vehicle *v)
Evaluate a newgrf callback for vehicles.
uint8_t cargo_subtype
Used for livery refits (NewGRF variations)
static void ChangeTrainDirRandomly(Train *v)
Rotate all vehicles of a (crashed) train chain randomly to animate the crash.
@ 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.
Specification of a rectangle with absolute coordinates of all edges.
uint Crash(bool flooded) override
Common code executed for crashed ground vehicles.
static void TrainEnterStation(Train *v, StationID station)
Trains enters a station, send out a news item if it is the first train, and start loading.
static constexpr int DAYS_IN_YEAR
days per year
VehicleOrderID GetNumOrders() const
Get the number of orders this vehicle has.
T * Last()
Get the last vehicle in the chain.
uint8_t cached_veh_length
Length of this vehicle in units of 1/VEHICLE_LENGTH of normal length. It is cached because this can b...
uint16_t wait_counter
Ticks waiting in front of a signal, ticks being stuck or a counter for forced proceeding through sign...
uint DoUpdateSpeed(uint accel, int min_speed, int max_speed)
Update the speed of the vehicle.
constexpr T ClrBit(T &x, const uint8_t y)
Clears a bit in a variable.
bool IsTileOwner(Tile tile, Owner owner)
Checks if a tile belongs to the given owner.
OrderList * orders
Pointer to the order list for this vehicle.
@ INVALID_TRACK
Flag for an invalid track.
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting)
uint8_t acceleration_type
Acceleration type of this rail type.
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.
Trackdir DiagDirToDiagTrackdir(DiagDirection diagdir)
Maps a (4-way) direction to the diagonal trackdir that runs in that direction.
void SetWindowWidgetDirty(WindowClass cls, WindowNumber number, WidgetID widget_index)
Mark a particular widget in a particular window as dirty (in need of repainting)
@ TRACK_BIT_DEPOT
Bitflag for a depot.
void MakeGoToDepot(DepotID destination, OrderDepotTypeFlags order, OrderNonStopFlags non_stop_type=ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS, OrderDepotActionFlags action=ODATF_SERVICE_ONLY, CargoID cargo=CARGO_NO_REFIT)
Makes this order a Go To Depot order.
void SetSignalStateByTrackdir(Tile tile, Trackdir trackdir, SignalState state)
Sets the state of the signal along the given trackdir.
bool TrainController(Train *v, Vehicle *nomove, bool reverse=true)
Move a vehicle chain one movement stop forwards.
@ INVALID_TRACKDIR
Flag for an invalid trackdir.
uint16_t cached_total_length
Length of the whole vehicle (valid only for the first engine).
Vehicle * first
NOSAVE: pointer to the first vehicle in the chain.
TileIndex TileAddByDiagDir(TileIndex tile, DiagDirection dir)
Adds a DiagDir to a tile.
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
@ TRACK_X
Track along the x-axis (north-east to south-west)
@ SRT_TRAIN_ARRIVES
Trigger platform when train arrives.
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...
void LeaveUnbunchingDepot()
Leave an unbunching depot and calculate the next departure time for shared order vehicles.
static void MarkTrainAsStuck(Train *v)
Mark a train as stuck and stop it if it isn't stopped right now.
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).
constexpr T ToggleBit(T &x, const uint8_t y)
Toggles a bit in a variable.
int m_tiles_skipped
number of skipped tunnel or station tiles
T * GetFirstEnginePart()
Get the first part of an articulated engine.
@ TFP_SIGNAL
Ignore next signal, after the signal ignore being stuck.
bool m_is_tunnel
last turn passed tunnel
CommandCost TunnelBridgeIsFree(TileIndex tile, TileIndex endtile, const Vehicle *ignore)
Finds vehicle in tunnel / bridge.
int8_t y_offs
y offset for vehicle sprite
BridgeType GetBridgeType(Tile t)
Determines the type of bridge on a tile.
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.
@ 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_t refit_cap
Capacity left over from before last refit.
bool IsMultiheaded() const
Check if the vehicle is a multiheaded engine.
uint8_t large_turn
Speed change due to a large turn.
GetNewVehiclePosResult GetNewVehiclePos(const Vehicle *v)
Get position information of a vehicle when moving one pixel in the direction it is facing.
uint32_t maximum_go_to_depot_penalty
What is the maximum penalty that may be endured for going to a depot.
uint8_t z_extent
z-extent of vehicle bounding box
@ CBID_TRAIN_ALLOW_WAGON_ATTACH
Determine whether a wagon can be attached to an already existing train.
static TileIndex TrainApproachingCrossingTile(const Train *v)
Determines whether train is approaching a rail-road crossing (thus making it barred)
bool HasSignalOnTrackdir(Tile tile, Trackdir trackdir)
Checks for the presence of signals along the given trackdir on the given rail tile.
@ RAILTYPES_RAIL
Non-electrified rails.
void ReverseTrainDirection(Train *v)
Turn a train around.
DiagDirection GetTunnelBridgeDirection(Tile t)
Get the direction pointing to the other end.
static Year year
Current year, starting at 0.
@ VETS_ENTERED_WORMHOLE
The vehicle either entered a bridge, tunnel or depot tile (this includes the last tile of the bridge/...
static Date date
Current date in days (day counter).
uint8_t breakdown_ctr
Counter for managing breakdown events.
constexpr uint8_t FindFirstBit(T x)
Search the first set bit in a value.
@ RAILTYPES_NONE
No rail types.
constexpr debug_inline bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.