Update: Translations from eints
[openttd-github.git] / src / aircraft_cmd.cpp
blob44d76650a171b7df323a7e797f9f6cb3f3d990fc
1 /*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6 */
8 /**
9 * @file aircraft_cmd.cpp
10 * This file deals with aircraft and airport movements functionalities
13 #include "stdafx.h"
14 #include "aircraft.h"
15 #include "landscape.h"
16 #include "news_func.h"
17 #include "newgrf_engine.h"
18 #include "newgrf_sound.h"
19 #include "spritecache.h"
20 #include "error_func.h"
21 #include "strings_func.h"
22 #include "command_func.h"
23 #include "window_func.h"
24 #include "timer/timer_game_calendar.h"
25 #include "timer/timer_game_economy.h"
26 #include "vehicle_func.h"
27 #include "sound_func.h"
28 #include "cheat_type.h"
29 #include "company_base.h"
30 #include "ai/ai.hpp"
31 #include "game/game.hpp"
32 #include "company_func.h"
33 #include "effectvehicle_func.h"
34 #include "station_base.h"
35 #include "engine_base.h"
36 #include "core/random_func.hpp"
37 #include "core/backup_type.hpp"
38 #include "zoom_func.h"
39 #include "disaster_vehicle.h"
40 #include "newgrf_airporttiles.h"
41 #include "framerate_type.h"
42 #include "aircraft_cmd.h"
43 #include "vehicle_cmd.h"
45 #include "table/strings.h"
47 #include "safeguards.h"
49 void Aircraft::UpdateDeltaXY()
51 this->x_offs = -1;
52 this->y_offs = -1;
53 this->x_extent = 2;
54 this->y_extent = 2;
56 switch (this->subtype) {
57 default: NOT_REACHED();
59 case AIR_AIRCRAFT:
60 case AIR_HELICOPTER:
61 switch (this->state) {
62 default: break;
63 case ENDTAKEOFF:
64 case LANDING:
65 case HELILANDING:
66 case FLYING:
67 this->x_extent = 24;
68 this->y_extent = 24;
69 break;
71 this->z_extent = 5;
72 break;
74 case AIR_SHADOW:
75 this->z_extent = 1;
76 this->x_offs = 0;
77 this->y_offs = 0;
78 break;
80 case AIR_ROTOR:
81 this->z_extent = 1;
82 break;
86 static bool AirportMove(Aircraft *v, const AirportFTAClass *apc);
87 static bool AirportSetBlocks(Aircraft *v, const AirportFTA *current_pos, const AirportFTAClass *apc);
88 static bool AirportHasBlock(Aircraft *v, const AirportFTA *current_pos, const AirportFTAClass *apc);
89 static bool AirportFindFreeTerminal(Aircraft *v, const AirportFTAClass *apc);
90 static bool AirportFindFreeHelipad(Aircraft *v, const AirportFTAClass *apc);
91 static void CrashAirplane(Aircraft *v);
93 static const SpriteID _aircraft_sprite[] = {
94 0x0EB5, 0x0EBD, 0x0EC5, 0x0ECD,
95 0x0ED5, 0x0EDD, 0x0E9D, 0x0EA5,
96 0x0EAD, 0x0EE5, 0x0F05, 0x0F0D,
97 0x0F15, 0x0F1D, 0x0F25, 0x0F2D,
98 0x0EED, 0x0EF5, 0x0EFD, 0x0F35,
99 0x0E9D, 0x0EA5, 0x0EAD, 0x0EB5,
100 0x0EBD, 0x0EC5
103 template <>
104 bool IsValidImageIndex<VEH_AIRCRAFT>(uint8_t image_index)
106 return image_index < lengthof(_aircraft_sprite);
109 /** Helicopter rotor animation states */
110 enum HelicopterRotorStates {
111 HRS_ROTOR_STOPPED,
112 HRS_ROTOR_MOVING_1,
113 HRS_ROTOR_MOVING_2,
114 HRS_ROTOR_MOVING_3,
118 * Find the nearest hangar to v
119 * INVALID_STATION is returned, if the company does not have any suitable
120 * airports (like helipads only)
121 * @param v vehicle looking for a hangar
122 * @return the StationID if one is found, otherwise, INVALID_STATION
124 static StationID FindNearestHangar(const Aircraft *v)
126 uint best = 0;
127 StationID index = INVALID_STATION;
128 TileIndex vtile = TileVirtXY(v->x_pos, v->y_pos);
129 const AircraftVehicleInfo *avi = AircraftVehInfo(v->engine_type);
130 uint max_range = v->acache.cached_max_range_sqr;
132 /* Determine destinations where it's coming from and where it's heading to */
133 const Station *last_dest = nullptr;
134 const Station *next_dest = nullptr;
135 if (max_range != 0) {
136 if (v->current_order.IsType(OT_GOTO_STATION) ||
137 (v->current_order.IsType(OT_GOTO_DEPOT) && (v->current_order.GetDepotActionType() & ODATFB_NEAREST_DEPOT) == 0)) {
138 last_dest = Station::GetIfValid(v->last_station_visited);
139 next_dest = Station::GetIfValid(v->current_order.GetDestination());
140 } else {
141 last_dest = GetTargetAirportIfValid(v);
142 next_dest = Station::GetIfValid(v->GetNextStoppingStation().value);
146 for (const Station *st : Station::Iterate()) {
147 if (st->owner != v->owner || !(st->facilities & FACIL_AIRPORT) || !st->airport.HasHangar()) continue;
149 const AirportFTAClass *afc = st->airport.GetFTA();
151 /* don't crash the plane if we know it can't land at the airport */
152 if ((afc->flags & AirportFTAClass::SHORT_STRIP) && (avi->subtype & AIR_FAST) && !_cheats.no_jetcrash.value) continue;
154 /* the plane won't land at any helicopter station */
155 if (!(afc->flags & AirportFTAClass::AIRPLANES) && (avi->subtype & AIR_CTOL)) continue;
157 /* Check if our last and next destinations can be reached from the depot airport. */
158 if (max_range != 0) {
159 uint last_dist = (last_dest != nullptr && last_dest->airport.tile != INVALID_TILE) ? DistanceSquare(st->airport.tile, last_dest->airport.tile) : 0;
160 uint next_dist = (next_dest != nullptr && next_dest->airport.tile != INVALID_TILE) ? DistanceSquare(st->airport.tile, next_dest->airport.tile) : 0;
161 if (last_dist > max_range || next_dist > max_range) continue;
164 /* v->tile can't be used here, when aircraft is flying v->tile is set to 0 */
165 uint distance = DistanceSquare(vtile, st->airport.tile);
166 if (distance < best || index == INVALID_STATION) {
167 best = distance;
168 index = st->index;
171 return index;
174 void Aircraft::GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const
176 uint8_t spritenum = this->spritenum;
178 if (is_custom_sprite(spritenum)) {
179 GetCustomVehicleSprite(this, direction, image_type, result);
180 if (result->IsValid()) return;
182 spritenum = this->GetEngine()->original_image_index;
185 assert(IsValidImageIndex<VEH_AIRCRAFT>(spritenum));
186 result->Set(direction + _aircraft_sprite[spritenum]);
189 void GetRotorImage(const Aircraft *v, EngineImageType image_type, VehicleSpriteSeq *result)
191 assert(v->subtype == AIR_HELICOPTER);
193 const Aircraft *w = v->Next()->Next();
194 if (is_custom_sprite(v->spritenum)) {
195 GetCustomRotorSprite(v, image_type, result);
196 if (result->IsValid()) return;
199 /* Return standard rotor sprites if there are no custom sprites for this helicopter */
200 result->Set(SPR_ROTOR_STOPPED + w->state);
203 static void GetAircraftIcon(EngineID engine, EngineImageType image_type, VehicleSpriteSeq *result)
205 const Engine *e = Engine::Get(engine);
206 uint8_t spritenum = e->u.air.image_index;
208 if (is_custom_sprite(spritenum)) {
209 GetCustomVehicleIcon(engine, DIR_W, image_type, result);
210 if (result->IsValid()) return;
212 spritenum = e->original_image_index;
215 assert(IsValidImageIndex<VEH_AIRCRAFT>(spritenum));
216 result->Set(DIR_W + _aircraft_sprite[spritenum]);
219 void DrawAircraftEngine(int left, int right, int preferred_x, int y, EngineID engine, PaletteID pal, EngineImageType image_type)
221 VehicleSpriteSeq seq;
222 GetAircraftIcon(engine, image_type, &seq);
224 Rect rect;
225 seq.GetBounds(&rect);
226 preferred_x = Clamp(preferred_x,
227 left - UnScaleGUI(rect.left),
228 right - UnScaleGUI(rect.right));
230 seq.Draw(preferred_x, y, pal, pal == PALETTE_CRASH);
232 if (!(AircraftVehInfo(engine)->subtype & AIR_CTOL)) {
233 VehicleSpriteSeq rotor_seq;
234 GetCustomRotorIcon(engine, image_type, &rotor_seq);
235 if (!rotor_seq.IsValid()) rotor_seq.Set(SPR_ROTOR_STOPPED);
236 rotor_seq.Draw(preferred_x, y - ScaleSpriteTrad(5), PAL_NONE, false);
241 * Get the size of the sprite of an aircraft sprite heading west (used for lists).
242 * @param engine The engine to get the sprite from.
243 * @param[out] width The width of the sprite.
244 * @param[out] height The height of the sprite.
245 * @param[out] xoffs Number of pixels to shift the sprite to the right.
246 * @param[out] yoffs Number of pixels to shift the sprite downwards.
247 * @param image_type Context the sprite is used in.
249 void GetAircraftSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type)
251 VehicleSpriteSeq seq;
252 GetAircraftIcon(engine, image_type, &seq);
254 Rect rect;
255 seq.GetBounds(&rect);
257 width = UnScaleGUI(rect.Width());
258 height = UnScaleGUI(rect.Height());
259 xoffs = UnScaleGUI(rect.left);
260 yoffs = UnScaleGUI(rect.top);
264 * Build an aircraft.
265 * @param flags type of operation.
266 * @param tile tile of the depot where aircraft is built.
267 * @param e the engine to build.
268 * @param[out] ret the vehicle that has been built.
269 * @return the cost of this operation or an error.
271 CommandCost CmdBuildAircraft(DoCommandFlag flags, TileIndex tile, const Engine *e, Vehicle **ret)
273 const AircraftVehicleInfo *avi = &e->u.air;
274 const Station *st = Station::GetByTile(tile);
276 /* Prevent building aircraft types at places which can't handle them */
277 if (!CanVehicleUseStation(e->index, st)) return CMD_ERROR;
279 /* Make sure all aircraft end up in the first tile of the hangar. */
280 tile = st->airport.GetHangarTile(st->airport.GetHangarNum(tile));
282 if (flags & DC_EXEC) {
283 Aircraft *v = new Aircraft(); // aircraft
284 Aircraft *u = new Aircraft(); // shadow
285 *ret = v;
287 v->direction = DIR_SE;
289 v->owner = u->owner = _current_company;
291 v->tile = tile;
293 uint x = TileX(tile) * TILE_SIZE + 5;
294 uint y = TileY(tile) * TILE_SIZE + 3;
296 v->x_pos = u->x_pos = x;
297 v->y_pos = u->y_pos = y;
299 u->z_pos = GetSlopePixelZ(x, y);
300 v->z_pos = u->z_pos + 1;
302 v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL;
303 u->vehstatus = VS_HIDDEN | VS_UNCLICKABLE | VS_SHADOW;
305 v->spritenum = avi->image_index;
307 v->cargo_cap = avi->passenger_capacity;
308 v->refit_cap = 0;
309 u->refit_cap = 0;
311 v->cargo_type = e->GetDefaultCargoType();
312 assert(IsValidCargoID(v->cargo_type));
314 CargoID mail = GetCargoIDByLabel(CT_MAIL);
315 if (IsValidCargoID(mail)) {
316 u->cargo_type = mail;
317 u->cargo_cap = avi->mail_capacity;
320 v->name.clear();
321 v->last_station_visited = INVALID_STATION;
322 v->last_loading_station = INVALID_STATION;
324 v->acceleration = avi->acceleration;
325 v->engine_type = e->index;
326 u->engine_type = e->index;
328 v->subtype = (avi->subtype & AIR_CTOL ? AIR_AIRCRAFT : AIR_HELICOPTER);
329 v->UpdateDeltaXY();
331 u->subtype = AIR_SHADOW;
332 u->UpdateDeltaXY();
334 v->reliability = e->reliability;
335 v->reliability_spd_dec = e->reliability_spd_dec;
336 v->max_age = e->GetLifeLengthInDays();
338 v->pos = GetVehiclePosOnBuild(tile);
340 v->state = HANGAR;
341 v->previous_pos = v->pos;
342 v->targetairport = GetStationIndex(tile);
343 v->SetNext(u);
345 v->SetServiceInterval(Company::Get(_current_company)->settings.vehicle.servint_aircraft);
347 v->date_of_last_service = TimerGameEconomy::date;
348 v->date_of_last_service_newgrf = TimerGameCalendar::date;
349 v->build_year = u->build_year = TimerGameCalendar::year;
351 v->sprite_cache.sprite_seq.Set(SPR_IMG_QUERY);
352 u->sprite_cache.sprite_seq.Set(SPR_IMG_QUERY);
354 v->random_bits = Random();
355 u->random_bits = Random();
357 v->vehicle_flags = 0;
358 if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) SetBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE);
359 v->SetServiceIntervalIsPercent(Company::Get(_current_company)->settings.vehicle.servint_ispercent);
361 v->InvalidateNewGRFCacheOfChain();
363 v->cargo_cap = e->DetermineCapacity(v, &u->cargo_cap);
365 v->InvalidateNewGRFCacheOfChain();
367 UpdateAircraftCache(v, true);
369 v->UpdatePosition();
370 u->UpdatePosition();
372 /* Aircraft with 3 vehicles (chopper)? */
373 if (v->subtype == AIR_HELICOPTER) {
374 Aircraft *w = new Aircraft();
375 w->engine_type = e->index;
376 w->direction = DIR_N;
377 w->owner = _current_company;
378 w->x_pos = v->x_pos;
379 w->y_pos = v->y_pos;
380 w->z_pos = v->z_pos + ROTOR_Z_OFFSET;
381 w->vehstatus = VS_HIDDEN | VS_UNCLICKABLE;
382 w->spritenum = 0xFF;
383 w->subtype = AIR_ROTOR;
384 w->sprite_cache.sprite_seq.Set(SPR_ROTOR_STOPPED);
385 w->random_bits = Random();
386 /* Use rotor's air.state to store the rotor animation frame */
387 w->state = HRS_ROTOR_STOPPED;
388 w->UpdateDeltaXY();
390 u->SetNext(w);
391 w->UpdatePosition();
395 return CommandCost();
399 ClosestDepot Aircraft::FindClosestDepot()
401 const Station *st = GetTargetAirportIfValid(this);
402 /* If the station is not a valid airport or if it has no hangars */
403 if (st == nullptr || !CanVehicleUseStation(this, st) || !st->airport.HasHangar()) {
404 /* the aircraft has to search for a hangar on its own */
405 StationID station = FindNearestHangar(this);
407 if (station == INVALID_STATION) return ClosestDepot();
409 st = Station::Get(station);
412 return ClosestDepot(st->xy, st->index);
415 static void CheckIfAircraftNeedsService(Aircraft *v)
417 if (Company::Get(v->owner)->settings.vehicle.servint_aircraft == 0 || !v->NeedsAutomaticServicing()) return;
418 if (v->IsChainInDepot()) {
419 VehicleServiceInDepot(v);
420 return;
423 /* When we're parsing conditional orders and the like
424 * we don't want to consider going to a depot too. */
425 if (!v->current_order.IsType(OT_GOTO_DEPOT) && !v->current_order.IsType(OT_GOTO_STATION)) return;
427 const Station *st = Station::Get(v->current_order.GetDestination());
429 assert(st != nullptr);
431 /* only goto depot if the target airport has a depot */
432 if (st->airport.HasHangar() && CanVehicleUseStation(v, st)) {
433 v->current_order.MakeGoToDepot(st->index, ODTFB_SERVICE);
434 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
435 } else if (v->current_order.IsType(OT_GOTO_DEPOT)) {
436 v->current_order.MakeDummy();
437 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
441 Money Aircraft::GetRunningCost() const
443 const Engine *e = this->GetEngine();
444 uint cost_factor = GetVehicleProperty(this, PROP_AIRCRAFT_RUNNING_COST_FACTOR, e->u.air.running_cost);
445 return GetPrice(PR_RUNNING_AIRCRAFT, cost_factor, e->GetGRF());
448 /** Calendar day handler */
449 void Aircraft::OnNewCalendarDay()
451 if (!this->IsNormalAircraft()) return;
452 AgeVehicle(this);
455 /** Economy day handler */
456 void Aircraft::OnNewEconomyDay()
458 if (!this->IsNormalAircraft()) return;
459 EconomyAgeVehicle(this);
461 if ((++this->day_counter & 7) == 0) DecreaseVehicleValue(this);
463 CheckOrders(this);
465 CheckVehicleBreakdown(this);
466 CheckIfAircraftNeedsService(this);
468 if (this->running_ticks == 0) return;
470 CommandCost cost(EXPENSES_AIRCRAFT_RUN, this->GetRunningCost() * this->running_ticks / (CalendarTime::DAYS_IN_YEAR * Ticks::DAY_TICKS));
472 this->profit_this_year -= cost.GetCost();
473 this->running_ticks = 0;
475 SubtractMoneyFromCompanyFract(this->owner, cost);
477 SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
478 SetWindowClassesDirty(WC_AIRCRAFT_LIST);
481 static void HelicopterTickHandler(Aircraft *v)
483 Aircraft *u = v->Next()->Next();
485 if (u->vehstatus & VS_HIDDEN) return;
487 /* if true, helicopter rotors do not rotate. This should only be the case if a helicopter is
488 * loading/unloading at a terminal or stopped */
489 if (v->current_order.IsType(OT_LOADING) || (v->vehstatus & VS_STOPPED)) {
490 if (u->cur_speed != 0) {
491 u->cur_speed++;
492 if (u->cur_speed >= 0x80 && u->state == HRS_ROTOR_MOVING_3) {
493 u->cur_speed = 0;
496 } else {
497 if (u->cur_speed == 0) {
498 u->cur_speed = 0x70;
500 if (u->cur_speed >= 0x50) {
501 u->cur_speed--;
505 int tick = ++u->tick_counter;
506 int spd = u->cur_speed >> 4;
508 VehicleSpriteSeq seq;
509 if (spd == 0) {
510 u->state = HRS_ROTOR_STOPPED;
511 GetRotorImage(v, EIT_ON_MAP, &seq);
512 if (u->sprite_cache.sprite_seq == seq) return;
513 } else if (tick >= spd) {
514 u->tick_counter = 0;
515 u->state++;
516 if (u->state > HRS_ROTOR_MOVING_3) u->state = HRS_ROTOR_MOVING_1;
517 GetRotorImage(v, EIT_ON_MAP, &seq);
518 } else {
519 return;
522 u->sprite_cache.sprite_seq = seq;
524 u->UpdatePositionAndViewport();
528 * Set aircraft position.
529 * @param v Aircraft to position.
530 * @param x New X position.
531 * @param y New y position.
532 * @param z New z position.
534 void SetAircraftPosition(Aircraft *v, int x, int y, int z)
536 v->x_pos = x;
537 v->y_pos = y;
538 v->z_pos = z;
540 v->UpdatePosition();
541 v->UpdateViewport(true, false);
542 if (v->subtype == AIR_HELICOPTER) {
543 GetRotorImage(v, EIT_ON_MAP, &v->Next()->Next()->sprite_cache.sprite_seq);
546 Aircraft *u = v->Next();
548 int safe_x = Clamp(x, 0, Map::MaxX() * TILE_SIZE);
549 int safe_y = Clamp(y - 1, 0, Map::MaxY() * TILE_SIZE);
550 u->x_pos = x;
551 u->y_pos = y - ((v->z_pos - GetSlopePixelZ(safe_x, safe_y)) >> 3);
553 safe_y = Clamp(u->y_pos, 0, Map::MaxY() * TILE_SIZE);
554 u->z_pos = GetSlopePixelZ(safe_x, safe_y);
555 u->sprite_cache.sprite_seq.CopyWithoutPalette(v->sprite_cache.sprite_seq); // the shadow is never coloured
557 u->UpdatePositionAndViewport();
559 u = u->Next();
560 if (u != nullptr) {
561 u->x_pos = x;
562 u->y_pos = y;
563 u->z_pos = z + ROTOR_Z_OFFSET;
565 u->UpdatePositionAndViewport();
570 * Handle Aircraft specific tasks when an Aircraft enters a hangar
571 * @param *v Vehicle that enters the hangar
573 void HandleAircraftEnterHangar(Aircraft *v)
575 v->subspeed = 0;
576 v->progress = 0;
578 Aircraft *u = v->Next();
579 u->vehstatus |= VS_HIDDEN;
580 u = u->Next();
581 if (u != nullptr) {
582 u->vehstatus |= VS_HIDDEN;
583 u->cur_speed = 0;
586 SetAircraftPosition(v, v->x_pos, v->y_pos, v->z_pos);
589 static void PlayAircraftSound(const Vehicle *v)
591 if (!PlayVehicleSound(v, VSE_START)) {
592 SndPlayVehicleFx(AircraftVehInfo(v->engine_type)->sfx, v);
598 * Update cached values of an aircraft.
599 * Currently caches callback 36 max speed.
600 * @param v Vehicle
601 * @param update_range Update the aircraft range.
603 void UpdateAircraftCache(Aircraft *v, bool update_range)
605 uint max_speed = GetVehicleProperty(v, PROP_AIRCRAFT_SPEED, 0);
606 if (max_speed != 0) {
607 /* Convert from original units to km-ish/h */
608 max_speed = (max_speed * 128) / 10;
610 v->vcache.cached_max_speed = max_speed;
611 } else {
612 /* Use the default max speed of the vehicle. */
613 v->vcache.cached_max_speed = AircraftVehInfo(v->engine_type)->max_speed;
616 /* Update cargo aging period. */
617 v->vcache.cached_cargo_age_period = GetVehicleProperty(v, PROP_AIRCRAFT_CARGO_AGE_PERIOD, EngInfo(v->engine_type)->cargo_age_period);
618 Aircraft *u = v->Next(); // Shadow for mail
619 u->vcache.cached_cargo_age_period = GetVehicleProperty(u, PROP_AIRCRAFT_CARGO_AGE_PERIOD, EngInfo(u->engine_type)->cargo_age_period);
621 /* Update aircraft range. */
622 if (update_range) {
623 v->acache.cached_max_range = GetVehicleProperty(v, PROP_AIRCRAFT_RANGE, AircraftVehInfo(v->engine_type)->max_range);
624 /* Squared it now so we don't have to do it later all the time. */
625 v->acache.cached_max_range_sqr = v->acache.cached_max_range * v->acache.cached_max_range;
631 * Special velocities for aircraft
633 enum AircraftSpeedLimits {
634 SPEED_LIMIT_TAXI = 50, ///< Maximum speed of an aircraft while taxiing
635 SPEED_LIMIT_APPROACH = 230, ///< Maximum speed of an aircraft on finals
636 SPEED_LIMIT_BROKEN = 320, ///< Maximum speed of an aircraft that is broken
637 SPEED_LIMIT_HOLD = 425, ///< Maximum speed of an aircraft that flies the holding pattern
638 SPEED_LIMIT_NONE = 0xFFFF, ///< No environmental speed limit. Speed limit is type dependent
642 * Sets the new speed for an aircraft
643 * @param v The vehicle for which the speed should be obtained
644 * @param speed_limit The maximum speed the vehicle may have.
645 * @param hard_limit If true, the limit is directly enforced, otherwise the plane is slowed down gradually
646 * @return The number of position updates needed within the tick
648 static int UpdateAircraftSpeed(Aircraft *v, uint speed_limit = SPEED_LIMIT_NONE, bool hard_limit = true)
651 * 'acceleration' has the unit 3/8 mph/tick. This function is called twice per tick.
652 * So the speed amount we need to accelerate is:
653 * acceleration * 3 / 16 mph = acceleration * 3 / 16 * 16 / 10 km-ish/h
654 * = acceleration * 3 / 10 * 256 * (km-ish/h / 256)
655 * ~ acceleration * 77 (km-ish/h / 256)
657 uint spd = v->acceleration * 77;
658 uint8_t t;
660 /* Adjust speed limits by plane speed factor to prevent taxiing
661 * and take-off speeds being too low. */
662 speed_limit *= _settings_game.vehicle.plane_speed;
664 /* adjust speed for broken vehicles */
665 if (v->vehstatus & VS_AIRCRAFT_BROKEN) {
666 if (SPEED_LIMIT_BROKEN < speed_limit) hard_limit = false;
667 speed_limit = std::min<uint>(speed_limit, SPEED_LIMIT_BROKEN);
670 if (v->vcache.cached_max_speed < speed_limit) {
671 if (v->cur_speed < speed_limit) hard_limit = false;
672 speed_limit = v->vcache.cached_max_speed;
675 v->subspeed = (t = v->subspeed) + (uint8_t)spd;
677 /* Aircraft's current speed is used twice so that very fast planes are
678 * forced to slow down rapidly in the short distance needed. The magic
679 * value 16384 was determined to give similar results to the old speed/48
680 * method at slower speeds. This also results in less reduction at slow
681 * speeds to that aircraft do not get to taxi speed straight after
682 * touchdown. */
683 if (!hard_limit && v->cur_speed > speed_limit) {
684 speed_limit = v->cur_speed - std::max(1, ((v->cur_speed * v->cur_speed) / 16384) / _settings_game.vehicle.plane_speed);
687 spd = std::min(v->cur_speed + (spd >> 8) + (v->subspeed < t), speed_limit);
689 /* updates statusbar only if speed have changed to save CPU time */
690 if (spd != v->cur_speed) {
691 v->cur_speed = spd;
692 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
695 /* Adjust distance moved by plane speed setting */
696 if (_settings_game.vehicle.plane_speed > 1) spd /= _settings_game.vehicle.plane_speed;
698 /* Convert direction-independent speed into direction-dependent speed. (old movement method) */
699 spd = v->GetOldAdvanceSpeed(spd);
701 spd += v->progress;
702 v->progress = (uint8_t)spd;
703 return spd >> 8;
707 * Get the tile height below the aircraft.
708 * This function is needed because aircraft can leave the mapborders.
710 * @param v The vehicle to get the height for.
711 * @return The height in pixels from 'z_pos' 0.
713 int GetTileHeightBelowAircraft(const Vehicle *v)
715 int safe_x = Clamp(v->x_pos, 0, Map::MaxX() * TILE_SIZE);
716 int safe_y = Clamp(v->y_pos, 0, Map::MaxY() * TILE_SIZE);
717 return TileHeight(TileVirtXY(safe_x, safe_y)) * TILE_HEIGHT;
721 * Get the 'flight level' bounds, in pixels from 'z_pos' 0 for a particular
722 * vehicle for normal flight situation.
723 * When the maximum is reached the vehicle should consider descending.
724 * When the minimum is reached the vehicle should consider ascending.
726 * @param v The vehicle to get the flight levels for.
727 * @param[out] min_level The minimum bounds for flight level.
728 * @param[out] max_level The maximum bounds for flight level.
730 void GetAircraftFlightLevelBounds(const Vehicle *v, int *min_level, int *max_level)
732 int base_altitude = GetTileHeightBelowAircraft(v);
733 if (v->type == VEH_AIRCRAFT && Aircraft::From(v)->subtype == AIR_HELICOPTER) {
734 base_altitude += HELICOPTER_HOLD_MAX_FLYING_ALTITUDE - PLANE_HOLD_MAX_FLYING_ALTITUDE;
737 /* Make sure eastbound and westbound planes do not "crash" into each
738 * other by providing them with vertical separation
740 switch (v->direction) {
741 case DIR_N:
742 case DIR_NE:
743 case DIR_E:
744 case DIR_SE:
745 base_altitude += 10;
746 break;
748 default: break;
751 /* Make faster planes fly higher so that they can overtake slower ones */
752 base_altitude += std::min(20 * (v->vcache.cached_max_speed / 200) - 90, 0);
754 if (min_level != nullptr) *min_level = base_altitude + AIRCRAFT_MIN_FLYING_ALTITUDE;
755 if (max_level != nullptr) *max_level = base_altitude + AIRCRAFT_MAX_FLYING_ALTITUDE;
759 * Gets the maximum 'flight level' for the holding pattern of the aircraft,
760 * in pixels 'z_pos' 0, depending on terrain below.
762 * @param v The aircraft that may or may not need to decrease its altitude.
763 * @return Maximal aircraft holding altitude, while in normal flight, in pixels.
765 int GetAircraftHoldMaxAltitude(const Aircraft *v)
767 int tile_height = GetTileHeightBelowAircraft(v);
769 return tile_height + ((v->subtype == AIR_HELICOPTER) ? HELICOPTER_HOLD_MAX_FLYING_ALTITUDE : PLANE_HOLD_MAX_FLYING_ALTITUDE);
772 template <class T>
773 int GetAircraftFlightLevel(T *v, bool takeoff)
775 /* Aircraft is in flight. We want to enforce it being somewhere
776 * between the minimum and the maximum allowed altitude. */
777 int aircraft_min_altitude;
778 int aircraft_max_altitude;
779 GetAircraftFlightLevelBounds(v, &aircraft_min_altitude, &aircraft_max_altitude);
780 int aircraft_middle_altitude = (aircraft_min_altitude + aircraft_max_altitude) / 2;
782 /* If those assumptions would be violated, aircraft would behave fairly strange. */
783 assert(aircraft_min_altitude < aircraft_middle_altitude);
784 assert(aircraft_middle_altitude < aircraft_max_altitude);
786 int z = v->z_pos;
787 if (z < aircraft_min_altitude ||
788 (HasBit(v->flags, VAF_IN_MIN_HEIGHT_CORRECTION) && z < aircraft_middle_altitude)) {
789 /* Ascend. And don't fly into that mountain right ahead.
790 * And avoid our aircraft become a stairclimber, so if we start
791 * correcting altitude, then we stop correction not too early. */
792 SetBit(v->flags, VAF_IN_MIN_HEIGHT_CORRECTION);
793 z += takeoff ? 2 : 1;
794 } else if (!takeoff && (z > aircraft_max_altitude ||
795 (HasBit(v->flags, VAF_IN_MAX_HEIGHT_CORRECTION) && z > aircraft_middle_altitude))) {
796 /* Descend lower. You are an aircraft, not an space ship.
797 * And again, don't stop correcting altitude too early. */
798 SetBit(v->flags, VAF_IN_MAX_HEIGHT_CORRECTION);
799 z--;
800 } else if (HasBit(v->flags, VAF_IN_MIN_HEIGHT_CORRECTION) && z >= aircraft_middle_altitude) {
801 /* Now, we have corrected altitude enough. */
802 ClrBit(v->flags, VAF_IN_MIN_HEIGHT_CORRECTION);
803 } else if (HasBit(v->flags, VAF_IN_MAX_HEIGHT_CORRECTION) && z <= aircraft_middle_altitude) {
804 /* Now, we have corrected altitude enough. */
805 ClrBit(v->flags, VAF_IN_MAX_HEIGHT_CORRECTION);
808 return z;
811 template int GetAircraftFlightLevel(DisasterVehicle *v, bool takeoff);
812 template int GetAircraftFlightLevel(Aircraft *v, bool takeoff);
815 * Find the entry point to an airport depending on direction which
816 * the airport is being approached from. Each airport can have up to
817 * four entry points for its approach system so that approaching
818 * aircraft do not fly through each other or are forced to do 180
819 * degree turns during the approach. The arrivals are grouped into
820 * four sectors dependent on the DiagDirection from which the airport
821 * is approached.
823 * @param v The vehicle that is approaching the airport
824 * @param apc The Airport Class being approached.
825 * @param rotation The rotation of the airport.
826 * @return The index of the entry point
828 static uint8_t AircraftGetEntryPoint(const Aircraft *v, const AirportFTAClass *apc, Direction rotation)
830 assert(v != nullptr);
831 assert(apc != nullptr);
833 /* In the case the station doesn't exit anymore, set target tile 0.
834 * It doesn't hurt much, aircraft will go to next order, nearest hangar
835 * or it will simply crash in next tick */
836 TileIndex tile = 0;
838 const Station *st = Station::GetIfValid(v->targetairport);
839 if (st != nullptr) {
840 /* Make sure we don't go to INVALID_TILE if the airport has been removed. */
841 tile = (st->airport.tile != INVALID_TILE) ? st->airport.tile : st->xy;
844 int delta_x = v->x_pos - TileX(tile) * TILE_SIZE;
845 int delta_y = v->y_pos - TileY(tile) * TILE_SIZE;
847 DiagDirection dir;
848 if (abs(delta_y) < abs(delta_x)) {
849 /* We are northeast or southwest of the airport */
850 dir = delta_x < 0 ? DIAGDIR_NE : DIAGDIR_SW;
851 } else {
852 /* We are northwest or southeast of the airport */
853 dir = delta_y < 0 ? DIAGDIR_NW : DIAGDIR_SE;
855 dir = ChangeDiagDir(dir, DiagDirDifference(DIAGDIR_NE, DirToDiagDir(rotation)));
856 return apc->entry_points[dir];
860 static void MaybeCrashAirplane(Aircraft *v);
863 * Controls the movement of an aircraft. This function actually moves the vehicle
864 * on the map and takes care of minor things like sound playback.
865 * @todo De-mystify the cur_speed values for helicopter rotors.
866 * @param v The vehicle that is moved. Must be the first vehicle of the chain
867 * @return Whether the position requested by the State Machine has been reached
869 static bool AircraftController(Aircraft *v)
871 /* nullptr if station is invalid */
872 const Station *st = Station::GetIfValid(v->targetairport);
873 /* INVALID_TILE if there is no station */
874 TileIndex tile = INVALID_TILE;
875 Direction rotation = DIR_N;
876 uint size_x = 1, size_y = 1;
877 if (st != nullptr) {
878 if (st->airport.tile != INVALID_TILE) {
879 tile = st->airport.tile;
880 rotation = st->airport.rotation;
881 size_x = st->airport.w;
882 size_y = st->airport.h;
883 } else {
884 tile = st->xy;
887 /* DUMMY if there is no station or no airport */
888 const AirportFTAClass *afc = tile == INVALID_TILE ? GetAirport(AT_DUMMY) : st->airport.GetFTA();
890 /* prevent going to INVALID_TILE if airport is deleted. */
891 if (st == nullptr || st->airport.tile == INVALID_TILE) {
892 /* Jump into our "holding pattern" state machine if possible */
893 if (v->pos >= afc->nofelements) {
894 v->pos = v->previous_pos = AircraftGetEntryPoint(v, afc, DIR_N);
895 } else if (v->targetairport != v->current_order.GetDestination()) {
896 /* If not possible, just get out of here fast */
897 v->state = FLYING;
898 UpdateAircraftCache(v);
899 AircraftNextAirportPos_and_Order(v);
900 /* get aircraft back on running altitude */
901 SetAircraftPosition(v, v->x_pos, v->y_pos, GetAircraftFlightLevel(v));
902 return false;
906 /* get airport moving data */
907 const AirportMovingData amd = RotateAirportMovingData(afc->MovingData(v->pos), rotation, size_x, size_y);
909 int x = TileX(tile) * TILE_SIZE;
910 int y = TileY(tile) * TILE_SIZE;
912 /* Helicopter raise */
913 if (amd.flag & AMED_HELI_RAISE) {
914 Aircraft *u = v->Next()->Next();
916 /* Make sure the rotors don't rotate too fast */
917 if (u->cur_speed > 32) {
918 v->cur_speed = 0;
919 if (--u->cur_speed == 32) {
920 if (!PlayVehicleSound(v, VSE_START)) {
921 SoundID sfx = AircraftVehInfo(v->engine_type)->sfx;
922 /* For compatibility with old NewGRF we ignore the sfx property, unless a NewGRF-defined sound is used.
923 * The baseset has only one helicopter sound, so this only limits using plane or cow sounds. */
924 if (sfx < ORIGINAL_SAMPLE_COUNT) sfx = SND_18_TAKEOFF_HELICOPTER;
925 SndPlayVehicleFx(sfx, v);
928 } else {
929 u->cur_speed = 32;
930 int count = UpdateAircraftSpeed(v);
931 if (count > 0) {
932 v->tile = 0;
934 int z_dest;
935 GetAircraftFlightLevelBounds(v, &z_dest, nullptr);
937 /* Reached altitude? */
938 if (v->z_pos >= z_dest) {
939 v->cur_speed = 0;
940 return true;
942 SetAircraftPosition(v, v->x_pos, v->y_pos, std::min(v->z_pos + count, z_dest));
945 return false;
948 /* Helicopter landing. */
949 if (amd.flag & AMED_HELI_LOWER) {
950 SetBit(v->flags, VAF_HELI_DIRECT_DESCENT);
952 if (st == nullptr) {
953 /* FIXME - AircraftController -> if station no longer exists, do not land
954 * helicopter will circle until sign disappears, then go to next order
955 * what to do when it is the only order left, right now it just stays in 1 place */
956 v->state = FLYING;
957 UpdateAircraftCache(v);
958 AircraftNextAirportPos_and_Order(v);
959 return false;
962 /* Vehicle is now at the airport.
963 * Helicopter has arrived at the target landing pad, so the current position is also where it should land.
964 * Except for Oilrigs which are special due to being a 1x1 station, and helicopters land outside it. */
965 if (st->airport.type != AT_OILRIG) {
966 x = v->x_pos;
967 y = v->y_pos;
968 tile = TileVirtXY(x, y);
970 v->tile = tile;
972 /* Find altitude of landing position. */
973 int z = GetSlopePixelZ(x, y) + 1 + afc->delta_z;
975 if (z == v->z_pos) {
976 Vehicle *u = v->Next()->Next();
978 /* Increase speed of rotors. When speed is 80, we've landed. */
979 if (u->cur_speed >= 80) {
980 ClrBit(v->flags, VAF_HELI_DIRECT_DESCENT);
981 return true;
983 u->cur_speed += 4;
984 } else {
985 int count = UpdateAircraftSpeed(v);
986 if (count > 0) {
987 if (v->z_pos > z) {
988 SetAircraftPosition(v, v->x_pos, v->y_pos, std::max(v->z_pos - count, z));
989 } else {
990 SetAircraftPosition(v, v->x_pos, v->y_pos, std::min(v->z_pos + count, z));
994 return false;
997 /* Get distance from destination pos to current pos. */
998 uint dist = abs(x + amd.x - v->x_pos) + abs(y + amd.y - v->y_pos);
1000 /* Need exact position? */
1001 if (!(amd.flag & AMED_EXACTPOS) && dist <= (amd.flag & AMED_SLOWTURN ? 8U : 4U)) return true;
1003 /* At final pos? */
1004 if (dist == 0) {
1005 /* Change direction smoothly to final direction. */
1006 DirDiff dirdiff = DirDifference(amd.direction, v->direction);
1007 /* if distance is 0, and plane points in right direction, no point in calling
1008 * UpdateAircraftSpeed(). So do it only afterwards */
1009 if (dirdiff == DIRDIFF_SAME) {
1010 v->cur_speed = 0;
1011 return true;
1014 if (!UpdateAircraftSpeed(v, SPEED_LIMIT_TAXI)) return false;
1016 v->direction = ChangeDir(v->direction, dirdiff > DIRDIFF_REVERSE ? DIRDIFF_45LEFT : DIRDIFF_45RIGHT);
1017 v->cur_speed >>= 1;
1019 SetAircraftPosition(v, v->x_pos, v->y_pos, v->z_pos);
1020 return false;
1023 if (amd.flag & AMED_BRAKE && v->cur_speed > SPEED_LIMIT_TAXI * _settings_game.vehicle.plane_speed) {
1024 MaybeCrashAirplane(v);
1025 if ((v->vehstatus & VS_CRASHED) != 0) return false;
1028 uint speed_limit = SPEED_LIMIT_TAXI;
1029 bool hard_limit = true;
1031 if (amd.flag & AMED_NOSPDCLAMP) speed_limit = SPEED_LIMIT_NONE;
1032 if (amd.flag & AMED_HOLD) { speed_limit = SPEED_LIMIT_HOLD; hard_limit = false; }
1033 if (amd.flag & AMED_LAND) { speed_limit = SPEED_LIMIT_APPROACH; hard_limit = false; }
1034 if (amd.flag & AMED_BRAKE) { speed_limit = SPEED_LIMIT_TAXI; hard_limit = false; }
1036 int count = UpdateAircraftSpeed(v, speed_limit, hard_limit);
1037 if (count == 0) return false;
1039 /* If the plane will be a few subpixels away from the destination after
1040 * this movement loop, start nudging it towards the exact position for
1041 * the whole loop. Otherwise, heavily depending on the speed of the plane,
1042 * it is possible we totally overshoot the target, causing the plane to
1043 * make a loop, and trying again, and again, and again .. */
1044 bool nudge_towards_target = static_cast<uint>(count) + 3 > dist;
1046 if (v->turn_counter != 0) v->turn_counter--;
1048 do {
1050 GetNewVehiclePosResult gp;
1052 if (nudge_towards_target || (amd.flag & AMED_LAND)) {
1053 /* move vehicle one pixel towards target */
1054 gp.x = (v->x_pos != (x + amd.x)) ?
1055 v->x_pos + ((x + amd.x > v->x_pos) ? 1 : -1) :
1056 v->x_pos;
1057 gp.y = (v->y_pos != (y + amd.y)) ?
1058 v->y_pos + ((y + amd.y > v->y_pos) ? 1 : -1) :
1059 v->y_pos;
1061 /* Oilrigs must keep v->tile as st->airport.tile, since the landing pad is in a non-airport tile */
1062 gp.new_tile = (st->airport.type == AT_OILRIG) ? st->airport.tile : TileVirtXY(gp.x, gp.y);
1064 } else {
1066 /* Turn. Do it slowly if in the air. */
1067 Direction newdir = GetDirectionTowards(v, x + amd.x, y + amd.y);
1068 if (newdir != v->direction) {
1069 if (amd.flag & AMED_SLOWTURN && v->number_consecutive_turns < 8 && v->subtype == AIR_AIRCRAFT) {
1070 if (v->turn_counter == 0 || newdir == v->last_direction) {
1071 if (newdir == v->last_direction) {
1072 v->number_consecutive_turns = 0;
1073 } else {
1074 v->number_consecutive_turns++;
1076 v->turn_counter = 2 * _settings_game.vehicle.plane_speed;
1077 v->last_direction = v->direction;
1078 v->direction = newdir;
1081 /* Move vehicle. */
1082 gp = GetNewVehiclePos(v);
1083 } else {
1084 v->cur_speed >>= 1;
1085 v->direction = newdir;
1087 /* When leaving a terminal an aircraft often goes to a position
1088 * directly in front of it. If it would move while turning it
1089 * would need an two extra turns to end up at the correct position.
1090 * To make it easier just disallow all moving while turning as
1091 * long as an aircraft is on the ground. */
1092 gp.x = v->x_pos;
1093 gp.y = v->y_pos;
1094 gp.new_tile = gp.old_tile = v->tile;
1096 } else {
1097 v->number_consecutive_turns = 0;
1098 /* Move vehicle. */
1099 gp = GetNewVehiclePos(v);
1103 v->tile = gp.new_tile;
1104 /* If vehicle is in the air, use tile coordinate 0. */
1105 if (amd.flag & (AMED_TAKEOFF | AMED_SLOWTURN | AMED_LAND)) v->tile = 0;
1107 /* Adjust Z for land or takeoff? */
1108 int z = v->z_pos;
1110 if (amd.flag & AMED_TAKEOFF) {
1111 z = GetAircraftFlightLevel(v, true);
1112 } else if (amd.flag & AMED_HOLD) {
1113 /* Let the plane drop from normal flight altitude to holding pattern altitude */
1114 if (z > GetAircraftHoldMaxAltitude(v)) z--;
1115 } else if ((amd.flag & AMED_SLOWTURN) && (amd.flag & AMED_NOSPDCLAMP)) {
1116 z = GetAircraftFlightLevel(v);
1119 /* NewGRF airports (like a rotated intercontinental from OpenGFX+Airports) can be non-rectangular
1120 * and their primary (north-most) tile does not have to be part of the airport.
1121 * As such, the height of the primary tile can be different from the rest of the airport.
1122 * Given we are landing/breaking, and as such are not a helicopter, we know that there has to be a hangar.
1123 * We also know that the airport itself has to be completely flat (otherwise it is not a valid airport).
1124 * Therefore, use the height of this hangar to calculate our z-value. */
1125 int airport_z = v->z_pos;
1126 if ((amd.flag & (AMED_LAND | AMED_BRAKE)) && st != nullptr) {
1127 assert(st->airport.HasHangar());
1128 TileIndex hangar_tile = st->airport.GetHangarTile(0);
1129 airport_z = GetTileMaxPixelZ(hangar_tile) + 1; // To avoid clashing with the shadow
1132 if (amd.flag & AMED_LAND) {
1133 if (st->airport.tile == INVALID_TILE) {
1134 /* Airport has been removed, abort the landing procedure */
1135 v->state = FLYING;
1136 UpdateAircraftCache(v);
1137 AircraftNextAirportPos_and_Order(v);
1138 /* get aircraft back on running altitude */
1139 SetAircraftPosition(v, gp.x, gp.y, GetAircraftFlightLevel(v));
1140 continue;
1143 /* We're not flying below our destination, right? */
1144 assert(airport_z <= z);
1145 int t = std::max(1U, dist - 4);
1146 int delta = z - airport_z;
1148 /* Only start lowering when we're sufficiently close for a 1:1 glide */
1149 if (delta >= t) {
1150 z -= CeilDiv(z - airport_z, t);
1152 if (z < airport_z) z = airport_z;
1155 /* We've landed. Decrease speed when we're reaching end of runway. */
1156 if (amd.flag & AMED_BRAKE) {
1158 if (z > airport_z) {
1159 z--;
1160 } else if (z < airport_z) {
1161 z++;
1166 SetAircraftPosition(v, gp.x, gp.y, z);
1167 } while (--count != 0);
1168 return false;
1172 * Handle crashed aircraft \a v.
1173 * @param v Crashed aircraft.
1175 static bool HandleCrashedAircraft(Aircraft *v)
1177 v->crashed_counter += 3;
1179 Station *st = GetTargetAirportIfValid(v);
1181 /* make aircraft crash down to the ground */
1182 if (v->crashed_counter < 500 && st == nullptr && ((v->crashed_counter % 3) == 0) ) {
1183 int z = GetSlopePixelZ(Clamp(v->x_pos, 0, Map::MaxX() * TILE_SIZE), Clamp(v->y_pos, 0, Map::MaxY() * TILE_SIZE));
1184 v->z_pos -= 1;
1185 if (v->z_pos <= z) {
1186 v->crashed_counter = 500;
1187 v->z_pos = z + 1;
1188 } else {
1189 v->crashed_counter = 0;
1191 SetAircraftPosition(v, v->x_pos, v->y_pos, v->z_pos);
1194 if (v->crashed_counter < 650) {
1195 uint32_t r;
1196 if (Chance16R(1, 32, r)) {
1197 static const DirDiff delta[] = {
1198 DIRDIFF_45LEFT, DIRDIFF_SAME, DIRDIFF_SAME, DIRDIFF_45RIGHT
1201 v->direction = ChangeDir(v->direction, delta[GB(r, 16, 2)]);
1202 SetAircraftPosition(v, v->x_pos, v->y_pos, v->z_pos);
1203 r = Random();
1204 CreateEffectVehicleRel(v,
1205 GB(r, 0, 4) - 4,
1206 GB(r, 4, 4) - 4,
1207 GB(r, 8, 4),
1208 EV_EXPLOSION_SMALL);
1210 } else if (v->crashed_counter >= 10000) {
1211 /* remove rubble of crashed airplane */
1213 /* clear runway-in on all airports, set by crashing plane
1214 * small airports use AIRPORT_BUSY, city airports use RUNWAY_IN_OUT_block, etc.
1215 * but they all share the same number */
1216 if (st != nullptr) {
1217 CLRBITS(st->airport.flags, RUNWAY_IN_block);
1218 CLRBITS(st->airport.flags, RUNWAY_IN_OUT_block); // commuter airport
1219 CLRBITS(st->airport.flags, RUNWAY_IN2_block); // intercontinental
1222 delete v;
1224 return false;
1227 return true;
1232 * Handle smoke of broken aircraft.
1233 * @param v Aircraft
1234 * @param mode Is this the non-first call for this vehicle in this tick?
1236 static void HandleAircraftSmoke(Aircraft *v, bool mode)
1238 static const struct {
1239 int8_t x;
1240 int8_t y;
1241 } smoke_pos[] = {
1242 { 5, 5 },
1243 { 6, 0 },
1244 { 5, -5 },
1245 { 0, -6 },
1246 { -5, -5 },
1247 { -6, 0 },
1248 { -5, 5 },
1249 { 0, 6 }
1252 if (!(v->vehstatus & VS_AIRCRAFT_BROKEN)) return;
1254 /* Stop smoking when landed */
1255 if (v->cur_speed < 10) {
1256 v->vehstatus &= ~VS_AIRCRAFT_BROKEN;
1257 v->breakdown_ctr = 0;
1258 return;
1261 /* Spawn effect et most once per Tick, i.e. !mode */
1262 if (!mode && (v->tick_counter & 0x0F) == 0) {
1263 CreateEffectVehicleRel(v,
1264 smoke_pos[v->direction].x,
1265 smoke_pos[v->direction].y,
1267 EV_BREAKDOWN_SMOKE_AIRCRAFT
1272 void HandleMissingAircraftOrders(Aircraft *v)
1275 * We do not have an order. This can be divided into two cases:
1276 * 1) we are heading to an invalid station. In this case we must
1277 * find another airport to go to. If there is nowhere to go,
1278 * we will destroy the aircraft as it otherwise will enter
1279 * the holding pattern for the first airport, which can cause
1280 * the plane to go into an undefined state when building an
1281 * airport with the same StationID.
1282 * 2) we are (still) heading to a (still) valid airport, then we
1283 * can continue going there. This can happen when you are
1284 * changing the aircraft's orders while in-flight or in for
1285 * example a depot. However, when we have a current order to
1286 * go to a depot, we have to keep that order so the aircraft
1287 * actually stops.
1289 const Station *st = GetTargetAirportIfValid(v);
1290 if (st == nullptr) {
1291 Backup<CompanyID> cur_company(_current_company, v->owner);
1292 CommandCost ret = Command<CMD_SEND_VEHICLE_TO_DEPOT>::Do(DC_EXEC, v->index, DepotCommand::None, {});
1293 cur_company.Restore();
1295 if (ret.Failed()) CrashAirplane(v);
1296 } else if (!v->current_order.IsType(OT_GOTO_DEPOT)) {
1297 v->current_order.Free();
1302 TileIndex Aircraft::GetOrderStationLocation(StationID)
1304 /* Orders are changed in flight, ensure going to the right station. */
1305 if (this->state == FLYING) {
1306 AircraftNextAirportPos_and_Order(this);
1309 /* Aircraft do not use dest-tile */
1310 return 0;
1313 void Aircraft::MarkDirty()
1315 this->colourmap = PAL_NONE;
1316 this->UpdateViewport(true, false);
1317 if (this->subtype == AIR_HELICOPTER) {
1318 GetRotorImage(this, EIT_ON_MAP, &this->Next()->Next()->sprite_cache.sprite_seq);
1323 uint Aircraft::Crash(bool flooded)
1325 uint victims = Vehicle::Crash(flooded) + 2; // pilots
1326 this->crashed_counter = flooded ? 9000 : 0; // max 10000, disappear pretty fast when flooded
1328 return victims;
1332 * Bring the aircraft in a crashed state, create the explosion animation, and create a news item about the crash.
1333 * @param v Aircraft that crashed.
1335 static void CrashAirplane(Aircraft *v)
1337 CreateEffectVehicleRel(v, 4, 4, 8, EV_EXPLOSION_LARGE);
1339 uint victims = v->Crash();
1340 SetDParam(0, victims);
1342 v->cargo.Truncate();
1343 v->Next()->cargo.Truncate();
1344 const Station *st = GetTargetAirportIfValid(v);
1345 StringID newsitem;
1346 TileIndex vt = TileVirtXY(v->x_pos, v->y_pos);
1347 if (st == nullptr) {
1348 newsitem = STR_NEWS_PLANE_CRASH_OUT_OF_FUEL;
1349 } else {
1350 SetDParam(1, st->index);
1351 newsitem = STR_NEWS_AIRCRAFT_CRASH;
1354 AI::NewEvent(v->owner, new ScriptEventVehicleCrashed(v->index, vt, st == nullptr ? ScriptEventVehicleCrashed::CRASH_AIRCRAFT_NO_AIRPORT : ScriptEventVehicleCrashed::CRASH_PLANE_LANDING, victims));
1355 Game::NewEvent(new ScriptEventVehicleCrashed(v->index, vt, st == nullptr ? ScriptEventVehicleCrashed::CRASH_AIRCRAFT_NO_AIRPORT : ScriptEventVehicleCrashed::CRASH_PLANE_LANDING, victims));
1357 NewsType newstype = NT_ACCIDENT;
1358 if (v->owner != _local_company) {
1359 newstype = NT_ACCIDENT_OTHER;
1362 AddTileNewsItem(newsitem, newstype, vt, nullptr, st != nullptr ? st->index : INVALID_STATION);
1364 ModifyStationRatingAround(vt, v->owner, -160, 30);
1365 if (_settings_client.sound.disaster) SndPlayVehicleFx(SND_12_EXPLOSION, v);
1369 * Decide whether aircraft \a v should crash.
1370 * @param v Aircraft to test.
1372 static void MaybeCrashAirplane(Aircraft *v)
1375 Station *st = Station::Get(v->targetairport);
1377 uint32_t prob;
1378 if ((st->airport.GetFTA()->flags & AirportFTAClass::SHORT_STRIP) &&
1379 (AircraftVehInfo(v->engine_type)->subtype & AIR_FAST) &&
1380 !_cheats.no_jetcrash.value) {
1381 prob = 3276;
1382 } else {
1383 if (_settings_game.vehicle.plane_crashes == 0) return;
1384 prob = (0x4000 << _settings_game.vehicle.plane_crashes) / 1500;
1387 if (GB(Random(), 0, 22) > prob) return;
1389 /* Crash the airplane. Remove all goods stored at the station. */
1390 for (GoodsEntry &ge : st->goods) {
1391 ge.rating = 1;
1392 ge.cargo.Truncate();
1395 CrashAirplane(v);
1399 * Aircraft arrives at a terminal. If it is the first aircraft, throw a party.
1400 * Start loading cargo.
1401 * @param v Aircraft that arrived.
1403 static void AircraftEntersTerminal(Aircraft *v)
1405 if (v->current_order.IsType(OT_GOTO_DEPOT)) return;
1407 Station *st = Station::Get(v->targetairport);
1408 v->last_station_visited = v->targetairport;
1410 /* Check if station was ever visited before */
1411 if (!(st->had_vehicle_of_type & HVOT_AIRCRAFT)) {
1412 st->had_vehicle_of_type |= HVOT_AIRCRAFT;
1413 SetDParam(0, st->index);
1414 /* show newsitem of celebrating citizens */
1415 AddVehicleNewsItem(
1416 STR_NEWS_FIRST_AIRCRAFT_ARRIVAL,
1417 (v->owner == _local_company) ? NT_ARRIVAL_COMPANY : NT_ARRIVAL_OTHER,
1418 v->index,
1419 st->index
1421 AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
1422 Game::NewEvent(new ScriptEventStationFirstVehicle(st->index, v->index));
1425 v->BeginLoading();
1429 * Aircraft touched down at the landing strip.
1430 * @param v Aircraft that landed.
1432 static void AircraftLandAirplane(Aircraft *v)
1434 Station *st = Station::Get(v->targetairport);
1436 TileIndex vt = TileVirtXY(v->x_pos, v->y_pos);
1438 v->UpdateDeltaXY();
1440 AirportTileAnimationTrigger(st, vt, AAT_STATION_AIRPLANE_LAND);
1442 if (!PlayVehicleSound(v, VSE_TOUCHDOWN)) {
1443 SndPlayVehicleFx(SND_17_SKID_PLANE, v);
1448 /** set the right pos when heading to other airports after takeoff */
1449 void AircraftNextAirportPos_and_Order(Aircraft *v)
1451 if (v->current_order.IsType(OT_GOTO_STATION) || v->current_order.IsType(OT_GOTO_DEPOT)) {
1452 v->targetairport = v->current_order.GetDestination();
1455 const Station *st = GetTargetAirportIfValid(v);
1456 const AirportFTAClass *apc = st == nullptr ? GetAirport(AT_DUMMY) : st->airport.GetFTA();
1457 Direction rotation = st == nullptr ? DIR_N : st->airport.rotation;
1458 v->pos = v->previous_pos = AircraftGetEntryPoint(v, apc, rotation);
1462 * Aircraft is about to leave the hangar.
1463 * @param v Aircraft leaving.
1464 * @param exit_dir The direction the vehicle leaves the hangar.
1465 * @note This function is called in AfterLoadGame for old savegames, so don't rely
1466 * on any data to be valid, especially don't rely on the fact that the vehicle
1467 * is actually on the ground inside a depot.
1469 void AircraftLeaveHangar(Aircraft *v, Direction exit_dir)
1471 v->cur_speed = 0;
1472 v->subspeed = 0;
1473 v->progress = 0;
1474 v->direction = exit_dir;
1475 v->vehstatus &= ~VS_HIDDEN;
1477 Vehicle *u = v->Next();
1478 u->vehstatus &= ~VS_HIDDEN;
1480 /* Rotor blades */
1481 u = u->Next();
1482 if (u != nullptr) {
1483 u->vehstatus &= ~VS_HIDDEN;
1484 u->cur_speed = 80;
1488 VehicleServiceInDepot(v);
1489 v->LeaveUnbunchingDepot();
1490 SetAircraftPosition(v, v->x_pos, v->y_pos, v->z_pos);
1491 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
1492 SetWindowClassesDirty(WC_AIRCRAFT_LIST);
1495 ////////////////////////////////////////////////////////////////////////////////
1496 /////////////////// AIRCRAFT MOVEMENT SCHEME ////////////////////////////////
1497 ////////////////////////////////////////////////////////////////////////////////
1498 static void AircraftEventHandler_EnterTerminal(Aircraft *v, const AirportFTAClass *apc)
1500 AircraftEntersTerminal(v);
1501 v->state = apc->layout[v->pos].heading;
1505 * Aircraft arrived in an airport hangar.
1506 * @param v Aircraft in the hangar.
1507 * @param apc Airport description containing the hangar.
1509 static void AircraftEventHandler_EnterHangar(Aircraft *v, const AirportFTAClass *apc)
1511 VehicleEnterDepot(v);
1512 v->state = apc->layout[v->pos].heading;
1516 * Handle aircraft movement/decision making in an airport hangar.
1517 * @param v Aircraft in the hangar.
1518 * @param apc Airport description containing the hangar.
1520 static void AircraftEventHandler_InHangar(Aircraft *v, const AirportFTAClass *apc)
1522 /* if we just arrived, execute EnterHangar first */
1523 if (v->previous_pos != v->pos) {
1524 AircraftEventHandler_EnterHangar(v, apc);
1525 return;
1528 /* if we were sent to the depot, stay there */
1529 if (v->current_order.IsType(OT_GOTO_DEPOT) && (v->vehstatus & VS_STOPPED)) {
1530 v->current_order.Free();
1531 return;
1534 /* Check if we should wait here for unbunching. */
1535 if (v->IsWaitingForUnbunching()) return;
1537 if (!v->current_order.IsType(OT_GOTO_STATION) &&
1538 !v->current_order.IsType(OT_GOTO_DEPOT))
1539 return;
1541 /* We are leaving a hangar, but have to go to the exact same one; re-enter */
1542 if (v->current_order.IsType(OT_GOTO_DEPOT) && v->current_order.GetDestination() == v->targetairport) {
1543 VehicleEnterDepot(v);
1544 return;
1547 /* if the block of the next position is busy, stay put */
1548 if (AirportHasBlock(v, &apc->layout[v->pos], apc)) return;
1550 /* We are already at the target airport, we need to find a terminal */
1551 if (v->current_order.GetDestination() == v->targetairport) {
1552 /* FindFreeTerminal:
1553 * 1. Find a free terminal, 2. Occupy it, 3. Set the vehicle's state to that terminal */
1554 if (v->subtype == AIR_HELICOPTER) {
1555 if (!AirportFindFreeHelipad(v, apc)) return; // helicopter
1556 } else {
1557 if (!AirportFindFreeTerminal(v, apc)) return; // airplane
1559 } else { // Else prepare for launch.
1560 /* airplane goto state takeoff, helicopter to helitakeoff */
1561 v->state = (v->subtype == AIR_HELICOPTER) ? HELITAKEOFF : TAKEOFF;
1563 const Station *st = Station::GetByTile(v->tile);
1564 AircraftLeaveHangar(v, st->airport.GetHangarExitDirection(v->tile));
1565 AirportMove(v, apc);
1568 /** At one of the Airport's Terminals */
1569 static void AircraftEventHandler_AtTerminal(Aircraft *v, const AirportFTAClass *apc)
1571 /* if we just arrived, execute EnterTerminal first */
1572 if (v->previous_pos != v->pos) {
1573 AircraftEventHandler_EnterTerminal(v, apc);
1574 /* on an airport with helipads, a helicopter will always land there
1575 * and get serviced at the same time - setting */
1576 if (_settings_game.order.serviceathelipad) {
1577 if (v->subtype == AIR_HELICOPTER && apc->num_helipads > 0) {
1578 /* an excerpt of ServiceAircraft, without the invisibility stuff */
1579 v->date_of_last_service = TimerGameEconomy::date;
1580 v->date_of_last_service_newgrf = TimerGameCalendar::date;
1581 v->breakdowns_since_last_service = 0;
1582 v->reliability = v->GetEngine()->reliability;
1583 SetWindowDirty(WC_VEHICLE_DETAILS, v->index);
1586 return;
1589 if (v->current_order.IsType(OT_NOTHING)) return;
1591 /* if the block of the next position is busy, stay put */
1592 if (AirportHasBlock(v, &apc->layout[v->pos], apc)) return;
1594 /* airport-road is free. We either have to go to another airport, or to the hangar
1595 * ---> start moving */
1597 bool go_to_hangar = false;
1598 switch (v->current_order.GetType()) {
1599 case OT_GOTO_STATION: // ready to fly to another airport
1600 break;
1601 case OT_GOTO_DEPOT: // visit hangar for servicing, sale, etc.
1602 go_to_hangar = v->current_order.GetDestination() == v->targetairport;
1603 break;
1604 case OT_CONDITIONAL:
1605 /* In case of a conditional order we just have to wait a tick
1606 * longer, so the conditional order can actually be processed;
1607 * we should not clear the order as that makes us go nowhere. */
1608 return;
1609 default: // orders have been deleted (no orders), goto depot and don't bother us
1610 v->current_order.Free();
1611 go_to_hangar = true;
1614 if (go_to_hangar && Station::Get(v->targetairport)->airport.HasHangar()) {
1615 v->state = HANGAR;
1616 } else {
1617 /* airplane goto state takeoff, helicopter to helitakeoff */
1618 v->state = (v->subtype == AIR_HELICOPTER) ? HELITAKEOFF : TAKEOFF;
1620 AirportMove(v, apc);
1623 static void AircraftEventHandler_General(Aircraft *, const AirportFTAClass *)
1625 FatalError("OK, you shouldn't be here, check your Airport Scheme!");
1628 static void AircraftEventHandler_TakeOff(Aircraft *v, const AirportFTAClass *)
1630 PlayAircraftSound(v); // play takeoffsound for airplanes
1631 v->state = STARTTAKEOFF;
1634 static void AircraftEventHandler_StartTakeOff(Aircraft *v, const AirportFTAClass *)
1636 v->state = ENDTAKEOFF;
1637 v->UpdateDeltaXY();
1640 static void AircraftEventHandler_EndTakeOff(Aircraft *v, const AirportFTAClass *)
1642 v->state = FLYING;
1643 /* get the next position to go to, differs per airport */
1644 AircraftNextAirportPos_and_Order(v);
1647 static void AircraftEventHandler_HeliTakeOff(Aircraft *v, const AirportFTAClass *)
1649 v->state = FLYING;
1650 v->UpdateDeltaXY();
1652 /* get the next position to go to, differs per airport */
1653 AircraftNextAirportPos_and_Order(v);
1655 /* Send the helicopter to a hangar if needed for replacement */
1656 if (v->NeedsAutomaticServicing()) {
1657 Backup<CompanyID> cur_company(_current_company, v->owner);
1658 Command<CMD_SEND_VEHICLE_TO_DEPOT>::Do(DC_EXEC, v->index, DepotCommand::Service | DepotCommand::LocateHangar, {});
1659 cur_company.Restore();
1663 static void AircraftEventHandler_Flying(Aircraft *v, const AirportFTAClass *apc)
1665 Station *st = Station::Get(v->targetairport);
1667 /* Runway busy, not allowed to use this airstation or closed, circle. */
1668 if (CanVehicleUseStation(v, st) && (st->owner == OWNER_NONE || st->owner == v->owner) && !(st->airport.flags & AIRPORT_CLOSED_block)) {
1669 /* {32,FLYING,NOTHING_block,37}, {32,LANDING,N,33}, {32,HELILANDING,N,41},
1670 * if it is an airplane, look for LANDING, for helicopter HELILANDING
1671 * it is possible to choose from multiple landing runways, so loop until a free one is found */
1672 uint8_t landingtype = (v->subtype == AIR_HELICOPTER) ? HELILANDING : LANDING;
1673 const AirportFTA *current = apc->layout[v->pos].next;
1674 while (current != nullptr) {
1675 if (current->heading == landingtype) {
1676 /* save speed before, since if AirportHasBlock is false, it resets them to 0
1677 * we don't want that for plane in air
1678 * hack for speed thingie */
1679 uint16_t tcur_speed = v->cur_speed;
1680 uint16_t tsubspeed = v->subspeed;
1681 if (!AirportHasBlock(v, current, apc)) {
1682 v->state = landingtype; // LANDING / HELILANDING
1683 if (v->state == HELILANDING) SetBit(v->flags, VAF_HELI_DIRECT_DESCENT);
1684 /* it's a bit dirty, but I need to set position to next position, otherwise
1685 * if there are multiple runways, plane won't know which one it took (because
1686 * they all have heading LANDING). And also occupy that block! */
1687 v->pos = current->next_position;
1688 SETBITS(st->airport.flags, apc->layout[v->pos].block);
1689 return;
1691 v->cur_speed = tcur_speed;
1692 v->subspeed = tsubspeed;
1694 current = current->next;
1697 v->state = FLYING;
1698 v->pos = apc->layout[v->pos].next_position;
1701 static void AircraftEventHandler_Landing(Aircraft *v, const AirportFTAClass *)
1703 v->state = ENDLANDING;
1704 AircraftLandAirplane(v); // maybe crash airplane
1706 /* check if the aircraft needs to be replaced or renewed and send it to a hangar if needed */
1707 if (v->NeedsAutomaticServicing()) {
1708 Backup<CompanyID> cur_company(_current_company, v->owner);
1709 Command<CMD_SEND_VEHICLE_TO_DEPOT>::Do(DC_EXEC, v->index, DepotCommand::Service, {});
1710 cur_company.Restore();
1714 static void AircraftEventHandler_HeliLanding(Aircraft *v, const AirportFTAClass *)
1716 v->state = HELIENDLANDING;
1717 v->UpdateDeltaXY();
1720 static void AircraftEventHandler_EndLanding(Aircraft *v, const AirportFTAClass *apc)
1722 /* next block busy, don't do a thing, just wait */
1723 if (AirportHasBlock(v, &apc->layout[v->pos], apc)) return;
1725 /* if going to terminal (OT_GOTO_STATION) choose one
1726 * 1. in case all terminals are busy AirportFindFreeTerminal() returns false or
1727 * 2. not going for terminal (but depot, no order),
1728 * --> get out of the way to the hangar. */
1729 if (v->current_order.IsType(OT_GOTO_STATION)) {
1730 if (AirportFindFreeTerminal(v, apc)) return;
1732 v->state = HANGAR;
1736 static void AircraftEventHandler_HeliEndLanding(Aircraft *v, const AirportFTAClass *apc)
1738 /* next block busy, don't do a thing, just wait */
1739 if (AirportHasBlock(v, &apc->layout[v->pos], apc)) return;
1741 /* if going to helipad (OT_GOTO_STATION) choose one. If airport doesn't have helipads, choose terminal
1742 * 1. in case all terminals/helipads are busy (AirportFindFreeHelipad() returns false) or
1743 * 2. not going for terminal (but depot, no order),
1744 * --> get out of the way to the hangar IF there are terminals on the airport.
1745 * --> else TAKEOFF
1746 * the reason behind this is that if an airport has a terminal, it also has a hangar. Airplanes
1747 * must go to a hangar. */
1748 if (v->current_order.IsType(OT_GOTO_STATION)) {
1749 if (AirportFindFreeHelipad(v, apc)) return;
1751 v->state = Station::Get(v->targetairport)->airport.HasHangar() ? HANGAR : HELITAKEOFF;
1755 * Signature of the aircraft handler function.
1756 * @param v Aircraft to handle.
1757 * @param apc Airport state machine.
1759 typedef void AircraftStateHandler(Aircraft *v, const AirportFTAClass *apc);
1760 /** Array of handler functions for each target of the aircraft. */
1761 static AircraftStateHandler * const _aircraft_state_handlers[] = {
1762 AircraftEventHandler_General, // TO_ALL = 0
1763 AircraftEventHandler_InHangar, // HANGAR = 1
1764 AircraftEventHandler_AtTerminal, // TERM1 = 2
1765 AircraftEventHandler_AtTerminal, // TERM2 = 3
1766 AircraftEventHandler_AtTerminal, // TERM3 = 4
1767 AircraftEventHandler_AtTerminal, // TERM4 = 5
1768 AircraftEventHandler_AtTerminal, // TERM5 = 6
1769 AircraftEventHandler_AtTerminal, // TERM6 = 7
1770 AircraftEventHandler_AtTerminal, // HELIPAD1 = 8
1771 AircraftEventHandler_AtTerminal, // HELIPAD2 = 9
1772 AircraftEventHandler_TakeOff, // TAKEOFF = 10
1773 AircraftEventHandler_StartTakeOff, // STARTTAKEOFF = 11
1774 AircraftEventHandler_EndTakeOff, // ENDTAKEOFF = 12
1775 AircraftEventHandler_HeliTakeOff, // HELITAKEOFF = 13
1776 AircraftEventHandler_Flying, // FLYING = 14
1777 AircraftEventHandler_Landing, // LANDING = 15
1778 AircraftEventHandler_EndLanding, // ENDLANDING = 16
1779 AircraftEventHandler_HeliLanding, // HELILANDING = 17
1780 AircraftEventHandler_HeliEndLanding, // HELIENDLANDING = 18
1781 AircraftEventHandler_AtTerminal, // TERM7 = 19
1782 AircraftEventHandler_AtTerminal, // TERM8 = 20
1783 AircraftEventHandler_AtTerminal, // HELIPAD3 = 21
1786 static void AirportClearBlock(const Aircraft *v, const AirportFTAClass *apc)
1788 /* we have left the previous block, and entered the new one. Free the previous block */
1789 if (apc->layout[v->previous_pos].block != apc->layout[v->pos].block) {
1790 Station *st = Station::Get(v->targetairport);
1792 CLRBITS(st->airport.flags, apc->layout[v->previous_pos].block);
1796 static void AirportGoToNextPosition(Aircraft *v)
1798 /* if aircraft is not in position, wait until it is */
1799 if (!AircraftController(v)) return;
1801 const AirportFTAClass *apc = Station::Get(v->targetairport)->airport.GetFTA();
1803 AirportClearBlock(v, apc);
1804 AirportMove(v, apc); // move aircraft to next position
1807 /* gets pos from vehicle and next orders */
1808 static bool AirportMove(Aircraft *v, const AirportFTAClass *apc)
1810 /* error handling */
1811 if (v->pos >= apc->nofelements) {
1812 Debug(misc, 0, "[Ap] position {} is not valid for current airport. Max position is {}", v->pos, apc->nofelements-1);
1813 assert(v->pos < apc->nofelements);
1816 const AirportFTA *current = &apc->layout[v->pos];
1817 /* we have arrived in an important state (eg terminal, hangar, etc.) */
1818 if (current->heading == v->state) {
1819 uint8_t prev_pos = v->pos; // location could be changed in state, so save it before-hand
1820 uint8_t prev_state = v->state;
1821 _aircraft_state_handlers[v->state](v, apc);
1822 if (v->state != FLYING) v->previous_pos = prev_pos;
1823 if (v->state != prev_state || v->pos != prev_pos) UpdateAircraftCache(v);
1824 return true;
1827 v->previous_pos = v->pos; // save previous location
1829 /* there is only one choice to move to */
1830 if (current->next == nullptr) {
1831 if (AirportSetBlocks(v, current, apc)) {
1832 v->pos = current->next_position;
1833 UpdateAircraftCache(v);
1834 } // move to next position
1835 return false;
1838 /* there are more choices to choose from, choose the one that
1839 * matches our heading */
1840 do {
1841 if (v->state == current->heading || current->heading == TO_ALL) {
1842 if (AirportSetBlocks(v, current, apc)) {
1843 v->pos = current->next_position;
1844 UpdateAircraftCache(v);
1845 } // move to next position
1846 return false;
1848 current = current->next;
1849 } while (current != nullptr);
1851 Debug(misc, 0, "[Ap] cannot move further on Airport! (pos {} state {}) for vehicle {}", v->pos, v->state, v->index);
1852 NOT_REACHED();
1855 /** returns true if the road ahead is busy, eg. you must wait before proceeding. */
1856 static bool AirportHasBlock(Aircraft *v, const AirportFTA *current_pos, const AirportFTAClass *apc)
1858 const AirportFTA *reference = &apc->layout[v->pos];
1859 const AirportFTA *next = &apc->layout[current_pos->next_position];
1861 /* same block, then of course we can move */
1862 if (apc->layout[current_pos->position].block != next->block) {
1863 const Station *st = Station::Get(v->targetairport);
1864 uint64_t airport_flags = next->block;
1866 /* check additional possible extra blocks */
1867 if (current_pos != reference && current_pos->block != NOTHING_block) {
1868 airport_flags |= current_pos->block;
1871 if (st->airport.flags & airport_flags) {
1872 v->cur_speed = 0;
1873 v->subspeed = 0;
1874 return true;
1877 return false;
1881 * "reserve" a block for the plane
1882 * @param v airplane that requires the operation
1883 * @param current_pos of the vehicle in the list of blocks
1884 * @param apc airport on which block is requested to be set
1885 * @returns true on success. Eg, next block was free and we have occupied it
1887 static bool AirportSetBlocks(Aircraft *v, const AirportFTA *current_pos, const AirportFTAClass *apc)
1889 const AirportFTA *next = &apc->layout[current_pos->next_position];
1890 const AirportFTA *reference = &apc->layout[v->pos];
1892 /* if the next position is in another block, check it and wait until it is free */
1893 if ((apc->layout[current_pos->position].block & next->block) != next->block) {
1894 uint64_t airport_flags = next->block;
1895 /* search for all all elements in the list with the same state, and blocks != N
1896 * this means more blocks should be checked/set */
1897 const AirportFTA *current = current_pos;
1898 if (current == reference) current = current->next;
1899 while (current != nullptr) {
1900 if (current->heading == current_pos->heading && current->block != 0) {
1901 airport_flags |= current->block;
1902 break;
1904 current = current->next;
1907 /* if the block to be checked is in the next position, then exclude that from
1908 * checking, because it has been set by the airplane before */
1909 if (current_pos->block == next->block) airport_flags ^= next->block;
1911 Station *st = Station::Get(v->targetairport);
1912 if (st->airport.flags & airport_flags) {
1913 v->cur_speed = 0;
1914 v->subspeed = 0;
1915 return false;
1918 if (next->block != NOTHING_block) {
1919 SETBITS(st->airport.flags, airport_flags); // occupy next block
1922 return true;
1926 * Combination of aircraft state for going to a certain terminal and the
1927 * airport flag for that terminal block.
1929 struct MovementTerminalMapping {
1930 AirportMovementStates state; ///< Aircraft movement state when going to this terminal.
1931 uint64_t airport_flag; ///< Bitmask in the airport flags that need to be free for this terminal.
1934 /** A list of all valid terminals and their associated blocks. */
1935 static const MovementTerminalMapping _airport_terminal_mapping[] = {
1936 {TERM1, TERM1_block},
1937 {TERM2, TERM2_block},
1938 {TERM3, TERM3_block},
1939 {TERM4, TERM4_block},
1940 {TERM5, TERM5_block},
1941 {TERM6, TERM6_block},
1942 {TERM7, TERM7_block},
1943 {TERM8, TERM8_block},
1944 {HELIPAD1, HELIPAD1_block},
1945 {HELIPAD2, HELIPAD2_block},
1946 {HELIPAD3, HELIPAD3_block},
1950 * Find a free terminal or helipad, and if available, assign it.
1951 * @param v Aircraft looking for a free terminal or helipad.
1952 * @param i First terminal to examine.
1953 * @param last_terminal Terminal number to stop examining.
1954 * @return A terminal or helipad has been found, and has been assigned to the aircraft.
1956 static bool FreeTerminal(Aircraft *v, uint8_t i, uint8_t last_terminal)
1958 assert(last_terminal <= lengthof(_airport_terminal_mapping));
1959 Station *st = Station::Get(v->targetairport);
1960 for (; i < last_terminal; i++) {
1961 if ((st->airport.flags & _airport_terminal_mapping[i].airport_flag) == 0) {
1962 /* TERMINAL# HELIPAD# */
1963 v->state = _airport_terminal_mapping[i].state; // start moving to that terminal/helipad
1964 SETBITS(st->airport.flags, _airport_terminal_mapping[i].airport_flag); // occupy terminal/helipad
1965 return true;
1968 return false;
1972 * Get the number of terminals at the airport.
1973 * @param apc Airport description.
1974 * @return Number of terminals.
1976 static uint GetNumTerminals(const AirportFTAClass *apc)
1978 uint num = 0;
1980 for (uint i = apc->terminals[0]; i > 0; i--) num += apc->terminals[i];
1982 return num;
1986 * Find a free terminal, and assign it if available.
1987 * @param v Aircraft to handle.
1988 * @param apc Airport state machine.
1989 * @return Found a free terminal and assigned it.
1991 static bool AirportFindFreeTerminal(Aircraft *v, const AirportFTAClass *apc)
1993 /* example of more terminalgroups
1994 * {0,HANGAR,NOTHING_block,1}, {0,TERMGROUP,TERM_GROUP1_block,0}, {0,TERMGROUP,TERM_GROUP2_ENTER_block,1}, {0,0,N,1},
1995 * Heading TERMGROUP denotes a group. We see 2 groups here:
1996 * 1. group 0 -- TERM_GROUP1_block (check block)
1997 * 2. group 1 -- TERM_GROUP2_ENTER_block (check block)
1998 * First in line is checked first, group 0. If the block (TERM_GROUP1_block) is free, it
1999 * looks at the corresponding terminals of that group. If no free ones are found, other
2000 * possible groups are checked (in this case group 1, since that is after group 0). If that
2001 * fails, then attempt fails and plane waits
2003 if (apc->terminals[0] > 1) {
2004 const Station *st = Station::Get(v->targetairport);
2005 const AirportFTA *temp = apc->layout[v->pos].next;
2007 while (temp != nullptr) {
2008 if (temp->heading == TERMGROUP) {
2009 if (!(st->airport.flags & temp->block)) {
2010 /* read which group do we want to go to?
2011 * (the first free group) */
2012 uint target_group = temp->next_position + 1;
2014 /* at what terminal does the group start?
2015 * that means, sum up all terminals of
2016 * groups with lower number */
2017 uint group_start = 0;
2018 for (uint i = 1; i < target_group; i++) {
2019 group_start += apc->terminals[i];
2022 uint group_end = group_start + apc->terminals[target_group];
2023 if (FreeTerminal(v, group_start, group_end)) return true;
2025 } else {
2026 /* once the heading isn't 255, we've exhausted the possible blocks.
2027 * So we cannot move */
2028 return false;
2030 temp = temp->next;
2034 /* if there is only 1 terminalgroup, all terminals are checked (starting from 0 to max) */
2035 return FreeTerminal(v, 0, GetNumTerminals(apc));
2039 * Find a free helipad, and assign it if available.
2040 * @param v Aircraft to handle.
2041 * @param apc Airport state machine.
2042 * @return Found a free helipad and assigned it.
2044 static bool AirportFindFreeHelipad(Aircraft *v, const AirportFTAClass *apc)
2046 /* if an airport doesn't have helipads, use terminals */
2047 if (apc->num_helipads == 0) return AirportFindFreeTerminal(v, apc);
2049 /* only 1 helicoptergroup, check all helipads
2050 * The blocks for helipads start after the last terminal (MAX_TERMINALS) */
2051 return FreeTerminal(v, MAX_TERMINALS, apc->num_helipads + MAX_TERMINALS);
2055 * Handle the 'dest too far' flag and the corresponding news message for aircraft.
2056 * @param v The aircraft.
2057 * @param too_far True if the current destination is too far away.
2059 static void AircraftHandleDestTooFar(Aircraft *v, bool too_far)
2061 if (too_far) {
2062 if (!HasBit(v->flags, VAF_DEST_TOO_FAR)) {
2063 SetBit(v->flags, VAF_DEST_TOO_FAR);
2064 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
2065 AI::NewEvent(v->owner, new ScriptEventAircraftDestTooFar(v->index));
2066 if (v->owner == _local_company) {
2067 /* Post a news message. */
2068 SetDParam(0, v->index);
2069 AddVehicleAdviceNewsItem(STR_NEWS_AIRCRAFT_DEST_TOO_FAR, v->index);
2072 return;
2075 if (HasBit(v->flags, VAF_DEST_TOO_FAR)) {
2076 /* Not too far anymore, clear flag and message. */
2077 ClrBit(v->flags, VAF_DEST_TOO_FAR);
2078 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
2079 DeleteVehicleNews(v->index, STR_NEWS_AIRCRAFT_DEST_TOO_FAR);
2083 static bool AircraftEventHandler(Aircraft *v, int loop)
2085 if (v->vehstatus & VS_CRASHED) {
2086 return HandleCrashedAircraft(v);
2089 if (v->vehstatus & VS_STOPPED) return true;
2091 v->HandleBreakdown();
2093 HandleAircraftSmoke(v, loop != 0);
2094 ProcessOrders(v);
2095 v->HandleLoading(loop != 0);
2097 if (v->current_order.IsType(OT_LOADING) || v->current_order.IsType(OT_LEAVESTATION)) return true;
2099 if (v->state >= ENDTAKEOFF && v->state <= HELIENDLANDING) {
2100 /* If we are flying, unconditionally clear the 'dest too far' state. */
2101 AircraftHandleDestTooFar(v, false);
2102 } else if (v->acache.cached_max_range_sqr != 0) {
2103 /* Check the distance to the next destination. This code works because the target
2104 * airport is only updated after take off and not on the ground. */
2105 Station *cur_st = Station::GetIfValid(v->targetairport);
2106 Station *next_st = v->current_order.IsType(OT_GOTO_STATION) || v->current_order.IsType(OT_GOTO_DEPOT) ? Station::GetIfValid(v->current_order.GetDestination()) : nullptr;
2108 if (cur_st != nullptr && cur_st->airport.tile != INVALID_TILE && next_st != nullptr && next_st->airport.tile != INVALID_TILE) {
2109 uint dist = DistanceSquare(cur_st->airport.tile, next_st->airport.tile);
2110 AircraftHandleDestTooFar(v, dist > v->acache.cached_max_range_sqr);
2114 if (!HasBit(v->flags, VAF_DEST_TOO_FAR)) AirportGoToNextPosition(v);
2116 return true;
2119 bool Aircraft::Tick()
2121 if (!this->IsNormalAircraft()) return true;
2123 PerformanceAccumulator framerate(PFE_GL_AIRCRAFT);
2125 this->tick_counter++;
2127 if (!(this->vehstatus & VS_STOPPED)) this->running_ticks++;
2129 if (this->subtype == AIR_HELICOPTER) HelicopterTickHandler(this);
2131 this->current_order_time++;
2133 for (uint i = 0; i != 2; i++) {
2134 /* stop if the aircraft was deleted */
2135 if (!AircraftEventHandler(this, i)) return false;
2138 return true;
2143 * Returns aircraft's target station if v->target_airport
2144 * is a valid station with airport.
2145 * @param v vehicle to get target airport for
2146 * @return pointer to target station, nullptr if invalid
2148 Station *GetTargetAirportIfValid(const Aircraft *v)
2150 assert(v->type == VEH_AIRCRAFT);
2152 Station *st = Station::GetIfValid(v->targetairport);
2153 if (st == nullptr) return nullptr;
2155 return st->airport.tile == INVALID_TILE ? nullptr : st;
2159 * Updates the status of the Aircraft heading or in the station
2160 * @param st Station been updated
2162 void UpdateAirplanesOnNewStation(const Station *st)
2164 /* only 1 station is updated per function call, so it is enough to get entry_point once */
2165 const AirportFTAClass *ap = st->airport.GetFTA();
2166 Direction rotation = st->airport.tile == INVALID_TILE ? DIR_N : st->airport.rotation;
2168 for (Aircraft *v : Aircraft::Iterate()) {
2169 if (!v->IsNormalAircraft() || v->targetairport != st->index) continue;
2170 assert(v->state == FLYING);
2172 Order *o = &v->current_order;
2173 /* The aircraft is heading to a hangar, but the new station doesn't have one,
2174 * or the aircraft can't land on the new station. Cancel current order. */
2175 if (o->IsType(OT_GOTO_DEPOT) && !(o->GetDepotOrderType() & ODTFB_PART_OF_ORDERS) && o->GetDestination() == st->index &&
2176 (!st->airport.HasHangar() || !CanVehicleUseStation(v, st))) {
2177 o->MakeDummy();
2178 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
2180 v->pos = v->previous_pos = AircraftGetEntryPoint(v, ap, rotation);
2181 UpdateAircraftCache(v);
2184 /* Heliports don't have a hangar. Invalidate all go to hangar orders from all aircraft. */
2185 if (!st->airport.HasHangar()) RemoveOrderFromAllVehicles(OT_GOTO_DEPOT, st->index, true);