57 #include "table/strings.h" 62 static const uint GEN_HASHX_BITS = 6;
63 static const uint GEN_HASHY_BITS = 6;
66 static const uint GEN_HASHX_BUCKET_BITS = 7;
67 static const uint GEN_HASHY_BUCKET_BITS = 6;
70 #define GEN_HASHX(x) GB((x), GEN_HASHX_BUCKET_BITS + ZOOM_LVL_SHIFT, GEN_HASHX_BITS) 71 #define GEN_HASHY(y) (GB((y), GEN_HASHY_BUCKET_BITS + ZOOM_LVL_SHIFT, GEN_HASHY_BITS) << GEN_HASHX_BITS) 72 #define GEN_HASH(x, y) (GEN_HASHY(y) + GEN_HASHX(x)) 75 static const int GEN_HASHX_SIZE = 1 << (GEN_HASHX_BUCKET_BITS + GEN_HASHX_BITS + ZOOM_LVL_SHIFT);
76 static const int GEN_HASHY_SIZE = 1 << (GEN_HASHY_BUCKET_BITS + GEN_HASHY_BITS + ZOOM_LVL_SHIFT);
79 static const int GEN_HASHX_INC = 1;
80 static const int GEN_HASHY_INC = 1 << GEN_HASHX_BITS;
83 static const uint GEN_HASHX_MASK = (1 << GEN_HASHX_BITS) - 1;
84 static const uint GEN_HASHY_MASK = ((1 << GEN_HASHY_BITS) - 1) << GEN_HASHX_BITS;
102 bounds->left = bounds->top = bounds->right = bounds->bottom = 0;
103 for (uint i = 0; i < this->count; ++i) {
106 bounds->left = spr->
x_offs;
107 bounds->top = spr->
y_offs;
111 if (spr->
x_offs < bounds->left) bounds->left = spr->
x_offs;
112 if (spr->
y_offs < bounds->top) bounds->top = spr->
y_offs;
115 if (right > bounds->right) bounds->right = right;
116 if (bottom > bounds->bottom) bounds->bottom = bottom;
130 for (uint i = 0; i < this->count; ++i) {
131 PaletteID pal = force_pal || !this->seq[i].
pal ? default_pal : this->seq[i].
pal;
193 if (this->ServiceIntervalIsPercent() ?
194 (this->reliability >= this->GetEngine()->reliability * (100 - this->GetServiceInterval()) / 100) :
195 (this->date_of_last_service + this->GetServiceInterval() >=
_date)) {
209 bool pending_replace =
false;
211 if (needed_money > c->
money)
return false;
214 bool replace_when_old =
false;
220 if (replace_when_old && !v->NeedsAutorenewing(c,
false))
continue;
223 CargoTypes available_cargo_types, union_mask;
226 if (union_mask != 0) {
234 if (!
HasBit(available_cargo_types, cargo_type))
continue;
240 pending_replace =
true;
241 needed_money += 2 *
Engine::Get(new_engine)->GetCost();
242 if (needed_money > c->
money)
return false;
245 return pending_replace;
255 if (this->HasDepotOrder())
return false;
256 if (this->current_order.IsType(OT_LOADING))
return false;
257 if (this->current_order.IsType(OT_GOTO_DEPOT) && this->current_order.GetDepotOrderType() !=
ODTFB_SERVICE)
return false;
258 return NeedsServicing();
264 assert(this->Previous() == NULL);
268 if (this->IsPrimaryVehicle()) this->vehstatus |=
VS_STOPPED;
270 for (
Vehicle *v =
this; v != NULL; v = v->
Next()) {
274 v->MarkAllViewportsDirty();
283 delete this->cargo_payment;
284 assert(this->cargo_payment == NULL);
304 if (grfconfig == NULL)
return;
318 GetString(buffer, part1,
lastof(buffer));
319 DEBUG(grf, 0,
"%s", buffer + 3);
322 GetString(buffer, part2,
lastof(buffer));
323 DEBUG(grf, 0,
"%s", buffer + 3);
351 this->fill_percent_te_id = INVALID_TE_ID;
353 this->colourmap = PAL_NONE;
354 this->cargo_age_counter = 1;
355 this->last_station_visited = INVALID_STATION;
356 this->last_loading_station = INVALID_STATION;
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 != NULL)
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 != NULL)
return a;
529 if (v->
z_pos > z)
return NULL;
556 if (v == (
const Vehicle *)data)
return NULL;
588 if ((t->track != rail_bits) && !
TracksOverlap(t->track | rail_bits))
return NULL;
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 != NULL) {
634 if (new_hash != NULL) {
645 static Vehicle *_vehicle_viewport_hash[1 << (GEN_HASHX_BITS + GEN_HASHY_BITS)];
647 static void UpdateVehicleViewportHash(
Vehicle *v,
int x,
int y)
649 Vehicle **old_hash, **new_hash;
650 int old_x = v->
coord.left;
651 int old_y = v->
coord.top;
653 new_hash = (x ==
INVALID_COORD) ? NULL : &_vehicle_viewport_hash[GEN_HASH(x, y)];
654 old_hash = (old_x ==
INVALID_COORD) ? NULL : &_vehicle_viewport_hash[GEN_HASH(old_x, old_y)];
656 if (old_hash == new_hash)
return;
659 if (old_hash != NULL) {
665 if (new_hash != NULL) {
673 void ResetVehicleHash()
677 memset(_vehicle_viewport_hash, 0,
sizeof(_vehicle_viewport_hash));
678 memset(_vehicle_tile_hash, 0,
sizeof(_vehicle_tile_hash));
681 void ResetVehicleColourMap()
694 void InitializeVehicles()
696 _vehicles_to_autoreplace.
Reset();
700 uint CountVehiclesInChain(
const Vehicle *v)
703 do count++;
while ((v = v->
Next()) != NULL);
713 switch (this->type) {
716 return !this->IsArticulatedPart() &&
720 default:
return false;
730 switch (this->type) {
735 default:
return false;
756 return this->GetEngine()->GetGRF();
766 return this->GetEngine()->GetGRFID();
795 AI::NewEvent(this->owner,
new ScriptEventVehicleLost(this->index));
805 if (CleaningPool())
return;
809 st->loading_vehicles.remove(
this);
812 this->CancelReservation(INVALID_STATION, st);
813 delete this->cargo_payment;
814 assert(this->cargo_payment == NULL);
817 if (this->IsEngineCountable()) {
826 if (this->type ==
VEH_AIRCRAFT && this->IsPrimaryVehicle()) {
836 if (this->type ==
VEH_ROAD && this->IsPrimaryVehicle()) {
844 if (this->Previous() == NULL) {
848 if (this->IsPrimaryVehicle()) {
859 this->cargo.Truncate();
863 extern void StopGlobalFollowVehicle(
const Vehicle *v);
864 StopGlobalFollowVehicle(
this);
871 if (CleaningPool()) {
872 this->cargo.OnCleanPool();
885 UpdateVehicleTileHash(
this,
true);
915 if (_game_mode != GM_NORMAL)
return;
920 if (v == NULL)
continue;
926 if (
HasBit(callback, 0)) {
927 TriggerVehicle(v, VEHICLE_TRIGGER_CALLBACK_32);
943 void CallVehicleTicks()
945 _vehicles_to_autoreplace.
Clear();
1058 if (error_message == STR_ERROR_AUTOREPLACE_NOTHING_TO_DO || error_message ==
INVALID_STRING_ID)
continue;
1060 if (error_message == STR_ERROR_NOT_ENOUGH_CASH_REQUIRES_CURRENCY) error_message = STR_ERROR_AUTOREPLACE_MONEY_LIMIT;
1063 if (error_message == STR_ERROR_TRAIN_TOO_LONG_AFTER_REPLACEMENT) {
1064 message = error_message;
1066 message = STR_NEWS_VEHICLE_AUTORENEW_FAILED;
1098 for (uint i = 0; i < v->
sprite_seq.count; ++i) {
1114 const int l = dpi->left;
1115 const int r = dpi->left + dpi->width;
1116 const int t = dpi->top;
1117 const int b = dpi->top + dpi->height;
1128 xu = GEN_HASHX_MASK;
1137 yu = GEN_HASHY_MASK;
1140 for (
int y = yl;; y = (y + GEN_HASHY_INC) & GEN_HASHY_MASK) {
1141 for (
int x = xl;; x = (x + GEN_HASHX_INC) & GEN_HASHX_MASK) {
1142 const Vehicle *v = _vehicle_viewport_hash[x + y];
1146 l <= v->
coord.right &&
1147 t <= v->
coord.bottom &&
1148 r >= v->
coord.left &&
1149 b >= v->
coord.top) {
1172 uint dist, best_dist = UINT_MAX;
1174 if ((uint)(x -= vp->
left) >= (uint)vp->
width || (uint)(y -= vp->
top) >= (uint)vp->
height)
return NULL;
1181 x >= v->coord.left && x <= v->coord.right &&
1182 y >= v->coord.top && y <= v->coord.bottom) {
1185 abs(((v->coord.left + v->coord.right) >> 1) - x),
1186 abs(((v->coord.top + v->coord.bottom) >> 1) - y)
1189 if (dist < best_dist) {
1209 static const byte _breakdown_chance[64] = {
1210 3, 3, 3, 3, 3, 3, 3, 3,
1211 4, 4, 5, 5, 6, 6, 7, 7,
1212 8, 8, 9, 9, 10, 10, 11, 11,
1213 12, 13, 13, 13, 13, 14, 15, 16,
1214 17, 19, 21, 25, 28, 31, 34, 37,
1215 40, 44, 48, 52, 56, 60, 64, 68,
1216 72, 80, 90, 100, 110, 120, 130, 140,
1217 150, 170, 190, 210, 230, 250, 250, 250,
1220 void CheckVehicleBreakdown(
Vehicle *v)
1233 v->
cur_speed < 5 || _game_mode == GM_MENU) {
1237 uint32 r = Random();
1272 switch (this->breakdown_ctr) {
1277 this->breakdown_ctr = 1;
1279 if (this->breakdowns_since_last_service != 255) {
1280 this->breakdowns_since_last_service++;
1287 this->cur_speed = 0;
1292 (train_or_ship ? SND_10_TRAIN_BREAKDOWN : SND_0F_VEHICLE_BREAKDOWN) :
1293 (train_or_ship ? SND_3A_COMEDY_BREAKDOWN_2 : SND_35_COMEDY_BREAKDOWN),
this);
1312 if ((this->tick_counter & (this->type ==
VEH_TRAIN ? 3 : 1)) == 0) {
1313 if (--this->breakdown_delay == 0) {
1314 this->breakdown_ctr = 0;
1322 if (!this->current_order.IsType(OT_LOADING)) this->breakdown_ctr--;
1356 str = STR_NEWS_VEHICLE_IS_GETTING_OLD;
1357 }
else if (age == 0) {
1358 str = STR_NEWS_VEHICLE_IS_GETTING_VERY_OLD;
1360 str = STR_NEWS_VEHICLE_IS_GETTING_VERY_OLD_AND;
1384 bool loading =
false;
1390 assert(colour == NULL || (st != NULL && is_loading));
1396 for (
const Vehicle *v = front; v != NULL; v = v->
Next()) {
1399 if (v->
cargo_cap != 0 && colour != NULL) {
1401 loading |= !order_no_load &&
1408 if (colour != NULL) {
1409 if (unloading == 0 && loading) {
1410 *colour = STR_PERCENT_UP;
1411 }
else if (unloading == 0 && !loading) {
1412 *colour = STR_PERCENT_NONE;
1413 }
else if (cars == unloading || !loading) {
1414 *colour = STR_PERCENT_DOWN;
1416 *colour = STR_PERCENT_UP_DOWN;
1421 if (max == 0)
return 100;
1424 if (count * 2 < max) {
1426 return CeilDiv(count * 100, max);
1429 return (count * 100) /
max;
1440 assert(v == v->
First());
1476 default: NOT_REACHED();
1493 TriggerVehicle(v, VEHICLE_TRIGGER_DEPOT);
1518 _vehicles_to_autoreplace[v] =
false;
1524 }
else if (cost.
GetCost() != 0) {
1540 _vehicles_to_autoreplace[v] =
false;
1562 UpdateVehicleTileHash(
this,
false);
1573 this->sprite_seq.GetBounds(&new_coord);
1575 Point pt =
RemapCoords(this->x_pos + this->x_offs, this->y_pos + this->y_offs, this->z_pos);
1576 new_coord.left += pt.x;
1577 new_coord.top += pt.y;
1578 new_coord.right += pt.x + 2 * ZOOM_LVL_BASE;
1579 new_coord.bottom += pt.y + 2 * ZOOM_LVL_BASE;
1581 UpdateVehicleViewportHash(
this, new_coord.left, new_coord.top);
1583 Rect old_coord = this->coord;
1584 this->coord = new_coord;
1591 min(old_coord.left, this->coord.left),
1592 min(old_coord.top, this->coord.top),
1593 max(old_coord.right, this->coord.right),
1594 max(old_coord.bottom, this->coord.bottom));
1604 this->UpdatePosition();
1605 this->UpdateViewport(
true);
1623 static const int8 _delta_coord[16] = {
1624 -1,-1,-1, 0, 1, 1, 1, 0,
1625 -1, 0, 1, 1, 1, 0,-1,-1,
1639 static const Direction _new_direction_table[] = {
1649 if (y >= v->
y_pos) {
1650 if (y != v->
y_pos) i += 3;
1654 if (x >= v->
x_pos) {
1655 if (x != v->
x_pos) i++;
1692 if (v->
type == type && v->
owner == owner) {
1697 if (this->
maxid == 0)
return;
1702 this->
cache = CallocT<bool>(this->
maxid + 2);
1706 if (v->
type == type && v->
owner == owner) {
1715 if (this->maxid <= this->
curid)
return ++this->
curid;
1717 while (this->
cache[++this->curid]) { }
1736 default: NOT_REACHED();
1772 default: NOT_REACHED();
1779 FOR_ALL_ENGINES_OF_TYPE(e, type) {
1807 default: NOT_REACHED();
1812 engine_type = parent_engine_type;
1817 if (cargo_type ==
CT_INVALID) cargo_type = e->GetDefaultCargoType();
1818 if (cargo_type ==
CT_INVALID) cargo_type = CT_GOODS;
1822 return LS_PASSENGER_WAGON_STEAM;
1825 switch (RailVehInfo(parent_engine_type)->engclass) {
1826 default: NOT_REACHED();
1827 case EC_STEAM:
return LS_PASSENGER_WAGON_STEAM;
1828 case EC_DIESEL:
return is_mu ? LS_DMU : LS_PASSENGER_WAGON_DIESEL;
1829 case EC_ELECTRIC:
return is_mu ? LS_EMU : LS_PASSENGER_WAGON_ELECTRIC;
1830 case EC_MONORAIL:
return LS_PASSENGER_WAGON_MONORAIL;
1831 case EC_MAGLEV:
return LS_PASSENGER_WAGON_MAGLEV;
1835 return LS_FREIGHT_WAGON;
1840 switch (e->u.rail.engclass) {
1841 default: NOT_REACHED();
1843 case EC_DIESEL:
return is_mu ? LS_DMU : LS_DIESEL;
1844 case EC_ELECTRIC:
return is_mu ? LS_EMU : LS_ELECTRIC;
1853 engine_type = parent_engine_type;
1857 if (cargo_type ==
CT_INVALID) cargo_type = e->GetDefaultCargoType();
1858 if (cargo_type ==
CT_INVALID) cargo_type = CT_GOODS;
1870 if (cargo_type ==
CT_INVALID) cargo_type = e->GetDefaultCargoType();
1871 if (cargo_type ==
CT_INVALID) cargo_type = CT_GOODS;
1875 switch (e->u.air.subtype) {
1876 case AIR_HELI:
return LS_HELICOPTER;
1877 case AIR_CTOL:
return LS_SMALL_PLANE;
1878 case AIR_CTOL | AIR_FAST:
return LS_LARGE_PLANE;
1879 default: NOT_REACHED();
1912 if (c->livery[LS_DEFAULT].
in_use != 0) {
1918 return &c->livery[scheme];
1927 if (map != PAL_NONE)
return map;
1936 assert_compile(PAL_NONE == 0);
1937 map =
GB(callback, 0, 14);
1940 if (!
HasBit(callback, 14)) {
1942 if (v != NULL)
const_cast<Vehicle *
>(v)->colourmap = map;
1958 if (twocc) map += livery->
colour2 * 16;
1961 if (v != NULL)
const_cast<Vehicle *
>(v)->colourmap = map;
1973 return GetEngineColourMap(engine_type, company,
INVALID_ENGINE, NULL);
1995 if (this->IsGroundVehicle()) {
1996 uint16 &gv_flags = this->GetGroundVehicleFlags();
2000 this->cur_implicit_order_index = this->cur_real_order_index;
2006 const Order *order = this->GetOrder(this->cur_implicit_order_index);
2007 while (order != NULL) {
2008 if (this->cur_implicit_order_index == this->cur_real_order_index)
break;
2010 if (order->
IsType(OT_IMPLICIT)) {
2011 DeleteOrder(
this, this->cur_implicit_order_index);
2013 order = this->GetOrder(this->cur_implicit_order_index);
2016 order = order->
next;
2017 this->cur_implicit_order_index++;
2021 if (order == NULL) {
2022 order = this->GetOrder(0);
2023 this->cur_implicit_order_index = 0;
2036 if (this->current_order.IsType(OT_GOTO_STATION) &&
2037 this->current_order.GetDestination() == this->last_station_visited) {
2038 this->DeleteUnreachedImplicitOrders();
2041 this->current_order.MakeLoading(
true);
2056 Order *in_list = this->GetOrder(this->cur_implicit_order_index);
2057 if (this->IsGroundVehicle() &&
2058 (in_list == NULL || !in_list->
IsType(OT_IMPLICIT) ||
2062 Order *prev_order = this->cur_implicit_order_index > 0 ? this->GetOrder(this->cur_implicit_order_index - 1) : (this->GetNumOrders() > 1 ? this->GetLastOrder() : NULL);
2063 if (prev_order == NULL ||
2064 (!prev_order->
IsType(OT_IMPLICIT) && !prev_order->
IsType(OT_GOTO_STATION)) ||
2072 int target_index = this->cur_implicit_order_index;
2074 while (target_index != this->cur_real_order_index || this->GetNumManualOrders() == 0) {
2075 const Order *order = this->GetOrder(target_index);
2076 if (order == NULL)
break;
2082 if (target_index >= this->orders.list->GetNumOrders()) {
2083 if (this->GetNumManualOrders() == 0 &&
2089 if (target_index == this->cur_implicit_order_index)
break;
2093 if (suppress_implicit_orders) {
2095 this->cur_implicit_order_index = target_index;
2099 const Order *order = this->GetOrder(this->cur_implicit_order_index);
2101 if (order->
IsType(OT_IMPLICIT)) {
2102 DeleteOrder(
this, this->cur_implicit_order_index);
2104 order = this->GetOrder(this->cur_implicit_order_index);
2107 order = order->
next;
2108 this->cur_implicit_order_index++;
2112 if (order == NULL) {
2113 order = this->GetOrder(0);
2114 this->cur_implicit_order_index = 0;
2116 assert(order != NULL);
2119 }
else if (!suppress_implicit_orders &&
2124 implicit_order->
MakeImplicit(this->last_station_visited);
2125 InsertOrder(
this, implicit_order, this->cur_implicit_order_index);
2126 if (this->cur_implicit_order_index > 0) --this->cur_implicit_order_index;
2130 uint16 &gv_flags = this->GetGroundVehicleFlags();
2135 this->current_order.MakeLoading(
false);
2138 if (this->last_loading_station != INVALID_STATION &&
2139 this->last_loading_station != this->last_station_visited &&
2140 ((this->current_order.GetLoadType() &
OLFB_NO_LOAD) == 0 ||
2153 this->cur_speed = 0;
2167 DEBUG(misc, 1,
"cancelling cargo reservation");
2181 assert(this->current_order.IsType(OT_LOADING));
2183 delete this->cargo_payment;
2184 assert(this->cargo_payment == NULL);
2189 if ((this->current_order.GetLoadType() &
OLFB_NO_LOAD) == 0 ||
2191 if (this->current_order.CanLeaveWithCargo(this->last_loading_station != INVALID_STATION)) {
2195 this->ResetRefitCaps();
2199 this->last_loading_station = this->last_station_visited;
2203 this->last_loading_station = INVALID_STATION;
2207 this->current_order.MakeLeaveStation();
2209 this->CancelReservation(INVALID_STATION, st);
2210 st->loading_vehicles.remove(
this);
2243 switch (this->current_order.GetType()) {
2245 uint wait_time =
max(this->current_order.GetTimetabledWait() - this->lateness_counter, 0);
2250 this->PlayLeaveStationSound();
2252 this->LeaveStation();
2255 const Order *order = this->GetOrder(this->cur_implicit_order_index);
2256 if (order == NULL ||
2257 (!order->
IsType(OT_IMPLICIT) && !order->
IsType(OT_GOTO_STATION)) ||
2264 case OT_DUMMY:
break;
2269 this->IncrementImplicitOrderIndex();
2278 for (
const Vehicle *v =
this; v != NULL; v = v->
Next()) {
2281 if (pair == capacities.
End()) {
2282 pair = capacities.
Append();
2291 uint Vehicle::GetConsistTotalCapacity()
const 2294 for (
const Vehicle *v =
this; v != NULL; v = v->
Next()) {
2309 if (ret.
Failed())
return ret;
2312 if (this->IsStoppedInDepot())
return CMD_ERROR;
2314 if (this->current_order.IsType(OT_GOTO_DEPOT)) {
2315 bool halt_in_depot = (this->current_order.GetDepotActionType() &
ODATFB_HALT) != 0;
2321 this->current_order.SetDepotOrderType(
ODTF_MANUAL);
2332 if (this->current_order.GetDepotOrderType() &
ODTFB_PART_OF_ORDERS) this->IncrementRealOrderIndex();
2334 if (this->IsGroundVehicle()) {
2335 uint16 &gv_flags = this->GetGroundVehicleFlags();
2339 this->current_order.MakeDummy();
2346 DestinationID destination;
2348 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};
2349 if (!this->FindClosestDepot(&location, &destination, &reverse))
return_cmd_error(no_depot[this->type]);
2352 if (this->current_order.IsType(OT_LOADING)) this->LeaveStation();
2354 if (this->IsGroundVehicle() && this->GetNumManualOrders() > 0) {
2355 uint16 &gv_flags = this->GetGroundVehicleFlags();
2359 this->SetDestTile(location);
2360 this->current_order.MakeGoToDepot(destination,
ODTF_MANUAL);
2390 const Engine *e = this->GetEngine();
2408 callback =
GB(callback, 0, 8);
2415 visual_effect = callback;
2439 this->vcache.cached_vis_effect = visual_effect;
2447 static const int8 _vehicle_smoke_pos[8] = {
2448 1, 1, 1, 0, -1, -1, -1, 0
2460 uint count =
GB(callback, 0, 2);
2461 bool auto_center =
HasBit(callback, 13);
2462 bool auto_rotate = !
HasBit(callback, 14);
2477 int8 x_center = _vehicle_smoke_pos[l_dir] * l_center;
2478 int8 y_center = _vehicle_smoke_pos[t_dir] * l_center;
2480 for (uint i = 0; i < count; i++) {
2482 uint type =
GB(reg, 0, 8);
2483 int8 x =
GB(reg, 8, 8);
2484 int8 y =
GB(reg, 16, 8);
2485 int8 z =
GB(reg, 24, 8);
2490 x = _vehicle_smoke_pos[l_dir] * l + _vehicle_smoke_pos[t_dir] * t;
2491 y = _vehicle_smoke_pos[t_dir] * l - _vehicle_smoke_pos[l_dir] * t;
2512 assert(this->IsPrimaryVehicle());
2522 this->cur_speed < 2) {
2527 uint max_speed = this->GetCurrentMaxSpeed();
2535 if (
HasBit(t->flags, VRF_REVERSING) ||
2551 if (effect_model >= VESM_END) effect_model =
VESM_NONE;
2578 switch (effect_model) {
2602 int power_weight_effect = 0;
2630 if (evt != EV_END && advanced) {
2633 }
else if (evt != EV_END) {
2641 int x = _vehicle_smoke_pos[v->
direction] * effect_offset;
2642 int y = _vehicle_smoke_pos[(v->
direction + 2) % 8] * effect_offset;
2651 }
while ((v = v->
Next()) != NULL);
2662 assert(
this != next);
2664 if (this->next != NULL) {
2666 for (
Vehicle *v = this->next; v != NULL; v = v->
Next()) {
2667 v->
first = this->next;
2674 if (this->next != NULL) {
2678 for (
Vehicle *v = this->next; v != NULL; v = v->
Next()) {
2679 v->
first = this->first;
2691 assert(this->previous_shared == NULL && this->next_shared == NULL);
2700 this->previous_shared = shared_chain;
2704 if (this->next_shared != NULL) this->next_shared->
previous_shared =
this;
2716 bool were_first = (this->FirstShared() ==
this);
2719 this->orders.list->RemoveVehicle(
this);
2723 this->previous_shared->next_shared = this->NextShared();
2726 if (this->next_shared != NULL) this->next_shared->previous_shared = this->previous_shared;
2729 if (this->orders.list->GetNumVehicles() == 1) {
2733 }
else if (were_first) {
2739 this->next_shared = NULL;
2740 this->previous_shared = NULL;
2743 void VehiclesYearlyLoop()
2750 if (v->
age >= 730 && profit < 0) {
2828 assert(this->IsGroundVehicle());
2843 assert(this->IsGroundVehicle());
2858 assert(this->IsGroundVehicle());
2873 assert(this->IsGroundVehicle());
2897 for (; u != NULL && num_vehicles > 0; num_vehicles--) {
2900 set.Include(u->
index);
void ViewportAddVehicles(DrawPixelInfo *dpi)
Add the vehicle sprites that should be drawn at a part of the screen.
Functions related to OTTD's strings.
void TriggerStationRandomisation(Station *st, TileIndex tile, StationRandomTrigger trigger, CargoID cargo_type)
Trigger station randomisation.
static TileType GetTileType(TileIndex tile)
Get the tiletype of a given tile.
bool HasVehicleOnPos(TileIndex tile, void *data, VehicleFromPosProc *proc)
Checks whether a vehicle is on a specific location.
VehicleSettings vehicle
options for vehicles
static bool HasPowerOnRail(RailType enginetype, RailType tiletype)
Checks if an engine of the given RailType got power on a tile with a given RailType.
Functions/types related to NewGRF debugging.
uint16 reliability
Current reliability of the engine.
CommandCost EnsureNoTrainOnTrackBits(TileIndex tile, TrackBits track_bits)
Tests if a vehicle interacts with the specified track bits.
uint32 PaletteID
The number of the palette.
static bool IsLocalCompany()
Is the current company the local company?
Vehicle * Previous() const
Get the previous vehicle of this vehicle.
Vehicle is stopped by the player.
Time spent processing cargo movement.
VehicleCargoList cargo
The cargo this vehicle is carrying.
GameSettings _settings_game
Game settings of a running game or the scenario editor.
static void RunVehicleDayProc()
Increases the day counter for all vehicles and calls 1-day and 32-day handlers.
static Titem * GetIfValid(size_t index)
Returns Titem with given index.
uint32 motion_counter
counter to occasionally play a vehicle sound.
Money value
Value of the vehicle.
bool _networking
are we in networking mode?
int virtual_left
Virtual left coordinate.
void DecreaseVehicleValue(Vehicle *v)
Decrease the value of a vehicle.
static const uint CALLBACK_FAILED
Different values for Callback result evaluations.
void LoadUnloadStation(Station *st)
Load/unload the vehicles in this station according to the order they entered.
Data about how and where to blit pixels.
virtual void MarkDirty()
Marks the vehicles to be redrawn and updates cached variables.
The information about a vehicle list.
void ShowVisualEffect() const
Draw visual effects (smoke and/or sparks) for a vehicle chain.
bool UsesWagonOverride(const Vehicle *v)
Check if a wagon is currently using a wagon override.
Definition of link refreshing utility.
StationID targetairport
Airport to go to next.
static const int VEHICLE_PROFIT_MIN_AGE
Only vehicles older than this have a meaningful profit.
LiveryScheme
List of different livery schemes.
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
byte landscape
the landscape we're currently in
static bool Chance16I(const uint a, const uint b, const uint32 r)
Checks if a given randomize-number is below a given probability.
Money GetDisplayProfitThisYear() const
Gets the profit vehicle had this year.
DirectionByte direction
facing
Base class for roadstops.
Vehicle * hash_tile_next
NOSAVE: Next vehicle in the tile location hash.
Functions related to the autoreplace GUIs.
void ResetRefitCaps()
Reset all refit_cap in the consist to cargo_cap.
Train is just leaving a station.
Don't cancel current goto depot command if any.
const Pair * Find(const T &key) const
Finds given key in this map.
Vehicle has finished loading.
Functions and type for generating vehicle lists.
static RoadStopType GetRoadStopType(TileIndex t)
Get the road stop type of this tile.
static EngineID EngineReplacementForCompany(const Company *c, EngineID engine, GroupID group, bool *replace_when_old=NULL)
Retrieve the engine replacement for the given company and original engine type.
CommandCost EnsureNoVehicleOnGround(TileIndex tile)
Ensure there is no vehicle at the ground at the given position.
VehiclePool _vehicle_pool("Vehicle")
The pool with all our precious vehicles.
void InvalidateVehicleOrder(const Vehicle *v, int data)
Updates the widgets of a vehicle which contains the order-data.
Flag for an invalid DiagDirection.
void HandleAircraftEnterHangar(Aircraft *v)
Handle Aircraft specific tasks when an Aircraft enters a hangar.
int height
Screen height of the viewport.
static Titem * Get(size_t index)
Returns Titem with given index.
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...
Functions related to dates.
static bool IsInsideMM(const T x, const uint min, const uint max)
Checks if a value is in an interval.
Angle of 45 degrees left.
virtual uint Crash(bool flooded=false)
Crash the (whole) vehicle chain.
Vehicle ** hash_viewport_prev
NOSAVE: Previous vehicle in the visual location hash.
Conventional Take Off and Landing, i.e. planes.
static T ToggleBit(T &x, const uint8 y)
Toggles a bit in a variable.
void Reset()
Remove all items from the list and free allocated memory.
const AirportFTAClass * GetFTA() const
Get the finite-state machine for this airport or the finite-state machine for the dummy airport in ca...
Sparcs of electric engines.
byte breakdown_delay
Counter for managing breakdown length.
Use default vehicle palette.
Angle of 90 degrees right.
Vehicle is a shadow vehicle.
Base for the train class.
Other order modifications.
uint8 smoke_amount
amount of smoke/sparks locomotives produce
virtual ~Vehicle()
We want to 'destruct' the right class.
static T SetBit(T &x, const uint8 y)
Set a bit in a variable.
Called to spawn visual effects for vehicles.
void Leave(RoadVehicle *rv)
Leave the road stop.
byte pos
Next desired position of the aircraft.
void SetTransferLoadPlace(TileIndex xy)
Sets loaded_at_xy to the current station for all cargo to be transfered.
Can planes land on this airport type?
uint16 cur_speed
current speed
uint16 cached_cargo_age_period
Number of ticks before carried cargo is aged.
static void AddVehicleAdviceNewsItem(StringID string, VehicleID vehicle)
Adds a vehicle-advice news item.
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
Do not show black smoke during a breakdown.
Data structure describing a sprite.
Depot view; Window numbers:
uint16 cargo_age_counter
Ticks till cargo is aged next.
GRFFilePropsBase< NUM_CARGO+2 > grf_prop
Properties related the the grf file.
Functions to be called to log possibly unsafe game events.
Types for recording game performance data.
Both directions faces to the same direction.
uint16 _returned_refit_capacity
Stores the capacity after a refit operation.
OrderList * list
Pointer to the order list for this vehicle.
Train * GetNextUnit() const
Get the next real (non-articulated part and non rear part of dualheaded engine) vehicle in the consis...
StationID last_loading_station
Last station the vehicle has stopped at and could possibly leave from with any cargo loaded...
byte visual_effect
Bitstuffed NewGRF visual effect data.
TileIndex dest_tile
Heading for this tile.
Vehicle ** hash_tile_prev
NOSAVE: Previous vehicle in the tile location hash.
uint16 wait_counter
Ticks waiting in front of a signal, ticks being stuck or a counter for forced proceeding through sign...
Implementation of simple mapping class.
Functions related to vehicles.
Aircraft, helicopters, rotors and their shadows belong to this class.
static bool IsWagon(EngineID index)
Determine whether an engine type is a wagon (and not a loco).
bool lost_vehicle_warn
if a vehicle can't find its destination, show a warning
void IncrementImplicitOrderIndex()
Increments cur_implicit_order_index, keeps care of the wrap-around and invalidates the GUI...
Trigger platform when train leaves.
static uint TileX(TileIndex tile)
Get the X component of a tile.
void VehicleEnterDepot(Vehicle *v)
Vehicle entirely entered the depot, update its status, orders, vehicle windows, service it...
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 Draw(int x, int y, PaletteID default_pal, bool force_pal) const
Draw the sprite sequence.
UnitID max_aircraft
max planes in game per company
void Clear()
Remove all items from the list.
byte vehicle_breakdowns
likelihood of vehicles breaking down
Flags flags
Flags for this airport type.
void Change(const U &new_value)
Change the value of the variable.
static int ScaleByZoom(int value, ZoomLevel zoom)
Scale by zoom level, usually shift left (when zoom > ZOOM_LVL_NORMAL) When shifting right...
const T * Begin() const
Get the pointer to the first item (const)
Only service the vehicle.
void PreDestructor()
Destroy all stuff that (still) needs the virtual functions to work properly.
void LeaveStation()
Perform all actions when leaving a station.
DifficultySettings difficulty
settings related to the difficulty
TrackBitsByte state
The "track" the ship is following.
Tindex index
Index of this pool item.
Vehicle is flying in the air.
A special vehicle is one of the following:
static const int DAY_TICKS
1 day is 74 ticks; _date_fract used to be uint16 and incremented by 885.
PaletteID GetVehiclePalette(const Vehicle *v)
Get the colour map for a vehicle.
void SetNext(Vehicle *next)
Set the next vehicle of this vehicle.
void UpdateViewport(bool force_update, bool update_delta)
Update vehicle sprite- and position caches.
Vehicle is unloading cargo.
bool IsMultiheaded() const
Check if the vehicle is a multiheaded engine.
StationID last_station_visited
The last station we stopped at.
#define lastof(x)
Get the last element of an fixed size array.
bool CanBuildVehicleInfrastructure(VehicleType type)
Check whether we can build infrastructure for the given vehicle type.
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.
Simple vector template class.
void DeleteVehicleOrders(Vehicle *v, bool keep_orderlist, bool reset_order_indices)
Delete all orders from a vehicle.
void MarkTilesDirty(bool cargo_change) const
Marks the tiles of the station as dirty.
A game paused because a (critical) error.
Money GetCost() const
The costs as made up to this moment.
void HandlePathfindingResult(bool path_found)
Handle the pathfinding result, especially the lost status.
bool IsArticulatedVehicleCarryingDifferentCargoes(const Vehicle *v, CargoID *cargo_type)
Tests if all parts of an articulated vehicle are refitted to the same cargo.
void AircraftNextAirportPos_and_Order(Aircraft *v)
set the right pos when heading to other airports after takeoff
The most basic (normal) sprite.
Visual effects and wagon power.
#define CLRBITS(x, y)
Clears several bits in a variable.
T * GetFirstEnginePart()
Get the first part of an articulated engine.
static const byte LIT_COMPANY
Show the liveries of your own company.
LiveryScheme GetEngineLiveryScheme(EngineID engine_type, EngineID parent_engine_type, const Vehicle *v)
Determines the LiveryScheme for a vehicle.
First bit that contains the offset (0 = front, 8 = centre, 15 = rear)
Common return value for all commands.
uint32 cached_power
Total power of the consist (valid only for the first engine).
GrfSpecFeature GetGrfSpecFeature(TileIndex tile)
Get the GrfSpecFeature associated with the tile.
void StartSpriteCombine()
Starts a block of sprites, which are "combined" into a single bounding box.
StationCargoList cargo
The cargo packets of cargo waiting in this station.
static T max(const T a, const T b)
Returns the maximum of two values.
void MarkAllViewportsDirty() const
Marks viewports dirty where the vehicle's image is.
bool HasRating() const
Does this cargo have a rating at this station?
UnitID GetFreeUnitNumber(VehicleType type)
Get an unused unit number for a vehicle (if allowed).
Cached, frequently calculated values.
uint StoredCount() const
Returns sum of cargo on board the vehicle (ie not only reserved).
uint Return(uint max_move, StationCargoList *dest, StationID next_station)
Returns reserved cargo to the station and removes it from the cache.
Time spent processing aircraft.
static Train * From(Vehicle *v)
Converts a Vehicle to SpecializedVehicle with type checking.
CompanySettings settings
settings specific for each company
const T * End() const
Get the pointer behind the last valid item (const)
Generates sequence of free UnitID numbers.
bool NeedsAutomaticServicing() const
Checks if the current order should be interrupted for a service-in-depot order.
const Engine * GetEngine() const
Retrieves the engine of the vehicle.
Vehicle * next_shared
pointer to the next vehicle that shares the order
bool IsNormalAircraft() const
Check if the aircraft type is a normal flying device; eg not a rotor or a shadow. ...
GoodsEntry goods[NUM_CARGO]
Goods at this station.
static const uint TILE_SIZE
Tile size in world coordinates.
byte VehicleRandomBits()
Get a value for a vehicle's random_bits.
Use default from engine class.
FreeUnitIDGenerator(VehicleType type, CompanyID owner)
Initializes the structure.
static uint32 RandomRange(uint32 limit)
Pick a random number between 0 and limit - 1, inclusive.
VehicleSpriteSeq sprite_seq
Vehicle appearance.
Direction
Defines the 8 directions on the map.
static T SB(T &x, const uint8 s, const uint8 n, const U d)
Set n bits in x starting at bit s to d.
Vehicle * hash_viewport_next
NOSAVE: Next vehicle in the visual location hash.
OrderDepotActionFlags GetDepotActionType() const
What are we going to do when in the depot.
int8 x_bb_offs
x offset of vehicle bounding box
DepotCommand
Flags to add to p1 for goto depot commands.
uint32 GetGRFID() const
Retrieve the GRF ID of the NewGRF the engine is tied to.
Money profit_last_year
Profit last year << 8, low 8 bits are fract.
SmallPair< T, U > * Append(uint to_add=1)
Append an item and return it.
Order * next
Pointer to next order. If NULL, end of list.
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.
replace/renew a vehicle while it is in a depot
CompanyByte _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
Value of offset corresponding to a position above the centre of the vehicle.
bool no_servicing_if_no_breakdowns
don't send vehicles to depot when breakdowns are disabled
Functions related to (drawing on) viewports.
Pseudo random number generator.
Vehicle ** hash_tile_current
NOSAVE: Cache of the current hash chain.
static const int32 INVALID_COORD
Sentinel for an invalid coordinate.
int8 y_bb_offs
y offset of vehicle bounding box
Angle of 45 degrees right.
byte breakdown_ctr
Counter for managing breakdown events.
Vehicle running normally.
The vehicle will stop at any station it passes and the destination.
byte subtype
subtype (Filled with values from AircraftSubType/DisasterSubType/EffectVehicleType/GroundVehicleSubty...
void EndSpriteCombine()
Terminates a block of sprites started by StartSpriteCombine.
static bool IsBridgeAbove(TileIndex t)
checks if a bridge is set above the ground of this tile
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...
TrackBits
Bitfield corresponding to Track.
Buses, trucks and trams belong to this class.
Critical errors, the MessageBox is shown in all cases.
bool ShouldStopAtStation(const Vehicle *v, StationID station) const
Check whether the given vehicle should stop at the given station based on this order and the non-stop...
uint16 cargo_cap
total capacity
void VehicleLengthChanged(const Vehicle *u)
Logs a bug in GRF and shows a warning message if this is for the first time this happened.
void ShowErrorMessage(StringID summary_msg, StringID detailed_msg, WarningLevel wl, int x=0, int y=0, const GRFFile *textref_stack_grffile=NULL, uint textref_stack_size=0, const uint32 *textref_stack=NULL)
Display an error message in a window.
VehicleEnterTileProc * vehicle_enter_tile_proc
Called when a vehicle enters a tile.
Shared order list linking together the linked list of orders and the list of vehicles sharing this or...
void SetDParamStr(uint n, const char *str)
This function is used to "bind" a C string to a OpenTTD dparam slot.
OrderDepotTypeFlags GetDepotOrderType() const
What caused us going to the depot?
Vehicle orders; Window numbers:
Map related accessors for depots.
static void SpawnAdvancedVisualEffect(const Vehicle *v)
Call CBID_VEHICLE_SPAWN_VISUAL_EFFECT and spawn requested effects.
Some methods of Pool are placed here in order to reduce compilation time and binary size...
static uint32 GetRegister(uint i)
Gets the value of a so-called newgrf "register".
void UpdateCache()
Update the caches of this ship.
First bit used for the type of effect.
uint32 grf_bugs
NOSAVE: bugs in this GRF in this run,.
TransparencyOption GetTransparencyOption() const
Determines the transparency option affecting the effect.
virtual bool IsPrimaryVehicle() const
Whether this is the primary vehicle in the chain.
static bool IsTileType(TileIndex tile, TileType type)
Checks if a tile is a given tiletype.
int16 y_offs
Number of pixels to shift the sprite downwards.
static void DoDrawVehicle(const Vehicle *v)
Add vehicle sprite for drawing to the screen.
Functions related to errors.
UnitID unitnumber
unit number, for display purposes only
int y
x and y position of the vehicle after moving
CommandCost DoCommand(const CommandContainer *container, DoCommandFlag flags)
Shorthand for calling the long DoCommand with a container.
void MakeImplicit(StationID destination)
Makes this order an implicit order.
byte subtype
Type of aircraft.
void AgeVehicle(Vehicle *v)
Update age of a vehicle.
DateFract _date_fract
Fractional part of the day.
void DeleteVehicleNews(VehicleID vid, StringID news)
Delete a news item type about a vehicle.
static size_t GetPoolSize()
Returns first unused index.
Information about GRF, used in the game and (part of it) in savegames.
static bool IsRailStationTile(TileIndex t)
Is this tile a station tile and a rail station?
void ConsistChanged(ConsistChangeFlags allowed_changes)
Recalculates the cached stuff of a train.
bool IsRefit() const
Is this order a refit order.
UnitID max_roadveh
max trucks in game per company
Internal structure used in openttd - Finite sTate mAchine –> FTA.
The vehicle will not stop at any stations it passes including the destination.
bool HasVehicleOnPosXY(int x, int y, void *data, VehicleFromPosProc *proc)
Checks whether a vehicle in on a specific location.
bool NeedsServicing() const
Check if the vehicle needs to go to a depot in near future (if a opportunity presents itself) for ser...
void MakeDummy()
Makes this order a Dummy order.
int8 y_offs
y offset for vehicle sprite
GroundVehicleCache * GetGroundVehicleCache()
Access the ground vehicle cache of the vehicle.
VehicleType
Available vehicle types.
EngineClass engclass
Class of engine for this vehicle.
void MarkAllViewportsDirty(int left, int top, int right, int bottom)
Mark all viewports that display an area as dirty (in need of repaint).
void HideFillingPercent(TextEffectID *te_id)
Hide vehicle loading indicators.
Manually initiated order.
Don't load anymore during the next load cycle.
uint32 VehicleID
The type all our vehicle IDs have.
UnitID maxid
maximum ID at the moment of constructor call
StringID GetErrorMessage() const
Returns the error message of a command.
Time spend processing road vehicles.
bool IsType(OrderType type) const
Check whether this order is of the given type.
CommandCost TunnelBridgeIsFree(TileIndex tile, TileIndex endtile, const Vehicle *ignore)
Finds vehicle in tunnel / bridge.
DoCommandFlag
List of flags for a command.
VisualEffectSpawnModel
Models for spawning visual effects.
T * Next() const
Get next vehicle in the chain.
byte callback_mask
Bitmask of vehicle callbacks that have to be called.
simple wagon, not motorized
Station with truck stops.
ClientSettings _settings_client
The current settings for this game.
Rail vehicle is a multiple-unit (DMU/EMU)
bool Succeeded() const
Did this command succeed?
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.
void PrepareUnload(Vehicle *front_v)
Prepare the vehicle to be unloaded.
Can helicopters land on this airport type?
Definition of base types and functions in a cross-platform compatible way.
PaletteID GetEnginePalette(EngineID engine_type, CompanyID company)
Get the colour map for an engine.
static const uint VEHICLE_LENGTH
The length of a vehicle in tile units.
bool IsArticulatedPart() const
Check if the vehicle is an articulated part of an engine.
A number of safeguards to prevent using unsafe methods.
Trigger platform when train leaves.
byte x_extent
x-extent of vehicle bounding box
static void Run(Vehicle *v, bool allow_merge=true, bool is_full_loading=false)
Refresh all links the given vehicle will visit.
void VehicleEnteredDepotThisTick(Vehicle *v)
Adds a vehicle to the list of vehicles that visited a depot this tick.
Vehicle uses two company colours.
bool HasAnyRailtypesAvail(const CompanyID company)
Test if any buildable railtype is available for a company.
void DeleteDepotHighlightOfVehicle(const Vehicle *v)
Removes the highlight of a vehicle in a depot window.
void DeleteOrder(Vehicle *v, VehicleOrderID sel_ord)
Delete an order but skip the parameter validation.
Vehicle refit; Window numbers:
DirDiff
Enumeration for the difference between two directions.
static uint CeilDiv(uint a, uint b)
Computes ceil(a / b) for non-negative a and b.
Station * GetTargetAirportIfValid(const Aircraft *v)
Returns aircraft's target station if v->target_airport is a valid station with airport.
struct AirportFTA * layout
state machine for airport
byte z_extent
z-extent of vehicle bounding box
byte visual_effect
Bitstuffed NewGRF visual effect data.
VehicleType type
Vehicle type, ie VEH_ROAD, VEH_TRAIN, etc.
Valid changes for arranging the consist in a depot.
Every 16 ticks while the vehicle is running (speed > 0).
CargoID cargo_type
type of cargo this vehicle is carrying
uint32 engine_renew_money
minimum amount of money before autorenew is used
uint ActionCount(MoveToAction action) const
Returns the amount of cargo designated for a given purpose.
CompanyMask company_avail
Bit for each company whether the engine is available for that company.
void AddToShared(Vehicle *shared_chain)
Adds this vehicle to a shared vehicle chain.
Change colour mapping of vehicle.
Information about a particular livery.
Effect vehicle type (smoke, explosions, sparks, bubbles)
Vehicle view; Window numbers:
static const byte LIT_ALL
Show the liveries of all companies.
GroupStatistics group_all[VEH_COMPANY_END]
NOSAVE: Statistics for the ALL_GROUP group.
Functions related to order backups.
Smoke of broken vehicles except aircraft.
bool IsFrontEngine() const
Check if the vehicle is a front engine.
GRFBugs
Encountered GRF bugs.
byte misc_flags
Miscellaneous flags.
Map accessor functions for bridges.
void FindVehicleOnPos(TileIndex tile, void *data, VehicleFromPosProc *proc)
Find a vehicle from a specific location.
TileIndex tile
Current tile index.
Road vehicle list; Window numbers:
CommandCost CheckOwnership(Owner owner, TileIndex tile)
Check whether the current owner owns something.
static void CountVehicle(const Vehicle *v, int delta)
Update num_vehicle when adding or removing a vehicle.
static Vehicle * VehicleFromPos(TileIndex tile, void *data, VehicleFromPosProc *proc, bool find_first)
Helper function for FindVehicleOnPos/HasVehicleOnPos.
Money money
Money owned by the company.
void MarkTileDirtyByTile(TileIndex tile, int bridge_level_offset, int tile_height_override)
Mark a tile given by its index dirty for repaint.
Vehicle timetable; Window numbers:
Every 16 ticks while the vehicle is stopped (speed == 0).
bool CanVehicleUseStation(EngineID engine_type, const Station *st)
Can this station be used by the given engine type?
static const GroupID INVALID_GROUP
Sentinel for invalid groups.
Station view; Window numbers:
OrderLoadFlags GetLoadType() const
How must the consist be loaded?
Base class for all effect vehicles.
Basic functions/variables used all over the place.
static DirDiff DirDifference(Direction d0, Direction d1)
Calculate the difference between two directions.
Service the vehicle and then halt it.
bool IsRearDualheaded() const
Tell if we are dealing with the rear end of a multiheaded engine.
uint16 num_vehicle
Number of vehicles.
static Direction ChangeDir(Direction d, DirDiff delta)
Change a direction by a given difference.
int8 x_offs
x offset for vehicle sprite
StationFacilityByte facilities
The facilities that this station has.
Sprite sequence for a vehicle part.
uint64 flags
stores which blocks on the airport are taken. was 16 bit earlier on, then 32
Called to determine if a specific colour map should be used for a vehicle instead of the default live...
static T min(const T a, const T b)
Returns the minimum of two values.
static bool IsCargoInClass(CargoID c, CargoClass cc)
Does cargo c have cargo class cc?
byte previous_pos
Previous desired position of the aircraft.
uint16 refit_cap
Capacity left over from before last refit.
Functions related to sound.
byte breakdowns_since_last_service
Counter for the amount of breakdowns.
uint16 reliability
Reliability.
Functions to cache sprites in memory.
uint32 StringID
Numeric value that represents a string, independent of the selected language.
Vehicle * First() const
Get the first vehicle of this vehicle chain.
Vehicle's pathfinder is lost.
bool Failed() const
Did this command fail?
byte tick_counter
Increased by one for each tick.
EffectVehicle * CreateEffectVehicleRel(const Vehicle *v, int x, int y, int z, EffectVehicleType type)
Create an effect vehicle above a particular vehicle.
byte colour2
Second colour, for vehicles with 2CC support.
UnitID curid
last ID returned; 0 if none
All ships have this type.
void InvalidateAutoreplaceWindow(EngineID e, GroupID id_g)
Rebuild the left autoreplace list if an engine is removed or added.
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.
bool PlayVehicleSound(const Vehicle *v, VehicleSoundEvent event)
Checks whether a NewGRF wants to play a different vehicle sound effect.
#define return_cmd_error(errcode)
Returns from a function with a specific StringID as error.
byte state
State of the airport.
int16 engine_renew_months
months before/after the maximum vehicle age a vehicle should be renewed
Base class for all pools.
bool engine_renew
is autorenew enabled
uint16 height
Height of the sprite.
static void NewEvent(CompanyID company, ScriptEvent *event)
Queue a new event for an AI.
#define DEBUG(name, level,...)
Output a line of debugging information.
'Train' is either a loco or a wagon.
static bool Chance16(const uint a, const uint b)
Flips a coin with given probability.
TileIndex old_tile
Current tile of the vehicle.
bool IsEngineCountable() const
Check if a vehicle is counted in num_engines in each company struct.
byte breakdown_chance
Current chance of breakdowns.
The vehicle is in a drive-through road stop.
Livery livery
Custom colour scheme for vehicles in this group.
#define INSTANTIATE_POOL_METHODS(name)
Force instantiation of pool methods so we don't get linker errors.
int left
Screen coordinate left egde of the viewport.
void DeleteWindowById(WindowClass cls, WindowNumber number, bool force)
Delete a window by its class and window number (if it is open).
union Vehicle::@47 orders
The orders currently assigned to the vehicle.
VehicleEnterTileStatus VehicleEnterTile(Vehicle *v, TileIndex tile, int x, int y)
Call the tile callback function for a vehicle entering a tile.
static void UpdateProfits()
Recompute the profits for all groups.
void RemoveFromShared()
Removes the vehicle from the shared order list.
void AddVehicle(Vehicle *v)
Adds the given vehicle to this shared order list.
execute the given command
UnitID max_ships
max ships in game per company
Flag to disable visual effect.
static const EngineID INVALID_ENGINE
Constant denoting an invalid engine.
bool vehicle_income_warn
if a vehicle isn't generating income, show a warning
static const GroupID DEFAULT_GROUP
Ungrouped vehicles are in this group.
The vehicle will leave the depot right after arrival (serivce only)
uint16 width
Width of the sprite.
Functions related to companies.
Called for every vehicle every 32 days (not all on same date though).
RailType GetTileRailType(TileIndex tile)
Return the rail type of tile, or INVALID_RAILTYPE if this is no rail tile.
GetNewVehiclePosResult GetNewVehiclePos(const Vehicle *v)
Get position information of a vehicle when moving one pixel in the direction it is facing...
void UpdatePosition()
Update the position of the vehicle.
static StationID GetStationIndex(TileIndex t)
Get StationID from a tile.
static TileIndex TileVirtXY(uint x, uint y)
Get a tile from the virtual XY-coordinate.
GRFConfig * GetGRFConfig(uint32 grfid, uint32 mask)
Retrieve a NewGRF from the current config by its grfid.
static const PaletteID PALETTE_RECOLOUR_START
First recolour sprite for company colours.
Functions related to articulated vehicles.
void ErrorUnknownCallbackResult(uint32 grfid, uint16 cbid, uint16 cb_res)
Record that a NewGRF returned an unknown/invalid callback result.
Header file for NewGRF stations.
static T ClrBit(T &x, const uint8 y)
Clears a bit in a variable.
bool IsGroundVehicle() const
Check if the vehicle is a ground vehicle.
GUISettings gui
settings related to the GUI
const GRFFile * GetGRF() const
Retrieve the NewGRF the engine is tied to.
DestinationID GetDestination() const
Gets the destination of this order.
bool NeedsAutorenewing(const Company *c, bool use_renew_setting=true) const
Function to tell if a vehicle needs to be autorenewed.
void VehicleServiceInDepot(Vehicle *v)
Service a vehicle and all subsequent vehicles in the consist.
GroupID parent
Parent group.
void SetWindowWidgetDirty(WindowClass cls, WindowNumber number, byte widget_index)
Mark a particular widget in a particular window as dirty (in need of repainting)
CargoList that is used for vehicles.
Time spent processing ships.
bool HandleBreakdown()
Handle all of the aspects of a vehicle breakdown This includes adding smoke and sounds, and ending the breakdown when appropriate.
static void ClearVehicle(const Vehicle *v)
Clear/update the (clone) vehicle from an order backup.
Data structure for viewport, display of a part of the world.
static const int MAX_VEHICLE_PIXEL_X
Maximum width of a vehicle in pixels in #ZOOM_LVL_BASE.
Used for vehicle var 0xFE bit 8 (toggled each time the train is reversed, accurate for first vehicle ...
uint16 EngineID
Unique identification number of an engine.
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo ID.
CompanyByte _current_company
Company currently doing an action.
Number of bits used for the effect type.
static Vehicle * EnsureNoVehicleProcZ(Vehicle *v, void *data)
Callback that returns 'real' vehicles lower or at height *(int*)data .
Ships list; Window numbers:
uint32 TileIndex
The index/ID of a Tile.
static const PaletteID PALETTE_CRASH
Recolour sprite greying of crashed vehicles.
static Vehicle * GetVehicleTunnelBridgeProc(Vehicle *v, void *data)
Procedure called for every vehicle found in tunnel/bridge in the hash map.
uint32 Pack() const
Pack a VehicleListIdentifier in a single uint32.
void DeleteGroupHighlightOfVehicle(const Vehicle *v)
Removes the highlight of a vehicle in a group window.
Functions related to depots.
void BeginLoading()
Prepare everything to begin the loading when arriving at a station.
Vehicle * Next() const
Get the next vehicle of this vehicle.
Date date_of_last_service
Last date the vehicle had a service at a depot.
void InsertOrder(Vehicle *v, Order *new_o, VehicleOrderID sel_ord)
Insert a new order but skip the validation.
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.
Position information of a vehicle after it moved.
OrderSettings order
settings related to orders
void GetVehicleSet(VehicleSet &set, Vehicle *v, uint8 num_vehicles)
Calculates the set of vehicles that will be affected by a given selection.
void FindVehicleOnPosXY(int x, int y, void *data, VehicleFromPosProc *proc)
Find a vehicle from a specific location.
static const int MAX_VEHICLE_PIXEL_Y
Maximum height of a vehicle in pixels in #ZOOM_LVL_BASE.
Send the vehicle to the nearest depot.
static uint TileY(TileIndex tile)
Get the Y component of a tile.
static Vehicle * VehicleFromPosXY(int x, int y, void *data, VehicleFromPosProc *proc, bool find_first)
Helper function for FindVehicleOnPos/HasVehicleOnPos.
uint64 block
64 bit blocks (st->airport.flags), should be enough for the most complex airports ...
Powered wagon changed poweredness state when not inside a depot.
OwnerByte owner
Which company owns the vehicle?
UnitID NextID()
Returns next free UnitID.
SigSegState UpdateSignalsOnSegment(TileIndex tile, DiagDirection side, Owner owner)
Update signals, starting at one side of a tile Will check tile next to this at opposite side too...
static T abs(const T a)
Returns the absolute value of (scalar) variable.
TileIndex xy
Base tile of the station.
void GetArticulatedRefitMasks(EngineID engine, bool include_initial_cargo_type, CargoTypes *union_mask, CargoTypes *intersection_mask)
Merges the refit_masks of all articulated parts.
static void UpdateAutoreplace(CompanyID company)
Update autoreplace_defined and autoreplace_finished of all statistics of a company.
static uint GB(const T x, const uint8 s, const uint8 n)
Fetch n bits from x, started at bit s.
bool GamelogGRFBugReverse(uint32 grfid, uint16 internal_id)
Logs GRF bug - rail vehicle has different length after reversing.
Trains list; Window numbers:
Functions related to zooming.
Full load all cargoes of the consist.
void AgeCargo()
Ages the all cargo in this list.
Vehicle * next
pointer to the next vehicle in the chain
void SubtractMoneyFromCompany(CommandCost cost)
Subtract money from the _current_company, if the company is valid.
void DeleteUnreachedImplicitOrders()
Delete all implicit orders which were not reached.
void ReleaseDisastersTargetingVehicle(VehicleID vehicle)
Notify disasters that we are about to delete a vehicle.
const TileTypeProcs *const _tile_type_procs[16]
Tile callback functions for each type of tile.
Invalid transparency option.
SmallMap< Vehicle *, bool, 4 > AutoreplaceMap
List of vehicles that should check for autoreplace this tick.
Vehicle * previous_shared
NOSAVE: pointer to the previous vehicle in the shared order chain.
Reverse the visible direction of the vehicle.
bool show_track_reservation
highlight reserved tracks.
uint16 _returned_mail_refit_capacity
Stores the mail capacity after a refit operation (Aircraft only).
#define MAX_DAY
The number of days till the last day.
int16 x_offs
Number of pixels to shift the sprite to the right.
Station with train station.
Totally no unloading will be done.
static bool CanAllocateItem(size_t n=1)
Helper functions so we can use PoolItem::Function() instead of _poolitem_pool.Function() ...
Vehicle * CheckClickOnVehicle(const ViewPort *vp, int x, int y)
Find the vehicle close to the clicked coordinates.
virtual void OnNewDay()
Calls the new day handler of the vehicle.
bool HasEngineType() const
Check whether Vehicle::engine_type has any meaning.
Default value to indicate that visual effect should be based on engine class.
Aircraft list; Window numbers:
uint16 & GetGroundVehicleFlags()
Access the ground vehicle flags of the vehicle.
Vehicle details; Window numbers:
Functions/definitions that have something to do with groups.
Functions related to commands.
static bool IsValidID(size_t index)
Tests whether given index is a valid index for station of this type.
byte in_use
Bit 0 set if this livery should override the default livery first colour, Bit 1 for the second colour...
Coordinates of a point in 2D.
Vehicle * previous
NOSAVE: pointer to the previous vehicle in the chain.
uint8 CalcPercentVehicleFilled(const Vehicle *front, StringID *colour)
Calculates how full a vehicle is.
static bool IsValidID(size_t index)
Tests whether given index can be used to get valid (non-NULL) Titem.
uint16 local_id
id defined by the grf file for this entity
static void CountEngine(const Vehicle *v, int delta)
Update num_engines when adding/removing an engine.
uint32 GetGRFID() const
Retrieve the GRF ID of the NewGRF the vehicle is tied to.
uint16 UnitID
Type for the company global vehicle unit number.
Base classes related to the economy.
static WindowClass GetWindowClassForVehicleType(VehicleType vt)
Get WindowClass for vehicle list of given vehicle type.
void GetConsistFreeCapacities(SmallMap< CargoID, uint > &capacities) const
Get a map of cargoes and free capacities in the consist.
Load the cargo from the station.
void KeepAll()
Marks all cargo in the vehicle as to be kept.
UnitID max_trains
max trains in game per company
Declaration of link graph classes used for cargo distribution.
bool * cache
array of occupied unit id numbers
EffectVehicleType
Effect vehicle types.
Order * GetOrder(int index) const
Returns order 'index' of a vehicle or NULL when it doesn't exists.
static const StringID INVALID_STRING_ID
Constant representing an invalid string (16bit in case it is used in savegames)
CommandCost SendToDepot(DoCommandFlag flags, DepotCommand command)
Send this vehicle to the depot using the given command(s).
uint16 GetVehicleCallback(CallbackID callback, uint32 param1, uint32 param2, EngineID engine, const Vehicle *v)
Evaluate a newgrf callback for vehicles.
const char * GetName() const
Get the name of this grf.
uint8 cached_veh_length
Length of this vehicle in units of 1/VEHICLE_LENGTH of normal length. It is cached because this can b...
static bool IsTunnelTile(TileIndex t)
Is this a tunnel (entrance)?
Airport airport
Tile area the airport covers.
byte y_extent
y-extent of vehicle bounding box
Flag to disable wagon power.
EngineID engine_type
The type of engine used for this vehicle.
byte liveries
options for displaying company liveries, 0=none, 1=self, 2=all
const struct GRFFile * grffile
grf file that introduced this entity
ZoomLevel zoom
The zoom level of the viewport.
byte cached_vis_effect
Visual effect to show (see VisualEffect)
bool disable_unsuitable_building
disable infrastructure building when no suitable vehicles are available
virtual bool Tick()
Calls the tick handler of the vehicle.
uint16 vehicle_flags
Used for gradual loading and other miscellaneous things (.
static bool HasBit(const T x, const uint8 y)
Checks if a bit in a value is set.
Functions related to NewGRF provided sounds.
void Restore()
Restore the variable.
Base functions for all AIs.
#define FOR_ALL_VEHICLES(var)
Iterate over all vehicles.
Map accessors for tunnels.
const GRFFile * GetGRF() const
Retrieve the NewGRF the vehicle is tied to.
byte colour1
First colour, for all vehicles.
int virtual_top
Virtual top coordinate.
GameCreationSettings game_creation
settings used during the creation of a game (map)
Smoke of broken aircraft.
static void VehicleReachedProfitAge(const Vehicle *v)
Add a vehicle to the profit sum of its group.
Specification of a rectangle with absolute coordinates of all edges.
byte CargoID
Cargo slots to indicate a cargo type within a game.
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...
Road vehicle is a tram/light rail vehicle.
Owner
Enum for all companies/owners.
Length of rail vehicle changes when not inside a depot.
Flag for advanced effects.
static bool IsDepotTile(TileIndex tile)
Is the given tile a tile with a depot on it?
int top
Screen coordinate top edge of the viewport.
void ShowCostOrIncomeAnimation(int x, int y, int z, Money cost)
Display animated income or costs on the map.
Vehicle(VehicleType type=VEH_INVALID)
Vehicle constructor.
VehicleEnterTileStatus
The returned bits of VehicleEnterTile.
One direction is the opposite of the other one.
SpriteID sprite
The 'real' sprite.
static const VehicleOrderID MAX_VEH_ORDER_ID
Last valid VehicleOrderID.
Money profit_this_year
Profit this year << 8, low 8 bits are fract.
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting)
This depot order is because of a regular order.
Functions related to news.
uint16 animation_state
State primarily used to change the graphics/behaviour.
Base classes/functions for stations.
VehicleCache vcache
Cache of often used vehicle values.
static Station * Get(size_t index)
Gets station with given index.
Date _date
Current date in days (day counter)
Number of bits used for the offset.
static Direction ReverseDir(Direction d)
Return the reverse of a direction.
Functions related to autoreplacing.
Company view; Window numbers:
Rect coord
NOSAVE: Graphical bounding box of the vehicle, i.e. what to redraw on moves.
TileIndex new_tile
Tile of the vehicle after moving.
Vehicle * first
NOSAVE: pointer to the first vehicle in the chain.
static bool IsCompanyBuildableVehicleType(VehicleType type)
Is the given vehicle type buildable by a company?
void DeleteNewGRFInspectWindow(GrfSpecFeature feature, uint index)
Delete inspect window for a given feature and index.
This depot order is because of the servicing limit.
VehicleOrderID cur_real_order_index
The index to the current real (non-implicit) order.
VehicleTypeByte type
Type of vehicle.
void HandleLoading(bool mode=false)
Handle the loading of the vehicle; when not it skips through dummy orders and does nothing in all oth...
Class for backupping variables and making sure they are restored later.
static const uint IMPLICIT_ORDER_ONLY_CAP
Maximum number of orders in implicit-only lists before we start searching harder for duplicates...
Functions related to effect vehicles.
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...
Time spent processing trains.
uint32 cached_weight
Total weight of the consist (valid only for the first engine).
Disable insertion and removal of automatic orders until the vehicle completes the real order...
byte day_counter
Increased by one for each day.
void DrawSprite(SpriteID img, PaletteID pal, int x, int y, const SubSprite *sub, ZoomLevel zoom)
Draw a sprite, not in a viewport.
static bool TracksOverlap(TrackBits bits)
Checks if the given tracks overlap, ie form a crossing.
Order current_order
The current order (+ status, like: loading)
void UpdatePositionAndViewport()
Update the position of the vehicle, and update the viewport.
static RoadStop * GetByTile(TileIndex tile, RoadStopType type)
Find a roadstop at given tile.
void UpdateVisualEffect(bool allow_power_change=true)
Update the cached visual effect.
GroupID group_id
Index of group Pool array.
void InvalidateWindowData(WindowClass cls, WindowNumber number, int data, bool gui_scope)
Mark window data of the window of a given class and specific window number as invalid (in need of re-...
static const int DAYS_IN_LEAP_YEAR
sometimes, you need one day more...
bool IsEngine() const
Check if a vehicle is an engine (can be first in a consist).
TransparencyOption
Transparency option bits: which position in _transparency_opt stands for which transparency.
GroundVehicleCache gcache
Cache of often calculated values.
Visual effects and wagon power (trains, road vehicles and ships)
CargoID GetRefitCargo() const
Get the cargo to to refit to.
Vehicle is not clickable by the user (shadow vehicles).
SpriteID colourmap
NOSAVE: cached colour mapping.
byte visual_effect
Bitstuffed NewGRF visual effect data.
static int GetTileMaxPixelZ(TileIndex tile)
Get top height of the tile.
Dynamic data of a loaded NewGRF.
Vehicle visual effect (steam, diesel smoke or electric spark) is shown.
static void SetDParam(uint n, uint64 v)
Set a string parameter v at index n in the global string parameter array.
void CancelReservation(StationID next, Station *st)
Return all reserved cargo packets to the station and reset all packets staged for transfer...
static void SetDepotReservation(TileIndex t, bool b)
Set the reservation state of the depot.
PaletteID pal
The palette (use PAL_NONE) if not needed)
int width
Screen width of the viewport.
static Station * GetIfValid(size_t index)
Returns station if the index is a valid index for this station type.