Rework the way the ReinitSeparation command is called. The old way was way too danger...
[openttd-joker.git] / src / aircraft_cmd.cpp
blob64aee61f4cf8ba0fe6a3e3edc395e72a8f1f660b
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * 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/>.
8 */
10 /**
11 * @file aircraft_cmd.cpp
12 * This file deals with aircraft and airport movements functionalities
15 #include "stdafx.h"
16 #include "aircraft.h"
17 #include "landscape.h"
18 #include "news_func.h"
19 #include "newgrf_engine.h"
20 #include "newgrf_sound.h"
21 #include "spritecache.h"
22 #include "strings_func.h"
23 #include "command_func.h"
24 #include "window_func.h"
25 #include "date_func.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"
41 #include "table/strings.h"
43 #include "safeguards.h"
45 void Aircraft::UpdateDeltaXY(Direction direction)
47 this->x_offs = -1;
48 this->y_offs = -1;
49 this->x_extent = 2;
50 this->y_extent = 2;
52 switch (this->subtype) {
53 default: NOT_REACHED();
55 case AIR_AIRCRAFT:
56 case AIR_HELICOPTER:
57 switch (this->state) {
58 default: break;
59 case ENDTAKEOFF:
60 case LANDING:
61 case HELILANDING:
62 case FLYING:
63 this->x_extent = 24;
64 this->y_extent = 24;
65 break;
67 this->z_extent = 5;
68 break;
70 case AIR_SHADOW:
71 this->z_extent = 1;
72 this->x_offs = 0;
73 this->y_offs = 0;
74 break;
76 case AIR_ROTOR:
77 this->z_extent = 1;
78 break;
82 static bool AirportMove(Aircraft *v, const AirportFTAClass *apc);
83 static bool AirportSetBlocks(Aircraft *v, const AirportFTA *current_pos, const AirportFTAClass *apc);
84 static bool AirportHasBlock(Aircraft *v, const AirportFTA *current_pos, const AirportFTAClass *apc);
85 static bool AirportFindFreeTerminal(Aircraft *v, const AirportFTAClass *apc);
86 static bool AirportFindFreeHelipad(Aircraft *v, const AirportFTAClass *apc);
87 static void CrashAirplane(Aircraft *v);
89 static const SpriteID _aircraft_sprite[] = {
90 0x0EB5, 0x0EBD, 0x0EC5, 0x0ECD,
91 0x0ED5, 0x0EDD, 0x0E9D, 0x0EA5,
92 0x0EAD, 0x0EE5, 0x0F05, 0x0F0D,
93 0x0F15, 0x0F1D, 0x0F25, 0x0F2D,
94 0x0EED, 0x0EF5, 0x0EFD, 0x0F35,
95 0x0E9D, 0x0EA5, 0x0EAD, 0x0EB5,
96 0x0EBD, 0x0EC5
99 template <>
100 bool IsValidImageIndex<VEH_AIRCRAFT>(uint8 image_index)
102 return image_index < lengthof(_aircraft_sprite);
105 /** Helicopter rotor animation states */
106 enum HelicopterRotorStates {
107 HRS_ROTOR_STOPPED,
108 HRS_ROTOR_MOVING_1,
109 HRS_ROTOR_MOVING_2,
110 HRS_ROTOR_MOVING_3,
114 * Find the nearest hangar to v
115 * INVALID_STATION is returned, if the company does not have any suitable
116 * airports (like helipads only)
117 * @param v vehicle looking for a hangar
118 * @return the StationID if one is found, otherwise, INVALID_STATION
120 static StationID FindNearestHangar(const Aircraft *v)
122 const Station *st;
123 uint best = 0;
124 StationID index = INVALID_STATION;
125 TileIndex vtile = TileVirtXY(v->x_pos, v->y_pos);
126 const AircraftVehicleInfo *avi = AircraftVehInfo(v->engine_type);
128 FOR_ALL_STATIONS(st) {
129 if (st->owner != v->owner || !(st->facilities & FACIL_AIRPORT)) continue;
131 const AirportFTAClass *afc = st->airport.GetFTA();
132 if (!st->airport.HasHangar() || (
133 /* don't crash the plane if we know it can't land at the airport */
134 (afc->flags & AirportFTAClass::SHORT_STRIP) &&
135 (avi->subtype & AIR_FAST) &&
136 !_cheats.no_jetcrash.value)) {
137 continue;
140 /* v->tile can't be used here, when aircraft is flying v->tile is set to 0 */
141 uint distance = DistanceSquare(vtile, st->airport.tile);
142 if (v->acache.cached_max_range_sqr != 0) {
143 /* Check if our current destination can be reached from the depot airport. */
144 const Station *cur_dest = GetTargetAirportIfValid(v);
145 if (cur_dest != nullptr && DistanceSquare(st->airport.tile, cur_dest->airport.tile) > v->acache.cached_max_range_sqr) continue;
147 if (distance < best || index == INVALID_STATION) {
148 best = distance;
149 index = st->index;
152 return index;
155 void Aircraft::GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const
157 uint8 spritenum = this->spritenum;
159 if (is_custom_sprite(spritenum)) {
160 GetCustomVehicleSprite(this, direction, image_type, result);
161 if (result->IsValid()) return;
163 spritenum = this->GetEngine()->original_image_index;
166 assert(IsValidImageIndex<VEH_AIRCRAFT>(spritenum));
167 result->Set(direction + _aircraft_sprite[spritenum]);
170 void GetRotorImage(const Aircraft *v, EngineImageType image_type, VehicleSpriteSeq *result)
172 assert(v->subtype == AIR_HELICOPTER);
174 const Aircraft *w = v->Next()->Next();
175 if (is_custom_sprite(v->spritenum)) {
176 GetCustomRotorSprite(v, false, image_type, result);
177 if (result->IsValid()) return;
180 /* Return standard rotor sprites if there are no custom sprites for this helicopter */
181 result->Set(SPR_ROTOR_STOPPED + w->state);
184 static void GetAircraftIcon(EngineID engine, EngineImageType image_type, VehicleSpriteSeq *result)
186 const Engine *e = Engine::Get(engine);
187 uint8 spritenum = e->u.air.image_index;
189 if (is_custom_sprite(spritenum)) {
190 GetCustomVehicleIcon(engine, DIR_W, image_type, result);
191 if (result->IsValid()) return;
193 spritenum = e->original_image_index;
196 assert(IsValidImageIndex<VEH_AIRCRAFT>(spritenum));
197 result->Set(DIR_W + _aircraft_sprite[spritenum]);
200 void DrawAircraftEngine(int left, int right, int preferred_x, int y, EngineID engine, PaletteID pal, EngineImageType image_type)
202 VehicleSpriteSeq seq;
203 GetAircraftIcon(engine, image_type, &seq);
205 Rect16 rect = seq.GetBounds();
206 preferred_x = Clamp(preferred_x,
207 left - UnScaleGUI(rect.left),
208 right - UnScaleGUI(rect.right));
210 seq.Draw(preferred_x, y, pal, pal == PALETTE_CRASH);
212 if (!(AircraftVehInfo(engine)->subtype & AIR_CTOL)) {
213 VehicleSpriteSeq rotor_seq;
214 GetCustomRotorIcon(engine, image_type, &rotor_seq);
215 if (!rotor_seq.IsValid()) rotor_seq.Set(SPR_ROTOR_STOPPED);
216 rotor_seq.Draw(preferred_x, y - ScaleGUITrad(5), PAL_NONE, false);
221 * Get the size of the sprite of an aircraft sprite heading west (used for lists).
222 * @param engine The engine to get the sprite from.
223 * @param[out] width The width of the sprite.
224 * @param[out] height The height of the sprite.
225 * @param[out] xoffs Number of pixels to shift the sprite to the right.
226 * @param[out] yoffs Number of pixels to shift the sprite downwards.
227 * @param image_type Context the sprite is used in.
229 void GetAircraftSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type)
231 VehicleSpriteSeq seq;
232 GetAircraftIcon(engine, image_type, &seq);
234 Rect16 rect = seq.GetBounds();
236 width = UnScaleGUI(rect.right - rect.left + 1);
237 height = UnScaleGUI(rect.bottom - rect.top + 1);
238 xoffs = UnScaleGUI(rect.left);
239 yoffs = UnScaleGUI(rect.top);
243 * Build an aircraft.
244 * @param tile tile of the depot where aircraft is built.
245 * @param flags type of operation.
246 * @param e the engine to build.
247 * @param data unused.
248 * @param ret[out] the vehicle that has been built.
249 * @return the cost of this operation or an error.
251 CommandCost CmdBuildAircraft(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **ret)
253 const AircraftVehicleInfo *avi = &e->u.air;
254 const Station *st = Station::GetByTile(tile);
256 /* Prevent building aircraft types at places which can't handle them */
257 if (!CanVehicleUseStation(e->index, st)) return CommandError();
259 /* Make sure all aircraft end up in the first tile of the hangar. */
260 tile = st->airport.GetHangarTile(st->airport.GetHangarNum(tile));
262 if (flags & DC_EXEC) {
263 Aircraft *v = new Aircraft(); // aircraft
264 Aircraft *u = new Aircraft(); // shadow
265 *ret = v;
267 v->direction = DIR_SE;
269 v->owner = u->owner = _current_company;
271 v->tile = tile;
273 uint x = TileX(tile) * TILE_SIZE + 5;
274 uint y = TileY(tile) * TILE_SIZE + 3;
276 v->x_pos = u->x_pos = x;
277 v->y_pos = u->y_pos = y;
279 u->z_pos = GetSlopePixelZ(x, y);
280 v->z_pos = u->z_pos + 1;
282 v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL;
283 u->vehstatus = VS_HIDDEN | VS_UNCLICKABLE | VS_SHADOW;
285 v->spritenum = avi->image_index;
287 v->cargo_cap = avi->passenger_capacity;
288 v->refit_cap = 0;
289 u->cargo_cap = avi->mail_capacity;
290 u->refit_cap = 0;
292 v->cargo_type = e->GetDefaultCargoType();
293 u->cargo_type = CT_MAIL;
295 v->name = nullptr;
296 v->last_station_visited = INVALID_STATION;
297 v->last_loading_station = INVALID_STATION;
299 v->acceleration = avi->acceleration;
300 v->engine_type = e->index;
301 u->engine_type = e->index;
303 v->subtype = (avi->subtype & AIR_CTOL ? AIR_AIRCRAFT : AIR_HELICOPTER);
304 v->UpdateDeltaXY(INVALID_DIR);
306 u->subtype = AIR_SHADOW;
307 u->UpdateDeltaXY(INVALID_DIR);
309 v->reliability = e->reliability;
310 v->reliability_spd_dec = e->reliability_spd_dec;
311 v->max_age = e->GetLifeLengthInDays();
313 _new_vehicle_id = v->index;
315 v->pos = GetVehiclePosOnBuild(tile);
317 v->state = HANGAR;
318 v->previous_pos = v->pos;
319 v->targetairport = GetStationIndex(tile);
320 v->SetNext(u);
322 v->SetServiceInterval(Company::Get(_current_company)->settings.vehicle.servint_aircraft);
324 v->date_of_last_service = _date;
325 v->build_year = u->build_year = _cur_year;
327 v->sprite_seq.Set(SPR_IMG_QUERY);
328 u->sprite_seq.Set(SPR_IMG_QUERY);
330 v->random_bits = VehicleRandomBits();
331 u->random_bits = VehicleRandomBits();
333 v->vehicle_flags = 0;
334 if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) SetBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE);
335 v->SetServiceIntervalIsPercent(Company::Get(_current_company)->settings.vehicle.servint_ispercent);
337 v->InvalidateNewGRFCacheOfChain();
339 v->cargo_cap = e->DetermineCapacity(v, &u->cargo_cap);
341 v->InvalidateNewGRFCacheOfChain();
343 UpdateAircraftCache(v, true);
345 v->UpdatePosition();
346 u->UpdatePosition();
348 /* Aircraft with 3 vehicles (chopper)? */
349 if (v->subtype == AIR_HELICOPTER) {
350 Aircraft *w = new Aircraft();
351 w->engine_type = e->index;
352 w->direction = DIR_N;
353 w->owner = _current_company;
354 w->x_pos = v->x_pos;
355 w->y_pos = v->y_pos;
356 w->z_pos = v->z_pos + ROTOR_Z_OFFSET;
357 w->vehstatus = VS_HIDDEN | VS_UNCLICKABLE;
358 w->spritenum = 0xFF;
359 w->subtype = AIR_ROTOR;
360 w->sprite_seq.Set(SPR_ROTOR_STOPPED);
361 w->UpdateSpriteSeqBound();
362 w->random_bits = VehicleRandomBits();
363 /* Use rotor's air.state to store the rotor animation frame */
364 w->state = HRS_ROTOR_STOPPED;
365 w->UpdateDeltaXY(INVALID_DIR);
367 u->SetNext(w);
368 w->UpdatePosition();
372 return CommandCost();
376 bool Aircraft::FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
378 const Station *st = GetTargetAirportIfValid(this);
379 /* If the station is not a valid airport or if it has no hangars */
380 if (st == nullptr || !st->airport.HasHangar()) {
381 /* the aircraft has to search for a hangar on its own */
382 StationID station = FindNearestHangar(this);
384 if (station == INVALID_STATION) return false;
386 st = Station::Get(station);
389 if (location != nullptr) *location = st->xy;
390 if (destination != nullptr) *destination = st->index;
392 return true;
395 static void CheckIfAircraftNeedsService(Aircraft *v)
397 if (Company::Get(v->owner)->settings.vehicle.servint_aircraft == 0 || !v->NeedsAutomaticServicing()) return;
398 if (v->IsChainInDepot()) {
399 VehicleServiceInDepot(v);
400 return;
403 /* When we're parsing conditional orders and the like
404 * we don't want to consider going to a depot too. */
405 if (!v->current_order.IsType(OT_GOTO_DEPOT) && !v->current_order.IsType(OT_GOTO_STATION)) return;
407 const Station *st = Station::Get(v->current_order.GetDestination());
409 assert(st != nullptr);
411 /* only goto depot if the target airport has a depot */
412 if (st->airport.HasHangar() && CanVehicleUseStation(v, st)) {
413 v->current_order.MakeGoToDepot(st->index, ODTFB_SERVICE);
414 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
415 } else if (v->current_order.IsType(OT_GOTO_DEPOT)) {
416 v->current_order.MakeDummy();
417 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
421 Money Aircraft::GetRunningCost() const
423 const Engine *e = this->GetEngine();
424 uint cost_factor = GetVehicleProperty(this, PROP_AIRCRAFT_RUNNING_COST_FACTOR, e->u.air.running_cost);
425 return GetPrice(PR_RUNNING_AIRCRAFT, cost_factor, e->GetGRF());
428 void Aircraft::OnNewDay()
430 if (!this->IsNormalAircraft()) return;
432 if ((++this->day_counter & 7) == 0) DecreaseVehicleValue(this);
434 CheckOrders(this);
436 CheckVehicleBreakdown(this);
437 AgeVehicle(this);
438 CheckIfAircraftNeedsService(this);
440 if (this->running_ticks == 0) return;
442 CommandCost cost(EXPENSES_AIRCRAFT_RUN, this->GetRunningCost() * this->running_ticks / (DAYS_IN_YEAR * DAY_TICKS));
444 this->profit_this_year -= cost.GetCost();
445 this->running_ticks = 0;
447 SubtractMoneyFromCompanyFract(this->owner, cost);
449 SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
450 SetWindowClassesDirty(WC_AIRCRAFT_LIST);
453 static void HelicopterTickHandler(Aircraft *v)
455 Aircraft *u = v->Next()->Next();
457 if (u->vehstatus & VS_HIDDEN) return;
459 /* if true, helicopter rotors do not rotate. This should only be the case if a helicopter is
460 * loading/unloading at a terminal or stopped */
461 if (v->current_order.IsType(OT_LOADING) || (v->vehstatus & VS_STOPPED)) {
462 if (u->cur_speed != 0) {
463 u->cur_speed++;
464 if (u->cur_speed >= 0x80 && u->state == HRS_ROTOR_MOVING_3) {
465 u->cur_speed = 0;
468 } else {
469 if (u->cur_speed == 0) {
470 u->cur_speed = 0x70;
472 if (u->cur_speed >= 0x50) {
473 u->cur_speed--;
477 int tick = ++u->tick_counter;
478 int spd = u->cur_speed >> 4;
480 VehicleSpriteSeq seq;
481 if (spd == 0) {
482 u->state = HRS_ROTOR_STOPPED;
483 GetRotorImage(v, EIT_ON_MAP, &seq);
484 if (u->sprite_seq == seq) return;
485 } else if (tick >= spd) {
486 u->tick_counter = 0;
487 u->state++;
488 if (u->state > HRS_ROTOR_MOVING_3) u->state = HRS_ROTOR_MOVING_1;
489 GetRotorImage(v, EIT_ON_MAP, &seq);
490 } else {
491 return;
494 u->sprite_seq = seq;
495 u->UpdateSpriteSeqBound();
497 u->UpdatePositionAndViewport();
501 * Set aircraft position.
502 * @param v Aircraft to position.
503 * @param x New X position.
504 * @param y New y position.
505 * @param z New z position.
507 void SetAircraftPosition(Aircraft *v, int x, int y, int z)
509 v->x_pos = x;
510 v->y_pos = y;
511 v->z_pos = z;
513 v->UpdatePosition();
514 v->UpdateViewport(true, false);
515 if (v->subtype == AIR_HELICOPTER) {
516 Aircraft *rotor = v->Next()->Next();
517 GetRotorImage(v, EIT_ON_MAP, &rotor->sprite_seq);
518 rotor->UpdateSpriteSeqBound();
521 Aircraft *u = v->Next();
523 int safe_x = Clamp(x, 0, MapMaxX() * TILE_SIZE);
524 int safe_y = Clamp(y - 1, 0, MapMaxY() * TILE_SIZE);
525 u->x_pos = x;
526 u->y_pos = y - ((v->z_pos - GetSlopePixelZ(safe_x, safe_y)) >> 3);
528 safe_y = Clamp(u->y_pos, 0, MapMaxY() * TILE_SIZE);
529 u->z_pos = GetSlopePixelZ(safe_x, safe_y);
530 u->sprite_seq.CopyWithoutPalette(v->sprite_seq); // the shadow is never coloured
531 u->sprite_seq_bounds = v->sprite_seq_bounds;
533 u->UpdatePositionAndViewport();
535 u = u->Next();
536 if (u != nullptr) {
537 u->x_pos = x;
538 u->y_pos = y;
539 u->z_pos = z + ROTOR_Z_OFFSET;
541 u->UpdatePositionAndViewport();
546 * Handle Aircraft specific tasks when an Aircraft enters a hangar
547 * @param *v Vehicle that enters the hangar
549 void HandleAircraftEnterHangar(Aircraft *v)
551 v->subspeed = 0;
552 v->progress = 0;
554 Aircraft *u = v->Next();
555 u->vehstatus |= VS_HIDDEN;
556 u = u->Next();
557 if (u != nullptr) {
558 u->vehstatus |= VS_HIDDEN;
559 u->cur_speed = 0;
562 SetAircraftPosition(v, v->x_pos, v->y_pos, v->z_pos);
565 static void PlayAircraftSound(const Vehicle *v)
567 if (!PlayVehicleSound(v, VSE_START)) {
568 SndPlayVehicleFx(AircraftVehInfo(v->engine_type)->sfx, v);
574 * Update cached values of an aircraft.
575 * Currently caches callback 36 max speed.
576 * @param v Vehicle
577 * @param update_range Update the aircraft range.
579 void UpdateAircraftCache(Aircraft *v, bool update_range)
581 uint max_speed = GetVehicleProperty(v, PROP_AIRCRAFT_SPEED, 0);
582 if (max_speed != 0) {
583 /* Convert from original units to km-ish/h */
584 max_speed = (max_speed * 128) / 10;
586 v->vcache.cached_max_speed = max_speed;
587 } else {
588 /* Use the default max speed of the vehicle. */
589 v->vcache.cached_max_speed = AircraftVehInfo(v->engine_type)->max_speed;
592 /* Update cargo aging period. */
593 v->vcache.cached_cargo_age_period = GetVehicleProperty(v, PROP_AIRCRAFT_CARGO_AGE_PERIOD, EngInfo(v->engine_type)->cargo_age_period);
594 Aircraft *u = v->Next(); // Shadow for mail
595 u->vcache.cached_cargo_age_period = GetVehicleProperty(u, PROP_AIRCRAFT_CARGO_AGE_PERIOD, EngInfo(u->engine_type)->cargo_age_period);
597 /* Update aircraft range. */
598 if (update_range) {
599 v->acache.cached_max_range = GetVehicleProperty(v, PROP_AIRCRAFT_RANGE, AircraftVehInfo(v->engine_type)->max_range);
600 /* Squared it now so we don't have to do it later all the time. */
601 v->acache.cached_max_range_sqr = v->acache.cached_max_range * v->acache.cached_max_range;
607 * Special velocities for aircraft
609 enum AircraftSpeedLimits {
610 SPEED_LIMIT_TAXI = 50, ///< Maximum speed of an aircraft while taxiing
611 SPEED_LIMIT_APPROACH = 230, ///< Maximum speed of an aircraft on finals
612 SPEED_LIMIT_BROKEN = 320, ///< Maximum speed of an aircraft that is broken
613 SPEED_LIMIT_HOLD = 425, ///< Maximum speed of an aircraft that flies the holding pattern
614 SPEED_LIMIT_NONE = 0xFFFF, ///< No environmental speed limit. Speed limit is type dependent
618 * Sets the new speed for an aircraft
619 * @param v The vehicle for which the speed should be obtained
620 * @param speed_limit The maximum speed the vehicle may have.
621 * @param hard_limit If true, the limit is directly enforced, otherwise the plane is slowed down gradually
622 * @return The number of position updates needed within the tick
624 static int UpdateAircraftSpeed(Aircraft *v, uint speed_limit = SPEED_LIMIT_NONE, bool hard_limit = true)
627 * 'acceleration' has the unit 3/8 mph/tick. This function is called twice per tick.
628 * So the speed amount we need to accelerate is:
629 * acceleration * 3 / 16 mph = acceleration * 3 / 16 * 16 / 10 km-ish/h
630 * = acceleration * 3 / 10 * 256 * (km-ish/h / 256)
631 * ~ acceleration * 77 (km-ish/h / 256)
633 uint spd = v->acceleration * 77;
634 byte t;
636 /* Adjust speed limits by plane speed factor to prevent taxiing
637 * and take-off speeds being too low. */
638 speed_limit *= _settings_game.vehicle.plane_speed;
640 if (v->vcache.cached_max_speed < speed_limit) {
641 if (v->cur_speed < speed_limit) hard_limit = false;
642 speed_limit = v->vcache.cached_max_speed;
645 v->subspeed = (t = v->subspeed) + (byte)spd;
647 /* Aircraft's current speed is used twice so that very fast planes are
648 * forced to slow down rapidly in the short distance needed. The magic
649 * value 16384 was determined to give similar results to the old speed/48
650 * method at slower speeds. This also results in less reduction at slow
651 * speeds to that aircraft do not get to taxi speed straight after
652 * touchdown. */
653 if (!hard_limit && v->cur_speed > speed_limit) {
654 speed_limit = v->cur_speed - max(1, ((v->cur_speed * v->cur_speed) / 16384) / _settings_game.vehicle.plane_speed);
657 spd = min(v->cur_speed + (spd >> 8) + (v->subspeed < t), speed_limit);
659 /* adjust speed for broken vehicles */
660 if (v->vehstatus & VS_AIRCRAFT_BROKEN) spd = min(spd, SPEED_LIMIT_BROKEN);
662 /* updates statusbar only if speed have changed to save CPU time */
663 if (spd != v->cur_speed) {
664 v->cur_speed = spd;
665 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
668 /* Adjust distance moved by plane speed setting */
669 if (_settings_game.vehicle.plane_speed > 1) spd /= _settings_game.vehicle.plane_speed;
671 /* Convert direction-independent speed into direction-dependent speed. (old movement method) */
672 spd = v->GetOldAdvanceSpeed(spd);
674 spd += v->progress;
675 v->progress = (byte)spd;
676 return spd >> 8;
680 * Get the tile height below the aircraft.
681 * This function is needed because aircraft can leave the mapborders.
683 * @param v The vehicle to get the height for.
684 * @return The height in pixels from 'z_pos' 0.
686 int GetTileHeightBelowAircraft(const Vehicle *v)
688 int safe_x = Clamp(v->x_pos, 0, MapMaxX() * TILE_SIZE);
689 int safe_y = Clamp(v->y_pos, 0, MapMaxY() * TILE_SIZE);
690 return TileHeight(TileVirtXY(safe_x, safe_y)) * TILE_HEIGHT;
694 * Get the 'flight level' bounds, in pixels from 'z_pos' 0 for a particular
695 * vehicle for normal flight situation.
696 * When the maximum is reached the vehicle should consider descending.
697 * When the minimum is reached the vehicle should consider ascending.
699 * @param v The vehicle to get the flight levels for.
700 * @param [out] min_level The minimum bounds for flight level.
701 * @param [out] max_level The maximum bounds for flight level.
703 void GetAircraftFlightLevelBounds(const Vehicle *v, int *min_level, int *max_level)
705 int base_altitude = GetTileHeightBelowAircraft(v);
706 if (v->type == VEH_AIRCRAFT && Aircraft::From(v)->subtype == AIR_HELICOPTER) {
707 base_altitude += HELICOPTER_HOLD_MAX_FLYING_ALTITUDE - PLANE_HOLD_MAX_FLYING_ALTITUDE;
710 /* Make sure eastbound and westbound planes do not "crash" into each
711 * other by providing them with vertical separation
713 switch (v->direction) {
714 case DIR_N:
715 case DIR_NE:
716 case DIR_E:
717 case DIR_SE:
718 base_altitude += 10;
719 break;
721 default: break;
724 /* Make faster planes fly higher so that they can overtake slower ones */
725 base_altitude += min(20 * (v->vcache.cached_max_speed / 200) - 90, 0);
727 if (min_level != nullptr) *min_level = base_altitude + AIRCRAFT_MIN_FLYING_ALTITUDE;
728 if (max_level != nullptr) *max_level = base_altitude + AIRCRAFT_MAX_FLYING_ALTITUDE;
732 * Gets the maximum 'flight level' for the holding pattern of the aircraft,
733 * in pixels 'z_pos' 0, depending on terrain below..
735 * @param v The aircraft that may or may not need to decrease its altitude.
736 * @return Maximal aircraft holding altitude, while in normal flight, in pixels.
738 int GetAircraftHoldMaxAltitude(const Aircraft *v)
740 int tile_height = GetTileHeightBelowAircraft(v);
742 return tile_height + ((v->subtype == AIR_HELICOPTER) ? HELICOPTER_HOLD_MAX_FLYING_ALTITUDE : PLANE_HOLD_MAX_FLYING_ALTITUDE);
745 template <class T>
746 int GetAircraftFlightLevel(T *v, bool takeoff)
748 /* Aircraft is in flight. We want to enforce it being somewhere
749 * between the minimum and the maximum allowed altitude. */
750 int aircraft_min_altitude;
751 int aircraft_max_altitude;
752 GetAircraftFlightLevelBounds(v, &aircraft_min_altitude, &aircraft_max_altitude);
753 int aircraft_middle_altitude = (aircraft_min_altitude + aircraft_max_altitude) / 2;
755 /* If those assumptions would be violated, aircrafts would behave fairly strange. */
756 assert(aircraft_min_altitude < aircraft_middle_altitude);
757 assert(aircraft_middle_altitude < aircraft_max_altitude);
759 int z = v->z_pos;
760 if (z < aircraft_min_altitude ||
761 (HasBit(v->flags, VAF_IN_MIN_HEIGHT_CORRECTION) && z < aircraft_middle_altitude)) {
762 /* Ascend. And don't fly into that mountain right ahead.
763 * And avoid our aircraft become a stairclimber, so if we start
764 * correcting altitude, then we stop correction not too early. */
765 SetBit(v->flags, VAF_IN_MIN_HEIGHT_CORRECTION);
766 z += takeoff ? 2 : 1;
767 } else if (!takeoff && (z > aircraft_max_altitude ||
768 (HasBit(v->flags, VAF_IN_MAX_HEIGHT_CORRECTION) && z > aircraft_middle_altitude))) {
769 /* Descend lower. You are an aircraft, not an space ship.
770 * And again, don't stop correcting altitude too early. */
771 SetBit(v->flags, VAF_IN_MAX_HEIGHT_CORRECTION);
772 z--;
773 } else if (HasBit(v->flags, VAF_IN_MIN_HEIGHT_CORRECTION) && z >= aircraft_middle_altitude) {
774 /* Now, we have corrected altitude enough. */
775 ClrBit(v->flags, VAF_IN_MIN_HEIGHT_CORRECTION);
776 } else if (HasBit(v->flags, VAF_IN_MAX_HEIGHT_CORRECTION) && z <= aircraft_middle_altitude) {
777 /* Now, we have corrected altitude enough. */
778 ClrBit(v->flags, VAF_IN_MAX_HEIGHT_CORRECTION);
781 return z;
784 template int GetAircraftFlightLevel(DisasterVehicle *v, bool takeoff);
787 * Find the entry point to an airport depending on direction which
788 * the airport is being approached from. Each airport can have up to
789 * four entry points for its approach system so that approaching
790 * aircraft do not fly through each other or are forced to do 180
791 * degree turns during the approach. The arrivals are grouped into
792 * four sectors dependent on the DiagDirection from which the airport
793 * is approached.
795 * @param v The vehicle that is approaching the airport
796 * @param apc The Airport Class being approached.
797 * @param rotation The rotation of the airport.
798 * @return The index of the entry point
800 static byte AircraftGetEntryPoint(const Aircraft *v, const AirportFTAClass *apc, Direction rotation)
802 assert(v != nullptr);
803 assert(apc != nullptr);
805 /* In the case the station doesn't exit anymore, set target tile 0.
806 * It doesn't hurt much, aircraft will go to next order, nearest hangar
807 * or it will simply crash in next tick */
808 TileIndex tile = 0;
810 const Station *st = Station::GetIfValid(v->targetairport);
811 if (st != nullptr) {
812 /* Make sure we don't go to INVALID_TILE if the airport has been removed. */
813 tile = (st->airport.tile != INVALID_TILE) ? st->airport.tile : st->xy;
816 int delta_x = v->x_pos - TileX(tile) * TILE_SIZE;
817 int delta_y = v->y_pos - TileY(tile) * TILE_SIZE;
819 DiagDirection dir;
820 if (abs(delta_y) < abs(delta_x)) {
821 /* We are northeast or southwest of the airport */
822 dir = delta_x < 0 ? DIAGDIR_NE : DIAGDIR_SW;
823 } else {
824 /* We are northwest or southeast of the airport */
825 dir = delta_y < 0 ? DIAGDIR_NW : DIAGDIR_SE;
827 dir = ChangeDiagDir(dir, DiagDirDifference(DIAGDIR_NE, DirToDiagDir(rotation)));
828 return apc->entry_points[dir];
832 static void MaybeCrashAirplane(Aircraft *v);
835 * Controls the movement of an aircraft. This function actually moves the vehicle
836 * on the map and takes care of minor things like sound playback.
837 * @todo De-mystify the cur_speed values for helicopter rotors.
838 * @param v The vehicle that is moved. Must be the first vehicle of the chain
839 * @return Whether the position requested by the State Machine has been reached
841 static bool AircraftController(Aircraft *v)
843 int count;
845 /* nullptr if station is invalid */
846 const Station *st = Station::GetIfValid(v->targetairport);
847 /* INVALID_TILE if there is no station */
848 TileIndex tile = INVALID_TILE;
849 Direction rotation = DIR_N;
850 uint size_x = 1, size_y = 1;
851 if (st != nullptr) {
852 if (st->airport.tile != INVALID_TILE) {
853 tile = st->airport.tile;
854 rotation = st->airport.rotation;
855 size_x = st->airport.w;
856 size_y = st->airport.h;
857 } else {
858 tile = st->xy;
861 /* DUMMY if there is no station or no airport */
862 const AirportFTAClass *afc = tile == INVALID_TILE ? GetAirport(AT_DUMMY) : st->airport.GetFTA();
864 /* prevent going to INVALID_TILE if airport is deleted. */
865 if (st == nullptr || st->airport.tile == INVALID_TILE) {
866 /* Jump into our "holding pattern" state machine if possible */
867 if (v->pos >= afc->nofelements) {
868 v->pos = v->previous_pos = AircraftGetEntryPoint(v, afc, DIR_N);
869 } else if (v->targetairport != v->current_order.GetDestination()) {
870 /* If not possible, just get out of here fast */
871 v->state = FLYING;
872 UpdateAircraftCache(v);
873 AircraftNextAirportPos_and_Order(v);
874 /* get aircraft back on running altitude */
875 SetAircraftPosition(v, v->x_pos, v->y_pos, GetAircraftFlightLevel(v));
876 return false;
880 /* get airport moving data */
881 const AirportMovingData amd = RotateAirportMovingData(afc->MovingData(v->pos), rotation, size_x, size_y);
883 int x = TileX(tile) * TILE_SIZE;
884 int y = TileY(tile) * TILE_SIZE;
886 /* Helicopter raise */
887 if (amd.flag & AMED_HELI_RAISE) {
888 Aircraft *u = v->Next()->Next();
890 /* Make sure the rotors don't rotate too fast */
891 if (u->cur_speed > 32) {
892 v->cur_speed = 0;
893 if (--u->cur_speed == 32) {
894 if (!PlayVehicleSound(v, VSE_START)) {
895 SndPlayVehicleFx(SND_18_HELICOPTER, v);
898 } else {
899 u->cur_speed = 32;
900 count = UpdateAircraftSpeed(v);
901 if (count > 0) {
902 v->tile = 0;
904 int z_dest;
905 GetAircraftFlightLevelBounds(v, &z_dest, nullptr);
907 /* Reached altitude? */
908 if (v->z_pos >= z_dest) {
909 v->cur_speed = 0;
910 return true;
912 SetAircraftPosition(v, v->x_pos, v->y_pos, min(v->z_pos + count, z_dest));
915 return false;
918 /* Helicopter landing. */
919 if (amd.flag & AMED_HELI_LOWER) {
920 if (st == nullptr) {
921 /* FIXME - AircraftController -> if station no longer exists, do not land
922 * helicopter will circle until sign disappears, then go to next order
923 * what to do when it is the only order left, right now it just stays in 1 place */
924 v->state = FLYING;
925 UpdateAircraftCache(v);
926 AircraftNextAirportPos_and_Order(v);
927 return false;
930 /* Vehicle is now at the airport. */
931 v->tile = tile;
933 /* Find altitude of landing position. */
934 int z = GetSlopePixelZ(x, y) + 1 + afc->delta_z;
936 if (z == v->z_pos) {
937 Vehicle *u = v->Next()->Next();
939 /* Increase speed of rotors. When speed is 80, we've landed. */
940 if (u->cur_speed >= 80) return true;
941 u->cur_speed += 4;
942 } else {
943 count = UpdateAircraftSpeed(v);
944 if (count > 0) {
945 if (v->z_pos > z) {
946 SetAircraftPosition(v, v->x_pos, v->y_pos, max(v->z_pos - count, z));
947 } else {
948 SetAircraftPosition(v, v->x_pos, v->y_pos, min(v->z_pos + count, z));
952 return false;
955 /* Get distance from destination pos to current pos. */
956 uint dist = abs(x + amd.x - v->x_pos) + abs(y + amd.y - v->y_pos);
958 /* Need exact position? */
959 if (!(amd.flag & AMED_EXACTPOS) && dist <= (amd.flag & AMED_SLOWTURN ? 8U : 4U)) return true;
961 /* At final pos? */
962 if (dist == 0) {
963 /* Change direction smoothly to final direction. */
964 DirDiff dirdiff = DirDifference(amd.direction, v->direction);
965 /* if distance is 0, and plane points in right direction, no point in calling
966 * UpdateAircraftSpeed(). So do it only afterwards */
967 if (dirdiff == DIRDIFF_SAME) {
968 v->cur_speed = 0;
969 return true;
972 if (!UpdateAircraftSpeed(v, SPEED_LIMIT_TAXI)) return false;
974 v->direction = ChangeDir(v->direction, dirdiff > DIRDIFF_REVERSE ? DIRDIFF_45LEFT : DIRDIFF_45RIGHT);
975 v->cur_speed >>= 1;
977 SetAircraftPosition(v, v->x_pos, v->y_pos, v->z_pos);
978 return false;
981 if (amd.flag & AMED_BRAKE && v->cur_speed > SPEED_LIMIT_TAXI * _settings_game.vehicle.plane_speed) {
982 MaybeCrashAirplane(v);
983 if ((v->vehstatus & VS_CRASHED) != 0) return false;
986 uint speed_limit = SPEED_LIMIT_TAXI;
987 bool hard_limit = true;
989 if (amd.flag & AMED_NOSPDCLAMP) speed_limit = SPEED_LIMIT_NONE;
990 if (amd.flag & AMED_HOLD) { speed_limit = SPEED_LIMIT_HOLD; hard_limit = false; }
991 if (amd.flag & AMED_LAND) { speed_limit = SPEED_LIMIT_APPROACH; hard_limit = false; }
992 if (amd.flag & AMED_BRAKE) { speed_limit = SPEED_LIMIT_TAXI; hard_limit = false; }
994 count = UpdateAircraftSpeed(v, speed_limit, hard_limit);
995 if (count == 0) return false;
997 if (v->turn_counter != 0) v->turn_counter--;
999 do {
1001 GetNewVehiclePosResult gp;
1003 if (dist < 4 || (amd.flag & AMED_LAND)) {
1004 /* move vehicle one pixel towards target */
1005 gp.x = (v->x_pos != (x + amd.x)) ?
1006 v->x_pos + ((x + amd.x > v->x_pos) ? 1 : -1) :
1007 v->x_pos;
1008 gp.y = (v->y_pos != (y + amd.y)) ?
1009 v->y_pos + ((y + amd.y > v->y_pos) ? 1 : -1) :
1010 v->y_pos;
1012 /* Oilrigs must keep v->tile as st->airport.tile, since the landing pad is in a non-airport tile */
1013 gp.new_tile = (st->airport.type == AT_OILRIG) ? st->airport.tile : TileVirtXY(gp.x, gp.y);
1015 } else {
1017 /* Turn. Do it slowly if in the air. */
1018 Direction newdir = GetDirectionTowards(v, x + amd.x, y + amd.y);
1019 if (newdir != v->direction) {
1020 if (amd.flag & AMED_SLOWTURN && v->number_consecutive_turns < 8 && v->subtype == AIR_AIRCRAFT) {
1021 if (v->turn_counter == 0 || newdir == v->last_direction) {
1022 if (newdir == v->last_direction) {
1023 v->number_consecutive_turns = 0;
1024 } else {
1025 v->number_consecutive_turns++;
1027 v->turn_counter = 2 * _settings_game.vehicle.plane_speed;
1028 v->last_direction = v->direction;
1029 v->direction = newdir;
1032 /* Move vehicle. */
1033 gp = GetNewVehiclePos(v);
1034 } else {
1035 v->cur_speed >>= 1;
1036 v->direction = newdir;
1038 /* When leaving a terminal an aircraft often goes to a position
1039 * directly in front of it. If it would move while turning it
1040 * would need an two extra turns to end up at the correct position.
1041 * To make it easier just disallow all moving while turning as
1042 * long as an aircraft is on the ground. */
1043 gp.x = v->x_pos;
1044 gp.y = v->y_pos;
1045 gp.new_tile = gp.old_tile = v->tile;
1047 } else {
1048 v->number_consecutive_turns = 0;
1049 /* Move vehicle. */
1050 gp = GetNewVehiclePos(v);
1054 v->tile = gp.new_tile;
1055 /* If vehicle is in the air, use tile coordinate 0. */
1056 if (amd.flag & (AMED_TAKEOFF | AMED_SLOWTURN | AMED_LAND)) v->tile = 0;
1058 /* Adjust Z for land or takeoff? */
1059 int z = v->z_pos;
1061 if (amd.flag & AMED_TAKEOFF) {
1062 z = GetAircraftFlightLevel(v, true);
1063 } else if (amd.flag & AMED_HOLD) {
1064 /* Let the plane drop from normal flight altitude to holding pattern altitude */
1065 if (z > GetAircraftHoldMaxAltitude(v)) z--;
1066 } else if ((amd.flag & AMED_SLOWTURN) && (amd.flag & AMED_NOSPDCLAMP)) {
1067 z = GetAircraftFlightLevel(v);
1070 if (amd.flag & AMED_LAND) {
1071 if (st->airport.tile == INVALID_TILE) {
1072 /* Airport has been removed, abort the landing procedure */
1073 v->state = FLYING;
1074 UpdateAircraftCache(v);
1075 AircraftNextAirportPos_and_Order(v);
1076 /* get aircraft back on running altitude */
1077 SetAircraftPosition(v, gp.x, gp.y, GetAircraftFlightLevel(v));
1078 continue;
1081 int curz = GetSlopePixelZ(x + amd.x, y + amd.y) + 1;
1083 /* We're not flying below our destination, right? */
1084 assert(curz <= z);
1085 int t = max(1U, dist - 4);
1086 int delta = z - curz;
1088 /* Only start lowering when we're sufficiently close for a 1:1 glide */
1089 if (delta >= t) {
1090 z -= CeilDiv(z - curz, t);
1092 if (z < curz) z = curz;
1095 /* We've landed. Decrease speed when we're reaching end of runway. */
1096 if (amd.flag & AMED_BRAKE) {
1097 int curz = GetSlopePixelZ(x, y) + 1;
1099 if (z > curz) {
1100 z--;
1101 } else if (z < curz) {
1102 z++;
1107 SetAircraftPosition(v, gp.x, gp.y, z);
1108 } while (--count != 0);
1109 return false;
1113 * Handle crashed aircraft \a v.
1114 * @param v Crashed aircraft.
1116 static bool HandleCrashedAircraft(Aircraft *v)
1118 v->crashed_counter += 3;
1120 Station *st = GetTargetAirportIfValid(v);
1122 /* make aircraft crash down to the ground */
1123 if (v->crashed_counter < 500 && st == nullptr && ((v->crashed_counter % 3) == 0) ) {
1124 int z = GetSlopePixelZ(Clamp(v->x_pos, 0, MapMaxX() * TILE_SIZE), Clamp(v->y_pos, 0, MapMaxY() * TILE_SIZE));
1125 v->z_pos -= 1;
1126 if (v->z_pos == z) {
1127 v->crashed_counter = 500;
1128 v->z_pos++;
1132 if (v->crashed_counter < 650) {
1133 uint32 r;
1134 if (Chance16R(1, 32, r)) {
1135 static const DirDiff delta[] = {
1136 DIRDIFF_45LEFT, DIRDIFF_SAME, DIRDIFF_SAME, DIRDIFF_45RIGHT
1139 v->direction = ChangeDir(v->direction, delta[GB(r, 16, 2)]);
1140 SetAircraftPosition(v, v->x_pos, v->y_pos, v->z_pos);
1141 r = Random();
1142 CreateEffectVehicleRel(v,
1143 GB(r, 0, 4) - 4,
1144 GB(r, 4, 4) - 4,
1145 GB(r, 8, 4),
1146 EV_EXPLOSION_SMALL);
1148 } else if (v->crashed_counter >= 10000) {
1149 /* remove rubble of crashed airplane */
1151 /* clear runway-in on all airports, set by crashing plane
1152 * small airports use AIRPORT_BUSY, city airports use RUNWAY_IN_OUT_block, etc.
1153 * but they all share the same number */
1154 if (st != nullptr) {
1155 CLRBITS(st->airport.flags, RUNWAY_IN_block);
1156 CLRBITS(st->airport.flags, RUNWAY_IN_OUT_block); // commuter airport
1157 CLRBITS(st->airport.flags, RUNWAY_IN2_block); // intercontinental
1160 delete v;
1162 return false;
1165 return true;
1170 * Handle smoke of broken aircraft.
1171 * @param v Aircraft
1172 * @param mode Is this the non-first call for this vehicle in this tick?
1174 static void HandleAircraftSmoke(Aircraft *v, bool mode)
1176 static const struct {
1177 int8 x;
1178 int8 y;
1179 } smoke_pos[] = {
1180 { 5, 5 },
1181 { 6, 0 },
1182 { 5, -5 },
1183 { 0, -6 },
1184 { -5, -5 },
1185 { -6, 0 },
1186 { -5, 5 },
1187 { 0, 6 }
1190 if (!(v->vehstatus & VS_AIRCRAFT_BROKEN)) return;
1192 /* Stop smoking when landed */
1193 if (v->cur_speed < 10) {
1194 v->vehstatus &= ~VS_AIRCRAFT_BROKEN;
1195 v->breakdown_ctr = 0;
1196 return;
1199 /* Spawn effect et most once per Tick, i.e. !mode */
1200 if (!mode && (v->tick_counter & 0x0F) == 0) {
1201 CreateEffectVehicleRel(v,
1202 smoke_pos[v->direction].x,
1203 smoke_pos[v->direction].y,
1205 EV_BREAKDOWN_SMOKE_AIRCRAFT
1210 void HandleMissingAircraftOrders(Aircraft *v)
1213 * We do not have an order. This can be divided into two cases:
1214 * 1) we are heading to an invalid station. In this case we must
1215 * find another airport to go to. If there is nowhere to go,
1216 * we will destroy the aircraft as it otherwise will enter
1217 * the holding pattern for the first airport, which can cause
1218 * the plane to go into an undefined state when building an
1219 * airport with the same StationID.
1220 * 2) we are (still) heading to a (still) valid airport, then we
1221 * can continue going there. This can happen when you are
1222 * changing the aircraft's orders while in-flight or in for
1223 * example a depot. However, when we have a current order to
1224 * go to a depot, we have to keep that order so the aircraft
1225 * actually stops.
1227 const Station *st = GetTargetAirportIfValid(v);
1228 if (st == nullptr) {
1229 Backup<CompanyByte> cur_company(_current_company, v->owner, FILE_LINE);
1230 CommandCost ret = DoCommand(v->tile, v->index, 0, DC_EXEC, CMD_SEND_VEHICLE_TO_DEPOT);
1231 cur_company.Restore();
1233 if (ret.Failed()) CrashAirplane(v);
1234 } else if (!v->current_order.IsType(OT_GOTO_DEPOT)) {
1235 v->current_order.Free();
1240 TileIndex Aircraft::GetOrderStationLocation(StationID station)
1242 /* Orders are changed in flight, ensure going to the right station. */
1243 if (this->state == FLYING) {
1244 AircraftNextAirportPos_and_Order(this);
1247 /* Aircraft do not use dest-tile */
1248 return 0;
1251 void Aircraft::MarkDirty()
1253 this->colourmap = PAL_NONE;
1254 this->UpdateViewport(true, false);
1255 if (this->subtype == AIR_HELICOPTER) {
1256 Aircraft *rotor = this->Next()->Next();
1257 GetRotorImage(this, EIT_ON_MAP, &rotor->sprite_seq);
1258 rotor->UpdateSpriteSeqBound();
1263 uint Aircraft::Crash(bool flooded)
1265 uint pass = Vehicle::Crash(flooded) + 2; // pilots
1266 this->crashed_counter = flooded ? 9000 : 0; // max 10000, disappear pretty fast when flooded
1268 return pass;
1272 * Bring the aircraft in a crashed state, create the explosion animation, and create a news item about the crash.
1273 * @param v Aircraft that crashed.
1275 static void CrashAirplane(Aircraft *v)
1277 CreateEffectVehicleRel(v, 4, 4, 8, EV_EXPLOSION_LARGE);
1279 uint pass = v->Crash();
1280 SetDParam(0, pass);
1282 v->cargo.Truncate();
1283 v->Next()->cargo.Truncate();
1284 const Station *st = GetTargetAirportIfValid(v);
1285 StringID newsitem;
1286 if (st == nullptr) {
1287 newsitem = STR_NEWS_PLANE_CRASH_OUT_OF_FUEL;
1288 } else {
1289 SetDParam(1, st->index);
1290 newsitem = STR_NEWS_AIRCRAFT_CRASH;
1293 AI::NewEvent(v->owner, new ScriptEventVehicleCrashed(v->index, v->tile, st == nullptr ? ScriptEventVehicleCrashed::CRASH_AIRCRAFT_NO_AIRPORT : ScriptEventVehicleCrashed::CRASH_PLANE_LANDING));
1294 Game::NewEvent(new ScriptEventVehicleCrashed(v->index, v->tile, st == nullptr ? ScriptEventVehicleCrashed::CRASH_AIRCRAFT_NO_AIRPORT : ScriptEventVehicleCrashed::CRASH_PLANE_LANDING));
1296 AddVehicleNewsItem(newsitem, NT_ACCIDENT, v->index, st != nullptr ? st->index : INVALID_STATION);
1298 ModifyStationRatingAround(v->tile, v->owner, -160, 30);
1299 if (_settings_client.sound.disaster) SndPlayVehicleFx(SND_12_EXPLOSION, v);
1303 * Decide whether aircraft \a v should crash.
1304 * @param v Aircraft to test.
1306 static void MaybeCrashAirplane(Aircraft *v)
1308 if (_settings_game.vehicle.plane_crashes == 0) return;
1310 Station *st = Station::Get(v->targetairport);
1312 /* FIXME -- MaybeCrashAirplane -> increase crashing chances of very modern airplanes on smaller than AT_METROPOLITAN airports */
1313 uint32 prob = (0x4000 << _settings_game.vehicle.plane_crashes);
1314 if ((st->airport.GetFTA()->flags & AirportFTAClass::SHORT_STRIP) &&
1315 (AircraftVehInfo(v->engine_type)->subtype & AIR_FAST) &&
1316 !_cheats.no_jetcrash.value) {
1317 prob /= 20;
1318 } else {
1319 prob /= 1500;
1322 if (GB(Random(), 0, 22) > prob) return;
1324 /* Crash the airplane. Remove all goods stored at the station. */
1325 for (CargoID i = 0; i < NUM_CARGO; i++) {
1326 st->goods[i].rating = 1;
1327 st->goods[i].cargo.Truncate();
1330 CrashAirplane(v);
1334 * Aircraft arrives at a terminal. If it is the first aircraft, throw a party.
1335 * Start loading cargo.
1336 * @param v Aircraft that arrived.
1338 static void AircraftEntersTerminal(Aircraft *v)
1340 if (v->current_order.IsType(OT_GOTO_DEPOT)) return;
1342 Station *st = Station::Get(v->targetairport);
1343 v->last_station_visited = v->targetairport;
1345 /* Check if station was ever visited before */
1346 if (!(st->had_vehicle_of_type & HVOT_AIRCRAFT)) {
1347 st->had_vehicle_of_type |= HVOT_AIRCRAFT;
1348 SetDParam(0, st->index);
1349 /* show newsitem of celebrating citizens */
1350 AddVehicleNewsItem(
1351 STR_NEWS_FIRST_AIRCRAFT_ARRIVAL,
1352 (v->owner == _local_company) ? NT_ARRIVAL_COMPANY : NT_ARRIVAL_OTHER,
1353 v->index,
1354 st->index
1356 AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
1357 Game::NewEvent(new ScriptEventStationFirstVehicle(st->index, v->index));
1360 v->BeginLoading();
1364 * Aircraft touched down at the landing strip.
1365 * @param v Aircraft that landed.
1367 static void AircraftLandAirplane(Aircraft *v)
1369 v->UpdateDeltaXY(INVALID_DIR);
1371 if (!PlayVehicleSound(v, VSE_TOUCHDOWN)) {
1372 SndPlayVehicleFx(SND_17_SKID_PLANE, v);
1377 /** set the right pos when heading to other airports after takeoff */
1378 void AircraftNextAirportPos_and_Order(Aircraft *v)
1380 if (v->current_order.IsType(OT_GOTO_STATION) || v->current_order.IsType(OT_GOTO_DEPOT)) {
1381 v->targetairport = v->current_order.GetDestination();
1384 const Station *st = GetTargetAirportIfValid(v);
1385 const AirportFTAClass *apc = st == nullptr ? GetAirport(AT_DUMMY) : st->airport.GetFTA();
1386 Direction rotation = st == nullptr ? DIR_N : st->airport.rotation;
1387 v->pos = v->previous_pos = AircraftGetEntryPoint(v, apc, rotation);
1391 * Aircraft is about to leave the hangar.
1392 * @param v Aircraft leaving.
1393 * @param exit_dir The direction the vehicle leaves the hangar.
1394 * @note This function is called in AfterLoadGame for old savegames, so don't rely
1395 * on any data to be valid, especially don't rely on the fact that the vehicle
1396 * is actually on the ground inside a depot.
1398 void AircraftLeaveHangar(Aircraft *v, Direction exit_dir)
1400 v->cur_speed = 0;
1401 v->subspeed = 0;
1402 v->progress = 0;
1403 v->direction = exit_dir;
1404 v->vehstatus &= ~VS_HIDDEN;
1406 Vehicle *u = v->Next();
1407 u->vehstatus &= ~VS_HIDDEN;
1409 /* Rotor blades */
1410 u = u->Next();
1411 if (u != nullptr) {
1412 u->vehstatus &= ~VS_HIDDEN;
1413 u->cur_speed = 80;
1417 VehicleServiceInDepot(v);
1418 SetAircraftPosition(v, v->x_pos, v->y_pos, v->z_pos);
1419 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
1420 SetWindowClassesDirty(WC_AIRCRAFT_LIST);
1423 ////////////////////////////////////////////////////////////////////////////////
1424 /////////////////// AIRCRAFT MOVEMENT SCHEME ////////////////////////////////
1425 ////////////////////////////////////////////////////////////////////////////////
1426 static void AircraftEventHandler_EnterTerminal(Aircraft *v, const AirportFTAClass *apc)
1428 AircraftEntersTerminal(v);
1429 v->state = apc->layout[v->pos].heading;
1433 * Aircraft arrived in an airport hangar.
1434 * @param v Aircraft in the hangar.
1435 * @param apc Airport description containing the hangar.
1437 static void AircraftEventHandler_EnterHangar(Aircraft *v, const AirportFTAClass *apc)
1439 VehicleEnterDepot(v);
1440 v->state = apc->layout[v->pos].heading;
1444 * Handle aircraft movement/decision making in an airport hangar.
1445 * @param v Aircraft in the hangar.
1446 * @param apc Airport description containing the hangar.
1448 static void AircraftEventHandler_InHangar(Aircraft *v, const AirportFTAClass *apc)
1450 /* if we just arrived, execute EnterHangar first */
1451 if (v->previous_pos != v->pos) {
1452 AircraftEventHandler_EnterHangar(v, apc);
1453 return;
1456 if (v->current_order.IsWaitTimetabled())
1457 v->HandleWaiting(false);
1458 if (v->current_order.IsType(OT_WAITING))
1459 return;
1461 /* if we were sent to the depot, stay there */
1462 if (v->current_order.IsType(OT_GOTO_DEPOT) && (v->vehstatus & VS_STOPPED)) {
1463 v->current_order.Free();
1464 return;
1467 if (!v->current_order.IsType(OT_GOTO_STATION) &&
1468 !v->current_order.IsType(OT_GOTO_DEPOT))
1469 return;
1471 /* We are leaving a hangar, but have to go to the exact same one; re-enter */
1472 if (v->current_order.IsType(OT_GOTO_DEPOT) && v->current_order.GetDestination() == v->targetairport) {
1473 VehicleEnterDepot(v);
1474 return;
1477 /* if the block of the next position is busy, stay put */
1478 if (AirportHasBlock(v, &apc->layout[v->pos], apc)) return;
1480 /* We are already at the target airport, we need to find a terminal */
1481 if (v->current_order.GetDestination() == v->targetairport) {
1482 /* FindFreeTerminal:
1483 * 1. Find a free terminal, 2. Occupy it, 3. Set the vehicle's state to that terminal */
1484 if (v->subtype == AIR_HELICOPTER) {
1485 if (!AirportFindFreeHelipad(v, apc)) return; // helicopter
1486 } else {
1487 if (!AirportFindFreeTerminal(v, apc)) return; // airplane
1489 } else { // Else prepare for launch.
1490 /* airplane goto state takeoff, helicopter to helitakeoff */
1491 v->state = (v->subtype == AIR_HELICOPTER) ? HELITAKEOFF : TAKEOFF;
1493 const Station *st = Station::GetByTile(v->tile);
1494 AircraftLeaveHangar(v, st->airport.GetHangarExitDirection(v->tile));
1495 AirportMove(v, apc);
1498 /** At one of the Airport's Terminals */
1499 static void AircraftEventHandler_AtTerminal(Aircraft *v, const AirportFTAClass *apc)
1501 /* if we just arrived, execute EnterTerminal first */
1502 if (v->previous_pos != v->pos) {
1503 AircraftEventHandler_EnterTerminal(v, apc);
1504 /* on an airport with helipads, a helicopter will always land there
1505 * and get serviced at the same time - setting */
1506 if (_settings_game.order.serviceathelipad) {
1507 if (v->subtype == AIR_HELICOPTER && apc->num_helipads > 0) {
1508 /* an excerpt of ServiceAircraft, without the invisibility stuff */
1509 v->date_of_last_service = _date;
1510 v->breakdowns_since_last_service = 0;
1511 v->reliability = v->GetEngine()->reliability;
1512 SetWindowDirty(WC_VEHICLE_DETAILS, v->index);
1515 return;
1518 if (v->current_order.IsType(OT_NOTHING)) return;
1520 /* if the block of the next position is busy, stay put */
1521 if (AirportHasBlock(v, &apc->layout[v->pos], apc)) return;
1523 /* airport-road is free. We either have to go to another airport, or to the hangar
1524 * ---> start moving */
1526 bool go_to_hangar = false;
1527 switch (v->current_order.GetType()) {
1528 case OT_GOTO_STATION: // ready to fly to another airport
1529 break;
1530 case OT_GOTO_DEPOT: // visit hangar for servicing, sale, etc.
1531 go_to_hangar = v->current_order.GetDestination() == v->targetairport;
1532 break;
1533 case OT_CONDITIONAL:
1534 /* In case of a conditional order we just have to wait a tick
1535 * longer, so the conditional order can actually be processed;
1536 * we should not clear the order as that makes us go nowhere. */
1537 return;
1538 default: // orders have been deleted (no orders), goto depot and don't bother us
1539 v->current_order.Free();
1540 go_to_hangar = Station::Get(v->targetairport)->airport.HasHangar();
1543 if (go_to_hangar) {
1544 v->state = HANGAR;
1545 } else {
1546 /* airplane goto state takeoff, helicopter to helitakeoff */
1547 v->state = (v->subtype == AIR_HELICOPTER) ? HELITAKEOFF : TAKEOFF;
1549 AirportMove(v, apc);
1552 static void AircraftEventHandler_General(Aircraft *v, const AirportFTAClass *apc)
1554 error("OK, you shouldn't be here, check your Airport Scheme!");
1557 static void AircraftEventHandler_TakeOff(Aircraft *v, const AirportFTAClass *apc)
1559 PlayAircraftSound(v); // play takeoffsound for airplanes
1560 v->state = STARTTAKEOFF;
1563 static void AircraftEventHandler_StartTakeOff(Aircraft *v, const AirportFTAClass *apc)
1565 v->state = ENDTAKEOFF;
1566 v->UpdateDeltaXY(INVALID_DIR);
1569 static void AircraftEventHandler_EndTakeOff(Aircraft *v, const AirportFTAClass *apc)
1571 v->state = FLYING;
1572 /* get the next position to go to, differs per airport */
1573 AircraftNextAirportPos_and_Order(v);
1576 static void AircraftEventHandler_HeliTakeOff(Aircraft *v, const AirportFTAClass *apc)
1578 v->state = FLYING;
1579 v->UpdateDeltaXY(INVALID_DIR);
1581 /* get the next position to go to, differs per airport */
1582 AircraftNextAirportPos_and_Order(v);
1584 /* Send the helicopter to a hangar if needed for replacement */
1585 if (v->NeedsAutomaticServicing()) {
1586 Backup<CompanyByte> cur_company(_current_company, v->owner, FILE_LINE);
1587 DoCommand(v->tile, v->index | DEPOT_SERVICE | DEPOT_LOCATE_HANGAR, 0, DC_EXEC, CMD_SEND_VEHICLE_TO_DEPOT);
1588 cur_company.Restore();
1592 static void AircraftEventHandler_Flying(Aircraft *v, const AirportFTAClass *apc)
1594 Station *st = Station::Get(v->targetairport);
1596 /* Runway busy, not allowed to use this airstation or closed, circle. */
1597 if (CanVehicleUseStation(v, st) && (st->owner == OWNER_NONE || st->owner == v->owner) && !(st->airport.flags & AIRPORT_CLOSED_block)) {
1598 /* {32,FLYING,NOTHING_block,37}, {32,LANDING,N,33}, {32,HELILANDING,N,41},
1599 * if it is an airplane, look for LANDING, for helicopter HELILANDING
1600 * it is possible to choose from multiple landing runways, so loop until a free one is found */
1601 byte landingtype = (v->subtype == AIR_HELICOPTER) ? HELILANDING : LANDING;
1602 const AirportFTA *current = apc->layout[v->pos].next;
1603 while (current != nullptr) {
1604 if (current->heading == landingtype) {
1605 /* save speed before, since if AirportHasBlock is false, it resets them to 0
1606 * we don't want that for plane in air
1607 * hack for speed thingie */
1608 uint16 tcur_speed = v->cur_speed;
1609 uint16 tsubspeed = v->subspeed;
1610 if (!AirportHasBlock(v, current, apc)) {
1611 v->state = landingtype; // LANDING / HELILANDING
1612 /* it's a bit dirty, but I need to set position to next position, otherwise
1613 * if there are multiple runways, plane won't know which one it took (because
1614 * they all have heading LANDING). And also occupy that block! */
1615 v->pos = current->next_position;
1616 SETBITS(st->airport.flags, apc->layout[v->pos].block);
1617 return;
1619 v->cur_speed = tcur_speed;
1620 v->subspeed = tsubspeed;
1622 current = current->next;
1625 v->state = FLYING;
1626 v->pos = apc->layout[v->pos].next_position;
1629 static void AircraftEventHandler_Landing(Aircraft *v, const AirportFTAClass *apc)
1631 v->state = ENDLANDING;
1632 AircraftLandAirplane(v); // maybe crash airplane
1634 /* check if the aircraft needs to be replaced or renewed and send it to a hangar if needed */
1635 if (v->NeedsAutomaticServicing()) {
1636 Backup<CompanyByte> cur_company(_current_company, v->owner, FILE_LINE);
1637 DoCommand(v->tile, v->index | DEPOT_SERVICE, 0, DC_EXEC, CMD_SEND_VEHICLE_TO_DEPOT);
1638 cur_company.Restore();
1642 static void AircraftEventHandler_HeliLanding(Aircraft *v, const AirportFTAClass *apc)
1644 v->state = HELIENDLANDING;
1645 v->UpdateDeltaXY(INVALID_DIR);
1648 static void AircraftEventHandler_EndLanding(Aircraft *v, const AirportFTAClass *apc)
1650 /* next block busy, don't do a thing, just wait */
1651 if (AirportHasBlock(v, &apc->layout[v->pos], apc)) return;
1653 /* if going to terminal (OT_GOTO_STATION) choose one
1654 * 1. in case all terminals are busy AirportFindFreeTerminal() returns false or
1655 * 2. not going for terminal (but depot, no order),
1656 * --> get out of the way to the hangar. */
1657 if (v->current_order.IsType(OT_GOTO_STATION)) {
1658 if (AirportFindFreeTerminal(v, apc)) return;
1660 v->state = HANGAR;
1664 static void AircraftEventHandler_HeliEndLanding(Aircraft *v, const AirportFTAClass *apc)
1666 /* next block busy, don't do a thing, just wait */
1667 if (AirportHasBlock(v, &apc->layout[v->pos], apc)) return;
1669 /* if going to helipad (OT_GOTO_STATION) choose one. If airport doesn't have helipads, choose terminal
1670 * 1. in case all terminals/helipads are busy (AirportFindFreeHelipad() returns false) or
1671 * 2. not going for terminal (but depot, no order),
1672 * --> get out of the way to the hangar IF there are terminals on the airport.
1673 * --> else TAKEOFF
1674 * the reason behind this is that if an airport has a terminal, it also has a hangar. Airplanes
1675 * must go to a hangar. */
1676 if (v->current_order.IsType(OT_GOTO_STATION)) {
1677 if (AirportFindFreeHelipad(v, apc)) return;
1679 v->state = Station::Get(v->targetairport)->airport.HasHangar() ? HANGAR : HELITAKEOFF;
1683 * Signature of the aircraft handler function.
1684 * @param v Aircraft to handle.
1685 * @param apc Airport state machine.
1687 typedef void AircraftStateHandler(Aircraft *v, const AirportFTAClass *apc);
1688 /** Array of handler functions for each target of the aircraft. */
1689 static AircraftStateHandler * const _aircraft_state_handlers[] = {
1690 AircraftEventHandler_General, // TO_ALL = 0
1691 AircraftEventHandler_InHangar, // HANGAR = 1
1692 AircraftEventHandler_AtTerminal, // TERM1 = 2
1693 AircraftEventHandler_AtTerminal, // TERM2 = 3
1694 AircraftEventHandler_AtTerminal, // TERM3 = 4
1695 AircraftEventHandler_AtTerminal, // TERM4 = 5
1696 AircraftEventHandler_AtTerminal, // TERM5 = 6
1697 AircraftEventHandler_AtTerminal, // TERM6 = 7
1698 AircraftEventHandler_AtTerminal, // HELIPAD1 = 8
1699 AircraftEventHandler_AtTerminal, // HELIPAD2 = 9
1700 AircraftEventHandler_TakeOff, // TAKEOFF = 10
1701 AircraftEventHandler_StartTakeOff, // STARTTAKEOFF = 11
1702 AircraftEventHandler_EndTakeOff, // ENDTAKEOFF = 12
1703 AircraftEventHandler_HeliTakeOff, // HELITAKEOFF = 13
1704 AircraftEventHandler_Flying, // FLYING = 14
1705 AircraftEventHandler_Landing, // LANDING = 15
1706 AircraftEventHandler_EndLanding, // ENDLANDING = 16
1707 AircraftEventHandler_HeliLanding, // HELILANDING = 17
1708 AircraftEventHandler_HeliEndLanding, // HELIENDLANDING = 18
1709 AircraftEventHandler_AtTerminal, // TERM7 = 19
1710 AircraftEventHandler_AtTerminal, // TERM8 = 20
1711 AircraftEventHandler_AtTerminal, // HELIPAD3 = 21
1714 static void AirportClearBlock(const Aircraft *v, const AirportFTAClass *apc)
1716 /* we have left the previous block, and entered the new one. Free the previous block */
1717 if (apc->layout[v->previous_pos].block != apc->layout[v->pos].block) {
1718 Station *st = Station::Get(v->targetairport);
1720 CLRBITS(st->airport.flags, apc->layout[v->previous_pos].block);
1724 static void AirportGoToNextPosition(Aircraft *v)
1726 /* if aircraft is not in position, wait until it is */
1727 if (!AircraftController(v)) return;
1729 const AirportFTAClass *apc = Station::Get(v->targetairport)->airport.GetFTA();
1731 AirportClearBlock(v, apc);
1732 AirportMove(v, apc); // move aircraft to next position
1735 /* gets pos from vehicle and next orders */
1736 static bool AirportMove(Aircraft *v, const AirportFTAClass *apc)
1738 /* error handling */
1739 if (v->pos >= apc->nofelements) {
1740 DEBUG(misc, 0, "[Ap] position %d is not valid for current airport. Max position is %d", v->pos, apc->nofelements-1);
1741 assert(v->pos < apc->nofelements);
1744 const AirportFTA *current = &apc->layout[v->pos];
1745 /* we have arrived in an important state (eg terminal, hangar, etc.) */
1746 if (current->heading == v->state) {
1747 byte prev_pos = v->pos; // location could be changed in state, so save it before-hand
1748 byte prev_state = v->state;
1749 _aircraft_state_handlers[v->state](v, apc);
1750 if (v->state != FLYING) v->previous_pos = prev_pos;
1751 if (v->state != prev_state || v->pos != prev_pos) UpdateAircraftCache(v);
1752 return true;
1755 v->previous_pos = v->pos; // save previous location
1757 /* there is only one choice to move to */
1758 if (current->next == nullptr) {
1759 if (AirportSetBlocks(v, current, apc)) {
1760 v->pos = current->next_position;
1761 UpdateAircraftCache(v);
1762 } // move to next position
1763 return false;
1766 /* there are more choices to choose from, choose the one that
1767 * matches our heading */
1768 do {
1769 if (v->state == current->heading || current->heading == TO_ALL) {
1770 if (AirportSetBlocks(v, current, apc)) {
1771 v->pos = current->next_position;
1772 UpdateAircraftCache(v);
1773 } // move to next position
1774 return false;
1776 current = current->next;
1777 } while (current != nullptr);
1779 DEBUG(misc, 0, "[Ap] cannot move further on Airport! (pos %d state %d) for vehicle %d", v->pos, v->state, v->index);
1780 NOT_REACHED();
1783 /** returns true if the road ahead is busy, eg. you must wait before proceeding. */
1784 static bool AirportHasBlock(Aircraft *v, const AirportFTA *current_pos, const AirportFTAClass *apc)
1786 const AirportFTA *reference = &apc->layout[v->pos];
1787 const AirportFTA *next = &apc->layout[current_pos->next_position];
1789 /* same block, then of course we can move */
1790 if (apc->layout[current_pos->position].block != next->block) {
1791 const Station *st = Station::Get(v->targetairport);
1792 uint64 airport_flags = next->block;
1794 /* check additional possible extra blocks */
1795 if (current_pos != reference && current_pos->block != NOTHING_block) {
1796 airport_flags |= current_pos->block;
1799 if (st->airport.flags & airport_flags) {
1800 v->cur_speed = 0;
1801 v->subspeed = 0;
1802 return true;
1805 return false;
1809 * "reserve" a block for the plane
1810 * @param v airplane that requires the operation
1811 * @param current_pos of the vehicle in the list of blocks
1812 * @param apc airport on which block is requsted to be set
1813 * @returns true on success. Eg, next block was free and we have occupied it
1815 static bool AirportSetBlocks(Aircraft *v, const AirportFTA *current_pos, const AirportFTAClass *apc)
1817 const AirportFTA *next = &apc->layout[current_pos->next_position];
1818 const AirportFTA *reference = &apc->layout[v->pos];
1820 /* if the next position is in another block, check it and wait until it is free */
1821 if ((apc->layout[current_pos->position].block & next->block) != next->block) {
1822 uint64 airport_flags = next->block;
1823 /* search for all all elements in the list with the same state, and blocks != N
1824 * this means more blocks should be checked/set */
1825 const AirportFTA *current = current_pos;
1826 if (current == reference) current = current->next;
1827 while (current != nullptr) {
1828 if (current->heading == current_pos->heading && current->block != 0) {
1829 airport_flags |= current->block;
1830 break;
1832 current = current->next;
1835 /* if the block to be checked is in the next position, then exclude that from
1836 * checking, because it has been set by the airplane before */
1837 if (current_pos->block == next->block) airport_flags ^= next->block;
1839 Station *st = Station::Get(v->targetairport);
1840 if (st->airport.flags & airport_flags) {
1841 v->cur_speed = 0;
1842 v->subspeed = 0;
1843 return false;
1846 if (next->block != NOTHING_block) {
1847 SETBITS(st->airport.flags, airport_flags); // occupy next block
1850 return true;
1854 * Combination of aircraft state for going to a certain terminal and the
1855 * airport flag for that terminal block.
1857 struct MovementTerminalMapping {
1858 AirportMovementStates state; ///< Aircraft movement state when going to this terminal.
1859 uint64 airport_flag; ///< Bitmask in the airport flags that need to be free for this terminal.
1862 /** A list of all valid terminals and their associated blocks. */
1863 static const MovementTerminalMapping _airport_terminal_mapping[] = {
1864 {TERM1, TERM1_block},
1865 {TERM2, TERM2_block},
1866 {TERM3, TERM3_block},
1867 {TERM4, TERM4_block},
1868 {TERM5, TERM5_block},
1869 {TERM6, TERM6_block},
1870 {TERM7, TERM7_block},
1871 {TERM8, TERM8_block},
1872 {HELIPAD1, HELIPAD1_block},
1873 {HELIPAD2, HELIPAD2_block},
1874 {HELIPAD3, HELIPAD3_block},
1878 * Find a free terminal or helipad, and if available, assign it.
1879 * @param v Aircraft looking for a free terminal or helipad.
1880 * @param i First terminal to examine.
1881 * @param last_terminal Terminal number to stop examining.
1882 * @return A terminal or helipad has been found, and has been assigned to the aircraft.
1884 static bool FreeTerminal(Aircraft *v, byte i, byte last_terminal)
1886 assert(last_terminal <= lengthof(_airport_terminal_mapping));
1887 Station *st = Station::Get(v->targetairport);
1888 for (; i < last_terminal; i++) {
1889 if ((st->airport.flags & _airport_terminal_mapping[i].airport_flag) == 0) {
1890 /* TERMINAL# HELIPAD# */
1891 v->state = _airport_terminal_mapping[i].state; // start moving to that terminal/helipad
1892 SETBITS(st->airport.flags, _airport_terminal_mapping[i].airport_flag); // occupy terminal/helipad
1893 return true;
1896 return false;
1900 * Get the number of terminals at the airport.
1901 * @param afc Airport description.
1902 * @return Number of terminals.
1904 static uint GetNumTerminals(const AirportFTAClass *apc)
1906 uint num = 0;
1908 for (uint i = apc->terminals[0]; i > 0; i--) num += apc->terminals[i];
1910 return num;
1914 * Find a free terminal, and assign it if available.
1915 * @param v Aircraft to handle.
1916 * @param apc Airport state machine.
1917 * @return Found a free terminal and assigned it.
1919 static bool AirportFindFreeTerminal(Aircraft *v, const AirportFTAClass *apc)
1921 /* example of more terminalgroups
1922 * {0,HANGAR,NOTHING_block,1}, {0,255,TERM_GROUP1_block,0}, {0,255,TERM_GROUP2_ENTER_block,1}, {0,0,N,1},
1923 * Heading 255 denotes a group. We see 2 groups here:
1924 * 1. group 0 -- TERM_GROUP1_block (check block)
1925 * 2. group 1 -- TERM_GROUP2_ENTER_block (check block)
1926 * First in line is checked first, group 0. If the block (TERM_GROUP1_block) is free, it
1927 * looks at the corresponding terminals of that group. If no free ones are found, other
1928 * possible groups are checked (in this case group 1, since that is after group 0). If that
1929 * fails, then attempt fails and plane waits
1931 if (apc->terminals[0] > 1) {
1932 const Station *st = Station::Get(v->targetairport);
1933 const AirportFTA *temp = apc->layout[v->pos].next;
1935 while (temp != nullptr) {
1936 if (temp->heading == 255) {
1937 if (!(st->airport.flags & temp->block)) {
1938 /* read which group do we want to go to?
1939 * (the first free group) */
1940 uint target_group = temp->next_position + 1;
1942 /* at what terminal does the group start?
1943 * that means, sum up all terminals of
1944 * groups with lower number */
1945 uint group_start = 0;
1946 for (uint i = 1; i < target_group; i++) {
1947 group_start += apc->terminals[i];
1950 uint group_end = group_start + apc->terminals[target_group];
1951 if (FreeTerminal(v, group_start, group_end)) return true;
1953 } else {
1954 /* once the heading isn't 255, we've exhausted the possible blocks.
1955 * So we cannot move */
1956 return false;
1958 temp = temp->next;
1962 /* if there is only 1 terminalgroup, all terminals are checked (starting from 0 to max) */
1963 return FreeTerminal(v, 0, GetNumTerminals(apc));
1967 * Find a free helipad, and assign it if available.
1968 * @param v Aircraft to handle.
1969 * @param apc Airport state machine.
1970 * @return Found a free helipad and assigned it.
1972 static bool AirportFindFreeHelipad(Aircraft *v, const AirportFTAClass *apc)
1974 /* if an airport doesn't have helipads, use terminals */
1975 if (apc->num_helipads == 0) return AirportFindFreeTerminal(v, apc);
1977 /* only 1 helicoptergroup, check all helipads
1978 * The blocks for helipads start after the last terminal (MAX_TERMINALS) */
1979 return FreeTerminal(v, MAX_TERMINALS, apc->num_helipads + MAX_TERMINALS);
1983 * Handle the 'dest too far' flag and the corresponding news message for aircraft.
1984 * @param v The aircraft.
1985 * @param too_far True if the current destination is too far away.
1987 static void AircraftHandleDestTooFar(Aircraft *v, bool too_far)
1989 if (too_far) {
1990 if (!HasBit(v->flags, VAF_DEST_TOO_FAR)) {
1991 SetBit(v->flags, VAF_DEST_TOO_FAR);
1992 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
1993 AI::NewEvent(v->owner, new ScriptEventAircraftDestTooFar(v->index));
1994 if (v->owner == _local_company) {
1995 /* Post a news message. */
1996 SetDParam(0, v->index);
1997 AddVehicleAdviceNewsItem(STR_NEWS_AIRCRAFT_DEST_TOO_FAR, v->index);
2000 return;
2003 if (HasBit(v->flags, VAF_DEST_TOO_FAR)) {
2004 /* Not too far anymore, clear flag and message. */
2005 ClrBit(v->flags, VAF_DEST_TOO_FAR);
2006 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
2007 DeleteVehicleNews(v->index, STR_NEWS_AIRCRAFT_DEST_TOO_FAR);
2011 static bool AircraftEventHandler(Aircraft *v, int loop)
2013 if (v->vehstatus & VS_CRASHED) {
2014 return HandleCrashedAircraft(v);
2017 if (v->vehstatus & VS_STOPPED) return true;
2019 v->HandleBreakdown();
2021 HandleAircraftSmoke(v, loop != 0);
2022 ProcessOrders(v);
2023 v->HandleLoading(loop != 0);
2025 if (v->current_order.IsType(OT_LOADING) || v->current_order.IsType(OT_LEAVESTATION)) return true;
2027 if (v->state >= ENDTAKEOFF && v->state <= HELIENDLANDING) {
2028 /* If we are flying, unconditionally clear the 'dest too far' state. */
2029 AircraftHandleDestTooFar(v, false);
2030 } else if (v->acache.cached_max_range_sqr != 0) {
2031 /* Check the distance to the next destination. This code works because the target
2032 * airport is only updated after take off and not on the ground. */
2033 Station *cur_st = Station::GetIfValid(v->targetairport);
2034 Station *next_st = v->current_order.IsType(OT_GOTO_STATION) || v->current_order.IsType(OT_GOTO_DEPOT) ? Station::GetIfValid(v->current_order.GetDestination()) : nullptr;
2036 if (cur_st != nullptr && cur_st->airport.tile != INVALID_TILE && next_st != nullptr && next_st->airport.tile != INVALID_TILE) {
2037 uint dist = DistanceSquare(cur_st->airport.tile, next_st->airport.tile);
2038 AircraftHandleDestTooFar(v, dist > v->acache.cached_max_range_sqr);
2042 if (!HasBit(v->flags, VAF_DEST_TOO_FAR)) AirportGoToNextPosition(v);
2044 return true;
2047 bool Aircraft::Tick()
2049 if (!this->IsNormalAircraft()) return true;
2051 this->tick_counter++;
2053 if (!((this->vehstatus & VS_STOPPED) || this->IsChainInDepot())) this->running_ticks++;
2055 if (this->subtype == AIR_HELICOPTER) HelicopterTickHandler(this);
2057 this->current_order_time++;
2059 for (uint i = 0; i != 2; i++) {
2060 /* stop if the aircraft was deleted */
2061 if (!AircraftEventHandler(this, i)) return false;
2064 return true;
2069 * Returns aircraft's target station if v->target_airport
2070 * is a valid station with airport.
2071 * @param v vehicle to get target airport for
2072 * @return pointer to target station, nullptr if invalid
2074 Station *GetTargetAirportIfValid(const Aircraft *v)
2076 assert(v->type == VEH_AIRCRAFT);
2078 Station *st = Station::GetIfValid(v->targetairport);
2079 if (st == nullptr) return nullptr;
2081 return st->airport.tile == INVALID_TILE ? nullptr : st;
2085 * Updates the status of the Aircraft heading or in the station
2086 * @param st Station been updated
2088 void UpdateAirplanesOnNewStation(const Station *st)
2090 /* only 1 station is updated per function call, so it is enough to get entry_point once */
2091 const AirportFTAClass *ap = st->airport.GetFTA();
2092 Direction rotation = st->airport.tile == INVALID_TILE ? DIR_N : st->airport.rotation;
2094 Aircraft *v;
2095 FOR_ALL_AIRCRAFT(v) {
2096 if (!v->IsNormalAircraft() || v->targetairport != st->index) continue;
2097 assert(v->state == FLYING);
2098 v->pos = v->previous_pos = AircraftGetEntryPoint(v, ap, rotation);
2099 UpdateAircraftCache(v);