OpenTTD
aircraft_cmd.cpp
Go to the documentation of this file.
1 /* $Id: aircraft_cmd.cpp 26951 2014-10-04 16:40:23Z peter1138 $ */
2 
3 /*
4  * This file is part of OpenTTD.
5  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8  */
9 
15 #include "stdafx.h"
16 #include "aircraft.h"
17 #include "landscape.h"
18 #include "news_func.h"
19 #include "newgrf_engine.h"
20 #include "newgrf_sound.h"
21 #include "spritecache.h"
22 #include "strings_func.h"
23 #include "command_func.h"
24 #include "window_func.h"
25 #include "date_func.h"
26 #include "vehicle_func.h"
27 #include "sound_func.h"
28 #include "cheat_type.h"
29 #include "company_base.h"
30 #include "ai/ai.hpp"
31 #include "game/game.hpp"
32 #include "company_func.h"
33 #include "effectvehicle_func.h"
34 #include "station_base.h"
35 #include "engine_base.h"
36 #include "core/random_func.hpp"
37 #include "core/backup_type.hpp"
38 #include "zoom_func.h"
39 #include "disaster_vehicle.h"
40 
41 #include "table/strings.h"
42 
43 #include "safeguards.h"
44 
46 {
47  this->x_offs = -1;
48  this->y_offs = -1;
49  this->x_extent = 2;
50  this->y_extent = 2;
51 
52  switch (this->subtype) {
53  default: NOT_REACHED();
54 
55  case AIR_AIRCRAFT:
56  case AIR_HELICOPTER:
57  switch (this->state) {
58  default: break;
59  case ENDTAKEOFF:
60  case LANDING:
61  case HELILANDING:
62  case FLYING:
63  this->x_extent = 24;
64  this->y_extent = 24;
65  break;
66  }
67  this->z_extent = 5;
68  break;
69 
70  case AIR_SHADOW:
71  this->z_extent = 1;
72  this->x_offs = 0;
73  this->y_offs = 0;
74  break;
75 
76  case AIR_ROTOR:
77  this->z_extent = 1;
78  break;
79  }
80 }
81 
82 static bool AirportMove(Aircraft *v, const AirportFTAClass *apc);
83 static bool AirportSetBlocks(Aircraft *v, const AirportFTA *current_pos, const AirportFTAClass *apc);
84 static bool AirportHasBlock(Aircraft *v, const AirportFTA *current_pos, const AirportFTAClass *apc);
85 static bool AirportFindFreeTerminal(Aircraft *v, const AirportFTAClass *apc);
86 static bool AirportFindFreeHelipad(Aircraft *v, const AirportFTAClass *apc);
87 static void CrashAirplane(Aircraft *v);
88 
89 static const SpriteID _aircraft_sprite[] = {
90  0x0EB5, 0x0EBD, 0x0EC5, 0x0ECD,
91  0x0ED5, 0x0EDD, 0x0E9D, 0x0EA5,
92  0x0EAD, 0x0EE5, 0x0F05, 0x0F0D,
93  0x0F15, 0x0F1D, 0x0F25, 0x0F2D,
94  0x0EED, 0x0EF5, 0x0EFD, 0x0F35,
95  0x0E9D, 0x0EA5, 0x0EAD, 0x0EB5,
96  0x0EBD, 0x0EC5
97 };
98 
99 template <>
100 bool IsValidImageIndex<VEH_AIRCRAFT>(uint8 image_index)
101 {
102  return image_index < lengthof(_aircraft_sprite);
103 }
104 
107  HRS_ROTOR_STOPPED,
108  HRS_ROTOR_MOVING_1,
109  HRS_ROTOR_MOVING_2,
110  HRS_ROTOR_MOVING_3,
111 };
112 
120 static StationID FindNearestHangar(const Aircraft *v)
121 {
122  const Station *st;
123  uint best = 0;
124  StationID index = INVALID_STATION;
125  TileIndex vtile = TileVirtXY(v->x_pos, v->y_pos);
126  const AircraftVehicleInfo *avi = AircraftVehInfo(v->engine_type);
127 
128  FOR_ALL_STATIONS(st) {
129  if (st->owner != v->owner || !(st->facilities & FACIL_AIRPORT)) continue;
130 
131  const AirportFTAClass *afc = st->airport.GetFTA();
132  if (!st->airport.HasHangar() || (
133  /* don't crash the plane if we know it can't land at the airport */
135  (avi->subtype & AIR_FAST) &&
137  continue;
138  }
139 
140  /* v->tile can't be used here, when aircraft is flying v->tile is set to 0 */
141  uint distance = DistanceSquare(vtile, st->airport.tile);
142  if (v->acache.cached_max_range_sqr != 0) {
143  /* Check if our current destination can be reached from the depot airport. */
144  const Station *cur_dest = GetTargetAirportIfValid(v);
145  if (cur_dest != NULL && DistanceSquare(st->airport.tile, cur_dest->airport.tile) > v->acache.cached_max_range_sqr) continue;
146  }
147  if (distance < best || index == INVALID_STATION) {
148  best = distance;
149  index = st->index;
150  }
151  }
152  return index;
153 }
154 
156 {
157  uint8 spritenum = this->spritenum;
158 
159  if (is_custom_sprite(spritenum)) {
160  SpriteID sprite = GetCustomVehicleSprite(this, direction, image_type);
161  if (sprite != 0) return sprite;
162 
163  spritenum = this->GetEngine()->original_image_index;
164  }
165 
166  assert(IsValidImageIndex<VEH_AIRCRAFT>(spritenum));
167  return direction + _aircraft_sprite[spritenum];
168 }
169 
170 SpriteID GetRotorImage(const Aircraft *v, EngineImageType image_type)
171 {
172  assert(v->subtype == AIR_HELICOPTER);
173 
174  const Aircraft *w = v->Next()->Next();
175  if (is_custom_sprite(v->spritenum)) {
176  SpriteID sprite = GetCustomRotorSprite(v, false, image_type);
177  if (sprite != 0) return sprite;
178  }
179 
180  /* Return standard rotor sprites if there are no custom sprites for this helicopter */
181  return SPR_ROTOR_STOPPED + w->state;
182 }
183 
184 static SpriteID GetAircraftIcon(EngineID engine, EngineImageType image_type)
185 {
186  const Engine *e = Engine::Get(engine);
187  uint8 spritenum = e->u.air.image_index;
188 
189  if (is_custom_sprite(spritenum)) {
190  SpriteID sprite = GetCustomVehicleIcon(engine, DIR_W, image_type);
191  if (sprite != 0) return sprite;
192 
193  spritenum = e->original_image_index;
194  }
195 
196  assert(IsValidImageIndex<VEH_AIRCRAFT>(spritenum));
197  return DIR_W + _aircraft_sprite[spritenum];
198 }
199 
200 void DrawAircraftEngine(int left, int right, int preferred_x, int y, EngineID engine, PaletteID pal, EngineImageType image_type)
201 {
202  SpriteID sprite = GetAircraftIcon(engine, image_type);
203  const Sprite *real_sprite = GetSprite(sprite, ST_NORMAL);
204  preferred_x = Clamp(preferred_x, left - UnScaleByZoom(real_sprite->x_offs, ZOOM_LVL_GUI), right - UnScaleByZoom(real_sprite->width, ZOOM_LVL_GUI) - UnScaleByZoom(real_sprite->x_offs, ZOOM_LVL_GUI));
205  DrawSprite(sprite, pal, preferred_x, y);
206 
207  if (!(AircraftVehInfo(engine)->subtype & AIR_CTOL)) {
208  SpriteID rotor_sprite = GetCustomRotorIcon(engine, image_type);
209  if (rotor_sprite == 0) rotor_sprite = SPR_ROTOR_STOPPED;
210  DrawSprite(rotor_sprite, PAL_NONE, preferred_x, y - UnScaleByZoom(4 * 5, ZOOM_LVL_GUI));
211  }
212 }
213 
223 void GetAircraftSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type)
224 {
225  const Sprite *spr = GetSprite(GetAircraftIcon(engine, image_type), ST_NORMAL);
226 
227  width = UnScaleByZoom(spr->width, ZOOM_LVL_GUI);
228  height = UnScaleByZoom(spr->height, ZOOM_LVL_GUI);
229  xoffs = UnScaleByZoom(spr->x_offs, ZOOM_LVL_GUI);
230  yoffs = UnScaleByZoom(spr->y_offs, ZOOM_LVL_GUI);
231 }
232 
242 CommandCost CmdBuildAircraft(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **ret)
243 {
244  const AircraftVehicleInfo *avi = &e->u.air;
245  const Station *st = Station::GetByTile(tile);
246 
247  /* Prevent building aircraft types at places which can't handle them */
248  if (!CanVehicleUseStation(e->index, st)) return CMD_ERROR;
249 
250  /* Make sure all aircraft end up in the first tile of the hangar. */
251  tile = st->airport.GetHangarTile(st->airport.GetHangarNum(tile));
252 
253  if (flags & DC_EXEC) {
254  Aircraft *v = new Aircraft(); // aircraft
255  Aircraft *u = new Aircraft(); // shadow
256  *ret = v;
257 
258  v->direction = DIR_SE;
259 
260  v->owner = u->owner = _current_company;
261 
262  v->tile = tile;
263 
264  uint x = TileX(tile) * TILE_SIZE + 5;
265  uint y = TileY(tile) * TILE_SIZE + 3;
266 
267  v->x_pos = u->x_pos = x;
268  v->y_pos = u->y_pos = y;
269 
270  u->z_pos = GetSlopePixelZ(x, y);
271  v->z_pos = u->z_pos + 1;
272 
275 
276  v->spritenum = avi->image_index;
277 
278  v->cargo_cap = avi->passenger_capacity;
279  v->refit_cap = 0;
280  u->cargo_cap = avi->mail_capacity;
281  u->refit_cap = 0;
282 
284  u->cargo_type = CT_MAIL;
285 
286  v->name = NULL;
287  v->last_station_visited = INVALID_STATION;
288  v->last_loading_station = INVALID_STATION;
289 
290  v->acceleration = avi->acceleration;
291  v->engine_type = e->index;
292  u->engine_type = e->index;
293 
294  v->subtype = (avi->subtype & AIR_CTOL ? AIR_AIRCRAFT : AIR_HELICOPTER);
296 
297  u->subtype = AIR_SHADOW;
299 
300  v->reliability = e->reliability;
302  v->max_age = e->GetLifeLengthInDays();
303 
304  _new_vehicle_id = v->index;
305 
306  v->pos = GetVehiclePosOnBuild(tile);
307 
308  v->state = HANGAR;
309  v->previous_pos = v->pos;
310  v->targetairport = GetStationIndex(tile);
311  v->SetNext(u);
312 
313  v->SetServiceInterval(Company::Get(_current_company)->settings.vehicle.servint_aircraft);
314 
316  v->build_year = u->build_year = _cur_year;
317 
318  v->cur_image = u->cur_image = SPR_IMG_QUERY;
319 
322 
323  v->vehicle_flags = 0;
325  v->SetServiceIntervalIsPercent(Company::Get(_current_company)->settings.vehicle.servint_ispercent);
326 
328 
329  v->cargo_cap = e->DetermineCapacity(v, &u->cargo_cap);
330 
332 
333  UpdateAircraftCache(v, true);
334 
335  v->UpdatePosition();
336  u->UpdatePosition();
337 
338  /* Aircraft with 3 vehicles (chopper)? */
339  if (v->subtype == AIR_HELICOPTER) {
340  Aircraft *w = new Aircraft();
341  w->engine_type = e->index;
342  w->direction = DIR_N;
343  w->owner = _current_company;
344  w->x_pos = v->x_pos;
345  w->y_pos = v->y_pos;
346  w->z_pos = v->z_pos + ROTOR_Z_OFFSET;
348  w->spritenum = 0xFF;
349  w->subtype = AIR_ROTOR;
350  w->cur_image = SPR_ROTOR_STOPPED;
352  /* Use rotor's air.state to store the rotor animation frame */
353  w->state = HRS_ROTOR_STOPPED;
355 
356  u->SetNext(w);
357  w->UpdatePosition();
358  }
359  }
360 
361  return CommandCost();
362 }
363 
364 
365 bool Aircraft::FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
366 {
367  const Station *st = GetTargetAirportIfValid(this);
368  /* If the station is not a valid airport or if it has no hangars */
369  if (st == NULL || !st->airport.HasHangar()) {
370  /* the aircraft has to search for a hangar on its own */
371  StationID station = FindNearestHangar(this);
372 
373  if (station == INVALID_STATION) return false;
374 
375  st = Station::Get(station);
376  }
377 
378  if (location != NULL) *location = st->xy;
379  if (destination != NULL) *destination = st->index;
380 
381  return true;
382 }
383 
384 static void CheckIfAircraftNeedsService(Aircraft *v)
385 {
386  if (Company::Get(v->owner)->settings.vehicle.servint_aircraft == 0 || !v->NeedsAutomaticServicing()) return;
387  if (v->IsChainInDepot()) {
389  return;
390  }
391 
392  /* When we're parsing conditional orders and the like
393  * we don't want to consider going to a depot too. */
394  if (!v->current_order.IsType(OT_GOTO_DEPOT) && !v->current_order.IsType(OT_GOTO_STATION)) return;
395 
397 
398  assert(st != NULL);
399 
400  /* only goto depot if the target airport has a depot */
401  if (st->airport.HasHangar() && CanVehicleUseStation(v, st)) {
404  } else if (v->current_order.IsType(OT_GOTO_DEPOT)) {
407  }
408 }
409 
411 {
412  const Engine *e = this->GetEngine();
413  uint cost_factor = GetVehicleProperty(this, PROP_AIRCRAFT_RUNNING_COST_FACTOR, e->u.air.running_cost);
414  return GetPrice(PR_RUNNING_AIRCRAFT, cost_factor, e->GetGRF());
415 }
416 
418 {
419  if (!this->IsNormalAircraft()) return;
420 
421  if ((++this->day_counter & 7) == 0) DecreaseVehicleValue(this);
422 
423  CheckOrders(this);
424 
425  CheckVehicleBreakdown(this);
426  AgeVehicle(this);
427  CheckIfAircraftNeedsService(this);
428 
429  if (this->running_ticks == 0) return;
430 
432 
433  this->profit_this_year -= cost.GetCost();
434  this->running_ticks = 0;
435 
437 
440 }
441 
442 static void HelicopterTickHandler(Aircraft *v)
443 {
444  Aircraft *u = v->Next()->Next();
445 
446  if (u->vehstatus & VS_HIDDEN) return;
447 
448  /* if true, helicopter rotors do not rotate. This should only be the case if a helicopter is
449  * loading/unloading at a terminal or stopped */
450  if (v->current_order.IsType(OT_LOADING) || (v->vehstatus & VS_STOPPED)) {
451  if (u->cur_speed != 0) {
452  u->cur_speed++;
453  if (u->cur_speed >= 0x80 && u->state == HRS_ROTOR_MOVING_3) {
454  u->cur_speed = 0;
455  }
456  }
457  } else {
458  if (u->cur_speed == 0) {
459  u->cur_speed = 0x70;
460  }
461  if (u->cur_speed >= 0x50) {
462  u->cur_speed--;
463  }
464  }
465 
466  int tick = ++u->tick_counter;
467  int spd = u->cur_speed >> 4;
468 
469  SpriteID img;
470  if (spd == 0) {
471  u->state = HRS_ROTOR_STOPPED;
472  img = GetRotorImage(v, EIT_ON_MAP);
473  if (u->cur_image == img) return;
474  } else if (tick >= spd) {
475  u->tick_counter = 0;
476  u->state++;
477  if (u->state > HRS_ROTOR_MOVING_3) u->state = HRS_ROTOR_MOVING_1;
478  img = GetRotorImage(v, EIT_ON_MAP);
479  } else {
480  return;
481  }
482 
483  u->cur_image = img;
484 
486 }
487 
495 void SetAircraftPosition(Aircraft *v, int x, int y, int z)
496 {
497  v->x_pos = x;
498  v->y_pos = y;
499  v->z_pos = z;
500 
501  v->UpdatePosition();
502  v->UpdateViewport(true, false);
503  if (v->subtype == AIR_HELICOPTER) v->Next()->Next()->cur_image = GetRotorImage(v, EIT_ON_MAP);
504 
505  Aircraft *u = v->Next();
506 
507  int safe_x = Clamp(x, 0, MapMaxX() * TILE_SIZE);
508  int safe_y = Clamp(y - 1, 0, MapMaxY() * TILE_SIZE);
509  u->x_pos = x;
510  u->y_pos = y - ((v->z_pos - GetSlopePixelZ(safe_x, safe_y)) >> 3);
511 
512  safe_y = Clamp(u->y_pos, 0, MapMaxY() * TILE_SIZE);
513  u->z_pos = GetSlopePixelZ(safe_x, safe_y);
514  u->cur_image = v->cur_image;
515 
517 
518  u = u->Next();
519  if (u != NULL) {
520  u->x_pos = x;
521  u->y_pos = y;
522  u->z_pos = z + ROTOR_Z_OFFSET;
523 
525  }
526 }
527 
533 {
534  v->subspeed = 0;
535  v->progress = 0;
536 
537  Aircraft *u = v->Next();
538  u->vehstatus |= VS_HIDDEN;
539  u = u->Next();
540  if (u != NULL) {
541  u->vehstatus |= VS_HIDDEN;
542  u->cur_speed = 0;
543  }
544 
545  SetAircraftPosition(v, v->x_pos, v->y_pos, v->z_pos);
546 }
547 
548 static void PlayAircraftSound(const Vehicle *v)
549 {
550  if (!PlayVehicleSound(v, VSE_START)) {
551  SndPlayVehicleFx(AircraftVehInfo(v->engine_type)->sfx, v);
552  }
553 }
554 
555 
562 void UpdateAircraftCache(Aircraft *v, bool update_range)
563 {
564  uint max_speed = GetVehicleProperty(v, PROP_AIRCRAFT_SPEED, 0);
565  if (max_speed != 0) {
566  /* Convert from original units to km-ish/h */
567  max_speed = (max_speed * 128) / 10;
568 
569  v->vcache.cached_max_speed = max_speed;
570  } else {
571  /* Use the default max speed of the vehicle. */
572  v->vcache.cached_max_speed = AircraftVehInfo(v->engine_type)->max_speed;
573  }
574 
575  /* Update cargo aging period. */
576  v->vcache.cached_cargo_age_period = GetVehicleProperty(v, PROP_AIRCRAFT_CARGO_AGE_PERIOD, EngInfo(v->engine_type)->cargo_age_period);
577  Aircraft *u = v->Next(); // Shadow for mail
578  u->vcache.cached_cargo_age_period = GetVehicleProperty(u, PROP_AIRCRAFT_CARGO_AGE_PERIOD, EngInfo(u->engine_type)->cargo_age_period);
579 
580  /* Update aircraft range. */
581  if (update_range) {
582  v->acache.cached_max_range = GetVehicleProperty(v, PROP_AIRCRAFT_RANGE, AircraftVehInfo(v->engine_type)->max_range);
583  /* Squared it now so we don't have to do it later all the time. */
584  v->acache.cached_max_range_sqr = v->acache.cached_max_range * v->acache.cached_max_range;
585  }
586 }
587 
588 
597  SPEED_LIMIT_NONE = 0xFFFF,
598 };
599 
607 static int UpdateAircraftSpeed(Aircraft *v, uint speed_limit = SPEED_LIMIT_NONE, bool hard_limit = true)
608 {
616  uint spd = v->acceleration * 77;
617  byte t;
618 
619  /* Adjust speed limits by plane speed factor to prevent taxiing
620  * and take-off speeds being too low. */
621  speed_limit *= _settings_game.vehicle.plane_speed;
622 
623  if (v->vcache.cached_max_speed < speed_limit) {
624  if (v->cur_speed < speed_limit) hard_limit = false;
625  speed_limit = v->vcache.cached_max_speed;
626  }
627 
628  v->subspeed = (t = v->subspeed) + (byte)spd;
629 
630  /* Aircraft's current speed is used twice so that very fast planes are
631  * forced to slow down rapidly in the short distance needed. The magic
632  * value 16384 was determined to give similar results to the old speed/48
633  * method at slower speeds. This also results in less reduction at slow
634  * speeds to that aircraft do not get to taxi speed straight after
635  * touchdown. */
636  if (!hard_limit && v->cur_speed > speed_limit) {
637  speed_limit = v->cur_speed - max(1, ((v->cur_speed * v->cur_speed) / 16384) / _settings_game.vehicle.plane_speed);
638  }
639 
640  spd = min(v->cur_speed + (spd >> 8) + (v->subspeed < t), speed_limit);
641 
642  /* adjust speed for broken vehicles */
643  if (v->vehstatus & VS_AIRCRAFT_BROKEN) spd = min(spd, SPEED_LIMIT_BROKEN);
644 
645  /* updates statusbar only if speed have changed to save CPU time */
646  if (spd != v->cur_speed) {
647  v->cur_speed = spd;
649  }
650 
651  /* Adjust distance moved by plane speed setting */
653 
654  /* Convert direction-independent speed into direction-dependent speed. (old movement method) */
655  spd = v->GetOldAdvanceSpeed(spd);
656 
657  spd += v->progress;
658  v->progress = (byte)spd;
659  return spd >> 8;
660 }
661 
670 {
671  int safe_x = Clamp(v->x_pos, 0, MapMaxX() * TILE_SIZE);
672  int safe_y = Clamp(v->y_pos, 0, MapMaxY() * TILE_SIZE);
673  return TileHeight(TileVirtXY(safe_x, safe_y)) * TILE_HEIGHT;
674 }
675 
686 void GetAircraftFlightLevelBounds(const Vehicle *v, int *min_level, int *max_level)
687 {
688  int base_altitude = GetTileHeightBelowAircraft(v);
689  if (v->type == VEH_AIRCRAFT && Aircraft::From(v)->subtype == AIR_HELICOPTER) {
691  }
692 
693  /* Make sure eastbound and westbound planes do not "crash" into each
694  * other by providing them with vertical separation
695  */
696  switch (v->direction) {
697  case DIR_N:
698  case DIR_NE:
699  case DIR_E:
700  case DIR_SE:
701  base_altitude += 10;
702  break;
703 
704  default: break;
705  }
706 
707  /* Make faster planes fly higher so that they can overtake slower ones */
708  base_altitude += min(20 * (v->vcache.cached_max_speed / 200) - 90, 0);
709 
710  if (min_level != NULL) *min_level = base_altitude + AIRCRAFT_MIN_FLYING_ALTITUDE;
711  if (max_level != NULL) *max_level = base_altitude + AIRCRAFT_MAX_FLYING_ALTITUDE;
712 }
713 
722 {
723  int tile_height = GetTileHeightBelowAircraft(v);
724 
726 }
727 
728 template <class T>
729 int GetAircraftFlightLevel(T *v, bool takeoff)
730 {
731  /* Aircraft is in flight. We want to enforce it being somewhere
732  * between the minimum and the maximum allowed altitude. */
733  int aircraft_min_altitude;
734  int aircraft_max_altitude;
735  GetAircraftFlightLevelBounds(v, &aircraft_min_altitude, &aircraft_max_altitude);
736  int aircraft_middle_altitude = (aircraft_min_altitude + aircraft_max_altitude) / 2;
737 
738  /* If those assumptions would be violated, aircrafts would behave fairly strange. */
739  assert(aircraft_min_altitude < aircraft_middle_altitude);
740  assert(aircraft_middle_altitude < aircraft_max_altitude);
741 
742  int z = v->z_pos;
743  if (z < aircraft_min_altitude ||
744  (HasBit(v->flags, VAF_IN_MIN_HEIGHT_CORRECTION) && z < aircraft_middle_altitude)) {
745  /* Ascend. And don't fly into that mountain right ahead.
746  * And avoid our aircraft become a stairclimber, so if we start
747  * correcting altitude, then we stop correction not too early. */
749  z += takeoff ? 2 : 1;
750  } else if (!takeoff && (z > aircraft_max_altitude ||
751  (HasBit(v->flags, VAF_IN_MAX_HEIGHT_CORRECTION) && z > aircraft_middle_altitude))) {
752  /* Descend lower. You are an aircraft, not an space ship.
753  * And again, don't stop correcting altitude too early. */
755  z--;
756  } else if (HasBit(v->flags, VAF_IN_MIN_HEIGHT_CORRECTION) && z >= aircraft_middle_altitude) {
757  /* Now, we have corrected altitude enough. */
759  } else if (HasBit(v->flags, VAF_IN_MAX_HEIGHT_CORRECTION) && z <= aircraft_middle_altitude) {
760  /* Now, we have corrected altitude enough. */
762  }
763 
764  return z;
765 }
766 
767 template int GetAircraftFlightLevel(DisasterVehicle *v, bool takeoff);
768 
783 static byte AircraftGetEntryPoint(const Aircraft *v, const AirportFTAClass *apc, Direction rotation)
784 {
785  assert(v != NULL);
786  assert(apc != NULL);
787 
788  /* In the case the station doesn't exit anymore, set target tile 0.
789  * It doesn't hurt much, aircraft will go to next order, nearest hangar
790  * or it will simply crash in next tick */
791  TileIndex tile = 0;
792 
793  const Station *st = Station::GetIfValid(v->targetairport);
794  if (st != NULL) {
795  /* Make sure we don't go to INVALID_TILE if the airport has been removed. */
796  tile = (st->airport.tile != INVALID_TILE) ? st->airport.tile : st->xy;
797  }
798 
799  int delta_x = v->x_pos - TileX(tile) * TILE_SIZE;
800  int delta_y = v->y_pos - TileY(tile) * TILE_SIZE;
801 
802  DiagDirection dir;
803  if (abs(delta_y) < abs(delta_x)) {
804  /* We are northeast or southwest of the airport */
805  dir = delta_x < 0 ? DIAGDIR_NE : DIAGDIR_SW;
806  } else {
807  /* We are northwest or southeast of the airport */
808  dir = delta_y < 0 ? DIAGDIR_NW : DIAGDIR_SE;
809  }
810  dir = ChangeDiagDir(dir, (DiagDirDiff)ReverseDiagDir(DirToDiagDir(rotation)));
811  return apc->entry_points[dir];
812 }
813 
814 
815 static void MaybeCrashAirplane(Aircraft *v);
816 
825 {
826  int count;
827 
828  /* NULL if station is invalid */
829  const Station *st = Station::GetIfValid(v->targetairport);
830  /* INVALID_TILE if there is no station */
831  TileIndex tile = INVALID_TILE;
832  Direction rotation = DIR_N;
833  uint size_x = 1, size_y = 1;
834  if (st != NULL) {
835  if (st->airport.tile != INVALID_TILE) {
836  tile = st->airport.tile;
837  rotation = st->airport.rotation;
838  size_x = st->airport.w;
839  size_y = st->airport.h;
840  } else {
841  tile = st->xy;
842  }
843  }
844  /* DUMMY if there is no station or no airport */
845  const AirportFTAClass *afc = tile == INVALID_TILE ? GetAirport(AT_DUMMY) : st->airport.GetFTA();
846 
847  /* prevent going to INVALID_TILE if airport is deleted. */
848  if (st == NULL || st->airport.tile == INVALID_TILE) {
849  /* Jump into our "holding pattern" state machine if possible */
850  if (v->pos >= afc->nofelements) {
851  v->pos = v->previous_pos = AircraftGetEntryPoint(v, afc, DIR_N);
852  } else if (v->targetairport != v->current_order.GetDestination()) {
853  /* If not possible, just get out of here fast */
854  v->state = FLYING;
857  /* get aircraft back on running altitude */
858  SetAircraftPosition(v, v->x_pos, v->y_pos, GetAircraftFlightLevel(v));
859  return false;
860  }
861  }
862 
863  /* get airport moving data */
864  const AirportMovingData amd = RotateAirportMovingData(afc->MovingData(v->pos), rotation, size_x, size_y);
865 
866  int x = TileX(tile) * TILE_SIZE;
867  int y = TileY(tile) * TILE_SIZE;
868 
869  /* Helicopter raise */
870  if (amd.flag & AMED_HELI_RAISE) {
871  Aircraft *u = v->Next()->Next();
872 
873  /* Make sure the rotors don't rotate too fast */
874  if (u->cur_speed > 32) {
875  v->cur_speed = 0;
876  if (--u->cur_speed == 32) {
877  if (!PlayVehicleSound(v, VSE_START)) {
878  SndPlayVehicleFx(SND_18_HELICOPTER, v);
879  }
880  }
881  } else {
882  u->cur_speed = 32;
883  count = UpdateAircraftSpeed(v);
884  if (count > 0) {
885  v->tile = 0;
886 
887  int z_dest;
888  GetAircraftFlightLevelBounds(v, &z_dest, NULL);
889 
890  /* Reached altitude? */
891  if (v->z_pos >= z_dest) {
892  v->cur_speed = 0;
893  return true;
894  }
895  SetAircraftPosition(v, v->x_pos, v->y_pos, min(v->z_pos + count, z_dest));
896  }
897  }
898  return false;
899  }
900 
901  /* Helicopter landing. */
902  if (amd.flag & AMED_HELI_LOWER) {
903  if (st == NULL) {
904  /* FIXME - AircraftController -> if station no longer exists, do not land
905  * helicopter will circle until sign disappears, then go to next order
906  * what to do when it is the only order left, right now it just stays in 1 place */
907  v->state = FLYING;
910  return false;
911  }
912 
913  /* Vehicle is now at the airport. */
914  v->tile = tile;
915 
916  /* Find altitude of landing position. */
917  int z = GetSlopePixelZ(x, y) + 1 + afc->delta_z;
918 
919  if (z == v->z_pos) {
920  Vehicle *u = v->Next()->Next();
921 
922  /* Increase speed of rotors. When speed is 80, we've landed. */
923  if (u->cur_speed >= 80) return true;
924  u->cur_speed += 4;
925  } else {
926  count = UpdateAircraftSpeed(v);
927  if (count > 0) {
928  if (v->z_pos > z) {
929  SetAircraftPosition(v, v->x_pos, v->y_pos, max(v->z_pos - count, z));
930  } else {
931  SetAircraftPosition(v, v->x_pos, v->y_pos, min(v->z_pos + count, z));
932  }
933  }
934  }
935  return false;
936  }
937 
938  /* Get distance from destination pos to current pos. */
939  uint dist = abs(x + amd.x - v->x_pos) + abs(y + amd.y - v->y_pos);
940 
941  /* Need exact position? */
942  if (!(amd.flag & AMED_EXACTPOS) && dist <= (amd.flag & AMED_SLOWTURN ? 8U : 4U)) return true;
943 
944  /* At final pos? */
945  if (dist == 0) {
946  /* Change direction smoothly to final direction. */
947  DirDiff dirdiff = DirDifference(amd.direction, v->direction);
948  /* if distance is 0, and plane points in right direction, no point in calling
949  * UpdateAircraftSpeed(). So do it only afterwards */
950  if (dirdiff == DIRDIFF_SAME) {
951  v->cur_speed = 0;
952  return true;
953  }
954 
955  if (!UpdateAircraftSpeed(v, SPEED_LIMIT_TAXI)) return false;
956 
958  v->cur_speed >>= 1;
959 
960  SetAircraftPosition(v, v->x_pos, v->y_pos, v->z_pos);
961  return false;
962  }
963 
966  if ((v->vehstatus & VS_CRASHED) != 0) return false;
967  }
968 
969  uint speed_limit = SPEED_LIMIT_TAXI;
970  bool hard_limit = true;
971 
972  if (amd.flag & AMED_NOSPDCLAMP) speed_limit = SPEED_LIMIT_NONE;
973  if (amd.flag & AMED_HOLD) { speed_limit = SPEED_LIMIT_HOLD; hard_limit = false; }
974  if (amd.flag & AMED_LAND) { speed_limit = SPEED_LIMIT_APPROACH; hard_limit = false; }
975  if (amd.flag & AMED_BRAKE) { speed_limit = SPEED_LIMIT_TAXI; hard_limit = false; }
976 
977  count = UpdateAircraftSpeed(v, speed_limit, hard_limit);
978  if (count == 0) return false;
979 
980  if (v->turn_counter != 0) v->turn_counter--;
981 
982  do {
983 
985 
986  if (dist < 4 || (amd.flag & AMED_LAND)) {
987  /* move vehicle one pixel towards target */
988  gp.x = (v->x_pos != (x + amd.x)) ?
989  v->x_pos + ((x + amd.x > v->x_pos) ? 1 : -1) :
990  v->x_pos;
991  gp.y = (v->y_pos != (y + amd.y)) ?
992  v->y_pos + ((y + amd.y > v->y_pos) ? 1 : -1) :
993  v->y_pos;
994 
995  /* Oilrigs must keep v->tile as st->airport.tile, since the landing pad is in a non-airport tile */
996  gp.new_tile = (st->airport.type == AT_OILRIG) ? st->airport.tile : TileVirtXY(gp.x, gp.y);
997 
998  } else {
999 
1000  /* Turn. Do it slowly if in the air. */
1001  Direction newdir = GetDirectionTowards(v, x + amd.x, y + amd.y);
1002  if (newdir != v->direction) {
1003  if (amd.flag & AMED_SLOWTURN && v->number_consecutive_turns < 8 && v->subtype == AIR_AIRCRAFT) {
1004  if (v->turn_counter == 0 || newdir == v->last_direction) {
1005  if (newdir == v->last_direction) {
1006  v->number_consecutive_turns = 0;
1007  } else {
1009  }
1011  v->last_direction = v->direction;
1012  v->direction = newdir;
1013  }
1014 
1015  /* Move vehicle. */
1016  gp = GetNewVehiclePos(v);
1017  } else {
1018  v->cur_speed >>= 1;
1019  v->direction = newdir;
1020 
1021  /* When leaving a terminal an aircraft often goes to a position
1022  * directly in front of it. If it would move while turning it
1023  * would need an two extra turns to end up at the correct position.
1024  * To make it easier just disallow all moving while turning as
1025  * long as an aircraft is on the ground. */
1026  gp.x = v->x_pos;
1027  gp.y = v->y_pos;
1028  gp.new_tile = gp.old_tile = v->tile;
1029  }
1030  } else {
1031  v->number_consecutive_turns = 0;
1032  /* Move vehicle. */
1033  gp = GetNewVehiclePos(v);
1034  }
1035  }
1036 
1037  v->tile = gp.new_tile;
1038  /* If vehicle is in the air, use tile coordinate 0. */
1039  if (amd.flag & (AMED_TAKEOFF | AMED_SLOWTURN | AMED_LAND)) v->tile = 0;
1040 
1041  /* Adjust Z for land or takeoff? */
1042  int z = v->z_pos;
1043 
1044  if (amd.flag & AMED_TAKEOFF) {
1045  z = GetAircraftFlightLevel(v, true);
1046  } else if (amd.flag & AMED_HOLD) {
1047  /* Let the plane drop from normal flight altitude to holding pattern altitude */
1048  if (z > GetAircraftHoldMaxAltitude(v)) z--;
1049  } else if ((amd.flag & AMED_SLOWTURN) && (amd.flag & AMED_NOSPDCLAMP)) {
1050  z = GetAircraftFlightLevel(v);
1051  }
1052 
1053  if (amd.flag & AMED_LAND) {
1054  if (st->airport.tile == INVALID_TILE) {
1055  /* Airport has been removed, abort the landing procedure */
1056  v->state = FLYING;
1059  /* get aircraft back on running altitude */
1060  SetAircraftPosition(v, gp.x, gp.y, GetAircraftFlightLevel(v));
1061  continue;
1062  }
1063 
1064  int curz = GetSlopePixelZ(x + amd.x, y + amd.y) + 1;
1065 
1066  /* We're not flying below our destination, right? */
1067  assert(curz <= z);
1068  int t = max(1U, dist - 4);
1069  int delta = z - curz;
1070 
1071  /* Only start lowering when we're sufficiently close for a 1:1 glide */
1072  if (delta >= t) {
1073  z -= CeilDiv(z - curz, t);
1074  }
1075  if (z < curz) z = curz;
1076  }
1077 
1078  /* We've landed. Decrease speed when we're reaching end of runway. */
1079  if (amd.flag & AMED_BRAKE) {
1080  int curz = GetSlopePixelZ(x, y) + 1;
1081 
1082  if (z > curz) {
1083  z--;
1084  } else if (z < curz) {
1085  z++;
1086  }
1087 
1088  }
1089 
1090  SetAircraftPosition(v, gp.x, gp.y, z);
1091  } while (--count != 0);
1092  return false;
1093 }
1094 
1100 {
1101  v->crashed_counter += 3;
1102 
1104 
1105  /* make aircraft crash down to the ground */
1106  if (v->crashed_counter < 500 && st == NULL && ((v->crashed_counter % 3) == 0) ) {
1107  int z = GetSlopePixelZ(Clamp(v->x_pos, 0, MapMaxX() * TILE_SIZE), Clamp(v->y_pos, 0, MapMaxY() * TILE_SIZE));
1108  v->z_pos -= 1;
1109  if (v->z_pos == z) {
1110  v->crashed_counter = 500;
1111  v->z_pos++;
1112  }
1113  }
1114 
1115  if (v->crashed_counter < 650) {
1116  uint32 r;
1117  if (Chance16R(1, 32, r)) {
1118  static const DirDiff delta[] = {
1120  };
1121 
1122  v->direction = ChangeDir(v->direction, delta[GB(r, 16, 2)]);
1123  SetAircraftPosition(v, v->x_pos, v->y_pos, v->z_pos);
1124  r = Random();
1126  GB(r, 0, 4) - 4,
1127  GB(r, 4, 4) - 4,
1128  GB(r, 8, 4),
1130  }
1131  } else if (v->crashed_counter >= 10000) {
1132  /* remove rubble of crashed airplane */
1133 
1134  /* clear runway-in on all airports, set by crashing plane
1135  * small airports use AIRPORT_BUSY, city airports use RUNWAY_IN_OUT_block, etc.
1136  * but they all share the same number */
1137  if (st != NULL) {
1138  CLRBITS(st->airport.flags, RUNWAY_IN_block);
1139  CLRBITS(st->airport.flags, RUNWAY_IN_OUT_block); // commuter airport
1140  CLRBITS(st->airport.flags, RUNWAY_IN2_block); // intercontinental
1141  }
1142 
1143  delete v;
1144 
1145  return false;
1146  }
1147 
1148  return true;
1149 }
1150 
1151 
1157 static void HandleAircraftSmoke(Aircraft *v, bool mode)
1158 {
1159  static const struct {
1160  int8 x;
1161  int8 y;
1162  } smoke_pos[] = {
1163  { 5, 5 },
1164  { 6, 0 },
1165  { 5, -5 },
1166  { 0, -6 },
1167  { -5, -5 },
1168  { -6, 0 },
1169  { -5, 5 },
1170  { 0, 6 }
1171  };
1172 
1173  if (!(v->vehstatus & VS_AIRCRAFT_BROKEN)) return;
1174 
1175  /* Stop smoking when landed */
1176  if (v->cur_speed < 10) {
1178  v->breakdown_ctr = 0;
1179  return;
1180  }
1181 
1182  /* Spawn effect et most once per Tick, i.e. !mode */
1183  if (!mode && (v->tick_counter & 0x0F) == 0) {
1185  smoke_pos[v->direction].x,
1186  smoke_pos[v->direction].y,
1187  2,
1189  );
1190  }
1191 }
1192 
1193 void HandleMissingAircraftOrders(Aircraft *v)
1194 {
1195  /*
1196  * We do not have an order. This can be divided into two cases:
1197  * 1) we are heading to an invalid station. In this case we must
1198  * find another airport to go to. If there is nowhere to go,
1199  * we will destroy the aircraft as it otherwise will enter
1200  * the holding pattern for the first airport, which can cause
1201  * the plane to go into an undefined state when building an
1202  * airport with the same StationID.
1203  * 2) we are (still) heading to a (still) valid airport, then we
1204  * can continue going there. This can happen when you are
1205  * changing the aircraft's orders while in-flight or in for
1206  * example a depot. However, when we have a current order to
1207  * go to a depot, we have to keep that order so the aircraft
1208  * actually stops.
1209  */
1210  const Station *st = GetTargetAirportIfValid(v);
1211  if (st == NULL) {
1212  Backup<CompanyByte> cur_company(_current_company, v->owner, FILE_LINE);
1214  cur_company.Restore();
1215 
1216  if (ret.Failed()) CrashAirplane(v);
1217  } else if (!v->current_order.IsType(OT_GOTO_DEPOT)) {
1218  v->current_order.Free();
1219  }
1220 }
1221 
1222 
1224 {
1225  /* Orders are changed in flight, ensure going to the right station. */
1226  if (this->state == FLYING) {
1228  }
1229 
1230  /* Aircraft do not use dest-tile */
1231  return 0;
1232 }
1233 
1235 {
1236  this->colourmap = PAL_NONE;
1237  this->UpdateViewport(true, false);
1238  if (this->subtype == AIR_HELICOPTER) this->Next()->Next()->cur_image = GetRotorImage(this, EIT_ON_MAP);
1239 }
1240 
1241 
1242 uint Aircraft::Crash(bool flooded)
1243 {
1244  uint pass = Vehicle::Crash(flooded) + 2; // pilots
1245  this->crashed_counter = flooded ? 9000 : 0; // max 10000, disappear pretty fast when flooded
1246 
1247  return pass;
1248 }
1249 
1254 static void CrashAirplane(Aircraft *v)
1255 {
1257 
1258  uint pass = v->Crash();
1259  SetDParam(0, pass);
1260 
1261  v->cargo.Truncate();
1262  v->Next()->cargo.Truncate();
1263  const Station *st = GetTargetAirportIfValid(v);
1264  StringID newsitem;
1265  if (st == NULL) {
1266  newsitem = STR_NEWS_PLANE_CRASH_OUT_OF_FUEL;
1267  } else {
1268  SetDParam(1, st->index);
1269  newsitem = STR_NEWS_AIRCRAFT_CRASH;
1270  }
1271 
1272  AI::NewEvent(v->owner, new ScriptEventVehicleCrashed(v->index, v->tile, st == NULL ? ScriptEventVehicleCrashed::CRASH_AIRCRAFT_NO_AIRPORT : ScriptEventVehicleCrashed::CRASH_PLANE_LANDING));
1273  Game::NewEvent(new ScriptEventVehicleCrashed(v->index, v->tile, st == NULL ? ScriptEventVehicleCrashed::CRASH_AIRCRAFT_NO_AIRPORT : ScriptEventVehicleCrashed::CRASH_PLANE_LANDING));
1274 
1275  AddVehicleNewsItem(newsitem, NT_ACCIDENT, v->index, st != NULL ? st->index : INVALID_STATION);
1276 
1277  ModifyStationRatingAround(v->tile, v->owner, -160, 30);
1278  if (_settings_client.sound.disaster) SndPlayVehicleFx(SND_12_EXPLOSION, v);
1279 }
1280 
1286 {
1287  if (_settings_game.vehicle.plane_crashes == 0) return;
1288 
1290 
1291  /* FIXME -- MaybeCrashAirplane -> increase crashing chances of very modern airplanes on smaller than AT_METROPOLITAN airports */
1292  uint32 prob = (0x4000 << _settings_game.vehicle.plane_crashes);
1294  (AircraftVehInfo(v->engine_type)->subtype & AIR_FAST) &&
1296  prob /= 20;
1297  } else {
1298  prob /= 1500;
1299  }
1300 
1301  if (GB(Random(), 0, 22) > prob) return;
1302 
1303  /* Crash the airplane. Remove all goods stored at the station. */
1304  for (CargoID i = 0; i < NUM_CARGO; i++) {
1305  st->goods[i].rating = 1;
1306  st->goods[i].cargo.Truncate();
1307  }
1308 
1309  CrashAirplane(v);
1310 }
1311 
1318 {
1319  if (v->current_order.IsType(OT_GOTO_DEPOT)) return;
1320 
1323 
1324  /* Check if station was ever visited before */
1325  if (!(st->had_vehicle_of_type & HVOT_AIRCRAFT)) {
1326  st->had_vehicle_of_type |= HVOT_AIRCRAFT;
1327  SetDParam(0, st->index);
1328  /* show newsitem of celebrating citizens */
1330  STR_NEWS_FIRST_AIRCRAFT_ARRIVAL,
1332  v->index,
1333  st->index
1334  );
1335  AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
1336  Game::NewEvent(new ScriptEventStationFirstVehicle(st->index, v->index));
1337  }
1338 
1339  v->BeginLoading();
1340 }
1341 
1347 {
1349 
1350  if (!PlayVehicleSound(v, VSE_TOUCHDOWN)) {
1351  SndPlayVehicleFx(SND_17_SKID_PLANE, v);
1352  }
1353 }
1354 
1355 
1358 {
1359  if (v->current_order.IsType(OT_GOTO_STATION) || v->current_order.IsType(OT_GOTO_DEPOT)) {
1361  }
1362 
1363  const Station *st = GetTargetAirportIfValid(v);
1364  const AirportFTAClass *apc = st == NULL ? GetAirport(AT_DUMMY) : st->airport.GetFTA();
1365  Direction rotation = st == NULL ? DIR_N : st->airport.rotation;
1366  v->pos = v->previous_pos = AircraftGetEntryPoint(v, apc, rotation);
1367 }
1368 
1378 {
1379  v->cur_speed = 0;
1380  v->subspeed = 0;
1381  v->progress = 0;
1382  v->direction = exit_dir;
1383  v->vehstatus &= ~VS_HIDDEN;
1384  {
1385  Vehicle *u = v->Next();
1386  u->vehstatus &= ~VS_HIDDEN;
1387 
1388  /* Rotor blades */
1389  u = u->Next();
1390  if (u != NULL) {
1391  u->vehstatus &= ~VS_HIDDEN;
1392  u->cur_speed = 80;
1393  }
1394  }
1395 
1397  SetAircraftPosition(v, v->x_pos, v->y_pos, v->z_pos);
1400 }
1401 
1405 static void AircraftEventHandler_EnterTerminal(Aircraft *v, const AirportFTAClass *apc)
1406 {
1408  v->state = apc->layout[v->pos].heading;
1409 }
1410 
1417 {
1418  VehicleEnterDepot(v);
1419  v->state = apc->layout[v->pos].heading;
1420 }
1421 
1428 {
1429  /* if we just arrived, execute EnterHangar first */
1430  if (v->previous_pos != v->pos) {
1432  return;
1433  }
1434 
1435  /* if we were sent to the depot, stay there */
1436  if (v->current_order.IsType(OT_GOTO_DEPOT) && (v->vehstatus & VS_STOPPED)) {
1437  v->current_order.Free();
1438  return;
1439  }
1440 
1441  if (!v->current_order.IsType(OT_GOTO_STATION) &&
1442  !v->current_order.IsType(OT_GOTO_DEPOT))
1443  return;
1444 
1445  /* We are leaving a hangar, but have to go to the exact same one; re-enter */
1446  if (v->current_order.IsType(OT_GOTO_DEPOT) && v->current_order.GetDestination() == v->targetairport) {
1447  VehicleEnterDepot(v);
1448  return;
1449  }
1450 
1451  /* if the block of the next position is busy, stay put */
1452  if (AirportHasBlock(v, &apc->layout[v->pos], apc)) return;
1453 
1454  /* We are already at the target airport, we need to find a terminal */
1455  if (v->current_order.GetDestination() == v->targetairport) {
1456  /* FindFreeTerminal:
1457  * 1. Find a free terminal, 2. Occupy it, 3. Set the vehicle's state to that terminal */
1458  if (v->subtype == AIR_HELICOPTER) {
1459  if (!AirportFindFreeHelipad(v, apc)) return; // helicopter
1460  } else {
1461  if (!AirportFindFreeTerminal(v, apc)) return; // airplane
1462  }
1463  } else { // Else prepare for launch.
1464  /* airplane goto state takeoff, helicopter to helitakeoff */
1465  v->state = (v->subtype == AIR_HELICOPTER) ? HELITAKEOFF : TAKEOFF;
1466  }
1467  const Station *st = Station::GetByTile(v->tile);
1469  AirportMove(v, apc);
1470 }
1471 
1474 {
1475  /* if we just arrived, execute EnterTerminal first */
1476  if (v->previous_pos != v->pos) {
1477  AircraftEventHandler_EnterTerminal(v, apc);
1478  /* on an airport with helipads, a helicopter will always land there
1479  * and get serviced at the same time - setting */
1481  if (v->subtype == AIR_HELICOPTER && apc->num_helipads > 0) {
1482  /* an excerpt of ServiceAircraft, without the invisibility stuff */
1485  v->reliability = v->GetEngine()->reliability;
1487  }
1488  }
1489  return;
1490  }
1491 
1492  if (v->current_order.IsType(OT_NOTHING)) return;
1493 
1494  /* if the block of the next position is busy, stay put */
1495  if (AirportHasBlock(v, &apc->layout[v->pos], apc)) return;
1496 
1497  /* airport-road is free. We either have to go to another airport, or to the hangar
1498  * ---> start moving */
1499 
1500  bool go_to_hangar = false;
1501  switch (v->current_order.GetType()) {
1502  case OT_GOTO_STATION: // ready to fly to another airport
1503  break;
1504  case OT_GOTO_DEPOT: // visit hangar for servicing, sale, etc.
1505  go_to_hangar = v->current_order.GetDestination() == v->targetairport;
1506  break;
1507  case OT_CONDITIONAL:
1508  /* In case of a conditional order we just have to wait a tick
1509  * longer, so the conditional order can actually be processed;
1510  * we should not clear the order as that makes us go nowhere. */
1511  return;
1512  default: // orders have been deleted (no orders), goto depot and don't bother us
1513  v->current_order.Free();
1514  go_to_hangar = Station::Get(v->targetairport)->airport.HasHangar();
1515  }
1516 
1517  if (go_to_hangar) {
1518  v->state = HANGAR;
1519  } else {
1520  /* airplane goto state takeoff, helicopter to helitakeoff */
1521  v->state = (v->subtype == AIR_HELICOPTER) ? HELITAKEOFF : TAKEOFF;
1522  }
1523  AirportMove(v, apc);
1524 }
1525 
1526 static void AircraftEventHandler_General(Aircraft *v, const AirportFTAClass *apc)
1527 {
1528  error("OK, you shouldn't be here, check your Airport Scheme!");
1529 }
1530 
1531 static void AircraftEventHandler_TakeOff(Aircraft *v, const AirportFTAClass *apc)
1532 {
1533  PlayAircraftSound(v); // play takeoffsound for airplanes
1534  v->state = STARTTAKEOFF;
1535 }
1536 
1537 static void AircraftEventHandler_StartTakeOff(Aircraft *v, const AirportFTAClass *apc)
1538 {
1539  v->state = ENDTAKEOFF;
1541 }
1542 
1543 static void AircraftEventHandler_EndTakeOff(Aircraft *v, const AirportFTAClass *apc)
1544 {
1545  v->state = FLYING;
1546  /* get the next position to go to, differs per airport */
1548 }
1549 
1550 static void AircraftEventHandler_HeliTakeOff(Aircraft *v, const AirportFTAClass *apc)
1551 {
1552  v->state = FLYING;
1554 
1555  /* get the next position to go to, differs per airport */
1557 
1558  /* Send the helicopter to a hangar if needed for replacement */
1559  if (v->NeedsAutomaticServicing()) {
1560  Backup<CompanyByte> cur_company(_current_company, v->owner, FILE_LINE);
1562  cur_company.Restore();
1563  }
1564 }
1565 
1566 static void AircraftEventHandler_Flying(Aircraft *v, const AirportFTAClass *apc)
1567 {
1569 
1570  /* Runway busy, not allowed to use this airstation or closed, circle. */
1571  if (CanVehicleUseStation(v, st) && (st->owner == OWNER_NONE || st->owner == v->owner) && !(st->airport.flags & AIRPORT_CLOSED_block)) {
1572  /* {32,FLYING,NOTHING_block,37}, {32,LANDING,N,33}, {32,HELILANDING,N,41},
1573  * if it is an airplane, look for LANDING, for helicopter HELILANDING
1574  * it is possible to choose from multiple landing runways, so loop until a free one is found */
1575  byte landingtype = (v->subtype == AIR_HELICOPTER) ? HELILANDING : LANDING;
1576  const AirportFTA *current = apc->layout[v->pos].next;
1577  while (current != NULL) {
1578  if (current->heading == landingtype) {
1579  /* save speed before, since if AirportHasBlock is false, it resets them to 0
1580  * we don't want that for plane in air
1581  * hack for speed thingie */
1582  uint16 tcur_speed = v->cur_speed;
1583  uint16 tsubspeed = v->subspeed;
1584  if (!AirportHasBlock(v, current, apc)) {
1585  v->state = landingtype; // LANDING / HELILANDING
1586  /* it's a bit dirty, but I need to set position to next position, otherwise
1587  * if there are multiple runways, plane won't know which one it took (because
1588  * they all have heading LANDING). And also occupy that block! */
1589  v->pos = current->next_position;
1590  SETBITS(st->airport.flags, apc->layout[v->pos].block);
1591  return;
1592  }
1593  v->cur_speed = tcur_speed;
1594  v->subspeed = tsubspeed;
1595  }
1596  current = current->next;
1597  }
1598  }
1599  v->state = FLYING;
1600  v->pos = apc->layout[v->pos].next_position;
1601 }
1602 
1603 static void AircraftEventHandler_Landing(Aircraft *v, const AirportFTAClass *apc)
1604 {
1605  v->state = ENDLANDING;
1606  AircraftLandAirplane(v); // maybe crash airplane
1607 
1608  /* check if the aircraft needs to be replaced or renewed and send it to a hangar if needed */
1609  if (v->NeedsAutomaticServicing()) {
1610  Backup<CompanyByte> cur_company(_current_company, v->owner, FILE_LINE);
1612  cur_company.Restore();
1613  }
1614 }
1615 
1616 static void AircraftEventHandler_HeliLanding(Aircraft *v, const AirportFTAClass *apc)
1617 {
1618  v->state = HELIENDLANDING;
1620 }
1621 
1622 static void AircraftEventHandler_EndLanding(Aircraft *v, const AirportFTAClass *apc)
1623 {
1624  /* next block busy, don't do a thing, just wait */
1625  if (AirportHasBlock(v, &apc->layout[v->pos], apc)) return;
1626 
1627  /* if going to terminal (OT_GOTO_STATION) choose one
1628  * 1. in case all terminals are busy AirportFindFreeTerminal() returns false or
1629  * 2. not going for terminal (but depot, no order),
1630  * --> get out of the way to the hangar. */
1631  if (v->current_order.IsType(OT_GOTO_STATION)) {
1632  if (AirportFindFreeTerminal(v, apc)) return;
1633  }
1634  v->state = HANGAR;
1635 
1636 }
1637 
1638 static void AircraftEventHandler_HeliEndLanding(Aircraft *v, const AirportFTAClass *apc)
1639 {
1640  /* next block busy, don't do a thing, just wait */
1641  if (AirportHasBlock(v, &apc->layout[v->pos], apc)) return;
1642 
1643  /* if going to helipad (OT_GOTO_STATION) choose one. If airport doesn't have helipads, choose terminal
1644  * 1. in case all terminals/helipads are busy (AirportFindFreeHelipad() returns false) or
1645  * 2. not going for terminal (but depot, no order),
1646  * --> get out of the way to the hangar IF there are terminals on the airport.
1647  * --> else TAKEOFF
1648  * the reason behind this is that if an airport has a terminal, it also has a hangar. Airplanes
1649  * must go to a hangar. */
1650  if (v->current_order.IsType(OT_GOTO_STATION)) {
1651  if (AirportFindFreeHelipad(v, apc)) return;
1652  }
1654 }
1655 
1661 typedef void AircraftStateHandler(Aircraft *v, const AirportFTAClass *apc);
1664  AircraftEventHandler_General, // TO_ALL = 0
1665  AircraftEventHandler_InHangar, // HANGAR = 1
1666  AircraftEventHandler_AtTerminal, // TERM1 = 2
1667  AircraftEventHandler_AtTerminal, // TERM2 = 3
1668  AircraftEventHandler_AtTerminal, // TERM3 = 4
1669  AircraftEventHandler_AtTerminal, // TERM4 = 5
1670  AircraftEventHandler_AtTerminal, // TERM5 = 6
1671  AircraftEventHandler_AtTerminal, // TERM6 = 7
1672  AircraftEventHandler_AtTerminal, // HELIPAD1 = 8
1673  AircraftEventHandler_AtTerminal, // HELIPAD2 = 9
1674  AircraftEventHandler_TakeOff, // TAKEOFF = 10
1675  AircraftEventHandler_StartTakeOff, // STARTTAKEOFF = 11
1676  AircraftEventHandler_EndTakeOff, // ENDTAKEOFF = 12
1677  AircraftEventHandler_HeliTakeOff, // HELITAKEOFF = 13
1678  AircraftEventHandler_Flying, // FLYING = 14
1679  AircraftEventHandler_Landing, // LANDING = 15
1680  AircraftEventHandler_EndLanding, // ENDLANDING = 16
1681  AircraftEventHandler_HeliLanding, // HELILANDING = 17
1682  AircraftEventHandler_HeliEndLanding, // HELIENDLANDING = 18
1683  AircraftEventHandler_AtTerminal, // TERM7 = 19
1684  AircraftEventHandler_AtTerminal, // TERM8 = 20
1685  AircraftEventHandler_AtTerminal, // HELIPAD3 = 21
1686 };
1687 
1688 static void AirportClearBlock(const Aircraft *v, const AirportFTAClass *apc)
1689 {
1690  /* we have left the previous block, and entered the new one. Free the previous block */
1691  if (apc->layout[v->previous_pos].block != apc->layout[v->pos].block) {
1693 
1694  CLRBITS(st->airport.flags, apc->layout[v->previous_pos].block);
1695  }
1696 }
1697 
1698 static void AirportGoToNextPosition(Aircraft *v)
1699 {
1700  /* if aircraft is not in position, wait until it is */
1701  if (!AircraftController(v)) return;
1702 
1704 
1705  AirportClearBlock(v, apc);
1706  AirportMove(v, apc); // move aircraft to next position
1707 }
1708 
1709 /* gets pos from vehicle and next orders */
1710 static bool AirportMove(Aircraft *v, const AirportFTAClass *apc)
1711 {
1712  /* error handling */
1713  if (v->pos >= apc->nofelements) {
1714  DEBUG(misc, 0, "[Ap] position %d is not valid for current airport. Max position is %d", v->pos, apc->nofelements-1);
1715  assert(v->pos < apc->nofelements);
1716  }
1717 
1718  const AirportFTA *current = &apc->layout[v->pos];
1719  /* we have arrived in an important state (eg terminal, hangar, etc.) */
1720  if (current->heading == v->state) {
1721  byte prev_pos = v->pos; // location could be changed in state, so save it before-hand
1722  byte prev_state = v->state;
1723  _aircraft_state_handlers[v->state](v, apc);
1724  if (v->state != FLYING) v->previous_pos = prev_pos;
1725  if (v->state != prev_state || v->pos != prev_pos) UpdateAircraftCache(v);
1726  return true;
1727  }
1728 
1729  v->previous_pos = v->pos; // save previous location
1730 
1731  /* there is only one choice to move to */
1732  if (current->next == NULL) {
1733  if (AirportSetBlocks(v, current, apc)) {
1734  v->pos = current->next_position;
1736  } // move to next position
1737  return false;
1738  }
1739 
1740  /* there are more choices to choose from, choose the one that
1741  * matches our heading */
1742  do {
1743  if (v->state == current->heading || current->heading == TO_ALL) {
1744  if (AirportSetBlocks(v, current, apc)) {
1745  v->pos = current->next_position;
1747  } // move to next position
1748  return false;
1749  }
1750  current = current->next;
1751  } while (current != NULL);
1752 
1753  DEBUG(misc, 0, "[Ap] cannot move further on Airport! (pos %d state %d) for vehicle %d", v->pos, v->state, v->index);
1754  NOT_REACHED();
1755 }
1756 
1758 static bool AirportHasBlock(Aircraft *v, const AirportFTA *current_pos, const AirportFTAClass *apc)
1759 {
1760  const AirportFTA *reference = &apc->layout[v->pos];
1761  const AirportFTA *next = &apc->layout[current_pos->next_position];
1762 
1763  /* same block, then of course we can move */
1764  if (apc->layout[current_pos->position].block != next->block) {
1765  const Station *st = Station::Get(v->targetairport);
1766  uint64 airport_flags = next->block;
1767 
1768  /* check additional possible extra blocks */
1769  if (current_pos != reference && current_pos->block != NOTHING_block) {
1770  airport_flags |= current_pos->block;
1771  }
1772 
1773  if (st->airport.flags & airport_flags) {
1774  v->cur_speed = 0;
1775  v->subspeed = 0;
1776  return true;
1777  }
1778  }
1779  return false;
1780 }
1781 
1789 static bool AirportSetBlocks(Aircraft *v, const AirportFTA *current_pos, const AirportFTAClass *apc)
1790 {
1791  const AirportFTA *next = &apc->layout[current_pos->next_position];
1792  const AirportFTA *reference = &apc->layout[v->pos];
1793 
1794  /* if the next position is in another block, check it and wait until it is free */
1795  if ((apc->layout[current_pos->position].block & next->block) != next->block) {
1796  uint64 airport_flags = next->block;
1797  /* search for all all elements in the list with the same state, and blocks != N
1798  * this means more blocks should be checked/set */
1799  const AirportFTA *current = current_pos;
1800  if (current == reference) current = current->next;
1801  while (current != NULL) {
1802  if (current->heading == current_pos->heading && current->block != 0) {
1803  airport_flags |= current->block;
1804  break;
1805  }
1806  current = current->next;
1807  }
1808 
1809  /* if the block to be checked is in the next position, then exclude that from
1810  * checking, because it has been set by the airplane before */
1811  if (current_pos->block == next->block) airport_flags ^= next->block;
1812 
1814  if (st->airport.flags & airport_flags) {
1815  v->cur_speed = 0;
1816  v->subspeed = 0;
1817  return false;
1818  }
1819 
1820  if (next->block != NOTHING_block) {
1821  SETBITS(st->airport.flags, airport_flags); // occupy next block
1822  }
1823  }
1824  return true;
1825 }
1826 
1833  uint64 airport_flag;
1834 };
1835 
1838  {TERM1, TERM1_block},
1839  {TERM2, TERM2_block},
1840  {TERM3, TERM3_block},
1841  {TERM4, TERM4_block},
1842  {TERM5, TERM5_block},
1843  {TERM6, TERM6_block},
1844  {TERM7, TERM7_block},
1845  {TERM8, TERM8_block},
1849 };
1850 
1858 static bool FreeTerminal(Aircraft *v, byte i, byte last_terminal)
1859 {
1860  assert(last_terminal <= lengthof(_airport_terminal_mapping));
1862  for (; i < last_terminal; i++) {
1863  if ((st->airport.flags & _airport_terminal_mapping[i].airport_flag) == 0) {
1864  /* TERMINAL# HELIPAD# */
1865  v->state = _airport_terminal_mapping[i].state; // start moving to that terminal/helipad
1866  SETBITS(st->airport.flags, _airport_terminal_mapping[i].airport_flag); // occupy terminal/helipad
1867  return true;
1868  }
1869  }
1870  return false;
1871 }
1872 
1878 static uint GetNumTerminals(const AirportFTAClass *apc)
1879 {
1880  uint num = 0;
1881 
1882  for (uint i = apc->terminals[0]; i > 0; i--) num += apc->terminals[i];
1883 
1884  return num;
1885 }
1886 
1894 {
1895  /* example of more terminalgroups
1896  * {0,HANGAR,NOTHING_block,1}, {0,255,TERM_GROUP1_block,0}, {0,255,TERM_GROUP2_ENTER_block,1}, {0,0,N,1},
1897  * Heading 255 denotes a group. We see 2 groups here:
1898  * 1. group 0 -- TERM_GROUP1_block (check block)
1899  * 2. group 1 -- TERM_GROUP2_ENTER_block (check block)
1900  * First in line is checked first, group 0. If the block (TERM_GROUP1_block) is free, it
1901  * looks at the corresponding terminals of that group. If no free ones are found, other
1902  * possible groups are checked (in this case group 1, since that is after group 0). If that
1903  * fails, then attempt fails and plane waits
1904  */
1905  if (apc->terminals[0] > 1) {
1906  const Station *st = Station::Get(v->targetairport);
1907  const AirportFTA *temp = apc->layout[v->pos].next;
1908 
1909  while (temp != NULL) {
1910  if (temp->heading == 255) {
1911  if (!(st->airport.flags & temp->block)) {
1912  /* read which group do we want to go to?
1913  * (the first free group) */
1914  uint target_group = temp->next_position + 1;
1915 
1916  /* at what terminal does the group start?
1917  * that means, sum up all terminals of
1918  * groups with lower number */
1919  uint group_start = 0;
1920  for (uint i = 1; i < target_group; i++) {
1921  group_start += apc->terminals[i];
1922  }
1923 
1924  uint group_end = group_start + apc->terminals[target_group];
1925  if (FreeTerminal(v, group_start, group_end)) return true;
1926  }
1927  } else {
1928  /* once the heading isn't 255, we've exhausted the possible blocks.
1929  * So we cannot move */
1930  return false;
1931  }
1932  temp = temp->next;
1933  }
1934  }
1935 
1936  /* if there is only 1 terminalgroup, all terminals are checked (starting from 0 to max) */
1937  return FreeTerminal(v, 0, GetNumTerminals(apc));
1938 }
1939 
1947 {
1948  /* if an airport doesn't have helipads, use terminals */
1949  if (apc->num_helipads == 0) return AirportFindFreeTerminal(v, apc);
1950 
1951  /* only 1 helicoptergroup, check all helipads
1952  * The blocks for helipads start after the last terminal (MAX_TERMINALS) */
1954 }
1955 
1961 static void AircraftHandleDestTooFar(Aircraft *v, bool too_far)
1962 {
1963  if (too_far) {
1964  if (!HasBit(v->flags, VAF_DEST_TOO_FAR)) {
1967  AI::NewEvent(v->owner, new ScriptEventAircraftDestTooFar(v->index));
1968  if (v->owner == _local_company) {
1969  /* Post a news message. */
1970  SetDParam(0, v->index);
1971  AddVehicleAdviceNewsItem(STR_NEWS_AIRCRAFT_DEST_TOO_FAR, v->index);
1972  }
1973  }
1974  return;
1975  }
1976 
1977  if (HasBit(v->flags, VAF_DEST_TOO_FAR)) {
1978  /* Not too far anymore, clear flag and message. */
1981  DeleteVehicleNews(v->index, STR_NEWS_AIRCRAFT_DEST_TOO_FAR);
1982  }
1983 }
1984 
1985 static bool AircraftEventHandler(Aircraft *v, int loop)
1986 {
1987  if (v->vehstatus & VS_CRASHED) {
1988  return HandleCrashedAircraft(v);
1989  }
1990 
1991  if (v->vehstatus & VS_STOPPED) return true;
1992 
1993  v->HandleBreakdown();
1994 
1995  HandleAircraftSmoke(v, loop != 0);
1996  ProcessOrders(v);
1997  v->HandleLoading(loop != 0);
1998 
1999  if (v->current_order.IsType(OT_LOADING) || v->current_order.IsType(OT_LEAVESTATION)) return true;
2000 
2001  if (v->state >= ENDTAKEOFF && v->state <= HELIENDLANDING) {
2002  /* If we are flying, unconditionally clear the 'dest too far' state. */
2003  AircraftHandleDestTooFar(v, false);
2004  } else if (v->acache.cached_max_range_sqr != 0) {
2005  /* Check the distance to the next destination. This code works because the target
2006  * airport is only updated after take off and not on the ground. */
2008  Station *next_st = v->current_order.IsType(OT_GOTO_STATION) || v->current_order.IsType(OT_GOTO_DEPOT) ? Station::GetIfValid(v->current_order.GetDestination()) : NULL;
2009 
2010  if (cur_st != NULL && cur_st->airport.tile != INVALID_TILE && next_st != NULL && next_st->airport.tile != INVALID_TILE) {
2011  uint dist = DistanceSquare(cur_st->airport.tile, next_st->airport.tile);
2012  AircraftHandleDestTooFar(v, dist > v->acache.cached_max_range_sqr);
2013  }
2014  }
2015 
2016  if (!HasBit(v->flags, VAF_DEST_TOO_FAR)) AirportGoToNextPosition(v);
2017 
2018  return true;
2019 }
2020 
2022 {
2023  if (!this->IsNormalAircraft()) return true;
2024 
2025  this->tick_counter++;
2026 
2027  if (!(this->vehstatus & VS_STOPPED)) this->running_ticks++;
2028 
2029  if (this->subtype == AIR_HELICOPTER) HelicopterTickHandler(this);
2030 
2031  this->current_order_time++;
2032 
2033  for (uint i = 0; i != 2; i++) {
2034  /* stop if the aircraft was deleted */
2035  if (!AircraftEventHandler(this, i)) return false;
2036  }
2037 
2038  return true;
2039 }
2040 
2041 
2049 {
2050  assert(v->type == VEH_AIRCRAFT);
2051 
2053  if (st == NULL) return NULL;
2054 
2055  return st->airport.tile == INVALID_TILE ? NULL : st;
2056 }
2057 
2063 {
2064  /* only 1 station is updated per function call, so it is enough to get entry_point once */
2065  const AirportFTAClass *ap = st->airport.GetFTA();
2066  Direction rotation = st->airport.tile == INVALID_TILE ? DIR_N : st->airport.rotation;
2067 
2068  Aircraft *v;
2069  FOR_ALL_AIRCRAFT(v) {
2070  if (!v->IsNormalAircraft() || v->targetairport != st->index) continue;
2071  assert(v->state == FLYING);
2072  v->pos = v->previous_pos = AircraftGetEntryPoint(v, ap, rotation);
2074  }
2075 }