Merge road stop removal cases in BuildRoadToolbarWindow
[openttd/fttd.git] / src / aircraft_cmd.cpp
blob053560f7751629d9ba9588aff3f82d6ec2c9f006
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 "map/zoneheight.h"
41 #include "table/strings.h"
43 void Aircraft::UpdateDeltaXY(Direction direction)
45 this->x_offs = -1;
46 this->y_offs = -1;
47 this->x_extent = 2;
48 this->y_extent = 2;
50 switch (this->subtype) {
51 default: NOT_REACHED();
53 case AIR_AIRCRAFT:
54 case AIR_HELICOPTER:
55 switch (this->state) {
56 default: break;
57 case ENDTAKEOFF:
58 case LANDING:
59 case HELILANDING:
60 case FLYING:
61 this->x_extent = 24;
62 this->y_extent = 24;
63 break;
65 this->z_extent = 5;
66 break;
68 case AIR_SHADOW:
69 this->z_extent = 1;
70 this->x_offs = 0;
71 this->y_offs = 0;
72 break;
74 case AIR_ROTOR:
75 this->z_extent = 1;
76 break;
80 static bool AirportMove (Aircraft *v, const AirportFTA *apc);
81 static bool AirportFindFreeTerminal (Aircraft *v, const AirportFTA *apc);
82 static bool AirportFindFreeHelipad (Aircraft *v, const AirportFTA *apc);
83 static void CrashAirplane(Aircraft *v);
85 static const SpriteID _aircraft_sprite[] = {
86 0x0EB5, 0x0EBD, 0x0EC5, 0x0ECD,
87 0x0ED5, 0x0EDD, 0x0E9D, 0x0EA5,
88 0x0EAD, 0x0EE5, 0x0F05, 0x0F0D,
89 0x0F15, 0x0F1D, 0x0F25, 0x0F2D,
90 0x0EED, 0x0EF5, 0x0EFD, 0x0F35,
91 0x0E9D, 0x0EA5, 0x0EAD, 0x0EB5,
92 0x0EBD, 0x0EC5
95 template <>
96 bool IsValidImageIndex<VEH_AIRCRAFT>(uint8 image_index)
98 return image_index < lengthof(_aircraft_sprite);
101 /** Helicopter rotor animation states */
102 enum HelicopterRotorStates {
103 HRS_ROTOR_STOPPED,
104 HRS_ROTOR_MOVING_1,
105 HRS_ROTOR_MOVING_2,
106 HRS_ROTOR_MOVING_3,
110 * Find the nearest hangar to v
111 * INVALID_STATION is returned, if the company does not have any suitable
112 * airports (like helipads only)
113 * @param v vehicle looking for a hangar
114 * @return the StationID if one is found, otherwise, INVALID_STATION
116 static StationID FindNearestHangar(const Aircraft *v)
118 const Station *st;
119 uint best = 0;
120 StationID index = INVALID_STATION;
121 TileIndex vtile = TileVirtXY(v->x_pos, v->y_pos);
122 const AircraftVehicleInfo *avi = AircraftVehInfo(v->engine_type);
124 FOR_ALL_STATIONS(st) {
125 if (st->owner != v->owner || !(st->facilities & FACIL_AIRPORT)) continue;
127 const AirportFTA *afc = st->airport.GetFTA();
128 if (!st->airport.HasHangar() || (
129 /* don't crash the plane if we know it can't land at the airport */
130 (afc->flags & AirportFTA::SHORT_STRIP) &&
131 (avi->subtype & AIR_FAST) &&
132 !_cheats.no_jetcrash.value)) {
133 continue;
136 /* v->tile can't be used here, when aircraft is flying v->tile is set to 0 */
137 uint distance = DistanceSquare(vtile, st->airport.tile);
138 if (v->acache.cached_max_range_sqr != 0) {
139 /* Check if our current destination can be reached from the depot airport. */
140 const Station *cur_dest = GetTargetAirportIfValid(v);
141 if (cur_dest != NULL && DistanceSquare(st->airport.tile, cur_dest->airport.tile) > v->acache.cached_max_range_sqr) continue;
143 if (distance < best || index == INVALID_STATION) {
144 best = distance;
145 index = st->index;
148 return index;
151 void Aircraft::GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const
153 uint8 spritenum = this->spritenum;
155 if (is_custom_sprite(spritenum)) {
156 GetCustomVehicleSprite(this, direction, image_type, result);
157 if (result->IsValid()) return;
159 spritenum = this->GetEngine()->original_image_index;
162 assert(IsValidImageIndex<VEH_AIRCRAFT>(spritenum));
163 result->Set(direction + _aircraft_sprite[spritenum]);
166 void GetRotorImage(const Aircraft *v, EngineImageType image_type, VehicleSpriteSeq *result)
168 assert(v->subtype == AIR_HELICOPTER);
170 const Aircraft *w = v->Next()->Next();
171 if (is_custom_sprite(v->spritenum)) {
172 GetCustomRotorSprite(v, false, image_type, result);
173 if (result->IsValid()) return;
176 /* Return standard rotor sprites if there are no custom sprites for this helicopter */
177 result->Set(SPR_ROTOR_STOPPED + w->state);
180 static void GetAircraftIcon(EngineID engine, EngineImageType image_type, VehicleSpriteSeq *result)
182 const Engine *e = Engine::Get(engine);
183 uint8 spritenum = e->u.air.image_index;
185 if (is_custom_sprite(spritenum)) {
186 GetCustomVehicleIcon(engine, DIR_W, image_type, result);
187 if (result->IsValid()) return;
189 spritenum = e->original_image_index;
192 assert(IsValidImageIndex<VEH_AIRCRAFT>(spritenum));
193 result->Set(DIR_W + _aircraft_sprite[spritenum]);
196 void DrawAircraftEngine (BlitArea *dpi, int left, int right,
197 int preferred_x, int y, EngineID engine, PaletteID pal,
198 EngineImageType image_type)
200 VehicleSpriteSeq seq;
201 GetAircraftIcon(engine, image_type, &seq);
203 Rect rect;
204 seq.GetBounds(&rect);
205 preferred_x = Clamp(preferred_x,
206 left - UnScaleGUI(rect.left),
207 right - UnScaleGUI(rect.right));
209 seq.Draw (dpi, preferred_x, y, pal, pal == PALETTE_CRASH);
211 if (!(AircraftVehInfo(engine)->subtype & AIR_CTOL)) {
212 VehicleSpriteSeq rotor_seq;
213 GetCustomRotorIcon(engine, image_type, &rotor_seq);
214 if (!rotor_seq.IsValid()) rotor_seq.Set(SPR_ROTOR_STOPPED);
215 rotor_seq.Draw (dpi, preferred_x, y - ScaleGUITrad(5), PAL_NONE, false);
220 * Get the size of the sprite of an aircraft sprite heading west (used for lists).
221 * @param engine The engine to get the sprite from.
222 * @param[out] width The width of the sprite.
223 * @param[out] height The height of the sprite.
224 * @param[out] xoffs Number of pixels to shift the sprite to the right.
225 * @param[out] yoffs Number of pixels to shift the sprite downwards.
226 * @param image_type Context the sprite is used in.
228 void GetAircraftSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type)
230 VehicleSpriteSeq seq;
231 GetAircraftIcon(engine, image_type, &seq);
233 Rect rect;
234 seq.GetBounds(&rect);
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 (!CanEngineUseStation (e, st)) return CMD_ERROR;
259 if (flags & DC_EXEC) {
260 Aircraft *v = new Aircraft(); // aircraft
261 Aircraft *u = new Aircraft(); // shadow
262 *ret = v;
264 v->direction = DIR_SE;
266 v->owner = u->owner = _current_company;
268 v->tile = tile;
270 uint x = TileX(tile) * TILE_SIZE + 5;
271 uint y = TileY(tile) * TILE_SIZE + 3;
273 v->x_pos = u->x_pos = x;
274 v->y_pos = u->y_pos = y;
276 u->z_pos = GetSlopePixelZ(x, y);
277 v->z_pos = u->z_pos + 1;
279 v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL;
280 u->vehstatus = VS_HIDDEN | VS_UNCLICKABLE | VS_SHADOW;
282 v->spritenum = avi->image_index;
284 v->cargo_cap = avi->passenger_capacity;
285 v->refit_cap = 0;
286 u->cargo_cap = avi->mail_capacity;
287 u->refit_cap = 0;
289 v->cargo_type = e->GetDefaultCargoType();
290 u->cargo_type = CT_MAIL;
292 v->name = NULL;
293 v->last_station_visited = INVALID_STATION;
294 v->last_loading_station = INVALID_STATION;
296 v->acceleration = avi->acceleration;
297 v->engine_type = e->index;
298 u->engine_type = e->index;
300 v->subtype = (avi->subtype & AIR_CTOL ? AIR_AIRCRAFT : AIR_HELICOPTER);
301 v->UpdateDeltaXY(INVALID_DIR);
303 u->subtype = AIR_SHADOW;
304 u->UpdateDeltaXY(INVALID_DIR);
306 v->reliability = e->reliability;
307 v->reliability_spd_dec = e->reliability_spd_dec;
308 v->max_age = e->GetLifeLengthInDays();
310 _new_vehicle_id = v->index;
312 /* Depots are always the first positions in the finite state
313 * machine of an airport, in order. */
314 v->pos = st->airport.GetHangarDataByTile(tile)->id;
315 assert (st->airport.GetFTA()->data[v->pos].heading == HANGAR);
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->random_bits = VehicleRandomBits();
362 /* Use rotor's air.state to store the rotor animation frame */
363 w->state = HRS_ROTOR_STOPPED;
364 w->UpdateDeltaXY(INVALID_DIR);
366 u->SetNext(w);
367 w->UpdatePosition();
371 return CommandCost();
375 bool Aircraft::FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
377 const Station *st = GetTargetAirportIfValid(this);
378 /* If the station is not a valid airport or if it has no hangars */
379 if (st == NULL || !st->airport.HasHangar()) {
380 /* the aircraft has to search for a hangar on its own */
381 StationID station = FindNearestHangar(this);
383 if (station == INVALID_STATION) return false;
385 st = Station::Get(station);
388 if (location != NULL) *location = st->xy;
389 if (destination != NULL) *destination = st->index;
391 return true;
394 static void CheckIfAircraftNeedsService(Aircraft *v)
396 if (Company::Get(v->owner)->settings.vehicle.servint_aircraft == 0 || !v->NeedsAutomaticServicing()) return;
397 if (v->IsChainInDepot()) {
398 VehicleServiceInDepot(v);
399 return;
402 /* When we're parsing conditional orders and the like
403 * we don't want to consider going to a depot too. */
404 if (!v->current_order.IsType(OT_GOTO_DEPOT) && !v->current_order.IsType(OT_GOTO_STATION)) return;
406 const Station *st = Station::Get(v->current_order.GetDestination());
408 assert(st != NULL);
410 /* only goto depot if the target airport has a depot */
411 if (st->airport.HasHangar() && CanVehicleUseStation(v, st)) {
412 v->current_order.MakeGoToDepot(st->index, ODTFB_SERVICE);
413 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
414 } else if (v->current_order.IsType(OT_GOTO_DEPOT)) {
415 v->current_order.MakeDummy();
416 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
420 Money Aircraft::GetRunningCost() const
422 const Engine *e = this->GetEngine();
423 uint cost_factor = GetVehicleProperty(this, PROP_AIRCRAFT_RUNNING_COST_FACTOR, e->u.air.running_cost);
424 return GetPrice(PR_RUNNING_AIRCRAFT, cost_factor, e->GetGRF());
427 void Aircraft::OnNewDay()
429 if (!this->IsNormalAircraft()) return;
431 if ((++this->day_counter & 7) == 0) DecreaseVehicleValue(this);
433 CheckOrders(this);
435 CheckVehicleBreakdown(this);
436 AgeVehicle(this);
437 CheckIfAircraftNeedsService(this);
439 if (this->running_ticks == 0) return;
441 CommandCost cost(EXPENSES_AIRCRAFT_RUN, this->GetRunningCost() * this->running_ticks / (DAYS_IN_YEAR * DAY_TICKS));
443 this->profit_this_year -= cost.GetCost();
444 this->running_ticks = 0;
446 SubtractMoneyFromCompanyFract(this->owner, cost);
448 SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
449 SetWindowClassesDirty(WC_AIRCRAFT_LIST);
452 static void HelicopterTickHandler(Aircraft *v)
454 Aircraft *u = v->Next()->Next();
456 if (u->vehstatus & VS_HIDDEN) return;
458 /* if true, helicopter rotors do not rotate. This should only be the case if a helicopter is
459 * loading/unloading at a terminal or stopped */
460 if (v->current_order.IsType(OT_LOADING) || (v->vehstatus & VS_STOPPED)) {
461 if (u->cur_speed != 0) {
462 u->cur_speed++;
463 if (u->cur_speed >= 0x80 && u->state == HRS_ROTOR_MOVING_3) {
464 u->cur_speed = 0;
467 } else {
468 if (u->cur_speed == 0) {
469 u->cur_speed = 0x70;
471 if (u->cur_speed >= 0x50) {
472 u->cur_speed--;
476 int tick = ++u->tick_counter;
477 int spd = u->cur_speed >> 4;
479 VehicleSpriteSeq seq;
480 if (spd == 0) {
481 u->state = HRS_ROTOR_STOPPED;
482 GetRotorImage(v, EIT_ON_MAP, &seq);
483 if (u->sprite_seq == seq) return;
484 } else if (tick >= spd) {
485 u->tick_counter = 0;
486 u->state++;
487 if (u->state > HRS_ROTOR_MOVING_3) u->state = HRS_ROTOR_MOVING_1;
488 GetRotorImage(v, EIT_ON_MAP, &seq);
489 } else {
490 return;
493 u->sprite_seq = seq;
495 u->UpdatePositionAndViewport();
499 * Set aircraft position.
500 * @param v Aircraft to position.
501 * @param x New X position.
502 * @param y New y position.
503 * @param z New z position.
505 void SetAircraftPosition(Aircraft *v, int x, int y, int z)
507 v->x_pos = x;
508 v->y_pos = y;
509 v->z_pos = z;
511 v->UpdatePosition();
512 v->UpdateViewport(true, false);
513 if (v->subtype == AIR_HELICOPTER) {
514 GetRotorImage(v, EIT_ON_MAP, &v->Next()->Next()->sprite_seq);
517 Aircraft *u = v->Next();
519 int safe_x = Clamp(x, 0, MapMaxX() * TILE_SIZE);
520 int safe_y = Clamp(y - 1, 0, MapMaxY() * TILE_SIZE);
521 u->x_pos = x;
522 u->y_pos = y - ((v->z_pos - GetSlopePixelZ(safe_x, safe_y)) >> 3);
524 safe_y = Clamp(u->y_pos, 0, MapMaxY() * TILE_SIZE);
525 u->z_pos = GetSlopePixelZ(safe_x, safe_y);
526 u->sprite_seq.CopyWithoutPalette(v->sprite_seq); // the shadow is never coloured
528 u->UpdatePositionAndViewport();
530 u = u->Next();
531 if (u != NULL) {
532 u->x_pos = x;
533 u->y_pos = y;
534 u->z_pos = z + ROTOR_Z_OFFSET;
536 u->UpdatePositionAndViewport();
542 * Update cached values of an aircraft.
543 * Currently caches callback 36 max speed.
544 * @param v Vehicle
545 * @param update_range Update the aircraft range.
547 void UpdateAircraftCache(Aircraft *v, bool update_range)
549 uint max_speed = GetVehicleProperty(v, PROP_AIRCRAFT_SPEED, 0);
550 if (max_speed != 0) {
551 /* Convert from original units to km-ish/h */
552 max_speed = (max_speed * 128) / 10;
554 v->vcache.cached_max_speed = max_speed;
555 } else {
556 /* Use the default max speed of the vehicle. */
557 v->vcache.cached_max_speed = AircraftVehInfo(v->engine_type)->max_speed;
560 /* Update cargo aging period. */
561 v->vcache.cached_cargo_age_period = GetVehicleProperty(v, PROP_AIRCRAFT_CARGO_AGE_PERIOD, EngInfo(v->engine_type)->cargo_age_period);
562 Aircraft *u = v->Next(); // Shadow for mail
563 u->vcache.cached_cargo_age_period = GetVehicleProperty(u, PROP_AIRCRAFT_CARGO_AGE_PERIOD, EngInfo(u->engine_type)->cargo_age_period);
565 /* Update aircraft range. */
566 if (update_range) {
567 v->acache.cached_max_range = GetVehicleProperty(v, PROP_AIRCRAFT_RANGE, AircraftVehInfo(v->engine_type)->max_range);
568 /* Squared it now so we don't have to do it later all the time. */
569 v->acache.cached_max_range_sqr = v->acache.cached_max_range * v->acache.cached_max_range;
575 * Special velocities for aircraft
577 enum AircraftSpeedLimits {
578 SPEED_LIMIT_TAXI = 50, ///< Maximum speed of an aircraft while taxiing
579 SPEED_LIMIT_APPROACH = 230, ///< Maximum speed of an aircraft on finals
580 SPEED_LIMIT_BROKEN = 320, ///< Maximum speed of an aircraft that is broken
581 SPEED_LIMIT_HOLD = 425, ///< Maximum speed of an aircraft that flies the holding pattern
582 SPEED_LIMIT_NONE = 0xFFFF, ///< No environmental speed limit. Speed limit is type dependent
586 * Sets the new speed for an aircraft
587 * @param v The vehicle for which the speed should be obtained
588 * @param speed_limit The maximum speed the vehicle may have.
589 * @param hard_limit If true, the limit is directly enforced, otherwise the plane is slowed down gradually
590 * @return The number of position updates needed within the tick
592 static int UpdateAircraftSpeed(Aircraft *v, uint speed_limit = SPEED_LIMIT_NONE, bool hard_limit = true)
595 * 'acceleration' has the unit 3/8 mph/tick. This function is called twice per tick.
596 * So the speed amount we need to accelerate is:
597 * acceleration * 3 / 16 mph = acceleration * 3 / 16 * 16 / 10 km-ish/h
598 * = acceleration * 3 / 10 * 256 * (km-ish/h / 256)
599 * ~ acceleration * 77 (km-ish/h / 256)
601 uint spd = v->acceleration * 77;
602 byte t;
604 /* Adjust speed limits by plane speed factor to prevent taxiing
605 * and take-off speeds being too low. */
606 speed_limit *= _settings_game.vehicle.plane_speed;
608 if (v->vcache.cached_max_speed < speed_limit) {
609 if (v->cur_speed < speed_limit) hard_limit = false;
610 speed_limit = v->vcache.cached_max_speed;
613 v->subspeed = (t = v->subspeed) + (byte)spd;
615 /* Aircraft's current speed is used twice so that very fast planes are
616 * forced to slow down rapidly in the short distance needed. The magic
617 * value 16384 was determined to give similar results to the old speed/48
618 * method at slower speeds. This also results in less reduction at slow
619 * speeds to that aircraft do not get to taxi speed straight after
620 * touchdown. */
621 if (!hard_limit && v->cur_speed > speed_limit) {
622 speed_limit = v->cur_speed - max(1, ((v->cur_speed * v->cur_speed) / 16384) / _settings_game.vehicle.plane_speed);
625 spd = min(v->cur_speed + (spd >> 8) + (v->subspeed < t), speed_limit);
627 /* adjust speed for broken vehicles */
628 if (v->vehstatus & VS_AIRCRAFT_BROKEN) spd = min(spd, SPEED_LIMIT_BROKEN);
630 /* updates statusbar only if speed have changed to save CPU time */
631 if (spd != v->cur_speed) {
632 v->cur_speed = spd;
633 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
636 /* Adjust distance moved by plane speed setting */
637 if (_settings_game.vehicle.plane_speed > 1) spd /= _settings_game.vehicle.plane_speed;
639 /* Convert direction-independent speed into direction-dependent speed. (old movement method) */
640 spd = v->GetOldAdvanceSpeed(spd);
642 spd += v->progress;
643 v->progress = (byte)spd;
644 return spd >> 8;
648 * Get the base altitude for an aircraft, which is used as reference to
649 * compute flight levels.
650 * @param v The vehicle to get the base altitude for.
651 * @return The base altitude in pixels.
653 static int GetAircraftBaseAltitude (const Vehicle *v)
655 int safe_x = Clamp(v->x_pos, 0, MapMaxX() * TILE_SIZE);
656 int safe_y = Clamp(v->y_pos, 0, MapMaxY() * TILE_SIZE);
657 int z = TileHeight (TileVirtXY (safe_x, safe_y)) * TILE_HEIGHT;
659 /* Base altitude is 120 pixels above ground. */
660 z += 120;
662 if (v->type == VEH_AIRCRAFT && Aircraft::From(v)->subtype == AIR_HELICOPTER) {
663 /* Base altitude is higher for helicopters. */
664 z += 34;
667 return z;
671 * Get the base flight level for an aircraft.
672 * @param v The vehicle to get the base flight level for.
673 * @return The base flight level in pixels.
675 int GetAircraftBaseFlightLevel (const Vehicle *v)
677 int z = GetAircraftBaseAltitude (v);
679 if (v->type == VEH_AIRCRAFT && Aircraft::From(v)->subtype != AIR_HELICOPTER) {
680 /* Make sure eastbound and westbound planes do not "crash" into
681 * each other by providing them with vertical separation. */
682 if (v->direction < (DIR_END / 2)) z += 10;
684 /* Make faster planes fly higher so that they can overtake slower ones */
685 z += min (20 * (v->vcache.cached_max_speed / 200) - 90, 0);
688 return z;
692 * Gets the maximum 'flight level' for the holding pattern of the aircraft,
693 * in pixels 'z_pos' 0, depending on terrain below..
695 * @param v The aircraft that may or may not need to decrease its altitude.
696 * @return Maximal aircraft holding altitude, while in normal flight, in pixels.
698 static int GetAircraftHoldMaxAltitude (const Aircraft *v)
700 /* Holding altitude range is 30 pixels. */
701 return GetAircraftBaseAltitude(v) + 30;
704 int GetAircraftFlightLevel (const Vehicle *v, byte *flags, bool takeoff)
706 /* Aircraft is in flight. We want to enforce it being somewhere
707 * between the minimum and the maximum allowed altitude. */
708 int aircraft_min_altitude = GetAircraftBaseFlightLevel (v);
710 /* Flight altitude range is 240 pixels. */
711 int aircraft_max_altitude = aircraft_min_altitude + 240;
713 int aircraft_middle_altitude = aircraft_min_altitude + 120;
715 int z = v->z_pos;
716 if (z < aircraft_min_altitude ||
717 (HasBit(*flags, VAF_IN_MIN_HEIGHT_CORRECTION) && z < aircraft_middle_altitude)) {
718 /* Ascend. And don't fly into that mountain right ahead.
719 * And avoid our aircraft become a stairclimber, so if we start
720 * correcting altitude, then we stop correction not too early. */
721 SetBit(*flags, VAF_IN_MIN_HEIGHT_CORRECTION);
722 z += takeoff ? 2 : 1;
723 } else if (!takeoff && (z > aircraft_max_altitude ||
724 (HasBit(*flags, VAF_IN_MAX_HEIGHT_CORRECTION) && z > aircraft_middle_altitude))) {
725 /* Descend lower. You are an aircraft, not an space ship.
726 * And again, don't stop correcting altitude too early. */
727 SetBit(*flags, VAF_IN_MAX_HEIGHT_CORRECTION);
728 z--;
729 } else if (HasBit(*flags, VAF_IN_MIN_HEIGHT_CORRECTION) && z >= aircraft_middle_altitude) {
730 /* Now, we have corrected altitude enough. */
731 ClrBit(*flags, VAF_IN_MIN_HEIGHT_CORRECTION);
732 } else if (HasBit(*flags, VAF_IN_MAX_HEIGHT_CORRECTION) && z <= aircraft_middle_altitude) {
733 /* Now, we have corrected altitude enough. */
734 ClrBit(*flags, VAF_IN_MAX_HEIGHT_CORRECTION);
737 return z;
741 * Find the entry point to an airport depending on direction which
742 * the airport is being approached from. Each airport can have up to
743 * four entry points for its approach system so that approaching
744 * aircraft do not fly through each other or are forced to do 180
745 * degree turns during the approach. The arrivals are grouped into
746 * four sectors dependent on the DiagDirection from which the airport
747 * is approached.
749 * @param v The vehicle that is approaching the airport
750 * @param apc The Airport Class being approached.
751 * @param rotation The rotation of the airport.
752 * @return The index of the entry point
754 static byte AircraftGetEntryPoint (const Aircraft *v, const AirportFTA *apc, Direction rotation)
756 assert(v != NULL);
757 assert(apc != NULL);
759 /* In the case the station doesn't exit anymore, set target tile 0.
760 * It doesn't hurt much, aircraft will go to next order, nearest hangar
761 * or it will simply crash in next tick */
762 TileIndex tile = 0;
764 const Station *st = Station::GetIfValid(v->targetairport);
765 if (st != NULL) {
766 /* Make sure we don't go to INVALID_TILE if the airport has been removed. */
767 tile = (st->airport.tile != INVALID_TILE) ? st->airport.tile : st->xy;
770 int delta_x = v->x_pos - TileX(tile) * TILE_SIZE;
771 int delta_y = v->y_pos - TileY(tile) * TILE_SIZE;
773 DiagDirection dir;
774 if (abs(delta_y) < abs(delta_x)) {
775 /* We are northeast or southwest of the airport */
776 dir = delta_x < 0 ? DIAGDIR_NE : DIAGDIR_SW;
777 } else {
778 /* We are northwest or southeast of the airport */
779 dir = delta_y < 0 ? DIAGDIR_NW : DIAGDIR_SE;
781 dir = ChangeDiagDir(dir, DiagDirDifference(DIAGDIR_NE, DirToDiagDir(rotation)));
782 return apc->entry_points[dir];
786 static bool MaybeCrashAirplane(Aircraft *v);
789 * Controls the movement of an aircraft. This function actually moves the vehicle
790 * on the map and takes care of minor things like sound playback.
791 * @todo De-mystify the cur_speed values for helicopter rotors.
792 * @param v The vehicle that is moved. Must be the first vehicle of the chain
793 * @return Whether the position requested by the State Machine has been reached
795 static bool AircraftController(Aircraft *v)
797 int count;
799 /* NULL if station is invalid */
800 const Station *st = Station::GetIfValid(v->targetairport);
801 /* INVALID_TILE if there is no station */
802 TileIndex tile = INVALID_TILE;
803 Direction rotation = DIR_N;
804 uint size_x = 1, size_y = 1;
805 if (st != NULL) {
806 if (st->airport.tile != INVALID_TILE) {
807 tile = st->airport.tile;
808 rotation = st->airport.rotation;
809 size_x = st->airport.w;
810 size_y = st->airport.h;
811 } else {
812 tile = st->xy;
815 /* DUMMY if there is no station or no airport */
816 const AirportFTA *afc = tile == INVALID_TILE ? &AirportFTA::dummy : st->airport.GetFTA();
818 /* prevent going to INVALID_TILE if airport is deleted. */
819 if (st == NULL || st->airport.tile == INVALID_TILE) {
820 /* Jump into our "holding pattern" state machine if possible */
821 if (v->pos >= afc->nofelements) {
822 v->pos = v->previous_pos = AircraftGetEntryPoint(v, afc, DIR_N);
823 } else if (v->targetairport != v->current_order.GetDestination()) {
824 /* If not possible, just get out of here fast */
825 v->state = FLYING;
826 UpdateAircraftCache(v);
827 AircraftNextAirportPos_and_Order(v);
828 /* get aircraft back on running altitude */
829 SetAircraftPosition(v, v->x_pos, v->y_pos, GetAircraftFlightLevel(v));
830 return false;
834 /* get airport moving data */
835 assert (v->pos < afc->nofelements);
836 const AirportFTA::Position *amd = &afc->data[v->pos];
838 int x = TileX(tile) * TILE_SIZE;
839 int y = TileY(tile) * TILE_SIZE;
841 /* Helicopter raise */
842 if (amd->flags & AMED_HELI_RAISE) {
843 Aircraft *u = v->Next()->Next();
845 /* Make sure the rotors don't rotate too fast */
846 if (u->cur_speed > 32) {
847 v->cur_speed = 0;
848 if (--u->cur_speed == 32) {
849 if (!PlayVehicleSound(v, VSE_START)) {
850 SndPlayVehicleFx(SND_18_HELICOPTER, v);
853 } else {
854 u->cur_speed = 32;
855 count = UpdateAircraftSpeed(v);
856 if (count > 0) {
857 v->tile = 0;
859 int z_dest = GetAircraftBaseFlightLevel (v);
861 /* Reached altitude? */
862 if (v->z_pos >= z_dest) {
863 v->cur_speed = 0;
864 return true;
866 SetAircraftPosition(v, v->x_pos, v->y_pos, min(v->z_pos + count, z_dest));
869 return false;
872 /* Helicopter landing. */
873 if (amd->flags & AMED_HELI_LOWER) {
874 if (st == NULL) {
875 /* FIXME - AircraftController -> if station no longer exists, do not land
876 * helicopter will circle until sign disappears, then go to next order
877 * what to do when it is the only order left, right now it just stays in 1 place */
878 v->state = FLYING;
879 UpdateAircraftCache(v);
880 AircraftNextAirportPos_and_Order(v);
881 return false;
884 /* Vehicle is now at the airport. */
885 v->tile = tile;
887 /* Find altitude of landing position. */
888 int z = GetSlopePixelZ(x, y) + 1 + afc->delta_z;
890 if (z == v->z_pos) {
891 Vehicle *u = v->Next()->Next();
893 /* Increase speed of rotors. When speed is 80, we've landed. */
894 if (u->cur_speed >= 80) return true;
895 u->cur_speed += 4;
896 } else {
897 count = UpdateAircraftSpeed(v);
898 if (count > 0) {
899 if (v->z_pos > z) {
900 SetAircraftPosition(v, v->x_pos, v->y_pos, max(v->z_pos - count, z));
901 } else {
902 SetAircraftPosition(v, v->x_pos, v->y_pos, min(v->z_pos + count, z));
906 return false;
909 int amd_x = x;
910 int amd_y = y;
911 switch (rotation) {
912 case DIR_N:
913 amd_x += amd->x;
914 amd_y += amd->y;
915 break;
917 case DIR_E:
918 amd_x += amd->y;
919 amd_y += size_y * TILE_SIZE - amd->x - 1;
920 break;
922 case DIR_S:
923 amd_x += size_x * TILE_SIZE - amd->x - 1;
924 amd_y += size_y * TILE_SIZE - amd->y - 1;
925 break;
927 case DIR_W:
928 amd_x += size_x * TILE_SIZE - amd->y - 1;
929 amd_y += amd->x;
930 break;
932 default: NOT_REACHED();
935 /* Get distance from destination pos to current pos. */
936 uint dist = abs (amd_x - v->x_pos) + abs (amd_y - v->y_pos);
938 /* Need exact position? */
939 if (!(amd->flags & AMED_EXACTPOS) && dist <= (amd->flags & AMED_SLOWTURN ? 8U : 4U)) return true;
941 /* At final pos? */
942 if (dist == 0) {
943 /* Change direction smoothly to final direction. */
944 Direction dir = (Direction)(amd->flags & 0x7);
945 dir = ChangeDir (dir, (DirDiff) rotation);
946 DirDiff dirdiff = DirDifference (dir, v->direction);
947 /* if distance is 0, and plane points in right direction, no point in calling
948 * UpdateAircraftSpeed(). So do it only afterwards */
949 if (dirdiff == DIRDIFF_SAME) {
950 v->cur_speed = 0;
951 return true;
954 if (!UpdateAircraftSpeed(v, SPEED_LIMIT_TAXI)) return false;
956 v->direction = ChangeDir(v->direction, dirdiff > DIRDIFF_REVERSE ? DIRDIFF_45LEFT : DIRDIFF_45RIGHT);
957 v->cur_speed >>= 1;
959 SetAircraftPosition(v, v->x_pos, v->y_pos, v->z_pos);
960 return false;
963 if (amd->flags & AMED_BRAKE && v->cur_speed > SPEED_LIMIT_TAXI * _settings_game.vehicle.plane_speed) {
964 if (MaybeCrashAirplane(v)) return false;
967 uint speed_limit = SPEED_LIMIT_TAXI;
968 bool hard_limit = true;
970 if (amd->flags & AMED_NOSPDCLAMP) speed_limit = SPEED_LIMIT_NONE;
971 if (amd->flags & AMED_HOLD) { speed_limit = SPEED_LIMIT_HOLD; hard_limit = false; }
972 if (amd->flags & AMED_LAND) { speed_limit = SPEED_LIMIT_APPROACH; hard_limit = false; }
973 if (amd->flags & AMED_BRAKE) { speed_limit = SPEED_LIMIT_TAXI; hard_limit = false; }
975 count = UpdateAircraftSpeed(v, speed_limit, hard_limit);
976 if (count == 0) return false;
978 if (v->turn_counter != 0) v->turn_counter--;
980 do {
981 FullPosTile gp;
983 if (dist < 4 || (amd->flags & AMED_LAND)) {
984 /* move vehicle one pixel towards target */
985 gp.set_towards (v->x_pos, v->y_pos, amd_x, amd_y);
987 /* Oilrigs must keep v->tile as st->airport.tile, since the landing pad is in a non-airport tile */
988 if (st->airport.type == AT_OILRIG) gp.tile = st->airport.tile;
990 } else {
992 /* Turn. Do it slowly if in the air. */
993 Direction newdir = GetDirectionTowards (v, amd_x, amd_y);
994 if (newdir == v->direction) {
995 v->number_consecutive_turns = 0;
996 /* Move vehicle. */
997 gp = GetNewVehiclePos(v);
998 } else if (amd->flags & AMED_SLOWTURN && v->number_consecutive_turns < 8 && v->subtype == AIR_AIRCRAFT) {
999 if (v->turn_counter == 0 || newdir == v->last_direction) {
1000 if (newdir == v->last_direction) {
1001 v->number_consecutive_turns = 0;
1002 } else {
1003 v->number_consecutive_turns++;
1005 v->turn_counter = 2 * _settings_game.vehicle.plane_speed;
1006 v->last_direction = v->direction;
1007 v->direction = newdir;
1010 /* Move vehicle. */
1011 gp = GetNewVehiclePos(v);
1012 } else {
1013 v->cur_speed >>= 1;
1014 v->direction = newdir;
1016 /* When leaving a terminal an aircraft often goes to a position
1017 * directly in front of it. If it would move while turning it
1018 * would need an two extra turns to end up at the correct position.
1019 * To make it easier just disallow all moving while turning as
1020 * long as an aircraft is on the ground. */
1021 gp.set (v->x_pos, v->y_pos, v->tile);
1025 v->tile = gp.tile;
1026 /* If vehicle is in the air, use tile coordinate 0. */
1027 if (amd->flags & (AMED_TAKEOFF | AMED_SLOWTURN | AMED_LAND)) v->tile = 0;
1029 /* Adjust Z for land or takeoff? */
1030 int z = v->z_pos;
1032 if (amd->flags & AMED_TAKEOFF) {
1033 z = GetAircraftFlightLevel(v, true);
1034 } else if (amd->flags & AMED_HOLD) {
1035 /* Let the plane drop from normal flight altitude to holding pattern altitude */
1036 if (z > GetAircraftHoldMaxAltitude(v)) z--;
1037 } else if ((amd->flags & AMED_SLOWTURN) && (amd->flags & AMED_NOSPDCLAMP)) {
1038 z = GetAircraftFlightLevel(v);
1041 if (amd->flags & AMED_LAND) {
1042 if (st->airport.tile == INVALID_TILE) {
1043 /* Airport has been removed, abort the landing procedure */
1044 v->state = FLYING;
1045 UpdateAircraftCache(v);
1046 AircraftNextAirportPos_and_Order(v);
1047 /* get aircraft back on running altitude */
1048 SetAircraftPosition(v, gp.xx, gp.yy, GetAircraftFlightLevel(v));
1049 continue;
1052 int curz = GetSlopePixelZ (amd_x, amd_y) + 1;
1054 /* We're not flying below our destination, right? */
1055 assert(curz <= z);
1056 int t = max(1U, dist - 4);
1057 int delta = z - curz;
1059 /* Only start lowering when we're sufficiently close for a 1:1 glide */
1060 if (delta >= t) {
1061 z -= CeilDiv(z - curz, t);
1063 if (z < curz) z = curz;
1066 /* We've landed. Decrease speed when we're reaching end of runway. */
1067 if (amd->flags & AMED_BRAKE) {
1068 int curz = GetSlopePixelZ(x, y) + 1;
1070 if (z > curz) {
1071 z--;
1072 } else if (z < curz) {
1073 z++;
1078 SetAircraftPosition(v, gp.xx, gp.yy, z);
1079 } while (--count != 0);
1080 return false;
1084 * Handle crashed aircraft \a v.
1085 * @param v Crashed aircraft.
1087 static bool HandleCrashedAircraft(Aircraft *v)
1089 v->crashed_counter += 3;
1091 Station *st = GetTargetAirportIfValid(v);
1093 /* make aircraft crash down to the ground */
1094 if (v->crashed_counter < 500 && st == NULL && ((v->crashed_counter % 3) == 0) ) {
1095 int z = GetSlopePixelZ(Clamp(v->x_pos, 0, MapMaxX() * TILE_SIZE), Clamp(v->y_pos, 0, MapMaxY() * TILE_SIZE));
1096 v->z_pos -= 1;
1097 if (v->z_pos == z) {
1098 v->crashed_counter = 500;
1099 v->z_pos++;
1103 if (v->crashed_counter < 650) {
1104 uint32 r;
1105 if (Chance16R(1, 32, r)) {
1106 static const DirDiff delta[] = {
1107 DIRDIFF_45LEFT, DIRDIFF_SAME, DIRDIFF_SAME, DIRDIFF_45RIGHT
1110 v->direction = ChangeDir(v->direction, delta[GB(r, 16, 2)]);
1111 SetAircraftPosition(v, v->x_pos, v->y_pos, v->z_pos);
1112 r = Random();
1113 CreateEffectVehicleRel(v,
1114 GB(r, 0, 4) - 4,
1115 GB(r, 4, 4) - 4,
1116 GB(r, 8, 4),
1117 EV_EXPLOSION_SMALL);
1119 } else if (v->crashed_counter >= 10000) {
1120 /* remove rubble of crashed airplane */
1122 /* clear runway-in on all airports, set by crashing plane
1123 * small airports use AIRPORT_BUSY, city airports use RUNWAY_IN_OUT_block, etc.
1124 * but they all share the same number */
1125 if (st != NULL) {
1126 CLRBITS(st->airport.flags, RUNWAY_IN_block);
1127 CLRBITS(st->airport.flags, RUNWAY_IN_OUT_block); // commuter airport
1128 CLRBITS(st->airport.flags, RUNWAY_IN2_block); // intercontinental
1131 delete v;
1133 return false;
1136 return true;
1141 * Handle smoke of broken aircraft.
1142 * @param v Aircraft
1143 * @param mode Is this the non-first call for this vehicle in this tick?
1145 static void HandleAircraftSmoke(Aircraft *v, bool mode)
1147 static const struct {
1148 int8 x;
1149 int8 y;
1150 } smoke_pos[] = {
1151 { 5, 5 },
1152 { 6, 0 },
1153 { 5, -5 },
1154 { 0, -6 },
1155 { -5, -5 },
1156 { -6, 0 },
1157 { -5, 5 },
1158 { 0, 6 }
1161 if (!(v->vehstatus & VS_AIRCRAFT_BROKEN)) return;
1163 /* Stop smoking when landed */
1164 if (v->cur_speed < 10) {
1165 v->vehstatus &= ~VS_AIRCRAFT_BROKEN;
1166 v->breakdown_ctr = 0;
1167 return;
1170 /* Spawn effect et most once per Tick, i.e. !mode */
1171 if (!mode && (v->tick_counter & 0x0F) == 0) {
1172 CreateEffectVehicleRel(v,
1173 smoke_pos[v->direction].x,
1174 smoke_pos[v->direction].y,
1176 EV_BREAKDOWN_SMOKE_AIRCRAFT
1181 void HandleMissingAircraftOrders(Aircraft *v)
1184 * We do not have an order. This can be divided into two cases:
1185 * 1) we are heading to an invalid station. In this case we must
1186 * find another airport to go to. If there is nowhere to go,
1187 * we will destroy the aircraft as it otherwise will enter
1188 * the holding pattern for the first airport, which can cause
1189 * the plane to go into an undefined state when building an
1190 * airport with the same StationID.
1191 * 2) we are (still) heading to a (still) valid airport, then we
1192 * can continue going there. This can happen when you are
1193 * changing the aircraft's orders while in-flight or in for
1194 * example a depot. However, when we have a current order to
1195 * go to a depot, we have to keep that order so the aircraft
1196 * actually stops.
1198 const Station *st = GetTargetAirportIfValid(v);
1199 if (st == NULL) {
1200 Backup<CompanyByte> cur_company(_current_company, v->owner, FILE_LINE);
1201 CommandCost ret = DoCommand(v->tile, v->index, 0, DC_EXEC, CMD_SEND_VEHICLE_TO_DEPOT);
1202 cur_company.Restore();
1204 if (ret.Failed()) CrashAirplane(v);
1205 } else if (!v->current_order.IsType(OT_GOTO_DEPOT)) {
1206 v->current_order.Clear();
1211 TileIndex Aircraft::GetOrderStationLocation(StationID station)
1213 /* Orders are changed in flight, ensure going to the right station. */
1214 if (this->state == FLYING) {
1215 AircraftNextAirportPos_and_Order(this);
1218 /* Aircraft do not use dest-tile */
1219 return 0;
1222 void Aircraft::MarkDirty()
1224 this->colourmap = PAL_NONE;
1225 this->UpdateViewport(true, false);
1226 if (this->subtype == AIR_HELICOPTER) {
1227 GetRotorImage(this, EIT_ON_MAP, &this->Next()->Next()->sprite_seq);
1232 uint Aircraft::Crash(bool flooded)
1234 uint pass = Vehicle::Crash(flooded) + 2; // pilots
1235 this->crashed_counter = flooded ? 9000 : 0; // max 10000, disappear pretty fast when flooded
1237 return pass;
1241 * Bring the aircraft in a crashed state, create the explosion animation, and create a news item about the crash.
1242 * @param v Aircraft that crashed.
1244 static void CrashAirplane(Aircraft *v)
1246 CreateEffectVehicleRel(v, 4, 4, 8, EV_EXPLOSION_LARGE);
1248 uint pass = v->Crash();
1250 v->cargo.Truncate();
1251 v->Next()->cargo.Truncate();
1252 const Station *st = GetTargetAirportIfValid(v);
1254 AI::NewEvent(v->owner, new ScriptEventVehicleCrashed(v->index, v->tile, st == NULL ? ScriptEventVehicleCrashed::CRASH_AIRCRAFT_NO_AIRPORT : ScriptEventVehicleCrashed::CRASH_PLANE_LANDING));
1255 Game::NewEvent(new ScriptEventVehicleCrashed(v->index, v->tile, st == NULL ? ScriptEventVehicleCrashed::CRASH_AIRCRAFT_NO_AIRPORT : ScriptEventVehicleCrashed::CRASH_PLANE_LANDING));
1257 AddNewsItem<PlaneCrashNewsItem> (v->index, st, pass);
1259 ModifyStationRatingAround(v->tile, v->owner, -160, 30);
1260 if (_settings_client.sound.disaster) SndPlayVehicleFx(SND_12_EXPLOSION, v);
1264 * Decide whether aircraft \a v should crash.
1265 * @param v Aircraft to test.
1266 * @return Whether the aircraft has been crashed
1268 static bool MaybeCrashAirplane(Aircraft *v)
1270 if (_settings_game.vehicle.plane_crashes == 0) return false;
1272 Station *st = Station::Get(v->targetairport);
1274 /* FIXME -- MaybeCrashAirplane -> increase crashing chances of very modern airplanes on smaller than AT_METROPOLITAN airports */
1275 uint32 prob = (0x4000 << _settings_game.vehicle.plane_crashes);
1276 if ((st->airport.GetFTA()->flags & AirportFTA::SHORT_STRIP) &&
1277 (AircraftVehInfo(v->engine_type)->subtype & AIR_FAST) &&
1278 !_cheats.no_jetcrash.value) {
1279 prob /= 20;
1280 } else {
1281 prob /= 1500;
1284 if (GB(Random(), 0, 22) > prob) return false;
1286 /* Crash the airplane. Remove all goods stored at the station. */
1287 for (CargoID i = 0; i < NUM_CARGO; i++) {
1288 st->goods[i].rating = 1;
1289 st->goods[i].cargo.Truncate();
1292 CrashAirplane(v);
1293 return true;
1296 /** returns true if the road ahead is busy, eg. you must wait before proceeding. */
1297 static bool AirportHasBlock (Aircraft *v, const AirportFTA *apc)
1299 const AirportFTA::Position *pos = &apc->data[v->pos];
1300 uint64 next_block = apc->data[pos->next_position].block;
1302 /* same block, then of course we can move */
1303 if (pos->block == next_block) return false;
1305 if (Station::Get(v->targetairport)->airport.flags & next_block) {
1306 v->cur_speed = 0;
1307 v->subspeed = 0;
1308 return true;
1311 return false;
1315 * Aircraft arrives at a terminal. If it is the first aircraft, throw a party.
1316 * Start loading cargo.
1317 * @param v Aircraft that arrived.
1319 static void AircraftEntersTerminal(Aircraft *v)
1321 if (v->current_order.IsType(OT_GOTO_DEPOT)) return;
1323 Station *st = Station::Get(v->targetairport);
1324 v->last_station_visited = v->targetairport;
1326 /* Check if station was ever visited before */
1327 if (!(st->had_vehicle_of_type & HVOT_AIRCRAFT)) {
1328 st->had_vehicle_of_type |= HVOT_AIRCRAFT;
1329 /* show newsitem of celebrating citizens */
1330 AddNewsItem<ArrivalNewsItem> (STR_NEWS_FIRST_AIRCRAFT_ARRIVAL, v, st);
1331 AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
1332 Game::NewEvent(new ScriptEventStationFirstVehicle(st->index, v->index));
1335 v->BeginLoading();
1339 /** set the right pos when heading to other airports after takeoff */
1340 void AircraftNextAirportPos_and_Order(Aircraft *v)
1342 if (v->current_order.IsType(OT_GOTO_STATION) || v->current_order.IsType(OT_GOTO_DEPOT)) {
1343 v->targetairport = v->current_order.GetDestination();
1346 const Station *st = GetTargetAirportIfValid(v);
1347 const AirportFTA *apc = st == NULL ? &AirportFTA::dummy : st->airport.GetFTA();
1348 Direction rotation = st == NULL ? DIR_N : st->airport.rotation;
1349 v->pos = v->previous_pos = AircraftGetEntryPoint(v, apc, rotation);
1353 * Aircraft is about to leave the hangar.
1354 * @param v Aircraft leaving.
1355 * @param exit_dir The direction the vehicle leaves the hangar.
1356 * @note This function is called in AfterLoadGame for old savegames, so don't rely
1357 * on any data to be valid, especially don't rely on the fact that the vehicle
1358 * is actually on the ground inside a depot.
1360 void AircraftLeaveHangar(Aircraft *v, Direction exit_dir)
1362 v->cur_speed = 0;
1363 v->subspeed = 0;
1364 v->progress = 0;
1365 v->direction = exit_dir;
1366 v->vehstatus &= ~VS_HIDDEN;
1368 Vehicle *u = v->Next();
1369 u->vehstatus &= ~VS_HIDDEN;
1371 /* Rotor blades */
1372 u = u->Next();
1373 if (u != NULL) {
1374 u->vehstatus &= ~VS_HIDDEN;
1375 u->cur_speed = 80;
1379 VehicleServiceInDepot(v);
1380 SetAircraftPosition(v, v->x_pos, v->y_pos, v->z_pos);
1381 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
1382 SetWindowClassesDirty(WC_AIRCRAFT_LIST);
1386 * Aircraft entirely entered the depot, update its status, orders, vehicle windows, service it, etc.
1387 * @param v Aircraft that entered a depot.
1389 static void AircraftEnterDepot (Aircraft *v)
1391 SetWindowClassesDirty (WC_AIRCRAFT_LIST);
1393 v->subspeed = 0;
1394 v->progress = 0;
1396 Aircraft *u = v->Next();
1397 u->vehstatus |= VS_HIDDEN;
1398 u = u->Next();
1399 if (u != NULL) {
1400 u->vehstatus |= VS_HIDDEN;
1401 u->cur_speed = 0;
1404 SetAircraftPosition (v, v->x_pos, v->y_pos, v->z_pos);
1406 VehicleEnterDepot (v);
1409 ////////////////////////////////////////////////////////////////////////////////
1410 /////////////////// AIRCRAFT MOVEMENT SCHEME ////////////////////////////////
1411 ////////////////////////////////////////////////////////////////////////////////
1414 * Handle aircraft movement/decision making in an airport hangar.
1415 * @param v Aircraft in the hangar.
1416 * @param apc Airport description containing the hangar.
1418 static void AircraftEventHandler_InHangar (Aircraft *v, const AirportFTA *apc)
1420 /* if we just arrived, execute EnterHangar first */
1421 if (v->previous_pos != v->pos) {
1422 AircraftEnterDepot (v);
1423 v->state = apc->data[v->pos].heading;
1424 return;
1427 /* if we were sent to the depot, stay there */
1428 if (v->current_order.IsType(OT_GOTO_DEPOT) && (v->vehstatus & VS_STOPPED)) {
1429 v->current_order.Clear();
1430 return;
1433 if (!v->current_order.IsType(OT_GOTO_STATION) &&
1434 !v->current_order.IsType(OT_GOTO_DEPOT))
1435 return;
1437 /* We are leaving a hangar, but have to go to the exact same one; re-enter */
1438 if (v->current_order.IsType(OT_GOTO_DEPOT) && v->current_order.GetDestination() == v->targetairport) {
1439 AircraftEnterDepot (v);
1440 return;
1443 /* if the block of the next position is busy, stay put */
1444 if (AirportHasBlock (v, apc)) return;
1446 /* We are already at the target airport, we need to find a terminal */
1447 if (v->current_order.GetDestination() == v->targetairport) {
1448 /* FindFreeTerminal:
1449 * 1. Find a free terminal, 2. Occupy it, 3. Set the vehicle's state to that terminal */
1450 if (v->subtype == AIR_HELICOPTER) {
1451 if (!AirportFindFreeHelipad(v, apc)) return; // helicopter
1452 } else {
1453 if (!AirportFindFreeTerminal(v, apc)) return; // airplane
1455 } else { // Else prepare for launch.
1456 /* airplane goto state takeoff, helicopter to helitakeoff */
1457 v->state = (v->subtype == AIR_HELICOPTER) ? HELITAKEOFF : TAKEOFF;
1459 const Station *st = Station::GetByTile(v->tile);
1460 AircraftLeaveHangar(v, st->airport.GetHangarExitDirection(v->tile));
1461 AirportMove(v, apc);
1464 /** At one of the Airport's Terminals */
1465 static void AircraftEventHandler_AtTerminal (Aircraft *v, const AirportFTA *apc)
1467 /* if we just arrived, execute EnterTerminal first */
1468 if (v->previous_pos != v->pos) {
1469 AircraftEntersTerminal (v);
1470 v->state = apc->data[v->pos].heading;
1471 /* on an airport with helipads, a helicopter will always land there
1472 * and get serviced at the same time - setting */
1473 if (_settings_game.order.serviceathelipad) {
1474 if (v->subtype == AIR_HELICOPTER && apc->num_helipads > 0) {
1475 /* an excerpt of ServiceAircraft, without the invisibility stuff */
1476 v->date_of_last_service = _date;
1477 v->breakdowns_since_last_service = 0;
1478 v->reliability = v->GetEngine()->reliability;
1479 SetWindowDirty(WC_VEHICLE_DETAILS, v->index);
1482 return;
1485 if (v->current_order.IsType(OT_NOTHING)) return;
1487 /* if the block of the next position is busy, stay put */
1488 if (AirportHasBlock (v, apc)) return;
1490 /* airport-road is free. We either have to go to another airport, or to the hangar
1491 * ---> start moving */
1493 bool go_to_hangar = false;
1494 switch (v->current_order.GetType()) {
1495 case OT_GOTO_STATION: // ready to fly to another airport
1496 break;
1497 case OT_GOTO_DEPOT: // visit hangar for servicing, sale, etc.
1498 go_to_hangar = v->current_order.GetDestination() == v->targetairport;
1499 break;
1500 case OT_CONDITIONAL:
1501 /* In case of a conditional order we just have to wait a tick
1502 * longer, so the conditional order can actually be processed;
1503 * we should not clear the order as that makes us go nowhere. */
1504 return;
1505 default: // orders have been deleted (no orders), goto depot and don't bother us
1506 v->current_order.Clear();
1507 go_to_hangar = Station::Get(v->targetairport)->airport.HasHangar();
1510 if (go_to_hangar) {
1511 v->state = HANGAR;
1512 } else {
1513 /* airplane goto state takeoff, helicopter to helitakeoff */
1514 v->state = (v->subtype == AIR_HELICOPTER) ? HELITAKEOFF : TAKEOFF;
1516 AirportMove(v, apc);
1519 static void AircraftEventHandler_Flying (Aircraft *v, const AirportFTA *apc)
1521 Station *st = Station::Get(v->targetairport);
1523 /* Runway busy, not allowed to use this airstation or closed, circle. */
1524 if (CanVehicleUseStation(v, st) && (st->owner == OWNER_NONE || st->owner == v->owner) && !(st->airport.flags & AIRPORT_CLOSED_block)) {
1525 /* {32,FLYING,NOTHING_block,37}, {32,LANDING,N,33}, {32,HELILANDING,N,41},
1526 * if it is an airplane, look for LANDING, for helicopter HELILANDING
1527 * it is possible to choose from multiple landing runways, so loop until a free one is found */
1528 byte landingtype = (v->subtype == AIR_HELICOPTER) ? HELILANDING : LANDING;
1529 const AirportFTA::Position *reference = &apc->data[v->pos];
1530 const AirportFTA::Transition *current = reference->transitions;
1531 assert (current != NULL);
1532 do {
1533 if (current->heading == landingtype) {
1534 assert (current->block != NOTHING_block);
1536 uint64 next_block = apc->data[current->next_position].block;
1537 assert (reference->block != next_block);
1539 if ((st->airport.flags & (next_block | current->block)) == 0) {
1540 v->state = landingtype; // LANDING / HELILANDING
1541 /* It's a bit dirty, but I need to set position
1542 * to next position, otherwise if there are
1543 * multiple runways, plane won't know which one
1544 * it took (because they all have heading
1545 * LANDING). And also occupy that block! */
1546 v->pos = current->next_position;
1547 SETBITS(st->airport.flags, next_block);
1548 return;
1550 break;
1552 } while (!(current++)->last);
1554 v->state = FLYING;
1555 v->pos = apc->data[v->pos].next_position;
1558 /* we have arrived in an important state (eg terminal, hangar, etc.) */
1559 static void AirportMoveEvent (Aircraft *v, const AirportFTA *apc)
1561 assert (apc->data[v->pos].heading == v->state);
1563 byte prev_pos = v->pos; // location could be changed in state, so save it before-hand
1564 byte prev_state = v->state;
1566 uint service_flag = 0;
1567 assert (v->state <= MAX_HEADINGS);
1568 switch (v->state) {
1569 case TO_ALL:
1570 error ("OK, you shouldn't be here, check your Airport Scheme!");
1571 break;
1573 case HANGAR:
1574 AircraftEventHandler_InHangar (v, apc);
1575 break;
1577 case TAKEOFF:
1578 if (!PlayVehicleSound (v, VSE_START)) {
1579 SndPlayVehicleFx (AircraftVehInfo(v->engine_type)->sfx, v);
1581 v->state = STARTTAKEOFF;
1582 break;
1584 case STARTTAKEOFF:
1585 v->state = ENDTAKEOFF;
1586 v->UpdateDeltaXY (INVALID_DIR);
1587 break;
1589 case ENDTAKEOFF:
1590 v->state = FLYING;
1591 /* get the next position to go to, differs per airport */
1592 AircraftNextAirportPos_and_Order (v);
1593 break;
1595 case HELITAKEOFF:
1596 v->state = FLYING;
1597 v->UpdateDeltaXY (INVALID_DIR);
1599 /* get the next position to go to, differs per airport */
1600 AircraftNextAirportPos_and_Order (v);
1602 /* Send the helicopter to a hangar if needed for replacement */
1603 assert_compile (DEPOT_SERVICE != 0);
1604 service_flag = DEPOT_SERVICE | DEPOT_LOCATE_HANGAR;
1605 break;
1607 case FLYING:
1608 AircraftEventHandler_Flying (v, apc);
1609 break;
1611 case LANDING:
1612 v->state = ENDLANDING;
1613 v->UpdateDeltaXY (INVALID_DIR);
1615 if (!PlayVehicleSound (v, VSE_TOUCHDOWN)) {
1616 SndPlayVehicleFx (SND_17_SKID_PLANE, v);
1619 /* check if the aircraft needs to be replaced or
1620 * renewed and send it to a hangar if needed */
1621 assert_compile (DEPOT_SERVICE != 0);
1622 service_flag = DEPOT_SERVICE;
1623 break;
1625 case ENDLANDING:
1626 /* next block busy, don't do a thing, just wait */
1627 if (AirportHasBlock (v, apc)) break;
1629 /* if going to terminal (OT_GOTO_STATION) choose one
1630 * 1. in case all terminals are busy AirportFindFreeTerminal() returns false or
1631 * 2. not going for terminal (but depot, no order),
1632 * --> get out of the way to the hangar. */
1633 if (!v->current_order.IsType (OT_GOTO_STATION)
1634 || !AirportFindFreeTerminal (v, apc)) {
1635 v->state = HANGAR;
1638 break;
1640 case HELILANDING:
1641 v->state = HELIENDLANDING;
1642 v->UpdateDeltaXY (INVALID_DIR);
1643 break;
1645 case HELIENDLANDING:
1646 /* next block busy, don't do a thing, just wait */
1647 if (AirportHasBlock (v, apc)) break;
1649 /* if going to helipad (OT_GOTO_STATION) choose one. If airport doesn't have helipads, choose terminal
1650 * 1. in case all terminals/helipads are busy (AirportFindFreeHelipad() returns false) or
1651 * 2. not going for terminal (but depot, no order),
1652 * --> get out of the way to the hangar IF there are terminals on the airport.
1653 * --> else TAKEOFF
1654 * the reason behind this is that if an airport has a terminal, it also has a hangar. Airplanes
1655 * must go to a hangar. */
1656 if (!v->current_order.IsType (OT_GOTO_STATION)
1657 || !AirportFindFreeHelipad (v, apc)) {
1658 v->state = Station::Get(v->targetairport)->airport.HasHangar() ?
1659 HANGAR : HELITAKEOFF;
1662 break;
1664 default:
1665 AircraftEventHandler_AtTerminal (v, apc);
1666 break;
1669 if ((service_flag != 0) && v->NeedsAutomaticServicing()) {
1670 Backup<CompanyByte> cur_company (_current_company, v->owner, FILE_LINE);
1671 DoCommand (v->tile, v->index | service_flag, 0, DC_EXEC, CMD_SEND_VEHICLE_TO_DEPOT);
1672 cur_company.Restore();
1675 if (v->state != FLYING) v->previous_pos = prev_pos;
1676 if (v->state != prev_state || v->pos != prev_pos) UpdateAircraftCache(v);
1679 /* gets pos from vehicle and next orders */
1680 static bool AirportMove (Aircraft *v, const AirportFTA *apc)
1682 /* error handling */
1683 if (v->pos >= apc->nofelements) {
1684 DEBUG(misc, 0, "[Ap] position %d is not valid for current airport. Max position is %d", v->pos, apc->nofelements-1);
1685 assert(v->pos < apc->nofelements);
1688 const AirportFTA::Position *current = &apc->data[v->pos];
1689 /* we have arrived in an important state (eg terminal, hangar, etc.) */
1690 if (current->heading == v->state) {
1691 AirportMoveEvent (v, apc);
1692 return true;
1695 v->previous_pos = v->pos; // save previous location
1697 byte next_position;
1698 uint64 required_block;
1699 if (current->transitions != NULL) {
1700 /* there are more choices to choose from, choose the one that
1701 * matches our heading */
1702 const AirportFTA::Transition *p = current->transitions;
1703 while (p->heading != v->state && p->heading != TO_ALL) {
1704 assert (!p->last);
1705 p++;
1707 next_position = p->next_position;
1708 required_block = p->block;
1709 } else {
1710 /* there is only one choice to move to */
1711 next_position = current->next_position;
1712 required_block = 0;
1715 /* Reserve a block for the plane. */
1716 uint64 next_block = apc->data[next_position].block;
1718 /* If the next position is in another block, check it and wait
1719 * until it is free. */
1720 if ((current->block & next_block) != next_block
1721 && required_block != next_block) {
1722 uint64 airport_flags = next_block | required_block;
1724 Station *st = Station::Get (v->targetairport);
1725 if (st->airport.flags & airport_flags) {
1726 v->cur_speed = 0;
1727 v->subspeed = 0;
1728 return false;
1731 if (next_block != NOTHING_block) {
1732 /* Occupy next block. */
1733 SETBITS(st->airport.flags, airport_flags);
1737 v->pos = next_position;
1738 UpdateAircraftCache (v);
1739 return false;
1743 * Combination of aircraft state for going to a certain terminal and the
1744 * airport flag for that terminal block.
1746 struct MovementTerminalMapping {
1747 AirportMovementStates state; ///< Aircraft movement state when going to this terminal.
1748 uint64 airport_flag; ///< Bitmask in the airport flags that need to be free for this terminal.
1751 /** A list of all valid terminals and their associated blocks. */
1752 static const MovementTerminalMapping _airport_terminal_mapping[] = {
1753 {TERM1, TERM1_block},
1754 {TERM2, TERM2_block},
1755 {TERM3, TERM3_block},
1756 {TERM4, TERM4_block},
1757 {TERM5, TERM5_block},
1758 {TERM6, TERM6_block},
1759 {TERM7, TERM7_block},
1760 {TERM8, TERM8_block},
1761 {HELIPAD1, HELIPAD1_block},
1762 {HELIPAD2, HELIPAD2_block},
1763 {HELIPAD3, HELIPAD3_block},
1767 * Find a free terminal or helipad, and if available, assign it.
1768 * @param v Aircraft looking for a free terminal or helipad.
1769 * @param i First terminal to examine.
1770 * @param last_terminal Terminal number to stop examining.
1771 * @return A terminal or helipad has been found, and has been assigned to the aircraft.
1773 static bool FreeTerminal(Aircraft *v, byte i, byte last_terminal)
1775 assert(last_terminal <= lengthof(_airport_terminal_mapping));
1776 Station *st = Station::Get(v->targetairport);
1777 for (; i < last_terminal; i++) {
1778 if ((st->airport.flags & _airport_terminal_mapping[i].airport_flag) == 0) {
1779 /* TERMINAL# HELIPAD# */
1780 v->state = _airport_terminal_mapping[i].state; // start moving to that terminal/helipad
1781 SETBITS(st->airport.flags, _airport_terminal_mapping[i].airport_flag); // occupy terminal/helipad
1782 return true;
1785 return false;
1789 * Find a free terminal, and assign it if available.
1790 * @param v Aircraft to handle.
1791 * @param apc Airport state machine.
1792 * @return Found a free terminal and assigned it.
1794 static bool AirportFindFreeTerminal (Aircraft *v, const AirportFTA *apc)
1796 /* example of more terminalgroups
1797 * {0,HANGAR,NOTHING_block,1}, {0,255,TERM_GROUP1_block,0}, {0,255,TERM_GROUP2_ENTER_block,1}, {0,0,N,1},
1798 * Heading 255 denotes a group. We see 2 groups here:
1799 * 1. group 0 -- TERM_GROUP1_block (check block)
1800 * 2. group 1 -- TERM_GROUP2_ENTER_block (check block)
1801 * First in line is checked first, group 0. If the block (TERM_GROUP1_block) is free, it
1802 * looks at the corresponding terminals of that group. If no free ones are found, other
1803 * possible groups are checked (in this case group 1, since that is after group 0). If that
1804 * fails, then attempt fails and plane waits
1806 if (apc->terminals[0] > 1) {
1807 const Station *st = Station::Get(v->targetairport);
1808 const AirportFTA::Transition *temp = apc->data[v->pos].transitions;
1810 if (temp != NULL) {
1811 do {
1812 if (temp->heading != 255) {
1813 /* Once the heading isn't 255, we've
1814 * exhausted the possible blocks,
1815 * so we cannot move. */
1816 return false;
1818 if (!(st->airport.flags & temp->block)) {
1819 /* read which group do we want to go to?
1820 * (the first free group) */
1821 uint target_group = temp->next_position + 1;
1823 /* at what terminal does the group start? */
1824 byte group_start = apc->terminals[target_group];
1826 byte group_end = apc->terminals[target_group + 1];
1827 if (FreeTerminal(v, group_start, group_end)) return true;
1829 } while (!(temp++)->last);
1833 /* if there is only 1 terminalgroup, all terminals are checked (starting from 0 to max) */
1834 return FreeTerminal (v, 0, apc->terminals[apc->terminals[0] + 1]);
1838 * Find a free helipad, and assign it if available.
1839 * @param v Aircraft to handle.
1840 * @param apc Airport state machine.
1841 * @return Found a free helipad and assigned it.
1843 static bool AirportFindFreeHelipad (Aircraft *v, const AirportFTA *apc)
1845 /* if an airport doesn't have helipads, use terminals */
1846 if (apc->num_helipads == 0) return AirportFindFreeTerminal(v, apc);
1848 /* only 1 helicoptergroup, check all helipads
1849 * The blocks for helipads start after the last terminal (MAX_TERMINALS) */
1850 return FreeTerminal(v, MAX_TERMINALS, apc->num_helipads + MAX_TERMINALS);
1854 * Handle the 'dest too far' flag and the corresponding news message for aircraft.
1855 * @param v The aircraft.
1856 * @param too_far True if the current destination is too far away.
1858 static void AircraftHandleDestTooFar(Aircraft *v, bool too_far)
1860 if (too_far) {
1861 if (!HasBit(v->flags, VAF_DEST_TOO_FAR)) {
1862 SetBit(v->flags, VAF_DEST_TOO_FAR);
1863 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
1864 AI::NewEvent(v->owner, new ScriptEventAircraftDestTooFar(v->index));
1865 if (v->owner == _local_company) {
1866 /* Post a news message. */
1867 AddNewsItem <VehicleAdviceNewsItem> (STR_NEWS_AIRCRAFT_DEST_TOO_FAR, v->index);
1870 return;
1873 if (HasBit(v->flags, VAF_DEST_TOO_FAR)) {
1874 /* Not too far anymore, clear flag and message. */
1875 ClrBit(v->flags, VAF_DEST_TOO_FAR);
1876 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
1877 DeleteVehicleNews(v->index, STR_NEWS_AIRCRAFT_DEST_TOO_FAR);
1881 static bool AircraftEventHandler(Aircraft *v, int loop)
1883 if (v->vehstatus & VS_CRASHED) {
1884 return HandleCrashedAircraft(v);
1887 if (v->vehstatus & VS_STOPPED) return true;
1889 v->HandleBreakdown();
1891 HandleAircraftSmoke(v, loop != 0);
1892 ProcessOrders(v);
1893 v->HandleLoading(loop != 0);
1895 if (v->current_order.IsType(OT_LOADING) || v->current_order.IsType(OT_LEAVESTATION)) return true;
1897 if (v->state >= ENDTAKEOFF && v->state <= HELIENDLANDING) {
1898 /* If we are flying, unconditionally clear the 'dest too far' state. */
1899 AircraftHandleDestTooFar(v, false);
1900 } else if (v->acache.cached_max_range_sqr != 0) {
1901 /* Check the distance to the next destination. This code works because the target
1902 * airport is only updated after take off and not on the ground. */
1903 Station *cur_st = Station::GetIfValid(v->targetairport);
1904 Station *next_st = v->current_order.IsType(OT_GOTO_STATION) || v->current_order.IsType(OT_GOTO_DEPOT) ? Station::GetIfValid(v->current_order.GetDestination()) : NULL;
1906 if (cur_st != NULL && cur_st->airport.tile != INVALID_TILE && next_st != NULL && next_st->airport.tile != INVALID_TILE) {
1907 uint dist = DistanceSquare(cur_st->airport.tile, next_st->airport.tile);
1908 AircraftHandleDestTooFar(v, dist > v->acache.cached_max_range_sqr);
1912 /* If aircraft is not in position, wait until it is. */
1913 if (!HasBit(v->flags, VAF_DEST_TOO_FAR) && AircraftController (v)) {
1914 Station *st = Station::Get (v->targetairport);
1915 const AirportFTA *apc = st->airport.GetFTA();
1917 /* We have left the previous block, and entered the new one.
1918 * Free the previous block. */
1919 uint64 prev_block = apc->data[v->previous_pos].block;
1920 if (prev_block != apc->data[v->pos].block) {
1921 CLRBITS(st->airport.flags, prev_block);
1924 AirportMove (v, apc); // move aircraft to next position
1927 return true;
1930 bool Aircraft::Tick()
1932 if (!this->IsNormalAircraft()) return true;
1934 this->tick_counter++;
1936 if (!(this->vehstatus & VS_STOPPED)) this->running_ticks++;
1938 if (this->subtype == AIR_HELICOPTER) HelicopterTickHandler(this);
1940 this->current_order_time++;
1942 for (uint i = 0; i != 2; i++) {
1943 /* stop if the aircraft was deleted */
1944 if (!AircraftEventHandler(this, i)) return false;
1947 return true;
1952 * Returns aircraft's target station if v->target_airport
1953 * is a valid station with airport.
1954 * @param v vehicle to get target airport for
1955 * @return pointer to target station, NULL if invalid
1957 Station *GetTargetAirportIfValid(const Aircraft *v)
1959 assert(v->type == VEH_AIRCRAFT);
1961 Station *st = Station::GetIfValid(v->targetairport);
1962 if (st == NULL) return NULL;
1964 return st->airport.tile == INVALID_TILE ? NULL : st;
1968 * Updates the status of the Aircraft heading or in the station
1969 * @param st Station been updated
1971 void UpdateAirplanesOnNewStation(const Station *st)
1973 /* only 1 station is updated per function call, so it is enough to get entry_point once */
1974 const AirportFTA *ap = st->airport.GetFTA();
1975 Direction rotation = st->airport.tile == INVALID_TILE ? DIR_N : st->airport.rotation;
1977 Aircraft *v;
1978 FOR_ALL_AIRCRAFT(v) {
1979 if (!v->IsNormalAircraft() || v->targetairport != st->index) continue;
1980 assert(v->state == FLYING);
1981 v->pos = v->previous_pos = AircraftGetEntryPoint(v, ap, rotation);
1982 UpdateAircraftCache(v);