OpenTTD Source 20260107-master-g88a467db19
aircraft_cmd.cpp
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
10#include "stdafx.h"
11#include "aircraft.h"
12#include "landscape.h"
13#include "news_func.h"
14#include "newgrf_engine.h"
15#include "newgrf_sound.h"
16#include "error_func.h"
17#include "strings_func.h"
18#include "command_func.h"
19#include "window_func.h"
22#include "vehicle_func.h"
23#include "sound_func.h"
24#include "cheat_type.h"
25#include "company_base.h"
26#include "ai/ai.hpp"
27#include "game/game.hpp"
28#include "company_func.h"
29#include "effectvehicle_func.h"
30#include "station_base.h"
31#include "engine_base.h"
32#include "core/random_func.hpp"
33#include "core/backup_type.hpp"
34#include "zoom_func.h"
35#include "disaster_vehicle.h"
36#include "newgrf_airporttiles.h"
37#include "framerate_type.h"
38#include "aircraft_cmd.h"
39#include "vehicle_cmd.h"
40
41#include "table/strings.h"
42
43#include "safeguards.h"
44
46{
47 this->bounds = {{-1, -1, 0}, {2, 2, 0}, {}};
48
49 switch (this->subtype) {
50 default: NOT_REACHED();
51
52 case AIR_AIRCRAFT:
53 case AIR_HELICOPTER:
54 switch (this->state) {
55 default: break;
56 case ENDTAKEOFF:
57 case LANDING:
58 case HELILANDING:
59 case FLYING:
60 /* Bounds are not centred on the aircraft. */
61 this->bounds.extent.x = 24;
62 this->bounds.extent.y = 24;
63 break;
64 }
65 this->bounds.extent.z = 5;
66 break;
67
68 case AIR_SHADOW:
69 this->bounds.extent.z = 1;
70 this->bounds.origin = {};
71 break;
72
73 case AIR_ROTOR:
74 this->bounds.extent.z = 1;
75 break;
76 }
77}
78
79static bool AirportMove(Aircraft *v, const AirportFTAClass *apc);
80static bool AirportSetBlocks(Aircraft *v, const AirportFTA *current_pos, const AirportFTAClass *apc);
81static bool AirportHasBlock(Aircraft *v, const AirportFTA *current_pos, const AirportFTAClass *apc);
82static bool AirportFindFreeTerminal(Aircraft *v, const AirportFTAClass *apc);
83static bool AirportFindFreeHelipad(Aircraft *v, const AirportFTAClass *apc);
84static void CrashAirplane(Aircraft *v);
85
86static const SpriteID _aircraft_sprite[] = {
87 0x0EB5, 0x0EBD, 0x0EC5, 0x0ECD,
88 0x0ED5, 0x0EDD, 0x0E9D, 0x0EA5,
89 0x0EAD, 0x0EE5, 0x0F05, 0x0F0D,
90 0x0F15, 0x0F1D, 0x0F25, 0x0F2D,
91 0x0EED, 0x0EF5, 0x0EFD, 0x0F35,
92 0x0E9D, 0x0EA5, 0x0EAD, 0x0EB5,
93 0x0EBD, 0x0EC5
94};
95
96template <>
97bool IsValidImageIndex<VEH_AIRCRAFT>(uint8_t image_index)
98{
99 return image_index < lengthof(_aircraft_sprite);
100}
101
103enum HelicopterRotorStates : uint8_t {
104 HRS_ROTOR_STOPPED,
105 HRS_ROTOR_MOVING_1,
106 HRS_ROTOR_MOVING_2,
107 HRS_ROTOR_MOVING_3,
108};
109
118{
119 uint best = 0;
120 StationID index = StationID::Invalid();
121 TileIndex vtile = TileVirtXY(v->x_pos, v->y_pos);
122 const AircraftVehicleInfo *avi = AircraftVehInfo(v->engine_type);
123 uint max_range = v->acache.cached_max_range_sqr;
124
125 /* Determine destinations where it's coming from and where it's heading to */
126 const Station *last_dest = nullptr;
127 const Station *next_dest = nullptr;
128 if (max_range != 0) {
129 if (v->current_order.IsType(OT_GOTO_STATION) ||
132 next_dest = Station::GetIfValid(v->current_order.GetDestination().ToStationID());
133 } else {
134 last_dest = GetTargetAirportIfValid(v);
135 std::vector<StationID> next_station;
136 v->GetNextStoppingStation(next_station);
137 if (!next_station.empty()) next_dest = Station::GetIfValid(next_station.back());
138 }
139 }
140
141 for (const Station *st : Station::Iterate()) {
142 if (st->owner != v->owner || !st->facilities.Test(StationFacility::Airport) || !st->airport.HasHangar()) continue;
143
144 const AirportFTAClass *afc = st->airport.GetFTA();
145
146 /* don't crash the plane if we know it can't land at the airport */
147 if (afc->flags.Test(AirportFTAClass::Flag::ShortStrip) && (avi->subtype & AIR_FAST) && !_cheats.no_jetcrash.value) continue;
148
149 /* the plane won't land at any helicopter station */
150 if (!afc->flags.Test(AirportFTAClass::Flag::Airplanes) && (avi->subtype & AIR_CTOL)) continue;
151
152 /* Check if our last and next destinations can be reached from the depot airport. */
153 if (max_range != 0) {
154 uint last_dist = (last_dest != nullptr && last_dest->airport.tile != INVALID_TILE) ? DistanceSquare(st->airport.tile, last_dest->airport.tile) : 0;
155 uint next_dist = (next_dest != nullptr && next_dest->airport.tile != INVALID_TILE) ? DistanceSquare(st->airport.tile, next_dest->airport.tile) : 0;
156 if (last_dist > max_range || next_dist > max_range) continue;
157 }
158
159 /* v->tile can't be used here, when aircraft is flying v->tile is set to 0 */
160 uint distance = DistanceSquare(vtile, st->airport.tile);
161 if (distance < best || index == StationID::Invalid()) {
162 best = distance;
163 index = st->index;
164 }
165 }
166 return index;
167}
168
169void Aircraft::GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const
170{
171 uint8_t spritenum = this->spritenum;
172
173 if (IsCustomVehicleSpriteNum(spritenum)) {
174 GetCustomVehicleSprite(this, direction, image_type, result);
175 if (result->IsValid()) return;
176
178 }
179
180 assert(IsValidImageIndex<VEH_AIRCRAFT>(spritenum));
181 result->Set(direction + _aircraft_sprite[spritenum]);
182}
183
184void GetRotorImage(const Aircraft *v, EngineImageType image_type, VehicleSpriteSeq *result)
185{
186 assert(v->subtype == AIR_HELICOPTER);
187
188 const Aircraft *w = v->Next()->Next();
189 if (IsCustomVehicleSpriteNum(v->spritenum)) {
190 GetCustomRotorSprite(v, image_type, result);
191 if (result->IsValid()) return;
192 }
193
194 /* Return standard rotor sprites if there are no custom sprites for this helicopter */
195 result->Set(SPR_ROTOR_STOPPED + w->state);
196}
197
198static void GetAircraftIcon(EngineID engine, EngineImageType image_type, VehicleSpriteSeq *result)
199{
200 const Engine *e = Engine::Get(engine);
201 uint8_t spritenum = e->VehInfo<AircraftVehicleInfo>().image_index;
202
203 if (IsCustomVehicleSpriteNum(spritenum)) {
204 GetCustomVehicleIcon(engine, DIR_W, image_type, result);
205 if (result->IsValid()) return;
206
207 spritenum = e->original_image_index;
208 }
209
210 assert(IsValidImageIndex<VEH_AIRCRAFT>(spritenum));
211 result->Set(DIR_W + _aircraft_sprite[spritenum]);
212}
213
214void DrawAircraftEngine(int left, int right, int preferred_x, int y, EngineID engine, PaletteID pal, EngineImageType image_type)
215{
217 GetAircraftIcon(engine, image_type, &seq);
218
219 Rect rect;
220 seq.GetBounds(&rect);
221 preferred_x = Clamp(preferred_x,
222 left - UnScaleGUI(rect.left),
223 right - UnScaleGUI(rect.right));
224
225 seq.Draw(preferred_x, y, pal, pal == PALETTE_CRASH);
226
227 if (!(AircraftVehInfo(engine)->subtype & AIR_CTOL)) {
228 VehicleSpriteSeq rotor_seq;
229 GetCustomRotorIcon(engine, image_type, &rotor_seq);
230 if (!rotor_seq.IsValid()) rotor_seq.Set(SPR_ROTOR_STOPPED);
231 rotor_seq.Draw(preferred_x, y - ScaleSpriteTrad(5), PAL_NONE, false);
232 }
233}
234
244void GetAircraftSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type)
245{
247 GetAircraftIcon(engine, image_type, &seq);
248
249 Rect rect;
250 seq.GetBounds(&rect);
251
252 width = UnScaleGUI(rect.Width());
253 height = UnScaleGUI(rect.Height());
254 xoffs = UnScaleGUI(rect.left);
255 yoffs = UnScaleGUI(rect.top);
256}
257
267{
268 const AircraftVehicleInfo *avi = &e->VehInfo<AircraftVehicleInfo>();
269 const Station *st = Station::GetByTile(tile);
270
271 /* Prevent building aircraft types at places which can't handle them */
272 if (!CanVehicleUseStation(e->index, st)) return CMD_ERROR;
273
274 /* Make sure all aircraft end up in the first tile of the hangar. */
275 tile = st->airport.GetHangarTile(st->airport.GetHangarNum(tile));
276
277 if (flags.Test(DoCommandFlag::Execute)) {
278 Aircraft *v = Aircraft::Create(); // aircraft
279 Aircraft *u = Aircraft::Create(); // shadow
280 *ret = v;
281
282 v->direction = DIR_SE;
283
284 v->owner = u->owner = _current_company;
285
286 v->tile = tile;
287
288 uint x = TileX(tile) * TILE_SIZE + 5;
289 uint y = TileY(tile) * TILE_SIZE + 3;
290
291 v->x_pos = u->x_pos = x;
292 v->y_pos = u->y_pos = y;
293
294 u->z_pos = GetSlopePixelZ(x, y);
295 v->z_pos = u->z_pos + 1;
296
299
300 v->spritenum = avi->image_index;
301
303 v->refit_cap = 0;
304 u->refit_cap = 0;
305
307 assert(IsValidCargoType(v->cargo_type));
308
309 CargoType mail = GetCargoTypeByLabel(CT_MAIL);
310 if (IsValidCargoType(mail)) {
311 u->cargo_type = mail;
312 u->cargo_cap = avi->mail_capacity;
313 }
314
315 v->name.clear();
316 v->last_station_visited = StationID::Invalid();
317 v->last_loading_station = StationID::Invalid();
318
319 v->acceleration = avi->acceleration;
320 v->engine_type = e->index;
321 u->engine_type = e->index;
322
324 v->UpdateDeltaXY();
325
326 u->subtype = AIR_SHADOW;
327 u->UpdateDeltaXY();
328
329 v->reliability = e->reliability;
332
333 v->pos = GetVehiclePosOnBuild(tile);
334
335 v->state = HANGAR;
336 v->previous_pos = v->pos;
338 v->SetNext(u);
339
340 v->SetServiceInterval(Company::Get(_current_company)->settings.vehicle.servint_aircraft);
341
345
346 v->sprite_cache.sprite_seq.Set(SPR_IMG_QUERY);
347 u->sprite_cache.sprite_seq.Set(SPR_IMG_QUERY);
348
349 v->random_bits = Random();
350 u->random_bits = Random();
351
352 v->vehicle_flags = {};
354 v->SetServiceIntervalIsPercent(Company::Get(_current_company)->settings.vehicle.servint_ispercent);
355
357
358 v->cargo_cap = e->DetermineCapacity(v, &u->cargo_cap);
359
361
362 UpdateAircraftCache(v, true);
363
364 v->UpdatePosition();
365 u->UpdatePosition();
366
367 /* Aircraft with 3 vehicles (chopper)? */
368 if (v->subtype == AIR_HELICOPTER) {
370 w->engine_type = e->index;
371 w->direction = DIR_N;
373 w->x_pos = v->x_pos;
374 w->y_pos = v->y_pos;
375 w->z_pos = v->z_pos + ROTOR_Z_OFFSET;
377 w->spritenum = 0xFF;
378 w->subtype = AIR_ROTOR;
379 w->sprite_cache.sprite_seq.Set(SPR_ROTOR_STOPPED);
380 w->random_bits = Random();
381 /* Use rotor's air.state to store the rotor animation frame */
382 w->state = HRS_ROTOR_STOPPED;
383 w->UpdateDeltaXY();
384
385 u->SetNext(w);
386 w->UpdatePosition();
387 }
388 }
389
390 return CommandCost();
391}
392
393
395{
396 const Station *st = GetTargetAirportIfValid(this);
397 /* If the station is not a valid airport or if it has no hangars */
398 if (st == nullptr || !CanVehicleUseStation(this, st) || !st->airport.HasHangar()) {
399 /* the aircraft has to search for a hangar on its own */
400 StationID station = FindNearestHangar(this);
401
402 if (station == StationID::Invalid()) return ClosestDepot();
403
404 st = Station::Get(station);
405 }
406
407 return ClosestDepot(st->xy, st->index);
408}
409
410static void CheckIfAircraftNeedsService(Aircraft *v)
411{
412 if (Company::Get(v->owner)->settings.vehicle.servint_aircraft == 0 || !v->NeedsAutomaticServicing()) return;
413 if (v->IsChainInDepot()) {
415 return;
416 }
417
418 /* When we're parsing conditional orders and the like
419 * we don't want to consider going to a depot too. */
420 if (!v->current_order.IsType(OT_GOTO_DEPOT) && !v->current_order.IsType(OT_GOTO_STATION)) return;
421
422 const Station *st = Station::Get(v->current_order.GetDestination().ToStationID());
423
424 assert(st != nullptr);
425
426 /* only goto depot if the target airport has a depot */
427 if (st->airport.HasHangar() && CanVehicleUseStation(v, st)) {
430 } else if (v->current_order.IsType(OT_GOTO_DEPOT)) {
433 }
434}
435
437{
438 const Engine *e = this->GetEngine();
439 uint cost_factor = GetVehicleProperty(this, PROP_AIRCRAFT_RUNNING_COST_FACTOR, e->VehInfo<AircraftVehicleInfo>().running_cost);
440 return GetPrice(PR_RUNNING_AIRCRAFT, cost_factor, e->GetGRF());
441}
442
445{
446 if (!this->IsNormalAircraft()) return;
447 AgeVehicle(this);
448}
449
452{
453 if (!this->IsNormalAircraft()) return;
454 EconomyAgeVehicle(this);
455
456 if ((++this->day_counter & 7) == 0) DecreaseVehicleValue(this);
457
458 CheckOrders(this);
459
460 CheckVehicleBreakdown(this);
461 CheckIfAircraftNeedsService(this);
462
463 if (this->running_ticks == 0) return;
464
466
467 this->profit_this_year -= cost.GetCost();
468 this->running_ticks = 0;
469
471
474}
475
476static void HelicopterTickHandler(Aircraft *v)
477{
478 Aircraft *u = v->Next()->Next();
479
480 if (u->vehstatus.Test(VehState::Hidden)) return;
481
482 /* if true, helicopter rotors do not rotate. This should only be the case if a helicopter is
483 * loading/unloading at a terminal or stopped */
484 if (v->current_order.IsType(OT_LOADING) || v->vehstatus.Test(VehState::Stopped)) {
485 if (u->cur_speed != 0) {
486 u->cur_speed++;
487 if (u->cur_speed >= 0x80 && u->state == HRS_ROTOR_MOVING_3) {
488 u->cur_speed = 0;
489 }
490 }
491 } else {
492 if (u->cur_speed == 0) {
493 u->cur_speed = 0x70;
494 }
495 if (u->cur_speed >= 0x50) {
496 u->cur_speed--;
497 }
498 }
499
500 int tick = ++u->tick_counter;
501 int spd = u->cur_speed >> 4;
502
504 if (spd == 0) {
505 u->state = HRS_ROTOR_STOPPED;
506 GetRotorImage(v, EIT_ON_MAP, &seq);
507 if (u->sprite_cache.sprite_seq == seq) return;
508 } else if (tick >= spd) {
509 u->tick_counter = 0;
510 u->state++;
511 if (u->state > HRS_ROTOR_MOVING_3) u->state = HRS_ROTOR_MOVING_1;
512 GetRotorImage(v, EIT_ON_MAP, &seq);
513 } else {
514 return;
515 }
516
517 u->sprite_cache.sprite_seq = seq;
518
520}
521
529void SetAircraftPosition(Aircraft *v, int x, int y, int z)
530{
531 v->x_pos = x;
532 v->y_pos = y;
533 v->z_pos = z;
534
535 v->UpdatePosition();
536 v->UpdateViewport(true, false);
537 if (v->subtype == AIR_HELICOPTER) {
538 GetRotorImage(v, EIT_ON_MAP, &v->Next()->Next()->sprite_cache.sprite_seq);
539 }
540
541 Aircraft *u = v->Next();
542
543 int safe_x = Clamp(x, 0, Map::MaxX() * TILE_SIZE);
544 int safe_y = Clamp(y - 1, 0, Map::MaxY() * TILE_SIZE);
545 u->x_pos = x;
546 u->y_pos = y - ((v->z_pos - GetSlopePixelZ(safe_x, safe_y)) >> 3);
547
548 safe_y = Clamp(u->y_pos, 0, Map::MaxY() * TILE_SIZE);
549 u->z_pos = GetSlopePixelZ(safe_x, safe_y);
550 u->sprite_cache.sprite_seq.CopyWithoutPalette(v->sprite_cache.sprite_seq); // the shadow is never coloured
551
553
554 u = u->Next();
555 if (u != nullptr) {
556 u->x_pos = x;
557 u->y_pos = y;
558 u->z_pos = z + ROTOR_Z_OFFSET;
559
561 }
562}
563
569{
570 v->subspeed = 0;
571 v->progress = 0;
572
573 Aircraft *u = v->Next();
575 u = u->Next();
576 if (u != nullptr) {
578 u->cur_speed = 0;
579 }
580
581 SetAircraftPosition(v, v->x_pos, v->y_pos, v->z_pos);
582}
583
584static void PlayAircraftSound(const Vehicle *v)
585{
586 if (!PlayVehicleSound(v, VSE_START)) {
587 SndPlayVehicleFx(AircraftVehInfo(v->engine_type)->sfx, v);
588 }
589}
590
591
598void UpdateAircraftCache(Aircraft *v, bool update_range)
599{
600 uint max_speed = GetVehicleProperty(v, PROP_AIRCRAFT_SPEED, 0);
601 if (max_speed != 0) {
602 /* Convert from original units to km-ish/h */
603 max_speed = (max_speed * 128) / 10;
604
605 v->vcache.cached_max_speed = max_speed;
606 } else {
607 /* Use the default max speed of the vehicle. */
608 v->vcache.cached_max_speed = AircraftVehInfo(v->engine_type)->max_speed;
609 }
610
611 /* Update cargo aging period. */
613 Aircraft *u = v->Next(); // Shadow for mail
615
616 /* Update aircraft range. */
617 if (update_range) {
618 v->acache.cached_max_range = GetVehicleProperty(v, PROP_AIRCRAFT_RANGE, AircraftVehInfo(v->engine_type)->max_range);
619 /* Squared it now so we don't have to do it later all the time. */
620 v->acache.cached_max_range_sqr = v->acache.cached_max_range * v->acache.cached_max_range;
621 }
622}
623
624
628static constexpr uint16_t SPEED_LIMIT_TAXI = 50;
629static constexpr uint16_t SPEED_LIMIT_APPROACH = 230;
630static constexpr uint16_t SPEED_LIMIT_BROKEN = 320;
631static constexpr uint16_t SPEED_LIMIT_HOLD = 425;
632static constexpr uint16_t SPEED_LIMIT_NONE = UINT16_MAX;
633
641static int UpdateAircraftSpeed(Aircraft *v, uint speed_limit = SPEED_LIMIT_NONE, bool hard_limit = true)
642{
650 uint spd = v->acceleration * 77;
651 uint8_t t;
652
653 /* Adjust speed limits by plane speed factor to prevent taxiing
654 * and take-off speeds being too low. */
655 speed_limit *= _settings_game.vehicle.plane_speed;
656
657 /* adjust speed for broken vehicles */
659 if (SPEED_LIMIT_BROKEN < speed_limit) hard_limit = false;
660 speed_limit = std::min<uint>(speed_limit, SPEED_LIMIT_BROKEN);
661 }
662
663 if (v->vcache.cached_max_speed < speed_limit) {
664 if (v->cur_speed < speed_limit) hard_limit = false;
665 speed_limit = v->vcache.cached_max_speed;
666 }
667
668 v->subspeed = (t = v->subspeed) + (uint8_t)spd;
669
670 /* Aircraft's current speed is used twice so that very fast planes are
671 * forced to slow down rapidly in the short distance needed. The magic
672 * value 16384 was determined to give similar results to the old speed/48
673 * method at slower speeds. This also results in less reduction at slow
674 * speeds to that aircraft do not get to taxi speed straight after
675 * touchdown. */
676 if (!hard_limit && v->cur_speed > speed_limit) {
677 speed_limit = v->cur_speed - std::max(1, ((v->cur_speed * v->cur_speed) / 16384) / _settings_game.vehicle.plane_speed);
678 }
679
680 spd = std::min(v->cur_speed + (spd >> 8) + (v->subspeed < t), speed_limit);
681
682 /* updates statusbar only if speed have changed to save CPU time */
683 if (spd != v->cur_speed) {
684 v->cur_speed = spd;
686 }
687
688 /* Adjust distance moved by plane speed setting */
690
691 /* Convert direction-independent speed into direction-dependent speed. (old movement method) */
692 spd = v->GetOldAdvanceSpeed(spd);
693
694 spd += v->progress;
695 v->progress = (uint8_t)spd;
696 return spd >> 8;
697}
698
707{
708 int safe_x = Clamp(v->x_pos, 0, Map::MaxX() * TILE_SIZE);
709 int safe_y = Clamp(v->y_pos, 0, Map::MaxY() * TILE_SIZE);
710 return TileHeight(TileVirtXY(safe_x, safe_y)) * TILE_HEIGHT;
711}
712
723void GetAircraftFlightLevelBounds(const Vehicle *v, int *min_level, int *max_level)
724{
725 int base_altitude = GetTileHeightBelowAircraft(v);
728 }
729
730 /* Make sure eastbound and westbound planes do not "crash" into each
731 * other by providing them with vertical separation
732 */
733 switch (v->direction) {
734 case DIR_N:
735 case DIR_NE:
736 case DIR_E:
737 case DIR_SE:
738 base_altitude += 10;
739 break;
740
741 default: break;
742 }
743
744 /* Make faster planes fly higher so that they can overtake slower ones */
745 base_altitude += std::min(20 * (v->vcache.cached_max_speed / 200) - 90, 0);
746
747 if (min_level != nullptr) *min_level = base_altitude + AIRCRAFT_MIN_FLYING_ALTITUDE;
748 if (max_level != nullptr) *max_level = base_altitude + AIRCRAFT_MAX_FLYING_ALTITUDE;
749}
750
759{
760 int tile_height = GetTileHeightBelowAircraft(v);
761
763}
764
765template <class T>
766int GetAircraftFlightLevel(T *v, bool takeoff)
767{
768 /* Aircraft is in flight. We want to enforce it being somewhere
769 * between the minimum and the maximum allowed altitude. */
770 int aircraft_min_altitude;
771 int aircraft_max_altitude;
772 GetAircraftFlightLevelBounds(v, &aircraft_min_altitude, &aircraft_max_altitude);
773 int aircraft_middle_altitude = (aircraft_min_altitude + aircraft_max_altitude) / 2;
774
775 /* If those assumptions would be violated, aircraft would behave fairly strange. */
776 assert(aircraft_min_altitude < aircraft_middle_altitude);
777 assert(aircraft_middle_altitude < aircraft_max_altitude);
778
779 int z = v->z_pos;
780 if (z < aircraft_min_altitude ||
781 (HasBit(v->flags, VAF_IN_MIN_HEIGHT_CORRECTION) && z < aircraft_middle_altitude)) {
782 /* Ascend. And don't fly into that mountain right ahead.
783 * And avoid our aircraft become a stairclimber, so if we start
784 * correcting altitude, then we stop correction not too early. */
786 z += takeoff ? 2 : 1;
787 } else if (!takeoff && (z > aircraft_max_altitude ||
788 (HasBit(v->flags, VAF_IN_MAX_HEIGHT_CORRECTION) && z > aircraft_middle_altitude))) {
789 /* Descend lower. You are an aircraft, not an space ship.
790 * And again, don't stop correcting altitude too early. */
792 z--;
793 } else if (HasBit(v->flags, VAF_IN_MIN_HEIGHT_CORRECTION) && z >= aircraft_middle_altitude) {
794 /* Now, we have corrected altitude enough. */
796 } else if (HasBit(v->flags, VAF_IN_MAX_HEIGHT_CORRECTION) && z <= aircraft_middle_altitude) {
797 /* Now, we have corrected altitude enough. */
799 }
800
801 return z;
802}
803
804template int GetAircraftFlightLevel(DisasterVehicle *v, bool takeoff);
805template int GetAircraftFlightLevel(Aircraft *v, bool takeoff);
806
821static uint8_t AircraftGetEntryPoint(const Aircraft *v, const AirportFTAClass *apc, Direction rotation)
822{
823 assert(v != nullptr);
824 assert(apc != nullptr);
825
826 /* In the case the station doesn't exit anymore, set target tile 0.
827 * It doesn't hurt much, aircraft will go to next order, nearest hangar
828 * or it will simply crash in next tick */
829 TileIndex tile{};
830
832 if (st != nullptr) {
833 /* Make sure we don't go to INVALID_TILE if the airport has been removed. */
834 tile = (st->airport.tile != INVALID_TILE) ? st->airport.tile : st->xy;
835 }
836
837 int delta_x = v->x_pos - TileX(tile) * TILE_SIZE;
838 int delta_y = v->y_pos - TileY(tile) * TILE_SIZE;
839
840 DiagDirection dir;
841 if (abs(delta_y) < abs(delta_x)) {
842 /* We are northeast or southwest of the airport */
843 dir = delta_x < 0 ? DIAGDIR_NE : DIAGDIR_SW;
844 } else {
845 /* We are northwest or southeast of the airport */
846 dir = delta_y < 0 ? DIAGDIR_NW : DIAGDIR_SE;
847 }
849 return apc->entry_points[dir];
850}
851
852
853static void MaybeCrashAirplane(Aircraft *v);
854
863{
864 /* nullptr if station is invalid */
866 /* INVALID_TILE if there is no station */
867 TileIndex tile = INVALID_TILE;
868 Direction rotation = DIR_N;
869 uint size_x = 1, size_y = 1;
870 if (st != nullptr) {
871 if (st->airport.tile != INVALID_TILE) {
872 tile = st->airport.tile;
873 rotation = st->airport.rotation;
874 size_x = st->airport.w;
875 size_y = st->airport.h;
876 } else {
877 tile = st->xy;
878 }
879 }
880 /* DUMMY if there is no station or no airport */
881 const AirportFTAClass *afc = tile == INVALID_TILE ? GetAirport(AT_DUMMY) : st->airport.GetFTA();
882
883 /* prevent going to INVALID_TILE if airport is deleted. */
884 if (st == nullptr || st->airport.tile == INVALID_TILE) {
885 /* Jump into our "holding pattern" state machine if possible */
886 if (v->pos >= afc->nofelements) {
887 v->pos = v->previous_pos = AircraftGetEntryPoint(v, afc, DIR_N);
888 } else if (v->targetairport != v->current_order.GetDestination()) {
889 /* If not possible, just get out of here fast */
890 v->state = FLYING;
893 /* get aircraft back on running altitude */
894 SetAircraftPosition(v, v->x_pos, v->y_pos, GetAircraftFlightLevel(v));
895 return false;
896 }
897 }
898
899 /* get airport moving data */
900 const AirportMovingData amd = RotateAirportMovingData(afc->MovingData(v->pos), rotation, size_x, size_y);
901
902 int x = TileX(tile) * TILE_SIZE;
903 int y = TileY(tile) * TILE_SIZE;
904
905 /* Helicopter raise */
907 Aircraft *u = v->Next()->Next();
908
909 /* Make sure the rotors don't rotate too fast */
910 if (u->cur_speed > 32) {
911 v->cur_speed = 0;
912 if (--u->cur_speed == 32) {
913 if (!PlayVehicleSound(v, VSE_START)) {
914 SoundID sfx = AircraftVehInfo(v->engine_type)->sfx;
915 /* For compatibility with old NewGRF we ignore the sfx property, unless a NewGRF-defined sound is used.
916 * The baseset has only one helicopter sound, so this only limits using plane or cow sounds. */
918 SndPlayVehicleFx(sfx, v);
919 }
920 }
921 } else {
922 u->cur_speed = 32;
923 int count = UpdateAircraftSpeed(v);
924 if (count > 0) {
925 v->tile = TileIndex{};
926
927 int z_dest;
928 GetAircraftFlightLevelBounds(v, &z_dest, nullptr);
929
930 /* Reached altitude? */
931 if (v->z_pos >= z_dest) {
932 v->cur_speed = 0;
933 return true;
934 }
935 SetAircraftPosition(v, v->x_pos, v->y_pos, std::min(v->z_pos + count, z_dest));
936 }
937 }
938 return false;
939 }
940
941 /* Helicopter landing. */
944
945 if (st == nullptr) {
946 v->state = FLYING;
949 return false;
950 }
951
952 /* Vehicle is now at the airport.
953 * Helicopter has arrived at the target landing pad, so the current position is also where it should land.
954 * Except for Oilrigs which are special due to being a 1x1 station, and helicopters land outside it. */
955 if (st->airport.type != AT_OILRIG) {
956 x = v->x_pos;
957 y = v->y_pos;
958 tile = TileVirtXY(x, y);
959 }
960 v->tile = tile;
961
962 /* Find altitude of landing position. */
963 int z = GetSlopePixelZ(x, y) + 1 + afc->delta_z;
964
965 if (z == v->z_pos) {
966 Vehicle *u = v->Next()->Next();
967
968 /* Increase speed of rotors. When speed is 80, we've landed. */
969 if (u->cur_speed >= 80) {
971 return true;
972 }
973 u->cur_speed += 4;
974 } else {
975 int count = UpdateAircraftSpeed(v);
976 if (count > 0) {
977 if (v->z_pos > z) {
978 SetAircraftPosition(v, v->x_pos, v->y_pos, std::max(v->z_pos - count, z));
979 } else {
980 SetAircraftPosition(v, v->x_pos, v->y_pos, std::min(v->z_pos + count, z));
981 }
982 }
983 }
984 return false;
985 }
986
987 /* Get distance from destination pos to current pos. */
988 uint dist = abs(x + amd.x - v->x_pos) + abs(y + amd.y - v->y_pos);
989
990 /* Need exact position? */
991 if (!amd.flags.Test(AirportMovingDataFlag::ExactPosition) && dist <= (amd.flags.Test(AirportMovingDataFlag::SlowTurn) ? 8U : 4U)) return true;
992
993 /* At final pos? */
994 if (dist == 0) {
995 /* Change direction smoothly to final direction. */
996 DirDiff dirdiff = DirDifference(amd.direction, v->direction);
997 /* if distance is 0, and plane points in right direction, no point in calling
998 * UpdateAircraftSpeed(). So do it only afterwards */
999 if (dirdiff == DIRDIFF_SAME) {
1000 v->cur_speed = 0;
1001 return true;
1002 }
1003
1004 if (!UpdateAircraftSpeed(v, SPEED_LIMIT_TAXI)) return false;
1005
1007 v->cur_speed >>= 1;
1008
1009 SetAircraftPosition(v, v->x_pos, v->y_pos, v->z_pos);
1010 return false;
1011 }
1012
1015 if (v->vehstatus.Test(VehState::Crashed)) return false;
1016 }
1017
1018 uint speed_limit = SPEED_LIMIT_TAXI;
1019 bool hard_limit = true;
1020
1022 speed_limit = SPEED_LIMIT_NONE;
1023 }
1025 speed_limit = SPEED_LIMIT_HOLD;
1026 hard_limit = false;
1027 }
1029 speed_limit = SPEED_LIMIT_APPROACH;
1030 hard_limit = false;
1031 }
1033 speed_limit = SPEED_LIMIT_TAXI;
1034 hard_limit = false;
1035 }
1036
1037 int count = UpdateAircraftSpeed(v, speed_limit, hard_limit);
1038 if (count == 0) return false;
1039
1040 /* If the plane will be a few subpixels away from the destination after
1041 * this movement loop, start nudging it towards the exact position for
1042 * the whole loop. Otherwise, heavily depending on the speed of the plane,
1043 * it is possible we totally overshoot the target, causing the plane to
1044 * make a loop, and trying again, and again, and again .. */
1045 bool nudge_towards_target = static_cast<uint>(count) + 3 > dist;
1046
1047 if (v->turn_counter != 0) v->turn_counter--;
1048
1049 do {
1050
1052
1053 if (nudge_towards_target || amd.flags.Test(AirportMovingDataFlag::Land)) {
1054 /* move vehicle one pixel towards target */
1055 gp.x = (v->x_pos != (x + amd.x)) ?
1056 v->x_pos + ((x + amd.x > v->x_pos) ? 1 : -1) :
1057 v->x_pos;
1058 gp.y = (v->y_pos != (y + amd.y)) ?
1059 v->y_pos + ((y + amd.y > v->y_pos) ? 1 : -1) :
1060 v->y_pos;
1061
1062 /* Oilrigs must keep v->tile as st->airport.tile, since the landing pad is in a non-airport tile */
1063 gp.new_tile = (st->airport.type == AT_OILRIG) ? st->airport.tile : TileVirtXY(gp.x, gp.y);
1064
1065 } else {
1066
1067 /* Turn. Do it slowly if in the air. */
1068 Direction newdir = GetDirectionTowards(v, x + amd.x, y + amd.y);
1069 if (newdir != v->direction) {
1071 if (v->turn_counter == 0 || newdir == v->last_direction) {
1072 if (newdir == v->last_direction) {
1074 } else {
1076 }
1078 v->last_direction = v->direction;
1079 v->direction = newdir;
1080 }
1081
1082 /* Move vehicle. */
1083 gp = GetNewVehiclePos(v);
1084 } else {
1085 v->cur_speed >>= 1;
1086 v->direction = newdir;
1087
1088 /* When leaving a terminal an aircraft often goes to a position
1089 * directly in front of it. If it would move while turning it
1090 * would need an two extra turns to end up at the correct position.
1091 * To make it easier just disallow all moving while turning as
1092 * long as an aircraft is on the ground. */
1093 gp.x = v->x_pos;
1094 gp.y = v->y_pos;
1095 gp.new_tile = gp.old_tile = v->tile;
1096 }
1097 } else {
1099 /* Move vehicle. */
1100 gp = GetNewVehiclePos(v);
1101 }
1102 }
1103
1104 v->tile = gp.new_tile;
1105 /* If vehicle is in the air, use tile coordinate 0. */
1106 if (amd.flags.Any({AirportMovingDataFlag::Takeoff, AirportMovingDataFlag::SlowTurn, AirportMovingDataFlag::Land})) v->tile = TileIndex{};
1107
1108 /* Adjust Z for land or takeoff? */
1109 int z = v->z_pos;
1110
1112 z = GetAircraftFlightLevel(v, true);
1113 } else if (amd.flags.Test(AirportMovingDataFlag::Hold)) {
1114 /* Let the plane drop from normal flight altitude to holding pattern altitude */
1115 if (z > GetAircraftHoldMaxAltitude(v)) z--;
1116 } else if (amd.flags.All({AirportMovingDataFlag::SlowTurn, AirportMovingDataFlag::NoSpeedClamp})) {
1117 z = GetAircraftFlightLevel(v);
1118 }
1119
1120 /* NewGRF airports (like a rotated intercontinental from OpenGFX+Airports) can be non-rectangular
1121 * and their primary (north-most) tile does not have to be part of the airport.
1122 * As such, the height of the primary tile can be different from the rest of the airport.
1123 * Given we are landing/breaking, and as such are not a helicopter, we know that there has to be a hangar.
1124 * We also know that the airport itself has to be completely flat (otherwise it is not a valid airport).
1125 * Therefore, use the height of this hangar to calculate our z-value. */
1126 int airport_z = v->z_pos;
1127 if (amd.flags.Any({AirportMovingDataFlag::Land, AirportMovingDataFlag::Brake}) && st != nullptr) {
1128 assert(st->airport.HasHangar());
1129 TileIndex hangar_tile = st->airport.GetHangarTile(0);
1130 airport_z = GetTileMaxPixelZ(hangar_tile) + 1; // To avoid clashing with the shadow
1131 }
1132
1135 /* Zeppeliner blocked the runway, abort landing */
1136 v->state = FLYING;
1138 SetAircraftPosition(v, gp.x, gp.y, GetAircraftFlightLevel(v));
1139 v->pos = v->previous_pos;
1140 continue;
1141 }
1142
1143 if (st->airport.tile == INVALID_TILE) {
1144 /* Airport has been removed, abort the landing procedure */
1145 v->state = FLYING;
1148 /* get aircraft back on running altitude */
1149 SetAircraftPosition(v, gp.x, gp.y, GetAircraftFlightLevel(v));
1150 continue;
1151 }
1152
1153 /* We're not flying below our destination, right? */
1154 assert(airport_z <= z);
1155 int t = std::max(1U, dist - 4);
1156 int delta = z - airport_z;
1157
1158 /* Only start lowering when we're sufficiently close for a 1:1 glide */
1159 if (delta >= t) {
1160 z -= CeilDiv(z - airport_z, t);
1161 }
1162 if (z < airport_z) z = airport_z;
1163 }
1164
1165 /* We've landed. Decrease speed when we're reaching end of runway. */
1167
1168 if (z > airport_z) {
1169 z--;
1170 } else if (z < airport_z) {
1171 z++;
1172 }
1173
1174 }
1175
1176 SetAircraftPosition(v, gp.x, gp.y, z);
1177 } while (--count != 0);
1178 return false;
1179}
1180
1186{
1187 v->crashed_counter += 3;
1188
1190
1191 /* make aircraft crash down to the ground */
1192 if (v->crashed_counter < 500 && st == nullptr && ((v->crashed_counter % 3) == 0)) {
1193 int z = GetSlopePixelZ(Clamp(v->x_pos, 0, Map::MaxX() * TILE_SIZE), Clamp(v->y_pos, 0, Map::MaxY() * TILE_SIZE));
1194 v->z_pos -= 1;
1195 if (v->z_pos <= z) {
1196 v->crashed_counter = 500;
1197 v->z_pos = z + 1;
1198 } else {
1199 v->crashed_counter = 0;
1200 }
1201 SetAircraftPosition(v, v->x_pos, v->y_pos, v->z_pos);
1202 }
1203
1204 if (v->crashed_counter < 650) {
1205 uint32_t r;
1206 if (Chance16R(1, 32, r)) {
1207 static const DirDiff delta[] = {
1209 };
1210
1211 v->direction = ChangeDir(v->direction, delta[GB(r, 16, 2)]);
1212 SetAircraftPosition(v, v->x_pos, v->y_pos, v->z_pos);
1213 r = Random();
1215 GB(r, 0, 4) - 4,
1216 GB(r, 4, 4) - 4,
1217 GB(r, 8, 4),
1219 }
1220 } else if (v->crashed_counter >= 10000) {
1221 /* remove rubble of crashed airplane */
1222
1223 /* clear runway-in on all airports, set by crashing plane
1224 * small airports use AIRPORT_BUSY, city airports use AirportBlock::RunwayInOut, etc.
1225 * but they all share the same number */
1226 if (st != nullptr) {
1227 st->airport.blocks.Reset(AirportBlock::RunwayIn);
1228 st->airport.blocks.Reset(AirportBlock::RunwayInOut); // commuter airport
1229 st->airport.blocks.Reset(AirportBlock::RunwayIn2); // intercontinental
1230 }
1231
1232 delete v;
1233
1234 return false;
1235 }
1236
1237 return true;
1238}
1239
1240
1246static void HandleAircraftSmoke(Aircraft *v, bool mode)
1247{
1248 static const struct {
1249 int8_t x;
1250 int8_t y;
1251 } smoke_pos[] = {
1252 { 5, 5 },
1253 { 6, 0 },
1254 { 5, -5 },
1255 { 0, -6 },
1256 { -5, -5 },
1257 { -6, 0 },
1258 { -5, 5 },
1259 { 0, 6 }
1260 };
1261
1262 if (!v->vehstatus.Test(VehState::AircraftBroken)) return;
1263
1264 /* Stop smoking when landed */
1265 if (v->cur_speed < 10) {
1267 v->breakdown_ctr = 0;
1268 return;
1269 }
1270
1271 /* Spawn effect et most once per Tick, i.e. !mode */
1272 if (!mode && (v->tick_counter & 0x0F) == 0) {
1274 smoke_pos[v->direction].x,
1275 smoke_pos[v->direction].y,
1276 2,
1278 );
1279 }
1280}
1281
1282void HandleMissingAircraftOrders(Aircraft *v)
1283{
1284 /*
1285 * We do not have an order. This can be divided into two cases:
1286 * 1) we are heading to an invalid station. In this case we must
1287 * find another airport to go to. If there is nowhere to go,
1288 * we will destroy the aircraft as it otherwise will enter
1289 * the holding pattern for the first airport, which can cause
1290 * the plane to go into an undefined state when building an
1291 * airport with the same StationID.
1292 * 2) we are (still) heading to a (still) valid airport, then we
1293 * can continue going there. This can happen when you are
1294 * changing the aircraft's orders while in-flight or in for
1295 * example a depot. However, when we have a current order to
1296 * go to a depot, we have to keep that order so the aircraft
1297 * actually stops.
1298 */
1299 const Station *st = GetTargetAirportIfValid(v);
1300 if (st == nullptr) {
1301 Backup<CompanyID> cur_company(_current_company, v->owner);
1303 cur_company.Restore();
1304
1305 if (ret.Failed()) CrashAirplane(v);
1306 } else if (!v->current_order.IsType(OT_GOTO_DEPOT)) {
1307 v->current_order.Free();
1308 }
1309}
1310
1311
1313{
1314 /* Orders are changed in flight, ensure going to the right station. */
1315 if (this->state == FLYING) {
1317 }
1318
1319 /* Aircraft do not use dest-tile */
1320 return TileIndex{};
1321}
1322
1324{
1325 this->colourmap = PAL_NONE;
1326 this->UpdateViewport(true, false);
1327 if (this->subtype == AIR_HELICOPTER) {
1328 GetRotorImage(this, EIT_ON_MAP, &this->Next()->Next()->sprite_cache.sprite_seq);
1329 }
1330}
1331
1332
1333uint Aircraft::Crash(bool flooded)
1334{
1335 uint victims = Vehicle::Crash(flooded) + 2; // pilots
1336 this->crashed_counter = flooded ? 9000 : 0; // max 10000, disappear pretty fast when flooded
1337
1338 return victims;
1339}
1340
1346{
1348
1349 uint victims = v->Crash();
1350
1351 v->cargo.Truncate();
1352 v->Next()->cargo.Truncate();
1353 const Station *st = GetTargetAirportIfValid(v);
1354 TileIndex vt = TileVirtXY(v->x_pos, v->y_pos);
1355
1356 EncodedString headline;
1357 if (st == nullptr) {
1358 headline = GetEncodedString(STR_NEWS_PLANE_CRASH_OUT_OF_FUEL, victims);
1359 } else {
1360 headline = GetEncodedString(STR_NEWS_AIRCRAFT_CRASH, victims, st->index);
1361 }
1362
1363 AI::NewEvent(v->owner, new ScriptEventVehicleCrashed(v->index, vt, st == nullptr ? ScriptEventVehicleCrashed::CRASH_AIRCRAFT_NO_AIRPORT : ScriptEventVehicleCrashed::CRASH_PLANE_LANDING, victims, v->owner));
1364 Game::NewEvent(new ScriptEventVehicleCrashed(v->index, vt, st == nullptr ? ScriptEventVehicleCrashed::CRASH_AIRCRAFT_NO_AIRPORT : ScriptEventVehicleCrashed::CRASH_PLANE_LANDING, victims, v->owner));
1365
1366 NewsType newstype = NewsType::Accident;
1367 if (v->owner != _local_company) {
1368 newstype = NewsType::AccidentOther;
1369 }
1370
1371 AddTileNewsItem(std::move(headline), newstype, vt, st != nullptr ? st->index : StationID::Invalid());
1372
1373 ModifyStationRatingAround(vt, v->owner, -160, 30);
1374 if (_settings_client.sound.disaster) SndPlayVehicleFx(SND_12_EXPLOSION, v);
1375}
1376
1382{
1383
1385
1386 uint32_t prob;
1388 (AircraftVehInfo(v->engine_type)->subtype & AIR_FAST) &&
1390 prob = 3276;
1391 } else {
1392 if (_settings_game.vehicle.plane_crashes == 0) return;
1393 prob = (0x4000 << _settings_game.vehicle.plane_crashes) / 1500;
1394 }
1395
1396 if (GB(Random(), 0, 22) > prob) return;
1397
1398 /* Crash the airplane. Remove all goods stored at the station. */
1399 for (GoodsEntry &ge : st->goods) {
1400 ge.rating = 1;
1401 if (ge.HasData()) ge.GetData().cargo.Truncate();
1402 }
1403
1404 CrashAirplane(v);
1405}
1406
1413{
1414 if (v->current_order.IsType(OT_GOTO_DEPOT)) return;
1415
1418
1419 /* Check if station was ever visited before */
1420 if (!(st->had_vehicle_of_type & HVOT_AIRCRAFT)) {
1421 st->had_vehicle_of_type |= HVOT_AIRCRAFT;
1422 /* show newsitem of celebrating citizens */
1424 GetEncodedString(STR_NEWS_FIRST_AIRCRAFT_ARRIVAL, st->index),
1426 v->index,
1427 st->index
1428 );
1429 AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
1430 Game::NewEvent(new ScriptEventStationFirstVehicle(st->index, v->index));
1431 }
1432
1433 v->BeginLoading();
1434}
1435
1441{
1443
1444 TileIndex vt = TileVirtXY(v->x_pos, v->y_pos);
1445
1446 v->UpdateDeltaXY();
1447
1448 TriggerAirportTileAnimation(st, vt, AirportAnimationTrigger::AirplaneTouchdown);
1449
1451 SndPlayVehicleFx(SND_17_SKID_PLANE, v);
1452 }
1453}
1454
1455
1458{
1459 if (v->current_order.IsType(OT_GOTO_STATION) || v->current_order.IsType(OT_GOTO_DEPOT)) {
1460 v->targetairport = v->current_order.GetDestination().ToStationID();
1461 }
1462
1463 const Station *st = GetTargetAirportIfValid(v);
1464 const AirportFTAClass *apc = st == nullptr ? GetAirport(AT_DUMMY) : st->airport.GetFTA();
1465 Direction rotation = st == nullptr ? DIR_N : st->airport.rotation;
1466 v->pos = v->previous_pos = AircraftGetEntryPoint(v, apc, rotation);
1467}
1468
1478{
1479 v->cur_speed = 0;
1480 v->subspeed = 0;
1481 v->progress = 0;
1482 v->direction = exit_dir;
1484 {
1485 Vehicle *u = v->Next();
1487
1488 /* Rotor blades */
1489 u = u->Next();
1490 if (u != nullptr) {
1492 u->cur_speed = 80;
1493 }
1494 }
1495
1498 SetAircraftPosition(v, v->x_pos, v->y_pos, v->z_pos);
1501}
1502
1506static void AircraftEventHandler_EnterTerminal(Aircraft *v, const AirportFTAClass *apc)
1507{
1509 v->state = apc->layout[v->pos].heading;
1510}
1511
1518{
1520 v->state = apc->layout[v->pos].heading;
1521}
1522
1529{
1530 /* if we just arrived, execute EnterHangar first */
1531 if (v->previous_pos != v->pos) {
1533 return;
1534 }
1535
1536 /* if we were sent to the depot, stay there */
1537 if (v->current_order.IsType(OT_GOTO_DEPOT) && v->vehstatus.Test(VehState::Stopped)) {
1538 v->current_order.Free();
1539 return;
1540 }
1541
1542 /* Check if we should wait here for unbunching. */
1543 if (v->IsWaitingForUnbunching()) return;
1544
1545 if (!v->current_order.IsType(OT_GOTO_STATION) &&
1546 !v->current_order.IsType(OT_GOTO_DEPOT))
1547 return;
1548
1549 /* We are leaving a hangar, but have to go to the exact same one; re-enter */
1550 if (v->current_order.IsType(OT_GOTO_DEPOT) && v->current_order.GetDestination() == v->targetairport) {
1552 return;
1553 }
1554
1555 /* if the block of the next position is busy, stay put */
1556 if (AirportHasBlock(v, &apc->layout[v->pos], apc)) return;
1557
1558 /* We are already at the target airport, we need to find a terminal */
1560 /* FindFreeTerminal:
1561 * 1. Find a free terminal, 2. Occupy it, 3. Set the vehicle's state to that terminal */
1562 if (v->subtype == AIR_HELICOPTER) {
1563 if (!AirportFindFreeHelipad(v, apc)) return; // helicopter
1564 } else {
1565 if (!AirportFindFreeTerminal(v, apc)) return; // airplane
1566 }
1567 } else { // Else prepare for launch.
1568 /* airplane goto state takeoff, helicopter to helitakeoff */
1570 }
1571 const Station *st = Station::GetByTile(v->tile);
1573 AirportMove(v, apc);
1574}
1575
1578{
1579 /* if we just arrived, execute EnterTerminal first */
1580 if (v->previous_pos != v->pos) {
1581 AircraftEventHandler_EnterTerminal(v, apc);
1582 /* on an airport with helipads, a helicopter will always land there
1583 * and get serviced at the same time - setting */
1585 if (v->subtype == AIR_HELICOPTER && apc->num_helipads > 0) {
1586 /* an excerpt of ServiceAircraft, without the invisibility stuff */
1592 }
1593 }
1594 return;
1595 }
1596
1597 if (v->current_order.IsType(OT_NOTHING)) return;
1598
1599 /* if the block of the next position is busy, stay put */
1600 if (AirportHasBlock(v, &apc->layout[v->pos], apc)) return;
1601
1602 /* airport-road is free. We either have to go to another airport, or to the hangar
1603 * ---> start moving */
1604
1605 bool go_to_hangar = false;
1606 switch (v->current_order.GetType()) {
1607 case OT_GOTO_STATION: // ready to fly to another airport
1608 break;
1609 case OT_GOTO_DEPOT: // visit hangar for servicing, sale, etc.
1610 go_to_hangar = v->current_order.GetDestination() == v->targetairport;
1611 break;
1612 case OT_CONDITIONAL:
1613 /* In case of a conditional order we just have to wait a tick
1614 * longer, so the conditional order can actually be processed;
1615 * we should not clear the order as that makes us go nowhere. */
1616 return;
1617 default: // orders have been deleted (no orders), goto depot and don't bother us
1618 v->current_order.Free();
1619 go_to_hangar = true;
1620 }
1621
1622 if (go_to_hangar && Station::Get(v->targetairport)->airport.HasHangar()) {
1623 v->state = HANGAR;
1624 } else {
1625 /* airplane goto state takeoff, helicopter to helitakeoff */
1627 }
1628 AirportMove(v, apc);
1629}
1630
1631static void AircraftEventHandler_General(Aircraft *, const AirportFTAClass *)
1632{
1633 FatalError("OK, you shouldn't be here, check your Airport Scheme!");
1634}
1635
1636static void AircraftEventHandler_TakeOff(Aircraft *v, const AirportFTAClass *)
1637{
1638 PlayAircraftSound(v); // play takeoffsound for airplanes
1639 v->state = STARTTAKEOFF;
1640}
1641
1642static void AircraftEventHandler_StartTakeOff(Aircraft *v, const AirportFTAClass *)
1643{
1644 v->state = ENDTAKEOFF;
1645 v->UpdateDeltaXY();
1646}
1647
1648static void AircraftEventHandler_EndTakeOff(Aircraft *v, const AirportFTAClass *)
1649{
1650 v->state = FLYING;
1651 /* get the next position to go to, differs per airport */
1653}
1654
1655static void AircraftEventHandler_HeliTakeOff(Aircraft *v, const AirportFTAClass *)
1656{
1657 v->state = FLYING;
1658 v->UpdateDeltaXY();
1659
1660 /* get the next position to go to, differs per airport */
1662
1663 /* Send the helicopter to a hangar if needed for replacement */
1664 if (v->NeedsAutomaticServicing()) {
1665 Backup<CompanyID> cur_company(_current_company, v->owner);
1667 cur_company.Restore();
1668 }
1669}
1670
1671static void AircraftEventHandler_Flying(Aircraft *v, const AirportFTAClass *apc)
1672{
1674
1675 /* Runway busy, not allowed to use this airstation or closed, circle. */
1676 if (CanVehicleUseStation(v, st) && (st->owner == OWNER_NONE || st->owner == v->owner) && !st->airport.blocks.Test(AirportBlock::AirportClosed)) {
1677 /* {32,FLYING,AirportBlock::Nothing,37}, {32,LANDING,N,33}, {32,HELILANDING,N,41},
1678 * if it is an airplane, look for LANDING, for helicopter HELILANDING
1679 * it is possible to choose from multiple landing runways, so loop until a free one is found */
1680 uint8_t landingtype = (v->subtype == AIR_HELICOPTER) ? HELILANDING : LANDING;
1681 const AirportFTA *current = apc->layout[v->pos].next.get();
1682 while (current != nullptr) {
1683 if (current->heading == landingtype) {
1684 /* save speed before, since if AirportHasBlock is false, it resets them to 0
1685 * we don't want that for plane in air
1686 * hack for speed thingy */
1687 uint16_t tcur_speed = v->cur_speed;
1688 uint16_t tsubspeed = v->subspeed;
1689 if (!AirportHasBlock(v, current, apc)) {
1690 v->state = landingtype; // LANDING / HELILANDING
1692 /* it's a bit dirty, but I need to set position to next position, otherwise
1693 * if there are multiple runways, plane won't know which one it took (because
1694 * they all have heading LANDING). And also occupy that block! */
1695 v->pos = current->next_position;
1696 st->airport.blocks.Set(apc->layout[v->pos].blocks);
1697 return;
1698 }
1699 v->cur_speed = tcur_speed;
1700 v->subspeed = tsubspeed;
1701 }
1702 current = current->next.get();
1703 }
1704 }
1705 v->state = FLYING;
1706 v->pos = apc->layout[v->pos].next_position;
1707}
1708
1709static void AircraftEventHandler_Landing(Aircraft *v, const AirportFTAClass *)
1710{
1711 v->state = ENDLANDING;
1712 AircraftLandAirplane(v); // maybe crash airplane
1713
1714 /* check if the aircraft needs to be replaced or renewed and send it to a hangar if needed */
1715 if (v->NeedsAutomaticServicing()) {
1716 Backup<CompanyID> cur_company(_current_company, v->owner);
1718 cur_company.Restore();
1719 }
1720}
1721
1722static void AircraftEventHandler_HeliLanding(Aircraft *v, const AirportFTAClass *)
1723{
1724 v->state = HELIENDLANDING;
1725 v->UpdateDeltaXY();
1726}
1727
1728static void AircraftEventHandler_EndLanding(Aircraft *v, const AirportFTAClass *apc)
1729{
1730 /* next block busy, don't do a thing, just wait */
1731 if (AirportHasBlock(v, &apc->layout[v->pos], apc)) return;
1732
1733 /* if going to terminal (OT_GOTO_STATION) choose one
1734 * 1. in case all terminals are busy AirportFindFreeTerminal() returns false or
1735 * 2. not going for terminal (but depot, no order),
1736 * --> get out of the way to the hangar. */
1737 if (v->current_order.IsType(OT_GOTO_STATION)) {
1738 if (AirportFindFreeTerminal(v, apc)) return;
1739 }
1740 v->state = HANGAR;
1741
1742}
1743
1744static void AircraftEventHandler_HeliEndLanding(Aircraft *v, const AirportFTAClass *apc)
1745{
1746 /* next block busy, don't do a thing, just wait */
1747 if (AirportHasBlock(v, &apc->layout[v->pos], apc)) return;
1748
1749 /* if going to helipad (OT_GOTO_STATION) choose one. If airport doesn't have helipads, choose terminal
1750 * 1. in case all terminals/helipads are busy (AirportFindFreeHelipad() returns false) or
1751 * 2. not going for terminal (but depot, no order),
1752 * --> get out of the way to the hangar IF there are terminals on the airport.
1753 * --> else TAKEOFF
1754 * the reason behind this is that if an airport has a terminal, it also has a hangar. Airplanes
1755 * must go to a hangar. */
1756 if (v->current_order.IsType(OT_GOTO_STATION)) {
1757 if (AirportFindFreeHelipad(v, apc)) return;
1758 }
1760}
1761
1767typedef void AircraftStateHandler(Aircraft *v, const AirportFTAClass *apc);
1770 AircraftEventHandler_General, // TO_ALL = 0
1771 AircraftEventHandler_InHangar, // HANGAR = 1
1778 AircraftEventHandler_AtTerminal, // HELIPAD1 = 8
1779 AircraftEventHandler_AtTerminal, // HELIPAD2 = 9
1780 AircraftEventHandler_TakeOff, // TAKEOFF = 10
1781 AircraftEventHandler_StartTakeOff, // STARTTAKEOFF = 11
1782 AircraftEventHandler_EndTakeOff, // ENDTAKEOFF = 12
1783 AircraftEventHandler_HeliTakeOff, // HELITAKEOFF = 13
1784 AircraftEventHandler_Flying, // FLYING = 14
1785 AircraftEventHandler_Landing, // LANDING = 15
1786 AircraftEventHandler_EndLanding, // ENDLANDING = 16
1787 AircraftEventHandler_HeliLanding, // HELILANDING = 17
1788 AircraftEventHandler_HeliEndLanding, // HELIENDLANDING = 18
1789 AircraftEventHandler_AtTerminal, // TERM7 = 19
1790 AircraftEventHandler_AtTerminal, // TERM8 = 20
1791 AircraftEventHandler_AtTerminal, // HELIPAD3 = 21
1792};
1793
1794static void AirportClearBlock(const Aircraft *v, const AirportFTAClass *apc)
1795{
1796 /* we have left the previous block, and entered the new one. Free the previous block */
1797 if (apc->layout[v->previous_pos].blocks != apc->layout[v->pos].blocks) {
1799
1801 apc->layout[v->previous_pos].blocks == AirportBlock::RunwayIn) {
1802 return;
1803 }
1804
1805 st->airport.blocks.Reset(apc->layout[v->previous_pos].blocks);
1806 }
1807}
1808
1809static void AirportGoToNextPosition(Aircraft *v)
1810{
1811 /* if aircraft is not in position, wait until it is */
1812 if (!AircraftController(v)) return;
1813
1815
1816 AirportClearBlock(v, apc);
1817 AirportMove(v, apc); // move aircraft to next position
1818}
1819
1820/* gets pos from vehicle and next orders */
1821static bool AirportMove(Aircraft *v, const AirportFTAClass *apc)
1822{
1823 /* error handling */
1824 if (v->pos >= apc->nofelements) {
1825 Debug(misc, 0, "[Ap] position {} is not valid for current airport. Max position is {}", v->pos, apc->nofelements - 1);
1826 assert(v->pos < apc->nofelements);
1827 }
1828
1829 const AirportFTA *current = &apc->layout[v->pos];
1830 /* we have arrived in an important state (eg terminal, hangar, etc.) */
1831 if (current->heading == v->state) {
1832 uint8_t prev_pos = v->pos; // location could be changed in state, so save it before-hand
1833 uint8_t prev_state = v->state;
1834 _aircraft_state_handlers[v->state](v, apc);
1835 if (v->state != FLYING) v->previous_pos = prev_pos;
1836 if (v->state != prev_state || v->pos != prev_pos) UpdateAircraftCache(v);
1837 return true;
1838 }
1839
1840 v->previous_pos = v->pos; // save previous location
1841
1842 /* there is only one choice to move to */
1843 if (current->next == nullptr) {
1844 if (AirportSetBlocks(v, current, apc)) {
1845 v->pos = current->next_position;
1847 } // move to next position
1848 return false;
1849 }
1850
1851 /* there are more choices to choose from, choose the one that
1852 * matches our heading */
1853 do {
1854 if (v->state == current->heading || current->heading == TO_ALL) {
1855 if (AirportSetBlocks(v, current, apc)) {
1856 v->pos = current->next_position;
1858 } // move to next position
1859 return false;
1860 }
1861 current = current->next.get();
1862 } while (current != nullptr);
1863
1864 Debug(misc, 0, "[Ap] cannot move further on Airport! (pos {} state {}) for vehicle {}", v->pos, v->state, v->index);
1865 NOT_REACHED();
1866}
1867
1869static bool AirportHasBlock(Aircraft *v, const AirportFTA *current_pos, const AirportFTAClass *apc)
1870{
1871 const AirportFTA *reference = &apc->layout[v->pos];
1872 const AirportFTA *next = &apc->layout[current_pos->next_position];
1873
1874 /* same block, then of course we can move */
1875 if (apc->layout[current_pos->position].blocks != next->blocks) {
1876 const Station *st = Station::Get(v->targetairport);
1877 AirportBlocks blocks = next->blocks;
1878
1879 /* check additional possible extra blocks */
1880 if (current_pos != reference && current_pos->blocks != AirportBlock::Nothing) {
1881 blocks.Set(current_pos->blocks);
1882 }
1883
1884 if (st->airport.blocks.Any(blocks)) {
1885 v->cur_speed = 0;
1886 v->subspeed = 0;
1887 return true;
1888 }
1889 }
1890 return false;
1891}
1892
1900static bool AirportSetBlocks(Aircraft *v, const AirportFTA *current_pos, const AirportFTAClass *apc)
1901{
1902 const AirportFTA *next = &apc->layout[current_pos->next_position];
1903 const AirportFTA *reference = &apc->layout[v->pos];
1904
1905 /* if the next position is in another block, check it and wait until it is free */
1906 if (!apc->layout[current_pos->position].blocks.All(next->blocks)) {
1907 AirportBlocks blocks = next->blocks;
1908 /* search for all all elements in the list with the same state, and blocks != N
1909 * this means more blocks should be checked/set */
1910 const AirportFTA *current = current_pos;
1911 if (current == reference) current = current->next.get();
1912 while (current != nullptr) {
1913 if (current->heading == current_pos->heading && current->blocks.Any()) {
1914 blocks.Set(current->blocks);
1915 break;
1916 }
1917 current = current->next.get();
1918 }
1919
1920 /* if the block to be checked is in the next position, then exclude that from
1921 * checking, because it has been set by the airplane before */
1922 if (current_pos->blocks == next->blocks) blocks.Flip(next->blocks);
1923
1925 if (st->airport.blocks.Any(blocks)) {
1926 v->cur_speed = 0;
1927 v->subspeed = 0;
1928 return false;
1929 }
1930
1931 if (next->blocks != AirportBlock::Nothing) {
1932 st->airport.blocks.Set(blocks); // occupy next block
1933 }
1934 }
1935 return true;
1936}
1937
1946
1961
1969static bool FreeTerminal(Aircraft *v, uint8_t i, uint8_t last_terminal)
1970{
1971 assert(last_terminal <= lengthof(_airport_terminal_mapping));
1973 for (; i < last_terminal; i++) {
1975 /* TERMINAL# HELIPAD# */
1976 v->state = _airport_terminal_mapping[i].state; // start moving to that terminal/helipad
1977 st->airport.blocks.Set(_airport_terminal_mapping[i].blocks); // occupy terminal/helipad
1978 return true;
1979 }
1980 }
1981 return false;
1982}
1983
1989static uint GetNumTerminals(const AirportFTAClass *apc)
1990{
1991 uint num = 0;
1992
1993 for (uint i = apc->terminals[0]; i > 0; i--) num += apc->terminals[i];
1994
1995 return num;
1996}
1997
2005{
2006 /* example of more terminalgroups
2007 * {0,HANGAR,AirportBlock::Nothing,1}, {0,TERMGROUP,AirportBlock::TermGroup1,0}, {0,TERMGROUP,TERM_GROUP2_ENTER_block,1}, {0,0,N,1},
2008 * Heading TERMGROUP denotes a group. We see 2 groups here:
2009 * 1. group 0 -- AirportBlock::TermGroup1 (check block)
2010 * 2. group 1 -- TERM_GROUP2_ENTER_block (check block)
2011 * First in line is checked first, group 0. If the block (AirportBlock::TermGroup1) is free, it
2012 * looks at the corresponding terminals of that group. If no free ones are found, other
2013 * possible groups are checked (in this case group 1, since that is after group 0). If that
2014 * fails, then attempt fails and plane waits
2015 */
2016 if (apc->terminals[0] > 1) {
2017 const Station *st = Station::Get(v->targetairport);
2018 const AirportFTA *temp = apc->layout[v->pos].next.get();
2019
2020 while (temp != nullptr) {
2021 if (temp->heading == TERMGROUP) {
2022 if (!st->airport.blocks.Any(temp->blocks)) {
2023 /* read which group do we want to go to?
2024 * (the first free group) */
2025 uint target_group = temp->next_position + 1;
2026
2027 /* at what terminal does the group start?
2028 * that means, sum up all terminals of
2029 * groups with lower number */
2030 uint group_start = 0;
2031 for (uint i = 1; i < target_group; i++) {
2032 group_start += apc->terminals[i];
2033 }
2034
2035 uint group_end = group_start + apc->terminals[target_group];
2036 if (FreeTerminal(v, group_start, group_end)) return true;
2037 }
2038 } else {
2039 /* once the heading isn't 255, we've exhausted the possible blocks.
2040 * So we cannot move */
2041 return false;
2042 }
2043 temp = temp->next.get();
2044 }
2045 }
2046
2047 /* if there is only 1 terminalgroup, all terminals are checked (starting from 0 to max) */
2048 return FreeTerminal(v, 0, GetNumTerminals(apc));
2049}
2050
2058{
2059 /* if an airport doesn't have helipads, use terminals */
2060 if (apc->num_helipads == 0) return AirportFindFreeTerminal(v, apc);
2061
2062 /* only 1 helicoptergroup, check all helipads
2063 * The blocks for helipads start after the last terminal (MAX_TERMINALS) */
2065}
2066
2072static void AircraftHandleDestTooFar(Aircraft *v, bool too_far)
2073{
2074 if (too_far) {
2075 if (!HasBit(v->flags, VAF_DEST_TOO_FAR)) {
2078 AI::NewEvent(v->owner, new ScriptEventAircraftDestTooFar(v->index));
2079 if (v->owner == _local_company) {
2080 /* Post a news message. */
2082 }
2083 }
2084 return;
2085 }
2086
2087 if (HasBit(v->flags, VAF_DEST_TOO_FAR)) {
2088 /* Not too far anymore, clear flag and message. */
2092 }
2093}
2094
2095static bool AircraftEventHandler(Aircraft *v, int loop)
2096{
2098 return HandleCrashedAircraft(v);
2099 }
2100
2101 if (v->vehstatus.Test(VehState::Stopped)) return true;
2102
2103 v->HandleBreakdown();
2104
2105 HandleAircraftSmoke(v, loop != 0);
2106 ProcessOrders(v);
2107 v->HandleLoading(loop != 0);
2108
2109 if (v->current_order.IsType(OT_LOADING) || v->current_order.IsType(OT_LEAVESTATION)) return true;
2110
2111 if (v->state >= ENDTAKEOFF && v->state <= HELIENDLANDING) {
2112 /* If we are flying, unconditionally clear the 'dest too far' state. */
2113 AircraftHandleDestTooFar(v, false);
2114 } else if (v->acache.cached_max_range_sqr != 0) {
2115 /* Check the distance to the next destination. This code works because the target
2116 * airport is only updated after take off and not on the ground. */
2118 Station *next_st = v->current_order.IsType(OT_GOTO_STATION) || v->current_order.IsType(OT_GOTO_DEPOT) ? Station::GetIfValid(v->current_order.GetDestination().ToStationID()) : nullptr;
2119
2120 if (cur_st != nullptr && cur_st->airport.tile != INVALID_TILE && next_st != nullptr && next_st->airport.tile != INVALID_TILE) {
2121 uint dist = DistanceSquare(cur_st->airport.tile, next_st->airport.tile);
2123 }
2124 }
2125
2126 if (!HasBit(v->flags, VAF_DEST_TOO_FAR)) AirportGoToNextPosition(v);
2127
2128 return true;
2129}
2130
2132{
2133 if (!this->IsNormalAircraft()) return true;
2134
2136
2137 this->tick_counter++;
2138
2139 if (!this->vehstatus.Test(VehState::Stopped)) this->running_ticks++;
2140
2141 if (this->subtype == AIR_HELICOPTER) HelicopterTickHandler(this);
2142
2143 this->current_order_time++;
2144
2145 for (uint i = 0; i != 2; i++) {
2146 /* stop if the aircraft was deleted */
2147 if (!AircraftEventHandler(this, i)) return false;
2148 }
2149
2150 return true;
2151}
2152
2153
2161{
2162 assert(v->type == VEH_AIRCRAFT);
2163
2165 if (st == nullptr) return nullptr;
2166
2167 return st->airport.tile == INVALID_TILE ? nullptr : st;
2168}
2169
2175{
2176 /* only 1 station is updated per function call, so it is enough to get entry_point once */
2177 const AirportFTAClass *ap = st->airport.GetFTA();
2178 Direction rotation = st->airport.tile == INVALID_TILE ? DIR_N : st->airport.rotation;
2179
2180 for (Aircraft *v : Aircraft::Iterate()) {
2181 if (!v->IsNormalAircraft() || v->targetairport != st->index) continue;
2182 assert(v->state == FLYING);
2183
2184 Order *o = &v->current_order;
2185 /* The aircraft is heading to a hangar, but the new station doesn't have one,
2186 * or the aircraft can't land on the new station. Cancel current order. */
2187 if (o->IsType(OT_GOTO_DEPOT) && !o->GetDepotOrderType().Test(OrderDepotTypeFlag::PartOfOrders) && o->GetDestination() == st->index &&
2188 (!st->airport.HasHangar() || !CanVehicleUseStation(v, st))) {
2189 o->MakeDummy();
2191 }
2192 v->pos = v->previous_pos = AircraftGetEntryPoint(v, ap, rotation);
2194 }
2195
2196 /* Heliports don't have a hangar. Invalidate all go to hangar orders from all aircraft. */
2197 if (!st->airport.HasHangar()) RemoveOrderFromAllVehicles(OT_GOTO_DEPOT, st->index, true);
2198}
Base functions for all AIs.
Base for aircraft.
static constexpr int AIRCRAFT_MIN_FLYING_ALTITUDE
Base values for flight levels above ground level for 'normal' flight and holding patterns.
Definition aircraft.h:20
static constexpr int HELICOPTER_HOLD_MAX_FLYING_ALTITUDE
holding flying altitude above tile of helicopters.
Definition aircraft.h:23
static const int ROTOR_Z_OFFSET
Z Offset between helicopter- and rotorsprite.
Definition aircraft.h:48
static constexpr int PLANE_HOLD_MAX_FLYING_ALTITUDE
holding flying altitude above tile of planes.
Definition aircraft.h:22
void AircraftNextAirportPos_and_Order(Aircraft *v)
set the right pos when heading to other airports after takeoff
Station * GetTargetAirportIfValid(const Aircraft *v)
Returns aircraft's target station if v->target_airport is a valid station with airport.
@ VAF_HELI_DIRECT_DESCENT
The helicopter is descending directly at its destination (helipad or in front of hangar)
Definition aircraft.h:45
@ VAF_DEST_TOO_FAR
Next destination is too far away.
Definition aircraft.h:37
@ VAF_IN_MIN_HEIGHT_CORRECTION
The vehicle is currently raising its altitude because it hit the lower bound.
Definition aircraft.h:43
@ VAF_IN_MAX_HEIGHT_CORRECTION
The vehicle is currently lowering its altitude because it hit the upper bound.
Definition aircraft.h:42
@ AIR_AIRCRAFT
an airplane
Definition aircraft.h:30
@ AIR_ROTOR
rotor of an helicopter
Definition aircraft.h:32
@ AIR_SHADOW
shadow of the aircraft
Definition aircraft.h:31
@ AIR_HELICOPTER
an helicopter
Definition aircraft.h:29
static constexpr int AIRCRAFT_MAX_FLYING_ALTITUDE
Maximum flying altitude above tile.
Definition aircraft.h:21
static void HandleAircraftSmoke(Aircraft *v, bool mode)
Handle smoke of broken aircraft.
static void AircraftEventHandler_InHangar(Aircraft *v, const AirportFTAClass *apc)
Handle aircraft movement/decision making in an airport hangar.
static StationID FindNearestHangar(const Aircraft *v)
Find the nearest hangar to v StationID::Invalid() is returned, if the company does not have any suita...
static uint GetNumTerminals(const AirportFTAClass *apc)
Get the number of terminals at the airport.
void UpdateAirplanesOnNewStation(const Station *st)
Updates the status of the Aircraft heading or in the station.
void AircraftNextAirportPos_and_Order(Aircraft *v)
set the right pos when heading to other airports after takeoff
int GetTileHeightBelowAircraft(const Vehicle *v)
Get the tile height below the aircraft.
void GetAircraftSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type)
Get the size of the sprite of an aircraft sprite heading west (used for lists).
static uint8_t AircraftGetEntryPoint(const Aircraft *v, const AirportFTAClass *apc, Direction rotation)
Find the entry point to an airport depending on direction which the airport is being approached from.
static const MovementTerminalMapping _airport_terminal_mapping[]
A list of all valid terminals and their associated blocks.
static bool AirportHasBlock(Aircraft *v, const AirportFTA *current_pos, const AirportFTAClass *apc)
returns true if the road ahead is busy, eg.
static bool AirportSetBlocks(Aircraft *v, const AirportFTA *current_pos, const AirportFTAClass *apc)
"reserve" a block for the plane
Station * GetTargetAirportIfValid(const Aircraft *v)
Returns aircraft's target station if v->target_airport is a valid station with airport.
static void AircraftLandAirplane(Aircraft *v)
Aircraft touched down at the landing strip.
int GetAircraftHoldMaxAltitude(const Aircraft *v)
Gets the maximum 'flight level' for the holding pattern of the aircraft, in pixels 'z_pos' 0,...
static bool FreeTerminal(Aircraft *v, uint8_t i, uint8_t last_terminal)
Find a free terminal or helipad, and if available, assign it.
static constexpr uint16_t SPEED_LIMIT_BROKEN
Maximum speed of an aircraft that is broken.
static void AircraftHandleDestTooFar(Aircraft *v, bool too_far)
Handle the 'dest too far' flag and the corresponding news message for aircraft.
static bool AircraftController(Aircraft *v)
Controls the movement of an aircraft.
void AircraftLeaveHangar(Aircraft *v, Direction exit_dir)
Aircraft is about to leave the hangar.
static bool AirportFindFreeHelipad(Aircraft *v, const AirportFTAClass *apc)
Find a free helipad, and assign it if available.
static constexpr uint16_t SPEED_LIMIT_NONE
No environmental speed limit. Speed limit is type dependent.
static void AircraftEntersTerminal(Aircraft *v)
Aircraft arrives at a terminal.
HelicopterRotorStates
Helicopter rotor animation states.
static void AircraftEventHandler_AtTerminal(Aircraft *v, const AirportFTAClass *apc)
At one of the Airport's Terminals.
void SetAircraftPosition(Aircraft *v, int x, int y, int z)
Set aircraft position.
static int UpdateAircraftSpeed(Aircraft *v, uint speed_limit=SPEED_LIMIT_NONE, bool hard_limit=true)
Sets the new speed for an aircraft.
static void MaybeCrashAirplane(Aircraft *v)
Decide whether aircraft v should crash.
static constexpr uint16_t SPEED_LIMIT_HOLD
Maximum speed of an aircraft that flies the holding pattern.
void GetAircraftFlightLevelBounds(const Vehicle *v, int *min_level, int *max_level)
Get the 'flight level' bounds, in pixels from 'z_pos' 0 for a particular vehicle for normal flight si...
static bool HandleCrashedAircraft(Aircraft *v)
Handle crashed aircraft v.
void UpdateAircraftCache(Aircraft *v, bool update_range)
Update cached values of an aircraft.
static AircraftStateHandler *const _aircraft_state_handlers[]
Array of handler functions for each target of the aircraft.
static void AircraftEventHandler_EnterHangar(Aircraft *v, const AirportFTAClass *apc)
Aircraft arrived in an airport hangar.
CommandCost CmdBuildAircraft(DoCommandFlags flags, TileIndex tile, const Engine *e, Vehicle **ret)
Build an aircraft.
static bool AirportFindFreeTerminal(Aircraft *v, const AirportFTAClass *apc)
Find a free terminal, and assign it if available.
void HandleAircraftEnterHangar(Aircraft *v)
Handle Aircraft specific tasks when an Aircraft enters a hangar.
static constexpr uint16_t SPEED_LIMIT_APPROACH
Maximum speed of an aircraft on finals.
static void CrashAirplane(Aircraft *v)
Bring the aircraft in a crashed state, create the explosion animation, and create a news item about t...
static constexpr uint16_t SPEED_LIMIT_TAXI
Special velocities for aircraft.
void AircraftStateHandler(Aircraft *v, const AirportFTAClass *apc)
Signature of the aircraft handler function.
Command definitions related to aircraft.
uint8_t GetVehiclePosOnBuild(TileIndex hangar_tile)
Get the vehicle position when an aircraft is build at the given tile.
Definition airport.cpp:197
const AirportFTAClass * GetAirport(const uint8_t airport_type)
Get the finite state machine of an airport type.
Definition airport.cpp:186
AirportMovingData RotateAirportMovingData(const AirportMovingData *orig, Direction rotation, uint num_tiles_x, uint num_tiles_y)
Rotate the airport moving data to another rotation.
Definition airport.cpp:81
static const uint MAX_TERMINALS
Some airport-related constants.
Definition airport.h:17
AirportBlock
Movement Blocks on Airports blocks (eg_airport_flags).
Definition airport.h:90
@ Zeppeliner
Block for the zeppeliner disaster vehicle.
@ Term2
Block belonging to terminal 2.
@ AirportClosed
Dummy block for indicating a closed airport.
@ Term5
Block belonging to terminal 5.
@ Term6
Block belonging to terminal 6.
@ Term4
Block belonging to terminal 4.
@ Helipad3
Block belonging to helipad 3.
@ Term7
Block belonging to terminal 7.
@ Helipad1
Block belonging to helipad 1.
@ Term3
Block belonging to terminal 3.
@ Term1
Block belonging to terminal 1.
@ Helipad2
Block belonging to helipad 2.
@ Term8
Block belonging to terminal 8.
@ HeliRaise
Helicopter take-off.
@ HeliLower
Helicopter landing.
@ Land
Landing onto landing strip.
@ Takeoff
Takeoff movement.
@ SlowTurn
Turn slowly (mostly used in the air).
@ Brake
Taxiing at the airport.
@ NoSpeedClamp
No speed restrictions.
@ Hold
Holding pattern movement (above the airport).
@ ExactPosition
Go exactly to the destination coordinates.
AirportMovementStates
Movement States on Airports (headings target)
Definition airport.h:62
@ HELITAKEOFF
Helicopter wants to leave the airport.
Definition airport.h:76
@ TERM4
Heading for terminal 4.
Definition airport.h:68
@ STARTTAKEOFF
Airplane has arrived at a runway for take-off.
Definition airport.h:74
@ HELIPAD2
Heading for helipad 2.
Definition airport.h:72
@ ENDTAKEOFF
Airplane has reached end-point of the take-off runway.
Definition airport.h:75
@ TERM5
Heading for terminal 5.
Definition airport.h:69
@ TERM6
Heading for terminal 6.
Definition airport.h:70
@ TERM3
Heading for terminal 3.
Definition airport.h:67
@ TERM8
Heading for terminal 8.
Definition airport.h:83
@ HELIPAD3
Heading for helipad 3.
Definition airport.h:84
@ HELIPAD1
Heading for helipad 1.
Definition airport.h:71
@ TERM2
Heading for terminal 2.
Definition airport.h:66
@ HANGAR
Heading for hangar.
Definition airport.h:64
@ FLYING
Vehicle is flying in the air.
Definition airport.h:77
@ TAKEOFF
Airplane wants to leave the airport.
Definition airport.h:73
@ HELILANDING
Helicopter wants to land.
Definition airport.h:80
@ TO_ALL
Go in this direction for every target.
Definition airport.h:63
@ ENDLANDING
Airplane wants to finish landing.
Definition airport.h:79
@ HELIENDLANDING
Helicopter wants to finish landing.
Definition airport.h:81
@ TERM1
Heading for terminal 1.
Definition airport.h:65
@ LANDING
Airplane wants to land.
Definition airport.h:78
@ TERM7
Heading for terminal 7.
Definition airport.h:82
@ TERMGROUP
Aircraft is looking for a free terminal in a terminalgroup.
Definition airport.h:86
@ AT_DUMMY
Dummy airport.
Definition airport.h:43
@ AT_OILRIG
Oilrig airport.
Definition airport.h:38
Class for backupping variables and making sure they are restored later.
@ BuiltAsPrototype
Vehicle is a prototype (accepted as exclusive preview).
static constexpr uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
constexpr T SetBit(T &x, const uint8_t y)
Set a bit in a variable.
constexpr bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
constexpr T ClrBit(T &x, const uint8_t y)
Clears a bit in a variable.
uint8_t CargoType
Cargo slots to indicate a cargo type within a game.
Definition cargo_type.h:21
bool IsValidCargoType(CargoType cargo)
Test whether cargo type is not INVALID_CARGO.
Definition cargo_type.h:104
Cheats _cheats
All the cheats.
Definition cheat.cpp:16
Types related to cheating.
static void NewEvent(CompanyID company, ScriptEvent *event)
Queue a new event for an AI.
Definition ai_core.cpp:235
constexpr bool All(const Timpl &other) const
Test if all of the values are set.
constexpr bool Test(Tvalue_type value) const
Test if the value-th bit is set.
constexpr Timpl & Reset()
Reset all bits.
constexpr Timpl & Flip(Tvalue_type value)
Flip the value-th bit.
constexpr Timpl & Set()
Set all bits.
constexpr bool Any(const Timpl &other) const
Test if any of the given values are set.
Common return value for all commands.
Money GetCost() const
The costs as made up to this moment.
bool Failed() const
Did this command fail?
Container for an encoded string, created by GetEncodedString.
uint16_t reliability_spd_dec
Speed of reliability decay between services (per day).
Definition engine_base.h:50
const GRFFile * GetGRF() const
Retrieve the NewGRF the engine is tied to.
uint DetermineCapacity(const Vehicle *v, uint16_t *mail_capacity=nullptr) const
Determines capacity of a given vehicle from scratch.
Definition engine.cpp:204
EngineFlags flags
Flags of the engine.
Definition engine_base.h:57
uint8_t original_image_index
Original vehicle image index, thus the image index of the overridden vehicle.
Definition engine_base.h:61
TimerGameCalendar::Date GetLifeLengthInDays() const
Returns the vehicle's (not model's!) life length in days.
Definition engine.cpp:446
CargoType GetDefaultCargoType() const
Determines the default cargo type of an engine.
Definition engine_base.h:94
uint16_t reliability
Current reliability of the engine.
Definition engine_base.h:49
Enum-as-bit-set wrapper.
static void NewEvent(class ScriptEvent *event)
Queue a new event for a Game Script.
RAII class for measuring multi-step elements of performance.
static constexpr TimerGameTick::Ticks DAY_TICKS
1 day is 74 ticks; TimerGameCalendar::date_fract used to be uint16_t and incremented by 885.
static Date date
Current date in days (day counter).
static Year year
Current year, starting at 0.
static constexpr int DAYS_IN_YEAR
days per year
static Date date
Current date in days (day counter).
uint Truncate(uint max_move=UINT_MAX)
Truncates the cargo in this list to the given amount.
Functions related to commands.
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
@ Execute
execute the given command
Definition of stuff that is very close to a company, like the company struct itself.
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
CompanyID _current_company
Company currently doing an action.
void SubtractMoneyFromCompanyFract(CompanyID company, const CommandCost &cst)
Subtract money from a company, including the money fraction.
Functions related to companies.
static constexpr Owner OWNER_NONE
The tile has no ownership.
#define Debug(category, level, format_string,...)
Output a line of debugging information.
Definition debug.h:37
DirDiff DirDifference(Direction d0, Direction d1)
Calculate the difference between two directions.
Direction ChangeDir(Direction d, DirDiff delta)
Change a direction by a given difference.
DiagDirection ChangeDiagDir(DiagDirection d, DiagDirDiff delta)
Applies a difference on a DiagDirection.
DiagDirDiff DiagDirDifference(DiagDirection d0, DiagDirection d1)
Calculate the difference between two DiagDirection values.
DiagDirection DirToDiagDir(Direction dir)
Convert a Direction to a DiagDirection.
DirDiff
Enumeration for the difference between two directions.
@ DIRDIFF_45LEFT
Angle of 45 degrees left.
@ DIRDIFF_REVERSE
One direction is the opposite of the other one.
@ DIRDIFF_45RIGHT
Angle of 45 degrees right.
@ DIRDIFF_SAME
Both directions faces to the same direction.
Direction
Defines the 8 directions on the map.
@ DIR_N
North.
@ DIR_SE
Southeast.
@ DIR_NE
Northeast.
@ DIR_W
West.
@ DIR_E
East.
DiagDirection
Enumeration for diagonal directions.
@ DIAGDIR_NE
Northeast, upper right on your monitor.
@ DIAGDIR_NW
Northwest.
@ DIAGDIR_SE
Southeast.
@ DIAGDIR_SW
Southwest.
All disaster vehicles.
Money GetPrice(Price index, uint cost_factor, const GRFFile *grf_file, int shift)
Determine a certain price.
Definition economy.cpp:940
@ EXPENSES_AIRCRAFT_RUN
Running costs aircraft.
EffectVehicle * CreateEffectVehicleRel(const Vehicle *v, int x, int y, int z, EffectVehicleType type)
Create an effect vehicle above a particular vehicle.
Functions related to effect vehicles.
@ EV_EXPLOSION_SMALL
Various explosions.
@ EV_EXPLOSION_LARGE
Various explosions.
@ EV_BREAKDOWN_SMOKE_AIRCRAFT
Smoke of broken aircraft.
Base class for engines.
@ AIR_CTOL
Conventional Take Off and Landing, i.e. planes.
@ ExclusivePreview
This vehicle is in the exclusive preview stage, either being used or being offered to a company.
Error reporting related functions.
fluid_settings_t * settings
FluidSynth settings handle.
Types for recording game performance data.
@ PFE_GL_AIRCRAFT
Time spent processing aircraft.
Base functions for all Games.
uint32_t SpriteID
The number of a sprite, without mapping bits and colourtables.
Definition gfx_type.h:17
uint32_t PaletteID
The number of the palette.
Definition gfx_type.h:18
int GetSlopePixelZ(int x, int y, bool ground_vehicle)
Return world Z coordinate of a given point of a tile.
Functions related to OTTD's landscape.
@ Random
Randomise borders.
uint DistanceSquare(TileIndex t0, TileIndex t1)
Gets the 'Square' distance between the two given tiles.
Definition map.cpp:175
static TileIndex TileVirtXY(uint x, uint y)
Get a tile from the virtual XY-coordinate.
Definition map_func.h:416
static uint TileY(TileIndex tile)
Get the Y component of a tile.
Definition map_func.h:437
static uint TileX(TileIndex tile)
Get the X component of a tile.
Definition map_func.h:427
constexpr T abs(const T a)
Returns the absolute value of (scalar) variable.
Definition math_func.hpp:23
constexpr uint CeilDiv(uint a, uint b)
Computes ceil(a / b) for non-negative a and b.
constexpr T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition math_func.hpp:79
NewGRF handling of airport tiles.
Functions for NewGRF engines.
@ PROP_AIRCRAFT_RANGE
Aircraft range.
@ PROP_AIRCRAFT_RUNNING_COST_FACTOR
Yearly runningcost.
@ PROP_AIRCRAFT_SPEED
Max. speed: 1 unit = 8 mph = 12.8 km-ish/h.
@ PROP_AIRCRAFT_CARGO_AGE_PERIOD
Number of ticks before carried cargo is aged.
bool PlayVehicleSound(const Vehicle *v, VehicleSoundEvent event, bool force)
Checks whether a NewGRF wants to play a different vehicle sound effect.
Functions related to NewGRF provided sounds.
@ VSE_TOUCHDOWN
Whenever a plane touches down.
@ VSE_START
Vehicle starting, i.e. leaving, the station.
Functions related to news.
void AddVehicleNewsItem(EncodedString &&headline, NewsType type, VehicleID vehicle, StationID station=StationID::Invalid())
Adds a newsitem referencing a vehicle.
Definition news_func.h:30
void AddVehicleAdviceNewsItem(AdviceType advice_type, EncodedString &&headline, VehicleID vehicle)
Adds a vehicle-advice news item.
Definition news_func.h:40
void DeleteVehicleNews(VehicleID vid, AdviceType advice_type=AdviceType::Invalid)
Delete news with a given advice type about a vehicle.
NewsType
Type of news.
Definition news_type.h:29
@ ArrivalCompany
First vehicle arrived for company.
@ AccidentOther
An accident or disaster has occurred.
@ ArrivalOther
First vehicle arrived for competitor.
@ Accident
An accident or disaster has occurred.
@ AircraftDestinationTooFar
Next (order) destination is too far for the aircraft type.
bool ProcessOrders(Vehicle *v)
Handle the orders of a vehicle and determine the next place to go to if needed.
void CheckOrders(const Vehicle *v)
Check the orders of a vehicle, to see if there are invalid orders and stuff.
void RemoveOrderFromAllVehicles(OrderType type, DestinationID destination, bool hangar)
Removes an order from all vehicles.
@ NearestDepot
Send the vehicle to the nearest depot.
@ PartOfOrders
This depot order is because of a regular order.
@ Service
This depot order is because of the servicing limit.
Pseudo random number generator.
bool Chance16R(const uint32_t a, const uint32_t b, uint32_t &r, const std::source_location location=std::source_location::current())
Flips a coin with a given probability and saves the randomize-number in a variable.
A number of safeguards to prevent using unsafe methods.
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition settings.cpp:61
ClientSettings _settings_client
The current settings for this game.
Definition settings.cpp:60
Functions related to sound.
static const uint ORIGINAL_SAMPLE_COUNT
The number of sounds in the original sample.cat.
Definition sound_type.h:124
@ SND_18_TAKEOFF_HELICOPTER
22 == 0x16 Takeoff: helicopter
Definition sound_type.h:69
@ SND_17_SKID_PLANE
21 == 0x15 Plane landing / touching ground
Definition sound_type.h:68
@ SND_12_EXPLOSION
16 == 0x10 Destruction, crashes, disasters, ...
Definition sound_type.h:63
static const PaletteID PALETTE_CRASH
Recolour sprite greying of crashed vehicles.
Definition sprites.h:1619
Base classes/functions for stations.
void ModifyStationRatingAround(TileIndex tile, Owner owner, int amount, uint radius)
Forcibly modify station ratings near a given tile.
StationID GetStationIndex(Tile t)
Get StationID from a tile.
Definition station_map.h:28
@ HVOT_AIRCRAFT
Station has seen an aircraft.
@ Airport
Station with an airport.
@ AirplaneTouchdown
Triggered when an airplane (not a helicopter) touches down at the airport (for single tile).
Definition of base types and functions in a cross-platform compatible way.
#define lengthof(array)
Return the length of an fixed size array.
Definition stdafx.h:271
EncodedString GetEncodedString(StringID str)
Encode a string with no parameters into an encoded string.
Definition strings.cpp:90
Functions related to OTTD's strings.
uint32_t cached_max_range_sqr
Cached squared maximum range.
Definition aircraft.h:65
uint16_t cached_max_range
Cached maximum range.
Definition aircraft.h:66
Information about a aircraft vehicle.
uint16_t max_speed
Maximum speed (1 unit = 8 mph = 12.8 km-ish/h)
uint8_t mail_capacity
Mail capacity (bags).
uint8_t subtype
Type of aircraft.
uint16_t passenger_capacity
Passenger capacity (persons).
uint16_t max_range
Maximum range of this aircraft.
Aircraft, helicopters, rotors and their shadows belong to this class.
Definition aircraft.h:72
bool Tick() override
Calls the tick handler of the vehicle.
uint8_t pos
Next desired position of the aircraft.
Definition aircraft.h:74
uint8_t state
State of the airport.
Definition aircraft.h:77
uint8_t flags
Aircraft flags.
Definition aircraft.h:81
Money GetRunningCost() const override
Gets the running cost of a vehicle.
void UpdateDeltaXY() override
Updates the x and y offsets and the size of the sprite used for this vehicle.
uint8_t number_consecutive_turns
Protection to prevent the aircraft of making a lot of turns in order to reach a specific point.
Definition aircraft.h:79
void OnNewEconomyDay() override
Economy day handler.
uint Crash(bool flooded=false) override
Crash the (whole) vehicle chain.
void GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const override
Gets the sprite to show for the given direction.
void OnNewCalendarDay() override
Calendar day handler.
uint8_t turn_counter
Ticks between each turn to prevent > 45 degree turns.
Definition aircraft.h:80
TileIndex GetOrderStationLocation(StationID station) override
Determine the location for the station where the vehicle goes to next.
bool IsNormalAircraft() const
Check if the aircraft type is a normal flying device; eg not a rotor or a shadow.
Definition aircraft.h:120
void MarkDirty() override
Marks the vehicles to be redrawn and updates cached variables.
uint8_t previous_pos
Previous desired position of the aircraft.
Definition aircraft.h:75
StationID targetairport
Airport to go to next.
Definition aircraft.h:76
ClosestDepot FindClosestDepot() override
Find the closest depot for this vehicle and tell us the location, DestinationID and whether we should...
uint16_t crashed_counter
Timer for handling crash animations.
Definition aircraft.h:73
Finite sTate mAchine (FTA) of an airport.
Definition airport.h:159
const uint8_t num_helipads
Number of helipads on this airport. When 0 helicopters will go to normal terminals.
Definition airport.h:193
const AirportMovingData * MovingData(uint8_t position) const
Get movement data at a position.
Definition airport.h:184
@ Airplanes
Can planes land on this airport type?
@ ShortStrip
This airport has a short landing strip, dangerous for fast aircraft.
uint8_t delta_z
Z adjustment for helicopter pads.
Definition airport.h:197
std::vector< AirportFTA > layout
state machine for airport
Definition airport.h:191
const uint8_t * terminals
Array with the number of terminal groups, followed by the number of terminals in each group.
Definition airport.h:192
const uint8_t * entry_points
when an airplane arrives at this airport, enter it at position entry_point, index depends on directio...
Definition airport.h:196
uint8_t nofelements
number of positions the airport consists of
Definition airport.h:195
Flags flags
Flags for this airport type.
Definition airport.h:194
Internal structure used in openttd - Finite sTate mAchine --> FTA.
Definition airport.h:148
std::unique_ptr< AirportFTA > next
possible extra movement choices from this position
Definition airport.h:151
uint8_t heading
heading (current orders), guiding an airplane to its target on an airport
Definition airport.h:155
AirportBlocks blocks
bitmap of blocks that could be reserved
Definition airport.h:152
uint8_t position
the position that an airplane is at
Definition airport.h:153
uint8_t next_position
next position from this position
Definition airport.h:154
A single location on an airport where aircraft can move to.
Definition airport.h:136
int16_t x
x-coordinate of the destination.
Definition airport.h:137
AirportMovingDataFlags flags
special flags when moving towards the destination.
Definition airport.h:139
int16_t y
y-coordinate of the destination.
Definition airport.h:138
Direction direction
Direction to turn the aircraft after reaching the destination.
Definition airport.h:140
AirportBlocks blocks
stores which blocks on the airport are taken. was 16 bit earlier on, then 32
bool HasHangar() const
Check if this airport has at least one hangar.
Direction rotation
How this airport is rotated.
uint8_t type
Type of this airport,.
Direction GetHangarExitDirection(TileIndex tile) const
Get the exit direction of the hangar at a specific tile.
const AirportFTAClass * GetFTA() const
Get the finite-state machine for this airport or the finite-state machine for the dummy airport in ca...
TileIndex GetHangarTile(uint hangar_num) const
Get the first tile of the given hangar.
Class to backup a specific variable and restore it later.
std::string name
Name of vehicle.
TimerGameTick::Ticks current_order_time
How many ticks have passed since this order started.
VehicleFlags vehicle_flags
Used for gradual loading and other miscellaneous things (.
TileIndex xy
Base tile of the station.
Owner owner
The owner of this station.
static BaseStation * GetByTile(TileIndex tile)
Get the base station belonging to a specific tile.
VehicleType type
Type of vehicle.
bool value
tells if the bool cheat is active or not
Definition cheat_type.h:18
Cheat no_jetcrash
no jet will crash on small airports anymore
Definition cheat_type.h:31
SoundSettings sound
sound effect settings
Structure to return information about the closest depot location, and whether it could be found.
T x
X coordinate.
T y
Y coordinate.
T z
Z coordinate.
Disasters, like submarines, skyrangers and their shadows, belong to this class.
uint16_t cargo_age_period
Number of ticks before carried cargo is aged.
VehicleSettings vehicle
options for vehicles
OrderSettings order
settings related to orders
Position information of a vehicle after it moved.
TileIndex new_tile
Tile of the vehicle after moving.
int y
x and y position of the vehicle after moving
TileIndex old_tile
Current tile of the vehicle.
Stores station stats for a single cargo.
static uint MaxY()
Gets the maximum Y coordinate within the map, including MP_VOID.
Definition map_func.h:308
static uint MaxX()
Gets the maximum X coordinate within the map, including MP_VOID.
Definition map_func.h:299
Combination of aircraft state for going to a certain terminal and the airport flag for that terminal ...
AirportBlock blocks
Bitmask in the airport flags that need to be free for this terminal.
AirportMovementStates state
Aircraft movement state when going to this terminal.
VehicleSpriteSeq sprite_seq
Vehicle appearance.
bool serviceathelipad
service helicopters at helipads automatically (no need to send to depot)
OrderDepotTypeFlags GetDepotOrderType() const
What caused us going to the depot?
Definition order_base.h:150
DestinationID GetDestination() const
Gets the destination of this order.
Definition order_base.h:99
bool IsType(OrderType type) const
Check whether this order is of the given type.
Definition order_base.h:66
OrderType GetType() const
Get the type of order of this order.
Definition order_base.h:72
void MakeDummy()
Makes this order a Dummy order.
void MakeGoToDepot(DestinationID destination, OrderDepotTypeFlags order, OrderNonStopFlags non_stop_type=OrderNonStopFlag::NoIntermediate, OrderDepotActionFlags action={}, CargoType cargo=CARGO_NO_REFIT)
Makes this order a Go To Depot order.
Definition order_cmd.cpp:73
OrderDepotActionFlags GetDepotActionType() const
What are we going to do when in the depot.
Definition order_base.h:152
void Free()
'Free' the order
Definition order_cmd.cpp:47
uint16_t w
The width of the area.
TileIndex tile
The base tile of the area.
uint16_t h
The height of the area.
static Pool::IterateWrapper< Titem > Iterate(size_t from=0)
Returns an iterable ensemble of all valid Titem.
static T * Create(Targs &&... args)
Creates a new T-object in the associated pool.
static Titem * Get(auto index)
Returns Titem with given index.
const Tindex index
Index of this pool item.
Specification of a rectangle with absolute coordinates of all edges.
int Width() const
Get width of Rect.
int Height() const
Get height of Rect.
bool disaster
Play disaster and accident sounds.
static Pool::IterateWrapper< Station > Iterate(size_t from=0)
Returns an iterable ensemble of all valid stations of type T.
static Station * Get(auto index)
Gets station with given index.
static Station * GetIfValid(auto index)
Returns station if the index is a valid index for this station type.
T * Next() const
Get next vehicle in the chain.
static Aircraft * From(Vehicle *v)
Converts a Vehicle to SpecializedVehicle with type checking.
void UpdateViewport(bool force_update, bool update_delta)
Update vehicle sprite- and position caches.
Coord3D< int8_t > origin
Position of northern corner within tile.
Definition sprite.h:19
Coord3D< uint8_t > extent
Size of bounding box.
Definition sprite.h:20
Station data structure.
std::array< GoodsEntry, NUM_CARGO > goods
Goods at this station.
Airport airport
Tile area the airport covers.
uint16_t cached_cargo_age_period
Number of ticks before carried cargo is aged.
uint16_t cached_max_speed
Maximum speed of the consist (minimum of the max speed of all vehicles in the consist).
uint8_t plane_crashes
number of plane crashes, 0 = none, 1 = reduced, 2 = normal
uint8_t plane_speed
divisor for speed of aircraft
Sprite sequence for a vehicle part.
bool IsValid() const
Check whether the sequence contains any sprites.
void GetBounds(Rect *bounds) const
Determine shared bounds of all sprites.
Definition vehicle.cpp:114
void Set(SpriteID sprite)
Assign a single sprite to the sequence.
void CopyWithoutPalette(const VehicleSpriteSeq &src)
Copy data from another sprite sequence, while dropping all recolouring information.
void Draw(int x, int y, PaletteID default_pal, bool force_pal) const
Draw the sprite sequence.
Definition vehicle.cpp:142
Vehicle data structure.
EngineID engine_type
The type of engine used for this vehicle.
int32_t z_pos
z coordinate.
Direction direction
facing
const Engine * GetEngine() const
Retrieves the engine of the vehicle.
Definition vehicle.cpp:719
virtual uint Crash(bool flooded=false)
Crash the (whole) vehicle chain.
Definition vehicle.cpp:291
virtual bool IsChainInDepot() const
Check whether the whole vehicle chain is in the depot.
VehicleCargoList cargo
The cargo this vehicle is carrying.
TimerGameEconomy::Date date_of_last_service
Last economy date the vehicle had a service at a depot.
uint16_t cargo_cap
total capacity
StationID last_loading_station
Last station the vehicle has stopped at and could possibly leave from with any cargo loaded.
uint8_t subtype
subtype (Filled with values from AircraftSubType/DisasterSubType/EffectVehicleType/GroundVehicleSubty...
uint16_t random_bits
Bits used for randomized variational spritegroups.
uint8_t day_counter
Increased by one for each day.
void HandleLoading(bool mode=false)
Handle the loading of the vehicle; when not it skips through dummy orders and does nothing in all oth...
Definition vehicle.cpp:2408
Money profit_this_year
Profit this year << 8, low 8 bits are fract.
SpriteID colourmap
NOSAVE: cached colour mapping.
uint8_t breakdown_ctr
Counter for managing breakdown events.
uint GetOldAdvanceSpeed(uint speed)
Determines the effective direction-specific vehicle movement speed.
VehStates vehstatus
Status.
TimerGameCalendar::Date date_of_last_service_newgrf
Last calendar date the vehicle had a service at a depot, unchanged by the date cheat to protect again...
uint8_t subspeed
fractional speed
void LeaveUnbunchingDepot()
Leave an unbunching depot and calculate the next departure time for shared order vehicles.
Definition vehicle.cpp:2487
void GetNextStoppingStation(std::vector< StationID > &next_station) const
Get the next station the vehicle will stop at.
CargoType cargo_type
type of cargo this vehicle is carrying
uint8_t acceleration
used by train & aircraft
Order current_order
The current order (+ status, like: loading)
Vehicle * Next() const
Get the next vehicle of this vehicle.
int32_t y_pos
y coordinate.
int32_t x_pos
x coordinate.
uint16_t refit_cap
Capacity left over from before last refit.
VehicleCache vcache
Cache of often used vehicle values.
SpriteBounds bounds
Bounding box of vehicle.
void BeginLoading()
Prepare everything to begin the loading when arriving at a station.
Definition vehicle.cpp:2184
uint8_t spritenum
currently displayed sprite index 0xfd == custom sprite, 0xfe == custom second head sprite 0xff == res...
uint16_t cur_speed
current speed
bool IsWaitingForUnbunching() const
Check whether a vehicle inside a depot is waiting for unbunching.
Definition vehicle.cpp:2534
void SetNext(Vehicle *next)
Set the next vehicle of this vehicle.
Definition vehicle.cpp:2928
uint8_t breakdowns_since_last_service
Counter for the amount of breakdowns.
TimerGameCalendar::Date max_age
Maximum age.
MutableSpriteCache sprite_cache
Cache of sprites and values related to recalculating them, see MutableSpriteCache.
uint16_t reliability
Reliability.
bool HandleBreakdown()
Handle all of the aspects of a vehicle breakdown This includes adding smoke and sounds,...
Definition vehicle.cpp:1333
uint8_t progress
The percentage (if divided by 256) this vehicle already crossed the tile unit.
void UpdatePositionAndViewport()
Update the position of the vehicle, and update the viewport.
Definition vehicle.cpp:1746
uint16_t reliability_spd_dec
Reliability decrease speed.
uint8_t tick_counter
Increased by one for each tick.
TileIndex tile
Current tile index.
void UpdatePosition()
Update the position of the vehicle.
Definition vehicle.cpp:1663
StationID last_station_visited
The last station we stopped at.
void InvalidateNewGRFCacheOfChain()
Invalidates cached NewGRF variables of all vehicles in the chain (after the current vehicle)
TimerGameCalendar::Year build_year
Year the vehicle has been built.
Owner owner
Which company owns the vehicle?
bool NeedsAutomaticServicing() const
Checks if the current order should be interrupted for a service-in-depot order.
Definition vehicle.cpp:283
uint8_t running_ticks
Number of ticks this vehicle was not stopped this day.
static uint TileHeight(Tile tile)
Returns the height of a tile.
Definition tile_map.h:29
int GetTileMaxPixelZ(TileIndex tile)
Get top height of the tile.
Definition tile_map.h:312
constexpr TileIndex INVALID_TILE
The very nice invalid tile marker.
Definition tile_type.h:95
static constexpr uint TILE_SIZE
Tile size in world coordinates.
Definition tile_type.h:15
static constexpr uint TILE_HEIGHT
Height of a height level in world coordinate AND in pixels in ZOOM_BASE.
Definition tile_type.h:18
Definition of the game-calendar-timer.
Definition of the game-economy-timer.
void VehicleEnterDepot(Vehicle *v)
Vehicle entirely entered the depot, update its status, orders, vehicle windows, service it,...
Definition vehicle.cpp:1521
void VehicleServiceInDepot(Vehicle *v)
Service a vehicle and all subsequent vehicles in the consist.
Definition vehicle.cpp:178
GetNewVehiclePosResult GetNewVehiclePos(const Vehicle *v)
Get position information of a vehicle when moving one pixel in the direction it is facing.
Definition vehicle.cpp:1766
void DecreaseVehicleValue(Vehicle *v)
Decrease the value of a vehicle.
Definition vehicle.cpp:1271
void EconomyAgeVehicle(Vehicle *v)
Update economy age of a vehicle.
Definition vehicle.cpp:1399
bool CanVehicleUseStation(EngineID engine_type, const Station *st)
Can this station be used by the given engine type?
Definition vehicle.cpp:3047
void AgeVehicle(Vehicle *v)
Update age of a vehicle.
Definition vehicle.cpp:1411
@ Unclickable
Vehicle is not clickable by the user (shadow vehicles).
@ Crashed
Vehicle is crashed.
@ Shadow
Vehicle is a shadow vehicle.
@ AircraftBroken
Aircraft is broken down.
@ Hidden
Vehicle is not visible.
@ DefaultPalette
Use default vehicle palette.
@ Stopped
Vehicle is stopped by the player.
Command definitions for vehicles.
Functions related to vehicles.
EngineImageType
Visualisation contexts of vehicles and engines.
@ EIT_ON_MAP
Vehicle drawn in viewport.
@ VEH_AIRCRAFT
Aircraft vehicle type.
DepotCommandFlag
Flags for goto depot commands.
@ Service
The vehicle will leave the depot right after arrival (service only)
@ WID_VV_START_STOP
Start or stop this vehicle, and show information about the current state.
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting)
Definition window.cpp:3208
void InvalidateWindowData(WindowClass cls, WindowNumber number, int data, bool gui_scope)
Mark window data of the window of a given class and specific window number as invalid (in need of re-...
Definition window.cpp:3300
void SetWindowWidgetDirty(WindowClass cls, WindowNumber number, WidgetID widget_index)
Mark a particular widget in a particular window as dirty (in need of repainting)
Definition window.cpp:3194
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
Definition window.cpp:3178
Window functions not directly related to making/drawing windows.
@ WC_VEHICLE_DEPOT
Depot view; Window numbers:
@ WC_VEHICLE_DETAILS
Vehicle details; Window numbers:
@ WC_VEHICLE_VIEW
Vehicle view; Window numbers:
@ WC_AIRCRAFT_LIST
Aircraft list; Window numbers:
Functions related to zooming.
int ScaleSpriteTrad(int value)
Scale traditional pixel dimensions to GUI zoom level, for drawing sprites.
Definition zoom_func.h:107
int UnScaleGUI(int value)
Short-hand to apply GUI zoom level.
Definition zoom_func.h:77