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/>.
11 * @file aircraft_cmd.cpp
12 * This file deals with aircraft and airport movements functionalities
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"
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
)
52 switch (this->subtype
) {
53 default: NOT_REACHED();
57 switch (this->state
) {
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,
100 bool IsValidImageIndex
<VEH_AIRCRAFT
>(uint8 image_index
)
102 return image_index
< lengthof(_aircraft_sprite
);
105 /** Helicopter rotor animation states */
106 enum HelicopterRotorStates
{
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
)
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
)) {
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
!= NULL
&& DistanceSquare(st
->airport
.tile
, cur_dest
->airport
.tile
) > v
->acache
.cached_max_range_sqr
) continue;
147 if (distance
< best
|| index
== INVALID_STATION
) {
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
);
206 seq
.GetBounds(&rect
);
207 preferred_x
= Clamp(preferred_x
,
208 left
- UnScaleGUI(rect
.left
),
209 right
- UnScaleGUI(rect
.right
));
211 seq
.Draw(preferred_x
, y
, pal
, pal
== PALETTE_CRASH
);
213 if (!(AircraftVehInfo(engine
)->subtype
& AIR_CTOL
)) {
214 VehicleSpriteSeq rotor_seq
;
215 GetCustomRotorIcon(engine
, image_type
, &rotor_seq
);
216 if (!rotor_seq
.IsValid()) rotor_seq
.Set(SPR_ROTOR_STOPPED
);
217 rotor_seq
.Draw(preferred_x
, y
- ScaleGUITrad(5), PAL_NONE
, false);
222 * Get the size of the sprite of an aircraft sprite heading west (used for lists).
223 * @param engine The engine to get the sprite from.
224 * @param[out] width The width of the sprite.
225 * @param[out] height The height of the sprite.
226 * @param[out] xoffs Number of pixels to shift the sprite to the right.
227 * @param[out] yoffs Number of pixels to shift the sprite downwards.
228 * @param image_type Context the sprite is used in.
230 void GetAircraftSpriteSize(EngineID engine
, uint
&width
, uint
&height
, int &xoffs
, int &yoffs
, EngineImageType image_type
)
232 VehicleSpriteSeq seq
;
233 GetAircraftIcon(engine
, image_type
, &seq
);
236 seq
.GetBounds(&rect
);
238 width
= UnScaleGUI(rect
.right
- rect
.left
+ 1);
239 height
= UnScaleGUI(rect
.bottom
- rect
.top
+ 1);
240 xoffs
= UnScaleGUI(rect
.left
);
241 yoffs
= UnScaleGUI(rect
.top
);
246 * @param tile tile of the depot where aircraft is built.
247 * @param flags type of operation.
248 * @param e the engine to build.
249 * @param data unused.
250 * @param ret[out] the vehicle that has been built.
251 * @return the cost of this operation or an error.
253 CommandCost
CmdBuildAircraft(TileIndex tile
, DoCommandFlag flags
, const Engine
*e
, uint16 data
, Vehicle
**ret
)
255 const AircraftVehicleInfo
*avi
= &e
->u
.air
;
256 const Station
*st
= Station::GetByTile(tile
);
258 /* Prevent building aircraft types at places which can't handle them */
259 if (!CanVehicleUseStation(e
->index
, st
)) return CMD_ERROR
;
261 /* Make sure all aircraft end up in the first tile of the hangar. */
262 tile
= st
->airport
.GetHangarTile(st
->airport
.GetHangarNum(tile
));
264 if (flags
& DC_EXEC
) {
265 Aircraft
*v
= new Aircraft(); // aircraft
266 Aircraft
*u
= new Aircraft(); // shadow
269 v
->direction
= DIR_SE
;
271 v
->owner
= u
->owner
= _current_company
;
275 uint x
= TileX(tile
) * TILE_SIZE
+ 5;
276 uint y
= TileY(tile
) * TILE_SIZE
+ 3;
278 v
->x_pos
= u
->x_pos
= x
;
279 v
->y_pos
= u
->y_pos
= y
;
281 u
->z_pos
= GetSlopePixelZ(x
, y
);
282 v
->z_pos
= u
->z_pos
+ 1;
284 v
->vehstatus
= VS_HIDDEN
| VS_STOPPED
| VS_DEFPAL
;
285 u
->vehstatus
= VS_HIDDEN
| VS_UNCLICKABLE
| VS_SHADOW
;
287 v
->spritenum
= avi
->image_index
;
289 v
->cargo_cap
= avi
->passenger_capacity
;
291 u
->cargo_cap
= avi
->mail_capacity
;
294 v
->cargo_type
= e
->GetDefaultCargoType();
295 u
->cargo_type
= CT_MAIL
;
298 v
->last_station_visited
= INVALID_STATION
;
299 v
->last_loading_station
= INVALID_STATION
;
301 v
->acceleration
= avi
->acceleration
;
302 v
->engine_type
= e
->index
;
303 u
->engine_type
= e
->index
;
305 v
->subtype
= (avi
->subtype
& AIR_CTOL
? AIR_AIRCRAFT
: AIR_HELICOPTER
);
306 v
->UpdateDeltaXY(INVALID_DIR
);
308 u
->subtype
= AIR_SHADOW
;
309 u
->UpdateDeltaXY(INVALID_DIR
);
311 v
->reliability
= e
->reliability
;
312 v
->reliability_spd_dec
= e
->reliability_spd_dec
;
313 v
->max_age
= e
->GetLifeLengthInDays();
315 _new_vehicle_id
= v
->index
;
317 v
->pos
= GetVehiclePosOnBuild(tile
);
320 v
->previous_pos
= v
->pos
;
321 v
->targetairport
= GetStationIndex(tile
);
324 v
->SetServiceInterval(Company::Get(_current_company
)->settings
.vehicle
.servint_aircraft
);
326 v
->date_of_last_service
= _date
;
327 v
->build_year
= u
->build_year
= _cur_year
;
329 v
->sprite_seq
.Set(SPR_IMG_QUERY
);
330 u
->sprite_seq
.Set(SPR_IMG_QUERY
);
332 v
->random_bits
= VehicleRandomBits();
333 u
->random_bits
= VehicleRandomBits();
335 v
->vehicle_flags
= 0;
336 if (e
->flags
& ENGINE_EXCLUSIVE_PREVIEW
) SetBit(v
->vehicle_flags
, VF_BUILT_AS_PROTOTYPE
);
337 v
->SetServiceIntervalIsPercent(Company::Get(_current_company
)->settings
.vehicle
.servint_ispercent
);
339 v
->InvalidateNewGRFCacheOfChain();
341 v
->cargo_cap
= e
->DetermineCapacity(v
, &u
->cargo_cap
);
343 v
->InvalidateNewGRFCacheOfChain();
345 UpdateAircraftCache(v
, true);
350 /* Aircraft with 3 vehicles (chopper)? */
351 if (v
->subtype
== AIR_HELICOPTER
) {
352 Aircraft
*w
= new Aircraft();
353 w
->engine_type
= e
->index
;
354 w
->direction
= DIR_N
;
355 w
->owner
= _current_company
;
358 w
->z_pos
= v
->z_pos
+ ROTOR_Z_OFFSET
;
359 w
->vehstatus
= VS_HIDDEN
| VS_UNCLICKABLE
;
361 w
->subtype
= AIR_ROTOR
;
362 w
->sprite_seq
.Set(SPR_ROTOR_STOPPED
);
363 w
->random_bits
= VehicleRandomBits();
364 /* Use rotor's air.state to store the rotor animation frame */
365 w
->state
= HRS_ROTOR_STOPPED
;
366 w
->UpdateDeltaXY(INVALID_DIR
);
373 return CommandCost();
377 bool Aircraft::FindClosestDepot(TileIndex
*location
, DestinationID
*destination
, bool *reverse
)
379 const Station
*st
= GetTargetAirportIfValid(this);
380 /* If the station is not a valid airport or if it has no hangars */
381 if (st
== NULL
|| !st
->airport
.HasHangar()) {
382 /* the aircraft has to search for a hangar on its own */
383 StationID station
= FindNearestHangar(this);
385 if (station
== INVALID_STATION
) return false;
387 st
= Station::Get(station
);
390 if (location
!= NULL
) *location
= st
->xy
;
391 if (destination
!= NULL
) *destination
= st
->index
;
396 static void CheckIfAircraftNeedsService(Aircraft
*v
)
398 if (Company::Get(v
->owner
)->settings
.vehicle
.servint_aircraft
== 0 || !v
->NeedsAutomaticServicing()) return;
399 if (v
->IsChainInDepot()) {
400 VehicleServiceInDepot(v
);
404 /* When we're parsing conditional orders and the like
405 * we don't want to consider going to a depot too. */
406 if (!v
->current_order
.IsType(OT_GOTO_DEPOT
) && !v
->current_order
.IsType(OT_GOTO_STATION
)) return;
408 const Station
*st
= Station::Get(v
->current_order
.GetDestination());
412 /* only goto depot if the target airport has a depot */
413 if (st
->airport
.HasHangar() && CanVehicleUseStation(v
, st
)) {
414 v
->current_order
.MakeGoToDepot(st
->index
, ODTFB_SERVICE
);
415 SetWindowWidgetDirty(WC_VEHICLE_VIEW
, v
->index
, WID_VV_START_STOP
);
416 } else if (v
->current_order
.IsType(OT_GOTO_DEPOT
)) {
417 v
->current_order
.MakeDummy();
418 SetWindowWidgetDirty(WC_VEHICLE_VIEW
, v
->index
, WID_VV_START_STOP
);
422 Money
Aircraft::GetRunningCost() const
424 const Engine
*e
= this->GetEngine();
425 uint cost_factor
= GetVehicleProperty(this, PROP_AIRCRAFT_RUNNING_COST_FACTOR
, e
->u
.air
.running_cost
);
426 return GetPrice(PR_RUNNING_AIRCRAFT
, cost_factor
, e
->GetGRF());
429 void Aircraft::OnNewDay()
431 if (!this->IsNormalAircraft()) return;
433 if ((++this->day_counter
& 7) == 0) DecreaseVehicleValue(this);
437 CheckVehicleBreakdown(this);
439 CheckIfAircraftNeedsService(this);
441 if (this->running_ticks
== 0) return;
443 CommandCost
cost(EXPENSES_AIRCRAFT_RUN
, this->GetRunningCost() * this->running_ticks
/ (DAYS_IN_YEAR
* DAY_TICKS
));
445 this->profit_this_year
-= cost
.GetCost();
446 this->running_ticks
= 0;
448 SubtractMoneyFromCompanyFract(this->owner
, cost
);
450 SetWindowDirty(WC_VEHICLE_DETAILS
, this->index
);
451 SetWindowClassesDirty(WC_AIRCRAFT_LIST
);
454 static void HelicopterTickHandler(Aircraft
*v
)
456 Aircraft
*u
= v
->Next()->Next();
458 if (u
->vehstatus
& VS_HIDDEN
) return;
460 /* if true, helicopter rotors do not rotate. This should only be the case if a helicopter is
461 * loading/unloading at a terminal or stopped */
462 if (v
->current_order
.IsType(OT_LOADING
) || (v
->vehstatus
& VS_STOPPED
)) {
463 if (u
->cur_speed
!= 0) {
465 if (u
->cur_speed
>= 0x80 && u
->state
== HRS_ROTOR_MOVING_3
) {
470 if (u
->cur_speed
== 0) {
473 if (u
->cur_speed
>= 0x50) {
478 int tick
= ++u
->tick_counter
;
479 int spd
= u
->cur_speed
>> 4;
481 VehicleSpriteSeq seq
;
483 u
->state
= HRS_ROTOR_STOPPED
;
484 GetRotorImage(v
, EIT_ON_MAP
, &seq
);
485 if (u
->sprite_seq
== seq
) return;
486 } else if (tick
>= spd
) {
489 if (u
->state
> HRS_ROTOR_MOVING_3
) u
->state
= HRS_ROTOR_MOVING_1
;
490 GetRotorImage(v
, EIT_ON_MAP
, &seq
);
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
)
514 v
->UpdateViewport(true, false);
515 if (v
->subtype
== AIR_HELICOPTER
) {
516 GetRotorImage(v
, EIT_ON_MAP
, &v
->Next()->Next()->sprite_seq
);
519 Aircraft
*u
= v
->Next();
521 int safe_x
= Clamp(x
, 0, MapMaxX() * TILE_SIZE
);
522 int safe_y
= Clamp(y
- 1, 0, MapMaxY() * TILE_SIZE
);
524 u
->y_pos
= y
- ((v
->z_pos
- GetSlopePixelZ(safe_x
, safe_y
)) >> 3);
526 safe_y
= Clamp(u
->y_pos
, 0, MapMaxY() * TILE_SIZE
);
527 u
->z_pos
= GetSlopePixelZ(safe_x
, safe_y
);
528 u
->sprite_seq
.CopyWithoutPalette(v
->sprite_seq
); // the shadow is never coloured
530 u
->UpdatePositionAndViewport();
536 u
->z_pos
= z
+ ROTOR_Z_OFFSET
;
538 u
->UpdatePositionAndViewport();
543 * Handle Aircraft specific tasks when an Aircraft enters a hangar
544 * @param *v Vehicle that enters the hangar
546 void HandleAircraftEnterHangar(Aircraft
*v
)
551 Aircraft
*u
= v
->Next();
552 u
->vehstatus
|= VS_HIDDEN
;
555 u
->vehstatus
|= VS_HIDDEN
;
559 SetAircraftPosition(v
, v
->x_pos
, v
->y_pos
, v
->z_pos
);
562 static void PlayAircraftSound(const Vehicle
*v
)
564 if (!PlayVehicleSound(v
, VSE_START
)) {
565 SndPlayVehicleFx(AircraftVehInfo(v
->engine_type
)->sfx
, v
);
571 * Update cached values of an aircraft.
572 * Currently caches callback 36 max speed.
574 * @param update_range Update the aircraft range.
576 void UpdateAircraftCache(Aircraft
*v
, bool update_range
)
578 uint max_speed
= GetVehicleProperty(v
, PROP_AIRCRAFT_SPEED
, 0);
579 if (max_speed
!= 0) {
580 /* Convert from original units to km-ish/h */
581 max_speed
= (max_speed
* 128) / 10;
583 v
->vcache
.cached_max_speed
= max_speed
;
585 /* Use the default max speed of the vehicle. */
586 v
->vcache
.cached_max_speed
= AircraftVehInfo(v
->engine_type
)->max_speed
;
589 /* Update cargo aging period. */
590 v
->vcache
.cached_cargo_age_period
= GetVehicleProperty(v
, PROP_AIRCRAFT_CARGO_AGE_PERIOD
, EngInfo(v
->engine_type
)->cargo_age_period
);
591 Aircraft
*u
= v
->Next(); // Shadow for mail
592 u
->vcache
.cached_cargo_age_period
= GetVehicleProperty(u
, PROP_AIRCRAFT_CARGO_AGE_PERIOD
, EngInfo(u
->engine_type
)->cargo_age_period
);
594 /* Update aircraft range. */
596 v
->acache
.cached_max_range
= GetVehicleProperty(v
, PROP_AIRCRAFT_RANGE
, AircraftVehInfo(v
->engine_type
)->max_range
);
597 /* Squared it now so we don't have to do it later all the time. */
598 v
->acache
.cached_max_range_sqr
= v
->acache
.cached_max_range
* v
->acache
.cached_max_range
;
604 * Special velocities for aircraft
606 enum AircraftSpeedLimits
{
607 SPEED_LIMIT_TAXI
= 50, ///< Maximum speed of an aircraft while taxiing
608 SPEED_LIMIT_APPROACH
= 230, ///< Maximum speed of an aircraft on finals
609 SPEED_LIMIT_BROKEN
= 320, ///< Maximum speed of an aircraft that is broken
610 SPEED_LIMIT_HOLD
= 425, ///< Maximum speed of an aircraft that flies the holding pattern
611 SPEED_LIMIT_NONE
= 0xFFFF, ///< No environmental speed limit. Speed limit is type dependent
615 * Sets the new speed for an aircraft
616 * @param v The vehicle for which the speed should be obtained
617 * @param speed_limit The maximum speed the vehicle may have.
618 * @param hard_limit If true, the limit is directly enforced, otherwise the plane is slowed down gradually
619 * @return The number of position updates needed within the tick
621 static int UpdateAircraftSpeed(Aircraft
*v
, uint speed_limit
= SPEED_LIMIT_NONE
, bool hard_limit
= true)
624 * 'acceleration' has the unit 3/8 mph/tick. This function is called twice per tick.
625 * So the speed amount we need to accelerate is:
626 * acceleration * 3 / 16 mph = acceleration * 3 / 16 * 16 / 10 km-ish/h
627 * = acceleration * 3 / 10 * 256 * (km-ish/h / 256)
628 * ~ acceleration * 77 (km-ish/h / 256)
630 uint spd
= v
->acceleration
* 77;
633 /* Adjust speed limits by plane speed factor to prevent taxiing
634 * and take-off speeds being too low. */
635 speed_limit
*= _settings_game
.vehicle
.plane_speed
;
637 if (v
->vcache
.cached_max_speed
< speed_limit
) {
638 if (v
->cur_speed
< speed_limit
) hard_limit
= false;
639 speed_limit
= v
->vcache
.cached_max_speed
;
642 v
->subspeed
= (t
= v
->subspeed
) + (byte
)spd
;
644 /* Aircraft's current speed is used twice so that very fast planes are
645 * forced to slow down rapidly in the short distance needed. The magic
646 * value 16384 was determined to give similar results to the old speed/48
647 * method at slower speeds. This also results in less reduction at slow
648 * speeds to that aircraft do not get to taxi speed straight after
650 if (!hard_limit
&& v
->cur_speed
> speed_limit
) {
651 speed_limit
= v
->cur_speed
- max(1, ((v
->cur_speed
* v
->cur_speed
) / 16384) / _settings_game
.vehicle
.plane_speed
);
654 spd
= min(v
->cur_speed
+ (spd
>> 8) + (v
->subspeed
< t
), speed_limit
);
656 /* adjust speed for broken vehicles */
657 if (v
->vehstatus
& VS_AIRCRAFT_BROKEN
) spd
= min(spd
, SPEED_LIMIT_BROKEN
);
659 /* updates statusbar only if speed have changed to save CPU time */
660 if (spd
!= v
->cur_speed
) {
662 SetWindowWidgetDirty(WC_VEHICLE_VIEW
, v
->index
, WID_VV_START_STOP
);
665 /* Adjust distance moved by plane speed setting */
666 if (_settings_game
.vehicle
.plane_speed
> 1) spd
/= _settings_game
.vehicle
.plane_speed
;
668 /* Convert direction-independent speed into direction-dependent speed. (old movement method) */
669 spd
= v
->GetOldAdvanceSpeed(spd
);
672 v
->progress
= (byte
)spd
;
677 * Get the tile height below the aircraft.
678 * This function is needed because aircraft can leave the mapborders.
680 * @param v The vehicle to get the height for.
681 * @return The height in pixels from 'z_pos' 0.
683 int GetTileHeightBelowAircraft(const Vehicle
*v
)
685 int safe_x
= Clamp(v
->x_pos
, 0, MapMaxX() * TILE_SIZE
);
686 int safe_y
= Clamp(v
->y_pos
, 0, MapMaxY() * TILE_SIZE
);
687 return TileHeight(TileVirtXY(safe_x
, safe_y
)) * TILE_HEIGHT
;
691 * Get the 'flight level' bounds, in pixels from 'z_pos' 0 for a particular
692 * vehicle for normal flight situation.
693 * When the maximum is reached the vehicle should consider descending.
694 * When the minimum is reached the vehicle should consider ascending.
696 * @param v The vehicle to get the flight levels for.
697 * @param [out] min_level The minimum bounds for flight level.
698 * @param [out] max_level The maximum bounds for flight level.
700 void GetAircraftFlightLevelBounds(const Vehicle
*v
, int *min_level
, int *max_level
)
702 int base_altitude
= GetTileHeightBelowAircraft(v
);
703 if (v
->type
== VEH_AIRCRAFT
&& Aircraft::From(v
)->subtype
== AIR_HELICOPTER
) {
704 base_altitude
+= HELICOPTER_HOLD_MAX_FLYING_ALTITUDE
- PLANE_HOLD_MAX_FLYING_ALTITUDE
;
707 /* Make sure eastbound and westbound planes do not "crash" into each
708 * other by providing them with vertical separation
710 switch (v
->direction
) {
721 /* Make faster planes fly higher so that they can overtake slower ones */
722 base_altitude
+= min(20 * (v
->vcache
.cached_max_speed
/ 200) - 90, 0);
724 if (min_level
!= NULL
) *min_level
= base_altitude
+ AIRCRAFT_MIN_FLYING_ALTITUDE
;
725 if (max_level
!= NULL
) *max_level
= base_altitude
+ AIRCRAFT_MAX_FLYING_ALTITUDE
;
729 * Gets the maximum 'flight level' for the holding pattern of the aircraft,
730 * in pixels 'z_pos' 0, depending on terrain below..
732 * @param v The aircraft that may or may not need to decrease its altitude.
733 * @return Maximal aircraft holding altitude, while in normal flight, in pixels.
735 int GetAircraftHoldMaxAltitude(const Aircraft
*v
)
737 int tile_height
= GetTileHeightBelowAircraft(v
);
739 return tile_height
+ ((v
->subtype
== AIR_HELICOPTER
) ? HELICOPTER_HOLD_MAX_FLYING_ALTITUDE
: PLANE_HOLD_MAX_FLYING_ALTITUDE
);
743 int GetAircraftFlightLevel(T
*v
, bool takeoff
)
745 /* Aircraft is in flight. We want to enforce it being somewhere
746 * between the minimum and the maximum allowed altitude. */
747 int aircraft_min_altitude
;
748 int aircraft_max_altitude
;
749 GetAircraftFlightLevelBounds(v
, &aircraft_min_altitude
, &aircraft_max_altitude
);
750 int aircraft_middle_altitude
= (aircraft_min_altitude
+ aircraft_max_altitude
) / 2;
752 /* If those assumptions would be violated, aircrafts would behave fairly strange. */
753 assert(aircraft_min_altitude
< aircraft_middle_altitude
);
754 assert(aircraft_middle_altitude
< aircraft_max_altitude
);
757 if (z
< aircraft_min_altitude
||
758 (HasBit(v
->flags
, VAF_IN_MIN_HEIGHT_CORRECTION
) && z
< aircraft_middle_altitude
)) {
759 /* Ascend. And don't fly into that mountain right ahead.
760 * And avoid our aircraft become a stairclimber, so if we start
761 * correcting altitude, then we stop correction not too early. */
762 SetBit(v
->flags
, VAF_IN_MIN_HEIGHT_CORRECTION
);
763 z
+= takeoff
? 2 : 1;
764 } else if (!takeoff
&& (z
> aircraft_max_altitude
||
765 (HasBit(v
->flags
, VAF_IN_MAX_HEIGHT_CORRECTION
) && z
> aircraft_middle_altitude
))) {
766 /* Descend lower. You are an aircraft, not an space ship.
767 * And again, don't stop correcting altitude too early. */
768 SetBit(v
->flags
, VAF_IN_MAX_HEIGHT_CORRECTION
);
770 } else if (HasBit(v
->flags
, VAF_IN_MIN_HEIGHT_CORRECTION
) && z
>= aircraft_middle_altitude
) {
771 /* Now, we have corrected altitude enough. */
772 ClrBit(v
->flags
, VAF_IN_MIN_HEIGHT_CORRECTION
);
773 } else if (HasBit(v
->flags
, VAF_IN_MAX_HEIGHT_CORRECTION
) && z
<= aircraft_middle_altitude
) {
774 /* Now, we have corrected altitude enough. */
775 ClrBit(v
->flags
, VAF_IN_MAX_HEIGHT_CORRECTION
);
781 template int GetAircraftFlightLevel(DisasterVehicle
*v
, bool takeoff
);
784 * Find the entry point to an airport depending on direction which
785 * the airport is being approached from. Each airport can have up to
786 * four entry points for its approach system so that approaching
787 * aircraft do not fly through each other or are forced to do 180
788 * degree turns during the approach. The arrivals are grouped into
789 * four sectors dependent on the DiagDirection from which the airport
792 * @param v The vehicle that is approaching the airport
793 * @param apc The Airport Class being approached.
794 * @param rotation The rotation of the airport.
795 * @return The index of the entry point
797 static byte
AircraftGetEntryPoint(const Aircraft
*v
, const AirportFTAClass
*apc
, Direction rotation
)
802 /* In the case the station doesn't exit anymore, set target tile 0.
803 * It doesn't hurt much, aircraft will go to next order, nearest hangar
804 * or it will simply crash in next tick */
807 const Station
*st
= Station::GetIfValid(v
->targetairport
);
809 /* Make sure we don't go to INVALID_TILE if the airport has been removed. */
810 tile
= (st
->airport
.tile
!= INVALID_TILE
) ? st
->airport
.tile
: st
->xy
;
813 int delta_x
= v
->x_pos
- TileX(tile
) * TILE_SIZE
;
814 int delta_y
= v
->y_pos
- TileY(tile
) * TILE_SIZE
;
817 if (abs(delta_y
) < abs(delta_x
)) {
818 /* We are northeast or southwest of the airport */
819 dir
= delta_x
< 0 ? DIAGDIR_NE
: DIAGDIR_SW
;
821 /* We are northwest or southeast of the airport */
822 dir
= delta_y
< 0 ? DIAGDIR_NW
: DIAGDIR_SE
;
824 dir
= ChangeDiagDir(dir
, DiagDirDifference(DIAGDIR_NE
, DirToDiagDir(rotation
)));
825 return apc
->entry_points
[dir
];
829 static void MaybeCrashAirplane(Aircraft
*v
);
832 * Controls the movement of an aircraft. This function actually moves the vehicle
833 * on the map and takes care of minor things like sound playback.
834 * @todo De-mystify the cur_speed values for helicopter rotors.
835 * @param v The vehicle that is moved. Must be the first vehicle of the chain
836 * @return Whether the position requested by the State Machine has been reached
838 static bool AircraftController(Aircraft
*v
)
842 /* NULL if station is invalid */
843 const Station
*st
= Station::GetIfValid(v
->targetairport
);
844 /* INVALID_TILE if there is no station */
845 TileIndex tile
= INVALID_TILE
;
846 Direction rotation
= DIR_N
;
847 uint size_x
= 1, size_y
= 1;
849 if (st
->airport
.tile
!= INVALID_TILE
) {
850 tile
= st
->airport
.tile
;
851 rotation
= st
->airport
.rotation
;
852 size_x
= st
->airport
.w
;
853 size_y
= st
->airport
.h
;
858 /* DUMMY if there is no station or no airport */
859 const AirportFTAClass
*afc
= tile
== INVALID_TILE
? GetAirport(AT_DUMMY
) : st
->airport
.GetFTA();
861 /* prevent going to INVALID_TILE if airport is deleted. */
862 if (st
== NULL
|| st
->airport
.tile
== INVALID_TILE
) {
863 /* Jump into our "holding pattern" state machine if possible */
864 if (v
->pos
>= afc
->nofelements
) {
865 v
->pos
= v
->previous_pos
= AircraftGetEntryPoint(v
, afc
, DIR_N
);
866 } else if (v
->targetairport
!= v
->current_order
.GetDestination()) {
867 /* If not possible, just get out of here fast */
869 UpdateAircraftCache(v
);
870 AircraftNextAirportPos_and_Order(v
);
871 /* get aircraft back on running altitude */
872 SetAircraftPosition(v
, v
->x_pos
, v
->y_pos
, GetAircraftFlightLevel(v
));
877 /* get airport moving data */
878 const AirportMovingData amd
= RotateAirportMovingData(afc
->MovingData(v
->pos
), rotation
, size_x
, size_y
);
880 int x
= TileX(tile
) * TILE_SIZE
;
881 int y
= TileY(tile
) * TILE_SIZE
;
883 /* Helicopter raise */
884 if (amd
.flag
& AMED_HELI_RAISE
) {
885 Aircraft
*u
= v
->Next()->Next();
887 /* Make sure the rotors don't rotate too fast */
888 if (u
->cur_speed
> 32) {
890 if (--u
->cur_speed
== 32) {
891 if (!PlayVehicleSound(v
, VSE_START
)) {
892 SndPlayVehicleFx(SND_18_HELICOPTER
, v
);
897 count
= UpdateAircraftSpeed(v
);
902 GetAircraftFlightLevelBounds(v
, &z_dest
, NULL
);
904 /* Reached altitude? */
905 if (v
->z_pos
>= z_dest
) {
909 SetAircraftPosition(v
, v
->x_pos
, v
->y_pos
, min(v
->z_pos
+ count
, z_dest
));
915 /* Helicopter landing. */
916 if (amd
.flag
& AMED_HELI_LOWER
) {
918 /* FIXME - AircraftController -> if station no longer exists, do not land
919 * helicopter will circle until sign disappears, then go to next order
920 * what to do when it is the only order left, right now it just stays in 1 place */
922 UpdateAircraftCache(v
);
923 AircraftNextAirportPos_and_Order(v
);
927 /* Vehicle is now at the airport. */
930 /* Find altitude of landing position. */
931 int z
= GetSlopePixelZ(x
, y
) + 1 + afc
->delta_z
;
934 Vehicle
*u
= v
->Next()->Next();
936 /* Increase speed of rotors. When speed is 80, we've landed. */
937 if (u
->cur_speed
>= 80) return true;
940 count
= UpdateAircraftSpeed(v
);
943 SetAircraftPosition(v
, v
->x_pos
, v
->y_pos
, max(v
->z_pos
- count
, z
));
945 SetAircraftPosition(v
, v
->x_pos
, v
->y_pos
, min(v
->z_pos
+ count
, z
));
952 /* Get distance from destination pos to current pos. */
953 uint dist
= abs(x
+ amd
.x
- v
->x_pos
) + abs(y
+ amd
.y
- v
->y_pos
);
955 /* Need exact position? */
956 if (!(amd
.flag
& AMED_EXACTPOS
) && dist
<= (amd
.flag
& AMED_SLOWTURN
? 8U : 4U)) return true;
960 /* Change direction smoothly to final direction. */
961 DirDiff dirdiff
= DirDifference(amd
.direction
, v
->direction
);
962 /* if distance is 0, and plane points in right direction, no point in calling
963 * UpdateAircraftSpeed(). So do it only afterwards */
964 if (dirdiff
== DIRDIFF_SAME
) {
969 if (!UpdateAircraftSpeed(v
, SPEED_LIMIT_TAXI
)) return false;
971 v
->direction
= ChangeDir(v
->direction
, dirdiff
> DIRDIFF_REVERSE
? DIRDIFF_45LEFT
: DIRDIFF_45RIGHT
);
974 SetAircraftPosition(v
, v
->x_pos
, v
->y_pos
, v
->z_pos
);
978 if (amd
.flag
& AMED_BRAKE
&& v
->cur_speed
> SPEED_LIMIT_TAXI
* _settings_game
.vehicle
.plane_speed
) {
979 MaybeCrashAirplane(v
);
980 if ((v
->vehstatus
& VS_CRASHED
) != 0) return false;
983 uint speed_limit
= SPEED_LIMIT_TAXI
;
984 bool hard_limit
= true;
986 if (amd
.flag
& AMED_NOSPDCLAMP
) speed_limit
= SPEED_LIMIT_NONE
;
987 if (amd
.flag
& AMED_HOLD
) { speed_limit
= SPEED_LIMIT_HOLD
; hard_limit
= false; }
988 if (amd
.flag
& AMED_LAND
) { speed_limit
= SPEED_LIMIT_APPROACH
; hard_limit
= false; }
989 if (amd
.flag
& AMED_BRAKE
) { speed_limit
= SPEED_LIMIT_TAXI
; hard_limit
= false; }
991 count
= UpdateAircraftSpeed(v
, speed_limit
, hard_limit
);
992 if (count
== 0) return false;
994 if (v
->turn_counter
!= 0) v
->turn_counter
--;
998 GetNewVehiclePosResult gp
;
1000 if (dist
< 4 || (amd
.flag
& AMED_LAND
)) {
1001 /* move vehicle one pixel towards target */
1002 gp
.x
= (v
->x_pos
!= (x
+ amd
.x
)) ?
1003 v
->x_pos
+ ((x
+ amd
.x
> v
->x_pos
) ? 1 : -1) :
1005 gp
.y
= (v
->y_pos
!= (y
+ amd
.y
)) ?
1006 v
->y_pos
+ ((y
+ amd
.y
> v
->y_pos
) ? 1 : -1) :
1009 /* Oilrigs must keep v->tile as st->airport.tile, since the landing pad is in a non-airport tile */
1010 gp
.new_tile
= (st
->airport
.type
== AT_OILRIG
) ? st
->airport
.tile
: TileVirtXY(gp
.x
, gp
.y
);
1014 /* Turn. Do it slowly if in the air. */
1015 Direction newdir
= GetDirectionTowards(v
, x
+ amd
.x
, y
+ amd
.y
);
1016 if (newdir
!= v
->direction
) {
1017 if (amd
.flag
& AMED_SLOWTURN
&& v
->number_consecutive_turns
< 8 && v
->subtype
== AIR_AIRCRAFT
) {
1018 if (v
->turn_counter
== 0 || newdir
== v
->last_direction
) {
1019 if (newdir
== v
->last_direction
) {
1020 v
->number_consecutive_turns
= 0;
1022 v
->number_consecutive_turns
++;
1024 v
->turn_counter
= 2 * _settings_game
.vehicle
.plane_speed
;
1025 v
->last_direction
= v
->direction
;
1026 v
->direction
= newdir
;
1030 gp
= GetNewVehiclePos(v
);
1033 v
->direction
= newdir
;
1035 /* When leaving a terminal an aircraft often goes to a position
1036 * directly in front of it. If it would move while turning it
1037 * would need an two extra turns to end up at the correct position.
1038 * To make it easier just disallow all moving while turning as
1039 * long as an aircraft is on the ground. */
1042 gp
.new_tile
= gp
.old_tile
= v
->tile
;
1045 v
->number_consecutive_turns
= 0;
1047 gp
= GetNewVehiclePos(v
);
1051 v
->tile
= gp
.new_tile
;
1052 /* If vehicle is in the air, use tile coordinate 0. */
1053 if (amd
.flag
& (AMED_TAKEOFF
| AMED_SLOWTURN
| AMED_LAND
)) v
->tile
= 0;
1055 /* Adjust Z for land or takeoff? */
1058 if (amd
.flag
& AMED_TAKEOFF
) {
1059 z
= GetAircraftFlightLevel(v
, true);
1060 } else if (amd
.flag
& AMED_HOLD
) {
1061 /* Let the plane drop from normal flight altitude to holding pattern altitude */
1062 if (z
> GetAircraftHoldMaxAltitude(v
)) z
--;
1063 } else if ((amd
.flag
& AMED_SLOWTURN
) && (amd
.flag
& AMED_NOSPDCLAMP
)) {
1064 z
= GetAircraftFlightLevel(v
);
1067 if (amd
.flag
& AMED_LAND
) {
1068 if (st
->airport
.tile
== INVALID_TILE
) {
1069 /* Airport has been removed, abort the landing procedure */
1071 UpdateAircraftCache(v
);
1072 AircraftNextAirportPos_and_Order(v
);
1073 /* get aircraft back on running altitude */
1074 SetAircraftPosition(v
, gp
.x
, gp
.y
, GetAircraftFlightLevel(v
));
1078 int curz
= GetSlopePixelZ(x
+ amd
.x
, y
+ amd
.y
) + 1;
1080 /* We're not flying below our destination, right? */
1082 int t
= max(1U, dist
- 4);
1083 int delta
= z
- curz
;
1085 /* Only start lowering when we're sufficiently close for a 1:1 glide */
1087 z
-= CeilDiv(z
- curz
, t
);
1089 if (z
< curz
) z
= curz
;
1092 /* We've landed. Decrease speed when we're reaching end of runway. */
1093 if (amd
.flag
& AMED_BRAKE
) {
1094 int curz
= GetSlopePixelZ(x
, y
) + 1;
1098 } else if (z
< curz
) {
1104 SetAircraftPosition(v
, gp
.x
, gp
.y
, z
);
1105 } while (--count
!= 0);
1110 * Handle crashed aircraft \a v.
1111 * @param v Crashed aircraft.
1113 static bool HandleCrashedAircraft(Aircraft
*v
)
1115 v
->crashed_counter
+= 3;
1117 Station
*st
= GetTargetAirportIfValid(v
);
1119 /* make aircraft crash down to the ground */
1120 if (v
->crashed_counter
< 500 && st
== NULL
&& ((v
->crashed_counter
% 3) == 0) ) {
1121 int z
= GetSlopePixelZ(Clamp(v
->x_pos
, 0, MapMaxX() * TILE_SIZE
), Clamp(v
->y_pos
, 0, MapMaxY() * TILE_SIZE
));
1123 if (v
->z_pos
== z
) {
1124 v
->crashed_counter
= 500;
1129 if (v
->crashed_counter
< 650) {
1131 if (Chance16R(1, 32, r
)) {
1132 static const DirDiff delta
[] = {
1133 DIRDIFF_45LEFT
, DIRDIFF_SAME
, DIRDIFF_SAME
, DIRDIFF_45RIGHT
1136 v
->direction
= ChangeDir(v
->direction
, delta
[GB(r
, 16, 2)]);
1137 SetAircraftPosition(v
, v
->x_pos
, v
->y_pos
, v
->z_pos
);
1139 CreateEffectVehicleRel(v
,
1143 EV_EXPLOSION_SMALL
);
1145 } else if (v
->crashed_counter
>= 10000) {
1146 /* remove rubble of crashed airplane */
1148 /* clear runway-in on all airports, set by crashing plane
1149 * small airports use AIRPORT_BUSY, city airports use RUNWAY_IN_OUT_block, etc.
1150 * but they all share the same number */
1152 CLRBITS(st
->airport
.flags
, RUNWAY_IN_block
);
1153 CLRBITS(st
->airport
.flags
, RUNWAY_IN_OUT_block
); // commuter airport
1154 CLRBITS(st
->airport
.flags
, RUNWAY_IN2_block
); // intercontinental
1167 * Handle smoke of broken aircraft.
1169 * @param mode Is this the non-first call for this vehicle in this tick?
1171 static void HandleAircraftSmoke(Aircraft
*v
, bool mode
)
1173 static const struct {
1187 if (!(v
->vehstatus
& VS_AIRCRAFT_BROKEN
)) return;
1189 /* Stop smoking when landed */
1190 if (v
->cur_speed
< 10) {
1191 v
->vehstatus
&= ~VS_AIRCRAFT_BROKEN
;
1192 v
->breakdown_ctr
= 0;
1196 /* Spawn effect et most once per Tick, i.e. !mode */
1197 if (!mode
&& (v
->tick_counter
& 0x0F) == 0) {
1198 CreateEffectVehicleRel(v
,
1199 smoke_pos
[v
->direction
].x
,
1200 smoke_pos
[v
->direction
].y
,
1202 EV_BREAKDOWN_SMOKE_AIRCRAFT
1207 void HandleMissingAircraftOrders(Aircraft
*v
)
1210 * We do not have an order. This can be divided into two cases:
1211 * 1) we are heading to an invalid station. In this case we must
1212 * find another airport to go to. If there is nowhere to go,
1213 * we will destroy the aircraft as it otherwise will enter
1214 * the holding pattern for the first airport, which can cause
1215 * the plane to go into an undefined state when building an
1216 * airport with the same StationID.
1217 * 2) we are (still) heading to a (still) valid airport, then we
1218 * can continue going there. This can happen when you are
1219 * changing the aircraft's orders while in-flight or in for
1220 * example a depot. However, when we have a current order to
1221 * go to a depot, we have to keep that order so the aircraft
1224 const Station
*st
= GetTargetAirportIfValid(v
);
1226 Backup
<CompanyByte
> cur_company(_current_company
, v
->owner
, FILE_LINE
);
1227 CommandCost ret
= DoCommand(v
->tile
, v
->index
, 0, DC_EXEC
, CMD_SEND_VEHICLE_TO_DEPOT
);
1228 cur_company
.Restore();
1230 if (ret
.Failed()) CrashAirplane(v
);
1231 } else if (!v
->current_order
.IsType(OT_GOTO_DEPOT
)) {
1232 v
->current_order
.Free();
1237 TileIndex
Aircraft::GetOrderStationLocation(StationID station
)
1239 /* Orders are changed in flight, ensure going to the right station. */
1240 if (this->state
== FLYING
) {
1241 AircraftNextAirportPos_and_Order(this);
1244 /* Aircraft do not use dest-tile */
1248 void Aircraft::MarkDirty()
1250 this->colourmap
= PAL_NONE
;
1251 this->UpdateViewport(true, false);
1252 if (this->subtype
== AIR_HELICOPTER
) {
1253 GetRotorImage(this, EIT_ON_MAP
, &this->Next()->Next()->sprite_seq
);
1258 uint
Aircraft::Crash(bool flooded
)
1260 uint pass
= Vehicle::Crash(flooded
) + 2; // pilots
1261 this->crashed_counter
= flooded
? 9000 : 0; // max 10000, disappear pretty fast when flooded
1267 * Bring the aircraft in a crashed state, create the explosion animation, and create a news item about the crash.
1268 * @param v Aircraft that crashed.
1270 static void CrashAirplane(Aircraft
*v
)
1272 CreateEffectVehicleRel(v
, 4, 4, 8, EV_EXPLOSION_LARGE
);
1274 uint pass
= v
->Crash();
1277 v
->cargo
.Truncate();
1278 v
->Next()->cargo
.Truncate();
1279 const Station
*st
= GetTargetAirportIfValid(v
);
1282 newsitem
= STR_NEWS_PLANE_CRASH_OUT_OF_FUEL
;
1284 SetDParam(1, st
->index
);
1285 newsitem
= STR_NEWS_AIRCRAFT_CRASH
;
1288 AI::NewEvent(v
->owner
, new ScriptEventVehicleCrashed(v
->index
, v
->tile
, st
== NULL
? ScriptEventVehicleCrashed::CRASH_AIRCRAFT_NO_AIRPORT
: ScriptEventVehicleCrashed::CRASH_PLANE_LANDING
));
1289 Game::NewEvent(new ScriptEventVehicleCrashed(v
->index
, v
->tile
, st
== NULL
? ScriptEventVehicleCrashed::CRASH_AIRCRAFT_NO_AIRPORT
: ScriptEventVehicleCrashed::CRASH_PLANE_LANDING
));
1291 AddVehicleNewsItem(newsitem
, NT_ACCIDENT
, v
->index
, st
!= NULL
? st
->index
: INVALID_STATION
);
1293 ModifyStationRatingAround(v
->tile
, v
->owner
, -160, 30);
1294 if (_settings_client
.sound
.disaster
) SndPlayVehicleFx(SND_12_EXPLOSION
, v
);
1298 * Decide whether aircraft \a v should crash.
1299 * @param v Aircraft to test.
1301 static void MaybeCrashAirplane(Aircraft
*v
)
1303 if (_settings_game
.vehicle
.plane_crashes
== 0) return;
1305 Station
*st
= Station::Get(v
->targetairport
);
1307 /* FIXME -- MaybeCrashAirplane -> increase crashing chances of very modern airplanes on smaller than AT_METROPOLITAN airports */
1308 uint32 prob
= (0x4000 << _settings_game
.vehicle
.plane_crashes
);
1309 if ((st
->airport
.GetFTA()->flags
& AirportFTAClass::SHORT_STRIP
) &&
1310 (AircraftVehInfo(v
->engine_type
)->subtype
& AIR_FAST
) &&
1311 !_cheats
.no_jetcrash
.value
) {
1317 if (GB(Random(), 0, 22) > prob
) return;
1319 /* Crash the airplane. Remove all goods stored at the station. */
1320 for (CargoID i
= 0; i
< NUM_CARGO
; i
++) {
1321 st
->goods
[i
].rating
= 1;
1322 st
->goods
[i
].cargo
.Truncate();
1329 * Aircraft arrives at a terminal. If it is the first aircraft, throw a party.
1330 * Start loading cargo.
1331 * @param v Aircraft that arrived.
1333 static void AircraftEntersTerminal(Aircraft
*v
)
1335 if (v
->current_order
.IsType(OT_GOTO_DEPOT
)) return;
1337 Station
*st
= Station::Get(v
->targetairport
);
1338 v
->last_station_visited
= v
->targetairport
;
1340 /* Check if station was ever visited before */
1341 if (!(st
->had_vehicle_of_type
& HVOT_AIRCRAFT
)) {
1342 st
->had_vehicle_of_type
|= HVOT_AIRCRAFT
;
1343 SetDParam(0, st
->index
);
1344 /* show newsitem of celebrating citizens */
1346 STR_NEWS_FIRST_AIRCRAFT_ARRIVAL
,
1347 (v
->owner
== _local_company
) ? NT_ARRIVAL_COMPANY
: NT_ARRIVAL_OTHER
,
1351 AI::NewEvent(v
->owner
, new ScriptEventStationFirstVehicle(st
->index
, v
->index
));
1352 Game::NewEvent(new ScriptEventStationFirstVehicle(st
->index
, v
->index
));
1359 * Aircraft touched down at the landing strip.
1360 * @param v Aircraft that landed.
1362 static void AircraftLandAirplane(Aircraft
*v
)
1364 v
->UpdateDeltaXY(INVALID_DIR
);
1366 if (!PlayVehicleSound(v
, VSE_TOUCHDOWN
)) {
1367 SndPlayVehicleFx(SND_17_SKID_PLANE
, v
);
1372 /** set the right pos when heading to other airports after takeoff */
1373 void AircraftNextAirportPos_and_Order(Aircraft
*v
)
1375 if (v
->current_order
.IsType(OT_GOTO_STATION
) || v
->current_order
.IsType(OT_GOTO_DEPOT
)) {
1376 v
->targetairport
= v
->current_order
.GetDestination();
1379 const Station
*st
= GetTargetAirportIfValid(v
);
1380 const AirportFTAClass
*apc
= st
== NULL
? GetAirport(AT_DUMMY
) : st
->airport
.GetFTA();
1381 Direction rotation
= st
== NULL
? DIR_N
: st
->airport
.rotation
;
1382 v
->pos
= v
->previous_pos
= AircraftGetEntryPoint(v
, apc
, rotation
);
1386 * Aircraft is about to leave the hangar.
1387 * @param v Aircraft leaving.
1388 * @param exit_dir The direction the vehicle leaves the hangar.
1389 * @note This function is called in AfterLoadGame for old savegames, so don't rely
1390 * on any data to be valid, especially don't rely on the fact that the vehicle
1391 * is actually on the ground inside a depot.
1393 void AircraftLeaveHangar(Aircraft
*v
, Direction exit_dir
)
1398 v
->direction
= exit_dir
;
1399 v
->vehstatus
&= ~VS_HIDDEN
;
1401 Vehicle
*u
= v
->Next();
1402 u
->vehstatus
&= ~VS_HIDDEN
;
1407 u
->vehstatus
&= ~VS_HIDDEN
;
1412 VehicleServiceInDepot(v
);
1413 SetAircraftPosition(v
, v
->x_pos
, v
->y_pos
, v
->z_pos
);
1414 InvalidateWindowData(WC_VEHICLE_DEPOT
, v
->tile
);
1415 SetWindowClassesDirty(WC_AIRCRAFT_LIST
);
1418 ////////////////////////////////////////////////////////////////////////////////
1419 /////////////////// AIRCRAFT MOVEMENT SCHEME ////////////////////////////////
1420 ////////////////////////////////////////////////////////////////////////////////
1421 static void AircraftEventHandler_EnterTerminal(Aircraft
*v
, const AirportFTAClass
*apc
)
1423 AircraftEntersTerminal(v
);
1424 v
->state
= apc
->layout
[v
->pos
].heading
;
1428 * Aircraft arrived in an airport hangar.
1429 * @param v Aircraft in the hangar.
1430 * @param apc Airport description containing the hangar.
1432 static void AircraftEventHandler_EnterHangar(Aircraft
*v
, const AirportFTAClass
*apc
)
1434 VehicleEnterDepot(v
);
1435 v
->state
= apc
->layout
[v
->pos
].heading
;
1439 * Handle aircraft movement/decision making in an airport hangar.
1440 * @param v Aircraft in the hangar.
1441 * @param apc Airport description containing the hangar.
1443 static void AircraftEventHandler_InHangar(Aircraft
*v
, const AirportFTAClass
*apc
)
1445 /* if we just arrived, execute EnterHangar first */
1446 if (v
->previous_pos
!= v
->pos
) {
1447 AircraftEventHandler_EnterHangar(v
, apc
);
1451 if (v
->current_order
.IsWaitTimetabled())
1452 v
->HandleWaiting(false);
1453 if (v
->current_order
.IsType(OT_WAITING
))
1456 /* if we were sent to the depot, stay there */
1457 if (v
->current_order
.IsType(OT_GOTO_DEPOT
) && (v
->vehstatus
& VS_STOPPED
)) {
1458 v
->current_order
.Free();
1462 if (!v
->current_order
.IsType(OT_GOTO_STATION
) &&
1463 !v
->current_order
.IsType(OT_GOTO_DEPOT
))
1466 /* We are leaving a hangar, but have to go to the exact same one; re-enter */
1467 if (v
->current_order
.IsType(OT_GOTO_DEPOT
) && v
->current_order
.GetDestination() == v
->targetairport
) {
1468 VehicleEnterDepot(v
);
1472 /* if the block of the next position is busy, stay put */
1473 if (AirportHasBlock(v
, &apc
->layout
[v
->pos
], apc
)) return;
1475 /* We are already at the target airport, we need to find a terminal */
1476 if (v
->current_order
.GetDestination() == v
->targetairport
) {
1477 /* FindFreeTerminal:
1478 * 1. Find a free terminal, 2. Occupy it, 3. Set the vehicle's state to that terminal */
1479 if (v
->subtype
== AIR_HELICOPTER
) {
1480 if (!AirportFindFreeHelipad(v
, apc
)) return; // helicopter
1482 if (!AirportFindFreeTerminal(v
, apc
)) return; // airplane
1484 } else { // Else prepare for launch.
1485 /* airplane goto state takeoff, helicopter to helitakeoff */
1486 v
->state
= (v
->subtype
== AIR_HELICOPTER
) ? HELITAKEOFF
: TAKEOFF
;
1488 const Station
*st
= Station::GetByTile(v
->tile
);
1489 AircraftLeaveHangar(v
, st
->airport
.GetHangarExitDirection(v
->tile
));
1490 AirportMove(v
, apc
);
1493 /** At one of the Airport's Terminals */
1494 static void AircraftEventHandler_AtTerminal(Aircraft
*v
, const AirportFTAClass
*apc
)
1496 /* if we just arrived, execute EnterTerminal first */
1497 if (v
->previous_pos
!= v
->pos
) {
1498 AircraftEventHandler_EnterTerminal(v
, apc
);
1499 /* on an airport with helipads, a helicopter will always land there
1500 * and get serviced at the same time - setting */
1501 if (_settings_game
.order
.serviceathelipad
) {
1502 if (v
->subtype
== AIR_HELICOPTER
&& apc
->num_helipads
> 0) {
1503 /* an excerpt of ServiceAircraft, without the invisibility stuff */
1504 v
->date_of_last_service
= _date
;
1505 v
->breakdowns_since_last_service
= 0;
1506 v
->reliability
= v
->GetEngine()->reliability
;
1507 SetWindowDirty(WC_VEHICLE_DETAILS
, v
->index
);
1513 if (v
->current_order
.IsType(OT_NOTHING
)) return;
1515 /* if the block of the next position is busy, stay put */
1516 if (AirportHasBlock(v
, &apc
->layout
[v
->pos
], apc
)) return;
1518 /* airport-road is free. We either have to go to another airport, or to the hangar
1519 * ---> start moving */
1521 bool go_to_hangar
= false;
1522 switch (v
->current_order
.GetType()) {
1523 case OT_GOTO_STATION
: // ready to fly to another airport
1525 case OT_GOTO_DEPOT
: // visit hangar for servicing, sale, etc.
1526 go_to_hangar
= v
->current_order
.GetDestination() == v
->targetairport
;
1528 case OT_CONDITIONAL
:
1529 /* In case of a conditional order we just have to wait a tick
1530 * longer, so the conditional order can actually be processed;
1531 * we should not clear the order as that makes us go nowhere. */
1533 default: // orders have been deleted (no orders), goto depot and don't bother us
1534 v
->current_order
.Free();
1535 go_to_hangar
= Station::Get(v
->targetairport
)->airport
.HasHangar();
1541 /* airplane goto state takeoff, helicopter to helitakeoff */
1542 v
->state
= (v
->subtype
== AIR_HELICOPTER
) ? HELITAKEOFF
: TAKEOFF
;
1544 AirportMove(v
, apc
);
1547 static void AircraftEventHandler_General(Aircraft
*v
, const AirportFTAClass
*apc
)
1549 error("OK, you shouldn't be here, check your Airport Scheme!");
1552 static void AircraftEventHandler_TakeOff(Aircraft
*v
, const AirportFTAClass
*apc
)
1554 PlayAircraftSound(v
); // play takeoffsound for airplanes
1555 v
->state
= STARTTAKEOFF
;
1558 static void AircraftEventHandler_StartTakeOff(Aircraft
*v
, const AirportFTAClass
*apc
)
1560 v
->state
= ENDTAKEOFF
;
1561 v
->UpdateDeltaXY(INVALID_DIR
);
1564 static void AircraftEventHandler_EndTakeOff(Aircraft
*v
, const AirportFTAClass
*apc
)
1567 /* get the next position to go to, differs per airport */
1568 AircraftNextAirportPos_and_Order(v
);
1571 static void AircraftEventHandler_HeliTakeOff(Aircraft
*v
, const AirportFTAClass
*apc
)
1574 v
->UpdateDeltaXY(INVALID_DIR
);
1576 /* get the next position to go to, differs per airport */
1577 AircraftNextAirportPos_and_Order(v
);
1579 /* Send the helicopter to a hangar if needed for replacement */
1580 if (v
->NeedsAutomaticServicing()) {
1581 Backup
<CompanyByte
> cur_company(_current_company
, v
->owner
, FILE_LINE
);
1582 DoCommand(v
->tile
, v
->index
| DEPOT_SERVICE
| DEPOT_LOCATE_HANGAR
, 0, DC_EXEC
, CMD_SEND_VEHICLE_TO_DEPOT
);
1583 cur_company
.Restore();
1587 static void AircraftEventHandler_Flying(Aircraft
*v
, const AirportFTAClass
*apc
)
1589 Station
*st
= Station::Get(v
->targetairport
);
1591 /* Runway busy, not allowed to use this airstation or closed, circle. */
1592 if (CanVehicleUseStation(v
, st
) && (st
->owner
== OWNER_NONE
|| st
->owner
== v
->owner
) && !(st
->airport
.flags
& AIRPORT_CLOSED_block
)) {
1593 /* {32,FLYING,NOTHING_block,37}, {32,LANDING,N,33}, {32,HELILANDING,N,41},
1594 * if it is an airplane, look for LANDING, for helicopter HELILANDING
1595 * it is possible to choose from multiple landing runways, so loop until a free one is found */
1596 byte landingtype
= (v
->subtype
== AIR_HELICOPTER
) ? HELILANDING
: LANDING
;
1597 const AirportFTA
*current
= apc
->layout
[v
->pos
].next
;
1598 while (current
!= NULL
) {
1599 if (current
->heading
== landingtype
) {
1600 /* save speed before, since if AirportHasBlock is false, it resets them to 0
1601 * we don't want that for plane in air
1602 * hack for speed thingie */
1603 uint16 tcur_speed
= v
->cur_speed
;
1604 uint16 tsubspeed
= v
->subspeed
;
1605 if (!AirportHasBlock(v
, current
, apc
)) {
1606 v
->state
= landingtype
; // LANDING / HELILANDING
1607 /* it's a bit dirty, but I need to set position to next position, otherwise
1608 * if there are multiple runways, plane won't know which one it took (because
1609 * they all have heading LANDING). And also occupy that block! */
1610 v
->pos
= current
->next_position
;
1611 SETBITS(st
->airport
.flags
, apc
->layout
[v
->pos
].block
);
1614 v
->cur_speed
= tcur_speed
;
1615 v
->subspeed
= tsubspeed
;
1617 current
= current
->next
;
1621 v
->pos
= apc
->layout
[v
->pos
].next_position
;
1624 static void AircraftEventHandler_Landing(Aircraft
*v
, const AirportFTAClass
*apc
)
1626 v
->state
= ENDLANDING
;
1627 AircraftLandAirplane(v
); // maybe crash airplane
1629 /* check if the aircraft needs to be replaced or renewed and send it to a hangar if needed */
1630 if (v
->NeedsAutomaticServicing()) {
1631 Backup
<CompanyByte
> cur_company(_current_company
, v
->owner
, FILE_LINE
);
1632 DoCommand(v
->tile
, v
->index
| DEPOT_SERVICE
, 0, DC_EXEC
, CMD_SEND_VEHICLE_TO_DEPOT
);
1633 cur_company
.Restore();
1637 static void AircraftEventHandler_HeliLanding(Aircraft
*v
, const AirportFTAClass
*apc
)
1639 v
->state
= HELIENDLANDING
;
1640 v
->UpdateDeltaXY(INVALID_DIR
);
1643 static void AircraftEventHandler_EndLanding(Aircraft
*v
, const AirportFTAClass
*apc
)
1645 /* next block busy, don't do a thing, just wait */
1646 if (AirportHasBlock(v
, &apc
->layout
[v
->pos
], apc
)) return;
1648 /* if going to terminal (OT_GOTO_STATION) choose one
1649 * 1. in case all terminals are busy AirportFindFreeTerminal() returns false or
1650 * 2. not going for terminal (but depot, no order),
1651 * --> get out of the way to the hangar. */
1652 if (v
->current_order
.IsType(OT_GOTO_STATION
)) {
1653 if (AirportFindFreeTerminal(v
, apc
)) return;
1659 static void AircraftEventHandler_HeliEndLanding(Aircraft
*v
, const AirportFTAClass
*apc
)
1661 /* next block busy, don't do a thing, just wait */
1662 if (AirportHasBlock(v
, &apc
->layout
[v
->pos
], apc
)) return;
1664 /* if going to helipad (OT_GOTO_STATION) choose one. If airport doesn't have helipads, choose terminal
1665 * 1. in case all terminals/helipads are busy (AirportFindFreeHelipad() returns false) or
1666 * 2. not going for terminal (but depot, no order),
1667 * --> get out of the way to the hangar IF there are terminals on the airport.
1669 * the reason behind this is that if an airport has a terminal, it also has a hangar. Airplanes
1670 * must go to a hangar. */
1671 if (v
->current_order
.IsType(OT_GOTO_STATION
)) {
1672 if (AirportFindFreeHelipad(v
, apc
)) return;
1674 v
->state
= Station::Get(v
->targetairport
)->airport
.HasHangar() ? HANGAR
: HELITAKEOFF
;
1678 * Signature of the aircraft handler function.
1679 * @param v Aircraft to handle.
1680 * @param apc Airport state machine.
1682 typedef void AircraftStateHandler(Aircraft
*v
, const AirportFTAClass
*apc
);
1683 /** Array of handler functions for each target of the aircraft. */
1684 static AircraftStateHandler
* const _aircraft_state_handlers
[] = {
1685 AircraftEventHandler_General
, // TO_ALL = 0
1686 AircraftEventHandler_InHangar
, // HANGAR = 1
1687 AircraftEventHandler_AtTerminal
, // TERM1 = 2
1688 AircraftEventHandler_AtTerminal
, // TERM2 = 3
1689 AircraftEventHandler_AtTerminal
, // TERM3 = 4
1690 AircraftEventHandler_AtTerminal
, // TERM4 = 5
1691 AircraftEventHandler_AtTerminal
, // TERM5 = 6
1692 AircraftEventHandler_AtTerminal
, // TERM6 = 7
1693 AircraftEventHandler_AtTerminal
, // HELIPAD1 = 8
1694 AircraftEventHandler_AtTerminal
, // HELIPAD2 = 9
1695 AircraftEventHandler_TakeOff
, // TAKEOFF = 10
1696 AircraftEventHandler_StartTakeOff
, // STARTTAKEOFF = 11
1697 AircraftEventHandler_EndTakeOff
, // ENDTAKEOFF = 12
1698 AircraftEventHandler_HeliTakeOff
, // HELITAKEOFF = 13
1699 AircraftEventHandler_Flying
, // FLYING = 14
1700 AircraftEventHandler_Landing
, // LANDING = 15
1701 AircraftEventHandler_EndLanding
, // ENDLANDING = 16
1702 AircraftEventHandler_HeliLanding
, // HELILANDING = 17
1703 AircraftEventHandler_HeliEndLanding
, // HELIENDLANDING = 18
1704 AircraftEventHandler_AtTerminal
, // TERM7 = 19
1705 AircraftEventHandler_AtTerminal
, // TERM8 = 20
1706 AircraftEventHandler_AtTerminal
, // HELIPAD3 = 21
1709 static void AirportClearBlock(const Aircraft
*v
, const AirportFTAClass
*apc
)
1711 /* we have left the previous block, and entered the new one. Free the previous block */
1712 if (apc
->layout
[v
->previous_pos
].block
!= apc
->layout
[v
->pos
].block
) {
1713 Station
*st
= Station::Get(v
->targetairport
);
1715 CLRBITS(st
->airport
.flags
, apc
->layout
[v
->previous_pos
].block
);
1719 static void AirportGoToNextPosition(Aircraft
*v
)
1721 /* if aircraft is not in position, wait until it is */
1722 if (!AircraftController(v
)) return;
1724 const AirportFTAClass
*apc
= Station::Get(v
->targetairport
)->airport
.GetFTA();
1726 AirportClearBlock(v
, apc
);
1727 AirportMove(v
, apc
); // move aircraft to next position
1730 /* gets pos from vehicle and next orders */
1731 static bool AirportMove(Aircraft
*v
, const AirportFTAClass
*apc
)
1733 /* error handling */
1734 if (v
->pos
>= apc
->nofelements
) {
1735 DEBUG(misc
, 0, "[Ap] position %d is not valid for current airport. Max position is %d", v
->pos
, apc
->nofelements
-1);
1736 assert(v
->pos
< apc
->nofelements
);
1739 const AirportFTA
*current
= &apc
->layout
[v
->pos
];
1740 /* we have arrived in an important state (eg terminal, hangar, etc.) */
1741 if (current
->heading
== v
->state
) {
1742 byte prev_pos
= v
->pos
; // location could be changed in state, so save it before-hand
1743 byte prev_state
= v
->state
;
1744 _aircraft_state_handlers
[v
->state
](v
, apc
);
1745 if (v
->state
!= FLYING
) v
->previous_pos
= prev_pos
;
1746 if (v
->state
!= prev_state
|| v
->pos
!= prev_pos
) UpdateAircraftCache(v
);
1750 v
->previous_pos
= v
->pos
; // save previous location
1752 /* there is only one choice to move to */
1753 if (current
->next
== NULL
) {
1754 if (AirportSetBlocks(v
, current
, apc
)) {
1755 v
->pos
= current
->next_position
;
1756 UpdateAircraftCache(v
);
1757 } // move to next position
1761 /* there are more choices to choose from, choose the one that
1762 * matches our heading */
1764 if (v
->state
== current
->heading
|| current
->heading
== TO_ALL
) {
1765 if (AirportSetBlocks(v
, current
, apc
)) {
1766 v
->pos
= current
->next_position
;
1767 UpdateAircraftCache(v
);
1768 } // move to next position
1771 current
= current
->next
;
1772 } while (current
!= NULL
);
1774 DEBUG(misc
, 0, "[Ap] cannot move further on Airport! (pos %d state %d) for vehicle %d", v
->pos
, v
->state
, v
->index
);
1778 /** returns true if the road ahead is busy, eg. you must wait before proceeding. */
1779 static bool AirportHasBlock(Aircraft
*v
, const AirportFTA
*current_pos
, const AirportFTAClass
*apc
)
1781 const AirportFTA
*reference
= &apc
->layout
[v
->pos
];
1782 const AirportFTA
*next
= &apc
->layout
[current_pos
->next_position
];
1784 /* same block, then of course we can move */
1785 if (apc
->layout
[current_pos
->position
].block
!= next
->block
) {
1786 const Station
*st
= Station::Get(v
->targetairport
);
1787 uint64 airport_flags
= next
->block
;
1789 /* check additional possible extra blocks */
1790 if (current_pos
!= reference
&& current_pos
->block
!= NOTHING_block
) {
1791 airport_flags
|= current_pos
->block
;
1794 if (st
->airport
.flags
& airport_flags
) {
1804 * "reserve" a block for the plane
1805 * @param v airplane that requires the operation
1806 * @param current_pos of the vehicle in the list of blocks
1807 * @param apc airport on which block is requsted to be set
1808 * @returns true on success. Eg, next block was free and we have occupied it
1810 static bool AirportSetBlocks(Aircraft
*v
, const AirportFTA
*current_pos
, const AirportFTAClass
*apc
)
1812 const AirportFTA
*next
= &apc
->layout
[current_pos
->next_position
];
1813 const AirportFTA
*reference
= &apc
->layout
[v
->pos
];
1815 /* if the next position is in another block, check it and wait until it is free */
1816 if ((apc
->layout
[current_pos
->position
].block
& next
->block
) != next
->block
) {
1817 uint64 airport_flags
= next
->block
;
1818 /* search for all all elements in the list with the same state, and blocks != N
1819 * this means more blocks should be checked/set */
1820 const AirportFTA
*current
= current_pos
;
1821 if (current
== reference
) current
= current
->next
;
1822 while (current
!= NULL
) {
1823 if (current
->heading
== current_pos
->heading
&& current
->block
!= 0) {
1824 airport_flags
|= current
->block
;
1827 current
= current
->next
;
1830 /* if the block to be checked is in the next position, then exclude that from
1831 * checking, because it has been set by the airplane before */
1832 if (current_pos
->block
== next
->block
) airport_flags
^= next
->block
;
1834 Station
*st
= Station::Get(v
->targetairport
);
1835 if (st
->airport
.flags
& airport_flags
) {
1841 if (next
->block
!= NOTHING_block
) {
1842 SETBITS(st
->airport
.flags
, airport_flags
); // occupy next block
1849 * Combination of aircraft state for going to a certain terminal and the
1850 * airport flag for that terminal block.
1852 struct MovementTerminalMapping
{
1853 AirportMovementStates state
; ///< Aircraft movement state when going to this terminal.
1854 uint64 airport_flag
; ///< Bitmask in the airport flags that need to be free for this terminal.
1857 /** A list of all valid terminals and their associated blocks. */
1858 static const MovementTerminalMapping _airport_terminal_mapping
[] = {
1859 {TERM1
, TERM1_block
},
1860 {TERM2
, TERM2_block
},
1861 {TERM3
, TERM3_block
},
1862 {TERM4
, TERM4_block
},
1863 {TERM5
, TERM5_block
},
1864 {TERM6
, TERM6_block
},
1865 {TERM7
, TERM7_block
},
1866 {TERM8
, TERM8_block
},
1867 {HELIPAD1
, HELIPAD1_block
},
1868 {HELIPAD2
, HELIPAD2_block
},
1869 {HELIPAD3
, HELIPAD3_block
},
1873 * Find a free terminal or helipad, and if available, assign it.
1874 * @param v Aircraft looking for a free terminal or helipad.
1875 * @param i First terminal to examine.
1876 * @param last_terminal Terminal number to stop examining.
1877 * @return A terminal or helipad has been found, and has been assigned to the aircraft.
1879 static bool FreeTerminal(Aircraft
*v
, byte i
, byte last_terminal
)
1881 assert(last_terminal
<= lengthof(_airport_terminal_mapping
));
1882 Station
*st
= Station::Get(v
->targetairport
);
1883 for (; i
< last_terminal
; i
++) {
1884 if ((st
->airport
.flags
& _airport_terminal_mapping
[i
].airport_flag
) == 0) {
1885 /* TERMINAL# HELIPAD# */
1886 v
->state
= _airport_terminal_mapping
[i
].state
; // start moving to that terminal/helipad
1887 SETBITS(st
->airport
.flags
, _airport_terminal_mapping
[i
].airport_flag
); // occupy terminal/helipad
1895 * Get the number of terminals at the airport.
1896 * @param afc Airport description.
1897 * @return Number of terminals.
1899 static uint
GetNumTerminals(const AirportFTAClass
*apc
)
1903 for (uint i
= apc
->terminals
[0]; i
> 0; i
--) num
+= apc
->terminals
[i
];
1909 * Find a free terminal, and assign it if available.
1910 * @param v Aircraft to handle.
1911 * @param apc Airport state machine.
1912 * @return Found a free terminal and assigned it.
1914 static bool AirportFindFreeTerminal(Aircraft
*v
, const AirportFTAClass
*apc
)
1916 /* example of more terminalgroups
1917 * {0,HANGAR,NOTHING_block,1}, {0,255,TERM_GROUP1_block,0}, {0,255,TERM_GROUP2_ENTER_block,1}, {0,0,N,1},
1918 * Heading 255 denotes a group. We see 2 groups here:
1919 * 1. group 0 -- TERM_GROUP1_block (check block)
1920 * 2. group 1 -- TERM_GROUP2_ENTER_block (check block)
1921 * First in line is checked first, group 0. If the block (TERM_GROUP1_block) is free, it
1922 * looks at the corresponding terminals of that group. If no free ones are found, other
1923 * possible groups are checked (in this case group 1, since that is after group 0). If that
1924 * fails, then attempt fails and plane waits
1926 if (apc
->terminals
[0] > 1) {
1927 const Station
*st
= Station::Get(v
->targetairport
);
1928 const AirportFTA
*temp
= apc
->layout
[v
->pos
].next
;
1930 while (temp
!= NULL
) {
1931 if (temp
->heading
== 255) {
1932 if (!(st
->airport
.flags
& temp
->block
)) {
1933 /* read which group do we want to go to?
1934 * (the first free group) */
1935 uint target_group
= temp
->next_position
+ 1;
1937 /* at what terminal does the group start?
1938 * that means, sum up all terminals of
1939 * groups with lower number */
1940 uint group_start
= 0;
1941 for (uint i
= 1; i
< target_group
; i
++) {
1942 group_start
+= apc
->terminals
[i
];
1945 uint group_end
= group_start
+ apc
->terminals
[target_group
];
1946 if (FreeTerminal(v
, group_start
, group_end
)) return true;
1949 /* once the heading isn't 255, we've exhausted the possible blocks.
1950 * So we cannot move */
1957 /* if there is only 1 terminalgroup, all terminals are checked (starting from 0 to max) */
1958 return FreeTerminal(v
, 0, GetNumTerminals(apc
));
1962 * Find a free helipad, and assign it if available.
1963 * @param v Aircraft to handle.
1964 * @param apc Airport state machine.
1965 * @return Found a free helipad and assigned it.
1967 static bool AirportFindFreeHelipad(Aircraft
*v
, const AirportFTAClass
*apc
)
1969 /* if an airport doesn't have helipads, use terminals */
1970 if (apc
->num_helipads
== 0) return AirportFindFreeTerminal(v
, apc
);
1972 /* only 1 helicoptergroup, check all helipads
1973 * The blocks for helipads start after the last terminal (MAX_TERMINALS) */
1974 return FreeTerminal(v
, MAX_TERMINALS
, apc
->num_helipads
+ MAX_TERMINALS
);
1978 * Handle the 'dest too far' flag and the corresponding news message for aircraft.
1979 * @param v The aircraft.
1980 * @param too_far True if the current destination is too far away.
1982 static void AircraftHandleDestTooFar(Aircraft
*v
, bool too_far
)
1985 if (!HasBit(v
->flags
, VAF_DEST_TOO_FAR
)) {
1986 SetBit(v
->flags
, VAF_DEST_TOO_FAR
);
1987 SetWindowWidgetDirty(WC_VEHICLE_VIEW
, v
->index
, WID_VV_START_STOP
);
1988 AI::NewEvent(v
->owner
, new ScriptEventAircraftDestTooFar(v
->index
));
1989 if (v
->owner
== _local_company
) {
1990 /* Post a news message. */
1991 SetDParam(0, v
->index
);
1992 AddVehicleAdviceNewsItem(STR_NEWS_AIRCRAFT_DEST_TOO_FAR
, v
->index
);
1998 if (HasBit(v
->flags
, VAF_DEST_TOO_FAR
)) {
1999 /* Not too far anymore, clear flag and message. */
2000 ClrBit(v
->flags
, VAF_DEST_TOO_FAR
);
2001 SetWindowWidgetDirty(WC_VEHICLE_VIEW
, v
->index
, WID_VV_START_STOP
);
2002 DeleteVehicleNews(v
->index
, STR_NEWS_AIRCRAFT_DEST_TOO_FAR
);
2006 static bool AircraftEventHandler(Aircraft
*v
, int loop
)
2008 if (v
->vehstatus
& VS_CRASHED
) {
2009 return HandleCrashedAircraft(v
);
2012 if (v
->vehstatus
& VS_STOPPED
) return true;
2014 v
->HandleBreakdown();
2016 HandleAircraftSmoke(v
, loop
!= 0);
2018 v
->HandleLoading(loop
!= 0);
2020 if (v
->current_order
.IsType(OT_LOADING
) || v
->current_order
.IsType(OT_LEAVESTATION
)) return true;
2022 if (v
->state
>= ENDTAKEOFF
&& v
->state
<= HELIENDLANDING
) {
2023 /* If we are flying, unconditionally clear the 'dest too far' state. */
2024 AircraftHandleDestTooFar(v
, false);
2025 } else if (v
->acache
.cached_max_range_sqr
!= 0) {
2026 /* Check the distance to the next destination. This code works because the target
2027 * airport is only updated after take off and not on the ground. */
2028 Station
*cur_st
= Station::GetIfValid(v
->targetairport
);
2029 Station
*next_st
= v
->current_order
.IsType(OT_GOTO_STATION
) || v
->current_order
.IsType(OT_GOTO_DEPOT
) ? Station::GetIfValid(v
->current_order
.GetDestination()) : NULL
;
2031 if (cur_st
!= NULL
&& cur_st
->airport
.tile
!= INVALID_TILE
&& next_st
!= NULL
&& next_st
->airport
.tile
!= INVALID_TILE
) {
2032 uint dist
= DistanceSquare(cur_st
->airport
.tile
, next_st
->airport
.tile
);
2033 AircraftHandleDestTooFar(v
, dist
> v
->acache
.cached_max_range_sqr
);
2037 if (!HasBit(v
->flags
, VAF_DEST_TOO_FAR
)) AirportGoToNextPosition(v
);
2042 bool Aircraft::Tick()
2044 if (!this->IsNormalAircraft()) return true;
2046 this->tick_counter
++;
2048 if (!((this->vehstatus
& VS_STOPPED
) || this->IsChainInDepot())) this->running_ticks
++;
2050 if (this->subtype
== AIR_HELICOPTER
) HelicopterTickHandler(this);
2052 this->current_order_time
++;
2054 for (uint i
= 0; i
!= 2; i
++) {
2055 /* stop if the aircraft was deleted */
2056 if (!AircraftEventHandler(this, i
)) return false;
2064 * Returns aircraft's target station if v->target_airport
2065 * is a valid station with airport.
2066 * @param v vehicle to get target airport for
2067 * @return pointer to target station, NULL if invalid
2069 Station
*GetTargetAirportIfValid(const Aircraft
*v
)
2071 assert(v
->type
== VEH_AIRCRAFT
);
2073 Station
*st
= Station::GetIfValid(v
->targetairport
);
2074 if (st
== NULL
) return NULL
;
2076 return st
->airport
.tile
== INVALID_TILE
? NULL
: st
;
2080 * Updates the status of the Aircraft heading or in the station
2081 * @param st Station been updated
2083 void UpdateAirplanesOnNewStation(const Station
*st
)
2085 /* only 1 station is updated per function call, so it is enough to get entry_point once */
2086 const AirportFTAClass
*ap
= st
->airport
.GetFTA();
2087 Direction rotation
= st
->airport
.tile
== INVALID_TILE
? DIR_N
: st
->airport
.rotation
;
2090 FOR_ALL_AIRCRAFT(v
) {
2091 if (!v
->IsNormalAircraft() || v
->targetairport
!= st
->index
) continue;
2092 assert(v
->state
== FLYING
);
2093 v
->pos
= v
->previous_pos
= AircraftGetEntryPoint(v
, ap
, rotation
);
2094 UpdateAircraftCache(v
);