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 "map/zoneheight.h"
41 #include "table/strings.h"
43 void Aircraft::UpdateDeltaXY(Direction direction
)
50 switch (this->subtype
) {
51 default: NOT_REACHED();
55 switch (this->state
) {
80 static bool AirportMove(Aircraft
*v
, const AirportFTAClass
*apc
);
81 static bool AirportSetBlocks(Aircraft
*v
, const AirportFTA
*current_pos
, const AirportFTAClass
*apc
);
82 static bool AirportHasBlock(Aircraft
*v
, const AirportFTA
*current_pos
, const AirportFTAClass
*apc
);
83 static bool AirportFindFreeTerminal(Aircraft
*v
, const AirportFTAClass
*apc
);
84 static bool AirportFindFreeHelipad(Aircraft
*v
, const AirportFTAClass
*apc
);
85 static void CrashAirplane(Aircraft
*v
);
87 static const SpriteID _aircraft_sprite
[] = {
88 0x0EB5, 0x0EBD, 0x0EC5, 0x0ECD,
89 0x0ED5, 0x0EDD, 0x0E9D, 0x0EA5,
90 0x0EAD, 0x0EE5, 0x0F05, 0x0F0D,
91 0x0F15, 0x0F1D, 0x0F25, 0x0F2D,
92 0x0EED, 0x0EF5, 0x0EFD, 0x0F35,
93 0x0E9D, 0x0EA5, 0x0EAD, 0x0EB5,
98 bool IsValidImageIndex
<VEH_AIRCRAFT
>(uint8 image_index
)
100 return image_index
< lengthof(_aircraft_sprite
);
103 /** Helicopter rotor animation states */
104 enum HelicopterRotorStates
{
112 * Find the nearest hangar to v
113 * INVALID_STATION is returned, if the company does not have any suitable
114 * airports (like helipads only)
115 * @param v vehicle looking for a hangar
116 * @return the StationID if one is found, otherwise, INVALID_STATION
118 static StationID
FindNearestHangar(const Aircraft
*v
)
122 StationID index
= INVALID_STATION
;
123 TileIndex vtile
= TileVirtXY(v
->x_pos
, v
->y_pos
);
124 const AircraftVehicleInfo
*avi
= AircraftVehInfo(v
->engine_type
);
126 FOR_ALL_STATIONS(st
) {
127 if (st
->owner
!= v
->owner
|| !(st
->facilities
& FACIL_AIRPORT
)) continue;
129 const AirportFTAClass
*afc
= st
->airport
.GetFTA();
130 if (!st
->airport
.HasHangar() || (
131 /* don't crash the plane if we know it can't land at the airport */
132 (afc
->flags
& AirportFTAClass::SHORT_STRIP
) &&
133 (avi
->subtype
& AIR_FAST
) &&
134 !_cheats
.no_jetcrash
.value
)) {
138 /* v->tile can't be used here, when aircraft is flying v->tile is set to 0 */
139 uint distance
= DistanceSquare(vtile
, st
->airport
.tile
);
140 if (v
->acache
.cached_max_range_sqr
!= 0) {
141 /* Check if our current destination can be reached from the depot airport. */
142 const Station
*cur_dest
= GetTargetAirportIfValid(v
);
143 if (cur_dest
!= NULL
&& DistanceSquare(st
->airport
.tile
, cur_dest
->airport
.tile
) > v
->acache
.cached_max_range_sqr
) continue;
145 if (distance
< best
|| index
== INVALID_STATION
) {
153 void Aircraft::GetImage(Direction direction
, EngineImageType image_type
, VehicleSpriteSeq
*result
) const
155 uint8 spritenum
= this->spritenum
;
157 if (is_custom_sprite(spritenum
)) {
158 GetCustomVehicleSprite(this, direction
, image_type
, result
);
159 if (result
->IsValid()) return;
161 spritenum
= this->GetEngine()->original_image_index
;
164 assert(IsValidImageIndex
<VEH_AIRCRAFT
>(spritenum
));
165 result
->Set(direction
+ _aircraft_sprite
[spritenum
]);
168 void GetRotorImage(const Aircraft
*v
, EngineImageType image_type
, VehicleSpriteSeq
*result
)
170 assert(v
->subtype
== AIR_HELICOPTER
);
172 const Aircraft
*w
= v
->Next()->Next();
173 if (is_custom_sprite(v
->spritenum
)) {
174 GetCustomRotorSprite(v
, false, image_type
, result
);
175 if (result
->IsValid()) return;
178 /* Return standard rotor sprites if there are no custom sprites for this helicopter */
179 result
->Set(SPR_ROTOR_STOPPED
+ w
->state
);
182 static void GetAircraftIcon(EngineID engine
, EngineImageType image_type
, VehicleSpriteSeq
*result
)
184 const Engine
*e
= Engine::Get(engine
);
185 uint8 spritenum
= e
->u
.air
.image_index
;
187 if (is_custom_sprite(spritenum
)) {
188 GetCustomVehicleIcon(engine
, DIR_W
, image_type
, result
);
189 if (result
->IsValid()) return;
191 spritenum
= e
->original_image_index
;
194 assert(IsValidImageIndex
<VEH_AIRCRAFT
>(spritenum
));
195 result
->Set(DIR_W
+ _aircraft_sprite
[spritenum
]);
198 void DrawAircraftEngine (BlitArea
*dpi
, int left
, int right
,
199 int preferred_x
, int y
, EngineID engine
, PaletteID pal
,
200 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 (dpi
, 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 (dpi
, 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();
542 static void PlayAircraftSound(const Vehicle
*v
)
544 if (!PlayVehicleSound(v
, VSE_START
)) {
545 SndPlayVehicleFx(AircraftVehInfo(v
->engine_type
)->sfx
, v
);
551 * Update cached values of an aircraft.
552 * Currently caches callback 36 max speed.
554 * @param update_range Update the aircraft range.
556 void UpdateAircraftCache(Aircraft
*v
, bool update_range
)
558 uint max_speed
= GetVehicleProperty(v
, PROP_AIRCRAFT_SPEED
, 0);
559 if (max_speed
!= 0) {
560 /* Convert from original units to km-ish/h */
561 max_speed
= (max_speed
* 128) / 10;
563 v
->vcache
.cached_max_speed
= max_speed
;
565 /* Use the default max speed of the vehicle. */
566 v
->vcache
.cached_max_speed
= AircraftVehInfo(v
->engine_type
)->max_speed
;
569 /* Update cargo aging period. */
570 v
->vcache
.cached_cargo_age_period
= GetVehicleProperty(v
, PROP_AIRCRAFT_CARGO_AGE_PERIOD
, EngInfo(v
->engine_type
)->cargo_age_period
);
571 Aircraft
*u
= v
->Next(); // Shadow for mail
572 u
->vcache
.cached_cargo_age_period
= GetVehicleProperty(u
, PROP_AIRCRAFT_CARGO_AGE_PERIOD
, EngInfo(u
->engine_type
)->cargo_age_period
);
574 /* Update aircraft range. */
576 v
->acache
.cached_max_range
= GetVehicleProperty(v
, PROP_AIRCRAFT_RANGE
, AircraftVehInfo(v
->engine_type
)->max_range
);
577 /* Squared it now so we don't have to do it later all the time. */
578 v
->acache
.cached_max_range_sqr
= v
->acache
.cached_max_range
* v
->acache
.cached_max_range
;
584 * Special velocities for aircraft
586 enum AircraftSpeedLimits
{
587 SPEED_LIMIT_TAXI
= 50, ///< Maximum speed of an aircraft while taxiing
588 SPEED_LIMIT_APPROACH
= 230, ///< Maximum speed of an aircraft on finals
589 SPEED_LIMIT_BROKEN
= 320, ///< Maximum speed of an aircraft that is broken
590 SPEED_LIMIT_HOLD
= 425, ///< Maximum speed of an aircraft that flies the holding pattern
591 SPEED_LIMIT_NONE
= 0xFFFF, ///< No environmental speed limit. Speed limit is type dependent
595 * Sets the new speed for an aircraft
596 * @param v The vehicle for which the speed should be obtained
597 * @param speed_limit The maximum speed the vehicle may have.
598 * @param hard_limit If true, the limit is directly enforced, otherwise the plane is slowed down gradually
599 * @return The number of position updates needed within the tick
601 static int UpdateAircraftSpeed(Aircraft
*v
, uint speed_limit
= SPEED_LIMIT_NONE
, bool hard_limit
= true)
604 * 'acceleration' has the unit 3/8 mph/tick. This function is called twice per tick.
605 * So the speed amount we need to accelerate is:
606 * acceleration * 3 / 16 mph = acceleration * 3 / 16 * 16 / 10 km-ish/h
607 * = acceleration * 3 / 10 * 256 * (km-ish/h / 256)
608 * ~ acceleration * 77 (km-ish/h / 256)
610 uint spd
= v
->acceleration
* 77;
613 /* Adjust speed limits by plane speed factor to prevent taxiing
614 * and take-off speeds being too low. */
615 speed_limit
*= _settings_game
.vehicle
.plane_speed
;
617 if (v
->vcache
.cached_max_speed
< speed_limit
) {
618 if (v
->cur_speed
< speed_limit
) hard_limit
= false;
619 speed_limit
= v
->vcache
.cached_max_speed
;
622 v
->subspeed
= (t
= v
->subspeed
) + (byte
)spd
;
624 /* Aircraft's current speed is used twice so that very fast planes are
625 * forced to slow down rapidly in the short distance needed. The magic
626 * value 16384 was determined to give similar results to the old speed/48
627 * method at slower speeds. This also results in less reduction at slow
628 * speeds to that aircraft do not get to taxi speed straight after
630 if (!hard_limit
&& v
->cur_speed
> speed_limit
) {
631 speed_limit
= v
->cur_speed
- max(1, ((v
->cur_speed
* v
->cur_speed
) / 16384) / _settings_game
.vehicle
.plane_speed
);
634 spd
= min(v
->cur_speed
+ (spd
>> 8) + (v
->subspeed
< t
), speed_limit
);
636 /* adjust speed for broken vehicles */
637 if (v
->vehstatus
& VS_AIRCRAFT_BROKEN
) spd
= min(spd
, SPEED_LIMIT_BROKEN
);
639 /* updates statusbar only if speed have changed to save CPU time */
640 if (spd
!= v
->cur_speed
) {
642 SetWindowWidgetDirty(WC_VEHICLE_VIEW
, v
->index
, WID_VV_START_STOP
);
645 /* Adjust distance moved by plane speed setting */
646 if (_settings_game
.vehicle
.plane_speed
> 1) spd
/= _settings_game
.vehicle
.plane_speed
;
648 /* Convert direction-independent speed into direction-dependent speed. (old movement method) */
649 spd
= v
->GetOldAdvanceSpeed(spd
);
652 v
->progress
= (byte
)spd
;
657 * Get the base altitude for an aircraft, which is used as reference to
658 * compute flight levels.
659 * @param v The vehicle to get the base altitude for.
660 * @return The base altitude in pixels.
662 static int GetAircraftBaseAltitude (const Vehicle
*v
)
664 int safe_x
= Clamp(v
->x_pos
, 0, MapMaxX() * TILE_SIZE
);
665 int safe_y
= Clamp(v
->y_pos
, 0, MapMaxY() * TILE_SIZE
);
666 int z
= TileHeight (TileVirtXY (safe_x
, safe_y
)) * TILE_HEIGHT
;
668 /* Base altitude is 120 pixels above ground. */
671 if (v
->type
== VEH_AIRCRAFT
&& Aircraft::From(v
)->subtype
== AIR_HELICOPTER
) {
672 /* Base altitude is higher for helicopters. */
680 * Get the base flight level for an aircraft.
681 * @param v The vehicle to get the base flight level for.
682 * @return The base flight level in pixels.
684 int GetAircraftBaseFlightLevel (const Vehicle
*v
)
686 int z
= GetAircraftBaseAltitude (v
);
688 if (v
->type
== VEH_AIRCRAFT
&& Aircraft::From(v
)->subtype
!= AIR_HELICOPTER
) {
689 /* Make sure eastbound and westbound planes do not "crash" into
690 * each other by providing them with vertical separation. */
691 if (v
->direction
< (DIR_END
/ 2)) z
+= 10;
693 /* Make faster planes fly higher so that they can overtake slower ones */
694 z
+= min (20 * (v
->vcache
.cached_max_speed
/ 200) - 90, 0);
701 * Gets the maximum 'flight level' for the holding pattern of the aircraft,
702 * in pixels 'z_pos' 0, depending on terrain below..
704 * @param v The aircraft that may or may not need to decrease its altitude.
705 * @return Maximal aircraft holding altitude, while in normal flight, in pixels.
707 static int GetAircraftHoldMaxAltitude (const Aircraft
*v
)
709 /* Holding altitude range is 30 pixels. */
710 return GetAircraftBaseAltitude(v
) + 30;
713 int GetAircraftFlightLevel (const Vehicle
*v
, byte
*flags
, bool takeoff
)
715 /* Aircraft is in flight. We want to enforce it being somewhere
716 * between the minimum and the maximum allowed altitude. */
717 int aircraft_min_altitude
= GetAircraftBaseFlightLevel (v
);
719 /* Flight altitude range is 240 pixels. */
720 int aircraft_max_altitude
= aircraft_min_altitude
+ 240;
722 int aircraft_middle_altitude
= aircraft_min_altitude
+ 120;
725 if (z
< aircraft_min_altitude
||
726 (HasBit(*flags
, VAF_IN_MIN_HEIGHT_CORRECTION
) && z
< aircraft_middle_altitude
)) {
727 /* Ascend. And don't fly into that mountain right ahead.
728 * And avoid our aircraft become a stairclimber, so if we start
729 * correcting altitude, then we stop correction not too early. */
730 SetBit(*flags
, VAF_IN_MIN_HEIGHT_CORRECTION
);
731 z
+= takeoff
? 2 : 1;
732 } else if (!takeoff
&& (z
> aircraft_max_altitude
||
733 (HasBit(*flags
, VAF_IN_MAX_HEIGHT_CORRECTION
) && z
> aircraft_middle_altitude
))) {
734 /* Descend lower. You are an aircraft, not an space ship.
735 * And again, don't stop correcting altitude too early. */
736 SetBit(*flags
, VAF_IN_MAX_HEIGHT_CORRECTION
);
738 } else if (HasBit(*flags
, VAF_IN_MIN_HEIGHT_CORRECTION
) && z
>= aircraft_middle_altitude
) {
739 /* Now, we have corrected altitude enough. */
740 ClrBit(*flags
, VAF_IN_MIN_HEIGHT_CORRECTION
);
741 } else if (HasBit(*flags
, VAF_IN_MAX_HEIGHT_CORRECTION
) && z
<= aircraft_middle_altitude
) {
742 /* Now, we have corrected altitude enough. */
743 ClrBit(*flags
, VAF_IN_MAX_HEIGHT_CORRECTION
);
750 * Find the entry point to an airport depending on direction which
751 * the airport is being approached from. Each airport can have up to
752 * four entry points for its approach system so that approaching
753 * aircraft do not fly through each other or are forced to do 180
754 * degree turns during the approach. The arrivals are grouped into
755 * four sectors dependent on the DiagDirection from which the airport
758 * @param v The vehicle that is approaching the airport
759 * @param apc The Airport Class being approached.
760 * @param rotation The rotation of the airport.
761 * @return The index of the entry point
763 static byte
AircraftGetEntryPoint(const Aircraft
*v
, const AirportFTAClass
*apc
, Direction rotation
)
768 /* In the case the station doesn't exit anymore, set target tile 0.
769 * It doesn't hurt much, aircraft will go to next order, nearest hangar
770 * or it will simply crash in next tick */
773 const Station
*st
= Station::GetIfValid(v
->targetairport
);
775 /* Make sure we don't go to INVALID_TILE if the airport has been removed. */
776 tile
= (st
->airport
.tile
!= INVALID_TILE
) ? st
->airport
.tile
: st
->xy
;
779 int delta_x
= v
->x_pos
- TileX(tile
) * TILE_SIZE
;
780 int delta_y
= v
->y_pos
- TileY(tile
) * TILE_SIZE
;
783 if (abs(delta_y
) < abs(delta_x
)) {
784 /* We are northeast or southwest of the airport */
785 dir
= delta_x
< 0 ? DIAGDIR_NE
: DIAGDIR_SW
;
787 /* We are northwest or southeast of the airport */
788 dir
= delta_y
< 0 ? DIAGDIR_NW
: DIAGDIR_SE
;
790 dir
= ChangeDiagDir(dir
, DiagDirDifference(DIAGDIR_NE
, DirToDiagDir(rotation
)));
791 return apc
->entry_points
[dir
];
795 static bool MaybeCrashAirplane(Aircraft
*v
);
798 * Controls the movement of an aircraft. This function actually moves the vehicle
799 * on the map and takes care of minor things like sound playback.
800 * @todo De-mystify the cur_speed values for helicopter rotors.
801 * @param v The vehicle that is moved. Must be the first vehicle of the chain
802 * @return Whether the position requested by the State Machine has been reached
804 static bool AircraftController(Aircraft
*v
)
808 /* NULL if station is invalid */
809 const Station
*st
= Station::GetIfValid(v
->targetairport
);
810 /* INVALID_TILE if there is no station */
811 TileIndex tile
= INVALID_TILE
;
812 Direction rotation
= DIR_N
;
813 uint size_x
= 1, size_y
= 1;
815 if (st
->airport
.tile
!= INVALID_TILE
) {
816 tile
= st
->airport
.tile
;
817 rotation
= st
->airport
.rotation
;
818 size_x
= st
->airport
.w
;
819 size_y
= st
->airport
.h
;
824 /* DUMMY if there is no station or no airport */
825 const AirportFTAClass
*afc
= tile
== INVALID_TILE
? GetAirport(AT_DUMMY
) : st
->airport
.GetFTA();
827 /* prevent going to INVALID_TILE if airport is deleted. */
828 if (st
== NULL
|| st
->airport
.tile
== INVALID_TILE
) {
829 /* Jump into our "holding pattern" state machine if possible */
830 if (v
->pos
>= afc
->nofelements
) {
831 v
->pos
= v
->previous_pos
= AircraftGetEntryPoint(v
, afc
, DIR_N
);
832 } else if (v
->targetairport
!= v
->current_order
.GetDestination()) {
833 /* If not possible, just get out of here fast */
835 UpdateAircraftCache(v
);
836 AircraftNextAirportPos_and_Order(v
);
837 /* get aircraft back on running altitude */
838 SetAircraftPosition(v
, v
->x_pos
, v
->y_pos
, GetAircraftFlightLevel(v
));
843 /* get airport moving data */
844 const AirportMovingData amd
= RotateAirportMovingData(afc
->MovingData(v
->pos
), rotation
, size_x
, size_y
);
846 int x
= TileX(tile
) * TILE_SIZE
;
847 int y
= TileY(tile
) * TILE_SIZE
;
849 /* Helicopter raise */
850 if (amd
.flag
& AMED_HELI_RAISE
) {
851 Aircraft
*u
= v
->Next()->Next();
853 /* Make sure the rotors don't rotate too fast */
854 if (u
->cur_speed
> 32) {
856 if (--u
->cur_speed
== 32) {
857 if (!PlayVehicleSound(v
, VSE_START
)) {
858 SndPlayVehicleFx(SND_18_HELICOPTER
, v
);
863 count
= UpdateAircraftSpeed(v
);
867 int z_dest
= GetAircraftBaseFlightLevel (v
);
869 /* Reached altitude? */
870 if (v
->z_pos
>= z_dest
) {
874 SetAircraftPosition(v
, v
->x_pos
, v
->y_pos
, min(v
->z_pos
+ count
, z_dest
));
880 /* Helicopter landing. */
881 if (amd
.flag
& AMED_HELI_LOWER
) {
883 /* FIXME - AircraftController -> if station no longer exists, do not land
884 * helicopter will circle until sign disappears, then go to next order
885 * what to do when it is the only order left, right now it just stays in 1 place */
887 UpdateAircraftCache(v
);
888 AircraftNextAirportPos_and_Order(v
);
892 /* Vehicle is now at the airport. */
895 /* Find altitude of landing position. */
896 int z
= GetSlopePixelZ(x
, y
) + 1 + afc
->delta_z
;
899 Vehicle
*u
= v
->Next()->Next();
901 /* Increase speed of rotors. When speed is 80, we've landed. */
902 if (u
->cur_speed
>= 80) return true;
905 count
= UpdateAircraftSpeed(v
);
908 SetAircraftPosition(v
, v
->x_pos
, v
->y_pos
, max(v
->z_pos
- count
, z
));
910 SetAircraftPosition(v
, v
->x_pos
, v
->y_pos
, min(v
->z_pos
+ count
, z
));
917 /* Get distance from destination pos to current pos. */
918 uint dist
= abs(x
+ amd
.x
- v
->x_pos
) + abs(y
+ amd
.y
- v
->y_pos
);
920 /* Need exact position? */
921 if (!(amd
.flag
& AMED_EXACTPOS
) && dist
<= (amd
.flag
& AMED_SLOWTURN
? 8U : 4U)) return true;
925 /* Change direction smoothly to final direction. */
926 DirDiff dirdiff
= DirDifference(amd
.direction
, v
->direction
);
927 /* if distance is 0, and plane points in right direction, no point in calling
928 * UpdateAircraftSpeed(). So do it only afterwards */
929 if (dirdiff
== DIRDIFF_SAME
) {
934 if (!UpdateAircraftSpeed(v
, SPEED_LIMIT_TAXI
)) return false;
936 v
->direction
= ChangeDir(v
->direction
, dirdiff
> DIRDIFF_REVERSE
? DIRDIFF_45LEFT
: DIRDIFF_45RIGHT
);
939 SetAircraftPosition(v
, v
->x_pos
, v
->y_pos
, v
->z_pos
);
943 if (amd
.flag
& AMED_BRAKE
&& v
->cur_speed
> SPEED_LIMIT_TAXI
* _settings_game
.vehicle
.plane_speed
) {
944 if (MaybeCrashAirplane(v
)) return false;
947 uint speed_limit
= SPEED_LIMIT_TAXI
;
948 bool hard_limit
= true;
950 if (amd
.flag
& AMED_NOSPDCLAMP
) speed_limit
= SPEED_LIMIT_NONE
;
951 if (amd
.flag
& AMED_HOLD
) { speed_limit
= SPEED_LIMIT_HOLD
; hard_limit
= false; }
952 if (amd
.flag
& AMED_LAND
) { speed_limit
= SPEED_LIMIT_APPROACH
; hard_limit
= false; }
953 if (amd
.flag
& AMED_BRAKE
) { speed_limit
= SPEED_LIMIT_TAXI
; hard_limit
= false; }
955 count
= UpdateAircraftSpeed(v
, speed_limit
, hard_limit
);
956 if (count
== 0) return false;
958 if (v
->turn_counter
!= 0) v
->turn_counter
--;
963 if (dist
< 4 || (amd
.flag
& AMED_LAND
)) {
964 /* move vehicle one pixel towards target */
965 gp
.set_towards (v
->x_pos
, v
->y_pos
, x
+ amd
.x
, y
+ amd
.y
);
967 /* Oilrigs must keep v->tile as st->airport.tile, since the landing pad is in a non-airport tile */
968 if (st
->airport
.type
== AT_OILRIG
) gp
.tile
= st
->airport
.tile
;
972 /* Turn. Do it slowly if in the air. */
973 Direction newdir
= GetDirectionTowards(v
, x
+ amd
.x
, y
+ amd
.y
);
974 if (newdir
== v
->direction
) {
975 v
->number_consecutive_turns
= 0;
977 gp
= GetNewVehiclePos(v
);
978 } else if (amd
.flag
& AMED_SLOWTURN
&& v
->number_consecutive_turns
< 8 && v
->subtype
== AIR_AIRCRAFT
) {
979 if (v
->turn_counter
== 0 || newdir
== v
->last_direction
) {
980 if (newdir
== v
->last_direction
) {
981 v
->number_consecutive_turns
= 0;
983 v
->number_consecutive_turns
++;
985 v
->turn_counter
= 2 * _settings_game
.vehicle
.plane_speed
;
986 v
->last_direction
= v
->direction
;
987 v
->direction
= newdir
;
991 gp
= GetNewVehiclePos(v
);
994 v
->direction
= newdir
;
996 /* When leaving a terminal an aircraft often goes to a position
997 * directly in front of it. If it would move while turning it
998 * would need an two extra turns to end up at the correct position.
999 * To make it easier just disallow all moving while turning as
1000 * long as an aircraft is on the ground. */
1001 gp
.set (v
->x_pos
, v
->y_pos
, v
->tile
);
1006 /* If vehicle is in the air, use tile coordinate 0. */
1007 if (amd
.flag
& (AMED_TAKEOFF
| AMED_SLOWTURN
| AMED_LAND
)) v
->tile
= 0;
1009 /* Adjust Z for land or takeoff? */
1012 if (amd
.flag
& AMED_TAKEOFF
) {
1013 z
= GetAircraftFlightLevel(v
, true);
1014 } else if (amd
.flag
& AMED_HOLD
) {
1015 /* Let the plane drop from normal flight altitude to holding pattern altitude */
1016 if (z
> GetAircraftHoldMaxAltitude(v
)) z
--;
1017 } else if ((amd
.flag
& AMED_SLOWTURN
) && (amd
.flag
& AMED_NOSPDCLAMP
)) {
1018 z
= GetAircraftFlightLevel(v
);
1021 if (amd
.flag
& AMED_LAND
) {
1022 if (st
->airport
.tile
== INVALID_TILE
) {
1023 /* Airport has been removed, abort the landing procedure */
1025 UpdateAircraftCache(v
);
1026 AircraftNextAirportPos_and_Order(v
);
1027 /* get aircraft back on running altitude */
1028 SetAircraftPosition(v
, gp
.xx
, gp
.yy
, GetAircraftFlightLevel(v
));
1032 int curz
= GetSlopePixelZ(x
+ amd
.x
, y
+ amd
.y
) + 1;
1034 /* We're not flying below our destination, right? */
1036 int t
= max(1U, dist
- 4);
1037 int delta
= z
- curz
;
1039 /* Only start lowering when we're sufficiently close for a 1:1 glide */
1041 z
-= CeilDiv(z
- curz
, t
);
1043 if (z
< curz
) z
= curz
;
1046 /* We've landed. Decrease speed when we're reaching end of runway. */
1047 if (amd
.flag
& AMED_BRAKE
) {
1048 int curz
= GetSlopePixelZ(x
, y
) + 1;
1052 } else if (z
< curz
) {
1058 SetAircraftPosition(v
, gp
.xx
, gp
.yy
, z
);
1059 } while (--count
!= 0);
1064 * Handle crashed aircraft \a v.
1065 * @param v Crashed aircraft.
1067 static bool HandleCrashedAircraft(Aircraft
*v
)
1069 v
->crashed_counter
+= 3;
1071 Station
*st
= GetTargetAirportIfValid(v
);
1073 /* make aircraft crash down to the ground */
1074 if (v
->crashed_counter
< 500 && st
== NULL
&& ((v
->crashed_counter
% 3) == 0) ) {
1075 int z
= GetSlopePixelZ(Clamp(v
->x_pos
, 0, MapMaxX() * TILE_SIZE
), Clamp(v
->y_pos
, 0, MapMaxY() * TILE_SIZE
));
1077 if (v
->z_pos
== z
) {
1078 v
->crashed_counter
= 500;
1083 if (v
->crashed_counter
< 650) {
1085 if (Chance16R(1, 32, r
)) {
1086 static const DirDiff delta
[] = {
1087 DIRDIFF_45LEFT
, DIRDIFF_SAME
, DIRDIFF_SAME
, DIRDIFF_45RIGHT
1090 v
->direction
= ChangeDir(v
->direction
, delta
[GB(r
, 16, 2)]);
1091 SetAircraftPosition(v
, v
->x_pos
, v
->y_pos
, v
->z_pos
);
1093 CreateEffectVehicleRel(v
,
1097 EV_EXPLOSION_SMALL
);
1099 } else if (v
->crashed_counter
>= 10000) {
1100 /* remove rubble of crashed airplane */
1102 /* clear runway-in on all airports, set by crashing plane
1103 * small airports use AIRPORT_BUSY, city airports use RUNWAY_IN_OUT_block, etc.
1104 * but they all share the same number */
1106 CLRBITS(st
->airport
.flags
, RUNWAY_IN_block
);
1107 CLRBITS(st
->airport
.flags
, RUNWAY_IN_OUT_block
); // commuter airport
1108 CLRBITS(st
->airport
.flags
, RUNWAY_IN2_block
); // intercontinental
1121 * Handle smoke of broken aircraft.
1123 * @param mode Is this the non-first call for this vehicle in this tick?
1125 static void HandleAircraftSmoke(Aircraft
*v
, bool mode
)
1127 static const struct {
1141 if (!(v
->vehstatus
& VS_AIRCRAFT_BROKEN
)) return;
1143 /* Stop smoking when landed */
1144 if (v
->cur_speed
< 10) {
1145 v
->vehstatus
&= ~VS_AIRCRAFT_BROKEN
;
1146 v
->breakdown_ctr
= 0;
1150 /* Spawn effect et most once per Tick, i.e. !mode */
1151 if (!mode
&& (v
->tick_counter
& 0x0F) == 0) {
1152 CreateEffectVehicleRel(v
,
1153 smoke_pos
[v
->direction
].x
,
1154 smoke_pos
[v
->direction
].y
,
1156 EV_BREAKDOWN_SMOKE_AIRCRAFT
1161 void HandleMissingAircraftOrders(Aircraft
*v
)
1164 * We do not have an order. This can be divided into two cases:
1165 * 1) we are heading to an invalid station. In this case we must
1166 * find another airport to go to. If there is nowhere to go,
1167 * we will destroy the aircraft as it otherwise will enter
1168 * the holding pattern for the first airport, which can cause
1169 * the plane to go into an undefined state when building an
1170 * airport with the same StationID.
1171 * 2) we are (still) heading to a (still) valid airport, then we
1172 * can continue going there. This can happen when you are
1173 * changing the aircraft's orders while in-flight or in for
1174 * example a depot. However, when we have a current order to
1175 * go to a depot, we have to keep that order so the aircraft
1178 const Station
*st
= GetTargetAirportIfValid(v
);
1180 Backup
<CompanyByte
> cur_company(_current_company
, v
->owner
, FILE_LINE
);
1181 CommandCost ret
= DoCommand(v
->tile
, v
->index
, 0, DC_EXEC
, CMD_SEND_VEHICLE_TO_DEPOT
);
1182 cur_company
.Restore();
1184 if (ret
.Failed()) CrashAirplane(v
);
1185 } else if (!v
->current_order
.IsType(OT_GOTO_DEPOT
)) {
1186 v
->current_order
.Clear();
1191 TileIndex
Aircraft::GetOrderStationLocation(StationID station
)
1193 /* Orders are changed in flight, ensure going to the right station. */
1194 if (this->state
== FLYING
) {
1195 AircraftNextAirportPos_and_Order(this);
1198 /* Aircraft do not use dest-tile */
1202 void Aircraft::MarkDirty()
1204 this->colourmap
= PAL_NONE
;
1205 this->UpdateViewport(true, false);
1206 if (this->subtype
== AIR_HELICOPTER
) {
1207 GetRotorImage(this, EIT_ON_MAP
, &this->Next()->Next()->sprite_seq
);
1212 uint
Aircraft::Crash(bool flooded
)
1214 uint pass
= Vehicle::Crash(flooded
) + 2; // pilots
1215 this->crashed_counter
= flooded
? 9000 : 0; // max 10000, disappear pretty fast when flooded
1221 * Bring the aircraft in a crashed state, create the explosion animation, and create a news item about the crash.
1222 * @param v Aircraft that crashed.
1224 static void CrashAirplane(Aircraft
*v
)
1226 CreateEffectVehicleRel(v
, 4, 4, 8, EV_EXPLOSION_LARGE
);
1228 uint pass
= v
->Crash();
1230 v
->cargo
.Truncate();
1231 v
->Next()->cargo
.Truncate();
1232 const Station
*st
= GetTargetAirportIfValid(v
);
1234 AI::NewEvent(v
->owner
, new ScriptEventVehicleCrashed(v
->index
, v
->tile
, st
== NULL
? ScriptEventVehicleCrashed::CRASH_AIRCRAFT_NO_AIRPORT
: ScriptEventVehicleCrashed::CRASH_PLANE_LANDING
));
1235 Game::NewEvent(new ScriptEventVehicleCrashed(v
->index
, v
->tile
, st
== NULL
? ScriptEventVehicleCrashed::CRASH_AIRCRAFT_NO_AIRPORT
: ScriptEventVehicleCrashed::CRASH_PLANE_LANDING
));
1237 AddNewsItem
<PlaneCrashNewsItem
> (v
->index
, st
, pass
);
1239 ModifyStationRatingAround(v
->tile
, v
->owner
, -160, 30);
1240 if (_settings_client
.sound
.disaster
) SndPlayVehicleFx(SND_12_EXPLOSION
, v
);
1244 * Decide whether aircraft \a v should crash.
1245 * @param v Aircraft to test.
1246 * @return Whether the aircraft has been crashed
1248 static bool MaybeCrashAirplane(Aircraft
*v
)
1250 if (_settings_game
.vehicle
.plane_crashes
== 0) return false;
1252 Station
*st
= Station::Get(v
->targetairport
);
1254 /* FIXME -- MaybeCrashAirplane -> increase crashing chances of very modern airplanes on smaller than AT_METROPOLITAN airports */
1255 uint32 prob
= (0x4000 << _settings_game
.vehicle
.plane_crashes
);
1256 if ((st
->airport
.GetFTA()->flags
& AirportFTAClass::SHORT_STRIP
) &&
1257 (AircraftVehInfo(v
->engine_type
)->subtype
& AIR_FAST
) &&
1258 !_cheats
.no_jetcrash
.value
) {
1264 if (GB(Random(), 0, 22) > prob
) return false;
1266 /* Crash the airplane. Remove all goods stored at the station. */
1267 for (CargoID i
= 0; i
< NUM_CARGO
; i
++) {
1268 st
->goods
[i
].rating
= 1;
1269 st
->goods
[i
].cargo
.Truncate();
1277 * Aircraft arrives at a terminal. If it is the first aircraft, throw a party.
1278 * Start loading cargo.
1279 * @param v Aircraft that arrived.
1281 static void AircraftEntersTerminal(Aircraft
*v
)
1283 if (v
->current_order
.IsType(OT_GOTO_DEPOT
)) return;
1285 Station
*st
= Station::Get(v
->targetairport
);
1286 v
->last_station_visited
= v
->targetairport
;
1288 /* Check if station was ever visited before */
1289 if (!(st
->had_vehicle_of_type
& HVOT_AIRCRAFT
)) {
1290 st
->had_vehicle_of_type
|= HVOT_AIRCRAFT
;
1291 /* show newsitem of celebrating citizens */
1292 AddNewsItem
<ArrivalNewsItem
> (STR_NEWS_FIRST_AIRCRAFT_ARRIVAL
, v
, st
);
1293 AI::NewEvent(v
->owner
, new ScriptEventStationFirstVehicle(st
->index
, v
->index
));
1294 Game::NewEvent(new ScriptEventStationFirstVehicle(st
->index
, v
->index
));
1301 * Aircraft touched down at the landing strip.
1302 * @param v Aircraft that landed.
1304 static void AircraftLandAirplane(Aircraft
*v
)
1306 v
->UpdateDeltaXY(INVALID_DIR
);
1308 if (!PlayVehicleSound(v
, VSE_TOUCHDOWN
)) {
1309 SndPlayVehicleFx(SND_17_SKID_PLANE
, v
);
1314 /** set the right pos when heading to other airports after takeoff */
1315 void AircraftNextAirportPos_and_Order(Aircraft
*v
)
1317 if (v
->current_order
.IsType(OT_GOTO_STATION
) || v
->current_order
.IsType(OT_GOTO_DEPOT
)) {
1318 v
->targetairport
= v
->current_order
.GetDestination();
1321 const Station
*st
= GetTargetAirportIfValid(v
);
1322 const AirportFTAClass
*apc
= st
== NULL
? GetAirport(AT_DUMMY
) : st
->airport
.GetFTA();
1323 Direction rotation
= st
== NULL
? DIR_N
: st
->airport
.rotation
;
1324 v
->pos
= v
->previous_pos
= AircraftGetEntryPoint(v
, apc
, rotation
);
1328 * Aircraft is about to leave the hangar.
1329 * @param v Aircraft leaving.
1330 * @param exit_dir The direction the vehicle leaves the hangar.
1331 * @note This function is called in AfterLoadGame for old savegames, so don't rely
1332 * on any data to be valid, especially don't rely on the fact that the vehicle
1333 * is actually on the ground inside a depot.
1335 void AircraftLeaveHangar(Aircraft
*v
, Direction exit_dir
)
1340 v
->direction
= exit_dir
;
1341 v
->vehstatus
&= ~VS_HIDDEN
;
1343 Vehicle
*u
= v
->Next();
1344 u
->vehstatus
&= ~VS_HIDDEN
;
1349 u
->vehstatus
&= ~VS_HIDDEN
;
1354 VehicleServiceInDepot(v
);
1355 SetAircraftPosition(v
, v
->x_pos
, v
->y_pos
, v
->z_pos
);
1356 InvalidateWindowData(WC_VEHICLE_DEPOT
, v
->tile
);
1357 SetWindowClassesDirty(WC_AIRCRAFT_LIST
);
1361 * Aircraft entirely entered the depot, update its status, orders, vehicle windows, service it, etc.
1362 * @param v Aircraft that entered a depot.
1364 static void AircraftEnterDepot (Aircraft
*v
)
1366 SetWindowClassesDirty (WC_AIRCRAFT_LIST
);
1371 Aircraft
*u
= v
->Next();
1372 u
->vehstatus
|= VS_HIDDEN
;
1375 u
->vehstatus
|= VS_HIDDEN
;
1379 SetAircraftPosition (v
, v
->x_pos
, v
->y_pos
, v
->z_pos
);
1381 VehicleEnterDepot (v
);
1384 ////////////////////////////////////////////////////////////////////////////////
1385 /////////////////// AIRCRAFT MOVEMENT SCHEME ////////////////////////////////
1386 ////////////////////////////////////////////////////////////////////////////////
1387 static void AircraftEventHandler_EnterTerminal(Aircraft
*v
, const AirportFTAClass
*apc
)
1389 AircraftEntersTerminal(v
);
1390 v
->state
= apc
->layout
[v
->pos
].heading
;
1394 * Aircraft arrived in an airport hangar.
1395 * @param v Aircraft in the hangar.
1396 * @param apc Airport description containing the hangar.
1398 static void AircraftEventHandler_EnterHangar(Aircraft
*v
, const AirportFTAClass
*apc
)
1400 AircraftEnterDepot (v
);
1401 v
->state
= apc
->layout
[v
->pos
].heading
;
1405 * Handle aircraft movement/decision making in an airport hangar.
1406 * @param v Aircraft in the hangar.
1407 * @param apc Airport description containing the hangar.
1409 static void AircraftEventHandler_InHangar(Aircraft
*v
, const AirportFTAClass
*apc
)
1411 /* if we just arrived, execute EnterHangar first */
1412 if (v
->previous_pos
!= v
->pos
) {
1413 AircraftEventHandler_EnterHangar(v
, apc
);
1417 /* if we were sent to the depot, stay there */
1418 if (v
->current_order
.IsType(OT_GOTO_DEPOT
) && (v
->vehstatus
& VS_STOPPED
)) {
1419 v
->current_order
.Clear();
1423 if (!v
->current_order
.IsType(OT_GOTO_STATION
) &&
1424 !v
->current_order
.IsType(OT_GOTO_DEPOT
))
1427 /* We are leaving a hangar, but have to go to the exact same one; re-enter */
1428 if (v
->current_order
.IsType(OT_GOTO_DEPOT
) && v
->current_order
.GetDestination() == v
->targetairport
) {
1429 AircraftEnterDepot (v
);
1433 /* if the block of the next position is busy, stay put */
1434 if (AirportHasBlock(v
, &apc
->layout
[v
->pos
], apc
)) return;
1436 /* We are already at the target airport, we need to find a terminal */
1437 if (v
->current_order
.GetDestination() == v
->targetairport
) {
1438 /* FindFreeTerminal:
1439 * 1. Find a free terminal, 2. Occupy it, 3. Set the vehicle's state to that terminal */
1440 if (v
->subtype
== AIR_HELICOPTER
) {
1441 if (!AirportFindFreeHelipad(v
, apc
)) return; // helicopter
1443 if (!AirportFindFreeTerminal(v
, apc
)) return; // airplane
1445 } else { // Else prepare for launch.
1446 /* airplane goto state takeoff, helicopter to helitakeoff */
1447 v
->state
= (v
->subtype
== AIR_HELICOPTER
) ? HELITAKEOFF
: TAKEOFF
;
1449 const Station
*st
= Station::GetByTile(v
->tile
);
1450 AircraftLeaveHangar(v
, st
->airport
.GetHangarExitDirection(v
->tile
));
1451 AirportMove(v
, apc
);
1454 /** At one of the Airport's Terminals */
1455 static void AircraftEventHandler_AtTerminal(Aircraft
*v
, const AirportFTAClass
*apc
)
1457 /* if we just arrived, execute EnterTerminal first */
1458 if (v
->previous_pos
!= v
->pos
) {
1459 AircraftEventHandler_EnterTerminal(v
, apc
);
1460 /* on an airport with helipads, a helicopter will always land there
1461 * and get serviced at the same time - setting */
1462 if (_settings_game
.order
.serviceathelipad
) {
1463 if (v
->subtype
== AIR_HELICOPTER
&& apc
->num_helipads
> 0) {
1464 /* an excerpt of ServiceAircraft, without the invisibility stuff */
1465 v
->date_of_last_service
= _date
;
1466 v
->breakdowns_since_last_service
= 0;
1467 v
->reliability
= v
->GetEngine()->reliability
;
1468 SetWindowDirty(WC_VEHICLE_DETAILS
, v
->index
);
1474 if (v
->current_order
.IsType(OT_NOTHING
)) return;
1476 /* if the block of the next position is busy, stay put */
1477 if (AirportHasBlock(v
, &apc
->layout
[v
->pos
], apc
)) return;
1479 /* airport-road is free. We either have to go to another airport, or to the hangar
1480 * ---> start moving */
1482 bool go_to_hangar
= false;
1483 switch (v
->current_order
.GetType()) {
1484 case OT_GOTO_STATION
: // ready to fly to another airport
1486 case OT_GOTO_DEPOT
: // visit hangar for servicing, sale, etc.
1487 go_to_hangar
= v
->current_order
.GetDestination() == v
->targetairport
;
1489 case OT_CONDITIONAL
:
1490 /* In case of a conditional order we just have to wait a tick
1491 * longer, so the conditional order can actually be processed;
1492 * we should not clear the order as that makes us go nowhere. */
1494 default: // orders have been deleted (no orders), goto depot and don't bother us
1495 v
->current_order
.Clear();
1496 go_to_hangar
= Station::Get(v
->targetairport
)->airport
.HasHangar();
1502 /* airplane goto state takeoff, helicopter to helitakeoff */
1503 v
->state
= (v
->subtype
== AIR_HELICOPTER
) ? HELITAKEOFF
: TAKEOFF
;
1505 AirportMove(v
, apc
);
1508 static void AircraftEventHandler_General(Aircraft
*v
, const AirportFTAClass
*apc
)
1510 error("OK, you shouldn't be here, check your Airport Scheme!");
1513 static void AircraftEventHandler_TakeOff(Aircraft
*v
, const AirportFTAClass
*apc
)
1515 PlayAircraftSound(v
); // play takeoffsound for airplanes
1516 v
->state
= STARTTAKEOFF
;
1519 static void AircraftEventHandler_StartTakeOff(Aircraft
*v
, const AirportFTAClass
*apc
)
1521 v
->state
= ENDTAKEOFF
;
1522 v
->UpdateDeltaXY(INVALID_DIR
);
1525 static void AircraftEventHandler_EndTakeOff(Aircraft
*v
, const AirportFTAClass
*apc
)
1528 /* get the next position to go to, differs per airport */
1529 AircraftNextAirportPos_and_Order(v
);
1532 static void AircraftEventHandler_HeliTakeOff(Aircraft
*v
, const AirportFTAClass
*apc
)
1535 v
->UpdateDeltaXY(INVALID_DIR
);
1537 /* get the next position to go to, differs per airport */
1538 AircraftNextAirportPos_and_Order(v
);
1540 /* Send the helicopter to a hangar if needed for replacement */
1541 if (v
->NeedsAutomaticServicing()) {
1542 Backup
<CompanyByte
> cur_company(_current_company
, v
->owner
, FILE_LINE
);
1543 DoCommand(v
->tile
, v
->index
| DEPOT_SERVICE
| DEPOT_LOCATE_HANGAR
, 0, DC_EXEC
, CMD_SEND_VEHICLE_TO_DEPOT
);
1544 cur_company
.Restore();
1548 static void AircraftEventHandler_Flying(Aircraft
*v
, const AirportFTAClass
*apc
)
1550 Station
*st
= Station::Get(v
->targetairport
);
1552 /* Runway busy, not allowed to use this airstation or closed, circle. */
1553 if (CanVehicleUseStation(v
, st
) && (st
->owner
== OWNER_NONE
|| st
->owner
== v
->owner
) && !(st
->airport
.flags
& AIRPORT_CLOSED_block
)) {
1554 /* {32,FLYING,NOTHING_block,37}, {32,LANDING,N,33}, {32,HELILANDING,N,41},
1555 * if it is an airplane, look for LANDING, for helicopter HELILANDING
1556 * it is possible to choose from multiple landing runways, so loop until a free one is found */
1557 byte landingtype
= (v
->subtype
== AIR_HELICOPTER
) ? HELILANDING
: LANDING
;
1558 const AirportFTA
*current
= apc
->layout
[v
->pos
].next
;
1559 while (current
!= NULL
) {
1560 if (current
->heading
== landingtype
) {
1561 /* save speed before, since if AirportHasBlock is false, it resets them to 0
1562 * we don't want that for plane in air
1563 * hack for speed thingie */
1564 uint16 tcur_speed
= v
->cur_speed
;
1565 uint16 tsubspeed
= v
->subspeed
;
1566 if (!AirportHasBlock(v
, current
, apc
)) {
1567 v
->state
= landingtype
; // LANDING / HELILANDING
1568 /* it's a bit dirty, but I need to set position to next position, otherwise
1569 * if there are multiple runways, plane won't know which one it took (because
1570 * they all have heading LANDING). And also occupy that block! */
1571 v
->pos
= current
->next_position
;
1572 SETBITS(st
->airport
.flags
, apc
->layout
[v
->pos
].block
);
1575 v
->cur_speed
= tcur_speed
;
1576 v
->subspeed
= tsubspeed
;
1578 current
= current
->next
;
1582 v
->pos
= apc
->layout
[v
->pos
].next_position
;
1585 static void AircraftEventHandler_Landing(Aircraft
*v
, const AirportFTAClass
*apc
)
1587 v
->state
= ENDLANDING
;
1588 AircraftLandAirplane(v
); // maybe crash airplane
1590 /* check if the aircraft needs to be replaced or renewed and send it to a hangar if needed */
1591 if (v
->NeedsAutomaticServicing()) {
1592 Backup
<CompanyByte
> cur_company(_current_company
, v
->owner
, FILE_LINE
);
1593 DoCommand(v
->tile
, v
->index
| DEPOT_SERVICE
, 0, DC_EXEC
, CMD_SEND_VEHICLE_TO_DEPOT
);
1594 cur_company
.Restore();
1598 static void AircraftEventHandler_HeliLanding(Aircraft
*v
, const AirportFTAClass
*apc
)
1600 v
->state
= HELIENDLANDING
;
1601 v
->UpdateDeltaXY(INVALID_DIR
);
1604 static void AircraftEventHandler_EndLanding(Aircraft
*v
, const AirportFTAClass
*apc
)
1606 /* next block busy, don't do a thing, just wait */
1607 if (AirportHasBlock(v
, &apc
->layout
[v
->pos
], apc
)) return;
1609 /* if going to terminal (OT_GOTO_STATION) choose one
1610 * 1. in case all terminals are busy AirportFindFreeTerminal() returns false or
1611 * 2. not going for terminal (but depot, no order),
1612 * --> get out of the way to the hangar. */
1613 if (v
->current_order
.IsType(OT_GOTO_STATION
)) {
1614 if (AirportFindFreeTerminal(v
, apc
)) return;
1620 static void AircraftEventHandler_HeliEndLanding(Aircraft
*v
, const AirportFTAClass
*apc
)
1622 /* next block busy, don't do a thing, just wait */
1623 if (AirportHasBlock(v
, &apc
->layout
[v
->pos
], apc
)) return;
1625 /* if going to helipad (OT_GOTO_STATION) choose one. If airport doesn't have helipads, choose terminal
1626 * 1. in case all terminals/helipads are busy (AirportFindFreeHelipad() returns false) or
1627 * 2. not going for terminal (but depot, no order),
1628 * --> get out of the way to the hangar IF there are terminals on the airport.
1630 * the reason behind this is that if an airport has a terminal, it also has a hangar. Airplanes
1631 * must go to a hangar. */
1632 if (v
->current_order
.IsType(OT_GOTO_STATION
)) {
1633 if (AirportFindFreeHelipad(v
, apc
)) return;
1635 v
->state
= Station::Get(v
->targetairport
)->airport
.HasHangar() ? HANGAR
: HELITAKEOFF
;
1639 * Signature of the aircraft handler function.
1640 * @param v Aircraft to handle.
1641 * @param apc Airport state machine.
1643 typedef void AircraftStateHandler(Aircraft
*v
, const AirportFTAClass
*apc
);
1644 /** Array of handler functions for each target of the aircraft. */
1645 static AircraftStateHandler
* const _aircraft_state_handlers
[] = {
1646 AircraftEventHandler_General
, // TO_ALL = 0
1647 AircraftEventHandler_InHangar
, // HANGAR = 1
1648 AircraftEventHandler_AtTerminal
, // TERM1 = 2
1649 AircraftEventHandler_AtTerminal
, // TERM2 = 3
1650 AircraftEventHandler_AtTerminal
, // TERM3 = 4
1651 AircraftEventHandler_AtTerminal
, // TERM4 = 5
1652 AircraftEventHandler_AtTerminal
, // TERM5 = 6
1653 AircraftEventHandler_AtTerminal
, // TERM6 = 7
1654 AircraftEventHandler_AtTerminal
, // HELIPAD1 = 8
1655 AircraftEventHandler_AtTerminal
, // HELIPAD2 = 9
1656 AircraftEventHandler_TakeOff
, // TAKEOFF = 10
1657 AircraftEventHandler_StartTakeOff
, // STARTTAKEOFF = 11
1658 AircraftEventHandler_EndTakeOff
, // ENDTAKEOFF = 12
1659 AircraftEventHandler_HeliTakeOff
, // HELITAKEOFF = 13
1660 AircraftEventHandler_Flying
, // FLYING = 14
1661 AircraftEventHandler_Landing
, // LANDING = 15
1662 AircraftEventHandler_EndLanding
, // ENDLANDING = 16
1663 AircraftEventHandler_HeliLanding
, // HELILANDING = 17
1664 AircraftEventHandler_HeliEndLanding
, // HELIENDLANDING = 18
1665 AircraftEventHandler_AtTerminal
, // TERM7 = 19
1666 AircraftEventHandler_AtTerminal
, // TERM8 = 20
1667 AircraftEventHandler_AtTerminal
, // HELIPAD3 = 21
1670 static void AirportClearBlock(const Aircraft
*v
, const AirportFTAClass
*apc
)
1672 /* we have left the previous block, and entered the new one. Free the previous block */
1673 if (apc
->layout
[v
->previous_pos
].block
!= apc
->layout
[v
->pos
].block
) {
1674 Station
*st
= Station::Get(v
->targetairport
);
1676 CLRBITS(st
->airport
.flags
, apc
->layout
[v
->previous_pos
].block
);
1680 static void AirportGoToNextPosition(Aircraft
*v
)
1682 /* if aircraft is not in position, wait until it is */
1683 if (!AircraftController(v
)) return;
1685 const AirportFTAClass
*apc
= Station::Get(v
->targetairport
)->airport
.GetFTA();
1687 AirportClearBlock(v
, apc
);
1688 AirportMove(v
, apc
); // move aircraft to next position
1691 /* gets pos from vehicle and next orders */
1692 static bool AirportMove(Aircraft
*v
, const AirportFTAClass
*apc
)
1694 /* error handling */
1695 if (v
->pos
>= apc
->nofelements
) {
1696 DEBUG(misc
, 0, "[Ap] position %d is not valid for current airport. Max position is %d", v
->pos
, apc
->nofelements
-1);
1697 assert(v
->pos
< apc
->nofelements
);
1700 const AirportFTA
*current
= &apc
->layout
[v
->pos
];
1701 /* we have arrived in an important state (eg terminal, hangar, etc.) */
1702 if (current
->heading
== v
->state
) {
1703 byte prev_pos
= v
->pos
; // location could be changed in state, so save it before-hand
1704 byte prev_state
= v
->state
;
1705 _aircraft_state_handlers
[v
->state
](v
, apc
);
1706 if (v
->state
!= FLYING
) v
->previous_pos
= prev_pos
;
1707 if (v
->state
!= prev_state
|| v
->pos
!= prev_pos
) UpdateAircraftCache(v
);
1711 v
->previous_pos
= v
->pos
; // save previous location
1713 /* there is only one choice to move to */
1714 if (current
->next
== NULL
) {
1715 if (AirportSetBlocks(v
, current
, apc
)) {
1716 v
->pos
= current
->next_position
;
1717 UpdateAircraftCache(v
);
1718 } // move to next position
1722 /* there are more choices to choose from, choose the one that
1723 * matches our heading */
1725 if (v
->state
== current
->heading
|| current
->heading
== TO_ALL
) {
1726 if (AirportSetBlocks(v
, current
, apc
)) {
1727 v
->pos
= current
->next_position
;
1728 UpdateAircraftCache(v
);
1729 } // move to next position
1732 current
= current
->next
;
1733 } while (current
!= NULL
);
1735 DEBUG(misc
, 0, "[Ap] cannot move further on Airport! (pos %d state %d) for vehicle %d", v
->pos
, v
->state
, v
->index
);
1739 /** returns true if the road ahead is busy, eg. you must wait before proceeding. */
1740 static bool AirportHasBlock(Aircraft
*v
, const AirportFTA
*current_pos
, const AirportFTAClass
*apc
)
1742 const AirportFTA
*reference
= &apc
->layout
[v
->pos
];
1743 const AirportFTA
*next
= &apc
->layout
[current_pos
->next_position
];
1745 /* same block, then of course we can move */
1746 if (apc
->layout
[current_pos
->position
].block
!= next
->block
) {
1747 const Station
*st
= Station::Get(v
->targetairport
);
1748 uint64 airport_flags
= next
->block
;
1750 /* check additional possible extra blocks */
1751 if (current_pos
!= reference
&& current_pos
->block
!= NOTHING_block
) {
1752 airport_flags
|= current_pos
->block
;
1755 if (st
->airport
.flags
& airport_flags
) {
1765 * "reserve" a block for the plane
1766 * @param v airplane that requires the operation
1767 * @param current_pos of the vehicle in the list of blocks
1768 * @param apc airport on which block is requsted to be set
1769 * @returns true on success. Eg, next block was free and we have occupied it
1771 static bool AirportSetBlocks(Aircraft
*v
, const AirportFTA
*current_pos
, const AirportFTAClass
*apc
)
1773 const AirportFTA
*next
= &apc
->layout
[current_pos
->next_position
];
1774 const AirportFTA
*reference
= &apc
->layout
[v
->pos
];
1776 /* if the next position is in another block, check it and wait until it is free */
1777 if ((apc
->layout
[current_pos
->position
].block
& next
->block
) != next
->block
) {
1778 uint64 airport_flags
= next
->block
;
1779 /* search for all all elements in the list with the same state, and blocks != N
1780 * this means more blocks should be checked/set */
1781 const AirportFTA
*current
= current_pos
;
1782 if (current
== reference
) current
= current
->next
;
1783 while (current
!= NULL
) {
1784 if (current
->heading
== current_pos
->heading
&& current
->block
!= 0) {
1785 airport_flags
|= current
->block
;
1788 current
= current
->next
;
1791 /* if the block to be checked is in the next position, then exclude that from
1792 * checking, because it has been set by the airplane before */
1793 if (current_pos
->block
== next
->block
) airport_flags
^= next
->block
;
1795 Station
*st
= Station::Get(v
->targetairport
);
1796 if (st
->airport
.flags
& airport_flags
) {
1802 if (next
->block
!= NOTHING_block
) {
1803 SETBITS(st
->airport
.flags
, airport_flags
); // occupy next block
1810 * Combination of aircraft state for going to a certain terminal and the
1811 * airport flag for that terminal block.
1813 struct MovementTerminalMapping
{
1814 AirportMovementStates state
; ///< Aircraft movement state when going to this terminal.
1815 uint64 airport_flag
; ///< Bitmask in the airport flags that need to be free for this terminal.
1818 /** A list of all valid terminals and their associated blocks. */
1819 static const MovementTerminalMapping _airport_terminal_mapping
[] = {
1820 {TERM1
, TERM1_block
},
1821 {TERM2
, TERM2_block
},
1822 {TERM3
, TERM3_block
},
1823 {TERM4
, TERM4_block
},
1824 {TERM5
, TERM5_block
},
1825 {TERM6
, TERM6_block
},
1826 {TERM7
, TERM7_block
},
1827 {TERM8
, TERM8_block
},
1828 {HELIPAD1
, HELIPAD1_block
},
1829 {HELIPAD2
, HELIPAD2_block
},
1830 {HELIPAD3
, HELIPAD3_block
},
1834 * Find a free terminal or helipad, and if available, assign it.
1835 * @param v Aircraft looking for a free terminal or helipad.
1836 * @param i First terminal to examine.
1837 * @param last_terminal Terminal number to stop examining.
1838 * @return A terminal or helipad has been found, and has been assigned to the aircraft.
1840 static bool FreeTerminal(Aircraft
*v
, byte i
, byte last_terminal
)
1842 assert(last_terminal
<= lengthof(_airport_terminal_mapping
));
1843 Station
*st
= Station::Get(v
->targetairport
);
1844 for (; i
< last_terminal
; i
++) {
1845 if ((st
->airport
.flags
& _airport_terminal_mapping
[i
].airport_flag
) == 0) {
1846 /* TERMINAL# HELIPAD# */
1847 v
->state
= _airport_terminal_mapping
[i
].state
; // start moving to that terminal/helipad
1848 SETBITS(st
->airport
.flags
, _airport_terminal_mapping
[i
].airport_flag
); // occupy terminal/helipad
1856 * Get the number of terminals at the airport.
1857 * @param afc Airport description.
1858 * @return Number of terminals.
1860 static uint
GetNumTerminals(const AirportFTAClass
*apc
)
1864 for (uint i
= apc
->terminals
[0]; i
> 0; i
--) num
+= apc
->terminals
[i
];
1870 * Find a free terminal, and assign it if available.
1871 * @param v Aircraft to handle.
1872 * @param apc Airport state machine.
1873 * @return Found a free terminal and assigned it.
1875 static bool AirportFindFreeTerminal(Aircraft
*v
, const AirportFTAClass
*apc
)
1877 /* example of more terminalgroups
1878 * {0,HANGAR,NOTHING_block,1}, {0,255,TERM_GROUP1_block,0}, {0,255,TERM_GROUP2_ENTER_block,1}, {0,0,N,1},
1879 * Heading 255 denotes a group. We see 2 groups here:
1880 * 1. group 0 -- TERM_GROUP1_block (check block)
1881 * 2. group 1 -- TERM_GROUP2_ENTER_block (check block)
1882 * First in line is checked first, group 0. If the block (TERM_GROUP1_block) is free, it
1883 * looks at the corresponding terminals of that group. If no free ones are found, other
1884 * possible groups are checked (in this case group 1, since that is after group 0). If that
1885 * fails, then attempt fails and plane waits
1887 if (apc
->terminals
[0] > 1) {
1888 const Station
*st
= Station::Get(v
->targetairport
);
1889 const AirportFTA
*temp
= apc
->layout
[v
->pos
].next
;
1891 while (temp
!= NULL
) {
1892 if (temp
->heading
== 255) {
1893 if (!(st
->airport
.flags
& temp
->block
)) {
1894 /* read which group do we want to go to?
1895 * (the first free group) */
1896 uint target_group
= temp
->next_position
+ 1;
1898 /* at what terminal does the group start?
1899 * that means, sum up all terminals of
1900 * groups with lower number */
1901 uint group_start
= 0;
1902 for (uint i
= 1; i
< target_group
; i
++) {
1903 group_start
+= apc
->terminals
[i
];
1906 uint group_end
= group_start
+ apc
->terminals
[target_group
];
1907 if (FreeTerminal(v
, group_start
, group_end
)) return true;
1910 /* once the heading isn't 255, we've exhausted the possible blocks.
1911 * So we cannot move */
1918 /* if there is only 1 terminalgroup, all terminals are checked (starting from 0 to max) */
1919 return FreeTerminal(v
, 0, GetNumTerminals(apc
));
1923 * Find a free helipad, and assign it if available.
1924 * @param v Aircraft to handle.
1925 * @param apc Airport state machine.
1926 * @return Found a free helipad and assigned it.
1928 static bool AirportFindFreeHelipad(Aircraft
*v
, const AirportFTAClass
*apc
)
1930 /* if an airport doesn't have helipads, use terminals */
1931 if (apc
->num_helipads
== 0) return AirportFindFreeTerminal(v
, apc
);
1933 /* only 1 helicoptergroup, check all helipads
1934 * The blocks for helipads start after the last terminal (MAX_TERMINALS) */
1935 return FreeTerminal(v
, MAX_TERMINALS
, apc
->num_helipads
+ MAX_TERMINALS
);
1939 * Handle the 'dest too far' flag and the corresponding news message for aircraft.
1940 * @param v The aircraft.
1941 * @param too_far True if the current destination is too far away.
1943 static void AircraftHandleDestTooFar(Aircraft
*v
, bool too_far
)
1946 if (!HasBit(v
->flags
, VAF_DEST_TOO_FAR
)) {
1947 SetBit(v
->flags
, VAF_DEST_TOO_FAR
);
1948 SetWindowWidgetDirty(WC_VEHICLE_VIEW
, v
->index
, WID_VV_START_STOP
);
1949 AI::NewEvent(v
->owner
, new ScriptEventAircraftDestTooFar(v
->index
));
1950 if (v
->owner
== _local_company
) {
1951 /* Post a news message. */
1952 AddNewsItem
<VehicleAdviceNewsItem
> (STR_NEWS_AIRCRAFT_DEST_TOO_FAR
, v
->index
);
1958 if (HasBit(v
->flags
, VAF_DEST_TOO_FAR
)) {
1959 /* Not too far anymore, clear flag and message. */
1960 ClrBit(v
->flags
, VAF_DEST_TOO_FAR
);
1961 SetWindowWidgetDirty(WC_VEHICLE_VIEW
, v
->index
, WID_VV_START_STOP
);
1962 DeleteVehicleNews(v
->index
, STR_NEWS_AIRCRAFT_DEST_TOO_FAR
);
1966 static bool AircraftEventHandler(Aircraft
*v
, int loop
)
1968 if (v
->vehstatus
& VS_CRASHED
) {
1969 return HandleCrashedAircraft(v
);
1972 if (v
->vehstatus
& VS_STOPPED
) return true;
1974 v
->HandleBreakdown();
1976 HandleAircraftSmoke(v
, loop
!= 0);
1978 v
->HandleLoading(loop
!= 0);
1980 if (v
->current_order
.IsType(OT_LOADING
) || v
->current_order
.IsType(OT_LEAVESTATION
)) return true;
1982 if (v
->state
>= ENDTAKEOFF
&& v
->state
<= HELIENDLANDING
) {
1983 /* If we are flying, unconditionally clear the 'dest too far' state. */
1984 AircraftHandleDestTooFar(v
, false);
1985 } else if (v
->acache
.cached_max_range_sqr
!= 0) {
1986 /* Check the distance to the next destination. This code works because the target
1987 * airport is only updated after take off and not on the ground. */
1988 Station
*cur_st
= Station::GetIfValid(v
->targetairport
);
1989 Station
*next_st
= v
->current_order
.IsType(OT_GOTO_STATION
) || v
->current_order
.IsType(OT_GOTO_DEPOT
) ? Station::GetIfValid(v
->current_order
.GetDestination()) : NULL
;
1991 if (cur_st
!= NULL
&& cur_st
->airport
.tile
!= INVALID_TILE
&& next_st
!= NULL
&& next_st
->airport
.tile
!= INVALID_TILE
) {
1992 uint dist
= DistanceSquare(cur_st
->airport
.tile
, next_st
->airport
.tile
);
1993 AircraftHandleDestTooFar(v
, dist
> v
->acache
.cached_max_range_sqr
);
1997 if (!HasBit(v
->flags
, VAF_DEST_TOO_FAR
)) AirportGoToNextPosition(v
);
2002 bool Aircraft::Tick()
2004 if (!this->IsNormalAircraft()) return true;
2006 this->tick_counter
++;
2008 if (!(this->vehstatus
& VS_STOPPED
)) this->running_ticks
++;
2010 if (this->subtype
== AIR_HELICOPTER
) HelicopterTickHandler(this);
2012 this->current_order_time
++;
2014 for (uint i
= 0; i
!= 2; i
++) {
2015 /* stop if the aircraft was deleted */
2016 if (!AircraftEventHandler(this, i
)) return false;
2024 * Returns aircraft's target station if v->target_airport
2025 * is a valid station with airport.
2026 * @param v vehicle to get target airport for
2027 * @return pointer to target station, NULL if invalid
2029 Station
*GetTargetAirportIfValid(const Aircraft
*v
)
2031 assert(v
->type
== VEH_AIRCRAFT
);
2033 Station
*st
= Station::GetIfValid(v
->targetairport
);
2034 if (st
== NULL
) return NULL
;
2036 return st
->airport
.tile
== INVALID_TILE
? NULL
: st
;
2040 * Updates the status of the Aircraft heading or in the station
2041 * @param st Station been updated
2043 void UpdateAirplanesOnNewStation(const Station
*st
)
2045 /* only 1 station is updated per function call, so it is enough to get entry_point once */
2046 const AirportFTAClass
*ap
= st
->airport
.GetFTA();
2047 Direction rotation
= st
->airport
.tile
== INVALID_TILE
? DIR_N
: st
->airport
.rotation
;
2050 FOR_ALL_AIRCRAFT(v
) {
2051 if (!v
->IsNormalAircraft() || v
->targetairport
!= st
->index
) continue;
2052 assert(v
->state
== FLYING
);
2053 v
->pos
= v
->previous_pos
= AircraftGetEntryPoint(v
, ap
, rotation
);
2054 UpdateAircraftCache(v
);