40 #include "table/strings.h" 52 static const byte _vehicle_initial_x_fract[4] = {10, 8, 4, 8};
53 static const byte _vehicle_initial_y_fract[4] = { 8, 4, 8, 10};
56 bool IsValidImageIndex<VEH_TRAIN>(uint8 image_index)
58 return image_index <
lengthof(_engine_sprite_base);
81 for (
const Train *u = v, *w = v->
Next(); w != NULL; u = w, w = w->
Next()) {
84 max(
abs(u->x_pos - w->x_pos),
abs(u->y_pos - w->y_pos)) != u->CalcNextVehicleOffset()) ||
111 uint16 max_speed = UINT16_MAX;
120 bool train_can_tilt =
true;
122 for (
Train *u =
this; u != NULL; u = u->
Next()) {
126 assert(u->First() ==
this);
129 u->gcache.first_engine =
this == u ?
INVALID_ENGINE : first_engine;
130 u->railtype = rvi_u->railtype;
132 if (u->IsEngine()) first_engine = u->engine_type;
136 this->InvalidateNewGRFCache();
137 u->InvalidateNewGRFCache();
140 for (
Train *u =
this; u != NULL; u = u->
Next()) {
144 u->InvalidateNewGRFCache();
147 for (
Train *u =
this; u != NULL; u = u->
Next()) {
148 const Engine *e_u = u->GetEngine();
154 u->tcache.cached_override = GetWagonOverrideSpriteSet(u->engine_type, u->cargo_type, u->gcache.first_engine);
157 u->colourmap = PAL_NONE;
160 u->UpdateVisualEffect(
true);
170 if (!u->IsArticulatedPart()) {
173 if (rvi_u->
power > 0) {
187 if (speed != 0) max_speed =
min(speed, max_speed);
194 if (u->cargo_cap > new_cap) u->cargo.Truncate(new_cap);
195 u->refit_cap =
min(new_cap, u->refit_cap);
196 u->cargo_cap = new_cap;
205 if (e_u->
GetGRF() != NULL && e_u->
GetGRF()->grf_version >= 8) {
221 u->gcache.cached_veh_length = veh_len;
229 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() != NULL; 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;
387 int distance_to_go = station_ahead /
TILE_SIZE - (station_length - stop_at) /
TILE_SIZE;
389 if (distance_to_go > 0) {
390 int st_max_speed = 120;
392 int delta_v = this->
cur_speed / (distance_to_go + 1);
393 if (max_speed > (this->
cur_speed - delta_v)) {
394 st_max_speed = this->
cur_speed - (delta_v / 10);
397 st_max_speed =
max(st_max_speed, 25 * distance_to_go);
398 max_speed =
min(max_speed, st_max_speed);
403 for (
const Train *u =
this; u != NULL; u = u->
Next()) {
405 max_speed =
min(max_speed, 61);
437 int reference_width = TRAININFO_DEFAULT_VEHICLE_WIDTH;
438 int vehicle_pitch = 0;
441 if (e->
GetGRF() != NULL && is_custom_sprite(e->u.rail.image_index)) {
446 if (offset != NULL) {
455 assert(IsValidImageIndex<VEH_TRAIN>(
spritenum));
456 return ((direction + _engine_sprite_add[
spritenum]) & _engine_sprite_and[spritenum]) + _engine_sprite_base[
spritenum];
471 if (is_custom_sprite(spritenum)) {
472 GetCustomVehicleSprite(
this, (
Direction)(direction + 4 * IS_CUSTOM_SECONDHEAD_SPRITE(spritenum)), image_type, result);
478 assert(IsValidImageIndex<VEH_TRAIN>(spritenum));
479 SpriteID sprite = GetDefaultTrainSprite(spritenum, direction);
492 if (is_custom_sprite(spritenum)) {
493 GetCustomVehicleIcon(engine, dir, image_type, result);
495 if (e->
GetGRF() != NULL) {
501 spritenum =
Engine::Get(engine)->original_image_index;
504 if (rear_head) spritenum++;
506 result->
Set(GetDefaultTrainSprite(spritenum,
DIR_W));
516 GetRailIcon(engine,
false, yf, image_type, &seqf);
517 GetRailIcon(engine,
true, yr, image_type, &seqr);
523 preferred_x =
Clamp(preferred_x,
531 GetRailIcon(engine,
false, y, image_type, &seq);
535 preferred_x =
Clamp(preferred_x,
557 GetRailIcon(engine,
false, y, image_type, &seq);
562 width =
UnScaleGUI(rect.right - rect.left + 1);
563 height =
UnScaleGUI(rect.bottom - rect.top + 1);
568 GetRailIcon(engine,
true, y, image_type, &seq);
573 height = max<uint>(height,
UnScaleGUI(rect.bottom - rect.top + 1));
574 xoffs = xoffs -
ScaleGUITrad(TRAININFO_DEFAULT_VEHICLE_WIDTH) / 2;
612 v->
z_pos = GetSlopePixelZ(x, y);
626 v->railtype = rvi->railtype;
637 _new_vehicle_id = v->
index;
648 if (w->
tile == tile &&
676 static void AddRearEngineToMultiheadedTrain(
Train *v)
694 u->railtype = v->railtype;
706 v->other_multiheaded_part = u;
707 u->other_multiheaded_part = v;
741 v->
z_pos = GetSlopePixelZ(x, y);
758 v->railtype = rvi->railtype;
759 _new_vehicle_id = v->
index;
778 AddRearEngineToMultiheadedTrain(v);
796 static Train *FindGoodVehiclePos(
const Train *src)
802 FOR_ALL_TRAINS(dst) {
808 if (t == NULL)
return dst;
826 for (; t != NULL; t = t->
Next()) *list.
Append() = t;
836 if (list.
Length() == 0)
return;
840 for (
Train **iter = list.
Begin(); iter != list.
End(); iter++) {
897 if (u == t->other_multiheaded_part)
continue;
913 if (chain == NULL)
return;
929 t->ClearFrontEngine();
947 if ((src != NULL && src->
IsEngine() ? 1 : 0) +
948 (dst != NULL && dst->
IsEngine() ? 1 : 0) -
949 (original_src != NULL && original_src->
IsEngine() ? 1 : 0) -
950 (original_dst != NULL && original_dst->
IsEngine() ? 1 : 0) <= 0) {
1017 if (head->
GetGRF()->grf_version < 8) {
1018 if (callback == 0xFD) error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
1022 if (callback < 0x400) {
1032 error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
1066 if (ret.
Failed())
return ret;
1068 if (ret.
Failed())
return ret;
1085 if (*src_head == *dst_head) {
1089 }
else if (*dst_head == NULL) {
1095 if (src == *src_head) {
1102 *src_head = move_chain ? NULL :
1126 if (head == NULL)
return;
1160 bool move_chain =
HasBit(p1, 20);
1166 if (ret.
Failed())
return ret;
1174 dst = src->
IsEngine() ? NULL : FindGoodVehiclePos(src);
1180 if (ret.
Failed())
return ret;
1199 dst_head = dst->
First();
1210 if (move_chain && src_head == dst_head)
return CommandCost();
1232 Train *original_src_head = src_head;
1233 Train *original_dst_head = (dst_head == src_head ? NULL : dst_head);
1238 bool original_src_head_front_engine = original_src_head->
IsFrontEngine();
1239 bool original_dst_head_front_engine = original_dst_head != NULL && original_dst_head->
IsFrontEngine();
1306 if (original_src_head != src && dst_head == src) {
1353 bool sell_chain =
HasBit(data, 0);
1367 Train *sell_head = NULL;
1437 static const int _sign_table[] =
1519 uint16 flag1 = *swap_flag1;
1520 uint16 flag2 = *swap_flag2;
1587 for (a = v; l != 0; l--) a = a->
Next();
1588 for (b = v; r != 0; r--) b = b->
Next();
1598 Swap(a->track, b->track);
1687 if (new_state && sound) {
1721 uint length = CountVehiclesInChain(v);
1723 while (length > 2) {
1725 first = first->
Next();
1754 if (leave != NULL) {
1770 uint length = CountVehiclesInChain(v);
1774 bool nomove = (dep == NULL);
1776 while (length > 2) {
1779 if (base == dep)
break;
1782 if (last == dep) nomove =
true;
1785 first = first->
Next();
1790 for (
int i = 0; i < differential; i++)
TrainController(first, (nomove ? last->
Next() : NULL));
1814 int r = CountVehiclesInChain(v) - 1;
1832 ClrBit(v->flags, VRF_REVERSING);
1838 for (
Train *u = v; u != NULL; u = u->
Next()) u->UpdateViewport(
false,
false);
1900 if (ret.
Failed())
return ret;
1906 return_cmd_error(STR_ERROR_CAN_T_REVERSE_DIRECTION_RAIL_VEHICLE_MULTIPLE_UNITS);
1933 while (last->
Next() != NULL) last = last->
Next();
1975 if (ret.
Failed())
return ret;
2011 default: NOT_REACHED();
2027 if (location != NULL) *location = tfdd.
tile;
2029 if (reverse != NULL) *reverse = tfdd.
reverse;
2037 static const SoundFx sfx[] = {
2048 SndPlayVehicleFx(sfx[RailVehInfo(engtype)->engclass],
this);
2069 case OT_GOTO_WAYPOINT:
2075 case OT_LEAVESTATION:
2120 for (
const Train *u = v; u != NULL; u = u->
Next()) {
2133 if (v->force_proceed ==
TFP_NONE) {
2249 for (
const Train *u = v; u != NULL; u = u->
Next()) {
2257 while (ft.
Follow(tile, td)) {
2292 static const byte _initial_tile_subcoord[6][4][3] = {
2293 {{ 15, 8, 1 }, { 0, 0, 0 }, { 0, 8, 5 }, { 0, 0, 0 }},
2294 {{ 0, 0, 0 }, { 8, 0, 3 }, { 0, 0, 0 }, { 8, 15, 7 }},
2295 {{ 0, 0, 0 }, { 7, 0, 2 }, { 0, 7, 6 }, { 0, 0, 0 }},
2296 {{ 15, 8, 2 }, { 0, 0, 0 }, { 0, 0, 0 }, { 8, 15, 6 }},
2297 {{ 15, 7, 0 }, { 8, 0, 4 }, { 0, 0, 0 }, { 0, 0, 0 }},
2298 {{ 0, 0, 0 }, { 0, 0, 0 }, { 0, 8, 4 }, { 7, 15, 0 }},
2319 default: NOT_REACHED();
2336 while (ft.
Follow(tile, cur_td)) {
2364 if (enterdir != NULL) *enterdir = ft.
m_exitdir;
2381 if (ft.m_err == CFollowTrackRail::EC_OWNER || ft.m_err == CFollowTrackRail::EC_NO_WAY) {
2391 while (tile != stopped || cur_td != stopped_td) {
2392 if (!ft.
Follow(tile, cur_td))
break;
2426 default: NOT_REACHED();
2436 StationID old_last_station_visited;
2438 bool suppress_implicit_orders;
2454 this->v->
dest_tile = this->old_dest_tile;
2468 if (skip_first) ++this->
index;
2474 if (this->index >= this->v->
GetNumOrders()) this->index = 0;
2477 assert(order != NULL);
2484 case OT_GOTO_STATION:
2485 case OT_GOTO_WAYPOINT:
2488 case OT_CONDITIONAL: {
2516 bool changed_signal =
false;
2520 if (got_reservation != NULL) *got_reservation =
false;
2532 do_track_reservation =
true;
2533 changed_signal =
true;
2535 }
else if (!do_track_reservation) {
2543 if (do_track_reservation) {
2551 if (res_dest.
okay) {
2553 if (got_reservation != NULL) *got_reservation =
true;
2586 bool path_found =
true;
2589 Track next_track =
DoTrainPathfind(v, new_tile, dest_enterdir, tracks, path_found, do_track_reservation, &res_dest);
2590 if (new_tile ==
tile) best_track = next_track;
2595 if (!do_track_reservation)
return best_track;
2612 if (got_reservation != NULL) *got_reservation =
true;
2621 if (got_reservation != NULL) *got_reservation =
true;
2637 DoTrainPathfind(v, next_tile, exitdir, reachable, path_found,
true, &cur_dest);
2639 res_dest = cur_dest;
2640 if (res_dest.
okay)
continue;
2644 if (got_reservation != NULL) *got_reservation =
false;
2645 changed_signal =
false;
2653 if (got_reservation != NULL) *got_reservation =
false;
2654 changed_signal =
false;
2699 if (other_train != NULL && other_train->
index != v->
index) {
2704 if (origin.
okay && (v->
tile != origin.
tile || first_tile_okay)) {
2723 bool res_made =
false;
2724 ChooseTrainTrack(v, new_tile, exitdir, reachable,
true, &res_made, mark_as_stuck);
2741 static bool CheckReverseTrain(
const Train *v)
2755 default: NOT_REACHED();
2785 }
while ((v = v->
Next()) != NULL);
2802 default: NOT_REACHED();
2822 if (!(st->had_vehicle_of_type &
HVOT_TRAIN)) {
2826 STR_NEWS_FIRST_TRAIN_ARRIVAL,
2862 {256 / 4, 256 / 2, 256 / 4, 2},
2863 {256 / 4, 256 / 2, 256 / 4, 2},
2864 {0, 256 / 2, 256 / 4, 2},
2878 if (old_z < v->
z_pos) {
2903 for (
const Train *u =
this; u != NULL; u = u->
Next()) {
2932 for (
const Train *v =
this; v != NULL; v = v->
Next()) {
3006 if (coll == tcc->
v)
return NULL;
3015 uint hash = (y_diff + 7) | (x_diff + 7);
3016 if (hash & ~15)
return NULL;
3020 if (x_diff * x_diff + y_diff * y_diff > min_diff * min_diff)
return NULL;
3059 if (tcc.
num == 0)
return false;
3064 ModifyStationRatingAround(v->
tile, v->
owner, -160, 30);
3095 bool direction_changed =
false;
3098 for (prev = v->
Previous(); v != nomove; prev = v, v = v->
Next()) {
3100 bool update_signals_crossing =
false;
3152 if (!CheckCompatibleRail(v, gp.
new_tile))
goto invalid_rail;
3178 if ((red_signals & chosen_track) && v->force_proceed ==
TFP_NONE) {
3201 if (!
HasVehicleOnPos(o_tile, &exitdir, &CheckTrainAtSignal))
return false;
3211 v->wait_counter = 0;
3214 goto reverse_train_direction;
3226 chosen_track = bits;
3228 chosen_track = prev->track;
3246 chosen_track = _connecting_track[enterdir][exitdir];
3248 chosen_track &= bits;
3258 const byte *b = _initial_tile_subcoord[
FIND_FIRST_BIT(chosen_track)][enterdir];
3259 gp.x = (gp.x & ~0xF) | b[0];
3260 gp.
y = (gp.
y & ~0xF) | b[1];
3286 v->track = chosen_track;
3292 update_signals_crossing =
true;
3294 if (chosen_dir != v->direction) {
3300 direction_changed =
true;
3301 v->direction = chosen_dir;
3304 if (v->IsFrontEngine()) {
3305 v->wait_counter = 0;
3323 if (v->IsFrontEngine()) {
3335 v->UpdatePosition();
3336 if ((v->vehstatus &
VS_HIDDEN) == 0) v->Vehicle::UpdateViewport(
true);
3346 v->UpdatePosition();
3356 if (update_signals_crossing) {
3357 if (v->IsFrontEngine()) {
3358 if (TrainMovedChangeSignals(gp.
new_tile, enterdir)) {
3377 if (v->Next() == NULL) {
3393 if (prev != NULL)
error(
"Disconnecting train");
3395 reverse_train_direction:
3397 v->wait_counter = 0;
3422 *trackbits |= train_tbits;
3444 for (; v->
Next() != NULL; v = v->
Next()) u = v;
3502 static const DirDiff delta[] = {
3520 }
while ((v = v->
Next()) != NULL);
3537 if (state <= 200 &&
Chance16R(1, 7, r)) {
3538 int index = (r * 10 >> 16);
3552 }
while ((u = u->
Next()) != NULL);
3558 bool ret = v->
Next() != NULL;
3568 225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, 15
3583 uint x = v->
x_pos & 0xF;
3584 uint y = v->
y_pos & 0xF;
3589 case DIR_N : x = ~x + ~y + 25;
break;
3590 case DIR_NW: x = y; FALLTHROUGH;
3591 case DIR_NE: x = ~x + 16;
break;
3592 case DIR_E : x = ~x + y + 9;
break;
3593 case DIR_SE: x = y;
break;
3594 case DIR_S : x = x + y - 7;
break;
3595 case DIR_W : x = ~y + x + 9;
break;
3667 !CheckCompatibleRail(v, tile)) {
3733 static bool TrainLocoHandler(
Train *v,
bool mode)
3740 if (v->force_proceed !=
TFP_NONE) {
3810 if (v->force_proceed ==
TFP_NONE)
return true;
3848 if (j < adv_spd || v->
cur_speed == 0)
break;
3852 if ((order_type == OT_GOTO_WAYPOINT || order_type == OT_GOTO_STATION) &&
3862 for (
Train *u = v; u != NULL; u = u->
Next()) {
3863 if ((u->vehstatus &
VS_HIDDEN) != 0)
continue;
3865 u->UpdateViewport(
false,
false);
3880 const Train *v =
this;
3884 if (e->u.rail.running_cost_class == INVALID_PRICE)
continue;
3887 if (cost_factor == 0)
continue;
3892 cost +=
GetPrice(e->u.rail.running_cost_class, cost_factor, e->
GetGRF());
3913 if (!TrainLocoHandler(
this,
false))
return false;
3915 return TrainLocoHandler(
this,
true);
3943 default: NOT_REACHED();
3981 CheckVehicleBreakdown(
this);
T * GetLastEnginePart()
Get the last part of an articulated engine.
bool TryPathReserve(Train *v, bool mark_as_stuck, bool first_tile_okay)
Try to reserve a path to a safe position.
Functions related to OTTD's strings.
void TriggerStationRandomisation(Station *st, TileIndex tile, StationRandomTrigger trigger, CargoID cargo_type)
Trigger station randomisation.
void ReverseTrainSwapVeh(Train *v, int l, int r)
Swap vehicles l and r in consist v, and reverse their direction.
static Vehicle * TrainApproachingCrossingEnum(Vehicle *v, void *data)
Checks if a train is approaching a rail-road crossing.
bool HasVehicleOnPos(TileIndex tile, void *data, VehicleFromPosProc *proc)
Checks whether a vehicle is on a specific location.
VehicleSettings vehicle
options for vehicles
This vehicle is in the exclusive preview stage, either being used or being offered to a company...
static bool HasPowerOnRail(RailType enginetype, RailType tiletype)
Checks if an engine of the given RailType got power on a tile with a given RailType.
Functions/types related to NewGRF debugging.
static void Swap(T &a, T &b)
Type safe swap operation.
uint16 reliability
Current reliability of the engine.
uint32 PaletteID
The number of the palette.
static bool HasSignalOnTrackdir(TileIndex tile, Trackdir trackdir)
Checks for the presence of signals along the given trackdir on the given rail tile.
Vehicle is stopped by the player.
First vehicle arrived for competitor.
bool cached_tilt
train can tilt; feature provides a bonus in curves
VehicleCargoList cargo
The cargo this vehicle is carrying.
GameSettings _settings_game
Game settings of a running game or the scenario editor.
static void NewEvent(class ScriptEvent *event)
Queue a new event for a Game Script.
Definition of stuff that is very close to a company, like the company struct itself.
static PBSTileInfo ExtendTrainReservation(const Train *v, TrackBits *new_tracks, DiagDirection *enterdir)
Extend a train path as far as possible.
static bool IsDiagonalDirection(Direction dir)
Checks if a given Direction is diagonal.
Money value
Value of the vehicle.
int CalcNextVehicleOffset() const
Calculate the offset from this vehicle's center to the following center taking the vehicle lengths in...
bool _networking
are we in networking mode?
uint16 DepotID
Type for the unique identifier of depots.
int GetAcceleration() const
Calculates the acceleration of the vehicle under its current conditions.
static const RailtypeInfo * GetRailTypeInfo(RailType railtype)
Returns a pointer to the Railtype information for a given railtype.
void DecreaseVehicleValue(Vehicle *v)
Decrease the value of a vehicle.
static const int DAYS_IN_YEAR
days per year
static const uint CALLBACK_FAILED
Different values for Callback result evaluations.
static void SetTunnelBridgeReservation(TileIndex t, bool b)
Set the reservation state of the rail tunnel/bridge.
void ShowVisualEffect() const
Draw visual effects (smoke and/or sparks) for a vehicle chain.
bool UsesWagonOverride(const Vehicle *v)
Check if a wagon is currently using a wagon override.
bool Follow(TileIndex old_tile, Trackdir old_td)
main follower routine.
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 SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
static DiagDirection DirToDiagDir(Direction dir)
Convert a Direction to a DiagDirection.
DirectionByte direction
facing
void InvalidateNewGRFInspectWindow(GrfSpecFeature feature, uint index)
Invalidate the inspect window for a given feature and index.
Bitmask for the first 6 bits.
static int UnScaleGUI(int value)
Short-hand to apply GUI zoom level.
TrackdirBits m_new_td_bits
the new set of available trackdirs
uint32 maximum_go_to_depot_penalty
What is the maximum penalty that may be endured for going to a depot.
bool m_is_tunnel
last turn passed tunnel
Train is just leaving a station.
void CheckOrders(const Vehicle *v)
Check the orders of a vehicle, to see if there are invalid orders and stuff.
void SetFrontEngine()
Set front engine state.
bool TrainController(Train *v, Vehicle *nomove, bool reverse=true)
Move a vehicle chain one movement stop forwards.
void MarkBridgeDirty(TileIndex begin, TileIndex end, DiagDirection direction, uint bridge_height)
Mark bridge tiles dirty.
static FindDepotData FindClosestTrainDepot(Train *v, int max_distance)
Try to find a depot nearby.
int TicksToLeaveDepot(const Train *v)
Compute number of ticks when next wagon will leave a depot.
ConsistChangeFlags
Flags for Train::ConsistChanged.
byte curve_speed
Multiplier for curve maximum speed advantage.
Flag for an invalid DiagDirection.
Max. speed: 1 unit = 1/1.6 mph = 1 km-ish/h.
static Titem * Get(size_t index)
Returns Titem with given index.
static bool TrainCheckIfLineEnds(Train *v, bool reverse=true)
Checks for line end.
static bool IsBridgeTile(TileIndex t)
checks if there is a bridge on this tile
Capacity of vehicle changes when not refitting or arranging.
void PlayLeaveStationSound() const
Play a sound for a train leaving the station.
Angle of 45 degrees left.
static T ToggleBit(T &x, const uint8 y)
Toggles a bit in a variable.
uint DoUpdateSpeed(uint accel, int min_speed, int max_speed)
Update the speed of the vehicle.
static Track TrackdirToTrack(Trackdir trackdir)
Returns the Track that a given Trackdir represents.
Vehicle composition was changed.
Trigger platform when train arrives.
static bool TrainApproachingCrossing(TileIndex tile)
Finds a vehicle approaching rail-road crossing.
static CommandCost CheckTrainAttachment(Train *t)
Check whether the train parts can be attached.
Use default vehicle palette.
Angle of 90 degrees right.
static bool HasCrossingReservation(TileIndex t)
Get the reservation state of the rail crossing.
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.
static const VehicleOrderID INVALID_VEH_ORDER_ID
Invalid vehicle order index (sentinel)
static void NormaliseTrainHead(Train *head)
Normalise the head of the train again, i.e.
void AddArticulatedParts(Vehicle *first)
Add the remaining articulated parts to the given vehicle.
bool reverse
True if reversing is necessary for the train to get to this depot.
static T SetBit(T &x, const uint8 y)
Set a bit in a variable.
Sprites to use for trains.
Track
These are used to specify a single track.
uint16 cur_speed
current speed
Temporary data storage for testing collisions.
static void AddVehicleAdviceNewsItem(StringID string, VehicleID vehicle)
Adds a vehicle-advice news item.
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
void ReserveTrackUnderConsist() const
Tries to reserve track under whole train consist.
static int ScaleGUITrad(int value)
Scale traditional pixel dimensions to GUI zoom level.
Depot view; Window numbers:
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.
Rail vehicle can be flipped in the depot.
Types for recording game performance data.
byte spritenum
currently displayed sprite index 0xfd == custom sprite, 0xfe == custom second head sprite 0xff == res...
CommandCost CmdBuildRailVehicle(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **ret)
Build a railroad vehicle.
bool IsStoppedInDepot() const
Check whether the vehicle is in the depot and stopped.
Both directions faces to the same direction.
fluid_settings_t * settings
FluidSynth settings handle.
OrderList * list
Pointer to the order list for this vehicle.
Train * GetNextUnit() const
Get the next real (non-articulated part and non rear part of dualheaded engine) vehicle in the consis...
StationID last_loading_station
Last station the vehicle has stopped at and could possibly leave from with any cargo loaded...
Yearly runningcost (if dualheaded: sum of both vehicles)
TileIndex dest_tile
Heading for this tile.
uint16 wait_counter
Ticks waiting in front of a signal, ticks being stuck or a counter for forced proceeding through sign...
static bool IsOnewaySignal(TileIndex t, Track track)
One-way signals can't be passed the 'wrong' way.
NPFSettings npf
pathfinder settings for the new pathfinder
Functions related to vehicles.
static TrackBits DiagDirToDiagTrackBits(DiagDirection diagdir)
Maps a (4-way) direction to the diagonal track bits incidating with that diagdir. ...
Stop at the middle of the platform.
static void NormaliseDualHeads(Train *t)
Normalise the dual heads in the train, i.e.
bool lost_vehicle_warn
if a vehicle can't find its destination, show a warning
void IncrementRealOrderIndex()
Advanced cur_real_order_index to the next real order, keeps care of the wrap-around and invalidates t...
uint32 current_order_time
How many ticks have passed since this order started.
static uint TileX(TileIndex tile)
Get the X component of a tile.
void VehicleEnterDepot(Vehicle *v)
Vehicle entirely entered the depot, update its status, orders, vehicle windows, service it...
void GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const
Get the sprite to display the train.
void Draw(int x, int y, PaletteID default_pal, bool force_pal) const
Draw the sprite sequence.
PathfinderSettings pf
settings for all pathfinders
VehicleOrderID ProcessConditionalOrder(const Order *order, const Vehicle *v)
Process a conditional order and determine the next order.
static TileIndex TileAddByDiagDir(TileIndex tile, DiagDirection dir)
Adds a DiagDir to a tile.
int UpdateSpeed()
This function looks at the vehicle and updates its speed (cur_speed and subspeed) variables...
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...
const T * Begin() const
Get the pointer to the first item (const)
void LeaveStation()
Perform all actions when leaving a station.
void Set(SpriteID sprite)
Assign a single sprite to the sequence.
DifficultySettings difficulty
settings related to the difficulty
bool ambient
Play ambient, industry and town sounds.
Tindex index
Index of this pool item.
static CommandCost CheckNewTrain(Train *original_dst, Train *dst, Train *original_src, Train *src)
Check/validate whether we may actually build a new train.
CommandCost CmdReverseTrainDirection(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Reverse train.
static const int DAY_TICKS
1 day is 74 ticks; _date_fract used to be uint16 and incremented by 885.
uint16 speed
maximum travel speed (1 unit = 1/1.6 mph = 1 km-ish/h)
void SetNext(Vehicle *next)
Set the next vehicle of this vehicle.
T * First() const
Get the first vehicle in the chain.
bool forbid_90_deg
forbid trains to make 90 deg turns
void UpdateViewport(bool force_update, bool update_delta)
Update vehicle sprite- and position caches.
bool IsMultiheaded() const
Check if the vehicle is a multiheaded engine.
static bool IsRailWaypointTile(TileIndex t)
Is this tile a station tile and a rail waypoint?
StationID last_station_visited
The last station we stopped at.
Rail vehicle tilts in curves.
uint16 reliability_spd_dec
Reliability decrease speed.
static Track DiagDirToDiagTrack(DiagDirection diagdir)
Maps a (4-way) direction to the diagonal track incidating with that diagdir.
Simple vector template class.
void DeleteVehicleOrders(Vehicle *v, bool keep_orderlist, bool reset_order_indices)
Delete all orders from a vehicle.
Determine whether a wagon can be attached to an already existing train.
TileIndex m_old_tile
the origin (vehicle moved from) before move
StringID GetGRFStringID(uint32 grfid, StringID stringid)
Returns the index for this stringid associated with its grfID.
A game paused because a (critical) error.
Money GetCost() const
The costs as made up to this moment.
RailTypes compatible_railtypes
bitmask to the OTHER railtypes on which an engine of THIS railtype can physically travel ...
void HandlePathfindingResult(bool path_found)
Handle the pathfinding result, especially the lost status.
Number of ticks before carried cargo is aged.
static void InsertInConsist(Train *dst, Train *chain)
Inserts a chain into the train at dst.
Standard non-electric rails.
T * GetFirstEnginePart()
Get the first part of an articulated engine.
void CargoChanged()
Recalculates the cached weight of a vehicle and its parts.
Common return value for all commands.
static TrackdirBits DiagdirReachesTrackdirs(DiagDirection diagdir)
Returns all trackdirs that can be reached when entering a tile from a given (diagonal) direction...
uint32 cached_power
Total power of the consist (valid only for the first engine).
static const VehicleID INVALID_VEHICLE
Constant representing a non-existing vehicle.
bool m_is_station
last turn passed station
static CommandCost ValidateTrains(Train *original_dst, Train *dst, Train *original_src, Train *src, bool check_limit)
Validate whether we are going to create valid trains.
static T max(const T a, const T b)
Returns the maximum of two values.
PBSTileInfo FollowTrainReservation(const Train *v, Vehicle **train_on_res)
Follow a train reservation to the last tile.
static void SwapTrainFlags(uint16 *swap_flag1, uint16 *swap_flag2)
Swap the two up/down flags in two ways:
EngineImageType
Visualisation contexts of vehicles and engines.
byte flags
Flags of the engine.
static DiagDirection TrackdirToExitdir(Trackdir trackdir)
Maps a trackdir to the (4-way) direction the tile is exited when following that trackdir.
UnitID GetFreeUnitNumber(VehicleType type)
Get an unused unit number for a vehicle (if allowed).
Year _cur_year
Current year, starting at 0.
uint StoredCount() const
Returns sum of cargo on board the vehicle (ie not only reserved).
void CheckTrainsLengths()
Checks if lengths of all rail vehicles are valid.
static void SetSignalStateByTrackdir(TileIndex tile, Trackdir trackdir, SignalState state)
Sets the state of the signal along the given trackdir.
bool m_is_bridge
last turn passed bridge ramp
static Train * From(Vehicle *v)
Converts a Vehicle to SpecializedVehicle with type checking.
static void RestoreTrainBackup(TrainList &list)
Restore the train from the backup list.
bool TryReserveRailTrack(TileIndex tile, Track t, bool trigger_stations)
Try to reserve a specific track on a tile.
uint16 cached_max_speed
Maximum speed of the consist (minimum of the max speed of all vehicles in the consist).
const T * End() const
Get the pointer behind the last valid item (const)
Money GetRunningCost() const
Get running cost for the train consist.
bool NeedsAutomaticServicing() const
Checks if the current order should be interrupted for a service-in-depot order.
const Engine * GetEngine() const
Retrieves the engine of the vehicle.
CargoID GetDefaultCargoType() const
Determines the default cargo type of an engine.
static const uint TILE_SIZE
Tile size in world coordinates.
byte VehicleRandomBits()
Get a value for a vehicle's random_bits.
Money GetPrice(Price index, uint cost_factor, const GRFFile *grf_file, int shift)
Determine a certain price.
void AddCost(const Money &cost)
Adds the given cost to the cost of the command.
VehicleSpriteSeq sprite_seq
Vehicle appearance.
Direction
Defines the 8 directions on the map.
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.
static void ArrangeTrains(Train **dst_head, Train *dst, Train **src_head, Train *src, bool move_chain)
Arrange the trains in the wanted way.
The vehicle will stop at any station it passes except the destination.
int8 x_bb_offs
x offset of vehicle bounding box
static Vehicle * FindTrainCollideEnum(Vehicle *v, void *data)
Collision test function.
uint32 GetGRFID() const
Retrieve the GRF ID of the NewGRF the engine is tied to.
when autoreplace/autorenew is in progress, this shall prevent truncating the amount of cargo in the v...
This struct contains all the info that is needed to draw and construct tracks.
bool SwitchToNextOrder(bool skip_first)
Set the current vehicle order to the next order in the order list.
Stop at the near end of the platform.
T * Append(uint to_add=1)
Append an item and return it.
EngineID first_engine
Cached EngineID of the front vehicle. INVALID_ENGINE for the front vehicle itself.
static void SetCrossingBarred(TileIndex t, bool barred)
Set the bar state of a level crossing.
CompanyByte _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
Functions related to (drawing on) viewports.
Normal rail tile with signals.
Pseudo random number generator.
uint Crash(bool flooded=false)
The train vehicle crashed! Update its status and other parts around it.
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...
int8 y_bb_offs
y offset of vehicle bounding box
Angle of 45 degrees right.
byte breakdown_ctr
Counter for managing breakdown events.
Stop at the far end of the platform.
static Track TrackBitsToTrack(TrackBits tracks)
Converts TrackBits to Track.
static bool CheckTrainCollision(Train *v)
Checks whether the specified train has a collision with another vehicle.
static void MakeTrainBackup(TrainList &list, Train *t)
Make a backup of a train into a train list.
static const AccelerationSlowdownParams _accel_slowdown[]
Speed update fractions for each acceleration type.
Train()
We don't want GCC to zero our struct! It already is zeroed and has an index!
TextEffectID fill_percent_te_id
a text-effect id to a loading indicator object
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...
static bool IsCompatibleTrainStationTile(TileIndex test_tile, TileIndex station_tile)
Check if a tile is a valid continuation to a railstation tile.
bool reverse_at_signals
whether to reverse at signals at all
TrackBits
Bitfield corresponding to Track.
Critical errors, the MessageBox is shown in all cases.
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...
static void MaybeBarCrossingWithSound(TileIndex tile)
Bars crossing and plays ding-ding sound if not barred already.
uint16 cargo_cap
total capacity
void VehicleLengthChanged(const Vehicle *u)
Logs a bug in GRF and shows a warning message if this is for the first time this happened.
static bool IsTileOwner(TileIndex tile, Owner owner)
Checks if a tile belongs to the given owner.
void ShowErrorMessage(StringID summary_msg, StringID detailed_msg, WarningLevel wl, int x=0, int y=0, const GRFFile *textref_stack_grffile=NULL, uint textref_stack_size=0, const uint32 *textref_stack=NULL)
Display an error message in a window.
Header of Action 04 "universal holder" structure and functions.
OrderDepotTypeFlags GetDepotOrderType() const
What caused us going to the depot?
byte z_up
Fraction to remove when moving up.
Vehicle orders; Window numbers:
User defined data for vehicle variable 0x42.
void GetTrainSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type)
Get the size of the sprite of a train sprite heading west, or both heads (used for lists)...
static const uint32 MAKE_ORDER_BACKUP_FLAG
Flag to pass to the vehicle construction command when an order should be preserved.
uint8 freight_trains
value to multiply the weight of cargo by
Vehicle is a prototype (accepted as exclusive preview).
static DiagDirection DiagdirBetweenTiles(TileIndex tile_from, TileIndex tile_to)
Determines the DiagDirection to get from one tile to another.
byte acceleration
used by train & aircraft
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.
static TileIndexDiff TileOffsByDiagDir(DiagDirection dir)
Convert a DiagDirection to a TileIndexDiff.
uint16 reliability_spd_dec
Speed of reliability decay between services (per day).
int traininfo_vehicle_pitch
Vertical offset for draing train images in depot GUI and vehicle details.
static bool IsValidTrackdir(Trackdir trackdir)
Checks if a Trackdir is valid for non-road vehicles.
bool Tick()
Update train vehicle data for a tick.
void SubtractMoneyFromCompanyFract(CompanyID company, CommandCost cst)
Subtract money from a company, including the money fraction.
Track NPFTrainChooseTrack(const Train *v, bool &path_found, bool reserve_track, struct PBSTileInfo *target)
Finds the best path for given train using NPF.
static bool IsTileType(TileIndex tile, TileType type)
Checks if a tile is a given tiletype.
bool IsWagon() const
Check if a vehicle is a wagon.
static void DeleteLastWagon(Train *v)
Deletes/Clears the last wagon of a crashed train.
Functions related to errors.
static Vehicle * TrainOnTileEnum(Vehicle *v, void *)
Check if the vehicle is a train.
SmallVector< Train *, 16 > TrainList
Helper type for lists/vectors of trains.
Track along the y-axis (north-west to south-east)
UnitID unitnumber
unit number, for display purposes only
int y
x and y position of the vehicle after moving
CommandCost DoCommand(const CommandContainer *container, DoCommandFlag flags)
Shorthand for calling the long DoCommand with a container.
byte cargo_subtype
Used for livery refits (NewGRF variations)
uint Length() const
Get the number of items in the list.
void AgeVehicle(Vehicle *v)
Update age of a vehicle.
void SetEngine()
Set engine status.
FindDepotData NPFTrainFindNearestDepot(const Train *v, int max_penalty)
Used when user sends train to the nearest depot or if train needs servicing using NPF...
uint16 crash_anim_pos
Crash animation counter.
bool IsValid() const
Check whether the sequence contains any sprites.
static void UpdateStatusAfterSwap(Train *v)
Updates some variables after swapping the vehicle.
SoundSettings sound
sound effect settings
static bool IsRailStationTile(TileIndex t)
Is this tile a station tile and a rail station?
void ConsistChanged(ConsistChangeFlags allowed_changes)
Recalculates the cached stuff of a train.
Segment is a PBS segment.
YAPFSettings yapf
pathfinder settings for the yet another pathfinder
#define FIND_FIRST_BIT(x)
Returns the first non-zero bit in a 6-bit value (from right).
bool NeedsServicing() const
Check if the vehicle needs to go to a depot in near future (if a opportunity presents itself) for ser...
void MakeDummy()
Makes this order a Dummy order.
int8 y_offs
y offset for vehicle sprite
void HideFillingPercent(TextEffectID *te_id)
Hide vehicle loading indicators.
uint32 VehicleID
The type all our vehicle IDs have.
CommandCost CmdForceTrainProceed(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Force a train through a red signal.
uint16 pow_wag_power
Extra power applied to consist if wagon should be powered.
bool IsType(OrderType type) const
Check whether this order is of the given type.
uint16 max_speed
Maximum speed (1 unit = 1/1.6 mph = 1 km-ish/h)
CommandCost TunnelBridgeIsFree(TileIndex tile, TileIndex endtile, const Vehicle *ignore)
Finds vehicle in tunnel / bridge.
static Owner GetTileOwner(TileIndex tile)
Returns the owner of a tile.
static DiagDirection GetRailDepotDirection(TileIndex t)
Returns the direction the depot is facing to.
static DiagDirection ReverseDiagDir(DiagDirection d)
Returns the reverse direction of the given DiagDirection.
DoCommandFlag
List of flags for a command.
T * Next() const
Get next vehicle in the chain.
byte callback_mask
Bitmask of vehicle callbacks that have to be called.
simple wagon, not motorized
ClientSettings _settings_client
The current settings for this game.
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.
The vehicle either entered a bridge, tunnel or depot tile (this includes the last tile of the bridge/...
Definition of base types and functions in a cross-platform compatible way.
Shift the VehicleEnterTileStatus this many bits to the right to get the station ID when VETS_ENTERED_...
bool IsWaitingPositionFree(const Train *v, TileIndex tile, Trackdir trackdir, bool forbid_90deg)
Check if a safe position is free.
static const BridgeSpec * GetBridgeSpec(BridgeType i)
Get the specification of a bridge type.
static const uint VEHICLE_LENGTH
The length of a vehicle in tile units.
bool IsArticulatedPart() const
Check if the vehicle is an articulated part of an engine.
A number of safeguards to prevent using unsafe methods.
AccelStatus GetAccelerationStatus() const
Checks the current acceleration status of this vehicle.
byte x_extent
x-extent of vehicle bounding box
#define FOR_EACH_SET_TRACK(var, track_bits)
Iterate through each set Track in a TrackBits value.
uint best_length
The distance towards the depot in penalty, or UINT_MAX if not found.
uint8 acceleration_type
Acceleration type of this rail type.
bool ProcessOrders(Vehicle *v)
Handle the orders of a vehicle and determine the next place to go to if needed.
void SetTrainGroupID(Train *v, GroupID grp)
Affect the groupID of a train to new_g.
static Trackdir RemoveFirstTrackdir(TrackdirBits *trackdirs)
Removes first Trackdir from TrackdirBits and returns it.
Vehicle refit; Window numbers:
Vehicle length (trains and road vehicles)
This class will save the current order of a vehicle and restore it on destruction.
DirDiff
Enumeration for the difference between two directions.
byte z_extent
z-extent of vehicle bounding box
Trackdir
Enumeration for tracks and directions.
Vehicle starting, i.e. leaving, the station.
Valid changes for arranging the consist in a depot.
static Axis GetCrossingRailAxis(TileIndex t)
Get the rail axis of a level crossing.
static TrackdirBits TrackStatusToRedSignals(TrackStatus ts)
Returns the red-signal-information of a TrackStatus.
static bool HasPbsSignalOnTrackdir(TileIndex tile, Trackdir td)
Is a pbs signal present along the trackdir?
static void NormaliseSubtypes(Train *chain)
Normalise the sub types of the parts in this chain.
CargoID cargo_type
type of cargo this vehicle is carrying
static Axis GetCrossingRoadAxis(TileIndex t)
Get the road axis of a level crossing.
static bool IsValidDiagDirection(DiagDirection d)
Checks if an integer value is a valid DiagDirection.
void AddToShared(Vehicle *shared_chain)
Adds this vehicle to a shared vehicle chain.
byte capacity
Cargo capacity of vehicle; For multiheaded engines the capacity of each single engine.
Vehicle view; Window numbers:
byte large_turn
Speed change due to a large turn.
uint traininfo_vehicle_width
Width (in pixels) of a 8/8 train vehicle in depot GUI and vehicle details.
Functions related to order backups.
bool IsFrontEngine() const
Check if the vehicle is a front engine.
byte misc_flags
Miscellaneous flags.
void FindVehicleOnPos(TileIndex tile, void *data, VehicleFromPosProc *proc)
Find a vehicle from a specific location.
TileIndex tile
Current tile index.
CommandCost CheckOwnership(Owner owner, TileIndex tile)
Check whether the current owner owns something.
byte shorten_factor
length on main map for this type is 8 - shorten_factor
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.
byte FreightWagonMult(CargoID cargo)
Return the cargo weight multiplier to use for a rail vehicle.
Functions to access the new pathfinder.
static void CountVehicle(const Vehicle *v, int delta)
Update num_vehicle when adding or removing a vehicle.
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...
void MarkTileDirtyByTile(TileIndex tile, int bridge_level_offset, int tile_height_override)
Mark a tile given by its index dirty for repaint.
Vehicle timetable; Window numbers:
static void CheckIfTrainNeedsService(Train *v)
Check whether a train needs service, and if so, find a depot or service it.
static Trackdir DiagDirToDiagTrackdir(DiagDirection diagdir)
Maps a (4-way) direction to the diagonal trackdir that runs in that direction.
VehicleEnterTileStatus VehicleEnterTile(Vehicle *v, TileIndex tile, int x, int y)
Call the tile callback function for a vehicle entering a tile.
void UpdateDeltaXY()
Updates the x and y offsets and the size of the sprite used for this vehicle.
Basic functions/variables used all over the place.
static DirDiff DirDifference(Direction d0, Direction d1)
Calculate the difference between two directions.
bool IsRearDualheaded() const
Tell if we are dealing with the rear end of a multiheaded engine.
static Direction ChangeDir(Direction d, DirDiff delta)
Change a direction by a given difference.
bool okay
True if tile is a safe waiting position, false otherwise.
int8 x_offs
x offset for vehicle sprite
StationFacilityByte facilities
The facilities that this station has.
static void RemoveFromConsist(Train *part, bool chain=false)
Remove the given wagon from its consist.
Sprite sequence for a vehicle part.
static Track GetRailDepotTrack(TileIndex t)
Returns the track of a depot, ignoring direction.
void UpdateTrainGroupID(Train *v)
Recalculates the groupID of a train.
bool DoCommandP(const CommandContainer *container, bool my_cmd)
Shortcut for the long DoCommandP when having a container with the data.
static uint TrainCrashed(Train *v)
Marks train as crashed and creates an AI event.
DiagDirection
Enumeration for diagonal directions.
#define lengthof(x)
Return the length of an fixed size array.
static TrackdirBits TrackdirReachesTrackdirs(Trackdir trackdir)
Maps a trackdir to the trackdirs that can be reached from it (ie, when entering the next tile...
static T min(const T a, const T b)
Returns the minimum of two values.
bool NPFTrainCheckReverse(const Train *v)
Returns true if it is better to reverse the train before leaving station using NPF.
uint16 refit_cap
Capacity left over from before last refit.
byte random_bits
Bits used for determining which randomized variational spritegroups to use when drawing.
Functions related to sound.
Add articulated engines (trains and road vehicles)
uint16 reliability
Reliability.
Data structure for storing engine speed changes of an acceleration type.
static void CheckNextTrainTile(Train *v)
Check if the train is on the last reserved tile and try to extend the path then.
static DiagDirection GetTunnelBridgeDirection(TileIndex t)
Get the direction pointing to the other end.
static bool IsPlainRailTile(TileIndex t)
Checks whether the tile is a rail tile or rail tile with signals.
Vehicle is currently going uphill. (Cached track information for acceleration)
Track follower helper template class (can serve pathfinders and vehicle controllers).
Functions to cache sprites in memory.
uint32 StringID
Numeric value that represents a string, independent of the selected language.
bool Failed() const
Did this command fail?
uint16 power
Power of engine (hp); For multiheaded engines the sum of both engine powers.
byte tick_counter
Increased by one for each tick.
EffectVehicle * CreateEffectVehicleRel(const Vehicle *v, int x, int y, int z, EffectVehicleType type)
Create an effect vehicle above a particular vehicle.
void CheckCargoCapacity(Vehicle *v)
Check the capacity of all vehicles in a chain and spread cargo if needed.
bool UpdateOrderDest(Vehicle *v, const Order *order, int conditional_depth, bool pbs_look_ahead)
Update the vehicle's destination tile from an order.
CommandCost CmdSellRailWagon(DoCommandFlag flags, Vehicle *t, uint16 data, uint32 user)
Sell a (single) train wagon/engine.
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.
byte small_turn
Speed change due to a small turn.
int GetDisplayImageWidth(Point *offset=NULL) const
Get the width of a train vehicle image in the GUI.
static void BarCrossing(TileIndex t)
Bar a level crossing.
static DepotID GetDepotIndex(TileIndex t)
Get the index of which depot is attached to the tile.
Year build_year
Year the vehicle has been built.
bool PlayVehicleSound(const Vehicle *v, VehicleSoundEvent event)
Checks whether a NewGRF wants to play a different vehicle sound effect.
static Trackdir ReverseTrackdir(Trackdir trackdir)
Maps a trackdir to the reverse trackdir.
TileIndex tile
Tile the path ends, INVALID_TILE if no valid path was found.
#define return_cmd_error(errcode)
Returns from a function with a specific StringID as error.
Information about a rail vehicle.
static const uint16 _breakdown_speeds[16]
Maximum speeds for train that is broken down or approaching line end.
TrackStatus GetTileTrackStatus(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
Returns information about trackdirs and signal states.
bool IsPrimaryVehicle() const
Whether this is the primary vehicle in the chain.
uint DetermineCapacity(const Vehicle *v, uint16 *mail_capacity=NULL) const
Determines capacity of a given vehicle from scratch.
static void NewEvent(CompanyID company, ScriptEvent *event)
Queue a new event for an AI.
void OnNewDay()
Update day counters of the train vehicle.
static bool HasSignals(TileIndex t)
Checks if a rail tile has signals.
static T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
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.
autoreplace/autorenew is in progress, this shall disable vehicle limits when building, and ignore certain restrictions when undoing things (like vehicle attach callback)
static TrackBits DiagdirReachesTracks(DiagDirection diagdir)
Returns all tracks that can be reached when entering a tile from a given (diagonal) direction...
'Train' is either a loco or a wagon.
static bool Chance16(const uint a, const uint b)
Flips a coin with given probability.
TileIndex tile
The tile of the depot.
This struct contains information about the end of a reserved path.
static RailTileType GetRailTileType(TileIndex t)
Returns the RailTileType (normal with or without signals, waypoint or depot).
TileIndex old_tile
Current tile of the vehicle.
static BridgeType GetBridgeType(TileIndex t)
Determines the type of bridge on a tile.
static bool CheckTrainStayInDepot(Train *v)
Will the train stay in the depot the next tick?
FindDepotData YapfTrainFindNearestDepot(const Train *v, int max_distance)
Used when user sends train to the nearest depot or if train needs servicing using YAPF...
static bool TrainApproachingLineEnd(Train *v, bool signal, bool reverse)
Train is approaching line end, slow down and possibly reverse.
static TrackBits GetTrackBits(TileIndex tile)
Gets the track bits of the given tile.
CommandCost CmdMoveRailVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Move a rail vehicle around inside the depot.
void DeleteWindowById(WindowClass cls, WindowNumber number, bool force)
Delete a window by its class and window number (if it is open).
static Axis DiagDirToAxis(DiagDirection d)
Convert a DiagDirection to the axis.
union Vehicle::@47 orders
The orders currently assigned to the vehicle.
Bitflag for a wormhole (used for tunnels)
static TileIndex GetOtherTunnelBridgeEnd(TileIndex t)
Determines type of the wormhole and returns its other end.
Angle of 90 degrees left.
execute the given command
bool FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
Locate the closest depot for this consist, and return the information to the caller.
static const EngineID INVALID_ENGINE
Constant denoting an invalid engine.
static TrackBits TrackToTrackBits(Track track)
Maps a Track to the corresponding TrackBits value.
static const GroupID DEFAULT_GROUP
Ungrouped vehicles are in this group.
static void AdvanceWagonsAfterSwap(Train *v)
Advances wagons for train reversing, needed for variable length wagons.
Functions related to companies.
byte path_backoff_interval
ticks between checks for a free path.
RailType GetTileRailType(TileIndex tile)
Return the rail type of tile, or INVALID_RAILTYPE if this is no rail tile.
GetNewVehiclePosResult GetNewVehiclePos(const Vehicle *v)
Get position information of a vehicle when moving one pixel in the direction it is facing...
void UpdatePosition()
Update the position of the vehicle.
static StationID GetStationIndex(TileIndex t)
Get StationID from a tile.
static TileIndex TileVirtXY(uint x, uint y)
Get a tile from the virtual XY-coordinate.
void CheckConsistencyOfArticulatedVehicle(const Vehicle *v)
Checks whether the specs of freshly build articulated vehicles are consistent with the information sp...
OrderStopLocation
Where to stop the trains.
Vehicle is currently going downhill. (Cached track information for acceleration)
Allow vehicles to change length.
Electric train engine is allowed to run on normal rail. */.
static T KillFirstBit(T value)
Clear the first bit in an integer.
Functions related to articulated vehicles.
void ErrorUnknownCallbackResult(uint32 grfid, uint16 cbid, uint16 cb_res)
Record that a NewGRF returned an unknown/invalid callback result.
Trigger platform when train arrives.
Header file for NewGRF stations.
Flag for an invalid track.
static T ClrBit(T &x, const uint8 y)
Clears a bit in a variable.
Train can't get a path reservation.
Trackdir GetVehicleTrackdir() const
Get the tracks of the train vehicle.
static bool TrainCanLeaveTile(const Train *v)
Determines whether train would like to leave the tile.
T * Previous() const
Get previous vehicle in the chain.
GUISettings gui
settings related to the GUI
Tunnel entry/exit and bridge heads.
DestinationID GetDestination() const
Gets the destination of this order.
const GRFFile * GetGRF() const
Retrieve the NewGRF the engine is tied to.
void VehicleServiceInDepot(Vehicle *v)
Service a vehicle and all subsequent vehicles in the consist.
void SetWindowWidgetDirty(WindowClass cls, WindowNumber number, byte widget_index)
Mark a particular widget in a particular window as dirty (in need of repainting)
byte subspeed
fractional speed
static bool IsRailDepotTile(TileIndex t)
Is this tile rail tile and a rail depot?
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.
bool HandleBreakdown()
Handle all of the aspects of a vehicle breakdown This includes adding smoke and sounds, and ending the breakdown when appropriate.
int cached_max_curve_speed
max consist speed limited by curves
uint32 SpriteID
The number of a sprite, without mapping bits and colourtables.
OrderStopLocation GetStopLocation() const
Where must we stop at the platform?
Used for vehicle var 0xFE bit 8 (toggled each time the train is reversed, accurate for first vehicle ...
uint16 EngineID
Unique identification number of an engine.
bool line_reverse_mode
reversing at stations or not
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo ID.
CompanyByte _current_company
Company currently doing an action.
T * Last()
Get the last vehicle in the chain.
uint32 TileIndex
The index/ID of a Tile.
static const PaletteID PALETTE_CRASH
Recolour sprite greying of crashed vehicles.
The vehicle entered a station.
uint GetAdvanceDistance()
Determines the vehicle "progress" needed for moving a step.
Helper container to find a depot.
Station has seen a train.
void BeginLoading()
Prepare everything to begin the loading when arriving at a station.
Vehicle * Next() const
Get the next vehicle of this vehicle.
Date date_of_last_service
Last date the vehicle had a service at a depot.
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.
byte z_down
Fraction to add when moving down.
Position information of a vehicle after it moved.
Base includes/functions for YAPF.
static bool IsLevelCrossingTile(TileIndex t)
Return whether a tile is a level crossing tile.
First vehicle arrived for company.
void FindVehicleOnPosXY(int x, int y, void *data, VehicleFromPosProc *proc)
Find a vehicle from a specific location.
static bool HandleCrashedTrain(Train *v)
Handle a crashed train.
bool wagon_speed_limits
enable wagon speed limits
static uint TileY(TileIndex tile)
Get the Y component of a tile.
Train * v
Vehicle we are testing for collision.
void Free()
'Free' the order
void CDECL error(const char *s,...)
Error handling for fatal non-user errors.
OwnerByte owner
Which company owns the vehicle?
uint8 pathfinder_for_trains
the pathfinder to use for trains
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 T abs(const T a)
Returns the absolute value of (scalar) variable.
indicates a combination of two locomotives
TrackBits GetReservedTrackbits(TileIndex t)
Get the reserved trackbits for any tile, regardless of type.
TileIndex m_new_tile
the new tile (the vehicle has entered)
TileIndex xy
Base tile of the station.
static uint GB(const T x, const uint8 s, const uint8 n)
Fetch n bits from x, started at bit s.
uint16 cached_total_length
Length of the whole vehicle (valid only for the first engine).
byte wait_twoway_signal
waitingtime in days before a twoway signal
Trains list; Window numbers:
Functions related to zooming.
Vehicle * next
pointer to the next vehicle in the chain
static Track FindFirstTrack(TrackBits tracks)
Returns first Track from TrackBits or INVALID_TRACK.
Reverse the visible direction of the vehicle.
bool show_track_reservation
highlight reserved tracks.
void SetRailStationPlatformReservation(TileIndex start, DiagDirection dir, bool b)
Set the reservation for a complete station platform.
void CopyVehicleConfigAndStatistics(const Vehicle *src)
Copy certain configurations and statistics of a vehicle after successful autoreplace/renew The functi...
int GetCurveSpeedLimit() const
Computes train speed limit caused by curves.
T * GetNextVehicle() const
Get the next real (non-articulated part) vehicle in the consist.
bool disaster
Play disaster and accident sounds.
SigSegState
State of the signal segment.
uint16 cached_max_track_speed
Maximum consist speed limited by track type (valid only for the first engine).
Station with train station.
static bool CanAllocateItem(size_t n=1)
Helper functions so we can use PoolItem::Function() instead of _poolitem_pool.Function() ...
static bool IsCompatibleRail(RailType enginetype, RailType tiletype)
Checks if an engine of the given RailType can drive on a tile with a given RailType.
RailTypes powered_railtypes
bitmask to the OTHER railtypes on which an engine of THIS railtype generates power ...
Vehicle details; Window numbers:
void UpdateLevelCrossing(TileIndex tile, bool sound)
Sets correct crossing state.
static DiagDirection VehicleExitDir(Direction direction, TrackBits track)
Determine the side in which the vehicle will leave the tile.
TrackdirBits
Enumeration of bitmasks for the TrackDirs.
Base functions for all Games.
Functions related to commands.
static void AdvanceWagonsBeforeSwap(Train *v)
Advances wagons for train reversing, needed for variable length wagons.
Coordinates of a point in 2D.
An accident or disaster has occurred.
static void AffectSpeedByZChange(Train *v, int old_z)
Modify the speed of the vehicle due to a change in altitude.
uint32 GetGRFID() const
Retrieve the GRF ID of the NewGRF the vehicle is tied to.
Proceed till next signal, but ignore being stuck till then. This includes force leaving depots...
uint8 train_acceleration_model
realistic acceleration for trains
uint32 maximum_go_to_depot_penalty
What is the maximum penalty that may be endured for going to a depot.
Ignore next signal, after the signal ignore being stuck.
UnitID max_trains
max trains in game per company
static void ChangeTrainDirRandomly(Train *v)
Rotate all vehicles of a (crashed) train chain randomly to animate the crash.
Order * GetOrder(int index) const
Returns order 'index' of a vehicle or NULL when it doesn't exists.
static const StringID INVALID_STRING_ID
Constant representing an invalid string (16bit in case it is used in savegames)
VehicleOrderID GetNumOrders() const
Get the number of orders this vehicle has.
uint16 GetVehicleCallback(CallbackID callback, uint32 param1, uint32 param2, EngineID engine, const Vehicle *v)
Evaluate a newgrf callback for vehicles.
uint num
Total number of victims if train collided.
void MarkDirty()
Goods at the consist have changed, update the graphics, cargo, and acceleration.
DiagDirection m_exitdir
exit direction (leaving the old tile)
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...
void SetSignalsOnBothDir(TileIndex tile, Track track, Owner owner)
Update signals at segments that are at both ends of given (existent or non-existent) track...
void SetLastSpeed()
Update the GUI variant of the current speed of the vehicle.
uint8 cached_veh_length
Length of this vehicle in units of 1/VEHICLE_LENGTH of normal length. It is cached because this can b...
bool IsFreeWagon() const
Check if the vehicle is a free wagon (got no engine in front of it).
uint8 original_image_index
Original vehicle image index, thus the image index of the overridden vehicle.
byte running_ticks
Number of ticks this vehicle was not stopped this day.
byte y_extent
y-extent of vehicle bounding box
Flag to disable wagon power.
EngineID engine_type
The type of engine used for this vehicle.
Trackdir m_old_td
the trackdir (the vehicle was on) before move
static TrackBits TrackCrossesTracks(Track track)
Maps a track to all tracks that make 90 deg turns with it.
void RemoveVehicleFromGroup(const Vehicle *v)
Decrease the num_vehicle variable before delete an front engine from a group.
int GetCurrentMaxSpeed() const
Calculates the maximum speed of the vehicle under its current conditions.
Trackdir trackdir
The reserved trackdir on the tile.
byte VehicleOrderID
The index of an order within its current vehicle (not pool related)
uint16 vehicle_flags
Used for gradual loading and other miscellaneous things (.
static bool HasReservedTracks(TileIndex tile, TrackBits tracks)
Check whether some of tracks is reserved on a tile.
static bool HasBit(const T x, const uint8 y)
Checks if a bit in a value is set.
Functions related to NewGRF provided sounds.
Base functions for all AIs.
static TrackdirBits TrackBitsToTrackdirBits(TrackBits bits)
Converts TrackBits to TrackdirBits while allowing both directions.
static const TileIndex INVALID_TILE
The very nice invalid tile marker.
bool reserve_paths
always reserve paths regardless of signal type.
void SetFreeWagon()
Set a vehicle as a free wagon.
static bool IsCrossingBarred(TileIndex t)
Check if the level crossing is barred.
const GRFFile * GetGRF() const
Retrieve the NewGRF the vehicle is tied to.
static void NormalizeTrainVehInDepot(const Train *u)
Move all free vehicles in the depot to the train.
byte progress
The percentage (if divided by 256) this vehicle already crossed the tile unit.
The vehicle cannot enter the tile.
static bool IsPlainRail(TileIndex t)
Returns whether this is plain rails, with or without signals.
OrderType GetType() const
Get the type of order of this order.
Specification of a rectangle with absolute coordinates of all edges.
byte CargoID
Cargo slots to indicate a cargo type within a game.
uint16 GetMaxSpeed() const
Get the maxmimum speed in km-ish/h a vehicle is allowed to reach on the way to the destination...
uint16 cargo_age_period
Number of ticks before carried cargo is aged.
static Vehicle * CollectTrackbitsFromCrashedVehiclesEnum(Vehicle *v, void *data)
Collect trackbits of all crashed train vehicles on a tile.
byte wait_for_pbs_path
how long to wait for a path reservation.
static TrackBits TrackdirBitsToTrackBits(TrackdirBits bits)
Discards all directional information from a TrackdirBits value.
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.
static bool HasDepotReservation(TileIndex t)
Get the reservation state of the depot.
Owner
Enum for all companies/owners.
static CommandCost CmdBuildRailWagon(TileIndex tile, DoCommandFlag flags, const Engine *e, Vehicle **ret)
Build a railroad wagon.
Flag for an invalid trackdir.
uint Crash(bool flooded)
Common code executed for crashed ground vehicles.
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 void Backup(const Vehicle *v, uint32 user)
Create an order backup for the given vehicle.
Track along the x-axis (north-east to south-west)
static DiagDirection AxisToDiagDir(Axis a)
Converts an Axis to a DiagDirection.
Vehicle length, returns the amount of 1/8's the vehicle is shorter for trains and RVs...
bool YapfTrainCheckReverse(const Train *v)
Returns true if it is better to reverse the train before leaving station using YAPF.
static SignalState GetSignalStateByTrackdir(TileIndex tile, Trackdir trackdir)
Gets the state of the signal along the given trackdir.
static TileIndex TrainApproachingCrossingTile(const Train *v)
Determines whether train is approaching a rail-road crossing (thus making it barred) ...
int UpdateInclination(bool new_tile, bool update_delta)
Checks if the vehicle is in a slope and sets the required flags in that case.
move a rail vehicle (in the depot)
Money profit_this_year
Profit this year << 8, low 8 bits are fract.
void SetMultiheaded()
Set a vehicle as a multiheaded engine.
byte running_cost
Running cost of engine; For multiheaded engines the sum of both running costs.
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting)
Functions related to news.
TileIndex GetOrderStationLocation(StationID station)
Get the location of the next station to visit.
VehicleCache vcache
Cache of often used vehicle values.
static Station * Get(size_t index)
Gets station with given index.
int m_tiles_skipped
number of skipped tunnel or station tiles
Date _date
Current date in days (day counter)
uint GetPlatformLength(TileIndex tile, DiagDirection dir) const
Determines the REMAINING length of a platform, starting at (and including) the given tile...
void SetWagon()
Set a vehicle to be a wagon.
static Direction ReverseDir(Direction d)
Return the reverse of a direction.
byte wait_oneway_signal
waitingtime in days before a oneway signal
Company view; Window numbers:
static TrackdirBits TrackdirCrossesTrackdirs(Trackdir trackdir)
Maps a trackdir to all trackdirs that make 90 deg turns with it.
TileIndex new_tile
Tile of the vehicle after moving.
Vehicle * first
NOSAVE: pointer to the first vehicle in the chain.
Allow vehicles to change capacity.
void DeleteNewGRFInspectWindow(GrfSpecFeature feature, uint index)
Delete inspect window for a given feature and index.
This depot order is because of the servicing limit.
VehicleOrderID cur_real_order_index
The index to the current real (non-implicit) order.
static bool IsTunnel(TileIndex t)
Is this a tunnel (entrance)?
VehicleTypeByte type
Type of vehicle.
byte user_def_data
Property 0x25: "User-defined bit mask" Used only for (very few) NewGRF vehicles.
void HandleLoading(bool mode=false)
Handle the loading of the vehicle; when not it skips through dummy orders and does nothing in all oth...
Valid changes while vehicle is driving, and possibly changing tracks.
static TrackdirBits TrackStatusToTrackdirBits(TrackStatus ts)
Returns the present-trackdir-information of a TrackStatus.
SoundFx
Sound effects from baseset.
void ReverseTrainDirection(Train *v)
Turn a train around.
Functions related to effect vehicles.
OrderNonStopFlags GetNonStopType() const
At which stations must we stop?
Time spent processing trains.
void FreeTrainTrackReservation(const Train *v)
Free the reserved path in front of a vehicle.
uint32 cached_weight
Total weight of the consist (valid only for the first engine).
void InvalidateNewGRFCache()
Invalidates cached NewGRF variables.
Disable insertion and removal of automatic orders until the vehicle completes the real order...
void GetBounds(Rect *bounds) const
Determine shared bounds of all sprites.
Date GetLifeLengthInDays() const
Returns the vehicle's (not model's!) life length in days.
static void MarkTrainAsStuck(Train *v)
Mark a train as stuck and stop it if it isn't stopped right now.
byte day_counter
Increased by one for each day.
static RailType GetRailType(TileIndex t)
Gets the rail type of the given tile.
static bool TracksOverlap(TrackBits bits)
Checks if the given tracks overlap, ie form a crossing.
Order current_order
The current order (+ status, like: loading)
static bool IsBridge(TileIndex t)
Checks if this is a bridge, instead of a tunnel.
static Direction DiagDirToDir(DiagDirection dir)
Convert a DiagDirection to a Direction.
GroupID group_id
Index of group Pool array.
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-...
bool IsEngine() const
Check if a vehicle is an engine (can be first in a consist).
void UpdateAcceleration()
Update acceleration of the train from the cached power and weight.
GroundVehicleCache gcache
Cache of often calculated values.
void UnreserveRailTrack(TileIndex tile, Track t)
Lift the reservation of a specific track on a tile.
static Trackdir FindFirstTrackdir(TrackdirBits trackdirs)
Returns first Trackdir from TrackdirBits or INVALID_TRACKDIR.
SpriteID colourmap
NOSAVE: cached colour mapping.
static Train * GetIfValid(size_t index)
Returns vehicle if the index is a valid index for this vehicle type.
static void SetDParam(uint n, uint64 v)
Set a string parameter v at index n in the global string parameter array.
uint8 max_train_length
maximum length for trains
static void SetDepotReservation(TileIndex t, bool b)
Set the reservation state of the depot.
bool IsChainInDepot() const
Check whether the whole vehicle chain is in the depot.
static void AddVehicleNewsItem(StringID string, NewsType type, VehicleID vehicle, StationID station=INVALID_STATION)
Adds a newsitem referencing a vehicle.
Base for the NewGRF implementation.