Go to the documentation of this file.
55 #include "table/strings.h"
60 static const uint GEN_HASHX_BITS = 6;
61 static const uint GEN_HASHY_BITS = 6;
64 static const uint GEN_HASHX_BUCKET_BITS = 7;
65 static const uint GEN_HASHY_BUCKET_BITS = 6;
68 #define GEN_HASHX(x) GB((x), GEN_HASHX_BUCKET_BITS + ZOOM_LVL_SHIFT, GEN_HASHX_BITS)
69 #define GEN_HASHY(y) (GB((y), GEN_HASHY_BUCKET_BITS + ZOOM_LVL_SHIFT, GEN_HASHY_BITS) << GEN_HASHX_BITS)
70 #define GEN_HASH(x, y) (GEN_HASHY(y) + GEN_HASHX(x))
73 static const int GEN_HASHX_SIZE = 1 << (GEN_HASHX_BUCKET_BITS + GEN_HASHX_BITS + ZOOM_LVL_SHIFT);
74 static const int GEN_HASHY_SIZE = 1 << (GEN_HASHY_BUCKET_BITS + GEN_HASHY_BITS + ZOOM_LVL_SHIFT);
77 static const int GEN_HASHX_INC = 1;
78 static const int GEN_HASHY_INC = 1 << GEN_HASHX_BITS;
81 static const uint GEN_HASHX_MASK = (1 << GEN_HASHX_BITS) - 1;
82 static const uint GEN_HASHY_MASK = ((1 << GEN_HASHY_BITS) - 1) << GEN_HASHX_BITS;
100 bounds->left = bounds->top = bounds->right = bounds->bottom = 0;
101 for (uint i = 0; i < this->count; ++i) {
104 bounds->left = spr->
x_offs;
105 bounds->top = spr->
y_offs;
109 if (spr->
x_offs < bounds->left) bounds->left = spr->
x_offs;
110 if (spr->
y_offs < bounds->top) bounds->top = spr->
y_offs;
113 if (right > bounds->right) bounds->right = right;
114 if (bottom > bounds->bottom) bounds->bottom = bottom;
128 for (uint i = 0; i < this->count; ++i) {
129 PaletteID pal = force_pal || !this->seq[i].
pal ? default_pal : this->seq[i].
pal;
164 assert(v !=
nullptr);
192 if (this->ServiceIntervalIsPercent() ?
208 bool pending_replace =
false;
210 if (needed_money > c->
money)
return false;
213 bool replace_when_old =
false;
219 if (replace_when_old && !v->NeedsAutorenewing(c,
false))
continue;
222 CargoTypes available_cargo_types, union_mask;
225 if (union_mask != 0) {
239 pending_replace =
true;
240 needed_money += 2 *
Engine::Get(new_engine)->GetCost();
241 if (needed_money > c->
money)
return false;
244 return pending_replace;
263 assert(this->
Previous() ==
nullptr);
269 for (
Vehicle *v =
this; v !=
nullptr; v = v->
Next()) {
273 v->MarkAllViewportsDirty();
303 if (grfconfig ==
nullptr)
return;
317 GetString(buffer, part1,
lastof(buffer));
318 DEBUG(grf, 0,
"%s", buffer + 3);
321 GetString(buffer, part2,
lastof(buffer));
322 DEBUG(grf, 0,
"%s", buffer + 3);
365 return GB(Random(), 0, 8);
370 const int HASH_BITS = 7;
371 const int HASH_SIZE = 1 << HASH_BITS;
372 const int HASH_MASK = HASH_SIZE - 1;
373 const int TOTAL_HASH_SIZE = 1 << (HASH_BITS * 2);
374 const int TOTAL_HASH_MASK = TOTAL_HASH_SIZE - 1;
378 const int HASH_RES = 0;
380 static Vehicle *_vehicle_tile_hash[TOTAL_HASH_SIZE];
382 static Vehicle *VehicleFromTileHash(
int xl,
int yl,
int xu,
int yu,
void *data, VehicleFromPosProc *proc,
bool find_first)
384 for (
int y = yl; ; y = (y + (1 << HASH_BITS)) & (HASH_MASK << HASH_BITS)) {
385 for (
int x = xl; ; x = (x + 1) & HASH_MASK) {
386 Vehicle *v = _vehicle_tile_hash[(x + y) & TOTAL_HASH_MASK];
389 if (find_first && a !=
nullptr)
return a;
413 const int COLL_DIST = 6;
416 int xl =
GB((x - COLL_DIST) /
TILE_SIZE, HASH_RES, HASH_BITS);
417 int xu =
GB((x + COLL_DIST) /
TILE_SIZE, HASH_RES, HASH_BITS);
418 int yl =
GB((y - COLL_DIST) /
TILE_SIZE, HASH_RES, HASH_BITS) << HASH_BITS;
419 int yu =
GB((y + COLL_DIST) /
TILE_SIZE, HASH_RES, HASH_BITS) << HASH_BITS;
421 return VehicleFromTileHash(xl, yl, xu, yu, data, proc, find_first);
471 int x =
GB(
TileX(tile), HASH_RES, HASH_BITS);
472 int y =
GB(
TileY(tile), HASH_RES, HASH_BITS) << HASH_BITS;
474 Vehicle *v = _vehicle_tile_hash[(x + y) & TOTAL_HASH_MASK];
476 if (v->
tile != tile)
continue;
479 if (find_first && a !=
nullptr)
return a;
529 if (v->
z_pos > z)
return nullptr;
556 if (v == (
const Vehicle *)data)
return nullptr;
588 if ((t->track != rail_bits) && !
TracksOverlap(t->track | rail_bits))
return nullptr;
612 static void UpdateVehicleTileHash(
Vehicle *v,
bool remove)
621 int y =
GB(
TileY(v->
tile), HASH_RES, HASH_BITS) << HASH_BITS;
622 new_hash = &_vehicle_tile_hash[(x + y) & TOTAL_HASH_MASK];
625 if (old_hash == new_hash)
return;
628 if (old_hash !=
nullptr) {
634 if (new_hash !=
nullptr) {
645 static Vehicle *_vehicle_viewport_hash[1 << (GEN_HASHX_BITS + GEN_HASHY_BITS)];
647 static void UpdateVehicleViewportHash(
Vehicle *v,
int x,
int y,
int old_x,
int old_y)
649 Vehicle **old_hash, **new_hash;
651 new_hash = (x ==
INVALID_COORD) ?
nullptr : &_vehicle_viewport_hash[GEN_HASH(x, y)];
652 old_hash = (old_x ==
INVALID_COORD) ?
nullptr : &_vehicle_viewport_hash[GEN_HASH(old_x, old_y)];
654 if (old_hash == new_hash)
return;
657 if (old_hash !=
nullptr) {
663 if (new_hash !=
nullptr) {
671 void ResetVehicleHash()
674 memset(_vehicle_viewport_hash, 0,
sizeof(_vehicle_viewport_hash));
675 memset(_vehicle_tile_hash, 0,
sizeof(_vehicle_tile_hash));
678 void ResetVehicleColourMap()
690 void InitializeVehicles()
692 _vehicles_to_autoreplace.clear();
693 _vehicles_to_autoreplace.shrink_to_fit();
697 uint CountVehiclesInChain(
const Vehicle *v)
700 do count++;
while ((v = v->
Next()) !=
nullptr);
710 switch (this->
type) {
717 default:
return false;
727 switch (this->
type) {
732 default:
return false;
806 st->loading_vehicles.remove(
this);
860 extern void StopGlobalFollowVehicle(
const Vehicle *v);
861 StopGlobalFollowVehicle(
this);
882 UpdateVehicleTileHash(
this,
true);
912 if (_game_mode != GM_NORMAL)
return;
917 if (v ==
nullptr)
continue;
923 if (
HasBit(callback, 0)) {
924 TriggerVehicle(v, VEHICLE_TRIGGER_CALLBACK_32);
940 void CallVehicleTicks()
942 _vehicles_to_autoreplace.clear();
957 size_t vehicle_index = v->
index;
1029 for (
auto &it : _vehicles_to_autoreplace) {
1032 cur_company.Change(v->
owner);
1057 if (error_message == STR_ERROR_AUTOREPLACE_NOTHING_TO_DO || error_message ==
INVALID_STRING_ID)
continue;
1059 if (error_message == STR_ERROR_NOT_ENOUGH_CASH_REQUIRES_CURRENCY) error_message = STR_ERROR_AUTOREPLACE_MONEY_LIMIT;
1062 if (error_message == STR_ERROR_TRAIN_TOO_LONG_AFTER_REPLACEMENT) {
1063 message = error_message;
1065 message = STR_NEWS_VEHICLE_AUTORENEW_FAILED;
1073 cur_company.Restore();
1113 const int l = dpi->left;
1114 const int r = dpi->left + dpi->width;
1115 const int t = dpi->top;
1116 const int b = dpi->top + dpi->height;
1125 if (dpi->width + xb < GEN_HASHX_SIZE) {
1126 xl = GEN_HASHX(l - xb);
1131 xu = GEN_HASHX_MASK;
1134 if (dpi->height + yb < GEN_HASHY_SIZE) {
1135 yl = GEN_HASHY(t - yb);
1140 yu = GEN_HASHY_MASK;
1143 for (
int y = yl;; y = (y + GEN_HASHY_INC) & GEN_HASHY_MASK) {
1144 for (
int x = xl;; x = (x + GEN_HASHX_INC) & GEN_HASHX_MASK) {
1145 const Vehicle *v = _vehicle_viewport_hash[x + y];
1147 while (v !=
nullptr) {
1150 l <= v->
coord.right + xb &&
1151 t <= v->
coord.bottom + yb &&
1152 r >= v->
coord.left - xb &&
1153 b >= v->
coord.top - yb)
1181 if (l <= v->coord.right &&
1182 t <= v->coord.bottom &&
1183 r >= v->
coord.left &&
1207 uint dist, best_dist = UINT_MAX;
1209 if ((uint)(x -= vp->
left) >= (uint)vp->
width || (uint)(y -= vp->
top) >= (uint)vp->
height)
return nullptr;
1216 x >= v->
coord.left && x <= v->coord.right &&
1217 y >= v->
coord.top && y <= v->coord.bottom) {
1224 if (dist < best_dist) {
1244 static const byte _breakdown_chance[64] = {
1245 3, 3, 3, 3, 3, 3, 3, 3,
1246 4, 4, 5, 5, 6, 6, 7, 7,
1247 8, 8, 9, 9, 10, 10, 11, 11,
1248 12, 13, 13, 13, 13, 14, 15, 16,
1249 17, 19, 21, 25, 28, 31, 34, 37,
1250 40, 44, 48, 52, 56, 60, 64, 68,
1251 72, 80, 90, 100, 110, 120, 130, 140,
1252 150, 170, 190, 210, 230, 250, 250, 250,
1255 void CheckVehicleBreakdown(
Vehicle *v)
1268 v->
cur_speed < 5 || _game_mode == GM_MENU) {
1272 uint32 r = Random();
1287 if (_breakdown_chance[(uint)std::min(rel, 0xffff) >> 10] <= v->
breakdown_chance) {
1394 str = STR_NEWS_VEHICLE_IS_GETTING_OLD;
1395 }
else if (age == 0) {
1396 str = STR_NEWS_VEHICLE_IS_GETTING_VERY_OLD;
1398 str = STR_NEWS_VEHICLE_IS_GETTING_VERY_OLD_AND;
1422 bool loading =
false;
1428 assert(colour ==
nullptr || (st !=
nullptr && is_loading));
1434 for (
const Vehicle *v = front; v !=
nullptr; v = v->
Next()) {
1437 if (v->
cargo_cap != 0 && colour !=
nullptr) {
1439 loading |= !order_no_load &&
1446 if (colour !=
nullptr) {
1447 if (unloading == 0 && loading) {
1448 *colour = STR_PERCENT_UP;
1449 }
else if (unloading == 0 && !loading) {
1450 *colour = STR_PERCENT_NONE;
1451 }
else if (cars == unloading || !loading) {
1452 *colour = STR_PERCENT_DOWN;
1454 *colour = STR_PERCENT_UP_DOWN;
1459 if (max == 0)
return 100;
1462 if (count * 2 < max) {
1464 return CeilDiv(count * 100, max);
1467 return (count * 100) / max;
1478 assert(v == v->
First());
1514 default: NOT_REACHED();
1531 TriggerVehicle(v, VEHICLE_TRIGGER_DEPOT);
1556 _vehicles_to_autoreplace[v] =
false;
1562 }
else if (cost.
GetCost() != 0) {
1578 _vehicles_to_autoreplace[v] =
false;
1600 UpdateVehicleTileHash(
this,
false);
1613 new_coord.left += pt.x;
1614 new_coord.top += pt.y;
1615 new_coord.right += pt.x + 2 * ZOOM_LVL_BASE;
1616 new_coord.bottom += pt.y + 2 * ZOOM_LVL_BASE;
1633 this->
coord = new_coord;
1645 UpdateVehicleViewportHash(
this, this->
coord.left, this->coord.top, old_coord.left, old_coord.top);
1653 std::min(this->sprite_cache.old_coord.top, this->coord.top),
1654 std::max(this->sprite_cache.old_coord.right, this->coord.right),
1655 std::max(this->sprite_cache.old_coord.bottom, this->coord.bottom));
1685 static const int8 _delta_coord[16] = {
1686 -1,-1,-1, 0, 1, 1, 1, 0,
1687 -1, 0, 1, 1, 1, 0,-1,-1,
1701 static const Direction _new_direction_table[] = {
1711 if (y >= v->
y_pos) {
1712 if (y != v->
y_pos) i += 3;
1716 if (x >= v->
x_pos) {
1717 if (x != v->
x_pos) i++;
1753 if (v->
type == type && v->
owner == owner) {
1758 if (this->
maxid == 0)
return;
1763 this->
cache = CallocT<bool>(this->
maxid + 2);
1767 if (v->
type == type && v->
owner == owner) {
1776 if (this->maxid <= this->
curid)
return ++this->
curid;
1778 while (this->
cache[++this->curid]) { }
1797 default: NOT_REACHED();
1835 default: NOT_REACHED();
1842 if (type ==
VEH_ROAD && GetRoadTramType(e->u.road.roadtype) != (RoadTramType)subtype)
continue;
1870 default: NOT_REACHED();
1875 engine_type = parent_engine_type;
1880 if (cargo_type ==
CT_INVALID) cargo_type = e->GetDefaultCargoType();
1881 if (cargo_type ==
CT_INVALID) cargo_type = CT_GOODS;
1885 return LS_PASSENGER_WAGON_STEAM;
1888 switch (RailVehInfo(parent_engine_type)->engclass) {
1889 default: NOT_REACHED();
1890 case EC_STEAM:
return LS_PASSENGER_WAGON_STEAM;
1891 case EC_DIESEL:
return is_mu ? LS_DMU : LS_PASSENGER_WAGON_DIESEL;
1892 case EC_ELECTRIC:
return is_mu ? LS_EMU : LS_PASSENGER_WAGON_ELECTRIC;
1893 case EC_MONORAIL:
return LS_PASSENGER_WAGON_MONORAIL;
1894 case EC_MAGLEV:
return LS_PASSENGER_WAGON_MAGLEV;
1898 return LS_FREIGHT_WAGON;
1903 switch (e->u.rail.engclass) {
1904 default: NOT_REACHED();
1906 case EC_DIESEL:
return is_mu ? LS_DMU : LS_DIESEL;
1907 case EC_ELECTRIC:
return is_mu ? LS_EMU : LS_ELECTRIC;
1916 engine_type = parent_engine_type;
1920 if (cargo_type ==
CT_INVALID) cargo_type = e->GetDefaultCargoType();
1921 if (cargo_type ==
CT_INVALID) cargo_type = CT_GOODS;
1933 if (cargo_type ==
CT_INVALID) cargo_type = e->GetDefaultCargoType();
1934 if (cargo_type ==
CT_INVALID) cargo_type = CT_GOODS;
1938 switch (e->u.air.subtype) {
1939 case AIR_HELI:
return LS_HELICOPTER;
1940 case AIR_CTOL:
return LS_SMALL_PLANE;
1941 case AIR_CTOL | AIR_FAST:
return LS_LARGE_PLANE;
1942 default: NOT_REACHED();
1975 if (c->livery[LS_DEFAULT].
in_use != 0) {
1981 return &c->livery[scheme];
1990 if (map != PAL_NONE)
return map;
1999 static_assert(PAL_NONE == 0);
2000 map =
GB(callback, 0, 14);
2003 if (!
HasBit(callback, 14)) {
2005 if (v !=
nullptr)
const_cast<Vehicle *
>(v)->colourmap = map;
2021 if (twocc) map += livery->
colour2 * 16;
2024 if (v !=
nullptr)
const_cast<Vehicle *
>(v)->colourmap = map;
2036 return GetEngineColourMap(engine_type, company,
INVALID_ENGINE,
nullptr);
2070 while (order !=
nullptr) {
2073 if (order->
IsType(OT_IMPLICIT)) {
2079 order = order->
next;
2084 if (order ==
nullptr) {
2100 this->current_order.GetDestination() == this->last_station_visited) {
2121 (in_list ==
nullptr || !in_list->
IsType(OT_IMPLICIT) ||
2126 if (prev_order ==
nullptr ||
2127 (!prev_order->
IsType(OT_IMPLICIT) && !prev_order->
IsType(OT_GOTO_STATION)) ||
2139 if (order ==
nullptr)
break;
2145 if (target_index >= this->
orders.list->GetNumOrders()) {
2156 if (suppress_implicit_orders) {
2164 if (order->
IsType(OT_IMPLICIT)) {
2170 order = order->
next;
2175 if (order ==
nullptr) {
2179 assert(order !=
nullptr);
2182 }
else if (!suppress_implicit_orders &&
2227 for (
Vehicle *v =
this; v !=
nullptr; v = v->
next) {
2230 DEBUG(misc, 1,
"cancelling cargo reservation");
2273 st->loading_vehicles.remove(
this);
2319 if (order ==
nullptr ||
2320 (!order->
IsType(OT_IMPLICIT) && !order->
IsType(OT_GOTO_STATION)) ||
2327 case OT_DUMMY:
break;
2341 for (
const Vehicle *v =
this; v !=
nullptr; v = v->
Next()) {
2344 if (pair == capacities.End()) {
2352 uint Vehicle::GetConsistTotalCapacity()
const
2355 for (
const Vehicle *v =
this; v !=
nullptr; v = v->
Next()) {
2370 if (ret.
Failed())
return ret;
2407 DestinationID destination;
2409 static const StringID no_depot[] = {STR_ERROR_UNABLE_TO_FIND_ROUTE_TO, STR_ERROR_UNABLE_TO_FIND_LOCAL_DEPOT, STR_ERROR_UNABLE_TO_FIND_LOCAL_DEPOT, STR_ERROR_CAN_T_SEND_AIRCRAFT_TO_HANGAR};
2420 this->SetDestTile(location);
2469 callback =
GB(callback, 0, 8);
2476 visual_effect = callback;
2508 static const int8 _vehicle_smoke_pos[8] = {
2509 1, 1, 1, 0, -1, -1, -1, 0
2521 uint count =
GB(callback, 0, 2);
2522 bool auto_center =
HasBit(callback, 13);
2523 bool auto_rotate = !
HasBit(callback, 14);
2538 int8 x_center = _vehicle_smoke_pos[l_dir] * l_center;
2539 int8 y_center = _vehicle_smoke_pos[t_dir] * l_center;
2541 for (uint i = 0; i < count; i++) {
2543 uint type =
GB(reg, 0, 8);
2544 int8 x =
GB(reg, 8, 8);
2545 int8 y =
GB(reg, 16, 8);
2546 int8 z =
GB(reg, 24, 8);
2551 x = _vehicle_smoke_pos[l_dir] * l + _vehicle_smoke_pos[t_dir] * t;
2552 y = _vehicle_smoke_pos[t_dir] * l - _vehicle_smoke_pos[l_dir] * t;
2583 this->cur_speed < 2) {
2596 if (
HasBit(t->flags, VRF_REVERSING) ||
2612 if (effect_model >= VESM_END) effect_model =
VESM_NONE;
2639 switch (effect_model) {
2663 int power_weight_effect = 0;
2691 if (evt != EV_END && advanced) {
2694 }
else if (evt != EV_END) {
2702 int x = _vehicle_smoke_pos[v->
direction] * effect_offset;
2703 int y = _vehicle_smoke_pos[(v->
direction + 2) % 8] * effect_offset;
2712 }
while ((v = v->
Next()) !=
nullptr);
2723 assert(
this !=
next);
2725 if (this->next !=
nullptr) {
2727 for (
Vehicle *v = this->next; v !=
nullptr; v = v->
Next()) {
2735 if (this->next !=
nullptr) {
2739 for (
Vehicle *v = this->next; v !=
nullptr; v = v->
Next()) {
2780 this->
orders.list->RemoveVehicle(
this);
2790 if (this->
orders.list->GetNumVehicles() == 1) {
2794 }
else if (were_first) {
2804 void VehiclesYearlyLoop()
2810 if (v->
age >= 730 && profit < 0) {
2844 assert(e !=
nullptr);
2957 for (; u !=
nullptr && num_vehicles > 0; num_vehicles--) {
@ VEH_AIRCRAFT
Aircraft vehicle type.
bool lost_vehicle_warn
if a vehicle can't find its destination, show a warning
Buses, trucks and trams belong to this class.
GroundVehicleCache * GetGroundVehicleCache()
Access the ground vehicle cache of the vehicle.
void DeleteNewGRFInspectWindow(GrfSpecFeature feature, uint index)
Delete inspect window for a given feature and index.
@ VRF_TOGGLE_REVERSE
Used for vehicle var 0xFE bit 8 (toggled each time the train is reversed, accurate for first vehicle ...
static bool IsTunnelTile(TileIndex t)
Is this a tunnel (entrance)?
StationFacility facilities
The facilities that this station has.
StationID targetairport
Airport to go to next.
VehicleOrderID cur_implicit_order_index
The index to the current implicit order.
static const EngineID INVALID_ENGINE
Constant denoting an invalid engine.
static bool IsCompanyBuildableVehicleType(VehicleType type)
Is the given vehicle type buildable by a company?
bool PlayVehicleSound(const Vehicle *v, VehicleSoundEvent event)
Checks whether a NewGRF wants to play a different vehicle sound effect.
bool IsRefit() const
Is this order a refit order.
UnitID max_aircraft
max planes in game per company
@ WC_ROADVEH_LIST
Road vehicle list; Window numbers:
uint32 GetGRFID() const
Retrieve the GRF ID of the NewGRF the engine is tied to.
bool is_viewport_candidate
This vehicle can potentially be drawn on a viewport.
uint32 TileIndex
The index/ID of a Tile.
uint StoredCount() const
Returns sum of cargo on board the vehicle (ie not only reserved).
const Livery * GetEngineLivery(EngineID engine_type, CompanyID company, EngineID parent_engine_type, const Vehicle *v, byte livery_setting)
Determines the livery for a vehicle.
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.
GoodsEntry goods[NUM_CARGO]
Goods at this station.
@ EV_ELECTRIC_SPARK
Sparcs of electric engines.
@ DIRDIFF_REVERSE
One direction is the opposite of the other one.
@ VE_OFFSET_COUNT
Number of bits used for the offset.
void AircraftNextAirportPos_and_Order(Aircraft *v)
set the right pos when heading to other airports after takeoff
static Pool::IterateWrapperFiltered< Engine, EngineTypeFilter > IterateType(VehicleType vt, size_t from=0)
Returns an iterable ensemble of all valid engines of the given type.
@ VE_DISABLE_EFFECT
Flag to disable visual effect.
static bool Chance16(const uint a, const uint b)
Flips a coin with given probability.
CommandCost DoCommand(const CommandContainer *container, DoCommandFlag flags)
Shorthand for calling the long DoCommand with a container.
@ CMD_REVERSE_TRAIN_DIRECTION
turn a train around
bool IsType(OrderType type) const
Check whether this order is of the given type.
void PreDestructor()
Destroy all stuff that (still) needs the virtual functions to work properly.
static Titem * Get(size_t index)
Returns Titem with given index.
void PrepareUnload(Vehicle *front_v)
Prepare the vehicle to be unloaded.
Direction
Defines the 8 directions on the map.
uint16 GetTimetabledWait() const
Get the time in ticks a vehicle should wait at the destination or 0 if it's not timetabled.
void OnCleanPool()
Empty the cargo list, but don't free the cargo packets; the cargo packets are cleaned by CargoPacket'...
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
VehicleSpriteSeq sprite_seq
Vehicle appearance.
static void CountEngine(const Vehicle *v, int delta)
Update num_engines when adding/removing an engine.
GroupStatistics group_all[VEH_COMPANY_END]
NOSAVE: Statistics for the ALL_GROUP group.
static uint GB(const T x, const uint8 s, const uint8 n)
Fetch n bits from x, started at bit s.
VehicleOrderID GetNumManualOrders() const
Get the number of manually added orders this vehicle has.
Money value
Value of the vehicle.
@ DIRDIFF_45LEFT
Angle of 45 degrees left.
byte subtype
Type of aircraft.
static Direction ChangeDir(Direction d, DirDiff delta)
Change a direction by a given difference.
const TileTypeProcs *const _tile_type_procs[16]
Tile callback functions for each type of tile.
bool HasEngineType() const
Check whether Vehicle::engine_type has any meaning.
static Titem * GetIfValid(size_t index)
Returns Titem with given index.
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
@ ODTFB_SERVICE
This depot order is because of the servicing limit.
void IncreaseStats(Station *st, CargoID cargo, StationID next_station_id, uint capacity, uint usage, EdgeUpdateMode mode)
Increase capacity for a link stat given by station cargo and next hop.
uint16 animation_state
State primarily used to change the graphics/behaviour.
@ GBUG_VEH_POWERED_WAGON
Powered wagon changed poweredness state when not inside a depot.
uint16 & GetGroundVehicleFlags()
Access the ground vehicle flags of the vehicle.
bool IsEngineCountable() const
Check if a vehicle is counted in num_engines in each company struct.
@ CBID_VEHICLE_VISUAL_EFFECT
Visual effects and wagon power.
The information about a vehicle list.
Vehicle * Previous() const
Get the previous vehicle of this vehicle.
bool HasVehicleOnPos(TileIndex tile, void *data, VehicleFromPosProc *proc)
Checks whether a vehicle is on a specific location.
byte landscape
the landscape we're currently in
@ 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.
Class to backup a specific variable and restore it later.
void MakeLoading(bool ordered)
Makes this order a Loading order.
void MakeLeaveStation()
Makes this order a Leave Station order.
void LeaveStation()
Perform all actions when leaving a station.
static bool IsWagon(EngineID index)
Determine whether an engine type is a wagon (and not a loco).
static bool IsTransparencySet(TransparencyOption to)
Check if the transparency option bit is set and if we aren't in the game menu (there's never transpar...
Vehicle * Next() const
Get the next vehicle of this vehicle.
T * Next() const
Get next vehicle in the chain.
@ FACIL_TRUCK_STOP
Station with truck stops.
@ DIRDIFF_SAME
Both directions faces to the same direction.
byte y_extent
y-extent of vehicle bounding box
@ OLFB_FULL_LOAD
Full load all cargoes of the consist.
uint16 UnitID
Type for the company global vehicle unit number.
DestinationID GetDestination() const
Gets the destination of this order.
int width
Screen width of the viewport.
bool NeedsAutomaticServicing() const
Checks if the current order should be interrupted for a service-in-depot order.
DateFract _date_fract
Fractional part of the day.
static void SpawnAdvancedVisualEffect(const Vehicle *v)
Call CBID_VEHICLE_SPAWN_VISUAL_EFFECT and spawn requested effects.
void GetArticulatedRefitMasks(EngineID engine, bool include_initial_cargo_type, CargoTypes *union_mask, CargoTypes *intersection_mask)
Merges the refit_masks of all articulated parts.
CompanyMask company_avail
Bit for each company whether the engine is available for that company.
static Point RemapCoords(int x, int y, int z)
Map 3D world or tile coordinate to equivalent 2D coordinate as used in the viewports and smallmap.
static const uint IMPLICIT_ORDER_ONLY_CAP
Maximum number of orders in implicit-only lists before we start searching harder for duplicates.
void GetVehicleSet(VehicleSet &set, Vehicle *v, uint8 num_vehicles)
Calculates the set of vehicles that will be affected by a given selection.
UnitID curid
last ID returned; 0 if none
int height
Screen height of the viewport.
@ EC_STEAM
Steam rail engine.
@ VE_DEFAULT
Default value to indicate that visual effect should be based on engine class.
GroupID parent
Parent group.
@ VS_DEFPAL
Use default vehicle palette.
@ VSE_BREAKDOWN
Vehicle breaking down.
Tindex index
Index of this pool item.
void SetNext(Vehicle *next)
Set the next vehicle of this vehicle.
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo ID.
virtual uint Crash(bool flooded=false)
Crash the (whole) vehicle chain.
static const int MAX_VEHICLE_PIXEL_Y
Maximum height of a vehicle in pixels in #ZOOM_LVL_BASE.
static bool HasPowerOnRail(RailType enginetype, RailType tiletype)
Checks if an engine of the given RailType got power on a tile with a given RailType.
int top
Screen coordinate top edge of the viewport.
@ PFE_GL_ROADVEHS
Time spend processing road vehicles.
SpriteID sprite
The 'real' sprite.
GroupID group_id
Index of group Pool array.
static EngineID EngineReplacementForCompany(const Company *c, EngineID engine, GroupID group, bool *replace_when_old=nullptr)
Retrieve the engine replacement for the given company and original engine type.
Vehicle(VehicleType type=VEH_INVALID)
Vehicle constructor.
@ EF_NO_BREAKDOWN_SMOKE
Do not show black smoke during a breakdown.
void DeleteVehicleNews(VehicleID vid, StringID news)
Delete a news item type about a vehicle.
DifficultySettings difficulty
settings related to the difficulty
static bool HasBit(const T x, const uint8 y)
Checks if a bit in a value is set.
static void CountVehicle(const Vehicle *v, int delta)
Update num_vehicle when adding or removing a vehicle.
uint16 _returned_mail_refit_capacity
Stores the mail capacity after a refit operation (Aircraft only).
bool include(std::vector< T > &vec, const T &item)
Helper function to append an item to a vector if it is not already contained Consider using std::set,...
static T ClrBit(T &x, const uint8 y)
Clears a bit in a variable.
static RoadStopType GetRoadStopType(TileIndex t)
Get the road stop type of this tile.
void HideFillingPercent(TextEffectID *te_id)
Hide vehicle loading indicators.
@ VE_TYPE_ELECTRIC
Electric sparks.
uint16 height
Height of the sprite.
static bool TracksOverlap(TrackBits bits)
Checks if the given tracks overlap, ie form a crossing.
Vehicle * next
pointer to the next vehicle in the chain
@ ODTF_MANUAL
Manually initiated order.
const GRFFile * GetGRF() const
Retrieve the NewGRF the vehicle is tied to.
static RoadStop * GetByTile(TileIndex tile, RoadStopType type)
Find a roadstop at given tile.
@ VF_LOADING_FINISHED
Vehicle has finished loading.
Livery livery
Custom colour scheme for vehicles in this group.
int16 x_offs
Number of pixels to shift the sprite to the right.
static const uint TILE_SIZE
Tile size in world coordinates.
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.
@ EV_STEAM_SMOKE
Smoke of steam engines.
static DirDiff DirDifference(Direction d0, Direction d1)
Calculate the difference between two directions.
virtual ~Vehicle()
We want to 'destruct' the right class.
ClientSettings _settings_client
The current settings for this game.
static uint32 GetRegister(uint i)
Gets the value of a so-called newgrf "register".
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.
static bool IsValidID(size_t index)
Tests whether given index is a valid index for station of this type.
@ WC_VEHICLE_TIMETABLE
Vehicle timetable; Window numbers:
@ VE_TYPE_COUNT
Number of bits used for the effect type.
static uint TileY(TileIndex tile)
Get the Y component of a tile.
void GetConsistFreeCapacities(SmallMap< CargoID, uint > &capacities) const
Get a map of cargoes and free capacities in the consist.
@ ST_NORMAL
The most basic (normal) sprite.
bool IsRearDualheaded() const
Tell if we are dealing with the rear end of a multiheaded engine.
@ VS_TRAIN_SLOWING
Train is slowing down.
static uint32 RandomRange(uint32 limit)
Pick a random number between 0 and limit - 1, inclusive.
@ SND_3A_BREAKDOWN_TRAIN_SHIP_TOYLAND
58 == 0x3A Breakdown: train or ship (toyland)
static bool Chance16I(const uint a, const uint b, const uint32 r)
Checks if a given randomize-number is below a given probability.
@ WC_COMPANY
Company view; Window numbers:
@ WC_STATION_VIEW
Station view; Window numbers:
static void ClearVehicle(const Vehicle *v)
Clear/update the (clone) vehicle from an order backup.
static const int MAX_VEHICLE_PIXEL_X
Maximum width of a vehicle in pixels in #ZOOM_LVL_BASE.
#define MAX_DAY
The number of days till the last day.
@ VEH_ROAD
Road vehicle type.
@ CC_PASSENGERS
Passengers.
uint16 cur_speed
current speed
virtual bool IsPrimaryVehicle() const
Whether this is the primary vehicle in the chain.
bool IsGroundVehicle() const
Check if the vehicle is a ground vehicle.
void Draw(int x, int y, PaletteID default_pal, bool force_pal) const
Draw the sprite sequence.
int virtual_top
Virtual top coordinate.
Owner owner
Which company owns the vehicle?
Owner
Enum for all companies/owners.
uint16 cached_cargo_age_period
Number of ticks before carried cargo is aged.
uint16 GetVehicleCallback(CallbackID callback, uint32 param1, uint32 param2, EngineID engine, const Vehicle *v)
Evaluate a newgrf callback for vehicles.
@ DC_EXEC
execute the given command
@ VSE_VISUAL_EFFECT
Vehicle visual effect (steam, diesel smoke or electric spark) is shown.
PaletteID GetEnginePalette(EngineID engine_type, CompanyID company)
Get the colour map for an engine.
StringID GetErrorMessage() const
Returns the error message of a command.
static bool IsLocalCompany()
Is the current company the local company?
void DeleteVehicleOrders(Vehicle *v, bool keep_orderlist, bool reset_order_indices)
Delete all orders from a vehicle.
Station * GetTargetAirportIfValid(const Aircraft *v)
Returns aircraft's target station if v->target_airport is a valid station with airport.
static void SetDParam(uint n, uint64 v)
Set a string parameter v at index n in the global string parameter array.
@ VS_AIRCRAFT_BROKEN
Aircraft is broken down.
DoCommandFlag
List of flags for a command.
void VehicleServiceInDepot(Vehicle *v)
Service a vehicle and all subsequent vehicles in the consist.
@ VE_OFFSET_START
First bit that contains the offset (0 = front, 8 = centre, 15 = rear)
CommandCost EnsureNoVehicleOnGround(TileIndex tile)
Ensure there is no vehicle at the ground at the given position.
byte breakdowns_since_last_service
Counter for the amount of breakdowns.
@ AIR_SHADOW
shadow of the aircraft
@ RVSB_IN_DT_ROAD_STOP
The vehicle is in a drive-through road stop.
GRFBugs
Encountered GRF bugs.
bool Succeeded() const
Did this command succeed?
@ SND_35_BREAKDOWN_ROADVEHICLE_TOYLAND
53 == 0x35 Breakdown: road vehicle (toyland)
static uint TileX(TileIndex tile)
Get the X component of a tile.
void HandleAircraftEnterHangar(Aircraft *v)
Handle Aircraft specific tasks when an Aircraft enters a hangar.
bool vehicle_income_warn
if a vehicle isn't generating income, show a warning
uint16 num_vehicle
Number of vehicles.
Implementation of simple mapping class.
void ShowErrorMessage(StringID summary_msg, StringID detailed_msg, WarningLevel wl, int x=0, int y=0, const GRFFile *textref_stack_grffile=nullptr, uint textref_stack_size=0, const uint32 *textref_stack=nullptr)
Display an error message in a window.
static bool IsDepotTile(TileIndex tile)
Is the given tile a tile with a depot on it?
GameCreationSettings game_creation
settings used during the creation of a game (map)
Vehicle * CheckClickOnVehicle(const Viewport *vp, int x, int y)
Find the vehicle close to the clicked coordinates.
bool IsArticulatedPart() const
Check if the vehicle is an articulated part of an engine.
static Pool::IterateWrapper< Station > Iterate(size_t from=0)
Returns an iterable ensemble of all valid stations of type T.
const AirportFTAClass * GetFTA() const
Get the finite-state machine for this airport or the finite-state machine for the dummy airport in ca...
void MakeGoToDepot(DepotID destination, OrderDepotTypeFlags order, OrderNonStopFlags non_stop_type=ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS, OrderDepotActionFlags action=ODATF_SERVICE_ONLY, CargoID cargo=CT_NO_REFIT)
Makes this order a Go To Depot order.
@ PFE_GL_TRAINS
Time spent processing trains.
@ EC_ELECTRIC
Electric rail engine.
OrderType GetType() const
Get the type of order of this order.
static bool IsInsideMM(const T x, const size_t min, const size_t max)
Checks if a value is in an interval.
CargoList that is used for vehicles.
Aircraft, helicopters, rotors and their shadows belong to this class.
void InsertOrder(Vehicle *v, Order *new_o, VehicleOrderID sel_ord)
Insert a new order but skip the validation.
void UpdateCache()
Update the caches of this ship.
@ VF_STOP_LOADING
Don't load anymore during the next load cycle.
@ VE_TYPE_DIESEL
Diesel fumes.
@ ONSF_NO_STOP_AT_ANY_STATION
The vehicle will not stop at any stations it passes including the destination.
GrfSpecFeature GetGrfSpecFeature(TileIndex tile)
Get the GrfSpecFeature associated with the tile.
const GRFFile * GetGRF() const
Retrieve the NewGRF the engine is tied to.
StationCargoList cargo
The cargo packets of cargo waiting in this station.
byte visual_effect
Bitstuffed NewGRF visual effect data.
void SetWindowWidgetDirty(WindowClass cls, WindowNumber number, byte widget_index)
Mark a particular widget in a particular window as dirty (in need of repainting)
@ EC_MAGLEV
Maglev engine.
@ SND_10_BREAKDOWN_TRAIN_SHIP
14 == 0x0E Breakdown: train or ship (non-toyland)
@ VRF_LEAVING_STATION
Train is just leaving a station.
OrderSettings order
settings related to orders
static size_t GetPoolSize()
Returns first unused index.
OrderNonStopFlags GetNonStopType() const
At which stations must we stop?
void BeginLoading()
Prepare everything to begin the loading when arriving at a station.
@ FACIL_BUS_STOP
Station with bus stops.
uint32 grf_bugs
NOSAVE: bugs in this GRF in this run,.
byte visual_effect
Bitstuffed NewGRF visual effect data.
byte breakdown_ctr
Counter for managing breakdown events.
@ VS_HIDDEN
Vehicle is not visible.
uint16 EngineID
Unique identification number of an engine.
void UpdateVisualEffect(bool allow_power_change=true)
Update the cached visual effect.
Data structure for viewport, display of a part of the world.
EngineClass engclass
Class of engine for this vehicle.
CommandCost CheckOwnership(Owner owner, TileIndex tile)
Check whether the current owner owns something.
bool IsValid() const
Check whether the sequence contains any sprites.
TileIndex dest_tile
Heading for this tile.
void HandlePathfindingResult(bool path_found)
Handle the pathfinding result, especially the lost status.
Money GetDisplayProfitThisYear() const
Gets the profit vehicle had this year.
#define return_cmd_error(errcode)
Returns from a function with a specific StringID as error.
void TriggerStationRandomisation(Station *st, TileIndex tile, StationRandomTrigger trigger, CargoID cargo_type)
Trigger station randomisation.
@ VE_TYPE_START
First bit used for the type of effect.
@ TO_INVALID
Invalid transparency option.
Cached, frequently calculated values.
static const GroupID INVALID_GROUP
Sentinel for invalid groups.
bool engine_renew
is autorenew enabled
CargoID GetRefitCargo() const
Get the cargo to to refit to.
static void NewEvent(CompanyID company, ScriptEvent *event)
Queue a new event for an AI.
uint8 CalcPercentVehicleFilled(const Vehicle *front, StringID *colour)
Calculates how full a vehicle is.
Common return value for all commands.
@ ONSF_STOP_EVERYWHERE
The vehicle will stop at any station it passes and the destination.
Date _date
Current date in days (day counter)
void UpdateBoundingBoxCoordinates(bool update_cache) const
Update the bounding box co-ordinates of the vehicle.
uint Truncate(uint max_move=UINT_MAX)
Truncates the cargo in this list to the given amount.
virtual int GetCurrentMaxSpeed() const
Calculates the maximum speed of the vehicle under its current conditions.
@ WC_VEHICLE_VIEW
Vehicle view; Window numbers:
UnitID NextID()
Returns next free UnitID.
void AddToShared(Vehicle *shared_chain)
Adds this vehicle to a shared vehicle chain.
Information about GRF, used in the game and (part of it) in savegames.
static const byte LIT_ALL
Show the liveries of all companies.
@ CMD_PAUSE
pause the game
void AgeCargo()
Ages the all cargo in this list.
byte callback_mask
Bitmask of vehicle callbacks that have to be called.
int virtual_left
Virtual left coordinate.
void RemoveFromShared()
Removes the vehicle from the shared order list.
@ VF_CARGO_UNLOADING
Vehicle is unloading cargo.
UnitID max_ships
max ships in game per company
@ EV_BREAKDOWN_SMOKE_AIRCRAFT
Smoke of broken aircraft.
bool HasRating() const
Does this cargo have a rating at this station?
TileIndex tile
Current tile index.
#define DEBUG(name, level,...)
Output a line of debugging information.
void CancelReservation(StationID next, Station *st)
Return all reserved cargo packets to the station and reset all packets staged for transfer.
@ EIT_ON_MAP
Vehicle drawn in viewport.
void MarkTilesDirty(bool cargo_change) const
Marks the tiles of the station as dirty.
int left
Screen coordinate left edge of the viewport.
EngineID engine_type
The type of engine used for this vehicle.
bool HasAnyRailtypesAvail(const CompanyID company)
Test if any buildable railtype is available for a company.
static void DoDrawVehicle(const Vehicle *v)
Add vehicle sprite for drawing to the screen.
uint8 cached_veh_length
Length of this vehicle in units of 1/VEHICLE_LENGTH of normal length. It is cached because this can b...
@ VS_CRASHED
Vehicle is crashed.
Sprite sequence for a vehicle part.
static T SB(T &x, const uint8 s, const uint8 n, const U d)
Set n bits in x starting at bit s to d.
byte visual_effect
Bitstuffed NewGRF visual effect data.
StationID last_station_visited
The last station we stopped at.
Money money
Money owned by the company.
UnitID GetFreeUnitNumber(VehicleType type)
Get an unused unit number for a vehicle (if allowed).
@ PFE_GL_SHIPS
Time spent processing ships.
@ EF_USES_2CC
Vehicle uses two company colours.
VehicleCargoList cargo
The cargo this vehicle is carrying.
@ CBID_VEHICLE_SPAWN_VISUAL_EFFECT
Called to spawn visual effects for vehicles.
bool Failed() const
Did this command fail?
Vehicle ** hash_tile_current
NOSAVE: Cache of the current hash chain.
@ CCF_ARRANGE
Valid changes for arranging the consist in a depot.
Order current_order
The current order (+ status, like: loading)
static bool IsInvisibilitySet(TransparencyOption to)
Check if the invisibility option bit is set and if we aren't in the game menu (there's never transpar...
Airport airport
Tile area the airport covers.
bool HasAnyRoadTypesAvail(CompanyID company, RoadTramType rtt)
Test if any buildable RoadType is available for a company.
GroundVehicleCache gcache
Cache of often calculated values.
@ EC_DIESEL
Diesel rail engine.
struct AirportFTA * layout
state machine for airport
@ VEH_EFFECT
Effect vehicle type (smoke, explosions, sparks, bubbles)
void EndSpriteCombine()
Terminates a block of sprites started by StartSpriteCombine.
uint32 Pack() const
Pack a VehicleListIdentifier in a single uint32.
int16 engine_renew_months
months before/after the maximum vehicle age a vehicle should be renewed
Flags flags
Flags for this airport type.
static const byte LIT_COMPANY
Show the liveries of your own company.
bool IsFrontEngine() const
Check if the vehicle is a front engine.
void DeleteOrder(Vehicle *v, VehicleOrderID sel_ord)
Delete an order but skip the parameter validation.
Order * GetLastOrder() const
Returns the last order of a vehicle, or nullptr if it doesn't exists.
@ ODATFB_NEAREST_DEPOT
Send the vehicle to the nearest depot.
Generates sequence of free UnitID numbers.
GameSettings _settings_game
Game settings of a running game or the scenario editor.
static Vehicle * VehicleFromPos(TileIndex tile, void *data, VehicleFromPosProc *proc, bool find_first)
Helper function for FindVehicleOnPos/HasVehicleOnPos.
byte in_use
Bit 0 set if this livery should override the default livery first colour, Bit 1 for the second colour...
@ WC_VEHICLE_DETAILS
Vehicle details; Window numbers:
Internal structure used in openttd - Finite sTate mAchine --> FTA.
uint32 engine_renew_money
minimum amount of money before autorenew is used
@ VS_STOPPED
Vehicle is stopped by the player.
int8 trip_occupancy
NOSAVE: Occupancy of vehicle of the current trip (updated after leaving a station).
uint32 GetGRFID() const
Retrieve the GRF ID of the NewGRF the vehicle is tied to.
bool IsArticulatedVehicleCarryingDifferentCargoes(const Vehicle *v, CargoID *cargo_type)
Tests if all parts of an articulated vehicle are refitted to the same cargo.
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.
VisualEffectSpawnModel
Models for spawning visual effects.
static void UpdateAutoreplace(CompanyID company)
Update autoreplace_defined and autoreplace_finished of all statistics of a company.
static Vehicle * VehicleFromPosXY(int x, int y, void *data, VehicleFromPosProc *proc, bool find_first)
Helper function for FindVehicleOnPos/HasVehicleOnPos.
TileIndex new_tile
Tile of the vehicle after moving.
@ EF_RAIL_IS_MU
Rail vehicle is a multiple-unit (DMU/EMU)
uint16 width
Width of the sprite.
void ResetRefitCaps()
Reset all refit_cap in the consist to cargo_cap.
uint16 reliability_spd_dec
Reliability decrease speed.
void UpdateViewport(bool dirty)
Update the vehicle on the viewport, updating the right hash and setting the new coordinates.
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.
uint64 flags
stores which blocks on the airport are taken. was 16 bit earlier on, then 32
Money GetCost() const
The costs as made up to this moment.
static const GroupID DEFAULT_GROUP
Ungrouped vehicles are in this group.
void SetTransferLoadPlace(TileIndex xy)
Sets loaded_at_xy to the current station for all cargo to be transferred.
Vehicle * previous_shared
NOSAVE: pointer to the previous vehicle in the shared order chain.
void DeleteDepotHighlightOfVehicle(const Vehicle *v)
Removes the highlight of a vehicle in a depot window.
@ WC_SHIPS_LIST
Ships list; Window numbers:
DepotCommand
Flags to add to p1 for goto depot commands.
Money profit_this_year
Profit this year << 8, low 8 bits are fract.
@ ODTFB_PART_OF_ORDERS
This depot order is because of a regular order.
bool _networking
are we in networking mode?
void StartSpriteCombine()
Starts a block of sprites, which are "combined" into a single bounding box.
@ VRF_REVERSE_DIRECTION
Reverse the visible direction of the vehicle.
@ INVALID_DIAGDIR
Flag for an invalid DiagDirection.
void DrawSprite(SpriteID img, PaletteID pal, int x, int y, const SubSprite *sub, ZoomLevel zoom)
Draw a sprite, not in a viewport.
bool MarkAllViewportsDirty() const
Marks viewports dirty where the vehicle's image is.
virtual void PlayLeaveStationSound() const
Play the sound associated with leaving the station.
void KeepAll()
Marks all cargo in the vehicle as to be kept.
static void VehicleReachedProfitAge(const Vehicle *v)
Add a vehicle to the profit sum of its group.
@ SRT_TRAIN_DEPARTS
Trigger platform when train leaves.
byte cached_vis_effect
Visual effect to show (see VisualEffect)
virtual bool FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
Find the closest depot for this vehicle and tell us the location, DestinationID and whether we should...
Coordinates of a point in 2D.
DirDiff
Enumeration for the difference between two directions.
@ WC_TRAINS_LIST
Trains list; Window numbers:
void HandleLoading(bool mode=false)
Handle the loading of the vehicle; when not it skips through dummy orders and does nothing in all oth...
@ PFE_GL_AIRCRAFT
Time spent processing aircraft.
@ FACIL_DOCK
Station with a dock.
EffectVehicle * CreateEffectVehicleRel(const Vehicle *v, int x, int y, int z, EffectVehicleType type)
Create an effect vehicle above a particular vehicle.
bool HasDepotOrder() const
Checks if a vehicle has a depot in its order list.
static const int DAYS_IN_LEAP_YEAR
sometimes, you need one day more...
static bool IsRailStationTile(TileIndex t)
Is this tile a station tile and a rail station?
bool show_track_reservation
highlight reserved tracks.
void ShowNewGrfVehicleError(EngineID engine, StringID part1, StringID part2, GRFBugs bug_type, bool critical)
Displays a "NewGrf Bug" error message for a engine, and pauses the game if not networking.
void ShowCostOrIncomeAnimation(int x, int y, int z, Money cost)
Display animated income or costs on the map.
uint16 vehicle_flags
Used for gradual loading and other miscellaneous things (.
CommandCost SendToDepot(DoCommandFlag flags, DepotCommand command)
Send this vehicle to the depot using the given command(s).
MutableSpriteCache sprite_cache
Cache of sprites and values related to recalculating them, see MutableSpriteCache.
VehicleType
Available vehicle types.
void Leave(RoadVehicle *rv)
Leave the road stop.
@ VE_TYPE_DEFAULT
Use default from engine class.
byte misc_flags
Miscellaneous flags.
int8 y_offs
y offset for vehicle sprite
SpriteID colourmap
NOSAVE: cached colour mapping.
static Vehicle * GetVehicleTunnelBridgeProc(Vehicle *v, void *data)
Procedure called for every vehicle found in tunnel/bridge in the hash map.
bool CanBuildVehicleInfrastructure(VehicleType type, byte subtype)
Check whether we can build infrastructure for the given vehicle type.
static bool IsTileType(TileIndex tile, TileType type)
Checks if a tile is a given tiletype.
@ VESM_DIESEL
Diesel model.
@ RAILVEH_WAGON
simple wagon, not motorized
static void SetDepotReservation(TileIndex t, bool b)
Set the reservation state of the depot.
@ ODATFB_HALT
Service the vehicle and then halt it.
@ WC_VEHICLE_REFIT
Vehicle refit; Window numbers:
uint _returned_refit_capacity
Stores the capacity after a refit operation.
void IncrementRealOrderIndex()
Advanced cur_real_order_index to the next real order, keeps care of the wrap-around and invalidates t...
void AddSortableSpriteToDraw(SpriteID image, PaletteID pal, int x, int y, int w, int h, int dz, int z, bool transparent, int bb_offset_x, int bb_offset_y, int bb_offset_z, const SubSprite *sub)
Draw a (transparent) sprite at given coordinates with a given bounding box.
byte vehicle_breakdowns
likelihood of vehicles breaking down
Direction direction
facing
bool * cache
array of occupied unit id numbers
@ TRACK_BIT_DEPOT
Bitflag for a depot.
bool MarkAllViewportsDirty(int left, int top, int right, int bottom)
Mark all viewports that display an area as dirty (in need of repaint).
OrderList * list
Pointer to the order list for this vehicle.
void VehicleEnteredDepotThisTick(Vehicle *v)
Adds a vehicle to the list of vehicles that visited a depot this tick.
VehicleOrderID cur_real_order_index
The index to the current real (non-implicit) order.
@ CBID_VEHICLE_COLOUR_MAPPING
Called to determine if a specific colour map should be used for a vehicle instead of the default live...
static WindowClass GetWindowClassForVehicleType(VehicleType vt)
Get WindowClass for vehicle list of given vehicle type.
static void RunVehicleDayProc()
Increases the day counter for all vehicles and calls 1-day and 32-day handlers.
Vehicle * next_shared
pointer to the next vehicle that shares the order
static Direction ReverseDir(Direction d)
Return the reverse of a direction.
Vehicle * FirstShared() const
Get the first vehicle of this vehicle chain.
byte x_extent
x-extent of vehicle bounding box
uint16 wait_counter
Ticks waiting in front of a signal, ticks being stuck or a counter for forced proceeding through sign...
static const uint CALLBACK_FAILED
Different values for Callback result evaluations.
uint32 StringID
Numeric value that represents a string, independent of the selected language.
VehicleCache vcache
Cache of often used vehicle values.
All ships have this type.
static const PaletteID PALETTE_RECOLOUR_START
First recolour sprite for company colours.
TransparencyOption
Transparency option bits: which position in _transparency_opt stands for which transparency.
void LoadUnloadStation(Station *st)
Load/unload the vehicles in this station according to the order they entered.
uint32 motion_counter
counter to occasionally play a vehicle sound.
CompanyID _current_company
Company currently doing an action.
@ DEPOT_SERVICE
The vehicle will leave the depot right after arrival (service only)
@ VESM_NONE
No visual effect.
bool revalidate_before_draw
We need to do a GetImage() and check bounds before drawing this sprite.
static const uint VEHICLE_LENGTH
The length of a vehicle in tile units.
void DeleteGroupHighlightOfVehicle(const Vehicle *v)
Removes the highlight of a vehicle in a group window.
static const PaletteID PALETTE_CRASH
Recolour sprite greying of crashed vehicles.
static Pool::IterateWrapper< Titem > Iterate(size_t from=0)
Returns an iterable ensemble of all valid Titem.
Vehicle * hash_viewport_next
NOSAVE: Next vehicle in the visual location hash.
Base class for all pools.
Vehicle * First() const
Get the first vehicle of this vehicle chain.
void DeleteWindowById(WindowClass cls, WindowNumber number, bool force)
Delete a window by its class and window number (if it is open).
bool no_servicing_if_no_breakdowns
don't send vehicles to depot when breakdowns are disabled
static int ScaleByZoom(int value, ZoomLevel zoom)
Scale by zoom level, usually shift left (when zoom > ZOOM_LVL_NORMAL) When shifting right,...
uint16 cargo_age_counter
Ticks till cargo is aged next.
byte tick_counter
Increased by one for each tick.
CommandCost EnsureNoTrainOnTrackBits(TileIndex tile, TrackBits track_bits)
Tests if a vehicle interacts with the specified track bits.
uint16 cargo_cap
total capacity
uint32 cached_power
Total power of the consist (valid only for the first engine).
@ PFE_GL_ECONOMY
Time spent processing cargo movement.
UnitID max_trains
max trains in game per company
void IncrementImplicitOrderIndex()
Increments cur_implicit_order_index, keeps care of the wrap-around and invalidates the GUI.
int8 x_offs
x offset for vehicle sprite
@ CBM_VEHICLE_VISUAL_EFFECT
Visual effects and wagon power (trains, road vehicles and ships)
void Restore()
Restore the variable.
static void UpdateProfits()
Recompute the profits for all groups.
@ FACIL_TRAIN
Station with train station.
static Train * From(Vehicle *v)
Converts a Vehicle to SpecializedVehicle with type checking.
void AddVehicle(Vehicle *v)
Adds the given vehicle to this shared order list.
@ DIRDIFF_45RIGHT
Angle of 45 degrees right.
PaletteID GetVehiclePalette(const Vehicle *v)
Get the colour map for a vehicle.
void ConsistChanged(ConsistChangeFlags allowed_changes)
Recalculates the cached stuff of a train.
byte z_extent
z-extent of vehicle bounding box
byte VehicleRandomBits()
Get a value for a vehicle's random_bits.
@ OUFB_NO_UNLOAD
Totally no unloading will be done.
uint32 PaletteID
The number of the palette.
UnitID maxid
maximum ID at the moment of constructor call
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...
EffectVehicleType
Effect vehicle types.
bool IsNormalAircraft() const
Check if the aircraft type is a normal flying device; eg not a rotor or a shadow.
Shared order list linking together the linked list of orders and the list of vehicles sharing this or...
bool IsEngine() const
Check if a vehicle is an engine (can be first in a consist).
@ CMD_AUTOREPLACE_VEHICLE
replace/renew a vehicle while it is in a depot
@ SAT_TRAIN_DEPARTS
Trigger platform when train leaves.
CargoPayment * cargo_payment
The cargo payment we're currently in.
static bool CleaningPool()
Returns current state of pool cleaning - yes or no.
LiveryScheme GetEngineLiveryScheme(EngineID engine_type, EngineID parent_engine_type, const Vehicle *v)
Determines the LiveryScheme for a vehicle.
uint32 current_order_time
How many ticks have passed since this order started.
void MarkTileDirtyByTile(TileIndex tile, int bridge_level_offset, int tile_height_override)
Mark a tile given by its index dirty for repaint.
Vehicle * NextShared() const
Get the next vehicle of the shared vehicle chain.
void ReleaseDisastersTargetingVehicle(VehicleID vehicle)
Notify disasters that we are about to delete a vehicle.
@ PM_PAUSED_NORMAL
A game normally paused.
@ MTA_LOAD
Load the cargo from the station.
TrackBits state
The "track" the ship is following.
Position information of a vehicle after it moved.
@ WC_VEHICLE_DEPOT
Depot view; Window numbers:
union Vehicle::@51 orders
The orders currently assigned to the vehicle.
@ VE_DISABLE_WAGON_POWER
Flag to disable wagon power.
@ MP_STATION
A tile of a station.
static StationID GetStationIndex(TileIndex t)
Get StationID from a tile.
byte previous_pos
Previous desired position of the aircraft.
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.
Money profit_last_year
Profit last year << 8, low 8 bits are fract.
byte breakdown_chance
Current chance of breakdowns.
@ EV_DIESEL_SMOKE
Smoke of diesel engines.
int16 y_offs
Number of pixels to shift the sprite downwards.
void SetDepotOrderType(OrderDepotTypeFlags depot_order_type)
Set the cause to go to the depot.
@ DIRDIFF_90RIGHT
Angle of 90 degrees right.
TileIndex xy
Base tile of the station.
UnitID unitnumber
unit number, for display purposes only
static int GetTileMaxPixelZ(TileIndex tile)
Get top height of the tile.
A special vehicle is one of the following:
static const VehicleOrderID MAX_VEH_ORDER_ID
Last valid VehicleOrderID.
void SetDepotActionType(OrderDepotActionFlags depot_service_type)
Set what we are going to do in the depot.
UnitID max_roadveh
max trucks in game per company
TileIndex old_tile
Current tile of the vehicle.
@ VE_ADVANCED_EFFECT
Flag for advanced effects.
int8 x_bb_offs
x offset of vehicle bounding box
@ EXPENSES_NEW_VEHICLES
New vehicles.
Vehicle ** hash_viewport_prev
NOSAVE: Previous vehicle in the visual location hash.
#define INSTANTIATE_POOL_METHODS(name)
Force instantiation of pool methods so we don't get linker errors.
@ VEH_DISASTER
Disaster vehicle type.
static T abs(const T a)
Returns the absolute value of (scalar) variable.
byte breakdown_delay
Counter for managing breakdown length.
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...
uint32 VehicleID
The type all our vehicle IDs have.
uint64 block
64 bit blocks (st->airport.flags), should be enough for the most complex airports
void InvalidateAutoreplaceWindow(EngineID e, GroupID id_g)
Rebuild the left autoreplace list if an engine is removed or added.
Rect coord
NOSAVE: Graphical bounding box of the vehicle, i.e. what to redraw on moves.
bool NeedsServicing() const
Check if the vehicle needs to go to a depot in near future (if a opportunity presents itself) for ser...
OrderDepotTypeFlags GetDepotOrderType() const
What caused us going to the depot?
byte pos
Next desired position of the aircraft.
static void AddVehicleAdviceNewsItem(StringID string, VehicleID vehicle)
Adds a vehicle-advice news item.
@ AIR_CTOL
Conventional Take Off and Landing, i.e. planes.
TrackBits
Bitfield corresponding to Track.
byte subtype
subtype (Filled with values from AircraftSubType/DisasterSubType/EffectVehicleType/GroundVehicleSubty...
std::vector< Pair >::const_iterator Find(const T &key) const
Finds given key in this map.
byte day_counter
Increased by one for each day.
@ VS_UNCLICKABLE
Vehicle is not clickable by the user (shadow vehicles).
void FindVehicleOnPosXY(int x, int y, void *data, VehicleFromPosProc *proc)
Find a vehicle from a specific location.
static T ToggleBit(T &x, const uint8 y)
Toggles a bit in a variable.
static T SetBit(T &x, const uint8 y)
Set a bit in a variable.
bool HasVehicleOnPosXY(int x, int y, void *data, VehicleFromPosProc *proc)
Checks whether a vehicle in on a specific location.
static void Run(Vehicle *v, bool allow_merge=true, bool is_full_loading=false)
Refresh all links the given vehicle will visit.
ZoomLevel zoom
The zoom level of the viewport.
bool NeedsAutorenewing(const Company *c, bool use_renew_setting=true) const
Function to tell if a vehicle needs to be autorenewed.
@ VF_PATHFINDER_LOST
Vehicle's pathfinder is lost.
void AgeVehicle(Vehicle *v)
Update age of a vehicle.
static Station * GetIfValid(size_t index)
Returns station if the index is a valid index for this station type.
byte CargoID
Cargo slots to indicate a cargo type within a game.
VehiclePool _vehicle_pool("Vehicle")
The pool with all our precious vehicles.
bool IsStoppedInDepot() const
Check whether the vehicle is in the depot and stopped.
uint ActionCount(MoveToAction action) const
Returns the amount of cargo designated for a given purpose.
@ CBID_VEHICLE_32DAY_CALLBACK
Called for every vehicle every 32 days (not all on same date though).
Vehicle * previous
NOSAVE: pointer to the previous vehicle in the chain.
RailType GetTileRailType(TileIndex tile)
Return the rail type of tile, or INVALID_RAILTYPE if this is no rail tile.
LiveryScheme
List of different livery schemes.
CargoID cargo_type
type of cargo this vehicle is carrying
@ ODATF_SERVICE_ONLY
Only service the vehicle.
GRFFilePropsBase< NUM_CARGO+2 > grf_prop
Properties related the the grf file.
static Vehicle * EnsureNoVehicleProcZ(Vehicle *v, void *data)
Callback that returns 'real' vehicles lower or at height *(int*)data .
@ VSE_RUNNING
Vehicle running normally.
Train * GetNextUnit() const
Get the next real (non-articulated part and non rear part of dualheaded engine) vehicle in the consis...
FreeUnitIDGenerator(VehicleType type, CompanyID owner)
Initializes the structure.
virtual void OnNewDay()
Calls the new day handler of the vehicle.
@ EF_ROAD_TRAM
Road vehicle is a tram/light rail vehicle.
static uint CeilDiv(uint a, uint b)
Computes ceil(a / b) for non-negative a and b.
uint16 local_id
id defined by the grf file for this entity
PaletteID pal
The palette (use PAL_NONE) if not needed)
byte state
State of the airport.
VehicleSettings vehicle
options for vehicles
void ErrorUnknownCallbackResult(uint32 grfid, uint16 cbid, uint16 cb_res)
Record that a NewGRF returned an unknown/invalid callback result.
@ TFP_NONE
Normal operation.
uint8 smoke_amount
amount of smoke/sparks locomotives produce
static TileType GetTileType(TileIndex tile)
Get the tiletype of a given tile.
@ CBM_VEHICLE_COLOUR_REMAP
Change colour mapping of vehicle.
@ VEH_TRAIN
Train vehicle type.
static bool IsValidID(size_t index)
Tests whether given index can be used to get valid (non-nullptr) Titem.
Order * GetOrder(int index) const
Returns order 'index' of a vehicle or nullptr when it doesn't exists.
VehicleType type
Type of vehicle.
void SubtractMoneyFromCompany(const CommandCost &cost)
Subtract money from the _current_company, if the company is valid.
@ HELICOPTERS
Can helicopters land on this airport type?
virtual bool Tick()
Calls the tick handler of the vehicle.
void UpdatePositionAndViewport()
Update the position of the vehicle, and update the viewport.
const struct GRFFile * grffile
grf file that introduced this entity
@ FACIL_AIRPORT
Station with an airport.
uint16 reliability
Reliability.
@ VIWD_MODIFY_ORDERS
Other order modifications.
void UpdatePosition()
Update the position of the vehicle.
Vehicle ** hash_tile_prev
NOSAVE: Previous vehicle in the tile location hash.
bool CanVehicleUseStation(EngineID engine_type, const Station *st)
Can this station be used by the given engine type?
bool HandleBreakdown()
Handle all of the aspects of a vehicle breakdown This includes adding smoke and sounds,...
void DecreaseVehicleValue(Vehicle *v)
Decrease the value of a vehicle.
int8 y_bb_offs
y offset of vehicle bounding box
int y
x and y position of the vehicle after moving
@ CT_INVALID
Invalid cargo type.
static bool IsCargoInClass(CargoID c, CargoClass cc)
Does cargo c have cargo class cc?
byte liveries
options for displaying company liveries, 0=none, 1=self, 2=all
bool CanLeaveWithCargo(bool has_cargo) const
A vehicle can leave the current station with cargo if:
uint Return(uint max_move, StationCargoList *dest, StationID next_station)
Returns reserved cargo to the station and removes it from the cache.
@ VEH_SHIP
Ship vehicle type.
@ VESM_ELECTRIC
Electric model.
Specification of a rectangle with absolute coordinates of all edges.
@ PM_PAUSED_ERROR
A game paused because a (critical) error.
@ VSE_STOPPED_16
Every 16 ticks while the vehicle is stopped (speed == 0).
@ AIRPLANES
Can planes land on this airport type?
VehicleOrderID GetNumOrders() const
Get the number of orders this vehicle has.
void InvalidateVehicleOrder(const Vehicle *v, int data)
Updates the widgets of a vehicle which contains the order-data.
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting)
void GetBounds(Rect *bounds) const
Determine shared bounds of all sprites.
OrderDepotActionFlags GetDepotActionType() const
What are we going to do when in the depot.
@ WC_AIRCRAFT_LIST
Aircraft list; Window numbers:
Vehicle * hash_tile_next
NOSAVE: Next vehicle in the tile location hash.
Data structure describing a sprite.
SmallMap< Vehicle *, bool > AutoreplaceMap
List of vehicles that should check for autoreplace this tick.
#define CLRBITS(x, y)
Clears several bits in a variable.
static bool EngineHasReplacementForCompany(const Company *c, EngineID engine, GroupID group)
Check if a company has a replacement set up for the given engine.
#define lastof(x)
Get the last element of an fixed size array.
void DeleteUnreachedImplicitOrders()
Delete all implicit orders which were not reached.
Vehicle * first
NOSAVE: pointer to the first vehicle in the chain.
@ GBUG_VEH_LENGTH
Length of rail vehicle changes when not inside a depot.
Order * next
Pointer to next order. If nullptr, end of list.
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
CompanySettings settings
settings specific for each company
@ VS_SHADOW
Vehicle is a shadow vehicle.
Information about a particular livery.
uint32 cached_weight
Total weight of the consist (valid only for the first engine).
TransparencyOption GetTransparencyOption() const
Determines the transparency option affecting the effect.
static const int32 INVALID_COORD
Sentinel for an invalid coordinate.
Rect old_coord
Co-ordinates from the last valid bounding box.
static const int DAY_TICKS
1 day is 74 ticks; _date_fract used to be uint16 and incremented by 885.
void ViewportAddVehicles(DrawPixelInfo *dpi)
Add the vehicle sprites that should be drawn at a part of the screen.
@ VE_OFFSET_CENTRE
Value of offset corresponding to a position above the centre of the vehicle.
void SetNonStopType(OrderNonStopFlags non_stop_type)
Set whether we must stop at stations or not.
VehicleEnterTileStatus
The returned bits of VehicleEnterTile.
GRFConfig * GetGRFConfig(uint32 grfid, uint32 mask)
Retrieve a NewGRF from the current config by its grfid.
void MakeImplicit(StationID destination)
Makes this order an implicit order.
T * GetFirstEnginePart()
Get the first part of an articulated engine.
@ FLYING
Vehicle is flying in the air.
@ VE_TYPE_STEAM
Steam plumes.
void SetDParamStr(uint n, const char *str)
This function is used to "bind" a C string to a OpenTTD dparam slot.
CommandCost TunnelBridgeIsFree(TileIndex tile, TileIndex endtile, const Vehicle *ignore)
Finds vehicle in tunnel / bridge.
@ EV_BREAKDOWN_SMOKE
Smoke of broken vehicles except aircraft.
static const StringID INVALID_STRING_ID
Constant representing an invalid string (16bit in case it is used in savegames)
virtual void MarkDirty()
Marks the vehicles to be redrawn and updates cached variables.
@ WC_VEHICLE_ORDERS
Vehicle orders; Window numbers:
Dynamic data of a loaded NewGRF.
GUISettings gui
settings related to the GUI
uint16 reliability
Current reliability of the engine.
@ WL_CRITICAL
Critical errors, the MessageBox is shown in all cases.
VehicleType type
Vehicle type, ie VEH_ROAD, VEH_TRAIN, etc.
@ SND_0F_BREAKDOWN_ROADVEHICLE
13 == 0x0D Breakdown: road vehicle (non-toyland)
uint16 refit_cap
Capacity left over from before last refit.
bool IsMultiheaded() const
Check if the vehicle is a multiheaded engine.
@ OLFB_NO_LOAD
Do not load anything.
Date date_of_last_service
Last date the vehicle had a service at a depot.
GetNewVehiclePosResult GetNewVehiclePos(const Vehicle *v)
Get position information of a vehicle when moving one pixel in the direction it is facing.
const char * GetName() const
Get the name of this grf.
Data about how and where to blit pixels.
static const int VEHICLE_PROFIT_MIN_AGE
Only vehicles older than this have a meaningful profit.
OrderLoadFlags GetLoadType() const
How must the consist be loaded?
VehicleEnterTileStatus VehicleEnterTile(Vehicle *v, TileIndex tile, int x, int y)
Call the tile callback function for a vehicle entering a tile.
static TileIndex TileVirtXY(uint x, uint y)
Get a tile from the virtual XY-coordinate.
@ EC_MONORAIL
Mono rail engine.
static bool IsBridgeAbove(TileIndex t)
checks if a bridge is set above the ground of this tile
@ VSE_RUNNING_16
Every 16 ticks while the vehicle is running (speed > 0).
byte colour2
Second colour, for vehicles with 2CC support.
bool GamelogGRFBugReverse(uint32 grfid, uint16 internal_id)
Logs GRF bug - rail vehicle has different length after reversing.
byte colour1
First colour, for all vehicles.
VehicleEnterTileProc * vehicle_enter_tile_proc
Called when a vehicle enters a tile.
@ DEPOT_DONT_CANCEL
Don't cancel current goto depot command if any.
virtual void GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const
Gets the sprite to show for the given direction.