Fix 03cc0d6: Mark level crossings dirty when removing road from them, not from bridge...
[openttd-github.git] / src / aircraft_cmd.cpp
blobd67969c0067bf9d8fd1a8648d2a514f5ce3bbb53
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 "strings_func.h"
21 #include "command_func.h"
22 #include "window_func.h"
23 #include "date_func.h"
24 #include "vehicle_func.h"
25 #include "sound_func.h"
26 #include "cheat_type.h"
27 #include "company_base.h"
28 #include "ai/ai.hpp"
29 #include "game/game.hpp"
30 #include "company_func.h"
31 #include "effectvehicle_func.h"
32 #include "station_base.h"
33 #include "engine_base.h"
34 #include "core/random_func.hpp"
35 #include "core/backup_type.hpp"
36 #include "zoom_func.h"
37 #include "disaster_vehicle.h"
38 #include "newgrf_airporttiles.h"
39 #include "framerate_type.h"
40 #include "aircraft_cmd.h"
41 #include "vehicle_cmd.h"
43 #include "table/strings.h"
45 #include "safeguards.h"
47 void Aircraft::UpdateDeltaXY()
49 this->x_offs = -1;
50 this->y_offs = -1;
51 this->x_extent = 2;
52 this->y_extent = 2;
54 switch (this->subtype) {
55 default: NOT_REACHED();
57 case AIR_AIRCRAFT:
58 case AIR_HELICOPTER:
59 switch (this->state) {
60 default: break;
61 case ENDTAKEOFF:
62 case LANDING:
63 case HELILANDING:
64 case FLYING:
65 this->x_extent = 24;
66 this->y_extent = 24;
67 break;
69 this->z_extent = 5;
70 break;
72 case AIR_SHADOW:
73 this->z_extent = 1;
74 this->x_offs = 0;
75 this->y_offs = 0;
76 break;
78 case AIR_ROTOR:
79 this->z_extent = 1;
80 break;
84 static bool AirportMove(Aircraft *v, const AirportFTAClass *apc);
85 static bool AirportSetBlocks(Aircraft *v, const AirportFTA *current_pos, const AirportFTAClass *apc);
86 static bool AirportHasBlock(Aircraft *v, const AirportFTA *current_pos, const AirportFTAClass *apc);
87 static bool AirportFindFreeTerminal(Aircraft *v, const AirportFTAClass *apc);
88 static bool AirportFindFreeHelipad(Aircraft *v, const AirportFTAClass *apc);
89 static void CrashAirplane(Aircraft *v);
91 static const SpriteID _aircraft_sprite[] = {
92 0x0EB5, 0x0EBD, 0x0EC5, 0x0ECD,
93 0x0ED5, 0x0EDD, 0x0E9D, 0x0EA5,
94 0x0EAD, 0x0EE5, 0x0F05, 0x0F0D,
95 0x0F15, 0x0F1D, 0x0F25, 0x0F2D,
96 0x0EED, 0x0EF5, 0x0EFD, 0x0F35,
97 0x0E9D, 0x0EA5, 0x0EAD, 0x0EB5,
98 0x0EBD, 0x0EC5
101 template <>
102 bool IsValidImageIndex<VEH_AIRCRAFT>(uint8 image_index)
104 return image_index < lengthof(_aircraft_sprite);
107 /** Helicopter rotor animation states */
108 enum HelicopterRotorStates {
109 HRS_ROTOR_STOPPED,
110 HRS_ROTOR_MOVING_1,
111 HRS_ROTOR_MOVING_2,
112 HRS_ROTOR_MOVING_3,
116 * Find the nearest hangar to v
117 * INVALID_STATION is returned, if the company does not have any suitable
118 * airports (like helipads only)
119 * @param v vehicle looking for a hangar
120 * @return the StationID if one is found, otherwise, INVALID_STATION
122 static StationID FindNearestHangar(const Aircraft *v)
124 uint best = 0;
125 StationID index = INVALID_STATION;
126 TileIndex vtile = TileVirtXY(v->x_pos, v->y_pos);
127 const AircraftVehicleInfo *avi = AircraftVehInfo(v->engine_type);
128 uint max_range = v->acache.cached_max_range_sqr;
130 /* Determine destinations where it's coming from and where it's heading to */
131 const Station *last_dest = nullptr;
132 const Station *next_dest = nullptr;
133 if (max_range != 0) {
134 if (v->current_order.IsType(OT_GOTO_STATION) ||
135 (v->current_order.IsType(OT_GOTO_DEPOT) && v->current_order.GetDepotActionType() != ODATFB_NEAREST_DEPOT)) {
136 last_dest = Station::GetIfValid(v->last_station_visited);
137 next_dest = Station::GetIfValid(v->current_order.GetDestination());
138 } else {
139 last_dest = GetTargetAirportIfValid(v);
140 next_dest = Station::GetIfValid(v->GetNextStoppingStation().value);
144 for (const Station *st : Station::Iterate()) {
145 if (st->owner != v->owner || !(st->facilities & FACIL_AIRPORT) || !st->airport.HasHangar()) continue;
147 const AirportFTAClass *afc = st->airport.GetFTA();
149 /* don't crash the plane if we know it can't land at the airport */
150 if ((afc->flags & AirportFTAClass::SHORT_STRIP) && (avi->subtype & AIR_FAST) && !_cheats.no_jetcrash.value) continue;
152 /* the plane won't land at any helicopter station */
153 if (!(afc->flags & AirportFTAClass::AIRPLANES) && (avi->subtype & AIR_CTOL)) continue;
155 /* Check if our last and next destinations can be reached from the depot airport. */
156 if (max_range != 0) {
157 uint last_dist = (last_dest != nullptr && last_dest->airport.tile != INVALID_TILE) ? DistanceSquare(st->airport.tile, last_dest->airport.tile) : 0;
158 uint next_dist = (next_dest != nullptr && next_dest->airport.tile != INVALID_TILE) ? DistanceSquare(st->airport.tile, next_dest->airport.tile) : 0;
159 if (last_dist > max_range || next_dist > max_range) continue;
162 /* v->tile can't be used here, when aircraft is flying v->tile is set to 0 */
163 uint distance = DistanceSquare(vtile, st->airport.tile);
164 if (distance < best || index == INVALID_STATION) {
165 best = distance;
166 index = st->index;
169 return index;
172 void Aircraft::GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const
174 uint8 spritenum = this->spritenum;
176 if (is_custom_sprite(spritenum)) {
177 GetCustomVehicleSprite(this, direction, image_type, result);
178 if (result->IsValid()) return;
180 spritenum = this->GetEngine()->original_image_index;
183 assert(IsValidImageIndex<VEH_AIRCRAFT>(spritenum));
184 result->Set(direction + _aircraft_sprite[spritenum]);
187 void GetRotorImage(const Aircraft *v, EngineImageType image_type, VehicleSpriteSeq *result)
189 assert(v->subtype == AIR_HELICOPTER);
191 const Aircraft *w = v->Next()->Next();
192 if (is_custom_sprite(v->spritenum)) {
193 GetCustomRotorSprite(v, image_type, result);
194 if (result->IsValid()) return;
197 /* Return standard rotor sprites if there are no custom sprites for this helicopter */
198 result->Set(SPR_ROTOR_STOPPED + w->state);
201 static void GetAircraftIcon(EngineID engine, EngineImageType image_type, VehicleSpriteSeq *result)
203 const Engine *e = Engine::Get(engine);
204 uint8 spritenum = e->u.air.image_index;
206 if (is_custom_sprite(spritenum)) {
207 GetCustomVehicleIcon(engine, DIR_W, image_type, result);
208 if (result->IsValid()) return;
210 spritenum = e->original_image_index;
213 assert(IsValidImageIndex<VEH_AIRCRAFT>(spritenum));
214 result->Set(DIR_W + _aircraft_sprite[spritenum]);
217 void DrawAircraftEngine(int left, int right, int preferred_x, int y, EngineID engine, PaletteID pal, EngineImageType image_type)
219 VehicleSpriteSeq seq;
220 GetAircraftIcon(engine, image_type, &seq);
222 Rect rect;
223 seq.GetBounds(&rect);
224 preferred_x = Clamp(preferred_x,
225 left - UnScaleGUI(rect.left),
226 right - UnScaleGUI(rect.right));
228 seq.Draw(preferred_x, y, pal, pal == PALETTE_CRASH);
230 if (!(AircraftVehInfo(engine)->subtype & AIR_CTOL)) {
231 VehicleSpriteSeq rotor_seq;
232 GetCustomRotorIcon(engine, image_type, &rotor_seq);
233 if (!rotor_seq.IsValid()) rotor_seq.Set(SPR_ROTOR_STOPPED);
234 rotor_seq.Draw(preferred_x, y - ScaleGUITrad(5), PAL_NONE, false);
239 * Get the size of the sprite of an aircraft sprite heading west (used for lists).
240 * @param engine The engine to get the sprite from.
241 * @param[out] width The width of the sprite.
242 * @param[out] height The height of the sprite.
243 * @param[out] xoffs Number of pixels to shift the sprite to the right.
244 * @param[out] yoffs Number of pixels to shift the sprite downwards.
245 * @param image_type Context the sprite is used in.
247 void GetAircraftSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type)
249 VehicleSpriteSeq seq;
250 GetAircraftIcon(engine, image_type, &seq);
252 Rect rect;
253 seq.GetBounds(&rect);
255 width = UnScaleGUI(rect.right - rect.left + 1);
256 height = UnScaleGUI(rect.bottom - rect.top + 1);
257 xoffs = UnScaleGUI(rect.left);
258 yoffs = UnScaleGUI(rect.top);
262 * Build an aircraft.
263 * @param flags type of operation.
264 * @param tile tile of the depot where aircraft is built.
265 * @param e the engine to build.
266 * @param[out] ret the vehicle that has been built.
267 * @return the cost of this operation or an error.
269 CommandCost CmdBuildAircraft(DoCommandFlag flags, TileIndex tile, const Engine *e, Vehicle **ret)
271 const AircraftVehicleInfo *avi = &e->u.air;
272 const Station *st = Station::GetByTile(tile);
274 /* Prevent building aircraft types at places which can't handle them */
275 if (!CanVehicleUseStation(e->index, st)) return CMD_ERROR;
277 /* Make sure all aircraft end up in the first tile of the hangar. */
278 tile = st->airport.GetHangarTile(st->airport.GetHangarNum(tile));
280 if (flags & DC_EXEC) {
281 Aircraft *v = new Aircraft(); // aircraft
282 Aircraft *u = new Aircraft(); // shadow
283 *ret = v;
285 v->direction = DIR_SE;
287 v->owner = u->owner = _current_company;
289 v->tile = tile;
291 uint x = TileX(tile) * TILE_SIZE + 5;
292 uint y = TileY(tile) * TILE_SIZE + 3;
294 v->x_pos = u->x_pos = x;
295 v->y_pos = u->y_pos = y;
297 u->z_pos = GetSlopePixelZ(x, y);
298 v->z_pos = u->z_pos + 1;
300 v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL;
301 u->vehstatus = VS_HIDDEN | VS_UNCLICKABLE | VS_SHADOW;
303 v->spritenum = avi->image_index;
305 v->cargo_cap = avi->passenger_capacity;
306 v->refit_cap = 0;
307 u->cargo_cap = avi->mail_capacity;
308 u->refit_cap = 0;
310 v->cargo_type = e->GetDefaultCargoType();
311 u->cargo_type = CT_MAIL;
313 v->name.clear();
314 v->last_station_visited = INVALID_STATION;
315 v->last_loading_station = INVALID_STATION;
317 v->acceleration = avi->acceleration;
318 v->engine_type = e->index;
319 u->engine_type = e->index;
321 v->subtype = (avi->subtype & AIR_CTOL ? AIR_AIRCRAFT : AIR_HELICOPTER);
322 v->UpdateDeltaXY();
324 u->subtype = AIR_SHADOW;
325 u->UpdateDeltaXY();
327 v->reliability = e->reliability;
328 v->reliability_spd_dec = e->reliability_spd_dec;
329 v->max_age = e->GetLifeLengthInDays();
331 v->pos = GetVehiclePosOnBuild(tile);
333 v->state = HANGAR;
334 v->previous_pos = v->pos;
335 v->targetairport = GetStationIndex(tile);
336 v->SetNext(u);
338 v->SetServiceInterval(Company::Get(_current_company)->settings.vehicle.servint_aircraft);
340 v->date_of_last_service = _date;
341 v->build_year = u->build_year = _cur_year;
343 v->sprite_cache.sprite_seq.Set(SPR_IMG_QUERY);
344 u->sprite_cache.sprite_seq.Set(SPR_IMG_QUERY);
346 v->random_bits = VehicleRandomBits();
347 u->random_bits = VehicleRandomBits();
349 v->vehicle_flags = 0;
350 if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) SetBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE);
351 v->SetServiceIntervalIsPercent(Company::Get(_current_company)->settings.vehicle.servint_ispercent);
353 v->InvalidateNewGRFCacheOfChain();
355 v->cargo_cap = e->DetermineCapacity(v, &u->cargo_cap);
357 v->InvalidateNewGRFCacheOfChain();
359 UpdateAircraftCache(v, true);
361 v->UpdatePosition();
362 u->UpdatePosition();
364 /* Aircraft with 3 vehicles (chopper)? */
365 if (v->subtype == AIR_HELICOPTER) {
366 Aircraft *w = new Aircraft();
367 w->engine_type = e->index;
368 w->direction = DIR_N;
369 w->owner = _current_company;
370 w->x_pos = v->x_pos;
371 w->y_pos = v->y_pos;
372 w->z_pos = v->z_pos + ROTOR_Z_OFFSET;
373 w->vehstatus = VS_HIDDEN | VS_UNCLICKABLE;
374 w->spritenum = 0xFF;
375 w->subtype = AIR_ROTOR;
376 w->sprite_cache.sprite_seq.Set(SPR_ROTOR_STOPPED);
377 w->random_bits = VehicleRandomBits();
378 /* Use rotor's air.state to store the rotor animation frame */
379 w->state = HRS_ROTOR_STOPPED;
380 w->UpdateDeltaXY();
382 u->SetNext(w);
383 w->UpdatePosition();
387 return CommandCost();
391 bool Aircraft::FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
393 const Station *st = GetTargetAirportIfValid(this);
394 /* If the station is not a valid airport or if it has no hangars */
395 if (st == nullptr || !CanVehicleUseStation(this, st) || !st->airport.HasHangar()) {
396 /* the aircraft has to search for a hangar on its own */
397 StationID station = FindNearestHangar(this);
399 if (station == INVALID_STATION) return false;
401 st = Station::Get(station);
404 if (location != nullptr) *location = st->xy;
405 if (destination != nullptr) *destination = st->index;
407 return true;
410 static void CheckIfAircraftNeedsService(Aircraft *v)
412 if (Company::Get(v->owner)->settings.vehicle.servint_aircraft == 0 || !v->NeedsAutomaticServicing()) return;
413 if (v->IsChainInDepot()) {
414 VehicleServiceInDepot(v);
415 return;
418 /* When we're parsing conditional orders and the like
419 * we don't want to consider going to a depot too. */
420 if (!v->current_order.IsType(OT_GOTO_DEPOT) && !v->current_order.IsType(OT_GOTO_STATION)) return;
422 const Station *st = Station::Get(v->current_order.GetDestination());
424 assert(st != nullptr);
426 /* only goto depot if the target airport has a depot */
427 if (st->airport.HasHangar() && CanVehicleUseStation(v, st)) {
428 v->current_order.MakeGoToDepot(st->index, ODTFB_SERVICE);
429 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
430 } else if (v->current_order.IsType(OT_GOTO_DEPOT)) {
431 v->current_order.MakeDummy();
432 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
436 Money Aircraft::GetRunningCost() const
438 const Engine *e = this->GetEngine();
439 uint cost_factor = GetVehicleProperty(this, PROP_AIRCRAFT_RUNNING_COST_FACTOR, e->u.air.running_cost);
440 return GetPrice(PR_RUNNING_AIRCRAFT, cost_factor, e->GetGRF());
443 void Aircraft::OnNewDay()
445 if (!this->IsNormalAircraft()) return;
447 if ((++this->day_counter & 7) == 0) DecreaseVehicleValue(this);
449 CheckOrders(this);
451 CheckVehicleBreakdown(this);
452 AgeVehicle(this);
453 CheckIfAircraftNeedsService(this);
455 if (this->running_ticks == 0) return;
457 CommandCost cost(EXPENSES_AIRCRAFT_RUN, this->GetRunningCost() * this->running_ticks / (DAYS_IN_YEAR * DAY_TICKS));
459 this->profit_this_year -= cost.GetCost();
460 this->running_ticks = 0;
462 SubtractMoneyFromCompanyFract(this->owner, cost);
464 SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
465 SetWindowClassesDirty(WC_AIRCRAFT_LIST);
468 static void HelicopterTickHandler(Aircraft *v)
470 Aircraft *u = v->Next()->Next();
472 if (u->vehstatus & VS_HIDDEN) return;
474 /* if true, helicopter rotors do not rotate. This should only be the case if a helicopter is
475 * loading/unloading at a terminal or stopped */
476 if (v->current_order.IsType(OT_LOADING) || (v->vehstatus & VS_STOPPED)) {
477 if (u->cur_speed != 0) {
478 u->cur_speed++;
479 if (u->cur_speed >= 0x80 && u->state == HRS_ROTOR_MOVING_3) {
480 u->cur_speed = 0;
483 } else {
484 if (u->cur_speed == 0) {
485 u->cur_speed = 0x70;
487 if (u->cur_speed >= 0x50) {
488 u->cur_speed--;
492 int tick = ++u->tick_counter;
493 int spd = u->cur_speed >> 4;
495 VehicleSpriteSeq seq;
496 if (spd == 0) {
497 u->state = HRS_ROTOR_STOPPED;
498 GetRotorImage(v, EIT_ON_MAP, &seq);
499 if (u->sprite_cache.sprite_seq == seq) return;
500 } else if (tick >= spd) {
501 u->tick_counter = 0;
502 u->state++;
503 if (u->state > HRS_ROTOR_MOVING_3) u->state = HRS_ROTOR_MOVING_1;
504 GetRotorImage(v, EIT_ON_MAP, &seq);
505 } else {
506 return;
509 u->sprite_cache.sprite_seq = seq;
511 u->UpdatePositionAndViewport();
515 * Set aircraft position.
516 * @param v Aircraft to position.
517 * @param x New X position.
518 * @param y New y position.
519 * @param z New z position.
521 void SetAircraftPosition(Aircraft *v, int x, int y, int z)
523 v->x_pos = x;
524 v->y_pos = y;
525 v->z_pos = z;
527 v->UpdatePosition();
528 v->UpdateViewport(true, false);
529 if (v->subtype == AIR_HELICOPTER) {
530 GetRotorImage(v, EIT_ON_MAP, &v->Next()->Next()->sprite_cache.sprite_seq);
533 Aircraft *u = v->Next();
535 int safe_x = Clamp(x, 0, MapMaxX() * TILE_SIZE);
536 int safe_y = Clamp(y - 1, 0, MapMaxY() * TILE_SIZE);
537 u->x_pos = x;
538 u->y_pos = y - ((v->z_pos - GetSlopePixelZ(safe_x, safe_y)) >> 3);
540 safe_y = Clamp(u->y_pos, 0, MapMaxY() * TILE_SIZE);
541 u->z_pos = GetSlopePixelZ(safe_x, safe_y);
542 u->sprite_cache.sprite_seq.CopyWithoutPalette(v->sprite_cache.sprite_seq); // the shadow is never coloured
544 u->UpdatePositionAndViewport();
546 u = u->Next();
547 if (u != nullptr) {
548 u->x_pos = x;
549 u->y_pos = y;
550 u->z_pos = z + ROTOR_Z_OFFSET;
552 u->UpdatePositionAndViewport();
557 * Handle Aircraft specific tasks when an Aircraft enters a hangar
558 * @param *v Vehicle that enters the hangar
560 void HandleAircraftEnterHangar(Aircraft *v)
562 v->subspeed = 0;
563 v->progress = 0;
565 Aircraft *u = v->Next();
566 u->vehstatus |= VS_HIDDEN;
567 u = u->Next();
568 if (u != nullptr) {
569 u->vehstatus |= VS_HIDDEN;
570 u->cur_speed = 0;
573 SetAircraftPosition(v, v->x_pos, v->y_pos, v->z_pos);
576 static void PlayAircraftSound(const Vehicle *v)
578 if (!PlayVehicleSound(v, VSE_START)) {
579 SndPlayVehicleFx(AircraftVehInfo(v->engine_type)->sfx, v);
585 * Update cached values of an aircraft.
586 * Currently caches callback 36 max speed.
587 * @param v Vehicle
588 * @param update_range Update the aircraft range.
590 void UpdateAircraftCache(Aircraft *v, bool update_range)
592 uint max_speed = GetVehicleProperty(v, PROP_AIRCRAFT_SPEED, 0);
593 if (max_speed != 0) {
594 /* Convert from original units to km-ish/h */
595 max_speed = (max_speed * 128) / 10;
597 v->vcache.cached_max_speed = max_speed;
598 } else {
599 /* Use the default max speed of the vehicle. */
600 v->vcache.cached_max_speed = AircraftVehInfo(v->engine_type)->max_speed;
603 /* Update cargo aging period. */
604 v->vcache.cached_cargo_age_period = GetVehicleProperty(v, PROP_AIRCRAFT_CARGO_AGE_PERIOD, EngInfo(v->engine_type)->cargo_age_period);
605 Aircraft *u = v->Next(); // Shadow for mail
606 u->vcache.cached_cargo_age_period = GetVehicleProperty(u, PROP_AIRCRAFT_CARGO_AGE_PERIOD, EngInfo(u->engine_type)->cargo_age_period);
608 /* Update aircraft range. */
609 if (update_range) {
610 v->acache.cached_max_range = GetVehicleProperty(v, PROP_AIRCRAFT_RANGE, AircraftVehInfo(v->engine_type)->max_range);
611 /* Squared it now so we don't have to do it later all the time. */
612 v->acache.cached_max_range_sqr = v->acache.cached_max_range * v->acache.cached_max_range;
618 * Special velocities for aircraft
620 enum AircraftSpeedLimits {
621 SPEED_LIMIT_TAXI = 50, ///< Maximum speed of an aircraft while taxiing
622 SPEED_LIMIT_APPROACH = 230, ///< Maximum speed of an aircraft on finals
623 SPEED_LIMIT_BROKEN = 320, ///< Maximum speed of an aircraft that is broken
624 SPEED_LIMIT_HOLD = 425, ///< Maximum speed of an aircraft that flies the holding pattern
625 SPEED_LIMIT_NONE = 0xFFFF, ///< No environmental speed limit. Speed limit is type dependent
629 * Sets the new speed for an aircraft
630 * @param v The vehicle for which the speed should be obtained
631 * @param speed_limit The maximum speed the vehicle may have.
632 * @param hard_limit If true, the limit is directly enforced, otherwise the plane is slowed down gradually
633 * @return The number of position updates needed within the tick
635 static int UpdateAircraftSpeed(Aircraft *v, uint speed_limit = SPEED_LIMIT_NONE, bool hard_limit = true)
638 * 'acceleration' has the unit 3/8 mph/tick. This function is called twice per tick.
639 * So the speed amount we need to accelerate is:
640 * acceleration * 3 / 16 mph = acceleration * 3 / 16 * 16 / 10 km-ish/h
641 * = acceleration * 3 / 10 * 256 * (km-ish/h / 256)
642 * ~ acceleration * 77 (km-ish/h / 256)
644 uint spd = v->acceleration * 77;
645 byte t;
647 /* Adjust speed limits by plane speed factor to prevent taxiing
648 * and take-off speeds being too low. */
649 speed_limit *= _settings_game.vehicle.plane_speed;
651 /* adjust speed for broken vehicles */
652 if (v->vehstatus & VS_AIRCRAFT_BROKEN) {
653 if (SPEED_LIMIT_BROKEN < speed_limit) hard_limit = false;
654 speed_limit = std::min<uint>(speed_limit, SPEED_LIMIT_BROKEN);
657 if (v->vcache.cached_max_speed < speed_limit) {
658 if (v->cur_speed < speed_limit) hard_limit = false;
659 speed_limit = v->vcache.cached_max_speed;
662 v->subspeed = (t = v->subspeed) + (byte)spd;
664 /* Aircraft's current speed is used twice so that very fast planes are
665 * forced to slow down rapidly in the short distance needed. The magic
666 * value 16384 was determined to give similar results to the old speed/48
667 * method at slower speeds. This also results in less reduction at slow
668 * speeds to that aircraft do not get to taxi speed straight after
669 * touchdown. */
670 if (!hard_limit && v->cur_speed > speed_limit) {
671 speed_limit = v->cur_speed - std::max(1, ((v->cur_speed * v->cur_speed) / 16384) / _settings_game.vehicle.plane_speed);
674 spd = std::min(v->cur_speed + (spd >> 8) + (v->subspeed < t), speed_limit);
676 /* updates statusbar only if speed have changed to save CPU time */
677 if (spd != v->cur_speed) {
678 v->cur_speed = spd;
679 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
682 /* Adjust distance moved by plane speed setting */
683 if (_settings_game.vehicle.plane_speed > 1) spd /= _settings_game.vehicle.plane_speed;
685 /* Convert direction-independent speed into direction-dependent speed. (old movement method) */
686 spd = v->GetOldAdvanceSpeed(spd);
688 spd += v->progress;
689 v->progress = (byte)spd;
690 return spd >> 8;
694 * Get the tile height below the aircraft.
695 * This function is needed because aircraft can leave the mapborders.
697 * @param v The vehicle to get the height for.
698 * @return The height in pixels from 'z_pos' 0.
700 int GetTileHeightBelowAircraft(const Vehicle *v)
702 int safe_x = Clamp(v->x_pos, 0, MapMaxX() * TILE_SIZE);
703 int safe_y = Clamp(v->y_pos, 0, MapMaxY() * TILE_SIZE);
704 return TileHeight(TileVirtXY(safe_x, safe_y)) * TILE_HEIGHT;
708 * Get the 'flight level' bounds, in pixels from 'z_pos' 0 for a particular
709 * vehicle for normal flight situation.
710 * When the maximum is reached the vehicle should consider descending.
711 * When the minimum is reached the vehicle should consider ascending.
713 * @param v The vehicle to get the flight levels for.
714 * @param[out] min_level The minimum bounds for flight level.
715 * @param[out] max_level The maximum bounds for flight level.
717 void GetAircraftFlightLevelBounds(const Vehicle *v, int *min_level, int *max_level)
719 int base_altitude = GetTileHeightBelowAircraft(v);
720 if (v->type == VEH_AIRCRAFT && Aircraft::From(v)->subtype == AIR_HELICOPTER) {
721 base_altitude += HELICOPTER_HOLD_MAX_FLYING_ALTITUDE - PLANE_HOLD_MAX_FLYING_ALTITUDE;
724 /* Make sure eastbound and westbound planes do not "crash" into each
725 * other by providing them with vertical separation
727 switch (v->direction) {
728 case DIR_N:
729 case DIR_NE:
730 case DIR_E:
731 case DIR_SE:
732 base_altitude += 10;
733 break;
735 default: break;
738 /* Make faster planes fly higher so that they can overtake slower ones */
739 base_altitude += std::min(20 * (v->vcache.cached_max_speed / 200) - 90, 0);
741 if (min_level != nullptr) *min_level = base_altitude + AIRCRAFT_MIN_FLYING_ALTITUDE;
742 if (max_level != nullptr) *max_level = base_altitude + AIRCRAFT_MAX_FLYING_ALTITUDE;
746 * Gets the maximum 'flight level' for the holding pattern of the aircraft,
747 * in pixels 'z_pos' 0, depending on terrain below.
749 * @param v The aircraft that may or may not need to decrease its altitude.
750 * @return Maximal aircraft holding altitude, while in normal flight, in pixels.
752 int GetAircraftHoldMaxAltitude(const Aircraft *v)
754 int tile_height = GetTileHeightBelowAircraft(v);
756 return tile_height + ((v->subtype == AIR_HELICOPTER) ? HELICOPTER_HOLD_MAX_FLYING_ALTITUDE : PLANE_HOLD_MAX_FLYING_ALTITUDE);
759 template <class T>
760 int GetAircraftFlightLevel(T *v, bool takeoff)
762 /* Aircraft is in flight. We want to enforce it being somewhere
763 * between the minimum and the maximum allowed altitude. */
764 int aircraft_min_altitude;
765 int aircraft_max_altitude;
766 GetAircraftFlightLevelBounds(v, &aircraft_min_altitude, &aircraft_max_altitude);
767 int aircraft_middle_altitude = (aircraft_min_altitude + aircraft_max_altitude) / 2;
769 /* If those assumptions would be violated, aircraft would behave fairly strange. */
770 assert(aircraft_min_altitude < aircraft_middle_altitude);
771 assert(aircraft_middle_altitude < aircraft_max_altitude);
773 int z = v->z_pos;
774 if (z < aircraft_min_altitude ||
775 (HasBit(v->flags, VAF_IN_MIN_HEIGHT_CORRECTION) && z < aircraft_middle_altitude)) {
776 /* Ascend. And don't fly into that mountain right ahead.
777 * And avoid our aircraft become a stairclimber, so if we start
778 * correcting altitude, then we stop correction not too early. */
779 SetBit(v->flags, VAF_IN_MIN_HEIGHT_CORRECTION);
780 z += takeoff ? 2 : 1;
781 } else if (!takeoff && (z > aircraft_max_altitude ||
782 (HasBit(v->flags, VAF_IN_MAX_HEIGHT_CORRECTION) && z > aircraft_middle_altitude))) {
783 /* Descend lower. You are an aircraft, not an space ship.
784 * And again, don't stop correcting altitude too early. */
785 SetBit(v->flags, VAF_IN_MAX_HEIGHT_CORRECTION);
786 z--;
787 } else if (HasBit(v->flags, VAF_IN_MIN_HEIGHT_CORRECTION) && z >= aircraft_middle_altitude) {
788 /* Now, we have corrected altitude enough. */
789 ClrBit(v->flags, VAF_IN_MIN_HEIGHT_CORRECTION);
790 } else if (HasBit(v->flags, VAF_IN_MAX_HEIGHT_CORRECTION) && z <= aircraft_middle_altitude) {
791 /* Now, we have corrected altitude enough. */
792 ClrBit(v->flags, VAF_IN_MAX_HEIGHT_CORRECTION);
795 return z;
798 template int GetAircraftFlightLevel(DisasterVehicle *v, bool takeoff);
799 template int GetAircraftFlightLevel(Aircraft *v, bool takeoff);
802 * Find the entry point to an airport depending on direction which
803 * the airport is being approached from. Each airport can have up to
804 * four entry points for its approach system so that approaching
805 * aircraft do not fly through each other or are forced to do 180
806 * degree turns during the approach. The arrivals are grouped into
807 * four sectors dependent on the DiagDirection from which the airport
808 * is approached.
810 * @param v The vehicle that is approaching the airport
811 * @param apc The Airport Class being approached.
812 * @param rotation The rotation of the airport.
813 * @return The index of the entry point
815 static byte AircraftGetEntryPoint(const Aircraft *v, const AirportFTAClass *apc, Direction rotation)
817 assert(v != nullptr);
818 assert(apc != nullptr);
820 /* In the case the station doesn't exit anymore, set target tile 0.
821 * It doesn't hurt much, aircraft will go to next order, nearest hangar
822 * or it will simply crash in next tick */
823 TileIndex tile = 0;
825 const Station *st = Station::GetIfValid(v->targetairport);
826 if (st != nullptr) {
827 /* Make sure we don't go to INVALID_TILE if the airport has been removed. */
828 tile = (st->airport.tile != INVALID_TILE) ? st->airport.tile : st->xy;
831 int delta_x = v->x_pos - TileX(tile) * TILE_SIZE;
832 int delta_y = v->y_pos - TileY(tile) * TILE_SIZE;
834 DiagDirection dir;
835 if (abs(delta_y) < abs(delta_x)) {
836 /* We are northeast or southwest of the airport */
837 dir = delta_x < 0 ? DIAGDIR_NE : DIAGDIR_SW;
838 } else {
839 /* We are northwest or southeast of the airport */
840 dir = delta_y < 0 ? DIAGDIR_NW : DIAGDIR_SE;
842 dir = ChangeDiagDir(dir, DiagDirDifference(DIAGDIR_NE, DirToDiagDir(rotation)));
843 return apc->entry_points[dir];
847 static void MaybeCrashAirplane(Aircraft *v);
850 * Controls the movement of an aircraft. This function actually moves the vehicle
851 * on the map and takes care of minor things like sound playback.
852 * @todo De-mystify the cur_speed values for helicopter rotors.
853 * @param v The vehicle that is moved. Must be the first vehicle of the chain
854 * @return Whether the position requested by the State Machine has been reached
856 static bool AircraftController(Aircraft *v)
858 /* nullptr if station is invalid */
859 const Station *st = Station::GetIfValid(v->targetairport);
860 /* INVALID_TILE if there is no station */
861 TileIndex tile = INVALID_TILE;
862 Direction rotation = DIR_N;
863 uint size_x = 1, size_y = 1;
864 if (st != nullptr) {
865 if (st->airport.tile != INVALID_TILE) {
866 tile = st->airport.tile;
867 rotation = st->airport.rotation;
868 size_x = st->airport.w;
869 size_y = st->airport.h;
870 } else {
871 tile = st->xy;
874 /* DUMMY if there is no station or no airport */
875 const AirportFTAClass *afc = tile == INVALID_TILE ? GetAirport(AT_DUMMY) : st->airport.GetFTA();
877 /* prevent going to INVALID_TILE if airport is deleted. */
878 if (st == nullptr || st->airport.tile == INVALID_TILE) {
879 /* Jump into our "holding pattern" state machine if possible */
880 if (v->pos >= afc->nofelements) {
881 v->pos = v->previous_pos = AircraftGetEntryPoint(v, afc, DIR_N);
882 } else if (v->targetairport != v->current_order.GetDestination()) {
883 /* If not possible, just get out of here fast */
884 v->state = FLYING;
885 UpdateAircraftCache(v);
886 AircraftNextAirportPos_and_Order(v);
887 /* get aircraft back on running altitude */
888 SetAircraftPosition(v, v->x_pos, v->y_pos, GetAircraftFlightLevel(v));
889 return false;
893 /* get airport moving data */
894 const AirportMovingData amd = RotateAirportMovingData(afc->MovingData(v->pos), rotation, size_x, size_y);
896 int x = TileX(tile) * TILE_SIZE;
897 int y = TileY(tile) * TILE_SIZE;
899 /* Helicopter raise */
900 if (amd.flag & AMED_HELI_RAISE) {
901 Aircraft *u = v->Next()->Next();
903 /* Make sure the rotors don't rotate too fast */
904 if (u->cur_speed > 32) {
905 v->cur_speed = 0;
906 if (--u->cur_speed == 32) {
907 if (!PlayVehicleSound(v, VSE_START)) {
908 SoundID sfx = AircraftVehInfo(v->engine_type)->sfx;
909 /* For compatibility with old NewGRF we ignore the sfx property, unless a NewGRF-defined sound is used.
910 * The baseset has only one helicopter sound, so this only limits using plane or cow sounds. */
911 if (sfx < ORIGINAL_SAMPLE_COUNT) sfx = SND_18_TAKEOFF_HELICOPTER;
912 SndPlayVehicleFx(sfx, v);
915 } else {
916 u->cur_speed = 32;
917 int count = UpdateAircraftSpeed(v);
918 if (count > 0) {
919 v->tile = 0;
921 int z_dest;
922 GetAircraftFlightLevelBounds(v, &z_dest, nullptr);
924 /* Reached altitude? */
925 if (v->z_pos >= z_dest) {
926 v->cur_speed = 0;
927 return true;
929 SetAircraftPosition(v, v->x_pos, v->y_pos, std::min(v->z_pos + count, z_dest));
932 return false;
935 /* Helicopter landing. */
936 if (amd.flag & AMED_HELI_LOWER) {
937 SetBit(v->flags, VAF_HELI_DIRECT_DESCENT);
939 if (st == nullptr) {
940 /* FIXME - AircraftController -> if station no longer exists, do not land
941 * helicopter will circle until sign disappears, then go to next order
942 * what to do when it is the only order left, right now it just stays in 1 place */
943 v->state = FLYING;
944 UpdateAircraftCache(v);
945 AircraftNextAirportPos_and_Order(v);
946 return false;
949 /* Vehicle is now at the airport.
950 * Helicopter has arrived at the target landing pad, so the current position is also where it should land.
951 * Except for Oilrigs which are special due to being a 1x1 station, and helicopters land outside it. */
952 if (st->airport.type != AT_OILRIG) {
953 x = v->x_pos;
954 y = v->y_pos;
955 tile = TileVirtXY(x, y);
957 v->tile = tile;
959 /* Find altitude of landing position. */
960 int z = GetSlopePixelZ(x, y) + 1 + afc->delta_z;
962 if (z == v->z_pos) {
963 Vehicle *u = v->Next()->Next();
965 /* Increase speed of rotors. When speed is 80, we've landed. */
966 if (u->cur_speed >= 80) {
967 ClrBit(v->flags, VAF_HELI_DIRECT_DESCENT);
968 return true;
970 u->cur_speed += 4;
971 } else {
972 int count = UpdateAircraftSpeed(v);
973 if (count > 0) {
974 if (v->z_pos > z) {
975 SetAircraftPosition(v, v->x_pos, v->y_pos, std::max(v->z_pos - count, z));
976 } else {
977 SetAircraftPosition(v, v->x_pos, v->y_pos, std::min(v->z_pos + count, z));
981 return false;
984 /* Get distance from destination pos to current pos. */
985 uint dist = abs(x + amd.x - v->x_pos) + abs(y + amd.y - v->y_pos);
987 /* Need exact position? */
988 if (!(amd.flag & AMED_EXACTPOS) && dist <= (amd.flag & AMED_SLOWTURN ? 8U : 4U)) return true;
990 /* At final pos? */
991 if (dist == 0) {
992 /* Change direction smoothly to final direction. */
993 DirDiff dirdiff = DirDifference(amd.direction, v->direction);
994 /* if distance is 0, and plane points in right direction, no point in calling
995 * UpdateAircraftSpeed(). So do it only afterwards */
996 if (dirdiff == DIRDIFF_SAME) {
997 v->cur_speed = 0;
998 return true;
1001 if (!UpdateAircraftSpeed(v, SPEED_LIMIT_TAXI)) return false;
1003 v->direction = ChangeDir(v->direction, dirdiff > DIRDIFF_REVERSE ? DIRDIFF_45LEFT : DIRDIFF_45RIGHT);
1004 v->cur_speed >>= 1;
1006 SetAircraftPosition(v, v->x_pos, v->y_pos, v->z_pos);
1007 return false;
1010 if (amd.flag & AMED_BRAKE && v->cur_speed > SPEED_LIMIT_TAXI * _settings_game.vehicle.plane_speed) {
1011 MaybeCrashAirplane(v);
1012 if ((v->vehstatus & VS_CRASHED) != 0) return false;
1015 uint speed_limit = SPEED_LIMIT_TAXI;
1016 bool hard_limit = true;
1018 if (amd.flag & AMED_NOSPDCLAMP) speed_limit = SPEED_LIMIT_NONE;
1019 if (amd.flag & AMED_HOLD) { speed_limit = SPEED_LIMIT_HOLD; hard_limit = false; }
1020 if (amd.flag & AMED_LAND) { speed_limit = SPEED_LIMIT_APPROACH; hard_limit = false; }
1021 if (amd.flag & AMED_BRAKE) { speed_limit = SPEED_LIMIT_TAXI; hard_limit = false; }
1023 int count = UpdateAircraftSpeed(v, speed_limit, hard_limit);
1024 if (count == 0) return false;
1026 /* If the plane will be a few subpixels away from the destination after
1027 * this movement loop, start nudging it towards the exact position for
1028 * the whole loop. Otherwise, heavily depending on the speed of the plane,
1029 * it is possible we totally overshoot the target, causing the plane to
1030 * make a loop, and trying again, and again, and again .. */
1031 bool nudge_towards_target = static_cast<uint>(count) + 3 > dist;
1033 if (v->turn_counter != 0) v->turn_counter--;
1035 do {
1037 GetNewVehiclePosResult gp;
1039 if (nudge_towards_target || (amd.flag & AMED_LAND)) {
1040 /* move vehicle one pixel towards target */
1041 gp.x = (v->x_pos != (x + amd.x)) ?
1042 v->x_pos + ((x + amd.x > v->x_pos) ? 1 : -1) :
1043 v->x_pos;
1044 gp.y = (v->y_pos != (y + amd.y)) ?
1045 v->y_pos + ((y + amd.y > v->y_pos) ? 1 : -1) :
1046 v->y_pos;
1048 /* Oilrigs must keep v->tile as st->airport.tile, since the landing pad is in a non-airport tile */
1049 gp.new_tile = (st->airport.type == AT_OILRIG) ? st->airport.tile : TileVirtXY(gp.x, gp.y);
1051 } else {
1053 /* Turn. Do it slowly if in the air. */
1054 Direction newdir = GetDirectionTowards(v, x + amd.x, y + amd.y);
1055 if (newdir != v->direction) {
1056 if (amd.flag & AMED_SLOWTURN && v->number_consecutive_turns < 8 && v->subtype == AIR_AIRCRAFT) {
1057 if (v->turn_counter == 0 || newdir == v->last_direction) {
1058 if (newdir == v->last_direction) {
1059 v->number_consecutive_turns = 0;
1060 } else {
1061 v->number_consecutive_turns++;
1063 v->turn_counter = 2 * _settings_game.vehicle.plane_speed;
1064 v->last_direction = v->direction;
1065 v->direction = newdir;
1068 /* Move vehicle. */
1069 gp = GetNewVehiclePos(v);
1070 } else {
1071 v->cur_speed >>= 1;
1072 v->direction = newdir;
1074 /* When leaving a terminal an aircraft often goes to a position
1075 * directly in front of it. If it would move while turning it
1076 * would need an two extra turns to end up at the correct position.
1077 * To make it easier just disallow all moving while turning as
1078 * long as an aircraft is on the ground. */
1079 gp.x = v->x_pos;
1080 gp.y = v->y_pos;
1081 gp.new_tile = gp.old_tile = v->tile;
1083 } else {
1084 v->number_consecutive_turns = 0;
1085 /* Move vehicle. */
1086 gp = GetNewVehiclePos(v);
1090 v->tile = gp.new_tile;
1091 /* If vehicle is in the air, use tile coordinate 0. */
1092 if (amd.flag & (AMED_TAKEOFF | AMED_SLOWTURN | AMED_LAND)) v->tile = 0;
1094 /* Adjust Z for land or takeoff? */
1095 int z = v->z_pos;
1097 if (amd.flag & AMED_TAKEOFF) {
1098 z = GetAircraftFlightLevel(v, true);
1099 } else if (amd.flag & AMED_HOLD) {
1100 /* Let the plane drop from normal flight altitude to holding pattern altitude */
1101 if (z > GetAircraftHoldMaxAltitude(v)) z--;
1102 } else if ((amd.flag & AMED_SLOWTURN) && (amd.flag & AMED_NOSPDCLAMP)) {
1103 z = GetAircraftFlightLevel(v);
1106 /* NewGRF airports (like a rotated intercontinental from OpenGFX+Airports) can be non-rectangular
1107 * and their primary (north-most) tile does not have to be part of the airport.
1108 * As such, the height of the primary tile can be different from the rest of the airport.
1109 * Given we are landing/breaking, and as such are not a helicopter, we know that there has to be a hangar.
1110 * We also know that the airport itself has to be completely flat (otherwise it is not a valid airport).
1111 * Therefore, use the height of this hangar to calculate our z-value. */
1112 int airport_z = v->z_pos;
1113 if ((amd.flag & (AMED_LAND | AMED_BRAKE)) && st != nullptr) {
1114 assert(st->airport.HasHangar());
1115 TileIndex hangar_tile = st->airport.GetHangarTile(0);
1116 airport_z = GetTileMaxPixelZ(hangar_tile) + 1; // To avoid clashing with the shadow
1119 if (amd.flag & AMED_LAND) {
1120 if (st->airport.tile == INVALID_TILE) {
1121 /* Airport has been removed, abort the landing procedure */
1122 v->state = FLYING;
1123 UpdateAircraftCache(v);
1124 AircraftNextAirportPos_and_Order(v);
1125 /* get aircraft back on running altitude */
1126 SetAircraftPosition(v, gp.x, gp.y, GetAircraftFlightLevel(v));
1127 continue;
1130 /* We're not flying below our destination, right? */
1131 assert(airport_z <= z);
1132 int t = std::max(1U, dist - 4);
1133 int delta = z - airport_z;
1135 /* Only start lowering when we're sufficiently close for a 1:1 glide */
1136 if (delta >= t) {
1137 z -= CeilDiv(z - airport_z, t);
1139 if (z < airport_z) z = airport_z;
1142 /* We've landed. Decrease speed when we're reaching end of runway. */
1143 if (amd.flag & AMED_BRAKE) {
1145 if (z > airport_z) {
1146 z--;
1147 } else if (z < airport_z) {
1148 z++;
1153 SetAircraftPosition(v, gp.x, gp.y, z);
1154 } while (--count != 0);
1155 return false;
1159 * Handle crashed aircraft \a v.
1160 * @param v Crashed aircraft.
1162 static bool HandleCrashedAircraft(Aircraft *v)
1164 v->crashed_counter += 3;
1166 Station *st = GetTargetAirportIfValid(v);
1168 /* make aircraft crash down to the ground */
1169 if (v->crashed_counter < 500 && st == nullptr && ((v->crashed_counter % 3) == 0) ) {
1170 int z = GetSlopePixelZ(Clamp(v->x_pos, 0, MapMaxX() * TILE_SIZE), Clamp(v->y_pos, 0, MapMaxY() * TILE_SIZE));
1171 v->z_pos -= 1;
1172 if (v->z_pos == z) {
1173 v->crashed_counter = 500;
1174 v->z_pos++;
1178 if (v->crashed_counter < 650) {
1179 uint32 r;
1180 if (Chance16R(1, 32, r)) {
1181 static const DirDiff delta[] = {
1182 DIRDIFF_45LEFT, DIRDIFF_SAME, DIRDIFF_SAME, DIRDIFF_45RIGHT
1185 v->direction = ChangeDir(v->direction, delta[GB(r, 16, 2)]);
1186 SetAircraftPosition(v, v->x_pos, v->y_pos, v->z_pos);
1187 r = Random();
1188 CreateEffectVehicleRel(v,
1189 GB(r, 0, 4) - 4,
1190 GB(r, 4, 4) - 4,
1191 GB(r, 8, 4),
1192 EV_EXPLOSION_SMALL);
1194 } else if (v->crashed_counter >= 10000) {
1195 /* remove rubble of crashed airplane */
1197 /* clear runway-in on all airports, set by crashing plane
1198 * small airports use AIRPORT_BUSY, city airports use RUNWAY_IN_OUT_block, etc.
1199 * but they all share the same number */
1200 if (st != nullptr) {
1201 CLRBITS(st->airport.flags, RUNWAY_IN_block);
1202 CLRBITS(st->airport.flags, RUNWAY_IN_OUT_block); // commuter airport
1203 CLRBITS(st->airport.flags, RUNWAY_IN2_block); // intercontinental
1206 delete v;
1208 return false;
1211 return true;
1216 * Handle smoke of broken aircraft.
1217 * @param v Aircraft
1218 * @param mode Is this the non-first call for this vehicle in this tick?
1220 static void HandleAircraftSmoke(Aircraft *v, bool mode)
1222 static const struct {
1223 int8 x;
1224 int8 y;
1225 } smoke_pos[] = {
1226 { 5, 5 },
1227 { 6, 0 },
1228 { 5, -5 },
1229 { 0, -6 },
1230 { -5, -5 },
1231 { -6, 0 },
1232 { -5, 5 },
1233 { 0, 6 }
1236 if (!(v->vehstatus & VS_AIRCRAFT_BROKEN)) return;
1238 /* Stop smoking when landed */
1239 if (v->cur_speed < 10) {
1240 v->vehstatus &= ~VS_AIRCRAFT_BROKEN;
1241 v->breakdown_ctr = 0;
1242 return;
1245 /* Spawn effect et most once per Tick, i.e. !mode */
1246 if (!mode && (v->tick_counter & 0x0F) == 0) {
1247 CreateEffectVehicleRel(v,
1248 smoke_pos[v->direction].x,
1249 smoke_pos[v->direction].y,
1251 EV_BREAKDOWN_SMOKE_AIRCRAFT
1256 void HandleMissingAircraftOrders(Aircraft *v)
1259 * We do not have an order. This can be divided into two cases:
1260 * 1) we are heading to an invalid station. In this case we must
1261 * find another airport to go to. If there is nowhere to go,
1262 * we will destroy the aircraft as it otherwise will enter
1263 * the holding pattern for the first airport, which can cause
1264 * the plane to go into an undefined state when building an
1265 * airport with the same StationID.
1266 * 2) we are (still) heading to a (still) valid airport, then we
1267 * can continue going there. This can happen when you are
1268 * changing the aircraft's orders while in-flight or in for
1269 * example a depot. However, when we have a current order to
1270 * go to a depot, we have to keep that order so the aircraft
1271 * actually stops.
1273 const Station *st = GetTargetAirportIfValid(v);
1274 if (st == nullptr) {
1275 Backup<CompanyID> cur_company(_current_company, v->owner, FILE_LINE);
1276 CommandCost ret = Command<CMD_SEND_VEHICLE_TO_DEPOT>::Do(DC_EXEC, v->index, DepotCommand::None, {});
1277 cur_company.Restore();
1279 if (ret.Failed()) CrashAirplane(v);
1280 } else if (!v->current_order.IsType(OT_GOTO_DEPOT)) {
1281 v->current_order.Free();
1286 TileIndex Aircraft::GetOrderStationLocation(StationID station)
1288 /* Orders are changed in flight, ensure going to the right station. */
1289 if (this->state == FLYING) {
1290 AircraftNextAirportPos_and_Order(this);
1293 /* Aircraft do not use dest-tile */
1294 return 0;
1297 void Aircraft::MarkDirty()
1299 this->colourmap = PAL_NONE;
1300 this->UpdateViewport(true, false);
1301 if (this->subtype == AIR_HELICOPTER) {
1302 GetRotorImage(this, EIT_ON_MAP, &this->Next()->Next()->sprite_cache.sprite_seq);
1307 uint Aircraft::Crash(bool flooded)
1309 uint pass = Vehicle::Crash(flooded) + 2; // pilots
1310 this->crashed_counter = flooded ? 9000 : 0; // max 10000, disappear pretty fast when flooded
1312 return pass;
1316 * Bring the aircraft in a crashed state, create the explosion animation, and create a news item about the crash.
1317 * @param v Aircraft that crashed.
1319 static void CrashAirplane(Aircraft *v)
1321 CreateEffectVehicleRel(v, 4, 4, 8, EV_EXPLOSION_LARGE);
1323 uint pass = v->Crash();
1324 SetDParam(0, pass);
1326 v->cargo.Truncate();
1327 v->Next()->cargo.Truncate();
1328 const Station *st = GetTargetAirportIfValid(v);
1329 StringID newsitem;
1330 TileIndex vt;
1331 if (st == nullptr) {
1332 newsitem = STR_NEWS_PLANE_CRASH_OUT_OF_FUEL;
1333 vt = TileVirtXY(v->x_pos, v->y_pos);
1334 } else {
1335 SetDParam(1, st->index);
1336 newsitem = STR_NEWS_AIRCRAFT_CRASH;
1337 vt = v->tile;
1340 AI::NewEvent(v->owner, new ScriptEventVehicleCrashed(v->index, vt, st == nullptr ? ScriptEventVehicleCrashed::CRASH_AIRCRAFT_NO_AIRPORT : ScriptEventVehicleCrashed::CRASH_PLANE_LANDING));
1341 Game::NewEvent(new ScriptEventVehicleCrashed(v->index, vt, st == nullptr ? ScriptEventVehicleCrashed::CRASH_AIRCRAFT_NO_AIRPORT : ScriptEventVehicleCrashed::CRASH_PLANE_LANDING));
1343 NewsType newstype = NT_ACCIDENT;
1344 if (v->owner != _local_company) {
1345 newstype = NT_ACCIDENT_OTHER;
1348 AddTileNewsItem(newsitem, newstype, vt, nullptr, st != nullptr ? st->index : INVALID_STATION);
1350 ModifyStationRatingAround(vt, v->owner, -160, 30);
1351 if (_settings_client.sound.disaster) SndPlayVehicleFx(SND_12_EXPLOSION, v);
1355 * Decide whether aircraft \a v should crash.
1356 * @param v Aircraft to test.
1358 static void MaybeCrashAirplane(Aircraft *v)
1361 Station *st = Station::Get(v->targetairport);
1363 uint32 prob;
1364 if ((st->airport.GetFTA()->flags & AirportFTAClass::SHORT_STRIP) &&
1365 (AircraftVehInfo(v->engine_type)->subtype & AIR_FAST) &&
1366 !_cheats.no_jetcrash.value) {
1367 prob = 3276;
1368 } else {
1369 if (_settings_game.vehicle.plane_crashes == 0) return;
1370 prob = (0x4000 << _settings_game.vehicle.plane_crashes) / 1500;
1373 if (GB(Random(), 0, 22) > prob) return;
1375 /* Crash the airplane. Remove all goods stored at the station. */
1376 for (CargoID i = 0; i < NUM_CARGO; i++) {
1377 st->goods[i].rating = 1;
1378 st->goods[i].cargo.Truncate();
1381 CrashAirplane(v);
1385 * Aircraft arrives at a terminal. If it is the first aircraft, throw a party.
1386 * Start loading cargo.
1387 * @param v Aircraft that arrived.
1389 static void AircraftEntersTerminal(Aircraft *v)
1391 if (v->current_order.IsType(OT_GOTO_DEPOT)) return;
1393 Station *st = Station::Get(v->targetairport);
1394 v->last_station_visited = v->targetairport;
1396 /* Check if station was ever visited before */
1397 if (!(st->had_vehicle_of_type & HVOT_AIRCRAFT)) {
1398 st->had_vehicle_of_type |= HVOT_AIRCRAFT;
1399 SetDParam(0, st->index);
1400 /* show newsitem of celebrating citizens */
1401 AddVehicleNewsItem(
1402 STR_NEWS_FIRST_AIRCRAFT_ARRIVAL,
1403 (v->owner == _local_company) ? NT_ARRIVAL_COMPANY : NT_ARRIVAL_OTHER,
1404 v->index,
1405 st->index
1407 AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
1408 Game::NewEvent(new ScriptEventStationFirstVehicle(st->index, v->index));
1411 v->BeginLoading();
1415 * Aircraft touched down at the landing strip.
1416 * @param v Aircraft that landed.
1418 static void AircraftLandAirplane(Aircraft *v)
1420 Station *st = Station::Get(v->targetairport);
1422 TileIndex vt = TileVirtXY(v->x_pos, v->y_pos);
1424 v->UpdateDeltaXY();
1426 AirportTileAnimationTrigger(st, vt, AAT_STATION_AIRPLANE_LAND);
1428 if (!PlayVehicleSound(v, VSE_TOUCHDOWN)) {
1429 SndPlayVehicleFx(SND_17_SKID_PLANE, v);
1434 /** set the right pos when heading to other airports after takeoff */
1435 void AircraftNextAirportPos_and_Order(Aircraft *v)
1437 if (v->current_order.IsType(OT_GOTO_STATION) || v->current_order.IsType(OT_GOTO_DEPOT)) {
1438 v->targetairport = v->current_order.GetDestination();
1441 const Station *st = GetTargetAirportIfValid(v);
1442 const AirportFTAClass *apc = st == nullptr ? GetAirport(AT_DUMMY) : st->airport.GetFTA();
1443 Direction rotation = st == nullptr ? DIR_N : st->airport.rotation;
1444 v->pos = v->previous_pos = AircraftGetEntryPoint(v, apc, rotation);
1448 * Aircraft is about to leave the hangar.
1449 * @param v Aircraft leaving.
1450 * @param exit_dir The direction the vehicle leaves the hangar.
1451 * @note This function is called in AfterLoadGame for old savegames, so don't rely
1452 * on any data to be valid, especially don't rely on the fact that the vehicle
1453 * is actually on the ground inside a depot.
1455 void AircraftLeaveHangar(Aircraft *v, Direction exit_dir)
1457 v->cur_speed = 0;
1458 v->subspeed = 0;
1459 v->progress = 0;
1460 v->direction = exit_dir;
1461 v->vehstatus &= ~VS_HIDDEN;
1463 Vehicle *u = v->Next();
1464 u->vehstatus &= ~VS_HIDDEN;
1466 /* Rotor blades */
1467 u = u->Next();
1468 if (u != nullptr) {
1469 u->vehstatus &= ~VS_HIDDEN;
1470 u->cur_speed = 80;
1474 VehicleServiceInDepot(v);
1475 SetAircraftPosition(v, v->x_pos, v->y_pos, v->z_pos);
1476 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
1477 SetWindowClassesDirty(WC_AIRCRAFT_LIST);
1480 ////////////////////////////////////////////////////////////////////////////////
1481 /////////////////// AIRCRAFT MOVEMENT SCHEME ////////////////////////////////
1482 ////////////////////////////////////////////////////////////////////////////////
1483 static void AircraftEventHandler_EnterTerminal(Aircraft *v, const AirportFTAClass *apc)
1485 AircraftEntersTerminal(v);
1486 v->state = apc->layout[v->pos].heading;
1490 * Aircraft arrived in an airport hangar.
1491 * @param v Aircraft in the hangar.
1492 * @param apc Airport description containing the hangar.
1494 static void AircraftEventHandler_EnterHangar(Aircraft *v, const AirportFTAClass *apc)
1496 VehicleEnterDepot(v);
1497 v->state = apc->layout[v->pos].heading;
1501 * Handle aircraft movement/decision making in an airport hangar.
1502 * @param v Aircraft in the hangar.
1503 * @param apc Airport description containing the hangar.
1505 static void AircraftEventHandler_InHangar(Aircraft *v, const AirportFTAClass *apc)
1507 /* if we just arrived, execute EnterHangar first */
1508 if (v->previous_pos != v->pos) {
1509 AircraftEventHandler_EnterHangar(v, apc);
1510 return;
1513 /* if we were sent to the depot, stay there */
1514 if (v->current_order.IsType(OT_GOTO_DEPOT) && (v->vehstatus & VS_STOPPED)) {
1515 v->current_order.Free();
1516 return;
1519 if (!v->current_order.IsType(OT_GOTO_STATION) &&
1520 !v->current_order.IsType(OT_GOTO_DEPOT))
1521 return;
1523 /* We are leaving a hangar, but have to go to the exact same one; re-enter */
1524 if (v->current_order.IsType(OT_GOTO_DEPOT) && v->current_order.GetDestination() == v->targetairport) {
1525 VehicleEnterDepot(v);
1526 return;
1529 /* if the block of the next position is busy, stay put */
1530 if (AirportHasBlock(v, &apc->layout[v->pos], apc)) return;
1532 /* We are already at the target airport, we need to find a terminal */
1533 if (v->current_order.GetDestination() == v->targetairport) {
1534 /* FindFreeTerminal:
1535 * 1. Find a free terminal, 2. Occupy it, 3. Set the vehicle's state to that terminal */
1536 if (v->subtype == AIR_HELICOPTER) {
1537 if (!AirportFindFreeHelipad(v, apc)) return; // helicopter
1538 } else {
1539 if (!AirportFindFreeTerminal(v, apc)) return; // airplane
1541 } else { // Else prepare for launch.
1542 /* airplane goto state takeoff, helicopter to helitakeoff */
1543 v->state = (v->subtype == AIR_HELICOPTER) ? HELITAKEOFF : TAKEOFF;
1545 const Station *st = Station::GetByTile(v->tile);
1546 AircraftLeaveHangar(v, st->airport.GetHangarExitDirection(v->tile));
1547 AirportMove(v, apc);
1550 /** At one of the Airport's Terminals */
1551 static void AircraftEventHandler_AtTerminal(Aircraft *v, const AirportFTAClass *apc)
1553 /* if we just arrived, execute EnterTerminal first */
1554 if (v->previous_pos != v->pos) {
1555 AircraftEventHandler_EnterTerminal(v, apc);
1556 /* on an airport with helipads, a helicopter will always land there
1557 * and get serviced at the same time - setting */
1558 if (_settings_game.order.serviceathelipad) {
1559 if (v->subtype == AIR_HELICOPTER && apc->num_helipads > 0) {
1560 /* an excerpt of ServiceAircraft, without the invisibility stuff */
1561 v->date_of_last_service = _date;
1562 v->breakdowns_since_last_service = 0;
1563 v->reliability = v->GetEngine()->reliability;
1564 SetWindowDirty(WC_VEHICLE_DETAILS, v->index);
1567 return;
1570 if (v->current_order.IsType(OT_NOTHING)) return;
1572 /* if the block of the next position is busy, stay put */
1573 if (AirportHasBlock(v, &apc->layout[v->pos], apc)) return;
1575 /* airport-road is free. We either have to go to another airport, or to the hangar
1576 * ---> start moving */
1578 bool go_to_hangar = false;
1579 switch (v->current_order.GetType()) {
1580 case OT_GOTO_STATION: // ready to fly to another airport
1581 break;
1582 case OT_GOTO_DEPOT: // visit hangar for servicing, sale, etc.
1583 go_to_hangar = v->current_order.GetDestination() == v->targetairport;
1584 break;
1585 case OT_CONDITIONAL:
1586 /* In case of a conditional order we just have to wait a tick
1587 * longer, so the conditional order can actually be processed;
1588 * we should not clear the order as that makes us go nowhere. */
1589 return;
1590 default: // orders have been deleted (no orders), goto depot and don't bother us
1591 v->current_order.Free();
1592 go_to_hangar = Station::Get(v->targetairport)->airport.HasHangar();
1595 if (go_to_hangar && Station::Get(v->targetairport)->airport.HasHangar()) {
1596 v->state = HANGAR;
1597 } else {
1598 /* airplane goto state takeoff, helicopter to helitakeoff */
1599 v->state = (v->subtype == AIR_HELICOPTER) ? HELITAKEOFF : TAKEOFF;
1601 AirportMove(v, apc);
1604 static void AircraftEventHandler_General(Aircraft *v, const AirportFTAClass *apc)
1606 error("OK, you shouldn't be here, check your Airport Scheme!");
1609 static void AircraftEventHandler_TakeOff(Aircraft *v, const AirportFTAClass *apc)
1611 PlayAircraftSound(v); // play takeoffsound for airplanes
1612 v->state = STARTTAKEOFF;
1615 static void AircraftEventHandler_StartTakeOff(Aircraft *v, const AirportFTAClass *apc)
1617 v->state = ENDTAKEOFF;
1618 v->UpdateDeltaXY();
1621 static void AircraftEventHandler_EndTakeOff(Aircraft *v, const AirportFTAClass *apc)
1623 v->state = FLYING;
1624 /* get the next position to go to, differs per airport */
1625 AircraftNextAirportPos_and_Order(v);
1628 static void AircraftEventHandler_HeliTakeOff(Aircraft *v, const AirportFTAClass *apc)
1630 v->state = FLYING;
1631 v->UpdateDeltaXY();
1633 /* get the next position to go to, differs per airport */
1634 AircraftNextAirportPos_and_Order(v);
1636 /* Send the helicopter to a hangar if needed for replacement */
1637 if (v->NeedsAutomaticServicing()) {
1638 Backup<CompanyID> cur_company(_current_company, v->owner, FILE_LINE);
1639 Command<CMD_SEND_VEHICLE_TO_DEPOT>::Do(DC_EXEC, v->index, DepotCommand::Service | DepotCommand::LocateHangar, {});
1640 cur_company.Restore();
1644 static void AircraftEventHandler_Flying(Aircraft *v, const AirportFTAClass *apc)
1646 Station *st = Station::Get(v->targetairport);
1648 /* Runway busy, not allowed to use this airstation or closed, circle. */
1649 if (CanVehicleUseStation(v, st) && (st->owner == OWNER_NONE || st->owner == v->owner) && !(st->airport.flags & AIRPORT_CLOSED_block)) {
1650 /* {32,FLYING,NOTHING_block,37}, {32,LANDING,N,33}, {32,HELILANDING,N,41},
1651 * if it is an airplane, look for LANDING, for helicopter HELILANDING
1652 * it is possible to choose from multiple landing runways, so loop until a free one is found */
1653 byte landingtype = (v->subtype == AIR_HELICOPTER) ? HELILANDING : LANDING;
1654 const AirportFTA *current = apc->layout[v->pos].next;
1655 while (current != nullptr) {
1656 if (current->heading == landingtype) {
1657 /* save speed before, since if AirportHasBlock is false, it resets them to 0
1658 * we don't want that for plane in air
1659 * hack for speed thingie */
1660 uint16 tcur_speed = v->cur_speed;
1661 uint16 tsubspeed = v->subspeed;
1662 if (!AirportHasBlock(v, current, apc)) {
1663 v->state = landingtype; // LANDING / HELILANDING
1664 if (v->state == HELILANDING) SetBit(v->flags, VAF_HELI_DIRECT_DESCENT);
1665 /* it's a bit dirty, but I need to set position to next position, otherwise
1666 * if there are multiple runways, plane won't know which one it took (because
1667 * they all have heading LANDING). And also occupy that block! */
1668 v->pos = current->next_position;
1669 SETBITS(st->airport.flags, apc->layout[v->pos].block);
1670 return;
1672 v->cur_speed = tcur_speed;
1673 v->subspeed = tsubspeed;
1675 current = current->next;
1678 v->state = FLYING;
1679 v->pos = apc->layout[v->pos].next_position;
1682 static void AircraftEventHandler_Landing(Aircraft *v, const AirportFTAClass *apc)
1684 v->state = ENDLANDING;
1685 AircraftLandAirplane(v); // maybe crash airplane
1687 /* check if the aircraft needs to be replaced or renewed and send it to a hangar if needed */
1688 if (v->NeedsAutomaticServicing()) {
1689 Backup<CompanyID> cur_company(_current_company, v->owner, FILE_LINE);
1690 Command<CMD_SEND_VEHICLE_TO_DEPOT>::Do(DC_EXEC, v->index, DepotCommand::Service, {});
1691 cur_company.Restore();
1695 static void AircraftEventHandler_HeliLanding(Aircraft *v, const AirportFTAClass *apc)
1697 v->state = HELIENDLANDING;
1698 v->UpdateDeltaXY();
1701 static void AircraftEventHandler_EndLanding(Aircraft *v, const AirportFTAClass *apc)
1703 /* next block busy, don't do a thing, just wait */
1704 if (AirportHasBlock(v, &apc->layout[v->pos], apc)) return;
1706 /* if going to terminal (OT_GOTO_STATION) choose one
1707 * 1. in case all terminals are busy AirportFindFreeTerminal() returns false or
1708 * 2. not going for terminal (but depot, no order),
1709 * --> get out of the way to the hangar. */
1710 if (v->current_order.IsType(OT_GOTO_STATION)) {
1711 if (AirportFindFreeTerminal(v, apc)) return;
1713 v->state = HANGAR;
1717 static void AircraftEventHandler_HeliEndLanding(Aircraft *v, const AirportFTAClass *apc)
1719 /* next block busy, don't do a thing, just wait */
1720 if (AirportHasBlock(v, &apc->layout[v->pos], apc)) return;
1722 /* if going to helipad (OT_GOTO_STATION) choose one. If airport doesn't have helipads, choose terminal
1723 * 1. in case all terminals/helipads are busy (AirportFindFreeHelipad() returns false) or
1724 * 2. not going for terminal (but depot, no order),
1725 * --> get out of the way to the hangar IF there are terminals on the airport.
1726 * --> else TAKEOFF
1727 * the reason behind this is that if an airport has a terminal, it also has a hangar. Airplanes
1728 * must go to a hangar. */
1729 if (v->current_order.IsType(OT_GOTO_STATION)) {
1730 if (AirportFindFreeHelipad(v, apc)) return;
1732 v->state = Station::Get(v->targetairport)->airport.HasHangar() ? HANGAR : HELITAKEOFF;
1736 * Signature of the aircraft handler function.
1737 * @param v Aircraft to handle.
1738 * @param apc Airport state machine.
1740 typedef void AircraftStateHandler(Aircraft *v, const AirportFTAClass *apc);
1741 /** Array of handler functions for each target of the aircraft. */
1742 static AircraftStateHandler * const _aircraft_state_handlers[] = {
1743 AircraftEventHandler_General, // TO_ALL = 0
1744 AircraftEventHandler_InHangar, // HANGAR = 1
1745 AircraftEventHandler_AtTerminal, // TERM1 = 2
1746 AircraftEventHandler_AtTerminal, // TERM2 = 3
1747 AircraftEventHandler_AtTerminal, // TERM3 = 4
1748 AircraftEventHandler_AtTerminal, // TERM4 = 5
1749 AircraftEventHandler_AtTerminal, // TERM5 = 6
1750 AircraftEventHandler_AtTerminal, // TERM6 = 7
1751 AircraftEventHandler_AtTerminal, // HELIPAD1 = 8
1752 AircraftEventHandler_AtTerminal, // HELIPAD2 = 9
1753 AircraftEventHandler_TakeOff, // TAKEOFF = 10
1754 AircraftEventHandler_StartTakeOff, // STARTTAKEOFF = 11
1755 AircraftEventHandler_EndTakeOff, // ENDTAKEOFF = 12
1756 AircraftEventHandler_HeliTakeOff, // HELITAKEOFF = 13
1757 AircraftEventHandler_Flying, // FLYING = 14
1758 AircraftEventHandler_Landing, // LANDING = 15
1759 AircraftEventHandler_EndLanding, // ENDLANDING = 16
1760 AircraftEventHandler_HeliLanding, // HELILANDING = 17
1761 AircraftEventHandler_HeliEndLanding, // HELIENDLANDING = 18
1762 AircraftEventHandler_AtTerminal, // TERM7 = 19
1763 AircraftEventHandler_AtTerminal, // TERM8 = 20
1764 AircraftEventHandler_AtTerminal, // HELIPAD3 = 21
1767 static void AirportClearBlock(const Aircraft *v, const AirportFTAClass *apc)
1769 /* we have left the previous block, and entered the new one. Free the previous block */
1770 if (apc->layout[v->previous_pos].block != apc->layout[v->pos].block) {
1771 Station *st = Station::Get(v->targetairport);
1773 CLRBITS(st->airport.flags, apc->layout[v->previous_pos].block);
1777 static void AirportGoToNextPosition(Aircraft *v)
1779 /* if aircraft is not in position, wait until it is */
1780 if (!AircraftController(v)) return;
1782 const AirportFTAClass *apc = Station::Get(v->targetairport)->airport.GetFTA();
1784 AirportClearBlock(v, apc);
1785 AirportMove(v, apc); // move aircraft to next position
1788 /* gets pos from vehicle and next orders */
1789 static bool AirportMove(Aircraft *v, const AirportFTAClass *apc)
1791 /* error handling */
1792 if (v->pos >= apc->nofelements) {
1793 Debug(misc, 0, "[Ap] position {} is not valid for current airport. Max position is {}", v->pos, apc->nofelements-1);
1794 assert(v->pos < apc->nofelements);
1797 const AirportFTA *current = &apc->layout[v->pos];
1798 /* we have arrived in an important state (eg terminal, hangar, etc.) */
1799 if (current->heading == v->state) {
1800 byte prev_pos = v->pos; // location could be changed in state, so save it before-hand
1801 byte prev_state = v->state;
1802 _aircraft_state_handlers[v->state](v, apc);
1803 if (v->state != FLYING) v->previous_pos = prev_pos;
1804 if (v->state != prev_state || v->pos != prev_pos) UpdateAircraftCache(v);
1805 return true;
1808 v->previous_pos = v->pos; // save previous location
1810 /* there is only one choice to move to */
1811 if (current->next == nullptr) {
1812 if (AirportSetBlocks(v, current, apc)) {
1813 v->pos = current->next_position;
1814 UpdateAircraftCache(v);
1815 } // move to next position
1816 return false;
1819 /* there are more choices to choose from, choose the one that
1820 * matches our heading */
1821 do {
1822 if (v->state == current->heading || current->heading == TO_ALL) {
1823 if (AirportSetBlocks(v, current, apc)) {
1824 v->pos = current->next_position;
1825 UpdateAircraftCache(v);
1826 } // move to next position
1827 return false;
1829 current = current->next;
1830 } while (current != nullptr);
1832 Debug(misc, 0, "[Ap] cannot move further on Airport! (pos {} state {}) for vehicle {}", v->pos, v->state, v->index);
1833 NOT_REACHED();
1836 /** returns true if the road ahead is busy, eg. you must wait before proceeding. */
1837 static bool AirportHasBlock(Aircraft *v, const AirportFTA *current_pos, const AirportFTAClass *apc)
1839 const AirportFTA *reference = &apc->layout[v->pos];
1840 const AirportFTA *next = &apc->layout[current_pos->next_position];
1842 /* same block, then of course we can move */
1843 if (apc->layout[current_pos->position].block != next->block) {
1844 const Station *st = Station::Get(v->targetairport);
1845 uint64 airport_flags = next->block;
1847 /* check additional possible extra blocks */
1848 if (current_pos != reference && current_pos->block != NOTHING_block) {
1849 airport_flags |= current_pos->block;
1852 if (st->airport.flags & airport_flags) {
1853 v->cur_speed = 0;
1854 v->subspeed = 0;
1855 return true;
1858 return false;
1862 * "reserve" a block for the plane
1863 * @param v airplane that requires the operation
1864 * @param current_pos of the vehicle in the list of blocks
1865 * @param apc airport on which block is requested to be set
1866 * @returns true on success. Eg, next block was free and we have occupied it
1868 static bool AirportSetBlocks(Aircraft *v, const AirportFTA *current_pos, const AirportFTAClass *apc)
1870 const AirportFTA *next = &apc->layout[current_pos->next_position];
1871 const AirportFTA *reference = &apc->layout[v->pos];
1873 /* if the next position is in another block, check it and wait until it is free */
1874 if ((apc->layout[current_pos->position].block & next->block) != next->block) {
1875 uint64 airport_flags = next->block;
1876 /* search for all all elements in the list with the same state, and blocks != N
1877 * this means more blocks should be checked/set */
1878 const AirportFTA *current = current_pos;
1879 if (current == reference) current = current->next;
1880 while (current != nullptr) {
1881 if (current->heading == current_pos->heading && current->block != 0) {
1882 airport_flags |= current->block;
1883 break;
1885 current = current->next;
1888 /* if the block to be checked is in the next position, then exclude that from
1889 * checking, because it has been set by the airplane before */
1890 if (current_pos->block == next->block) airport_flags ^= next->block;
1892 Station *st = Station::Get(v->targetairport);
1893 if (st->airport.flags & airport_flags) {
1894 v->cur_speed = 0;
1895 v->subspeed = 0;
1896 return false;
1899 if (next->block != NOTHING_block) {
1900 SETBITS(st->airport.flags, airport_flags); // occupy next block
1903 return true;
1907 * Combination of aircraft state for going to a certain terminal and the
1908 * airport flag for that terminal block.
1910 struct MovementTerminalMapping {
1911 AirportMovementStates state; ///< Aircraft movement state when going to this terminal.
1912 uint64 airport_flag; ///< Bitmask in the airport flags that need to be free for this terminal.
1915 /** A list of all valid terminals and their associated blocks. */
1916 static const MovementTerminalMapping _airport_terminal_mapping[] = {
1917 {TERM1, TERM1_block},
1918 {TERM2, TERM2_block},
1919 {TERM3, TERM3_block},
1920 {TERM4, TERM4_block},
1921 {TERM5, TERM5_block},
1922 {TERM6, TERM6_block},
1923 {TERM7, TERM7_block},
1924 {TERM8, TERM8_block},
1925 {HELIPAD1, HELIPAD1_block},
1926 {HELIPAD2, HELIPAD2_block},
1927 {HELIPAD3, HELIPAD3_block},
1931 * Find a free terminal or helipad, and if available, assign it.
1932 * @param v Aircraft looking for a free terminal or helipad.
1933 * @param i First terminal to examine.
1934 * @param last_terminal Terminal number to stop examining.
1935 * @return A terminal or helipad has been found, and has been assigned to the aircraft.
1937 static bool FreeTerminal(Aircraft *v, byte i, byte last_terminal)
1939 assert(last_terminal <= lengthof(_airport_terminal_mapping));
1940 Station *st = Station::Get(v->targetairport);
1941 for (; i < last_terminal; i++) {
1942 if ((st->airport.flags & _airport_terminal_mapping[i].airport_flag) == 0) {
1943 /* TERMINAL# HELIPAD# */
1944 v->state = _airport_terminal_mapping[i].state; // start moving to that terminal/helipad
1945 SETBITS(st->airport.flags, _airport_terminal_mapping[i].airport_flag); // occupy terminal/helipad
1946 return true;
1949 return false;
1953 * Get the number of terminals at the airport.
1954 * @param apc Airport description.
1955 * @return Number of terminals.
1957 static uint GetNumTerminals(const AirportFTAClass *apc)
1959 uint num = 0;
1961 for (uint i = apc->terminals[0]; i > 0; i--) num += apc->terminals[i];
1963 return num;
1967 * Find a free terminal, and assign it if available.
1968 * @param v Aircraft to handle.
1969 * @param apc Airport state machine.
1970 * @return Found a free terminal and assigned it.
1972 static bool AirportFindFreeTerminal(Aircraft *v, const AirportFTAClass *apc)
1974 /* example of more terminalgroups
1975 * {0,HANGAR,NOTHING_block,1}, {0,TERMGROUP,TERM_GROUP1_block,0}, {0,TERMGROUP,TERM_GROUP2_ENTER_block,1}, {0,0,N,1},
1976 * Heading TERMGROUP denotes a group. We see 2 groups here:
1977 * 1. group 0 -- TERM_GROUP1_block (check block)
1978 * 2. group 1 -- TERM_GROUP2_ENTER_block (check block)
1979 * First in line is checked first, group 0. If the block (TERM_GROUP1_block) is free, it
1980 * looks at the corresponding terminals of that group. If no free ones are found, other
1981 * possible groups are checked (in this case group 1, since that is after group 0). If that
1982 * fails, then attempt fails and plane waits
1984 if (apc->terminals[0] > 1) {
1985 const Station *st = Station::Get(v->targetairport);
1986 const AirportFTA *temp = apc->layout[v->pos].next;
1988 while (temp != nullptr) {
1989 if (temp->heading == TERMGROUP) {
1990 if (!(st->airport.flags & temp->block)) {
1991 /* read which group do we want to go to?
1992 * (the first free group) */
1993 uint target_group = temp->next_position + 1;
1995 /* at what terminal does the group start?
1996 * that means, sum up all terminals of
1997 * groups with lower number */
1998 uint group_start = 0;
1999 for (uint i = 1; i < target_group; i++) {
2000 group_start += apc->terminals[i];
2003 uint group_end = group_start + apc->terminals[target_group];
2004 if (FreeTerminal(v, group_start, group_end)) return true;
2006 } else {
2007 /* once the heading isn't 255, we've exhausted the possible blocks.
2008 * So we cannot move */
2009 return false;
2011 temp = temp->next;
2015 /* if there is only 1 terminalgroup, all terminals are checked (starting from 0 to max) */
2016 return FreeTerminal(v, 0, GetNumTerminals(apc));
2020 * Find a free helipad, and assign it if available.
2021 * @param v Aircraft to handle.
2022 * @param apc Airport state machine.
2023 * @return Found a free helipad and assigned it.
2025 static bool AirportFindFreeHelipad(Aircraft *v, const AirportFTAClass *apc)
2027 /* if an airport doesn't have helipads, use terminals */
2028 if (apc->num_helipads == 0) return AirportFindFreeTerminal(v, apc);
2030 /* only 1 helicoptergroup, check all helipads
2031 * The blocks for helipads start after the last terminal (MAX_TERMINALS) */
2032 return FreeTerminal(v, MAX_TERMINALS, apc->num_helipads + MAX_TERMINALS);
2036 * Handle the 'dest too far' flag and the corresponding news message for aircraft.
2037 * @param v The aircraft.
2038 * @param too_far True if the current destination is too far away.
2040 static void AircraftHandleDestTooFar(Aircraft *v, bool too_far)
2042 if (too_far) {
2043 if (!HasBit(v->flags, VAF_DEST_TOO_FAR)) {
2044 SetBit(v->flags, VAF_DEST_TOO_FAR);
2045 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
2046 AI::NewEvent(v->owner, new ScriptEventAircraftDestTooFar(v->index));
2047 if (v->owner == _local_company) {
2048 /* Post a news message. */
2049 SetDParam(0, v->index);
2050 AddVehicleAdviceNewsItem(STR_NEWS_AIRCRAFT_DEST_TOO_FAR, v->index);
2053 return;
2056 if (HasBit(v->flags, VAF_DEST_TOO_FAR)) {
2057 /* Not too far anymore, clear flag and message. */
2058 ClrBit(v->flags, VAF_DEST_TOO_FAR);
2059 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
2060 DeleteVehicleNews(v->index, STR_NEWS_AIRCRAFT_DEST_TOO_FAR);
2064 static bool AircraftEventHandler(Aircraft *v, int loop)
2066 if (v->vehstatus & VS_CRASHED) {
2067 return HandleCrashedAircraft(v);
2070 if (v->vehstatus & VS_STOPPED) return true;
2072 v->HandleBreakdown();
2074 HandleAircraftSmoke(v, loop != 0);
2075 ProcessOrders(v);
2076 v->HandleLoading(loop != 0);
2078 if (v->current_order.IsType(OT_LOADING) || v->current_order.IsType(OT_LEAVESTATION)) return true;
2080 if (v->state >= ENDTAKEOFF && v->state <= HELIENDLANDING) {
2081 /* If we are flying, unconditionally clear the 'dest too far' state. */
2082 AircraftHandleDestTooFar(v, false);
2083 } else if (v->acache.cached_max_range_sqr != 0) {
2084 /* Check the distance to the next destination. This code works because the target
2085 * airport is only updated after take off and not on the ground. */
2086 Station *cur_st = Station::GetIfValid(v->targetairport);
2087 Station *next_st = v->current_order.IsType(OT_GOTO_STATION) || v->current_order.IsType(OT_GOTO_DEPOT) ? Station::GetIfValid(v->current_order.GetDestination()) : nullptr;
2089 if (cur_st != nullptr && cur_st->airport.tile != INVALID_TILE && next_st != nullptr && next_st->airport.tile != INVALID_TILE) {
2090 uint dist = DistanceSquare(cur_st->airport.tile, next_st->airport.tile);
2091 AircraftHandleDestTooFar(v, dist > v->acache.cached_max_range_sqr);
2095 if (!HasBit(v->flags, VAF_DEST_TOO_FAR)) AirportGoToNextPosition(v);
2097 return true;
2100 bool Aircraft::Tick()
2102 if (!this->IsNormalAircraft()) return true;
2104 PerformanceAccumulator framerate(PFE_GL_AIRCRAFT);
2106 this->tick_counter++;
2108 if (!(this->vehstatus & VS_STOPPED)) this->running_ticks++;
2110 if (this->subtype == AIR_HELICOPTER) HelicopterTickHandler(this);
2112 this->current_order_time++;
2114 for (uint i = 0; i != 2; i++) {
2115 /* stop if the aircraft was deleted */
2116 if (!AircraftEventHandler(this, i)) return false;
2119 return true;
2124 * Returns aircraft's target station if v->target_airport
2125 * is a valid station with airport.
2126 * @param v vehicle to get target airport for
2127 * @return pointer to target station, nullptr if invalid
2129 Station *GetTargetAirportIfValid(const Aircraft *v)
2131 assert(v->type == VEH_AIRCRAFT);
2133 Station *st = Station::GetIfValid(v->targetairport);
2134 if (st == nullptr) return nullptr;
2136 return st->airport.tile == INVALID_TILE ? nullptr : st;
2140 * Updates the status of the Aircraft heading or in the station
2141 * @param st Station been updated
2143 void UpdateAirplanesOnNewStation(const Station *st)
2145 /* only 1 station is updated per function call, so it is enough to get entry_point once */
2146 const AirportFTAClass *ap = st->airport.GetFTA();
2147 Direction rotation = st->airport.tile == INVALID_TILE ? DIR_N : st->airport.rotation;
2149 for (Aircraft *v : Aircraft::Iterate()) {
2150 if (!v->IsNormalAircraft() || v->targetairport != st->index) continue;
2151 assert(v->state == FLYING);
2153 Order *o = &v->current_order;
2154 /* The aircraft is heading to a hangar, but the new station doesn't have one,
2155 * or the aircraft can't land on the new station. Cancel current order. */
2156 if (o->IsType(OT_GOTO_DEPOT) && !(o->GetDepotOrderType() & ODTFB_PART_OF_ORDERS) && o->GetDestination() == st->index &&
2157 (!st->airport.HasHangar() || !CanVehicleUseStation(v, st))) {
2158 o->MakeDummy();
2159 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
2161 v->pos = v->previous_pos = AircraftGetEntryPoint(v, ap, rotation);
2162 UpdateAircraftCache(v);
2165 /* Heliports don't have a hangar. Invalidate all go to hangar orders from all aircraft. */
2166 if (!st->airport.HasHangar()) RemoveOrderFromAllVehicles(OT_GOTO_DEPOT, st->index, true);