OpenTTD: src/aircraft_cmd.cpp Source File

OpenTTD

- Main Page
- Related Pages
- Modules
- Namespaces
- Data Structures
- Files

- File List
- Globals

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