64#include "table/strings.h"
69static const uint GEN_HASHX_BITS = 6;
70static const uint GEN_HASHY_BITS = 6;
73static const uint GEN_HASHX_BUCKET_BITS = 7;
74static const uint GEN_HASHY_BUCKET_BITS = 6;
77static inline uint GetViewportHashX(
int x)
79 return GB(x, GEN_HASHX_BUCKET_BITS + ZOOM_BASE_SHIFT, GEN_HASHX_BITS);
82static inline uint GetViewportHashY(
int y)
84 return GB(y, GEN_HASHY_BUCKET_BITS + ZOOM_BASE_SHIFT, GEN_HASHY_BITS) << GEN_HASHX_BITS;
87static inline uint GetViewportHash(
int x,
int y)
89 return GetViewportHashX(x) + GetViewportHashY(y);
93static const uint GEN_HASHX_SIZE = 1 << (GEN_HASHX_BUCKET_BITS + GEN_HASHX_BITS + ZOOM_BASE_SHIFT);
94static const uint GEN_HASHY_SIZE = 1 << (GEN_HASHY_BUCKET_BITS + GEN_HASHY_BITS + ZOOM_BASE_SHIFT);
97static const uint GEN_HASHX_INC = 1;
98static const uint GEN_HASHY_INC = 1 << GEN_HASHX_BITS;
101static const uint GEN_HASHX_MASK = (1 << GEN_HASHX_BITS) - 1;
102static const uint GEN_HASHY_MASK = ((1 << GEN_HASHY_BITS) - 1) << GEN_HASHX_BITS;
116 bounds->left = bounds->top = bounds->right = bounds->bottom = 0;
117 for (uint i = 0; i < this->count; ++i) {
120 bounds->left = spr->
x_offs;
121 bounds->top = spr->
y_offs;
125 if (spr->
x_offs < bounds->left) bounds->left = spr->
x_offs;
126 if (spr->
y_offs < bounds->top) bounds->top = spr->
y_offs;
129 if (right > bounds->right) bounds->right = right;
130 if (bottom > bounds->bottom) bounds->bottom = bottom;
144 for (uint i = 0; i < this->count; ++i) {
145 PaletteID pal = force_pal || !this->seq[i].pal ? default_pal : this->seq[i].pal;
180 assert(v !=
nullptr);
205 if (this->
vehstatus.
Any({VehState::Stopped, VehState::Crashed}))
return false;
211 if (this->ServiceIntervalIsPercent()) {
232 bool pending_replace =
false;
237 bool replace_when_old =
false;
241 if (new_engine == EngineID::Invalid() || !
Engine::Get(new_engine)->company_avail.Test(v->owner))
continue;
243 if (replace_when_old && !v->NeedsAutorenewing(c,
false))
continue;
246 CargoTypes available_cargo_types, union_mask;
249 if (union_mask != 0) {
254 if ((cargo_mask & new_engine_default_cargoes) != cargo_mask) {
270 pending_replace =
true;
271 needed_money += 2 *
Engine::Get(new_engine)->GetCost();
275 return pending_replace;
294 assert(this->
Previous() ==
nullptr);
300 for (
Vehicle *v =
this; v !=
nullptr; v = v->
Next()) {
304 v->MarkAllViewportsDirty();
334 if (grfconfig ==
nullptr)
return;
385constexpr uint TILE_HASH_BITS = 7;
386constexpr uint TILE_HASH_SIZE = 1 << TILE_HASH_BITS;
387constexpr uint TILE_HASH_MASK = TILE_HASH_SIZE - 1;
388constexpr uint TOTAL_TILE_HASH_SIZE = 1 << (TILE_HASH_BITS * 2);
392constexpr uint TILE_HASH_RES = 0;
399 return GB(p, TILE_HASH_RES, TILE_HASH_BITS);
407 return (h + 1) & TILE_HASH_MASK;
415 return hx | hy << TILE_HASH_BITS;
426static std::array<Vehicle *, TOTAL_TILE_HASH_SIZE> _vehicle_tile_hash{};
435 pos_rect.left = std::max<int>(0, x - max_dist);
436 pos_rect.right = std::max<int>(0, x + max_dist);
437 pos_rect.top = std::max<int>(0, y - max_dist);
438 pos_rect.bottom = std::max<int>(0, y + max_dist);
440 if (2 * max_dist < TILE_HASH_MASK *
TILE_SIZE) {
448 this->hxmin = this->hx = 0;
449 this->hxmax = TILE_HASH_MASK;
450 this->hymin = this->hy = 0;
451 this->hymax = TILE_HASH_MASK;
454 this->current_veh = _vehicle_tile_hash[
ComposeTileHash(this->hx, this->hy)];
464 assert(this->current_veh !=
nullptr);
465 this->current_veh = this->current_veh->hash_tile_next;
466 this->SkipEmptyBuckets();
474 while (this->current_veh ==
nullptr) {
475 if (this->hx != this->hxmax) {
477 }
else if (this->hy != this->hymax) {
478 this->hx = this->hxmin;
483 this->current_veh = _vehicle_tile_hash[
ComposeTileHash(this->hx, this->hy)];
492 while (this->current_veh !=
nullptr && !this->pos_rect.Contains({this->current_veh->x_pos, this->current_veh->y_pos})) this->Increment();
511 this->current = this->current->hash_tile_next;
519 while (this->current !=
nullptr && this->current->tile != this->tile) this->Increment();
537 if (v->z_pos > z)
continue;
539 return CommandCost(STR_ERROR_TRAIN_IN_THE_WAY + v->type);
560 if (v == ignore)
continue;
561 return CommandCost(STR_ERROR_TRAIN_IN_THE_WAY + v->type);
585 if ((t->track != track_bits) && !
TracksOverlap(t->track | track_bits))
continue;
587 return CommandCost(STR_ERROR_TRAIN_IN_THE_WAY + v->type);
592static void UpdateVehicleTileHash(
Vehicle *v,
bool remove)
603 if (old_hash == new_hash)
return;
606 if (old_hash !=
nullptr) {
612 if (new_hash !=
nullptr) {
623static std::array<
Vehicle *, 1 << (GEN_HASHX_BITS + GEN_HASHY_BITS)> _vehicle_viewport_hash{};
625static void UpdateVehicleViewportHash(
Vehicle *v,
int x,
int y,
int old_x,
int old_y)
627 Vehicle **old_hash, **new_hash;
629 new_hash = (x ==
INVALID_COORD) ?
nullptr : &_vehicle_viewport_hash[GetViewportHash(x, y)];
630 old_hash = (old_x ==
INVALID_COORD) ?
nullptr : &_vehicle_viewport_hash[GetViewportHash(old_x, old_y)];
632 if (old_hash == new_hash)
return;
635 if (old_hash !=
nullptr) {
641 if (new_hash !=
nullptr) {
649void ResetVehicleHash()
652 _vehicle_viewport_hash.fill(
nullptr);
653 _vehicle_tile_hash.fill(
nullptr);
656void ResetVehicleColourMap()
668void InitializeVehicles()
670 _vehicles_to_autoreplace.clear();
674uint CountVehiclesInChain(
const Vehicle *v)
677 do count++;
while ((v = v->
Next()) !=
nullptr);
687 switch (this->type) {
690 return !this->IsArticulatedPart() &&
694 default:
return false;
704 switch (this->type) {
709 default:
return false;
730 return this->GetEngine()->GetGRF();
740 return this->GetEngine()->GetGRFID();
786 this->ResetDepotUnbunching();
789 AI::NewEvent(this->owner,
new ScriptEventVehicleLost(this->index));
798 if (CleaningPool())
return;
802 st->loading_vehicles.remove(
this);
805 this->CancelReservation(StationID::Invalid(), st);
806 delete this->cargo_payment;
807 assert(this->cargo_payment ==
nullptr);
810 if (this->IsEngineCountable()) {
819 Company::Get(this->owner)->freeunits[this->type].ReleaseID(this->unitnumber);
821 if (this->type ==
VEH_AIRCRAFT && this->IsPrimaryVehicle()) {
831 if (this->type ==
VEH_ROAD && this->IsPrimaryVehicle()) {
841 if (this->Previous() ==
nullptr) {
845 if (this->IsPrimaryVehicle()) {
856 this->cargo.Truncate();
860 StopGlobalFollowVehicle(
this);
865 if (CleaningPool()) {
866 this->cargo.OnCleanPool();
874 Vehicle *v = this->Next();
875 this->SetNext(
nullptr);
879 UpdateVehicleTileHash(
this,
true);
880 UpdateVehicleViewportHash(
this,
INVALID_COORD, 0, this->sprite_cache.old_coord.left, this->sprite_cache.old_coord.top);
909 if (_game_mode != GM_NORMAL)
return;
914 if (v ==
nullptr)
continue;
926 if (_game_mode != GM_NORMAL)
return;
931 if (v ==
nullptr)
continue;
937 if (
HasBit(callback, 0)) {
954void CallVehicleTicks()
956 _vehicles_to_autoreplace.clear();
1043 for (
auto &it : _vehicles_to_autoreplace) {
1046 cur_company.Change(v->
owner);
1071 if (error_message == STR_ERROR_AUTOREPLACE_NOTHING_TO_DO || error_message ==
INVALID_STRING_ID)
continue;
1073 if (error_message == STR_ERROR_NOT_ENOUGH_CASH_REQUIRES_CURRENCY) error_message = STR_ERROR_AUTOREPLACE_MONEY_LIMIT;
1076 if (error_message == STR_ERROR_TRAIN_TOO_LONG_AFTER_REPLACEMENT) {
1079 headline =
GetEncodedString(STR_NEWS_VEHICLE_AUTORENEW_FAILED, v->
index, error_message, std::monostate{});
1085 cur_company.Restore();
1125 const int l = dpi->left;
1126 const int r = dpi->left + dpi->width;
1127 const int t = dpi->top;
1128 const int b = dpi->top + dpi->height;
1135 uint xl, xu, yl, yu;
1137 if (
static_cast<uint
>(dpi->width + xb) < GEN_HASHX_SIZE) {
1138 xl = GetViewportHashX(l - xb);
1139 xu = GetViewportHashX(r);
1143 xu = GEN_HASHX_MASK;
1146 if (
static_cast<uint
>(dpi->height + yb) < GEN_HASHY_SIZE) {
1147 yl = GetViewportHashY(t - yb);
1148 yu = GetViewportHashY(b);
1152 yu = GEN_HASHY_MASK;
1155 for (uint y = yl;; y = (y + GEN_HASHY_INC) & GEN_HASHY_MASK) {
1156 for (uint x = xl;; x = (x + GEN_HASHX_INC) & GEN_HASHX_MASK) {
1157 const Vehicle *v = _vehicle_viewport_hash[x + y];
1159 while (v !=
nullptr) {
1162 l <= v->
coord.right + xb &&
1163 t <= v->
coord.bottom + yb &&
1164 r >= v->
coord.left - xb &&
1165 b >= v->
coord.top - yb)
1193 if (l <= v->coord.right &&
1194 t <= v->coord.bottom &&
1195 r >= v->
coord.left &&
1219 uint dist, best_dist = UINT_MAX;
1233 uint xl = GetViewportHashX(x - xb);
1234 uint xu = GetViewportHashX(x);
1235 uint yl = GetViewportHashY(y - yb);
1236 uint yu = GetViewportHashY(y);
1238 for (uint hy = yl;; hy = (hy + GEN_HASHY_INC) & GEN_HASHY_MASK) {
1239 for (uint hx = xl;; hx = (hx + GEN_HASHX_INC) & GEN_HASHX_MASK) {
1240 Vehicle *v = _vehicle_viewport_hash[hx + hy];
1242 while (v !=
nullptr) {
1244 x >= v->
coord.left && x <= v->coord.right &&
1245 y >= v->
coord.top && y <= v->coord.bottom) {
1252 if (dist < best_dist) {
1259 if (hx == xu)
break;
1261 if (hy == yu)
break;
1277static const uint8_t _breakdown_chance[64] = {
1278 3, 3, 3, 3, 3, 3, 3, 3,
1279 4, 4, 5, 5, 6, 6, 7, 7,
1280 8, 8, 9, 9, 10, 10, 11, 11,
1281 12, 13, 13, 13, 13, 14, 15, 16,
1282 17, 19, 21, 25, 28, 31, 34, 37,
1283 40, 44, 48, 52, 56, 60, 64, 68,
1284 72, 80, 90, 100, 110, 120, 130, 140,
1285 150, 170, 190, 210, 230, 250, 250, 250,
1288void CheckVehicleBreakdown(
Vehicle *v)
1301 v->
cur_speed < 5 || _game_mode == GM_MENU) {
1320 if (_breakdown_chance[ClampTo<uint16_t>(rel) >> 10] <= v->
breakdown_chance) {
1340 switch (this->breakdown_ctr) {
1345 this->breakdown_ctr = 1;
1347 if (this->breakdowns_since_last_service != 255) {
1348 this->breakdowns_since_last_service++;
1355 this->cur_speed = 0;
1380 if ((this->tick_counter & (this->type ==
VEH_TRAIN ? 3 : 1)) == 0) {
1381 if (--this->breakdown_delay == 0) {
1382 this->breakdown_ctr = 0;
1390 if (!this->current_order.IsType(OT_LOADING)) this->breakdown_ctr--;
1418 for (int32_t i = 0; i <= 4; i++) {
1441 str = STR_NEWS_VEHICLE_IS_GETTING_OLD;
1443 str = STR_NEWS_VEHICLE_IS_GETTING_VERY_OLD;
1445 str = STR_NEWS_VEHICLE_IS_GETTING_VERY_OLD_AND;
1468 bool loading =
false;
1474 assert(colour ==
nullptr || (st !=
nullptr && is_loading));
1480 for (
const Vehicle *v = front; v !=
nullptr; v = v->
Next()) {
1483 if (v->
cargo_cap != 0 && colour !=
nullptr) {
1485 loading |= !order_no_load &&
1492 if (colour !=
nullptr) {
1493 if (unloading == 0 && loading) {
1494 *colour = STR_PERCENT_UP;
1495 }
else if (unloading == 0 && !loading) {
1496 *colour = STR_PERCENT_NONE;
1497 }
else if (cars == unloading || !loading) {
1498 *colour = STR_PERCENT_DOWN;
1500 *colour = STR_PERCENT_UP_DOWN;
1505 if (max == 0)
return 100;
1508 if (count * 2 < max) {
1510 return CeilDiv(count * 100, max);
1513 return (count * 100) / max;
1524 assert(v == v->
First());
1560 default: NOT_REACHED();
1605 _vehicles_to_autoreplace[v->
index] =
false;
1610 }
else if (cost.
GetCost() != 0) {
1626 _vehicles_to_autoreplace[v->
index] =
false;
1665 UpdateVehicleTileHash(
this,
false);
1675 this->sprite_cache.sprite_seq.GetBounds(&new_coord);
1677 Point pt =
RemapCoords(this->x_pos + this->x_offs, this->y_pos + this->y_offs, this->z_pos);
1678 new_coord.left += pt.x;
1679 new_coord.top += pt.y;
1680 new_coord.right += pt.x + 2 * ZOOM_BASE;
1681 new_coord.bottom += pt.y + 2 * ZOOM_BASE;
1688 this->sprite_cache.old_coord = this->coord.left ==
INVALID_COORD ? new_coord : this->coord;
1692 this->sprite_cache.old_coord.left = std::min(this->sprite_cache.old_coord.left, this->coord.left);
1693 this->sprite_cache.old_coord.top = std::min(this->sprite_cache.old_coord.top, this->coord.top);
1694 this->sprite_cache.old_coord.right = std::max(this->sprite_cache.old_coord.right, this->coord.right);
1695 this->sprite_cache.old_coord.bottom = std::max(this->sprite_cache.old_coord.bottom, this->coord.bottom);
1698 this->coord = new_coord;
1708 bool ignore_cached_coords = this->sprite_cache.old_coord.left ==
INVALID_COORD;
1710 this->UpdateBoundingBoxCoordinates(
true);
1712 if (ignore_cached_coords) {
1715 UpdateVehicleViewportHash(
this, this->coord.left, this->coord.top, this->sprite_cache.old_coord.left, this->sprite_cache.old_coord.top);
1719 if (ignore_cached_coords) {
1723 std::min(this->sprite_cache.old_coord.left, this->coord.left),
1724 std::min(this->sprite_cache.old_coord.top, this->coord.top),
1725 std::max(this->sprite_cache.old_coord.right, this->coord.right),
1726 std::max(this->sprite_cache.old_coord.bottom, this->coord.bottom));
1736 this->UpdatePosition();
1737 this->UpdateViewport(
true);
1746 return ::MarkAllViewportsDirty(this->coord.left, this->coord.top, this->coord.right, this->coord.bottom);
1756 static const int8_t _delta_coord[16] = {
1757 -1,-1,-1, 0, 1, 1, 1, 0,
1758 -1, 0, 1, 1, 1, 0,-1,-1,
1772static const Direction _new_direction_table[] = {
1782 if (y >= v->
y_pos) {
1783 if (y != v->
y_pos) i += 3;
1787 if (x >= v->
x_pos) {
1788 if (x != v->
x_pos) i++;
1820 for (
auto it = std::begin(this->used_bitmap); it != std::end(this->used_bitmap); ++it) {
1821 BitmapStorage available = ~(*it);
1822 if (available == 0)
continue;
1823 return static_cast<UnitID>(std::distance(std::begin(this->used_bitmap), it) * BITMAP_SIZE +
FindFirstBit(available) + 1);
1825 return static_cast<UnitID>(this->used_bitmap.size() * BITMAP_SIZE + 1);
1835 if (index == 0 || index == UINT16_MAX)
return index;
1839 size_t slot = index / BITMAP_SIZE;
1840 if (slot >= this->used_bitmap.size()) this->used_bitmap.resize(slot + 1);
1841 SetBit(this->used_bitmap[index / BITMAP_SIZE], index % BITMAP_SIZE);
1852 if (index == 0 || index == UINT16_MAX)
return;
1856 assert(index / BITMAP_SIZE < this->used_bitmap.size());
1857 ClrBit(this->used_bitmap[index / BITMAP_SIZE], index % BITMAP_SIZE);
1874 default: NOT_REACHED();
1878 if (c->
group_all[type].num_vehicle >= max_veh)
return UINT16_MAX;
1880 return c->freeunits[type].NextID();
1910 default: NOT_REACHED();
1917 if (type ==
VEH_ROAD && GetRoadTramType(e->u.road.roadtype) != (RoadTramType)subtype)
continue;
1945 default: NOT_REACHED();
1950 engine_type = parent_engine_type;
1956 if (!
IsValidCargoType(cargo_type)) cargo_type = GetCargoTypeByLabel(CT_GOODS);
1960 if (parent_engine_type == EngineID::Invalid()) {
1961 return LS_PASSENGER_WAGON_STEAM;
1964 switch (RailVehInfo(parent_engine_type)->engclass) {
1965 default: NOT_REACHED();
1966 case EC_STEAM:
return LS_PASSENGER_WAGON_STEAM;
1967 case EC_DIESEL:
return is_mu ? LS_DMU : LS_PASSENGER_WAGON_DIESEL;
1968 case EC_ELECTRIC:
return is_mu ? LS_EMU : LS_PASSENGER_WAGON_ELECTRIC;
1969 case EC_MONORAIL:
return LS_PASSENGER_WAGON_MONORAIL;
1970 case EC_MAGLEV:
return LS_PASSENGER_WAGON_MAGLEV;
1974 return LS_FREIGHT_WAGON;
1980 default: NOT_REACHED();
1982 case EC_DIESEL:
return is_mu ? LS_DMU : LS_DIESEL;
1983 case EC_ELECTRIC:
return is_mu ? LS_EMU : LS_ELECTRIC;
1991 if (v !=
nullptr && parent_engine_type != EngineID::Invalid()) {
1992 engine_type = parent_engine_type;
1997 if (!
IsValidCargoType(cargo_type)) cargo_type = GetCargoTypeByLabel(CT_GOODS);
2011 if (!
IsValidCargoType(cargo_type)) cargo_type = GetCargoTypeByLabel(CT_GOODS);
2017 case AIR_HELI:
return LS_HELICOPTER;
2018 case AIR_CTOL:
return LS_SMALL_PLANE;
2019 case AIR_CTOL | AIR_FAST:
return LS_LARGE_PLANE;
2020 default: NOT_REACHED();
2053 if (c->livery[LS_DEFAULT].in_use != 0) {
2059 return &c->livery[scheme];
2068 if (map != PAL_NONE)
return map;
2077 static_assert(PAL_NONE == 0);
2078 map =
GB(callback, 0, 14);
2081 if (!
HasBit(callback, 14)) {
2083 if (v !=
nullptr)
const_cast<Vehicle *
>(v)->colourmap = map;
2099 if (twocc) map += livery->
colour2 * 16;
2102 if (v !=
nullptr)
const_cast<Vehicle *
>(v)->colourmap = map;
2114 return GetEngineColourMap(engine_type, company, EngineID::Invalid(),
nullptr);
2128 return GetEngineColourMap(v->
engine_type, v->
owner, EngineID::Invalid(), v);
2136 if (this->IsGroundVehicle()) {
2137 uint16_t &gv_flags = this->GetGroundVehicleFlags();
2141 this->cur_implicit_order_index = this->cur_real_order_index;
2147 const Order *order = this->GetOrder(this->cur_implicit_order_index);
2148 while (order !=
nullptr) {
2149 if (this->cur_implicit_order_index == this->cur_real_order_index)
break;
2151 if (order->
IsType(OT_IMPLICIT)) {
2152 DeleteOrder(
this, this->cur_implicit_order_index);
2154 order = this->GetOrder(this->cur_implicit_order_index);
2157 order = order->
next;
2158 this->cur_implicit_order_index++;
2162 if (order ==
nullptr) {
2163 order = this->GetOrder(0);
2164 this->cur_implicit_order_index = 0;
2178 if (this->current_order.IsType(OT_GOTO_STATION) &&
2179 this->current_order.GetDestination() == this->last_station_visited) {
2180 this->DeleteUnreachedImplicitOrders();
2183 this->current_order.MakeLoading(
true);
2198 Order *in_list = this->GetOrder(this->cur_implicit_order_index);
2199 if (this->IsGroundVehicle() &&
2200 (in_list ==
nullptr || !in_list->
IsType(OT_IMPLICIT) ||
2204 Order *prev_order = this->cur_implicit_order_index > 0 ? this->GetOrder(this->cur_implicit_order_index - 1) : (this->GetNumOrders() > 1 ? this->GetLastOrder() :
nullptr);
2205 if (prev_order ==
nullptr ||
2206 (!prev_order->
IsType(OT_IMPLICIT) && !prev_order->
IsType(OT_GOTO_STATION)) ||
2214 int target_index = this->cur_implicit_order_index;
2216 while (target_index != this->cur_real_order_index || this->GetNumManualOrders() == 0) {
2217 const Order *order = this->GetOrder(target_index);
2218 if (order ==
nullptr)
break;
2224 if (target_index >= this->orders->GetNumOrders()) {
2225 if (this->GetNumManualOrders() == 0 &&
2231 if (target_index == this->cur_implicit_order_index)
break;
2235 if (suppress_implicit_orders) {
2237 this->cur_implicit_order_index = target_index;
2241 const Order *order = this->GetOrder(this->cur_implicit_order_index);
2243 if (order->
IsType(OT_IMPLICIT)) {
2244 DeleteOrder(
this, this->cur_implicit_order_index);
2246 order = this->GetOrder(this->cur_implicit_order_index);
2249 order = order->
next;
2250 this->cur_implicit_order_index++;
2254 if (order ==
nullptr) {
2255 order = this->GetOrder(0);
2256 this->cur_implicit_order_index = 0;
2258 assert(order !=
nullptr);
2261 }
else if (!suppress_implicit_orders &&
2266 implicit_order->
MakeImplicit(this->last_station_visited);
2267 InsertOrder(
this, implicit_order, this->cur_implicit_order_index);
2268 if (this->cur_implicit_order_index > 0) --this->cur_implicit_order_index;
2272 uint16_t &gv_flags = this->GetGroundVehicleFlags();
2277 this->current_order.MakeLoading(
false);
2280 if (this->last_loading_station != StationID::Invalid() &&
2281 this->last_loading_station != this->last_station_visited &&
2282 ((this->current_order.GetLoadType() &
OLFB_NO_LOAD) == 0 ||
2295 this->cur_speed = 0;
2306 for (
Vehicle *v =
this; v !=
nullptr; v = v->
next) {
2309 Debug(misc, 1,
"cancelling cargo reservation");
2322 assert(this->current_order.IsType(OT_LOADING));
2324 delete this->cargo_payment;
2325 assert(this->cargo_payment ==
nullptr);
2330 if ((this->current_order.GetLoadType() &
OLFB_NO_LOAD) == 0 ||
2332 if (this->current_order.CanLeaveWithCargo(this->last_loading_station != StationID::Invalid())) {
2336 this->ResetRefitCaps();
2340 this->last_loading_station = this->last_station_visited;
2345 this->last_loading_station = StationID::Invalid();
2349 this->current_order.MakeLeaveStation();
2351 this->CancelReservation(StationID::Invalid(), st);
2352 st->loading_vehicles.remove(
this);
2391 Company::Get(this->owner)->freeunits[this->type].ReleaseID(this->unitnumber);
2392 this->unitnumber = 0;
2402 switch (this->current_order.GetType()) {
2404 TimerGameTick::Ticks wait_time = std::max(this->current_order.GetTimetabledWait() - this->lateness_counter, 0);
2409 this->PlayLeaveStationSound();
2411 this->LeaveStation();
2414 const Order *order = this->GetOrder(this->cur_implicit_order_index);
2415 if (order ==
nullptr ||
2416 (!order->
IsType(OT_IMPLICIT) && !order->
IsType(OT_GOTO_STATION)) ||
2423 case OT_DUMMY:
break;
2428 this->IncrementImplicitOrderIndex();
2437 for (
Order *o : this->Orders()) {
2449 for (
Order *o : this->Orders()) {
2450 if (o->IsType(OT_CONDITIONAL))
return true;
2461 for (
Order *o : this->Orders()) {
2462 if (o->IsType(OT_GOTO_DEPOT) && o->GetDepotActionType() &
ODATFB_UNBUNCH)
return true;
2477 if (previous_order ==
nullptr || !previous_order->
IsType(OT_GOTO_DEPOT))
return false;
2493 this->lateness_counter = 0;
2497 int num_vehicles = 0;
2500 Vehicle *u = this->FirstShared();
2503 if (u->
vehstatus.
Any({VehState::Stopped, VehState::Crashed}))
continue;
2510 num_vehicles = std::max(num_vehicles, 1);
2513 TimerGameTick::Ticks separation = std::max((total_travel_time / num_vehicles / num_vehicles), 1);
2517 u = this->FirstShared();
2520 if (u->
vehstatus.
Any({VehState::Stopped, VehState::Crashed}))
continue;
2533 assert(this->IsInDepot());
2536 if (!this->IsOrderListShared())
return false;
2539 if (this->GetNumOrders() <= 1)
return false;
2556 if (ret.
Failed())
return ret;
2559 if (this->IsStoppedInDepot())
return CMD_ERROR;
2564 if (this->current_order.IsType(OT_GOTO_DEPOT)) {
2565 bool halt_in_depot = (this->current_order.GetDepotActionType() &
ODATFB_HALT) != 0;
2571 this->current_order.SetDepotOrderType(
ODTF_MANUAL);
2582 if (this->current_order.GetDepotOrderType() &
ODTFB_PART_OF_ORDERS) this->IncrementRealOrderIndex();
2584 if (this->IsGroundVehicle()) {
2585 uint16_t &gv_flags = this->GetGroundVehicleFlags();
2589 this->current_order.MakeDummy();
2596 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};
2597 if (!closest_depot.found)
return CommandCost(no_depot[this->type]);
2600 if (this->current_order.IsType(OT_LOADING)) this->LeaveStation();
2602 if (this->IsGroundVehicle() && this->GetNumManualOrders() > 0) {
2603 uint16_t &gv_flags = this->GetGroundVehicleFlags();
2607 this->SetDestTile(closest_depot.location);
2637 const Engine *e = this->GetEngine();
2640 uint8_t visual_effect;
2655 callback =
GB(callback, 0, 8);
2662 visual_effect = callback;
2686 this->vcache.cached_vis_effect = visual_effect;
2694static const int8_t _vehicle_smoke_pos[8] = {
2695 1, 1, 1, 0, -1, -1, -1, 0
2704 std::array<int32_t, 4> regs100;
2708 uint count =
GB(callback, 0, 2);
2709 assert(count <= std::size(regs100));
2710 bool auto_center =
HasBit(callback, 13);
2711 bool auto_rotate = !
HasBit(callback, 14);
2713 int8_t l_center = 0;
2726 int8_t x_center = _vehicle_smoke_pos[l_dir] * l_center;
2727 int8_t y_center = _vehicle_smoke_pos[t_dir] * l_center;
2729 for (uint i = 0; i < count; i++) {
2730 int32_t reg = regs100[i];
2731 uint type =
GB(reg, 0, 8);
2732 int8_t x =
GB(reg, 8, 8);
2733 int8_t y =
GB(reg, 16, 8);
2734 int8_t z =
GB(reg, 24, 8);
2739 x = _vehicle_smoke_pos[l_dir] * l + _vehicle_smoke_pos[t_dir] * t;
2740 y = _vehicle_smoke_pos[t_dir] * l - _vehicle_smoke_pos[l_dir] * t;
2761 assert(this->IsPrimaryVehicle());
2770 this->vehstatus.Any({VehState::TrainSlowing, VehState::Stopped}) ||
2771 this->cur_speed < 2) {
2776 uint max_speed = this->GetCurrentMaxSpeed();
2784 if (
HasBit(t->flags, VRF_REVERSING) ||
2800 if (effect_model >= VESM_END) effect_model =
VESM_NONE;
2827 switch (effect_model) {
2851 int power_weight_effect = 0;
2853 power_weight_effect = (32 >> (
Train::From(
this)->gcache.cached_power >> 10)) - (32 >> (
Train::From(
this)->gcache.cached_weight >> 9));
2879 if (evt != EV_END && advanced) {
2882 }
else if (evt != EV_END) {
2890 int x = _vehicle_smoke_pos[v->
direction] * effect_offset;
2891 int y = _vehicle_smoke_pos[(v->
direction + 2) % 8] * effect_offset;
2900 }
while ((v = v->
Next()) !=
nullptr);
2911 assert(
this != next);
2913 if (this->next !=
nullptr) {
2915 for (
Vehicle *v = this->next; v !=
nullptr; v = v->
Next()) {
2916 v->
first = this->next;
2923 if (this->next !=
nullptr) {
2927 for (
Vehicle *v = this->next; v !=
nullptr; v = v->
Next()) {
2928 v->
first = this->first;
2940 assert(this->previous_shared ==
nullptr && this->next_shared ==
nullptr);
2942 if (shared_chain->
orders ==
nullptr) {
2945 this->orders = shared_chain->
orders =
new OrderList(
nullptr, shared_chain);
2949 this->previous_shared = shared_chain;
2953 if (this->next_shared !=
nullptr) this->next_shared->
previous_shared =
this;
2965 bool were_first = (this->FirstShared() ==
this);
2968 this->orders->RemoveVehicle(
this);
2972 this->previous_shared->next_shared = this->NextShared();
2975 if (this->next_shared !=
nullptr) this->next_shared->previous_shared = this->previous_shared;
2978 if (this->orders->GetNumVehicles() == 1) {
2982 }
else if (were_first) {
2988 this->next_shared =
nullptr;
2989 this->previous_shared =
nullptr;
3031 assert(e !=
nullptr);
3078 return STR_ERROR_NO_RAIL_STATION;
3084 StringID err = rv->
IsBus() ? STR_ERROR_NO_BUS_STATION : STR_ERROR_NO_TRUCK_STATION;
3086 for (; rs !=
nullptr; rs = rs->
next) {
3089 err = STR_ERROR_NO_STOP_ARTICULATED_VEHICLE;
3096 err = RoadTypeIsRoad(rv->
roadtype) ? STR_ERROR_NO_STOP_COMPATIBLE_ROAD_TYPE : STR_ERROR_NO_STOP_COMPATIBLE_TRAM_TYPE;
3105 return STR_ERROR_NO_DOCK;
3110 return STR_ERROR_AIRPORT_NO_PLANES;
3112 return STR_ERROR_AIRPORT_NO_HELICOPTERS;
3127 assert(this->IsGroundVehicle());
3142 assert(this->IsGroundVehicle());
3157 assert(this->IsGroundVehicle());
3172 assert(this->IsGroundVehicle());
3196 for (; u !=
nullptr && num_vehicles > 0; num_vehicles--) {
3216 uint32_t max_weight = 0;
3218 for (
const Vehicle *u =
this; u !=
nullptr; u = u->
Next()) {
3219 max_weight += u->GetMaxWeight();
3231 uint32_t max_weight = GetDisplayMaxWeight();
3232 if (max_weight == 0)
return 0;
3233 return GetGroundVehicleCache()->cached_power * 10u / max_weight;
3245 if (v1 ==
nullptr && v2 ==
nullptr)
return true;
3246 if (v1 ==
nullptr || v2 ==
nullptr)
return false;
3264 if (o1 ==
nullptr && o2 ==
nullptr)
return true;
3265 if (o1 ==
nullptr || o2 ==
nullptr)
return false;
3266 if (!o1->
Equals(*o2))
return false;
Base functions for all AIs.
void AircraftNextAirportPos_and_Order(Aircraft *v)
set the right pos when heading to other airports after takeoff
Station * GetTargetAirportIfValid(const Aircraft *v)
Returns aircraft's target station if v->target_airport is a valid station with airport.
@ AIR_SHADOW
shadow of the aircraft
void HandleAircraftEnterHangar(Aircraft *v)
Handle Aircraft specific tasks when an Aircraft enters a hangar.
@ FLYING
Vehicle is flying in the air.
CargoTypes GetCargoTypesOfArticulatedVehicle(const Vehicle *v, CargoType *cargo_type)
Get cargo mask of all cargoes carried by an articulated vehicle.
void GetArticulatedRefitMasks(EngineID engine, bool include_initial_cargo_type, CargoTypes *union_mask, CargoTypes *intersection_mask)
Merges the refit_masks of all articulated parts.
CargoTypes GetCargoTypesOfArticulatedParts(EngineID engine)
Get the cargo mask of the parts of a given engine.
Functions related to articulated vehicles.
Command definitions related to autoreplace.
Functions related to autoreplacing.
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.
bool EngineHasReplacementForCompany(const Company *c, EngineID engine, GroupID group)
Check if a company has a replacement set up for the given engine.
void InvalidateAutoreplaceWindow(EngineID e, GroupID id_g)
Rebuild the left autoreplace list if an engine is removed or added.
Functions related to the autoreplace GUIs.
Class for backupping variables and making sure they are restored later.
@ PathfinderLost
Vehicle's pathfinder is lost.
@ StopLoading
Don't load anymore during the next load cycle.
@ LoadingFinished
Vehicle has finished loading.
@ CargoUnloading
Vehicle is unloading cargo.
debug_inline constexpr bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
constexpr T SB(T &x, const uint8_t s, const uint8_t n, const U d)
Set n bits in x starting at bit s to d.
constexpr T SetBit(T &x, const uint8_t y)
Set a bit in a variable.
constexpr uint8_t FindFirstBit(T x)
Search the first set bit in a value.
constexpr bool HasAtMostOneBit(T value)
Test whether value has at most 1 bit set.
debug_inline static constexpr uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
constexpr T ToggleBit(T &x, const uint8_t y)
Toggles a bit in a variable.
constexpr T ClrBit(T &x, const uint8_t y)
Clears a bit in a variable.
Map accessor functions for bridges.
bool IsBridgeAbove(Tile t)
checks if a bridge is set above the ground of this tile
uint8_t CargoType
Cargo slots to indicate a cargo type within a game.
bool IsValidCargoType(CargoType cargo)
Test whether cargo type is not INVALID_CARGO.
bool IsCargoInClass(CargoType cargo, CargoClasses cc)
Does cargo c have cargo class cc?
static void NewEvent(CompanyID company, ScriptEvent *event)
Queue a new event for an AI.
constexpr bool Test(Tvalue_type value) const
Test if the value-th bit is set.
constexpr Timpl & Reset()
Reset all bits.
constexpr Timpl & Set()
Set all bits.
constexpr bool Any(const Timpl &other) const
Test if any of the given values are set.
@ MTA_LOAD
Load the cargo from the station.
Common return value for all commands.
bool Succeeded() const
Did this command succeed?
Money GetCost() const
The costs as made up to this moment.
bool Failed() const
Did this command fail?
StringID GetErrorMessage() const
Returns the error message of a command.
static constexpr int DAYS_IN_ECONOMY_MONTH
Days in an economy month, when in wallclock timekeeping mode.
Container for an encoded string, created by GetEncodedString.
UnitID UseID(UnitID index)
Use a unit number.
void ReleaseID(UnitID index)
Release a unit number.
UnitID NextID() const
Find first unused unit number.
bool GRFBugReverse(uint32_t grfid, uint16_t internal_id)
Logs GRF bug - rail vehicle has different length after reversing.
An interval timer will fire every interval, and will continue to fire until it is deleted.
static void Run(Vehicle *v, bool allow_merge=true, bool is_full_loading=false)
Refresh all links the given vehicle will visit.
static constexpr TimerGameTick::Ticks DAY_TICKS
1 day is 74 ticks; TimerGameCalendar::date_fract used to be uint16_t and incremented by 885.
static Date date
Current date in days (day counter).
static DateFract date_fract
Fractional part of the day.
static constexpr TimerGame< struct Economy >::Date MAX_DATE
The date of the last day of the max year.
static constexpr int DAYS_IN_LEAP_YEAR
sometimes, you need one day more...
static Date date
Current date in days (day counter).
static bool UsingWallclockUnits(bool newgame=false)
Check if we are using wallclock units.
static DateFract date_fract
Fractional part of the day.
uint64_t TickCounter
The type that the tick counter is stored in.
static TickCounter counter
Monotonic counter, in ticks, since start of game.
int32_t Ticks
The type to store ticks in.
static constexpr Date DateAtStartOfYear(Year year)
Calculate the date of the first day of a given year.
CargoList that is used for vehicles.
uint ActionCount(MoveToAction action) const
Returns the amount of cargo designated for a given purpose.
uint Return(uint max_move, StationCargoList *dest, StationID next_station, TileIndex current_tile)
Returns reserved cargo to the station and removes it from the cache.
void KeepAll()
Marks all cargo in the vehicle as to be kept.
void AgeCargo()
Ages the all cargo in this list.
uint StoredCount() const
Returns sum of cargo on board the vehicle (ie not only reserved).
void SkipEmptyBuckets()
Advance the internal state until we reach a non-empty bucket, or the end.
Iterator(int32_t x, int32_t y, uint max_dist)
Iterator constructor.
void Increment()
Advance the internal state to the next potential vehicle.
void SkipFalseMatches()
Advance the internal state until it reaches a vehicle within the search area.
Iterator(TileIndex tile)
Iterator constructor.
void Increment()
Advance the internal state to the next potential vehicle.
void SkipFalseMatches()
Advance the internal state until it reaches a vehicle on the correct tile or the end.
Iterate over all vehicles on a tile.
Functions related to commands.
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
@ Execute
execute the given command
CommandCost CheckOwnership(Owner owner, TileIndex tile)
Check whether the current owner owns something.
void SubtractMoneyFromCompany(const CommandCost &cost)
Subtract money from the _current_company, if the company is valid.
Money GetAvailableMoney(CompanyID company)
Get the amount of money that a company has available, or INT64_MAX if there is no such valid company.
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
CompanyID _current_company
Company currently doing an action.
Functions related to companies.
bool IsLocalCompany()
Is the current company the local company?
Some simple functions to help with accessing containers.
bool include(Container &container, typename Container::const_reference &item)
Helper function to append an item to a container if it is not already contained.
#define Debug(category, level, format_string,...)
Output a line of debugging information.
Functions related to depots.
void DeleteDepotHighlightOfVehicle(const Vehicle *v)
Removes the highlight of a vehicle in a depot window.
Map related accessors for depots.
bool IsDepotTile(Tile tile)
Is the given tile a tile with a depot on it?
DirDiff DirDifference(Direction d0, Direction d1)
Calculate the difference between two directions.
Direction ReverseDir(Direction d)
Return the reverse of a direction.
Direction ChangeDir(Direction d, DirDiff delta)
Change a direction by a given difference.
DirDiff
Enumeration for the difference between two directions.
@ DIRDIFF_45LEFT
Angle of 45 degrees left.
@ DIRDIFF_REVERSE
One direction is the opposite of the other one.
@ DIRDIFF_45RIGHT
Angle of 45 degrees right.
@ DIRDIFF_SAME
Both directions faces to the same direction.
@ DIRDIFF_90RIGHT
Angle of 90 degrees right.
Direction
Defines the 8 directions on the map.
@ INVALID_DIAGDIR
Flag for an invalid DiagDirection.
void LoadUnloadStation(Station *st)
Load/unload the vehicles in this station according to the order they entered.
void PrepareUnload(Vehicle *front_v)
Prepare the vehicle to be unloaded.
Base classes related to the economy.
@ EXPENSES_NEW_VEHICLES
New vehicles.
EffectVehicle * CreateEffectVehicleRel(const Vehicle *v, int x, int y, int z, EffectVehicleType type)
Create an effect vehicle above a particular vehicle.
Base class for all effect vehicles.
Functions related to effect vehicles.
EffectVehicleType
Effect vehicle types.
@ EV_BREAKDOWN_SMOKE
Smoke of broken vehicles except aircraft.
@ EV_STEAM_SMOKE
Smoke of steam engines.
@ EV_DIESEL_SMOKE
Smoke of diesel engines.
@ EV_BREAKDOWN_SMOKE_AIRCRAFT
Smoke of broken aircraft.
@ EV_ELECTRIC_SPARK
Sparcs of electric engines.
@ AIR_CTOL
Conventional Take Off and Landing, i.e. planes.
@ RoadIsTram
Road vehicle is a tram/light rail vehicle.
@ NoBreakdownSmoke
Do not show black smoke during a breakdown.
@ Uses2CC
Vehicle uses two company colours.
@ RailIsMU
Rail vehicle is a multiple-unit (DMU/EMU)
@ EC_DIESEL
Diesel rail engine.
@ EC_STEAM
Steam rail engine.
@ EC_MAGLEV
Maglev engine.
@ EC_ELECTRIC
Electric rail engine.
@ EC_MONORAIL
Mono rail engine.
@ RAILVEH_WAGON
simple wagon, not motorized
Functions related to errors.
@ WL_CRITICAL
Critical errors, the MessageBox is shown in all cases.
void ShowErrorMessage(EncodedString &&summary_msg, int x, int y, CommandCost &cc)
Display an error message in a window.
Types for recording game performance data.
@ PFE_GL_SHIPS
Time spent processing ships.
@ PFE_GL_AIRCRAFT
Time spent processing aircraft.
@ PFE_GL_ECONOMY
Time spent processing cargo movement.
@ PFE_GL_ROADVEHS
Time spend processing road vehicles.
@ PFE_GL_TRAINS
Time spent processing trains.
Gamelog _gamelog
Gamelog instance.
Functions to be called to log fundamental changes to the game.
void DrawSprite(SpriteID img, PaletteID pal, int x, int y, const SubSprite *sub, ZoomLevel zoom)
Draw a sprite, not in a viewport.
@ Normal
The most basic (normal) sprite.
uint32_t PaletteID
The number of the palette.
@ GVF_SUPPRESS_IMPLICIT_ORDERS
Disable insertion and removal of automatic orders until the vehicle completes the real order.
bool MarkAllViewportsDirty(int left, int top, int right, int bottom)
Mark all viewports that display an area as dirty (in need of repaint).
void MarkTilesDirty(bool cargo_change) const
Marks the tiles of the station as dirty.
void MarkTileDirtyByTile(TileIndex tile, int bridge_level_offset, int tile_height_override)
Mark a tile given by its index dirty for repaint.
virtual void MarkDirty()
Marks the vehicles to be redrawn and updates cached variables.
void DeleteGroupHighlightOfVehicle(const Vehicle *v)
Removes the highlight of a vehicle in a group window.
Functions/definitions that have something to do with groups.
static constexpr GroupID DEFAULT_GROUP
Ungrouped vehicles are in this group.
const TileTypeProcs *const _tile_type_procs[16]
Tile callback functions for each type of tile.
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.
@ Random
Randomise borders.
Declaration of link graph classes used for cargo distribution.
static const uint8_t LIT_ALL
Show the liveries of all companies.
LiveryScheme
List of different livery schemes.
static const uint8_t LIT_COMPANY
Show the liveries of your own company.
static debug_inline uint TileY(TileIndex tile)
Get the Y component of a tile.
static debug_inline uint TileX(TileIndex tile)
Get the X component of a tile.
static debug_inline TileIndex TileVirtXY(uint x, uint y)
Get a tile from the virtual XY-coordinate.
constexpr bool IsInsideMM(const size_t x, const size_t min, const size_t max) noexcept
Checks if a value is in an interval.
constexpr T abs(const T a)
Returns the absolute value of (scalar) variable.
constexpr uint CeilDiv(uint a, uint b)
Computes ceil(a / b) for non-negative a and b.
constexpr T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Miscellaneous command definitions.
void HideFillingPercent(TextEffectID *te_id)
Hide vehicle loading indicators.
void ShowCostOrIncomeAnimation(int x, int y, int z, Money cost)
Display animated income or costs on the map.
bool _networking
are we in networking mode?
Basic functions/variables used all over the place.
@ VisualEffect
Visual effects and wagon power (trains, road vehicles and ships)
@ ColourRemap
Change colour mapping of vehicle.
@ CBID_VEHICLE_SPAWN_VISUAL_EFFECT
Called to spawn visual effects for vehicles.
@ CBID_VEHICLE_COLOUR_MAPPING
Called to determine if a specific colour map should be used for a vehicle instead of the default live...
@ CBID_VEHICLE_32DAY_CALLBACK
Called for every vehicle every 32 days (not all on same date though).
@ CBID_VEHICLE_VISUAL_EFFECT
Visual effects and wagon power.
static const uint CALLBACK_FAILED
Different values for Callback result evaluations.
void ErrorUnknownCallbackResult(uint32_t grfid, uint16_t cbid, uint16_t cb_res)
Record that a NewGRF returned an unknown/invalid callback result.
GRFConfig * GetGRFConfig(uint32_t grfid, uint32_t mask)
Retrieve a NewGRF from the current config by its grfid.
GRFBug
Encountered GRF bugs.
@ VehPoweredWagon
Powered wagon changed poweredness state when not inside a depot.
@ VehLength
Length of rail vehicle changes when not inside a depot.
Functions/types related to NewGRF debugging.
GrfSpecFeature GetGrfSpecFeature(TileIndex tile)
Get the GrfSpecFeature associated with the tile.
void DeleteNewGRFInspectWindow(GrfSpecFeature feature, uint index)
Delete inspect window for a given feature and index.
bool UsesWagonOverride(const Vehicle *v)
Check if a wagon is currently using a wagon override.
uint16_t GetVehicleCallback(CallbackID callback, uint32_t param1, uint32_t param2, EngineID engine, const Vehicle *v, std::span< int32_t > regs100)
Evaluate a newgrf callback for vehicles.
NewGRF definitions and structures for road stops.
bool PlayVehicleSound(const Vehicle *v, VehicleSoundEvent event, bool force)
Checks whether a NewGRF wants to play a different vehicle sound effect.
Functions related to NewGRF provided sounds.
@ VSE_VISUAL_EFFECT
Vehicle visual effect (steam, diesel smoke or electric spark) is shown.
@ VSE_RUNNING
Vehicle running normally.
@ VSE_STOPPED_16
Every 16 ticks while the vehicle is stopped (speed == 0).
@ VSE_RUNNING_16
Every 16 ticks while the vehicle is running (speed > 0).
@ VSE_BREAKDOWN
Vehicle breaking down.
void TriggerStationRandomisation(BaseStation *st, TileIndex trigger_tile, StationRandomTrigger trigger, CargoType cargo_type)
Trigger station randomisation.
Header file for NewGRF stations.
Functions related to news.
void AddVehicleAdviceNewsItem(AdviceType advice_type, EncodedString &&headline, VehicleID vehicle)
Adds a vehicle-advice news item.
void DeleteVehicleNews(VehicleID vid, AdviceType advice_type=AdviceType::Invalid)
Delete news with a given advice type about a vehicle.
@ VehicleLost
The vehicle has become lost.
@ VehicleWaiting
The vehicle is waiting in the depot.
@ AutorenewFailed
Autorenew or autoreplace failed.
@ VehicleOld
The vehicle is starting to get old.
@ VehicleUnprofitable
The vehicle is costing you money.
@ RefitFailed
The refit order failed to execute.
@ Error
A game paused because a (critical) error.
@ Normal
A game normally paused.
Functions related to order backups.
void InsertOrder(Vehicle *v, Order *new_o, VehicleOrderID sel_ord)
Insert a new order but skip the validation.
void DeleteOrder(Vehicle *v, VehicleOrderID sel_ord)
Delete an order but skip the parameter validation.
void InvalidateVehicleOrder(const Vehicle *v, int data)
Updates the widgets of a vehicle which contains the order-data.
void DeleteVehicleOrders(Vehicle *v, bool keep_orderlist, bool reset_order_indices)
Delete all orders from a vehicle.
@ OUFB_NO_UNLOAD
Totally no unloading will be done.
@ ODTFB_PART_OF_ORDERS
This depot order is because of a regular order.
@ ODTFB_SERVICE
This depot order is because of the servicing limit.
@ ODTF_MANUAL
Manually initiated order.
@ ODATFB_UNBUNCH
Service the vehicle and then unbunch it.
@ ODATFB_NEAREST_DEPOT
Send the vehicle to the nearest depot.
@ ODATFB_HALT
Service the vehicle and then halt it.
@ ODATF_SERVICE_ONLY
Only service the vehicle.
static const VehicleOrderID MAX_VEH_ORDER_ID
Last valid VehicleOrderID.
@ OLFB_FULL_LOAD
Full load all cargoes of the consist.
@ OLFB_NO_LOAD
Do not load anything.
@ OLF_FULL_LOAD_ANY
Full load a single cargo of the consist.
static const uint IMPLICIT_ORDER_ONLY_CAP
Maximum number of orders in implicit-only lists before we start searching harder for duplicates.
@ ONSF_NO_STOP_AT_ANY_STATION
The vehicle will not stop at any stations it passes including the destination.
@ ONSF_STOP_EVERYWHERE
The vehicle will stop at any station it passes and the destination.
Some methods of Pool are placed here in order to reduce compilation time and binary size.
#define INSTANTIATE_POOL_METHODS(name)
Force instantiation of pool methods so we don't get linker errors.
bool HasAnyRailTypesAvail(const CompanyID company)
Test if any buildable railtype is available for a company.
RailType GetTileRailType(Tile tile)
Return the rail type of tile, or INVALID_RAILTYPE if this is no rail tile.
bool HasPowerOnRail(RailType enginetype, RailType tiletype)
Checks if an engine of the given RailType got power on a tile with a given RailType.
void SetDepotReservation(Tile t, bool b)
Set the reservation state of the depot.
Pseudo random number generator.
uint32_t RandomRange(uint32_t limit, const std::source_location location=std::source_location::current())
Pick a random number between 0 and limit - 1, inclusive.
bool Chance16I(const uint32_t a, const uint32_t b, const uint32_t r)
Checks if a given randomize-number is below a given probability.
bool Chance16(const uint32_t a, const uint32_t b, const std::source_location location=std::source_location::current())
Flips a coin with given probability.
Definition of link refreshing utility.
bool HasAnyRoadTypesAvail(CompanyID company, RoadTramType rtt)
Test if any buildable RoadType is available for a company.
bool HasTileAnyRoadType(Tile t, RoadTypes rts)
Check if a tile has one of the specified road types.
Base class for roadstops.
@ RVSB_IN_DT_ROAD_STOP
The vehicle is in a drive-through road stop.
A number of safeguards to prevent using unsafe methods.
GameSettings _settings_game
Game settings of a running game or the scenario editor.
ClientSettings _settings_client
The current settings for this game.
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.
Functions related to sound.
@ SND_3A_BREAKDOWN_TRAIN_SHIP_TOYLAND
58 == 0x3A Breakdown: train or ship (toyland)
@ SND_10_BREAKDOWN_TRAIN_SHIP
14 == 0x0E Breakdown: train or ship (non-toyland)
@ SND_0F_BREAKDOWN_ROADVEHICLE
13 == 0x0D Breakdown: road vehicle (non-toyland)
@ SND_35_BREAKDOWN_ROADVEHICLE_TOYLAND
53 == 0x35 Breakdown: road vehicle (toyland)
Functions to cache sprites in memory.
static const PaletteID PALETTE_RECOLOUR_START
First recolour sprite for company colours.
static const PaletteID PALETTE_CRASH
Recolour sprite greying of crashed vehicles.
Base classes/functions for stations.
void IncreaseStats(Station *st, CargoType cargo, StationID next_station_id, uint capacity, uint usage, uint32_t time, EdgeUpdateModes modes)
Increase capacity for a link stat given by station cargo and next hop.
bool IsStationRoadStopTile(Tile t)
Is tile t a road stop station?
bool IsBayRoadStopTile(Tile t)
Is tile t a bay (non-drive through) road stop station?
bool IsRailStationTile(Tile t)
Is this tile a station tile and a rail station?
StationID GetStationIndex(Tile t)
Get StationID from a tile.
RoadStopType GetRoadStopType(Tile t)
Get the road stop type of this tile.
@ Bus
A standard stop for buses.
@ Truck
A standard stop for trucks.
@ Dock
Station with a dock.
@ TruckStop
Station with truck stops.
@ Train
Station with train station.
@ Airport
Station with an airport.
@ BusStop
Station with bus stops.
@ VehicleDeparts
Trigger platform when train leaves.
@ VehicleDeparts
Trigger platform when train leaves.
Definition of base types and functions in a cross-platform compatible way.
static void StrMakeValid(Builder &builder, StringConsumer &consumer, StringValidationSettings settings)
Copies the valid (UTF-8) characters from consumer to the builder.
EncodedString GetEncodedString(StringID str)
Encode a string with no parameters into an encoded string.
std::string GetString(StringID string)
Resolve the given StringID into a std::string with formatting but no parameters.
Functions related to OTTD's strings.
uint32_t StringID
Numeric value that represents a string, independent of the selected language.
static const StringID INVALID_STRING_ID
Constant representing an invalid string (16bit in case it is used in savegames)
uint8_t subtype
Type of aircraft.
Aircraft, helicopters, rotors and their shadows belong to this class.
uint8_t pos
Next desired position of the aircraft.
uint8_t state
State of the airport.
bool IsNormalAircraft() const
Check if the aircraft type is a normal flying device; eg not a rotor or a shadow.
uint8_t previous_pos
Previous desired position of the aircraft.
StationID targetairport
Airport to go to next.
@ Airplanes
Can planes land on this airport type?
@ Helicopters
Can helicopters land on this airport type?
std::vector< AirportFTA > layout
state machine for airport
Flags flags
Flags for this airport type.
AirportBlocks blocks
stores which blocks on the airport are taken. was 16 bit earlier on, then 32
const AirportFTAClass * GetFTA() const
Get the finite-state machine for this airport or the finite-state machine for the dummy airport in ca...
Class to backup a specific variable and restore it later.
void Restore()
Restore the variable.
TimerGameTick::TickCounter depot_unbunching_next_departure
When the vehicle will next try to leave its unbunching depot.
VehicleOrderID cur_real_order_index
The index to the current real (non-implicit) order.
TimerGameTick::Ticks round_trip_time
How many ticks for a single circumnavigation of the orders.
VehicleFlags vehicle_flags
Used for gradual loading and other miscellaneous things (.
TimerGameTick::TickCounter depot_unbunching_last_departure
When the vehicle last left its unbunching depot.
VehicleOrderID cur_implicit_order_index
The index to the current implicit order.
void ResetDepotUnbunching()
Resets all the data used for depot unbunching.
StationFacilities facilities
The facilities that this station has.
VehicleType type
Type of vehicle.
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo type.
GUISettings gui
settings related to the GUI
Structure to return information about the closest depot location, and whether it could be found.
DestinationID destination
The DestinationID as used for orders.
CompanySettings settings
settings specific for each company
uint32_t engine_renew_money
minimum amount of money before autorenew is used
int16_t engine_renew_months
months before/after the maximum vehicle age a vehicle should be renewed
bool engine_renew
is autorenew enabled
std::array< GroupStatistics, VEH_COMPANY_END > group_all
NOSAVE: Statistics for the ALL_GROUP group.
uint8_t vehicle_breakdowns
likelihood of vehicles breaking down
Data about how and where to blit pixels.
A special vehicle is one of the following:
TransparencyOption GetTransparencyOption() const
Determines the transparency option affecting the effect.
uint16_t animation_state
State primarily used to change the graphics/behaviour.
EngineMiscFlags misc_flags
Miscellaneous flags.
VehicleCallbackMasks callback_mask
Bitmask of vehicle callbacks that have to be called.
uint32_t GetGRFID() const
Retrieve the GRF ID of the NewGRF the engine is tied to.
const GRFFile * GetGRF() const
Retrieve the NewGRF the engine is tied to.
static Pool::IterateWrapperFiltered< Engine, EngineTypeFilter > IterateType(VehicleType vt, size_t from=0)
Returns an iterable ensemble of all valid engines of the given type.
CargoGRFFileProps grf_prop
Link to NewGRF.
CompanyMask company_avail
Bit for each company whether the engine is available for that company.
VehicleType type
Vehicle type, ie VEH_ROAD, VEH_TRAIN, etc.
CargoType GetDefaultCargoType() const
Determines the default cargo type of an engine.
uint16_t reliability
Current reliability of the engine.
Information about GRF, used in the game and (part of it) in savegames.
GRFBugs grf_bugs
NOSAVE: bugs in this GRF in this run,.
std::string GetName() const
Get the name of this grf.
uint16_t local_id
id defined by the grf file for this entity
uint32_t grfid
grfid that introduced this entity.
Dynamic data of a loaded NewGRF.
bool lost_vehicle_warn
if a vehicle can't find its destination, show a warning
bool vehicle_income_warn
if a vehicle isn't generating income, show a warning
bool show_track_reservation
highlight reserved tracks.
uint8_t liveries
options for displaying company liveries, 0=none, 1=self, 2=all
bool old_vehicle_warn
if a vehicle is getting old, show a warning
LandscapeType landscape
the landscape we're currently in
DifficultySettings difficulty
settings related to the difficulty
GameCreationSettings game_creation
settings used during the creation of a game (map)
VehicleSettings vehicle
options for vehicles
OrderSettings order
settings related to orders
Position information of a vehicle after it moved.
TileIndex new_tile
Tile of the vehicle after moving.
int y
x and y position of the vehicle after moving
TileIndex old_tile
Current tile of the vehicle.
Cached, frequently calculated values.
EngineID first_engine
Cached EngineID of the front vehicle. EngineID::Invalid() for the front vehicle itself.
bool IsMultiheaded() const
Check if the vehicle is a multiheaded engine.
static void CountVehicle(const Vehicle *v, int delta)
Update num_vehicle when adding or removing a vehicle.
static void VehicleReachedMinAge(const Vehicle *v)
Add a vehicle to the profit sum of its group.
static void CountEngine(const Vehicle *v, int delta)
Update num_engines when adding/removing an engine.
static void UpdateAutoreplace(CompanyID company)
Update autoreplace_defined and autoreplace_finished of all statistics of a company.
static void UpdateProfits()
Recompute the profits for all groups.
Livery livery
Custom colour scheme for vehicles in this group.
GroupID parent
Parent group.
Information about a particular livery.
Colours colour2
Second colour, for vehicles with 2CC support.
Colours colour1
First colour, for all vehicles.
uint8_t in_use
Bit 0 set if this livery should override the default livery first colour, Bit 1 for the second colour...
bool revalidate_before_draw
We need to do a GetImage() and check bounds before drawing this sprite.
VehicleSpriteSeq sprite_seq
Vehicle appearance.
Rect old_coord
Co-ordinates from the last valid bounding box.
static void ClearVehicle(const Vehicle *v)
Clear/update the (clone) vehicle from an order backup.
Shared order list linking together the linked list of orders and the list of vehicles sharing this or...
void AddVehicle(Vehicle *v)
Adds the given vehicle to this shared order list.
bool no_servicing_if_no_breakdowns
don't send vehicles to depot when breakdowns are disabled
OrderDepotTypeFlags GetDepotOrderType() const
What caused us going to the depot?
bool Equals(const Order &other) const
Does this order have the same type, flags and destination?
DestinationID GetDestination() const
Gets the destination of this order.
bool IsType(OrderType type) const
Check whether this order is of the given type.
CargoType GetRefitCargo() const
Get the cargo to to refit to.
OrderLoadFlags GetLoadType() const
How must the consist be loaded?
void MakeDummy()
Makes this order a Dummy order.
Order * next
Pointer to next order. If nullptr, end of list.
OrderDepotActionFlags GetDepotActionType() const
What are we going to do when in the depot.
bool ShouldStopAtStation(const Vehicle *v, StationID station) const
Check whether the given vehicle should stop at the given station based on this order and the non-stop...
void MakeImplicit(StationID destination)
Makes this order an implicit order.
bool IsRefit() const
Is this order a refit order.
Coordinates of a point in 2D.
static Pool::IterateWrapper< Titem > Iterate(size_t from=0)
Returns an iterable ensemble of all valid Titem.
static size_t GetPoolSize()
Returns first unused index.
static Titem * Get(auto index)
Returns Titem with given index.
Tindex index
Index of this pool item.
static bool CanAllocateItem(size_t n=1)
Helper functions so we can use PoolItem::Function() instead of _poolitem_pool.Function()
static bool IsValidID(auto index)
Tests whether given index can be used to get valid (non-nullptr) Titem.
static Titem * GetIfValid(auto index)
Returns Titem with given index.
Base class for all pools.
uint8_t visual_effect
Bitstuffed NewGRF visual effect data.
EngineClass engclass
Class of engine for this vehicle.
Specification of a rectangle with absolute coordinates of all edges.
A Stop for a Road Vehicle.
void Leave(RoadVehicle *rv)
Leave the road stop.
RoadStop * next
Next stop of the given type at this station.
TileIndex xy
Position on the map.
static RoadStop * GetByTile(TileIndex tile, RoadStopType type)
Find a roadstop at given tile.
uint8_t visual_effect
Bitstuffed NewGRF visual effect data.
Buses, trucks and trams belong to this class.
RoadTypes compatible_roadtypes
NOSAVE: Roadtypes this consist is powered on.
bool IsBus() const
Check whether a roadvehicle is a bus.
RoadType roadtype
NOSAVE: Roadtype of this vehicle.
VehicleID disaster_vehicle
NOSAVE: Disaster vehicle targetting this vehicle.
uint8_t visual_effect
Bitstuffed NewGRF visual effect data.
All ships have this type.
TrackBits state
The "track" the ship is following.
void UpdateCache()
Update the caches of this ship.
static bool IsValidID(auto index)
Tests whether given index is a valid index for station of this type.
static Station * Get(auto index)
Gets station with given index.
static Station * GetIfValid(auto index)
Returns station if the index is a valid index for this station type.
T * Next() const
Get next vehicle in the chain.
static T * From(Vehicle *v)
Converts a Vehicle to SpecializedVehicle with type checking.
void UpdateViewport(bool force_update, bool update_delta)
Update vehicle sprite- and position caches.
T * GetFirstEnginePart()
Get the first part of an articulated engine.
Data structure describing a sprite.
uint16_t width
Width of the sprite.
uint16_t height
Height of the sprite.
int16_t y_offs
Number of pixels to shift the sprite downwards.
int16_t x_offs
Number of pixels to shift the sprite to the right.
std::array< GoodsEntry, NUM_CARGO > goods
Goods at this station.
Airport airport
Tile area the airport covers.
VehicleEnterTileProc * vehicle_enter_tile_proc
Called when a vehicle enters a tile.
'Train' is either a loco or a wagon.
void ConsistChanged(ConsistChangeFlags allowed_changes)
Recalculates the cached stuff of a train.
uint16_t wait_counter
Ticks waiting in front of a signal, ticks being stuck or a counter for forced proceeding through sign...
uint8_t cached_vis_effect
Visual effect to show (see VisualEffect)
uint16_t cached_cargo_age_period
Number of ticks before carried cargo is aged.
The information about a vehicle list.
WindowNumber ToWindowNumber() const
Pack a VehicleListIdentifier in 32 bits so it can be used as unique WindowNumber.
UnitID max_ships
max ships in game per company
UnitID max_trains
max trains in game per company
uint8_t smoke_amount
amount of smoke/sparks locomotives produce
UnitID max_aircraft
max planes in game per company
UnitID max_roadveh
max trucks in game per company
Sprite sequence for a vehicle part.
bool IsValid() const
Check whether the sequence contains any sprites.
void Draw(int x, int y, PaletteID default_pal, bool force_pal) const
Draw the sprite sequence.
Money GetDisplayProfitThisYear() const
Gets the profit vehicle had this year.
CargoPayment * cargo_payment
The cargo payment we're currently in.
EngineID engine_type
The type of engine used for this vehicle.
uint16_t cargo_age_counter
Ticks till cargo is aged next.
int32_t z_pos
z coordinate.
uint16_t & GetGroundVehicleFlags()
Access the ground vehicle flags of the vehicle.
Direction direction
facing
void ShiftDates(TimerGameEconomy::Date interval)
Shift all dates by given interval.
TimerGameEconomy::Date economy_age
Age in economy days.
const Engine * GetEngine() const
Retrieves the engine of the vehicle.
virtual uint Crash(bool flooded=false)
Crash the (whole) vehicle chain.
Order * GetOrder(int index) const
Returns order 'index' of a vehicle or nullptr when it doesn't exists.
bool HasDepotOrder() const
Checks if a vehicle has a depot in its order list.
void LeaveStation()
Perform all actions when leaving a station.
void AddToShared(Vehicle *shared_chain)
Adds this vehicle to a shared vehicle chain.
VehicleCargoList cargo
The cargo this vehicle is carrying.
uint8_t x_extent
x-extent of vehicle bounding box
Vehicle ** hash_tile_prev
NOSAVE: Previous vehicle in the tile location hash.
bool HasUnbunchingOrder() const
Check if the current vehicle has an unbunching order.
TimerGameEconomy::Date date_of_last_service
Last economy date the vehicle had a service at a depot.
uint16_t cargo_cap
total capacity
StationID last_loading_station
Last station the vehicle has stopped at and could possibly leave from with any cargo loaded.
CommandCost SendToDepot(DoCommandFlags flags, DepotCommandFlags command)
Send this vehicle to the depot using the given command(s).
void ReleaseUnitNumber()
Release the vehicle's unit number.
void UpdateBoundingBoxCoordinates(bool update_cache) const
Update the bounding box co-ordinates of the vehicle.
uint8_t day_counter
Increased by one for each day.
void HandleLoading(bool mode=false)
Handle the loading of the vehicle; when not it skips through dummy orders and does nothing in all oth...
Money profit_this_year
Profit this year << 8, low 8 bits are fract.
bool HasArticulatedPart() const
Check if an engine has an articulated part.
SpriteID colourmap
NOSAVE: cached colour mapping.
uint8_t breakdown_ctr
Counter for managing breakdown events.
uint8_t breakdown_delay
Counter for managing breakdown length.
Vehicle * GetNextVehicle() const
Get the next real (non-articulated part) vehicle in the consist.
GroupID group_id
Index of group Pool array.
void IncrementImplicitOrderIndex()
Increments cur_implicit_order_index, keeps care of the wrap-around and invalidates the GUI.
uint8_t z_extent
z-extent of vehicle bounding box
VehStates vehstatus
Status.
TimerGameCalendar::Date date_of_last_service_newgrf
Last calendar date the vehicle had a service at a depot, unchanged by the date cheat to protect again...
Vehicle * first
NOSAVE: pointer to the first vehicle in the chain.
void CancelReservation(StationID next, Station *st)
Return all reserved cargo packets to the station and reset all packets staged for transfer.
Money profit_last_year
Profit last year << 8, low 8 bits are fract.
Order * GetFirstOrder() const
Get the first order of the vehicles order list.
bool IsEngineCountable() const
Check if a vehicle is counted in num_engines in each company struct.
virtual ~Vehicle()
We want to 'destruct' the right class.
bool IsArticulatedPart() const
Check if the vehicle is an articulated part of an engine.
bool NeedsAutorenewing(const Company *c, bool use_renew_setting=true) const
Function to tell if a vehicle needs to be autorenewed.
void UpdateVisualEffect(bool allow_power_change=true)
Update the cached visual effect.
void LeaveUnbunchingDepot()
Leave an unbunching depot and calculate the next departure time for shared order vehicles.
int8_t y_offs
y offset for vehicle sprite
CargoType cargo_type
type of cargo this vehicle is carrying
debug_inline bool IsFrontEngine() const
Check if the vehicle is a front engine.
Vehicle * previous_shared
NOSAVE: pointer to the previous vehicle in the shared order chain.
Vehicle * First() const
Get the first vehicle of this vehicle chain.
int8_t x_bb_offs
x offset of vehicle bounding box
Order current_order
The current order (+ status, like: loading)
void PreDestructor()
Destroy all stuff that (still) needs the virtual functions to work properly.
void HandlePathfindingResult(bool path_found)
Handle the pathfinding result, especially the lost status.
Vehicle * Next() const
Get the next vehicle of this vehicle.
int8_t x_offs
x offset for vehicle sprite
int32_t y_pos
y coordinate.
int32_t x_pos
x coordinate.
const GRFFile * GetGRF() const
Retrieve the NewGRF the vehicle is tied to.
OrderList * orders
Pointer to the order list for this vehicle.
uint32_t GetDisplayMinPowerToWeight() const
Calculates the minimum power-to-weight ratio using the maximum weight of the ground vehicle.
uint8_t y_extent
y-extent of vehicle bounding box
void UpdateViewport(bool dirty)
Update the vehicle on the viewport, updating the right hash and setting the new coordinates.
Money value
Value of the vehicle.
bool MarkAllViewportsDirty() const
Marks viewports dirty where the vehicle's image is.
uint16_t refit_cap
Capacity left over from before last refit.
VehicleCache vcache
Cache of often used vehicle values.
uint32_t motion_counter
counter to occasionally play a vehicle sound.
uint32_t GetGRFID() const
Retrieve the GRF ID of the NewGRF the vehicle is tied to.
GroundVehicleCache * GetGroundVehicleCache()
Access the ground vehicle cache of the vehicle.
virtual void OnNewEconomyDay()
Calls the new economy day handler of the vehicle.
Vehicle ** hash_tile_current
NOSAVE: Cache of the current hash chain.
virtual void OnNewCalendarDay()
Calls the new calendar day handler of the vehicle.
Vehicle * NextShared() const
Get the next vehicle of the shared vehicle chain.
int8_t y_bb_offs
y offset of vehicle bounding box
bool HasFullLoadOrder() const
Check if the current vehicle has a full load order.
virtual bool IsPrimaryVehicle() const
Whether this is the primary vehicle in the chain.
void BeginLoading()
Prepare everything to begin the loading when arriving at a station.
Order * GetLastOrder() const
Returns the last order of a vehicle, or nullptr if it doesn't exists.
Vehicle * hash_tile_next
NOSAVE: Next vehicle in the tile location hash.
uint16_t cur_speed
current speed
Vehicle * previous
NOSAVE: pointer to the previous vehicle in the chain.
bool HasEngineType() const
Check whether Vehicle::engine_type has any meaning.
TimerGameCalendar::Date age
Age in calendar days.
bool IsWaitingForUnbunching() const
Check whether a vehicle inside a depot is waiting for unbunching.
TextEffectID fill_percent_te_id
a text-effect id to a loading indicator object
void SetNext(Vehicle *next)
Set the next vehicle of this vehicle.
uint8_t breakdowns_since_last_service
Counter for the amount of breakdowns.
Vehicle * next
pointer to the next vehicle in the chain
TimerGameCalendar::Date max_age
Maximum age.
MutableSpriteCache sprite_cache
Cache of sprites and values related to recalculating them, see MutableSpriteCache.
uint16_t reliability
Reliability.
uint32_t GetDisplayMaxWeight() const
Calculates the maximum weight of the ground vehicle when loaded.
void RemoveFromShared()
Removes the vehicle from the shared order list.
bool HandleBreakdown()
Handle all of the aspects of a vehicle breakdown This includes adding smoke and sounds,...
debug_inline bool IsGroundVehicle() const
Check if the vehicle is a ground vehicle.
void UpdatePositionAndViewport()
Update the position of the vehicle, and update the viewport.
Vehicle(VehicleType type=VEH_INVALID)
Vehicle constructor.
Vehicle * Previous() const
Get the previous vehicle of this vehicle.
Rect coord
NOSAVE: Graphical bounding box of the vehicle, i.e. what to redraw on moves.
uint16_t reliability_spd_dec
Reliability decrease speed.
uint8_t tick_counter
Increased by one for each tick.
TileIndex tile
Current tile index.
virtual bool Tick()
Calls the tick handler of the vehicle.
TileIndex dest_tile
Heading for this tile.
bool NeedsServicing() const
Check if the vehicle needs to go to a depot in near future (if a opportunity presents itself) for ser...
bool HasConditionalOrder() const
Check if the current vehicle has a conditional order.
void UpdatePosition()
Update the position of the vehicle.
StationID last_station_visited
The last station we stopped at.
void ResetRefitCaps()
Reset all refit_cap in the consist to cargo_cap.
uint8_t breakdown_chance
Current chance of breakdowns.
void ShowVisualEffect() const
Draw visual effects (smoke and/or sparks) for a vehicle chain.
Owner owner
Which company owns the vehicle?
Vehicle * next_shared
pointer to the next vehicle that shares the order
bool NeedsAutomaticServicing() const
Checks if the current order should be interrupted for a service-in-depot order.
void DeleteUnreachedImplicitOrders()
Delete all implicit orders which were not reached.
Vehicle ** hash_viewport_prev
NOSAVE: Previous vehicle in the visual location hash.
virtual void GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const
Gets the sprite to show for the given direction.
Vehicle * hash_viewport_next
NOSAVE: Next vehicle in the visual location hash.
Data structure for viewport, display of a part of the world.
int top
Screen coordinate top edge of the viewport.
int width
Screen width of the viewport.
ZoomLevel zoom
The zoom level of the viewport.
int virtual_top
Virtual top coordinate.
int virtual_left
Virtual left coordinate.
int left
Screen coordinate left edge of the viewport.
int height
Screen height of the viewport.
VehicleEnterTileStates VehicleEnterTile(Vehicle *v, TileIndex tile, int x, int y)
Call the tile callback function for a vehicle entering a tile.
int GetTileMaxPixelZ(TileIndex tile)
Get top height of the tile.
static debug_inline TileType GetTileType(Tile tile)
Get the tiletype of a given tile.
static debug_inline bool IsTileType(Tile tile, TileType type)
Checks if a tile is a given tiletype.
static const int MAX_VEHICLE_PIXEL_Y
Maximum height of a vehicle in pixels in ZOOM_BASE.
static const uint TILE_SIZE
Tile size in world coordinates.
static const int MAX_VEHICLE_PIXEL_X
Maximum width of a vehicle in pixels in ZOOM_BASE.
@ MP_STATION
A tile of a station.
Definition of Interval and OneShot timers.
Definition of the game-calendar-timer.
Definition of the game-economy-timer.
Definition of the tick-based game-timer.
bool TracksOverlap(TrackBits bits)
Checks if the given tracks overlap, ie form a crossing.
TrackBits
Allow incrementing of Track variables.
@ TRACK_BIT_DEPOT
Bitflag for a depot.
Base for the train class.
@ VRF_LEAVING_STATION
Train is just leaving a station.
@ VRF_TOGGLE_REVERSE
Used for vehicle var 0xFE bit 8 (toggled each time the train is reversed, accurate for first vehicle ...
@ VRF_REVERSE_DIRECTION
Reverse the visible direction of the vehicle.
@ TFP_NONE
Normal operation.
static constexpr ConsistChangeFlags CCF_ARRANGE
Valid changes for arranging the consist in a depot.
Command definitions related to trains.
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...
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...
TransparencyOption
Transparency option bits: which position in _transparency_opt stands for which transparency.
@ TO_INVALID
Invalid transparency option.
uint16_t UnitID
Type for the company global vehicle unit number.
Map accessors for tunnels.
bool IsTunnelTile(Tile t)
Is this a tunnel (entrance)?
void ShowNewGrfVehicleError(EngineID engine, StringID part1, StringID part2, GRFBug bug_type, bool critical)
Displays a "NewGrf Bug" error message for a engine, and pauses the game if not networking.
static uint GetTileHash(uint x, uint y)
Compute hash for tile coordinate.
static void VehicleEnteredDepotThisTick(Vehicle *v)
Adds a vehicle to the list of vehicles that visited a depot this tick.
static void SpawnAdvancedVisualEffect(const Vehicle *v)
Call CBID_VEHICLE_SPAWN_VISUAL_EFFECT and spawn requested effects.
static uint GetTileHash1D(uint p)
Compute hash for 1D tile coordinate.
void VehicleLengthChanged(const Vehicle *u)
Logs a bug in GRF and shows a warning message if this is for the first time this happened.
VehiclePool _vehicle_pool("Vehicle")
The pool with all our precious vehicles.
void VehicleServiceInDepot(Vehicle *v)
Service a vehicle and all subsequent vehicles in the consist.
static void RunEconomyVehicleDayProc()
Increases the day counter for all vehicles and calls 1-day and 32-day handlers.
static uint ComposeTileHash(uint hx, uint hy)
Compose two 1D hashes into 2D hash.
static uint IncTileHash1D(uint h)
Increment 1D hash to next bucket.
bool CanVehicleUseStation(EngineID engine_type, const Station *st)
Can this station be used by the given engine type?
Vehicle * CheckClickOnVehicle(const Viewport &vp, int x, int y)
Find the vehicle close to the clicked coordinates.
std::map< VehicleID, bool > AutoreplaceMap
List of vehicles that should check for autoreplace this tick.
static bool PreviousOrderIsUnbunching(const Vehicle *v)
Check if the previous order is a depot unbunching order.
static void DoDrawVehicle(const Vehicle *v)
Add vehicle sprite for drawing to the screen.
@ VE_TYPE_DEFAULT
Use default from engine class.
@ VE_TYPE_COUNT
Number of bits used for the effect type.
@ VE_OFFSET_CENTRE
Value of offset corresponding to a position above the centre of the vehicle.
@ VE_TYPE_ELECTRIC
Electric sparks.
@ VE_TYPE_START
First bit used for the type of effect.
@ VE_OFFSET_COUNT
Number of bits used for the offset.
@ VE_ADVANCED_EFFECT
Flag for advanced effects.
@ VE_DISABLE_EFFECT
Flag to disable visual effect.
@ VE_TYPE_STEAM
Steam plumes.
@ VE_TYPE_DIESEL
Diesel fumes.
@ VE_DEFAULT
Default value to indicate that visual effect should be based on engine class.
@ VE_OFFSET_START
First bit that contains the offset (0 = front, 8 = centre, 15 = rear)
@ VE_DISABLE_WAGON_POWER
Flag to disable wagon power.
@ Unclickable
Vehicle is not clickable by the user (shadow vehicles).
@ Crashed
Vehicle is crashed.
@ Shadow
Vehicle is a shadow vehicle.
@ TrainSlowing
Train is slowing down.
@ AircraftBroken
Aircraft is broken down.
@ Hidden
Vehicle is not visible.
@ DefaultPalette
Use default vehicle palette.
@ Stopped
Vehicle is stopped by the player.
VisualEffectSpawnModel
Models for spawning visual effects.
@ VESM_ELECTRIC
Electric model.
@ VESM_DIESEL
Diesel model.
@ VESM_NONE
No visual effect.
static const int32_t INVALID_COORD
Sentinel for an invalid coordinate.
Command definitions for vehicles.
Functions related to vehicles.
void ShowNewGrfVehicleError(EngineID engine, StringID part1, StringID part2, GRFBug bug_type, bool critical)
Displays a "NewGrf Bug" error message for a engine, and pauses the game if not networking.
CommandCost EnsureNoVehicleOnGround(TileIndex tile)
Ensure there is no vehicle at the ground at the given position.
bool VehiclesHaveSameEngineList(const Vehicle *v1, const Vehicle *v2)
Checks if two vehicle chains have the same list of engines.
bool VehiclesHaveSameOrderList(const Vehicle *v1, const Vehicle *v2)
Checks if two vehicles have the same list of orders.
SpriteID GetEnginePalette(EngineID engine_type, CompanyID company)
Get the colour map for an engine.
void VehicleEnterDepot(Vehicle *v)
Vehicle entirely entered the depot, update its status, orders, vehicle windows, service it,...
static const TimerGameEconomy::Date VEHICLE_PROFIT_MIN_AGE
Only vehicles older than this have a meaningful profit.
void GetVehicleSet(VehicleSet &set, Vehicle *v, uint8_t num_vehicles)
Calculates the set of vehicles that will be affected by a given selection.
UnitID GetFreeUnitNumber(VehicleType type)
Get an unused unit number for a vehicle (if allowed).
void RunVehicleCalendarDayProc()
Age all vehicles, spreading out the action using the current TimerGameCalendar::date_fract.
void VehicleServiceInDepot(Vehicle *v)
Service a vehicle and all subsequent vehicles in the consist.
CommandCost EnsureNoTrainOnTrackBits(TileIndex tile, TrackBits track_bits)
Tests if a vehicle interacts with the specified track bits.
LiveryScheme GetEngineLiveryScheme(EngineID engine_type, EngineID parent_engine_type, const Vehicle *v)
Determines the LiveryScheme for a vehicle.
void ViewportAddVehicles(DrawPixelInfo *dpi)
Add the vehicle sprites that should be drawn at a part of the screen.
GetNewVehiclePosResult GetNewVehiclePos(const Vehicle *v)
Get position information of a vehicle when moving one pixel in the direction it is facing.
StringID GetVehicleCannotUseStationReason(const Vehicle *v, const Station *st)
Get reason string why this station can't be used by the given vehicle.
void ReleaseDisasterVehicle(VehicleID vehicle)
Notify disasters that we are about to delete a vehicle.
void DecreaseVehicleValue(Vehicle *v)
Decrease the value of a vehicle.
void EconomyAgeVehicle(Vehicle *v)
Update economy age of a vehicle.
const struct Livery * GetEngineLivery(EngineID engine_type, CompanyID company, EngineID parent_engine_type, const Vehicle *v, uint8_t livery_setting)
Determines the livery for a vehicle.
CommandCost TunnelBridgeIsFree(TileIndex tile, TileIndex endtile, const Vehicle *ignore=nullptr)
Finds vehicle in tunnel / bridge.
bool CanBuildVehicleInfrastructure(VehicleType type, uint8_t subtype=0)
Check whether we can build infrastructure for the given vehicle type.
void AgeVehicle(Vehicle *v)
Update age of a vehicle.
SpriteID GetVehiclePalette(const Vehicle *v)
Get the colour map for a vehicle.
uint8_t CalcPercentVehicleFilled(const Vehicle *v, StringID *colour)
Calculates how full a vehicle is.
bool IsCompanyBuildableVehicleType(VehicleType type)
Is the given vehicle type buildable by a company?
@ VIWD_MODIFY_ORDERS
Other order modifications.
WindowClass GetWindowClassForVehicleType(VehicleType vt)
Get WindowClass for vehicle list of given vehicle type.
@ EIT_ON_MAP
Vehicle drawn in viewport.
VehicleType
Available vehicle types.
@ VEH_ROAD
Road vehicle type.
@ VEH_DISASTER
Disaster vehicle type.
@ VEH_AIRCRAFT
Aircraft vehicle type.
@ VEH_SHIP
Ship vehicle type.
@ VEH_EFFECT
Effect vehicle type (smoke, explosions, sparks, bubbles)
@ VEH_TRAIN
Train vehicle type.
@ Callback32
All vehicles in consist: 32 day callback requested rerandomisation.
@ Depot
Front vehicle only: Consist arrived in depot.
@ DontCancel
Don't cancel current goto depot command if any.
@ Service
The vehicle will leave the depot right after arrival (service only)
static const uint VEHICLE_LENGTH
The length of a vehicle in tile units.
Functions and type for generating vehicle lists.
@ VL_SHARED_ORDERS
Index is the first vehicle of the shared orders.
void StartSpriteCombine()
Starts a block of sprites, which are "combined" into a single bounding box.
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.
void EndSpriteCombine()
Terminates a block of sprites started by StartSpriteCombine.
Functions related to (drawing on) viewports.
void CloseWindowById(WindowClass cls, WindowNumber number, bool force, int data)
Close a window by its class and window number (if it is open).
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting)
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 SetWindowWidgetDirty(WindowClass cls, WindowNumber number, WidgetID widget_index)
Mark a particular widget in a particular window as dirty (in need of repainting)
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
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...
@ WC_ROADVEH_LIST
Road vehicle list; Window numbers:
@ WC_VEHICLE_ORDERS
Vehicle orders; Window numbers:
@ WC_VEHICLE_DEPOT
Depot view; Window numbers:
@ WC_SHIPS_LIST
Ships list; Window numbers:
@ WC_STATION_VIEW
Station view; Window numbers:
@ WC_TRAINS_LIST
Trains list; Window numbers:
@ WC_VEHICLE_REFIT
Vehicle refit; Window numbers:
@ WC_VEHICLE_DETAILS
Vehicle details; Window numbers:
@ WC_COMPANY
Company view; Window numbers:
@ WC_VEHICLE_VIEW
Vehicle view; Window numbers:
@ WC_VEHICLE_TIMETABLE
Vehicle timetable; Window numbers:
@ WC_AIRCRAFT_LIST
Aircraft list; Window numbers:
Functions related to zooming.
int ScaleByZoom(int value, ZoomLevel zoom)
Scale by zoom level, usually shift left (when zoom > ZoomLevel::Min) When shifting right,...