OpenTTD Source: src/aircraft_cmd.cpp Source File

OpenTTD Source 13.1

aircraft_cmd.cpp
Go to the documentation of this file.
1 /*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6 */
7
13 #include "stdafx.h"
14 #include "aircraft.h"
15 #include "landscape.h"
16 #include "news_func.h"
17 #include "newgrf_engine.h"
18 #include "newgrf_sound.h"
19 #include "spritecache.h"
20 #include "strings_func.h"
21 #include "command_func.h"
22 #include "window_func.h"
23 #include "date_func.h"
24 #include "vehicle_func.h"
25 #include "sound_func.h"
26 #include "cheat_type.h"
27 #include "company_base.h"
28 #include "ai/ai.hpp"
29 #include "game/game.hpp"
30 #include "company_func.h"
31 #include "effectvehicle_func.h"
32 #include "station_base.h"
33 #include "engine_base.h"
34 #include "core/random_func.hpp"
35 #include "core/backup_type.hpp"
36 #include "zoom_func.h"
37 #include "disaster_vehicle.h"
38 #include "newgrf_airporttiles.h"
39 #include "framerate_type.h"
40 #include "aircraft_cmd.h"
41 #include "vehicle_cmd.h"
42
43 #include "table/strings.h"
44
45 #include "safeguards.h"
46
47 void Aircraft::UpdateDeltaXY()
48 {
49 this->x_offs = -1;
50 this->y_offs = -1;
51 this->x_extent = 2;
52 this->y_extent = 2;
53
54 switch (this->subtype) {
55 default: NOT_REACHED();
56
57 case AIR_AIRCRAFT:
58 case AIR_HELICOPTER:
59 switch (this->state) {
60 default: break;
61 case ENDTAKEOFF:
62 case LANDING:
63 case HELILANDING:
64 case FLYING:
65 this->x_extent = 24;
66 this->y_extent = 24;
67 break;
68 }
69 this->z_extent = 5;
70 break;
71
72 case AIR_SHADOW:
73 this->z_extent = 1;
74 this->x_offs = 0;
75 this->y_offs = 0;
76 break;
77
78 case AIR_ROTOR:
79 this->z_extent = 1;
80 break;
81 }
82 }
83
84 static bool AirportMove(Aircraft *v, const AirportFTAClass *apc);
85 static bool AirportSetBlocks(Aircraft *v, const AirportFTA *current_pos, const AirportFTAClass *apc);
86 static bool AirportHasBlock(Aircraft *v, const AirportFTA *current_pos, const AirportFTAClass *apc);
87 static bool AirportFindFreeTerminal(Aircraft *v, const AirportFTAClass *apc);
88 static bool AirportFindFreeHelipad(Aircraft *v, const AirportFTAClass *apc);
89 static void CrashAirplane(Aircraft *v);
90
91 static const SpriteID _aircraft_sprite[] = {
92 0x0EB5, 0x0EBD, 0x0EC5, 0x0ECD,
93 0x0ED5, 0x0EDD, 0x0E9D, 0x0EA5,
94 0x0EAD, 0x0EE5, 0x0F05, 0x0F0D,
95 0x0F15, 0x0F1D, 0x0F25, 0x0F2D,
96 0x0EED, 0x0EF5, 0x0EFD, 0x0F35,
97 0x0E9D, 0x0EA5, 0x0EAD, 0x0EB5,
98 0x0EBD, 0x0EC5
99 };
100
101 template <>
102 bool IsValidImageIndex<VEH_AIRCRAFT>(uint8 image_index)
103 {
104 return image_index < lengthof(_aircraft_sprite);
105 }
106
108 enum HelicopterRotorStates {
109 HRS_ROTOR_STOPPED,
110 HRS_ROTOR_MOVING_1,
111 HRS_ROTOR_MOVING_2,
112 HRS_ROTOR_MOVING_3,
113 };
114
122 static StationID FindNearestHangar(const Aircraft *v)
123 {
124 uint best = 0;
125 StationID index = INVALID_STATION;
126 TileIndex vtile = TileVirtXY(v->x_pos, v->y_pos);
127 const AircraftVehicleInfo *avi = AircraftVehInfo(v->engine_type);
128 uint max_range = v->acache.cached_max_range_sqr;
129
130 /* Determine destinations where it's coming from and where it's heading to */
131 const Station *last_dest = nullptr;
132 const Station *next_dest = nullptr;
133 if (max_range != 0) {
134 if (v->current_order.IsType(OT_GOTO_STATION) ||
135 (v->current_order.IsType(OT_GOTO_DEPOT) && v->current_order.GetDepotActionType() != ODATFB_NEAREST_DEPOT)) {
136 last_dest = Station::GetIfValid(v->last_station_visited);
137 next_dest = Station::GetIfValid(v->current_order.GetDestination());
138 } else {
139 last_dest = GetTargetAirportIfValid(v);
140 next_dest = Station::GetIfValid(v->GetNextStoppingStation().value);
141 }
142 }
143
144 for (const Station *st : Station::Iterate()) {
145 if (st->owner != v->owner || !(st->facilities & FACIL_AIRPORT) || !st->airport.HasHangar()) continue;
146
147 const AirportFTAClass *afc = st->airport.GetFTA();
148
149 /* don't crash the plane if we know it can't land at the airport */
150 if ((afc->flags & AirportFTAClass::SHORT_STRIP) && (avi->subtype & AIR_FAST) && !_cheats.no_jetcrash.value) continue;
151
152 /* the plane won't land at any helicopter station */
153 if (!(afc->flags & AirportFTAClass::AIRPLANES) && (avi->subtype & AIR_CTOL)) continue;
154
155 /* Check if our last and next destinations can be reached from the depot airport. */
156 if (max_range != 0) {
157 uint last_dist = (last_dest != nullptr && last_dest->airport.tile != INVALID_TILE) ? DistanceSquare(st->airport.tile, last_dest->airport.tile) : 0;
158 uint next_dist = (next_dest != nullptr && next_dest->airport.tile != INVALID_TILE) ? DistanceSquare(st->airport.tile, next_dest->airport.tile) : 0;
159 if (last_dist > max_range || next_dist > max_range) continue;
160 }
161
162 /* v->tile can't be used here, when aircraft is flying v->tile is set to 0 */
163 uint distance = DistanceSquare(vtile, st->airport.tile);
164 if (distance < best || index == INVALID_STATION) {
165 best = distance;
166 index = st->index;
167 }
168 }
169 return index;
170 }
171
172 void Aircraft::GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const
173 {
174 uint8 spritenum = this->spritenum;
175
176 if (is_custom_sprite(spritenum)) {
177 GetCustomVehicleSprite(this, direction, image_type, result);
178 if (result->IsValid()) return;
179
180 spritenum = this->GetEngine()->original_image_index;
181 }
182
183 assert(IsValidImageIndex<VEH_AIRCRAFT>(spritenum));
184 result->Set(direction + _aircraft_sprite[spritenum]);
185 }
186
187 void GetRotorImage(const Aircraft *v, EngineImageType image_type, VehicleSpriteSeq *result)
188 {
189 assert(v->subtype == AIR_HELICOPTER);
190
191 const Aircraft *w = v->Next()->Next();
192 if (is_custom_sprite(v->spritenum)) {
193 GetCustomRotorSprite(v, image_type, result);
194 if (result->IsValid()) return;
195 }
196
197 /* Return standard rotor sprites if there are no custom sprites for this helicopter */
198 result->Set(SPR_ROTOR_STOPPED + w->state);
199 }
200
201 static void GetAircraftIcon(EngineID engine, EngineImageType image_type, VehicleSpriteSeq *result)
202 {
203 const Engine *e = Engine::Get(engine);
204 uint8 spritenum = e->u.air.image_index;
205
206 if (is_custom_sprite(spritenum)) {
207 GetCustomVehicleIcon(engine, DIR_W, image_type, result);
208 if (result->IsValid()) return;
209
210 spritenum = e->original_image_index;
211 }
212
213 assert(IsValidImageIndex<VEH_AIRCRAFT>(spritenum));
214 result->Set(DIR_W + _aircraft_sprite[spritenum]);
215 }
216
217 void DrawAircraftEngine(int left, int right, int preferred_x, int y, EngineID engine, PaletteID pal, EngineImageType image_type)
218 {
219 VehicleSpriteSeq seq;
220 GetAircraftIcon(engine, image_type, &seq);
221
222 Rect rect;
223 seq.GetBounds(&rect);
224 preferred_x = Clamp(preferred_x,
225 left - UnScaleGUI(rect.left),
226 right - UnScaleGUI(rect.right));
227
228 seq.Draw(preferred_x, y, pal, pal == PALETTE_CRASH);
229
230 if (!(AircraftVehInfo(engine)->subtype & AIR_CTOL)) {
231 VehicleSpriteSeq rotor_seq;
232 GetCustomRotorIcon(engine, image_type, &rotor_seq);
233 if (!rotor_seq.IsValid()) rotor_seq.Set(SPR_ROTOR_STOPPED);
234 rotor_seq.Draw(preferred_x, y - ScaleSpriteTrad(5), PAL_NONE, false);
235 }
236 }
237
247 void GetAircraftSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type)
248 {
249 VehicleSpriteSeq seq;
250 GetAircraftIcon(engine, image_type, &seq);
251
252 Rect rect;
253 seq.GetBounds(&rect);
254
255 width = UnScaleGUI(rect.Width());
256 height = UnScaleGUI(rect.Height());
257 xoffs = UnScaleGUI(rect.left);
258 yoffs = UnScaleGUI(rect.top);
259 }
260
269 CommandCost CmdBuildAircraft(DoCommandFlag flags, TileIndex tile, const Engine *e, Vehicle **ret)
270 {
271 const AircraftVehicleInfo *avi = &e->u.air;
272 const Station *st = Station::GetByTile(tile);
273
274 /* Prevent building aircraft types at places which can't handle them */
275 if (!CanVehicleUseStation(e->index, st)) return CMD_ERROR;
276
277 /* Make sure all aircraft end up in the first tile of the hangar. */
278 tile = st->airport.GetHangarTile(st->airport.GetHangarNum(tile));
279
280 if (flags & DC_EXEC) {
281 Aircraft *v = new Aircraft(); // aircraft
282 Aircraft *u = new Aircraft(); // shadow
283 *ret = v;
284
285 v->direction = DIR_SE;
286
287 v->owner = u->owner = _current_company;
288
289 v->tile = tile;
290
291 uint x = TileX(tile) * TILE_SIZE + 5;
292 uint y = TileY(tile) * TILE_SIZE + 3;
293
294 v->x_pos = u->x_pos = x;
295 v->y_pos = u->y_pos = y;
296
297 u->z_pos = GetSlopePixelZ(x, y);
298 v->z_pos = u->z_pos + 1;
299
300 v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL;
301 u->vehstatus = VS_HIDDEN | VS_UNCLICKABLE | VS_SHADOW;
302
303 v->spritenum = avi->image_index;
304
305 v->cargo_cap = avi->passenger_capacity;
306 v->refit_cap = 0;
307 u->cargo_cap = avi->mail_capacity;
308 u->refit_cap = 0;
309
310 v->cargo_type = e->GetDefaultCargoType();
311 u->cargo_type = CT_MAIL;
312
313 v->name.clear();
314 v->last_station_visited = INVALID_STATION;
315 v->last_loading_station = INVALID_STATION;
316
317 v->acceleration = avi->acceleration;
318 v->engine_type = e->index;
319 u->engine_type = e->index;
320
321 v->subtype = (avi->subtype & AIR_CTOL ? AIR_AIRCRAFT : AIR_HELICOPTER);
322 v->UpdateDeltaXY();
323
324 u->subtype = AIR_SHADOW;
325 u->UpdateDeltaXY();
326
327 v->reliability = e->reliability;
328 v->reliability_spd_dec = e->reliability_spd_dec;
329 v->max_age = e->GetLifeLengthInDays();
330
331 v->pos = GetVehiclePosOnBuild(tile);
332
333 v->state = HANGAR;
334 v->previous_pos = v->pos;
335 v->targetairport = GetStationIndex(tile);
336 v->SetNext(u);
337
338 v->SetServiceInterval(Company::Get(_current_company)->settings.vehicle.servint_aircraft);
339
340 v->date_of_last_service = _date;
341 v->build_year = u->build_year = _cur_year;
342
343 v->sprite_cache.sprite_seq.Set(SPR_IMG_QUERY);
344 u->sprite_cache.sprite_seq.Set(SPR_IMG_QUERY);
345
346 v->random_bits = VehicleRandomBits();
347 u->random_bits = VehicleRandomBits();
348
349 v->vehicle_flags = 0;
350 if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) SetBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE);
351 v->SetServiceIntervalIsPercent(Company::Get(_current_company)->settings.vehicle.servint_ispercent);
352
353 v->InvalidateNewGRFCacheOfChain();
354
355 v->cargo_cap = e->DetermineCapacity(v, &u->cargo_cap);
356
357 v->InvalidateNewGRFCacheOfChain();
358
359 UpdateAircraftCache(v, true);
360
361 v->UpdatePosition();
362 u->UpdatePosition();
363
364 /* Aircraft with 3 vehicles (chopper)? */
365 if (v->subtype == AIR_HELICOPTER) {
366 Aircraft *w = new Aircraft();
367 w->engine_type = e->index;
368 w->direction = DIR_N;
369 w->owner = _current_company;
370 w->x_pos = v->x_pos;
371 w->y_pos = v->y_pos;
372 w->z_pos = v->z_pos + ROTOR_Z_OFFSET;
373 w->vehstatus = VS_HIDDEN | VS_UNCLICKABLE;
374 w->spritenum = 0xFF;
375 w->subtype = AIR_ROTOR;
376 w->sprite_cache.sprite_seq.Set(SPR_ROTOR_STOPPED);
377 w->random_bits = VehicleRandomBits();
378 /* Use rotor's air.state to store the rotor animation frame */
379 w->state = HRS_ROTOR_STOPPED;
380 w->UpdateDeltaXY();
381
382 u->SetNext(w);
383 w->UpdatePosition();
384 }
385 }
386
387 return CommandCost();
388 }
389
390
391 bool Aircraft::FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
392 {
393 const Station *st = GetTargetAirportIfValid(this);
394 /* If the station is not a valid airport or if it has no hangars */
395 if (st == nullptr || !CanVehicleUseStation(this, st) || !st->airport.HasHangar()) {
396 /* the aircraft has to search for a hangar on its own */
397 StationID station = FindNearestHangar(this);
398
399 if (station == INVALID_STATION) return false;
400
401 st = Station::Get(station);
402 }
403
404 if (location != nullptr) *location = st->xy;
405 if (destination != nullptr) *destination = st->index;
406
407 return true;
408 }
409
410 static void CheckIfAircraftNeedsService(Aircraft *v)
411 {
412 if (Company::Get(v->owner)->settings.vehicle.servint_aircraft == 0 || !v->NeedsAutomaticServicing()) return;
413 if (v->IsChainInDepot()) {
414 VehicleServiceInDepot(v);
415 return;
416 }
417
418 /* When we're parsing conditional orders and the like
419 * we don't want to consider going to a depot too. */
420 if (!v->current_order.IsType(OT_GOTO_DEPOT) && !v->current_order.IsType(OT_GOTO_STATION)) return;
421
422 const Station *st = Station::Get(v->current_order.GetDestination());
423
424 assert(st != nullptr);
425
426 /* only goto depot if the target airport has a depot */
427 if (st->airport.HasHangar() && CanVehicleUseStation(v, st)) {
428 v->current_order.MakeGoToDepot(st->index, ODTFB_SERVICE);
429 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
430 } else if (v->current_order.IsType(OT_GOTO_DEPOT)) {
431 v->current_order.MakeDummy();
432 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
433 }
434 }
435
436 Money Aircraft::GetRunningCost() const
437 {
438 const Engine *e = this->GetEngine();
439 uint cost_factor = GetVehicleProperty(this, PROP_AIRCRAFT_RUNNING_COST_FACTOR, e->u.air.running_cost);
440 return GetPrice(PR_RUNNING_AIRCRAFT, cost_factor, e->GetGRF());
441 }
442
443 void Aircraft::OnNewDay()
444 {
445 if (!this->IsNormalAircraft()) return;
446
447 if ((++this->day_counter & 7) == 0) DecreaseVehicleValue(this);
448
449 CheckOrders(this);
450
451 CheckVehicleBreakdown(this);
452 AgeVehicle(this);
453 CheckIfAircraftNeedsService(this);
454
455 if (this->running_ticks == 0) return;
456
457 CommandCost cost(EXPENSES_AIRCRAFT_RUN, this->GetRunningCost() * this->running_ticks / (DAYS_IN_YEAR * DAY_TICKS));
458
459 this->profit_this_year -= cost.GetCost();
460 this->running_ticks = 0;
461
462 SubtractMoneyFromCompanyFract(this->owner, cost);
463
464 SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
465 SetWindowClassesDirty(WC_AIRCRAFT_LIST);
466 }
467
468 static void HelicopterTickHandler(Aircraft *v)
469 {
470 Aircraft *u = v->Next()->Next();
471
472 if (u->vehstatus & VS_HIDDEN) return;
473
474 /* if true, helicopter rotors do not rotate. This should only be the case if a helicopter is
475 * loading/unloading at a terminal or stopped */
476 if (v->current_order.IsType(OT_LOADING) || (v->vehstatus & VS_STOPPED)) {
477 if (u->cur_speed != 0) {
478 u->cur_speed++;
479 if (u->cur_speed >= 0x80 && u->state == HRS_ROTOR_MOVING_3) {
480 u->cur_speed = 0;
481 }
482 }
483 } else {
484 if (u->cur_speed == 0) {
485 u->cur_speed = 0x70;
486 }
487 if (u->cur_speed >= 0x50) {
488 u->cur_speed--;
489 }
490 }
491
492 int tick = ++u->tick_counter;
493 int spd = u->cur_speed >> 4;
494
495 VehicleSpriteSeq seq;
496 if (spd == 0) {
497 u->state = HRS_ROTOR_STOPPED;
498 GetRotorImage(v, EIT_ON_MAP, &seq);
499 if (u->sprite_cache.sprite_seq == seq) return;
500 } else if (tick >= spd) {
501 u->tick_counter = 0;
502 u->state++;
503 if (u->state > HRS_ROTOR_MOVING_3) u->state = HRS_ROTOR_MOVING_1;
504 GetRotorImage(v, EIT_ON_MAP, &seq);
505 } else {
506 return;
507 }
508
509 u->sprite_cache.sprite_seq = seq;
510
511 u->UpdatePositionAndViewport();
512 }
513
521 void SetAircraftPosition(Aircraft *v, int x, int y, int z)
522 {
523 v->x_pos = x;
524 v->y_pos = y;
525 v->z_pos = z;
526
527 v->UpdatePosition();
528 v->UpdateViewport(true, false);
529 if (v->subtype == AIR_HELICOPTER) {
530 GetRotorImage(v, EIT_ON_MAP, &v->Next()->Next()->sprite_cache.sprite_seq);
531 }
532
533 Aircraft *u = v->Next();
534
535 int safe_x = Clamp(x, 0, MapMaxX() * TILE_SIZE);
536 int safe_y = Clamp(y - 1, 0, MapMaxY() * TILE_SIZE);
537 u->x_pos = x;
538 u->y_pos = y - ((v->z_pos - GetSlopePixelZ(safe_x, safe_y)) >> 3);
539
540 safe_y = Clamp(u->y_pos, 0, MapMaxY() * TILE_SIZE);
541 u->z_pos = GetSlopePixelZ(safe_x, safe_y);
542 u->sprite_cache.sprite_seq.CopyWithoutPalette(v->sprite_cache.sprite_seq); // the shadow is never coloured
543
544 u->UpdatePositionAndViewport();
545
546 u = u->Next();
547 if (u != nullptr) {
548 u->x_pos = x;
549 u->y_pos = y;
550 u->z_pos = z + ROTOR_Z_OFFSET;
551
552 u->UpdatePositionAndViewport();
553 }
554 }
555
560 void HandleAircraftEnterHangar(Aircraft *v)
561 {
562 v->subspeed = 0;
563 v->progress = 0;
564
565 Aircraft *u = v->Next();
566 u->vehstatus |= VS_HIDDEN;
567 u = u->Next();
568 if (u != nullptr) {
569 u->vehstatus |= VS_HIDDEN;
570 u->cur_speed = 0;
571 }
572
573 SetAircraftPosition(v, v->x_pos, v->y_pos, v->z_pos);
574 }
575
576 static void PlayAircraftSound(const Vehicle *v)
577 {
578 if (!PlayVehicleSound(v, VSE_START)) {
579 SndPlayVehicleFx(AircraftVehInfo(v->engine_type)->sfx, v);
580 }
581 }
582
583
590 void UpdateAircraftCache(Aircraft *v, bool update_range)
591 {
592 uint max_speed = GetVehicleProperty(v, PROP_AIRCRAFT_SPEED, 0);
593 if (max_speed != 0) {
594 /* Convert from original units to km-ish/h */
595 max_speed = (max_speed * 128) / 10;
596
597 v->vcache.cached_max_speed = max_speed;
598 } else {
599 /* Use the default max speed of the vehicle. */
600 v->vcache.cached_max_speed = AircraftVehInfo(v->engine_type)->max_speed;
601 }
602
603 /* Update cargo aging period. */
604 v->vcache.cached_cargo_age_period = GetVehicleProperty(v, PROP_AIRCRAFT_CARGO_AGE_PERIOD, EngInfo(v->engine_type)->cargo_age_period);
605 Aircraft *u = v->Next(); // Shadow for mail
606 u->vcache.cached_cargo_age_period = GetVehicleProperty(u, PROP_AIRCRAFT_CARGO_AGE_PERIOD, EngInfo(u->engine_type)->cargo_age_period);
607
608 /* Update aircraft range. */
609 if (update_range) {
610 v->acache.cached_max_range = GetVehicleProperty(v, PROP_AIRCRAFT_RANGE, AircraftVehInfo(v->engine_type)->max_range);
611 /* Squared it now so we don't have to do it later all the time. */
612 v->acache.cached_max_range_sqr = v->acache.cached_max_range * v->acache.cached_max_range;
613 }
614 }
615
616
620 enum AircraftSpeedLimits {
621 SPEED_LIMIT_TAXI = 50,
622 SPEED_LIMIT_APPROACH = 230,
623 SPEED_LIMIT_BROKEN = 320,
624 SPEED_LIMIT_HOLD = 425,
625 SPEED_LIMIT_NONE = 0xFFFF,
626 };
627
635 static int UpdateAircraftSpeed(Aircraft *v, uint speed_limit = SPEED_LIMIT_NONE, bool hard_limit = true)
636 {
644 uint spd = v->acceleration * 77;
645 byte t;
646
647 /* Adjust speed limits by plane speed factor to prevent taxiing
648 * and take-off speeds being too low. */
649 speed_limit *= _settings_game.vehicle.plane_speed;
650
651 /* adjust speed for broken vehicles */
652 if (v->vehstatus & VS_AIRCRAFT_BROKEN) {
653 if (SPEED_LIMIT_BROKEN < speed_limit) hard_limit = false;
654 speed_limit = std::min<uint>(speed_limit, SPEED_LIMIT_BROKEN);
655 }
656
657 if (v->vcache.cached_max_speed < speed_limit) {
658 if (v->cur_speed < speed_limit) hard_limit = false;
659 speed_limit = v->vcache.cached_max_speed;
660 }
661
662 v->subspeed = (t = v->subspeed) + (byte)spd;
663
664 /* Aircraft's current speed is used twice so that very fast planes are
665 * forced to slow down rapidly in the short distance needed. The magic
666 * value 16384 was determined to give similar results to the old speed/48
667 * method at slower speeds. This also results in less reduction at slow
668 * speeds to that aircraft do not get to taxi speed straight after
669 * touchdown. */
670 if (!hard_limit && v->cur_speed > speed_limit) {
671 speed_limit = v->cur_speed - std::max(1, ((v->cur_speed * v->cur_speed) / 16384) / _settings_game.vehicle.plane_speed);
672 }
673
674 spd = std::min(v->cur_speed + (spd >> 8) + (v->subspeed < t), speed_limit);
675
676 /* updates statusbar only if speed have changed to save CPU time */
677 if (spd != v->cur_speed) {
678 v->cur_speed = spd;
679 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
680 }
681
682 /* Adjust distance moved by plane speed setting */
683 if (_settings_game.vehicle.plane_speed > 1) spd /= _settings_game.vehicle.plane_speed;
684
685 /* Convert direction-independent speed into direction-dependent speed. (old movement method) */
686 spd = v->GetOldAdvanceSpeed(spd);
687
688 spd += v->progress;
689 v->progress = (byte)spd;
690 return spd >> 8;
691 }
692
700 int GetTileHeightBelowAircraft(const Vehicle *v)
701 {
702 int safe_x = Clamp(v->x_pos, 0, MapMaxX() * TILE_SIZE);
703 int safe_y = Clamp(v->y_pos, 0, MapMaxY() * TILE_SIZE);
704 return TileHeight(TileVirtXY(safe_x, safe_y)) * TILE_HEIGHT;
705 }
706
717 void GetAircraftFlightLevelBounds(const Vehicle *v, int *min_level, int *max_level)
718 {
719 int base_altitude = GetTileHeightBelowAircraft(v);
720 if (v->type == VEH_AIRCRAFT && Aircraft::From(v)->subtype == AIR_HELICOPTER) {
721 base_altitude += HELICOPTER_HOLD_MAX_FLYING_ALTITUDE - PLANE_HOLD_MAX_FLYING_ALTITUDE;
722 }
723
724 /* Make sure eastbound and westbound planes do not "crash" into each
725 * other by providing them with vertical separation
726 */
727 switch (v->direction) {
728 case DIR_N:
729 case DIR_NE:
730 case DIR_E:
731 case DIR_SE:
732 base_altitude += 10;
733 break;
734
735 default: break;
736 }
737
738 /* Make faster planes fly higher so that they can overtake slower ones */
739 base_altitude += std::min(20 * (v->vcache.cached_max_speed / 200) - 90, 0);
740
741 if (min_level != nullptr) *min_level = base_altitude + AIRCRAFT_MIN_FLYING_ALTITUDE;
742 if (max_level != nullptr) *max_level = base_altitude + AIRCRAFT_MAX_FLYING_ALTITUDE;
743 }
744
752 int GetAircraftHoldMaxAltitude(const Aircraft *v)
753 {
754 int tile_height = GetTileHeightBelowAircraft(v);
755
756 return tile_height + ((v->subtype == AIR_HELICOPTER) ? HELICOPTER_HOLD_MAX_FLYING_ALTITUDE : PLANE_HOLD_MAX_FLYING_ALTITUDE);
757 }
758
759 template <class T>
760 int GetAircraftFlightLevel(T *v, bool takeoff)
761 {
762 /* Aircraft is in flight. We want to enforce it being somewhere
763 * between the minimum and the maximum allowed altitude. */
764 int aircraft_min_altitude;
765 int aircraft_max_altitude;
766 GetAircraftFlightLevelBounds(v, &aircraft_min_altitude, &aircraft_max_altitude);
767 int aircraft_middle_altitude = (aircraft_min_altitude + aircraft_max_altitude) / 2;
768
769 /* If those assumptions would be violated, aircraft would behave fairly strange. */
770 assert(aircraft_min_altitude < aircraft_middle_altitude);
771 assert(aircraft_middle_altitude < aircraft_max_altitude);
772
773 int z = v->z_pos;
774 if (z < aircraft_min_altitude ||
775 (HasBit(v->flags, VAF_IN_MIN_HEIGHT_CORRECTION) && z < aircraft_middle_altitude)) {
776 /* Ascend. And don't fly into that mountain right ahead.
777 * And avoid our aircraft become a stairclimber, so if we start
778 * correcting altitude, then we stop correction not too early. */
779 SetBit(v->flags, VAF_IN_MIN_HEIGHT_CORRECTION);
780 z += takeoff ? 2 : 1;
781 } else if (!takeoff && (z > aircraft_max_altitude ||
782 (HasBit(v->flags, VAF_IN_MAX_HEIGHT_CORRECTION) && z > aircraft_middle_altitude))) {
783 /* Descend lower. You are an aircraft, not an space ship.
784 * And again, don't stop correcting altitude too early. */
785 SetBit(v->flags, VAF_IN_MAX_HEIGHT_CORRECTION);
786 z--;
787 } else if (HasBit(v->flags, VAF_IN_MIN_HEIGHT_CORRECTION) && z >= aircraft_middle_altitude) {
788 /* Now, we have corrected altitude enough. */
789 ClrBit(v->flags, VAF_IN_MIN_HEIGHT_CORRECTION);
790 } else if (HasBit(v->flags, VAF_IN_MAX_HEIGHT_CORRECTION) && z <= aircraft_middle_altitude) {
791 /* Now, we have corrected altitude enough. */
792 ClrBit(v->flags, VAF_IN_MAX_HEIGHT_CORRECTION);
793 }
794
795 return z;
796 }
797
798 template int GetAircraftFlightLevel(DisasterVehicle *v, bool takeoff);
799 template int GetAircraftFlightLevel(Aircraft *v, bool takeoff);
800
815 static byte AircraftGetEntryPoint(const Aircraft *v, const AirportFTAClass *apc, Direction rotation)
816 {
817 assert(v != nullptr);
818 assert(apc != nullptr);
819
820 /* In the case the station doesn't exit anymore, set target tile 0.
821 * It doesn't hurt much, aircraft will go to next order, nearest hangar
822 * or it will simply crash in next tick */
823 TileIndex tile = 0;
824
825 const Station *st = Station::GetIfValid(v->targetairport);
826 if (st != nullptr) {
827 /* Make sure we don't go to INVALID_TILE if the airport has been removed. */
828 tile = (st->airport.tile != INVALID_TILE) ? st->airport.tile : st->xy;
829 }
830
831 int delta_x = v->x_pos - TileX(tile) * TILE_SIZE;
832 int delta_y = v->y_pos - TileY(tile) * TILE_SIZE;
833
834 DiagDirection dir;
835 if (abs(delta_y) < abs(delta_x)) {
836 /* We are northeast or southwest of the airport */
837 dir = delta_x < 0 ? DIAGDIR_NE : DIAGDIR_SW;
838 } else {
839 /* We are northwest or southeast of the airport */
840 dir = delta_y < 0 ? DIAGDIR_NW : DIAGDIR_SE;
841 }
842 dir = ChangeDiagDir(dir, DiagDirDifference(DIAGDIR_NE, DirToDiagDir(rotation)));
843 return apc->entry_points[dir];
844 }
845
846
847 static void MaybeCrashAirplane(Aircraft *v);
848
856 static bool AircraftController(Aircraft *v)
857 {
858 /* nullptr if station is invalid */
859 const Station *st = Station::GetIfValid(v->targetairport);
860 /* INVALID_TILE if there is no station */
861 TileIndex tile = INVALID_TILE;
862 Direction rotation = DIR_N;
863 uint size_x = 1, size_y = 1;
864 if (st != nullptr) {
865 if (st->airport.tile != INVALID_TILE) {
866 tile = st->airport.tile;
867 rotation = st->airport.rotation;
868 size_x = st->airport.w;
869 size_y = st->airport.h;
870 } else {
871 tile = st->xy;
872 }
873 }
874 /* DUMMY if there is no station or no airport */
875 const AirportFTAClass *afc = tile == INVALID_TILE ? GetAirport(AT_DUMMY) : st->airport.GetFTA();
876
877 /* prevent going to INVALID_TILE if airport is deleted. */
878 if (st == nullptr || st->airport.tile == INVALID_TILE) {
879 /* Jump into our "holding pattern" state machine if possible */
880 if (v->pos >= afc->nofelements) {
881 v->pos = v->previous_pos = AircraftGetEntryPoint(v, afc, DIR_N);
882 } else if (v->targetairport != v->current_order.GetDestination()) {
883 /* If not possible, just get out of here fast */
884 v->state = FLYING;
885 UpdateAircraftCache(v);
886 AircraftNextAirportPos_and_Order(v);
887 /* get aircraft back on running altitude */
888 SetAircraftPosition(v, v->x_pos, v->y_pos, GetAircraftFlightLevel(v));
889 return false;
890 }
891 }
892
893 /* get airport moving data */
894 const AirportMovingData amd = RotateAirportMovingData(afc->MovingData(v->pos), rotation, size_x, size_y);
895
896 int x = TileX(tile) * TILE_SIZE;
897 int y = TileY(tile) * TILE_SIZE;
898
899 /* Helicopter raise */
900 if (amd.flag & AMED_HELI_RAISE) {
901 Aircraft *u = v->Next()->Next();
902
903 /* Make sure the rotors don't rotate too fast */
904 if (u->cur_speed > 32) {
905 v->cur_speed = 0;
906 if (--u->cur_speed == 32) {
907 if (!PlayVehicleSound(v, VSE_START)) {
908 SoundID sfx = AircraftVehInfo(v->engine_type)->sfx;
909 /* For compatibility with old NewGRF we ignore the sfx property, unless a NewGRF-defined sound is used.
910 * The baseset has only one helicopter sound, so this only limits using plane or cow sounds. */
911 if (sfx < ORIGINAL_SAMPLE_COUNT) sfx = SND_18_TAKEOFF_HELICOPTER;
912 SndPlayVehicleFx(sfx, v);
913 }
914 }
915 } else {
916 u->cur_speed = 32;
917 int count = UpdateAircraftSpeed(v);
918 if (count > 0) {
919 v->tile = 0;
920
921 int z_dest;
922 GetAircraftFlightLevelBounds(v, &z_dest, nullptr);
923
924 /* Reached altitude? */
925 if (v->z_pos >= z_dest) {
926 v->cur_speed = 0;
927 return true;
928 }
929 SetAircraftPosition(v, v->x_pos, v->y_pos, std::min(v->z_pos + count, z_dest));
930 }
931 }
932 return false;
933 }
934
935 /* Helicopter landing. */
936 if (amd.flag & AMED_HELI_LOWER) {
937 SetBit(v->flags, VAF_HELI_DIRECT_DESCENT);
938
939 if (st == nullptr) {
940 /* FIXME - AircraftController -> if station no longer exists, do not land
941 * helicopter will circle until sign disappears, then go to next order
942 * what to do when it is the only order left, right now it just stays in 1 place */
943 v->state = FLYING;
944 UpdateAircraftCache(v);
945 AircraftNextAirportPos_and_Order(v);
946 return false;
947 }
948
949 /* Vehicle is now at the airport.
950 * Helicopter has arrived at the target landing pad, so the current position is also where it should land.
951 * Except for Oilrigs which are special due to being a 1x1 station, and helicopters land outside it. */
952 if (st->airport.type != AT_OILRIG) {
953 x = v->x_pos;
954 y = v->y_pos;
955 tile = TileVirtXY(x, y);
956 }
957 v->tile = tile;
958
959 /* Find altitude of landing position. */
960 int z = GetSlopePixelZ(x, y) + 1 + afc->delta_z;
961
962 if (z == v->z_pos) {
963 Vehicle *u = v->Next()->Next();
964
965 /* Increase speed of rotors. When speed is 80, we've landed. */
966 if (u->cur_speed >= 80) {
967 ClrBit(v->flags, VAF_HELI_DIRECT_DESCENT);
968 return true;
969 }
970 u->cur_speed += 4;
971 } else {
972 int count = UpdateAircraftSpeed(v);
973 if (count > 0) {
974 if (v->z_pos > z) {
975 SetAircraftPosition(v, v->x_pos, v->y_pos, std::max(v->z_pos - count, z));
976 } else {
977 SetAircraftPosition(v, v->x_pos, v->y_pos, std::min(v->z_pos + count, z));
978 }
979 }
980 }
981 return false;
982 }
983
984 /* Get distance from destination pos to current pos. */
985 uint dist = abs(x + amd.x - v->x_pos) + abs(y + amd.y - v->y_pos);
986
987 /* Need exact position? */
988 if (!(amd.flag & AMED_EXACTPOS) && dist <= (amd.flag & AMED_SLOWTURN ? 8U : 4U)) return true;
989
990 /* At final pos? */
991 if (dist == 0) {
992 /* Change direction smoothly to final direction. */
993 DirDiff dirdiff = DirDifference(amd.direction, v->direction);
994 /* if distance is 0, and plane points in right direction, no point in calling
995 * UpdateAircraftSpeed(). So do it only afterwards */
996 if (dirdiff == DIRDIFF_SAME) {
997 v->cur_speed = 0;
998 return true;
999 }
1000
1001 if (!UpdateAircraftSpeed(v, SPEED_LIMIT_TAXI)) return false;
1002
1003 v->direction = ChangeDir(v->direction, dirdiff > DIRDIFF_REVERSE ? DIRDIFF_45LEFT : DIRDIFF_45RIGHT);
1004 v->cur_speed >>= 1;
1005
1006 SetAircraftPosition(v, v->x_pos, v->y_pos, v->z_pos);
1007 return false;
1008 }
1009
1010 if (amd.flag & AMED_BRAKE && v->cur_speed > SPEED_LIMIT_TAXI * _settings_game.vehicle.plane_speed) {
1011 MaybeCrashAirplane(v);
1012 if ((v->vehstatus & VS_CRASHED) != 0) return false;
1013 }
1014
1015 uint speed_limit = SPEED_LIMIT_TAXI;
1016 bool hard_limit = true;
1017
1018 if (amd.flag & AMED_NOSPDCLAMP) speed_limit = SPEED_LIMIT_NONE;
1019 if (amd.flag & AMED_HOLD) { speed_limit = SPEED_LIMIT_HOLD; hard_limit = false; }
1020 if (amd.flag & AMED_LAND) { speed_limit = SPEED_LIMIT_APPROACH; hard_limit = false; }
1021 if (amd.flag & AMED_BRAKE) { speed_limit = SPEED_LIMIT_TAXI; hard_limit = false; }
1022
1023 int count = UpdateAircraftSpeed(v, speed_limit, hard_limit);
1024 if (count == 0) return false;
1025
1026 /* If the plane will be a few subpixels away from the destination after
1027 * this movement loop, start nudging it towards the exact position for
1028 * the whole loop. Otherwise, heavily depending on the speed of the plane,
1029 * it is possible we totally overshoot the target, causing the plane to
1030 * make a loop, and trying again, and again, and again .. */
1031 bool nudge_towards_target = static_cast<uint>(count) + 3 > dist;
1032
1033 if (v->turn_counter != 0) v->turn_counter--;
1034
1035 do {
1036
1037 GetNewVehiclePosResult gp;
1038
1039 if (nudge_towards_target || (amd.flag & AMED_LAND)) {
1040 /* move vehicle one pixel towards target */
1041 gp.x = (v->x_pos != (x + amd.x)) ?
1042 v->x_pos + ((x + amd.x > v->x_pos) ? 1 : -1) :
1043 v->x_pos;
1044 gp.y = (v->y_pos != (y + amd.y)) ?
1045 v->y_pos + ((y + amd.y > v->y_pos) ? 1 : -1) :
1046 v->y_pos;
1047
1048 /* Oilrigs must keep v->tile as st->airport.tile, since the landing pad is in a non-airport tile */
1049 gp.new_tile = (st->airport.type == AT_OILRIG) ? st->airport.tile : TileVirtXY(gp.x, gp.y);
1050
1051 } else {
1052
1053 /* Turn. Do it slowly if in the air. */
1054 Direction newdir = GetDirectionTowards(v, x + amd.x, y + amd.y);
1055 if (newdir != v->direction) {
1056 if (amd.flag & AMED_SLOWTURN && v->number_consecutive_turns < 8 && v->subtype == AIR_AIRCRAFT) {
1057 if (v->turn_counter == 0 || newdir == v->last_direction) {
1058 if (newdir == v->last_direction) {
1059 v->number_consecutive_turns = 0;
1060 } else {
1061 v->number_consecutive_turns++;
1062 }
1063 v->turn_counter = 2 * _settings_game.vehicle.plane_speed;
1064 v->last_direction = v->direction;
1065 v->direction = newdir;
1066 }
1067
1068 /* Move vehicle. */
1069 gp = GetNewVehiclePos(v);
1070 } else {
1071 v->cur_speed >>= 1;
1072 v->direction = newdir;
1073
1074 /* When leaving a terminal an aircraft often goes to a position
1075 * directly in front of it. If it would move while turning it
1076 * would need an two extra turns to end up at the correct position.
1077 * To make it easier just disallow all moving while turning as
1078 * long as an aircraft is on the ground. */
1079 gp.x = v->x_pos;
1080 gp.y = v->y_pos;
1081 gp.new_tile = gp.old_tile = v->tile;
1082 }
1083 } else {
1084 v->number_consecutive_turns = 0;
1085 /* Move vehicle. */
1086 gp = GetNewVehiclePos(v);
1087 }
1088 }
1089
1090 v->tile = gp.new_tile;
1091 /* If vehicle is in the air, use tile coordinate 0. */
1092 if (amd.flag & (AMED_TAKEOFF | AMED_SLOWTURN | AMED_LAND)) v->tile = 0;
1093
1094 /* Adjust Z for land or takeoff? */
1095 int z = v->z_pos;
1096
1097 if (amd.flag & AMED_TAKEOFF) {
1098 z = GetAircraftFlightLevel(v, true);
1099 } else if (amd.flag & AMED_HOLD) {
1100 /* Let the plane drop from normal flight altitude to holding pattern altitude */
1101 if (z > GetAircraftHoldMaxAltitude(v)) z--;
1102 } else if ((amd.flag & AMED_SLOWTURN) && (amd.flag & AMED_NOSPDCLAMP)) {
1103 z = GetAircraftFlightLevel(v);
1104 }
1105
1106 /* NewGRF airports (like a rotated intercontinental from OpenGFX+Airports) can be non-rectangular
1107 * and their primary (north-most) tile does not have to be part of the airport.
1108 * As such, the height of the primary tile can be different from the rest of the airport.
1109 * Given we are landing/breaking, and as such are not a helicopter, we know that there has to be a hangar.
1110 * We also know that the airport itself has to be completely flat (otherwise it is not a valid airport).
1111 * Therefore, use the height of this hangar to calculate our z-value. */
1112 int airport_z = v->z_pos;
1113 if ((amd.flag & (AMED_LAND | AMED_BRAKE)) && st != nullptr) {
1114 assert(st->airport.HasHangar());
1115 TileIndex hangar_tile = st->airport.GetHangarTile(0);
1116 airport_z = GetTileMaxPixelZ(hangar_tile) + 1; // To avoid clashing with the shadow
1117 }
1118
1119 if (amd.flag & AMED_LAND) {
1120 if (st->airport.tile == INVALID_TILE) {
1121 /* Airport has been removed, abort the landing procedure */
1122 v->state = FLYING;
1123 UpdateAircraftCache(v);
1124 AircraftNextAirportPos_and_Order(v);
1125 /* get aircraft back on running altitude */
1126 SetAircraftPosition(v, gp.x, gp.y, GetAircraftFlightLevel(v));
1127 continue;
1128 }
1129
1130 /* We're not flying below our destination, right? */
1131 assert(airport_z <= z);
1132 int t = std::max(1U, dist - 4);
1133 int delta = z - airport_z;
1134
1135 /* Only start lowering when we're sufficiently close for a 1:1 glide */
1136 if (delta >= t) {
1137 z -= CeilDiv(z - airport_z, t);
1138 }
1139 if (z < airport_z) z = airport_z;
1140 }
1141
1142 /* We've landed. Decrease speed when we're reaching end of runway. */
1143 if (amd.flag & AMED_BRAKE) {
1144
1145 if (z > airport_z) {
1146 z--;
1147 } else if (z < airport_z) {
1148 z++;
1149 }
1150
1151 }
1152
1153 SetAircraftPosition(v, gp.x, gp.y, z);
1154 } while (--count != 0);
1155 return false;
1156 }
1157
1162 static bool HandleCrashedAircraft(Aircraft *v)
1163 {
1164 v->crashed_counter += 3;
1165
1166 Station *st = GetTargetAirportIfValid(v);
1167
1168 /* make aircraft crash down to the ground */
1169 if (v->crashed_counter < 500 && st == nullptr && ((v->crashed_counter % 3) == 0) ) {
1170 int z = GetSlopePixelZ(Clamp(v->x_pos, 0, MapMaxX() * TILE_SIZE), Clamp(v->y_pos, 0, MapMaxY() * TILE_SIZE));
1171 v->z_pos -= 1;
1172 if (v->z_pos == z) {
1173 v->crashed_counter = 500;
1174 v->z_pos++;
1175 }
1176 }
1177
1178 if (v->crashed_counter < 650) {
1179 uint32 r;
1180 if (Chance16R(1, 32, r)) {
1181 static const DirDiff delta[] = {
1182 DIRDIFF_45LEFT, DIRDIFF_SAME, DIRDIFF_SAME, DIRDIFF_45RIGHT
1183 };
1184
1185 v->direction = ChangeDir(v->direction, delta[GB(r, 16, 2)]);
1186 SetAircraftPosition(v, v->x_pos, v->y_pos, v->z_pos);
1187 r = Random();
1188 CreateEffectVehicleRel(v,
1189 GB(r, 0, 4) - 4,
1190 GB(r, 4, 4) - 4,
1191 GB(r, 8, 4),
1192 EV_EXPLOSION_SMALL);
1193 }
1194 } else if (v->crashed_counter >= 10000) {
1195 /* remove rubble of crashed airplane */
1196
1197 /* clear runway-in on all airports, set by crashing plane
1198 * small airports use AIRPORT_BUSY, city airports use RUNWAY_IN_OUT_block, etc.
1199 * but they all share the same number */
1200 if (st != nullptr) {
1201 CLRBITS(st->airport.flags, RUNWAY_IN_block);
1202 CLRBITS(st->airport.flags, RUNWAY_IN_OUT_block); // commuter airport
1203 CLRBITS(st->airport.flags, RUNWAY_IN2_block); // intercontinental
1204 }
1205
1206 delete v;
1207
1208 return false;
1209 }
1210
1211 return true;
1212 }
1213
1214
1220 static void HandleAircraftSmoke(Aircraft *v, bool mode)
1221 {
1222 static const struct {
1223 int8 x;
1224 int8 y;
1225 } smoke_pos[] = {
1226 { 5, 5 },
1227 { 6, 0 },
1228 { 5, -5 },
1229 { 0, -6 },
1230 { -5, -5 },
1231 { -6, 0 },
1232 { -5, 5 },
1233 { 0, 6 }
1234 };
1235
1236 if (!(v->vehstatus & VS_AIRCRAFT_BROKEN)) return;
1237
1238 /* Stop smoking when landed */
1239 if (v->cur_speed < 10) {
1240 v->vehstatus &= ~VS_AIRCRAFT_BROKEN;
1241 v->breakdown_ctr = 0;
1242 return;
1243 }
1244
1245 /* Spawn effect et most once per Tick, i.e. !mode */
1246 if (!mode && (v->tick_counter & 0x0F) == 0) {
1247 CreateEffectVehicleRel(v,
1248 smoke_pos[v->direction].x,
1249 smoke_pos[v->direction].y,
1250 2,
1251 EV_BREAKDOWN_SMOKE_AIRCRAFT
1252 );
1253 }
1254 }
1255
1256 void HandleMissingAircraftOrders(Aircraft *v)
1257 {
1258 /*
1259 * We do not have an order. This can be divided into two cases:
1260 * 1) we are heading to an invalid station. In this case we must
1261 * find another airport to go to. If there is nowhere to go,
1262 * we will destroy the aircraft as it otherwise will enter
1263 * the holding pattern for the first airport, which can cause
1264 * the plane to go into an undefined state when building an
1265 * airport with the same StationID.
1266 * 2) we are (still) heading to a (still) valid airport, then we
1267 * can continue going there. This can happen when you are
1268 * changing the aircraft's orders while in-flight or in for
1269 * example a depot. However, when we have a current order to
1270 * go to a depot, we have to keep that order so the aircraft
1271 * actually stops.
1272 */
1273 const Station *st = GetTargetAirportIfValid(v);
1274 if (st == nullptr) {
1275 Backup<CompanyID> cur_company(_current_company, v->owner, FILE_LINE);
1276 CommandCost ret = Command<CMD_SEND_VEHICLE_TO_DEPOT>::Do(DC_EXEC, v->index, DepotCommand::None, {});
1277 cur_company.Restore();
1278
1279 if (ret.Failed()) CrashAirplane(v);
1280 } else if (!v->current_order.IsType(OT_GOTO_DEPOT)) {
1281 v->current_order.Free();
1282 }
1283 }
1284
1285
1286 TileIndex Aircraft::GetOrderStationLocation(StationID station)
1287 {
1288 /* Orders are changed in flight, ensure going to the right station. */
1289 if (this->state == FLYING) {
1290 AircraftNextAirportPos_and_Order(this);
1291 }
1292
1293 /* Aircraft do not use dest-tile */
1294 return 0;
1295 }
1296
1297 void Aircraft::MarkDirty()
1298 {
1299 this->colourmap = PAL_NONE;
1300 this->UpdateViewport(true, false);
1301 if (this->subtype == AIR_HELICOPTER) {
1302 GetRotorImage(this, EIT_ON_MAP, &this->Next()->Next()->sprite_cache.sprite_seq);
1303 }
1304 }
1305
1306
1307 uint Aircraft::Crash(bool flooded)
1308 {
1309 uint pass = Vehicle::Crash(flooded) + 2; // pilots
1310 this->crashed_counter = flooded ? 9000 : 0; // max 10000, disappear pretty fast when flooded
1311
1312 return pass;
1313 }
1314
1319 static void CrashAirplane(Aircraft *v)
1320 {
1321 CreateEffectVehicleRel(v, 4, 4, 8, EV_EXPLOSION_LARGE);
1322
1323 uint pass = v->Crash();
1324 SetDParam(0, pass);
1325
1326 v->cargo.Truncate();
1327 v->Next()->cargo.Truncate();
1328 const Station *st = GetTargetAirportIfValid(v);
1329 StringID newsitem;
1330 TileIndex vt;
1331 if (st == nullptr) {
1332 newsitem = STR_NEWS_PLANE_CRASH_OUT_OF_FUEL;
1333 vt = TileVirtXY(v->x_pos, v->y_pos);
1334 } else {
1335 SetDParam(1, st->index);
1336 newsitem = STR_NEWS_AIRCRAFT_CRASH;
1337 vt = v->tile;
1338 }
1339
1340 AI::NewEvent(v->owner, new ScriptEventVehicleCrashed(v->index, vt, st == nullptr ? ScriptEventVehicleCrashed::CRASH_AIRCRAFT_NO_AIRPORT : ScriptEventVehicleCrashed::CRASH_PLANE_LANDING));
1341 Game::NewEvent(new ScriptEventVehicleCrashed(v->index, vt, st == nullptr ? ScriptEventVehicleCrashed::CRASH_AIRCRAFT_NO_AIRPORT : ScriptEventVehicleCrashed::CRASH_PLANE_LANDING));
1342
1343 NewsType newstype = NT_ACCIDENT;
1344 if (v->owner != _local_company) {
1345 newstype = NT_ACCIDENT_OTHER;
1346 }
1347
1348 AddTileNewsItem(newsitem, newstype, vt, nullptr, st != nullptr ? st->index : INVALID_STATION);
1349
1350 ModifyStationRatingAround(vt, v->owner, -160, 30);
1351 if (_settings_client.sound.disaster) SndPlayVehicleFx(SND_12_EXPLOSION, v);
1352 }
1353
1358 static void MaybeCrashAirplane(Aircraft *v)
1359 {
1360
1361 Station *st = Station::Get(v->targetairport);
1362
1363 uint32 prob;
1364 if ((st->airport.GetFTA()->flags & AirportFTAClass::SHORT_STRIP) &&
1365 (AircraftVehInfo(v->engine_type)->subtype & AIR_FAST) &&
1366 !_cheats.no_jetcrash.value) {
1367 prob = 3276;
1368 } else {
1369 if (_settings_game.vehicle.plane_crashes == 0) return;
1370 prob = (0x4000 << _settings_game.vehicle.plane_crashes) / 1500;
1371 }
1372
1373 if (GB(Random(), 0, 22) > prob) return;
1374
1375 /* Crash the airplane. Remove all goods stored at the station. */
1376 for (CargoID i = 0; i < NUM_CARGO; i++) {
1377 st->goods[i].rating = 1;
1378 st->goods[i].cargo.Truncate();
1379 }
1380
1381 CrashAirplane(v);
1382 }
1383
1389 static void AircraftEntersTerminal(Aircraft *v)
1390 {
1391 if (v->current_order.IsType(OT_GOTO_DEPOT)) return;
1392
1393 Station *st = Station::Get(v->targetairport);
1394 v->last_station_visited = v->targetairport;
1395
1396 /* Check if station was ever visited before */
1397 if (!(st->had_vehicle_of_type & HVOT_AIRCRAFT)) {
1398 st->had_vehicle_of_type |= HVOT_AIRCRAFT;
1399 SetDParam(0, st->index);
1400 /* show newsitem of celebrating citizens */
1401 AddVehicleNewsItem(
1402 STR_NEWS_FIRST_AIRCRAFT_ARRIVAL,
1403 (v->owner == _local_company) ? NT_ARRIVAL_COMPANY : NT_ARRIVAL_OTHER,
1404 v->index,
1405 st->index
1406 );
1407 AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
1408 Game::NewEvent(new ScriptEventStationFirstVehicle(st->index, v->index));
1409 }
1410
1411 v->BeginLoading();
1412 }
1413
1418 static void AircraftLandAirplane(Aircraft *v)
1419 {
1420 Station *st = Station::Get(v->targetairport);
1421
1422 TileIndex vt = TileVirtXY(v->x_pos, v->y_pos);
1423
1424 v->UpdateDeltaXY();
1425
1426 AirportTileAnimationTrigger(st, vt, AAT_STATION_AIRPLANE_LAND);
1427
1428 if (!PlayVehicleSound(v, VSE_TOUCHDOWN)) {
1429 SndPlayVehicleFx(SND_17_SKID_PLANE, v);
1430 }
1431 }
1432
1433
1435 void AircraftNextAirportPos_and_Order(Aircraft *v)
1436 {
1437 if (v->current_order.IsType(OT_GOTO_STATION) || v->current_order.IsType(OT_GOTO_DEPOT)) {
1438 v->targetairport = v->current_order.GetDestination();
1439 }
1440
1441 const Station *st = GetTargetAirportIfValid(v);
1442 const AirportFTAClass *apc = st == nullptr ? GetAirport(AT_DUMMY) : st->airport.GetFTA();
1443 Direction rotation = st == nullptr ? DIR_N : st->airport.rotation;
1444 v->pos = v->previous_pos = AircraftGetEntryPoint(v, apc, rotation);
1445 }
1446
1455 void AircraftLeaveHangar(Aircraft *v, Direction exit_dir)
1456 {
1457 v->cur_speed = 0;
1458 v->subspeed = 0;
1459 v->progress = 0;
1460 v->direction = exit_dir;
1461 v->vehstatus &= ~VS_HIDDEN;
1462 {
1463 Vehicle *u = v->Next();
1464 u->vehstatus &= ~VS_HIDDEN;
1465
1466 /* Rotor blades */
1467 u = u->Next();
1468 if (u != nullptr) {
1469 u->vehstatus &= ~VS_HIDDEN;
1470 u->cur_speed = 80;
1471 }
1472 }
1473
1474 VehicleServiceInDepot(v);
1475 SetAircraftPosition(v, v->x_pos, v->y_pos, v->z_pos);
1476 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
1477 SetWindowClassesDirty(WC_AIRCRAFT_LIST);
1478 }
1479
1483 static void AircraftEventHandler_EnterTerminal(Aircraft *v, const AirportFTAClass *apc)
1484 {
1485 AircraftEntersTerminal(v);
1486 v->state = apc->layout[v->pos].heading;
1487 }
1488
1494 static void AircraftEventHandler_EnterHangar(Aircraft *v, const AirportFTAClass *apc)
1495 {
1496 VehicleEnterDepot(v);
1497 v->state = apc->layout[v->pos].heading;
1498 }
1499
1505 static void AircraftEventHandler_InHangar(Aircraft *v, const AirportFTAClass *apc)
1506 {
1507 /* if we just arrived, execute EnterHangar first */
1508 if (v->previous_pos != v->pos) {
1509 AircraftEventHandler_EnterHangar(v, apc);
1510 return;
1511 }
1512
1513 /* if we were sent to the depot, stay there */
1514 if (v->current_order.IsType(OT_GOTO_DEPOT) && (v->vehstatus & VS_STOPPED)) {
1515 v->current_order.Free();
1516 return;
1517 }
1518
1519 if (!v->current_order.IsType(OT_GOTO_STATION) &&
1520 !v->current_order.IsType(OT_GOTO_DEPOT))
1521 return;
1522
1523 /* We are leaving a hangar, but have to go to the exact same one; re-enter */
1524 if (v->current_order.IsType(OT_GOTO_DEPOT) && v->current_order.GetDestination() == v->targetairport) {
1525 VehicleEnterDepot(v);
1526 return;
1527 }
1528
1529 /* if the block of the next position is busy, stay put */
1530 if (AirportHasBlock(v, &apc->layout[v->pos], apc)) return;
1531
1532 /* We are already at the target airport, we need to find a terminal */
1533 if (v->current_order.GetDestination() == v->targetairport) {
1534 /* FindFreeTerminal:
1535 * 1. Find a free terminal, 2. Occupy it, 3. Set the vehicle's state to that terminal */
1536 if (v->subtype == AIR_HELICOPTER) {
1537 if (!AirportFindFreeHelipad(v, apc)) return; // helicopter
1538 } else {
1539 if (!AirportFindFreeTerminal(v, apc)) return; // airplane
1540 }
1541 } else { // Else prepare for launch.
1542 /* airplane goto state takeoff, helicopter to helitakeoff */
1543 v->state = (v->subtype == AIR_HELICOPTER) ? HELITAKEOFF : TAKEOFF;
1544 }
1545 const Station *st = Station::GetByTile(v->tile);
1546 AircraftLeaveHangar(v, st->airport.GetHangarExitDirection(v->tile));
1547 AirportMove(v, apc);
1548 }
1549
1551 static void AircraftEventHandler_AtTerminal(Aircraft *v, const AirportFTAClass *apc)
1552 {
1553 /* if we just arrived, execute EnterTerminal first */
1554 if (v->previous_pos != v->pos) {
1555 AircraftEventHandler_EnterTerminal(v, apc);
1556 /* on an airport with helipads, a helicopter will always land there
1557 * and get serviced at the same time - setting */
1558 if (_settings_game.order.serviceathelipad) {
1559 if (v->subtype == AIR_HELICOPTER && apc->num_helipads > 0) {
1560 /* an excerpt of ServiceAircraft, without the invisibility stuff */
1561 v->date_of_last_service = _date;
1562 v->breakdowns_since_last_service = 0;
1563 v->reliability = v->GetEngine()->reliability;
1564 SetWindowDirty(WC_VEHICLE_DETAILS, v->index);
1565 }
1566 }
1567 return;
1568 }
1569
1570 if (v->current_order.IsType(OT_NOTHING)) return;
1571
1572 /* if the block of the next position is busy, stay put */
1573 if (AirportHasBlock(v, &apc->layout[v->pos], apc)) return;
1574
1575 /* airport-road is free. We either have to go to another airport, or to the hangar
1576 * ---> start moving */
1577
1578 bool go_to_hangar = false;
1579 switch (v->current_order.GetType()) {
1580 case OT_GOTO_STATION: // ready to fly to another airport
1581 break;
1582 case OT_GOTO_DEPOT: // visit hangar for servicing, sale, etc.
1583 go_to_hangar = v->current_order.GetDestination() == v->targetairport;
1584 break;
1585 case OT_CONDITIONAL:
1586 /* In case of a conditional order we just have to wait a tick
1587 * longer, so the conditional order can actually be processed;
1588 * we should not clear the order as that makes us go nowhere. */
1589 return;
1590 default: // orders have been deleted (no orders), goto depot and don't bother us
1591 v->current_order.Free();
1592 go_to_hangar = Station::Get(v->targetairport)->airport.HasHangar();
1593 }
1594
1595 if (go_to_hangar && Station::Get(v->targetairport)->airport.HasHangar()) {
1596 v->state = HANGAR;
1597 } else {
1598 /* airplane goto state takeoff, helicopter to helitakeoff */
1599 v->state = (v->subtype == AIR_HELICOPTER) ? HELITAKEOFF : TAKEOFF;
1600 }
1601 AirportMove(v, apc);
1602 }
1603
1604 static void AircraftEventHandler_General(Aircraft *v, const AirportFTAClass *apc)
1605 {
1606 error("OK, you shouldn't be here, check your Airport Scheme!");
1607 }
1608
1609 static void AircraftEventHandler_TakeOff(Aircraft *v, const AirportFTAClass *apc)
1610 {
1611 PlayAircraftSound(v); // play takeoffsound for airplanes
1612 v->state = STARTTAKEOFF;
1613 }
1614
1615 static void AircraftEventHandler_StartTakeOff(Aircraft *v, const AirportFTAClass *apc)
1616 {
1617 v->state = ENDTAKEOFF;
1618 v->UpdateDeltaXY();
1619 }
1620
1621 static void AircraftEventHandler_EndTakeOff(Aircraft *v, const AirportFTAClass *apc)
1622 {
1623 v->state = FLYING;
1624 /* get the next position to go to, differs per airport */
1625 AircraftNextAirportPos_and_Order(v);
1626 }
1627
1628 static void AircraftEventHandler_HeliTakeOff(Aircraft *v, const AirportFTAClass *apc)
1629 {
1630 v->state = FLYING;
1631 v->UpdateDeltaXY();
1632
1633 /* get the next position to go to, differs per airport */
1634 AircraftNextAirportPos_and_Order(v);
1635
1636 /* Send the helicopter to a hangar if needed for replacement */
1637 if (v->NeedsAutomaticServicing()) {
1638 Backup<CompanyID> cur_company(_current_company, v->owner, FILE_LINE);
1639 Command<CMD_SEND_VEHICLE_TO_DEPOT>::Do(DC_EXEC, v->index, DepotCommand::Service | DepotCommand::LocateHangar, {});
1640 cur_company.Restore();
1641 }
1642 }
1643
1644 static void AircraftEventHandler_Flying(Aircraft *v, const AirportFTAClass *apc)
1645 {
1646 Station *st = Station::Get(v->targetairport);
1647
1648 /* Runway busy, not allowed to use this airstation or closed, circle. */
1649 if (CanVehicleUseStation(v, st) && (st->owner == OWNER_NONE || st->owner == v->owner) && !(st->airport.flags & AIRPORT_CLOSED_block)) {
1650 /* {32,FLYING,NOTHING_block,37}, {32,LANDING,N,33}, {32,HELILANDING,N,41},
1651 * if it is an airplane, look for LANDING, for helicopter HELILANDING
1652 * it is possible to choose from multiple landing runways, so loop until a free one is found */
1653 byte landingtype = (v->subtype == AIR_HELICOPTER) ? HELILANDING : LANDING;
1654 const AirportFTA *current = apc->layout[v->pos].next;
1655 while (current != nullptr) {
1656 if (current->heading == landingtype) {
1657 /* save speed before, since if AirportHasBlock is false, it resets them to 0
1658 * we don't want that for plane in air
1659 * hack for speed thingie */
1660 uint16 tcur_speed = v->cur_speed;
1661 uint16 tsubspeed = v->subspeed;
1662 if (!AirportHasBlock(v, current, apc)) {
1663 v->state = landingtype; // LANDING / HELILANDING
1664 if (v->state == HELILANDING) SetBit(v->flags, VAF_HELI_DIRECT_DESCENT);
1665 /* it's a bit dirty, but I need to set position to next position, otherwise
1666 * if there are multiple runways, plane won't know which one it took (because
1667 * they all have heading LANDING). And also occupy that block! */
1668 v->pos = current->next_position;
1669 SETBITS(st->airport.flags, apc->layout[v->pos].block);
1670 return;
1671 }
1672 v->cur_speed = tcur_speed;
1673 v->subspeed = tsubspeed;
1674 }
1675 current = current->next;
1676 }
1677 }
1678 v->state = FLYING;
1679 v->pos = apc->layout[v->pos].next_position;
1680 }
1681
1682 static void AircraftEventHandler_Landing(Aircraft *v, const AirportFTAClass *apc)
1683 {
1684 v->state = ENDLANDING;
1685 AircraftLandAirplane(v); // maybe crash airplane
1686
1687 /* check if the aircraft needs to be replaced or renewed and send it to a hangar if needed */
1688 if (v->NeedsAutomaticServicing()) {
1689 Backup<CompanyID> cur_company(_current_company, v->owner, FILE_LINE);
1690 Command<CMD_SEND_VEHICLE_TO_DEPOT>::Do(DC_EXEC, v->index, DepotCommand::Service, {});
1691 cur_company.Restore();
1692 }
1693 }
1694
1695 static void AircraftEventHandler_HeliLanding(Aircraft *v, const AirportFTAClass *apc)
1696 {
1697 v->state = HELIENDLANDING;
1698 v->UpdateDeltaXY();
1699 }
1700
1701 static void AircraftEventHandler_EndLanding(Aircraft *v, const AirportFTAClass *apc)
1702 {
1703 /* next block busy, don't do a thing, just wait */
1704 if (AirportHasBlock(v, &apc->layout[v->pos], apc)) return;
1705
1706 /* if going to terminal (OT_GOTO_STATION) choose one
1707 * 1. in case all terminals are busy AirportFindFreeTerminal() returns false or
1708 * 2. not going for terminal (but depot, no order),
1709 * --> get out of the way to the hangar. */
1710 if (v->current_order.IsType(OT_GOTO_STATION)) {
1711 if (AirportFindFreeTerminal(v, apc)) return;
1712 }
1713 v->state = HANGAR;
1714
1715 }
1716
1717 static void AircraftEventHandler_HeliEndLanding(Aircraft *v, const AirportFTAClass *apc)
1718 {
1719 /* next block busy, don't do a thing, just wait */
1720 if (AirportHasBlock(v, &apc->layout[v->pos], apc)) return;
1721
1722 /* if going to helipad (OT_GOTO_STATION) choose one. If airport doesn't have helipads, choose terminal
1723 * 1. in case all terminals/helipads are busy (AirportFindFreeHelipad() returns false) or
1724 * 2. not going for terminal (but depot, no order),
1725 * --> get out of the way to the hangar IF there are terminals on the airport.
1726 * --> else TAKEOFF
1727 * the reason behind this is that if an airport has a terminal, it also has a hangar. Airplanes
1728 * must go to a hangar. */
1729 if (v->current_order.IsType(OT_GOTO_STATION)) {
1730 if (AirportFindFreeHelipad(v, apc)) return;
1731 }
1732 v->state = Station::Get(v->targetairport)->airport.HasHangar() ? HANGAR : HELITAKEOFF;
1733 }
1734
1740 typedef void AircraftStateHandler(Aircraft *v, const AirportFTAClass *apc);
1742 static AircraftStateHandler * const _aircraft_state_handlers[] = {
1743 AircraftEventHandler_General, // TO_ALL = 0
1744 AircraftEventHandler_InHangar, // HANGAR = 1
1745 AircraftEventHandler_AtTerminal, // TERM1 = 2
1746 AircraftEventHandler_AtTerminal, // TERM2 = 3
1747 AircraftEventHandler_AtTerminal, // TERM3 = 4
1748 AircraftEventHandler_AtTerminal, // TERM4 = 5
1749 AircraftEventHandler_AtTerminal, // TERM5 = 6
1750 AircraftEventHandler_AtTerminal, // TERM6 = 7
1751 AircraftEventHandler_AtTerminal, // HELIPAD1 = 8
1752 AircraftEventHandler_AtTerminal, // HELIPAD2 = 9
1753 AircraftEventHandler_TakeOff, // TAKEOFF = 10
1754 AircraftEventHandler_StartTakeOff, // STARTTAKEOFF = 11
1755 AircraftEventHandler_EndTakeOff, // ENDTAKEOFF = 12
1756 AircraftEventHandler_HeliTakeOff, // HELITAKEOFF = 13
1757 AircraftEventHandler_Flying, // FLYING = 14
1758 AircraftEventHandler_Landing, // LANDING = 15
1759 AircraftEventHandler_EndLanding, // ENDLANDING = 16
1760 AircraftEventHandler_HeliLanding, // HELILANDING = 17
1761 AircraftEventHandler_HeliEndLanding, // HELIENDLANDING = 18
1762 AircraftEventHandler_AtTerminal, // TERM7 = 19
1763 AircraftEventHandler_AtTerminal, // TERM8 = 20
1764 AircraftEventHandler_AtTerminal, // HELIPAD3 = 21
1765 };
1766
1767 static void AirportClearBlock(const Aircraft *v, const AirportFTAClass *apc)
1768 {
1769 /* we have left the previous block, and entered the new one. Free the previous block */
1770 if (apc->layout[v->previous_pos].block != apc->layout[v->pos].block) {
1771 Station *st = Station::Get(v->targetairport);
1772
1773 CLRBITS(st->airport.flags, apc->layout[v->previous_pos].block);
1774 }
1775 }
1776
1777 static void AirportGoToNextPosition(Aircraft *v)
1778 {
1779 /* if aircraft is not in position, wait until it is */
1780 if (!AircraftController(v)) return;
1781
1782 const AirportFTAClass *apc = Station::Get(v->targetairport)->airport.GetFTA();
1783
1784 AirportClearBlock(v, apc);
1785 AirportMove(v, apc); // move aircraft to next position
1786 }
1787
1788 /* gets pos from vehicle and next orders */
1789 static bool AirportMove(Aircraft *v, const AirportFTAClass *apc)
1790 {
1791 /* error handling */
1792 if (v->pos >= apc->nofelements) {
1793 Debug(misc, 0, "[Ap] position {} is not valid for current airport. Max position is {}", v->pos, apc->nofelements-1);
1794 assert(v->pos < apc->nofelements);
1795 }
1796
1797 const AirportFTA *current = &apc->layout[v->pos];
1798 /* we have arrived in an important state (eg terminal, hangar, etc.) */
1799 if (current->heading == v->state) {
1800 byte prev_pos = v->pos; // location could be changed in state, so save it before-hand
1801 byte prev_state = v->state;
1802 _aircraft_state_handlers[v->state](v, apc);
1803 if (v->state != FLYING) v->previous_pos = prev_pos;
1804 if (v->state != prev_state || v->pos != prev_pos) UpdateAircraftCache(v);
1805 return true;
1806 }
1807
1808 v->previous_pos = v->pos; // save previous location
1809
1810 /* there is only one choice to move to */
1811 if (current->next == nullptr) {
1812 if (AirportSetBlocks(v, current, apc)) {
1813 v->pos = current->next_position;
1814 UpdateAircraftCache(v);
1815 } // move to next position
1816 return false;
1817 }
1818
1819 /* there are more choices to choose from, choose the one that
1820 * matches our heading */
1821 do {
1822 if (v->state == current->heading || current->heading == TO_ALL) {
1823 if (AirportSetBlocks(v, current, apc)) {
1824 v->pos = current->next_position;
1825 UpdateAircraftCache(v);
1826 } // move to next position
1827 return false;
1828 }
1829 current = current->next;
1830 } while (current != nullptr);
1831
1832 Debug(misc, 0, "[Ap] cannot move further on Airport! (pos {} state {}) for vehicle {}", v->pos, v->state, v->index);
1833 NOT_REACHED();
1834 }
1835
1837 static bool AirportHasBlock(Aircraft *v, const AirportFTA *current_pos, const AirportFTAClass *apc)
1838 {
1839 const AirportFTA *reference = &apc->layout[v->pos];
1840 const AirportFTA *next = &apc->layout[current_pos->next_position];
1841
1842 /* same block, then of course we can move */
1843 if (apc->layout[current_pos->position].block != next->block) {
1844 const Station *st = Station::Get(v->targetairport);
1845 uint64 airport_flags = next->block;
1846
1847 /* check additional possible extra blocks */
1848 if (current_pos != reference && current_pos->block != NOTHING_block) {
1849 airport_flags |= current_pos->block;
1850 }
1851
1852 if (st->airport.flags & airport_flags) {
1853 v->cur_speed = 0;
1854 v->subspeed = 0;
1855 return true;
1856 }
1857 }
1858 return false;
1859 }
1860
1868 static bool AirportSetBlocks(Aircraft *v, const AirportFTA *current_pos, const AirportFTAClass *apc)
1869 {
1870 const AirportFTA *next = &apc->layout[current_pos->next_position];
1871 const AirportFTA *reference = &apc->layout[v->pos];
1872
1873 /* if the next position is in another block, check it and wait until it is free */
1874 if ((apc->layout[current_pos->position].block & next->block) != next->block) {
1875 uint64 airport_flags = next->block;
1876 /* search for all all elements in the list with the same state, and blocks != N
1877 * this means more blocks should be checked/set */
1878 const AirportFTA *current = current_pos;
1879 if (current == reference) current = current->next;
1880 while (current != nullptr) {
1881 if (current->heading == current_pos->heading && current->block != 0) {
1882 airport_flags |= current->block;
1883 break;
1884 }
1885 current = current->next;
1886 }
1887
1888 /* if the block to be checked is in the next position, then exclude that from
1889 * checking, because it has been set by the airplane before */
1890 if (current_pos->block == next->block) airport_flags ^= next->block;
1891
1892 Station *st = Station::Get(v->targetairport);
1893 if (st->airport.flags & airport_flags) {
1894 v->cur_speed = 0;
1895 v->subspeed = 0;
1896 return false;
1897 }
1898
1899 if (next->block != NOTHING_block) {
1900 SETBITS(st->airport.flags, airport_flags); // occupy next block
1901 }
1902 }
1903 return true;
1904 }
1905
1910 struct MovementTerminalMapping {
1911 AirportMovementStates state;
1912 uint64 airport_flag;
1913 };
1914
1916 static const MovementTerminalMapping _airport_terminal_mapping[] = {
1917 {TERM1, TERM1_block},
1918 {TERM2, TERM2_block},
1919 {TERM3, TERM3_block},
1920 {TERM4, TERM4_block},
1921 {TERM5, TERM5_block},
1922 {TERM6, TERM6_block},
1923 {TERM7, TERM7_block},
1924 {TERM8, TERM8_block},
1925 {HELIPAD1, HELIPAD1_block},
1926 {HELIPAD2, HELIPAD2_block},
1927 {HELIPAD3, HELIPAD3_block},
1928 };
1929
1937 static bool FreeTerminal(Aircraft *v, byte i, byte last_terminal)
1938 {
1939 assert(last_terminal <= lengthof(_airport_terminal_mapping));
1940 Station *st = Station::Get(v->targetairport);
1941 for (; i < last_terminal; i++) {
1942 if ((st->airport.flags & _airport_terminal_mapping[i].airport_flag) == 0) {
1943 /* TERMINAL# HELIPAD# */
1944 v->state = _airport_terminal_mapping[i].state; // start moving to that terminal/helipad
1945 SETBITS(st->airport.flags, _airport_terminal_mapping[i].airport_flag); // occupy terminal/helipad
1946 return true;
1947 }
1948 }
1949 return false;
1950 }
1951
1957 static uint GetNumTerminals(const AirportFTAClass *apc)
1958 {
1959 uint num = 0;
1960
1961 for (uint i = apc->terminals[0]; i > 0; i--) num += apc->terminals[i];
1962
1963 return num;
1964 }
1965
1972 static bool AirportFindFreeTerminal(Aircraft *v, const AirportFTAClass *apc)
1973 {
1974 /* example of more terminalgroups
1975 * {0,HANGAR,NOTHING_block,1}, {0,TERMGROUP,TERM_GROUP1_block,0}, {0,TERMGROUP,TERM_GROUP2_ENTER_block,1}, {0,0,N,1},
1976 * Heading TERMGROUP denotes a group. We see 2 groups here:
1977 * 1. group 0 -- TERM_GROUP1_block (check block)
1978 * 2. group 1 -- TERM_GROUP2_ENTER_block (check block)
1979 * First in line is checked first, group 0. If the block (TERM_GROUP1_block) is free, it
1980 * looks at the corresponding terminals of that group. If no free ones are found, other
1981 * possible groups are checked (in this case group 1, since that is after group 0). If that
1982 * fails, then attempt fails and plane waits
1983 */
1984 if (apc->terminals[0] > 1) {
1985 const Station *st = Station::Get(v->targetairport);
1986 const AirportFTA *temp = apc->layout[v->pos].next;
1987
1988 while (temp != nullptr) {
1989 if (temp->heading == TERMGROUP) {
1990 if (!(st->airport.flags & temp->block)) {
1991 /* read which group do we want to go to?
1992 * (the first free group) */
1993 uint target_group = temp->next_position + 1;
1994
1995 /* at what terminal does the group start?
1996 * that means, sum up all terminals of
1997 * groups with lower number */
1998 uint group_start = 0;
1999 for (uint i = 1; i < target_group; i++) {
2000 group_start += apc->terminals[i];
2001 }
2002
2003 uint group_end = group_start + apc->terminals[target_group];
2004 if (FreeTerminal(v, group_start, group_end)) return true;
2005 }
2006 } else {
2007 /* once the heading isn't 255, we've exhausted the possible blocks.
2008 * So we cannot move */
2009 return false;
2010 }
2011 temp = temp->next;
2012 }
2013 }
2014
2015 /* if there is only 1 terminalgroup, all terminals are checked (starting from 0 to max) */
2016 return FreeTerminal(v, 0, GetNumTerminals(apc));
2017 }
2018
2025 static bool AirportFindFreeHelipad(Aircraft *v, const AirportFTAClass *apc)
2026 {
2027 /* if an airport doesn't have helipads, use terminals */
2028 if (apc->num_helipads == 0) return AirportFindFreeTerminal(v, apc);
2029
2030 /* only 1 helicoptergroup, check all helipads
2031 * The blocks for helipads start after the last terminal (MAX_TERMINALS) */
2032 return FreeTerminal(v, MAX_TERMINALS, apc->num_helipads + MAX_TERMINALS);
2033 }
2034
2040 static void AircraftHandleDestTooFar(Aircraft *v, bool too_far)
2041 {
2042 if (too_far) {
2043 if (!HasBit(v->flags, VAF_DEST_TOO_FAR)) {
2044 SetBit(v->flags, VAF_DEST_TOO_FAR);
2045 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
2046 AI::NewEvent(v->owner, new ScriptEventAircraftDestTooFar(v->index));
2047 if (v->owner == _local_company) {
2048 /* Post a news message. */
2049 SetDParam(0, v->index);
2050 AddVehicleAdviceNewsItem(STR_NEWS_AIRCRAFT_DEST_TOO_FAR, v->index);
2051 }
2052 }
2053 return;
2054 }
2055
2056 if (HasBit(v->flags, VAF_DEST_TOO_FAR)) {
2057 /* Not too far anymore, clear flag and message. */
2058 ClrBit(v->flags, VAF_DEST_TOO_FAR);
2059 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
2060 DeleteVehicleNews(v->index, STR_NEWS_AIRCRAFT_DEST_TOO_FAR);
2061 }
2062 }
2063
2064 static bool AircraftEventHandler(Aircraft *v, int loop)
2065 {
2066 if (v->vehstatus & VS_CRASHED) {
2067 return HandleCrashedAircraft(v);
2068 }
2069
2070 if (v->vehstatus & VS_STOPPED) return true;
2071
2072 v->HandleBreakdown();
2073
2074 HandleAircraftSmoke(v, loop != 0);
2075 ProcessOrders(v);
2076 v->HandleLoading(loop != 0);
2077
2078 if (v->current_order.IsType(OT_LOADING) || v->current_order.IsType(OT_LEAVESTATION)) return true;
2079
2080 if (v->state >= ENDTAKEOFF && v->state <= HELIENDLANDING) {
2081 /* If we are flying, unconditionally clear the 'dest too far' state. */
2082 AircraftHandleDestTooFar(v, false);
2083 } else if (v->acache.cached_max_range_sqr != 0) {
2084 /* Check the distance to the next destination. This code works because the target
2085 * airport is only updated after take off and not on the ground. */
2086 Station *cur_st = Station::GetIfValid(v->targetairport);
2087 Station *next_st = v->current_order.IsType(OT_GOTO_STATION) || v->current_order.IsType(OT_GOTO_DEPOT) ? Station::GetIfValid(v->current_order.GetDestination()) : nullptr;
2088
2089 if (cur_st != nullptr && cur_st->airport.tile != INVALID_TILE && next_st != nullptr && next_st->airport.tile != INVALID_TILE) {
2090 uint dist = DistanceSquare(cur_st->airport.tile, next_st->airport.tile);
2091 AircraftHandleDestTooFar(v, dist > v->acache.cached_max_range_sqr);
2092 }
2093 }
2094
2095 if (!HasBit(v->flags, VAF_DEST_TOO_FAR)) AirportGoToNextPosition(v);
2096
2097 return true;
2098 }
2099
2100 bool Aircraft::Tick()
2101 {
2102 if (!this->IsNormalAircraft()) return true;
2103
2104 PerformanceAccumulator framerate(PFE_GL_AIRCRAFT);
2105
2106 this->tick_counter++;
2107
2108 if (!(this->vehstatus & VS_STOPPED)) this->running_ticks++;
2109
2110 if (this->subtype == AIR_HELICOPTER) HelicopterTickHandler(this);
2111
2112 this->current_order_time++;
2113
2114 for (uint i = 0; i != 2; i++) {
2115 /* stop if the aircraft was deleted */
2116 if (!AircraftEventHandler(this, i)) return false;
2117 }
2118
2119 return true;
2120 }
2121
2122
2129 Station *GetTargetAirportIfValid(const Aircraft *v)
2130 {
2131 assert(v->type == VEH_AIRCRAFT);
2132
2133 Station *st = Station::GetIfValid(v->targetairport);
2134 if (st == nullptr) return nullptr;
2135
2136 return st->airport.tile == INVALID_TILE ? nullptr : st;
2137 }
2138
2143 void UpdateAirplanesOnNewStation(const Station *st)
2144 {
2145 /* only 1 station is updated per function call, so it is enough to get entry_point once */
2146 const AirportFTAClass *ap = st->airport.GetFTA();
2147 Direction rotation = st->airport.tile == INVALID_TILE ? DIR_N : st->airport.rotation;
2148
2149 for (Aircraft *v : Aircraft::Iterate()) {
2150 if (!v->IsNormalAircraft() || v->targetairport != st->index) continue;
2151 assert(v->state == FLYING);
2152
2153 Order *o = &v->current_order;
2154 /* The aircraft is heading to a hangar, but the new station doesn't have one,
2155 * or the aircraft can't land on the new station. Cancel current order. */
2156 if (o->IsType(OT_GOTO_DEPOT) && !(o->GetDepotOrderType() & ODTFB_PART_OF_ORDERS) && o->GetDestination() == st->index &&
2157 (!st->airport.HasHangar() || !CanVehicleUseStation(v, st))) {
2158 o->MakeDummy();
2159 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
2160 }
2161 v->pos = v->previous_pos = AircraftGetEntryPoint(v, ap, rotation);
2162 UpdateAircraftCache(v);
2163 }
2164
2165 /* Heliports don't have a hangar. Invalidate all go to hangar orders from all aircraft. */
2166 if (!st->airport.HasHangar()) RemoveOrderFromAllVehicles(OT_GOTO_DEPOT, st->index, true);
2167 }
VEH_AIRCRAFT
@ VEH_AIRCRAFT
Aircraft vehicle type.
Definition: vehicle_type.h:27
VSE_START
@ VSE_START
Vehicle starting, i.e. leaving, the station.
Definition: newgrf_sound.h:19
game.hpp
CrashAirplane
static void CrashAirplane(Aircraft *v)
Bring the aircraft in a crashed state, create the explosion animation, and create a news item about t...
Definition: aircraft_cmd.cpp:1319
Vehicle::IsChainInDepot
virtual bool IsChainInDepot() const
Check whether the whole vehicle chain is in the depot.
Definition: vehicle_base.h:537
Aircraft::targetairport
StationID targetairport
Airport to go to next.
Definition: aircraft.h:78
AircraftEventHandler_EnterHangar
static void AircraftEventHandler_EnterHangar(Aircraft *v, const AirportFTAClass *apc)
Aircraft arrived in an airport hangar.
Definition: aircraft_cmd.cpp:1494
DIAGDIR_SE
@ DIAGDIR_SE
Southeast.
Definition: direction_type.h:80
AirportFTA::heading
byte heading
heading (current orders), guiding an airplane to its target on an airport
Definition: airport.h:195
HELILANDING
@ HELILANDING
Helicopter wants to land.
Definition: airport.h:78
AircraftHandleDestTooFar
static void AircraftHandleDestTooFar(Aircraft *v, bool too_far)
Handle the 'dest too far' flag and the corresponding news message for aircraft.
Definition: aircraft_cmd.cpp:2040
Cheats::no_jetcrash
Cheat no_jetcrash
no jet will crash on small airports anymore
Definition: cheat_type.h:31
UpdateAircraftSpeed
static int UpdateAircraftSpeed(Aircraft *v, uint speed_limit=SPEED_LIMIT_NONE, bool hard_limit=true)
Sets the new speed for an aircraft.
Definition: aircraft_cmd.cpp:635
InvalidateWindowData
void InvalidateWindowData(WindowClass cls, WindowNumber number, int data, bool gui_scope)
Mark window data of the window of a given class and specific window number as invalid (in need of re-...
Definition: window.cpp:3252
Order::MakeDummy
void MakeDummy()
Makes this order a Dummy order.
Definition: order_cmd.cpp:133
sound_func.h
Airport::GetHangarExitDirection
Direction GetHangarExitDirection(TileIndex tile) const
Get the exit direction of the hangar at a specific tile.
Definition: station_base.h:387
Station::goods
GoodsEntry goods[NUM_CARGO]
Goods at this station.
Definition: station_base.h:483
DIRDIFF_REVERSE
@ DIRDIFF_REVERSE
One direction is the opposite of the other one.
Definition: direction_type.h:66
Order::IsType
bool IsType(OrderType type) const
Check whether this order is of the given type.
Definition: order_base.h:71
Rect::Height
int Height() const
Get height of Rect.
Definition: geometry_type.hpp:85
Pool::PoolItem<&_engine_pool >::Get
static Titem * Get(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:337
SND_18_TAKEOFF_HELICOPTER
@ SND_18_TAKEOFF_HELICOPTER
22 == 0x16 Takeoff: helicopter
Definition: sound_type.h:61
Direction
Direction
Defines the 8 directions on the map.
Definition: direction_type.h:24
ENDTAKEOFF
@ ENDTAKEOFF
Airplane has reached end-point of the take-off runway.
Definition: airport.h:73
Airport::GetHangarNum
uint GetHangarNum(TileIndex tile) const
Get the hangar number of the hangar at a specific tile.
Definition: station_base.h:400
Vehicle::y_pos
int32 y_pos
y coordinate.
Definition: vehicle_base.h:284
SetWindowDirty
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
Definition: window.cpp:3154
MutableSpriteCache::sprite_seq
VehicleSpriteSeq sprite_seq
Vehicle appearance.
Definition: vehicle_base.h:197
VehicleSpriteSeq::CopyWithoutPalette
void CopyWithoutPalette(const VehicleSpriteSeq &src)
Copy data from another sprite sequence, while dropping all recolouring information.
Definition: vehicle_base.h:175
AirportMovingData
A single location on an airport where aircraft can move to.
Definition: airport.h:131
GetPrice
Money GetPrice(Price index, uint cost_factor, const GRFFile *grf_file, int shift)
Determine a certain price.
Definition: economy.cpp:961
GB
static uint GB(const T x, const uint8 s, const uint8 n)
Fetch n bits from x, started at bit s.
Definition: bitmath_func.hpp:32
NT_ARRIVAL_OTHER
@ NT_ARRIVAL_OTHER
First vehicle arrived for competitor.
Definition: news_type.h:23
Vehicle::x_pos
int32 x_pos
x coordinate.
Definition: vehicle_base.h:283
DIRDIFF_45LEFT
@ DIRDIFF_45LEFT
Angle of 45 degrees left.
Definition: direction_type.h:68
ChangeDir
static Direction ChangeDir(Direction d, DirDiff delta)
Change a direction by a given difference.
Definition: direction_func.h:104
AircraftVehicleInfo::subtype
byte subtype
Type of aircraft.
Definition: engine_type.h:103
command_func.h
DIR_SE
@ DIR_SE
Southeast.
Definition: direction_type.h:29
GetAircraftHoldMaxAltitude
int GetAircraftHoldMaxAltitude(const Aircraft *v)
Gets the maximum 'flight level' for the holding pattern of the aircraft, in pixels 'z_pos' 0,...
Definition: aircraft_cmd.cpp:752
RotateAirportMovingData
AirportMovingData RotateAirportMovingData(const AirportMovingData *orig, Direction rotation, uint num_tiles_x, uint num_tiles_y)
Rotate the airport moving data to another rotation.
Definition: airport.cpp:80
ODTFB_SERVICE
@ ODTFB_SERVICE
This depot order is because of the servicing limit.
Definition: order_type.h:95
CMD_ERROR
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
Definition: command_func.h:28
GetTileHeightBelowAircraft
int GetTileHeightBelowAircraft(const Vehicle *v)
Get the tile height below the aircraft.
Definition: aircraft_cmd.cpp:700
HELIPAD3_block
static const uint64 HELIPAD3_block
Block belonging to helipad 3.
Definition: airport.h:117
_airport_terminal_mapping
static const MovementTerminalMapping _airport_terminal_mapping[]
A list of all valid terminals and their associated blocks.
Definition: aircraft_cmd.cpp:1916
CheckOrders
void CheckOrders(const Vehicle *v)
Check the orders of a vehicle, to see if there are invalid orders and stuff.
Definition: order_cmd.cpp:1689
Engine::reliability_spd_dec
uint16 reliability_spd_dec
Speed of reliability decay between services (per day).
Definition: engine_base.h:41
Backup
Class to backup a specific variable and restore it later.
Definition: backup_type.hpp:21
AMED_LAND
@ AMED_LAND
Landing onto landing strip.
Definition: airport.h:51
company_base.h
Vehicle::Next
Vehicle * Next() const
Get the next vehicle of this vehicle.
Definition: vehicle_base.h:610
_cur_year
Year _cur_year
Current year, starting at 0.
Definition: date.cpp:26
HELIENDLANDING
@ HELIENDLANDING
Helicopter wants to finish landing.
Definition: airport.h:79
SpecializedVehicle::Next
T * Next() const
Get next vehicle in the chain.
Definition: vehicle_base.h:1098
DIRDIFF_SAME
@ DIRDIFF_SAME
Both directions faces to the same direction.
Definition: direction_type.h:63
Vehicle::y_extent
byte y_extent
y-extent of vehicle bounding box
Definition: vehicle_base.h:296
Station
Station data structure.
Definition: station_base.h:454
Order::GetDestination
DestinationID GetDestination() const
Gets the destination of this order.
Definition: order_base.h:104
Vehicle::NeedsAutomaticServicing
bool NeedsAutomaticServicing() const
Checks if the current order should be interrupted for a service-in-depot order.
Definition: vehicle.cpp:252
Vehicle::z_pos
int32 z_pos
z coordinate.
Definition: vehicle_base.h:285
VehicleSpriteSeq::Set
void Set(SpriteID sprite)
Assign a single sprite to the sequence.
Definition: vehicle_base.h:165
PLANE_HOLD_MAX_FLYING_ALTITUDE
@ PLANE_HOLD_MAX_FLYING_ALTITUDE
holding flying altitude above tile of planes.
Definition: aircraft.h:23
VSE_TOUCHDOWN
@ VSE_TOUCHDOWN
Whenever a plane touches down.
Definition: newgrf_sound.h:23
HandleAircraftSmoke
static void HandleAircraftSmoke(Aircraft *v, bool mode)
Handle smoke of broken aircraft.
Definition: aircraft_cmd.cpp:1220
Vehicle::random_bits
byte random_bits
Bits used for determining which randomized variational spritegroups to use when drawing.
Definition: vehicle_base.h:313
Vehicle::vehstatus
byte vehstatus
Status.
Definition: vehicle_base.h:332
BaseConsist::name
std::string name
Name of vehicle.
Definition: base_consist.h:19
TERM5_block
static const uint64 TERM5_block
Block belonging to terminal 5.
Definition: airport.h:93
AircraftVehicleInfo::passenger_capacity
uint16 passenger_capacity
Passenger capacity (persons).
Definition: engine_type.h:108
MovementTerminalMapping::airport_flag
uint64 airport_flag
Bitmask in the airport flags that need to be free for this terminal.
Definition: aircraft_cmd.cpp:1912
VS_DEFPAL
@ VS_DEFPAL
Use default vehicle palette.
Definition: vehicle_base.h:37
Pool::PoolItem::index
Tindex index
Index of this pool item.
Definition: pool_type.hpp:235
Vehicle::SetNext
void SetNext(Vehicle *next)
Set the next vehicle of this vehicle.
Definition: vehicle.cpp:2741
Vehicle::Crash
virtual uint Crash(bool flooded=false)
Crash the (whole) vehicle chain.
Definition: vehicle.cpp:260
AirportFTAClass::SHORT_STRIP
@ SHORT_STRIP
This airport has a short landing strip, dangerous for fast aircraft.
Definition: airport.h:150
Vehicle::acceleration
byte acceleration
used by train & aircraft
Definition: vehicle_base.h:309
AMED_TAKEOFF
@ AMED_TAKEOFF
Takeoff movement.
Definition: airport.h:49
PROP_AIRCRAFT_RUNNING_COST_FACTOR
@ PROP_AIRCRAFT_RUNNING_COST_FACTOR
Yearly runningcost.
Definition: newgrf_properties.h:51
Order::Free
void Free()
'Free' the order
Definition: order_cmd.cpp:63
DeleteVehicleNews
void DeleteVehicleNews(VehicleID vid, StringID news)
Delete a news item type about a vehicle.
Definition: news_gui.cpp:919
HasBit
static bool HasBit(const T x, const uint8 y)
Checks if a bit in a value is set.
Definition: bitmath_func.hpp:103
INVALID_TILE
static constexpr TileIndex INVALID_TILE
The very nice invalid tile marker.
Definition: tile_type.h:108
TERM1
@ TERM1
Heading for terminal 1.
Definition: airport.h:63
UnScaleGUI
static int UnScaleGUI(int value)
Short-hand to apply GUI zoom level.
Definition: zoom_func.h:77
AircraftStateHandler
void AircraftStateHandler(Aircraft *v, const AirportFTAClass *apc)
Signature of the aircraft handler function.
Definition: aircraft_cmd.cpp:1740
SND_12_EXPLOSION
@ SND_12_EXPLOSION
16 == 0x10 Destruction, crashes, disasters, ...
Definition: sound_type.h:55
ClrBit
static T ClrBit(T &x, const uint8 y)
Clears a bit in a variable.
Definition: bitmath_func.hpp:151
TileIndex
The index/ID of a Tile.
Definition: tile_type.h:85
VAF_IN_MAX_HEIGHT_CORRECTION
@ VAF_IN_MAX_HEIGHT_CORRECTION
The vehicle is currently lowering its altitude because it hit the upper bound.
Definition: aircraft.h:44
AirportFTAClass::num_helipads
const byte num_helipads
Number of helipads on this airport. When 0 helicopters will go to normal terminals.
Definition: airport.h:179
EXPENSES_AIRCRAFT_RUN
@ EXPENSES_AIRCRAFT_RUN
Running costs aircraft.
Definition: economy_type.h:162
Aircraft::number_consecutive_turns
byte number_consecutive_turns
Protection to prevent the aircraft of making a lot of turns in order to reach a specific point.
Definition: aircraft.h:81
ENDLANDING
@ ENDLANDING
Airplane wants to finish landing.
Definition: airport.h:77
zoom_func.h
HandleAircraftEnterHangar
void HandleAircraftEnterHangar(Aircraft *v)
Handle Aircraft specific tasks when an Aircraft enters a hangar.
Definition: aircraft_cmd.cpp:560
aircraft.h
TILE_SIZE
static const uint TILE_SIZE
Tile size in world coordinates.
Definition: tile_type.h:15
AddVehicleNewsItem
static void AddVehicleNewsItem(StringID string, NewsType type, VehicleID vehicle, StationID station=INVALID_STATION)
Adds a newsitem referencing a vehicle.
Definition: news_func.h:30
Vehicle::running_ticks
byte running_ticks
Number of ticks this vehicle was not stopped this day.
Definition: vehicle_base.h:330
SpecializedStation< Station, false >::Get
static Station * Get(size_t index)
Gets station with given index.
Definition: base_station_base.h:218
DirDifference
static DirDiff DirDifference(Direction d0, Direction d1)
Calculate the difference between two directions.
Definition: direction_func.h:68
_settings_client
ClientSettings _settings_client
The current settings for this game.
Definition: settings.cpp:53
VehicleEnterDepot
void VehicleEnterDepot(Vehicle *v)
Vehicle entirely entered the depot, update its status, orders, vehicle windows, service it,...
Definition: vehicle.cpp:1487
TileY
static uint TileY(TileIndex tile)
Get the Y component of a tile.
Definition: map_func.h:215
GetAircraftSpriteSize
void GetAircraftSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type)
Get the size of the sprite of an aircraft sprite heading west (used for lists).
Definition: aircraft_cmd.cpp:247
Engine::GetLifeLengthInDays
Date GetLifeLengthInDays() const
Returns the vehicle's (not model's!) life length in days.
Definition: engine.cpp:437
DepotCommand::LocateHangar
@ LocateHangar
Find another airport if the target one lacks a hangar.
DIAGDIR_NW
@ DIAGDIR_NW
Northwest.
Definition: direction_type.h:82
DIR_W
@ DIR_W
West.
Definition: direction_type.h:32
EV_EXPLOSION_SMALL
@ EV_EXPLOSION_SMALL
Various explosions.
Definition: effectvehicle_func.h:24
EngineImageType
EngineImageType
Visualisation contexts of vehicles and engines.
Definition: vehicle_type.h:86
GetTargetAirportIfValid
Station * GetTargetAirportIfValid(const Aircraft *v)
Returns aircraft's target station if v->target_airport is a valid station with airport.
Definition: aircraft_cmd.cpp:2129
Engine
Definition: engine_base.h:36
Vehicle::cur_speed
uint16 cur_speed
current speed
Definition: vehicle_base.h:307
Vehicle
Vehicle data structure.
Definition: vehicle_base.h:224
Engine::GetDefaultCargoType
CargoID GetDefaultCargoType() const
Determines the default cargo type of an engine.
Definition: engine_base.h:95
VehicleSpriteSeq::Draw
void Draw(int x, int y, PaletteID default_pal, bool force_pal) const
Draw the sprite sequence.
Definition: vehicle.cpp:126
Vehicle::owner
Owner owner
Which company owns the vehicle?
Definition: vehicle_base.h:288
VehicleCache::cached_cargo_age_period
uint16 cached_cargo_age_period
Number of ticks before carried cargo is aged.
Definition: vehicle_base.h:126
EV_EXPLOSION_LARGE
@ EV_EXPLOSION_LARGE
Various explosions.
Definition: effectvehicle_func.h:22
DC_EXEC
@ DC_EXEC
execute the given command
Definition: command_type.h:357
aircraft_cmd.h
BaseStation::owner
Owner owner
The owner of this station.
Definition: base_station_base.h:62
DIR_N
@ DIR_N
North.
Definition: direction_type.h:26
AIR_AIRCRAFT
@ AIR_AIRCRAFT
an airplane
Definition: aircraft.h:32
HELIPAD2_block
static const uint64 HELIPAD2_block
Block belonging to helipad 2.
Definition: airport.h:96
Aircraft::FindClosestDepot
bool FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
Find the closest depot for this vehicle and tell us the location, DestinationID and whether we should...
Definition: aircraft_cmd.cpp:391
SetDParam
static void SetDParam(uint n, uint64 v)
Set a string parameter v at index n in the global string parameter array.
Definition: strings_func.h:196
VS_AIRCRAFT_BROKEN
@ VS_AIRCRAFT_BROKEN
Aircraft is broken down.
Definition: vehicle_base.h:40
HANGAR
@ HANGAR
Heading for hangar.
Definition: airport.h:62
DoCommandFlag
DoCommandFlag
List of flags for a command.
Definition: command_type.h:355
VehicleServiceInDepot
void VehicleServiceInDepot(Vehicle *v)
Service a vehicle and all subsequent vehicles in the consist.
Definition: vehicle.cpp:162
SPEED_LIMIT_APPROACH
@ SPEED_LIMIT_APPROACH
Maximum speed of an aircraft on finals.
Definition: aircraft_cmd.cpp:622
Vehicle::breakdowns_since_last_service
byte breakdowns_since_last_service
Counter for the amount of breakdowns.
Definition: vehicle_base.h:280
AIR_SHADOW
@ AIR_SHADOW
shadow of the aircraft
Definition: aircraft.h:33
SETBITS
#define SETBITS(x, y)
Sets several bits in a variable.
Definition: bitmath_func.hpp:136
GetAirport
const AirportFTAClass * GetAirport(const byte airport_type)
Get the finite state machine of an airport type.
Definition: airport.cpp:207
TERM7
@ TERM7
Heading for terminal 7.
Definition: airport.h:80
TileX
static uint TileX(TileIndex tile)
Get the X component of a tile.
Definition: map_func.h:205
AirportMovingData::direction
Direction direction
Direction to turn the aircraft after reaching the destination.
Definition: airport.h:135
TERM3
@ TERM3
Heading for terminal 3.
Definition: airport.h:65
effectvehicle_func.h
SpecializedStation< Station, false >::Iterate
static Pool::IterateWrapper< Station > Iterate(size_t from=0)
Returns an iterable ensemble of all valid stations of type T.
Definition: base_station_base.h:269
AMED_EXACTPOS
@ AMED_EXACTPOS
Go exactly to the destination coordinates.
Definition: airport.h:52
Airport::GetFTA
const AirportFTAClass * GetFTA() const
Get the finite-state machine for this airport or the finite-state machine for the dummy airport in ca...
Definition: station_base.h:329
AircraftEventHandler_InHangar
static void AircraftEventHandler_InHangar(Aircraft *v, const AirportFTAClass *apc)
Handle aircraft movement/decision making in an airport hangar.
Definition: aircraft_cmd.cpp:1505
ai.hpp
Order::MakeGoToDepot
void MakeGoToDepot(DepotID destination, OrderDepotTypeFlags order, OrderNonStopFlags non_stop_type=ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS, OrderDepotActionFlags action=ODATF_SERVICE_ONLY, CargoID cargo=CT_NO_REFIT)
Makes this order a Go To Depot order.
Definition: order_cmd.cpp:90
Order::GetType
OrderType GetType() const
Get the type of order of this order.
Definition: order_base.h:77
DepotCommand::Service
@ Service
The vehicle will leave the depot right after arrival (service only)
Aircraft
Aircraft, helicopters, rotors and their shadows belong to this class.
Definition: aircraft.h:74
SpriteID
uint32 SpriteID
The number of a sprite, without mapping bits and colourtables.
Definition: gfx_type.h:17
Engine::GetGRF
const GRFFile * GetGRF() const
Retrieve the NewGRF the engine is tied to.
Definition: engine_base.h:154
GoodsEntry::cargo
StationCargoList cargo
The cargo packets of cargo waiting in this station.
Definition: station_base.h:252
NT_ARRIVAL_COMPANY
@ NT_ARRIVAL_COMPANY
First vehicle arrived for company.
Definition: news_type.h:22
SetWindowWidgetDirty
void SetWindowWidgetDirty(WindowClass cls, WindowNumber number, byte widget_index)
Mark a particular widget in a particular window as dirty (in need of repainting)
Definition: window.cpp:3167
ENGINE_EXCLUSIVE_PREVIEW
@ ENGINE_EXCLUSIVE_PREVIEW
This vehicle is in the exclusive preview stage, either being used or being offered to a company.
Definition: engine_type.h:182
newgrf_airporttiles.h
GameSettings::order
OrderSettings order
settings related to orders
Definition: settings_type.h:594
VehicleSettings::plane_crashes
uint8 plane_crashes
number of plane crashes, 0 = none, 1 = reduced, 2 = normal
Definition: settings_type.h:505
Airport::HasHangar
bool HasHangar() const
Check if this airport has at least one hangar.
Definition: station_base.h:335
Vehicle::BeginLoading
void BeginLoading()
Prepare everything to begin the loading when arriving at a station.
Definition: vehicle.cpp:2113
DIAGDIR_SW
@ DIAGDIR_SW
Southwest.
Definition: direction_type.h:81
DiagDirDifference
static DiagDirDiff DiagDirDifference(DiagDirection d0, DiagDirection d1)
Calculate the difference between two DiagDirection values.
Definition: direction_func.h:131
Airport::rotation
Direction rotation
How this airport is rotated.
Definition: station_base.h:308
Vehicle::breakdown_ctr
byte breakdown_ctr
Counter for managing breakdown events.
Definition: vehicle_base.h:278
VS_HIDDEN
@ VS_HIDDEN
Vehicle is not visible.
Definition: vehicle_base.h:34
EngineID
uint16 EngineID
Unique identification number of an engine.
Definition: engine_type.h:21
SND_17_SKID_PLANE
@ SND_17_SKID_PLANE
21 == 0x15 Plane landing / touching ground
Definition: sound_type.h:60
AAT_STATION_AIRPLANE_LAND
@ AAT_STATION_AIRPLANE_LAND
Triggered when an airplane (not a helicopter) touches down at the airport (for single tile).
Definition: newgrf_animation_type.h:52
VehicleSpriteSeq::IsValid
bool IsValid() const
Check whether the sequence contains any sprites.
Definition: vehicle_base.h:149
DirToDiagDir
static DiagDirection DirToDiagDir(Direction dir)
Convert a Direction to a DiagDirection.
Definition: direction_func.h:166
AirportSetBlocks
static bool AirportSetBlocks(Aircraft *v, const AirportFTA *current_pos, const AirportFTAClass *apc)
"reserve" a block for the plane
Definition: aircraft_cmd.cpp:1868
AIRCRAFT_MAX_FLYING_ALTITUDE
@ AIRCRAFT_MAX_FLYING_ALTITUDE
Maximum flying altitude above tile.
Definition: aircraft.h:22
AI::NewEvent
static void NewEvent(CompanyID company, ScriptEvent *event)
Queue a new event for an AI.
Definition: ai_core.cpp:236
Aircraft::GetRunningCost
Money GetRunningCost() const
Gets the running cost of a vehicle.
Definition: aircraft_cmd.cpp:436
CommandCost
Common return value for all commands.
Definition: command_type.h:24
VAF_HELI_DIRECT_DESCENT
@ VAF_HELI_DIRECT_DESCENT
The helicopter is descending directly at its destination (helipad or in front of hangar)
Definition: aircraft.h:47
_date
Date _date
Current date in days (day counter)
Definition: date.cpp:28
PROP_AIRCRAFT_CARGO_AGE_PERIOD
@ PROP_AIRCRAFT_CARGO_AGE_PERIOD
Number of ticks before carried cargo is aged.
Definition: newgrf_properties.h:54
VehicleCargoList::Truncate
uint Truncate(uint max_move=UINT_MAX)
Truncates the cargo in this list to the given amount.
Definition: cargopacket.cpp:654
AMED_SLOWTURN
@ AMED_SLOWTURN
Turn slowly (mostly used in the air).
Definition: airport.h:50
WC_VEHICLE_VIEW
@ WC_VEHICLE_VIEW
Vehicle view; Window numbers:
Definition: window_type.h:332
TileHeight
static uint TileHeight(TileIndex tile)
Returns the height of a tile.
Definition: tile_map.h:29
ClientSettings::sound
SoundSettings sound
sound effect settings
Definition: settings_type.h:607
AirportMovingData::flag
uint16 flag
special flags when moving towards the destination.
Definition: airport.h:134
newgrf_engine.h
ChangeDiagDir
static DiagDirection ChangeDiagDir(DiagDirection d, DiagDirDiff delta)
Applies a difference on a DiagDirection.
Definition: direction_func.h:149
DIR_E
@ DIR_E
East.
Definition: direction_type.h:28
Aircraft::turn_counter
byte turn_counter
Ticks between each turn to prevent > 45 degree turns.
Definition: aircraft.h:82
AirportFTAClass::nofelements
byte nofelements
number of positions the airport consists of
Definition: airport.h:181
EV_BREAKDOWN_SMOKE_AIRCRAFT
@ EV_BREAKDOWN_SMOKE_AIRCRAFT
Smoke of broken aircraft.
Definition: effectvehicle_func.h:27
NewsType
NewsType
Type of news.
Definition: news_type.h:21
SubtractMoneyFromCompanyFract
void SubtractMoneyFromCompanyFract(CompanyID company, const CommandCost &cst)
Subtract money from a company, including the money fraction.
Definition: company_cmd.cpp:258
Vehicle::tile
TileIndex tile
Current tile index.
Definition: vehicle_base.h:245
AircraftGetEntryPoint
static byte AircraftGetEntryPoint(const Aircraft *v, const AirportFTAClass *apc, Direction rotation)
Find the entry point to an airport depending on direction which the airport is being approached from.
Definition: aircraft_cmd.cpp:815
EIT_ON_MAP
@ EIT_ON_MAP
Vehicle drawn in viewport.
Definition: vehicle_type.h:87
Vehicle::engine_type
EngineID engine_type
The type of engine used for this vehicle.
Definition: vehicle_base.h:302
VS_CRASHED
@ VS_CRASHED
Vehicle is crashed.
Definition: vehicle_base.h:41
_cheats
Cheats _cheats
All the cheats.
Definition: cheat.cpp:16
VehicleSpriteSeq
Sprite sequence for a vehicle part.
Definition: vehicle_base.h:132
Vehicle::last_station_visited
StationID last_station_visited
The last station we stopped at.
Definition: vehicle_base.h:316
OrthogonalTileArea::w
uint16 w
The width of the area.
Definition: tilearea_type.h:20
AMED_HOLD
@ AMED_HOLD
Holding pattern movement (above the airport).
Definition: airport.h:56
Vehicle::cargo
VehicleCargoList cargo
The cargo this vehicle is carrying.
Definition: vehicle_base.h:324
Vehicle::GetOldAdvanceSpeed
uint GetOldAdvanceSpeed(uint speed)
Determines the effective direction-specific vehicle movement speed.
Definition: vehicle_base.h:411
CommandCost::Failed
bool Failed() const
Did this command fail?
Definition: command_type.h:160
SPEED_LIMIT_TAXI
@ SPEED_LIMIT_TAXI
Maximum speed of an aircraft while taxiing.
Definition: aircraft_cmd.cpp:621
Vehicle::current_order
Order current_order
The current order (+ status, like: loading)
Definition: vehicle_base.h:333
Airport::GetHangarTile
TileIndex GetHangarTile(uint hangar_num) const
Get the first tile of the given hangar.
Definition: station_base.h:370
AirportFindFreeHelipad
static bool AirportFindFreeHelipad(Aircraft *v, const AirportFTAClass *apc)
Find a free helipad, and assign it if available.
Definition: aircraft_cmd.cpp:2025
Vehicle::max_age
Date max_age
Maximum age.
Definition: vehicle_base.h:274
Station::airport
Airport airport
Tile area the airport covers.
Definition: station_base.h:468
HelicopterRotorStates
HelicopterRotorStates
Helicopter rotor animation states.
Definition: aircraft_cmd.cpp:108
ScaleSpriteTrad
static int ScaleSpriteTrad(int value)
Scale traditional pixel dimensions to GUI zoom level, for drawing sprites.
Definition: zoom_func.h:107
AirportFTAClass::layout
struct AirportFTA * layout
state machine for airport
Definition: airport.h:177
DIR_NE
@ DIR_NE
Northeast.
Definition: direction_type.h:27
AirportFTAClass::flags
Flags flags
Flags for this airport type.
Definition: airport.h:180
ODATFB_NEAREST_DEPOT
@ ODATFB_NEAREST_DEPOT
Send the vehicle to the nearest depot.
Definition: order_type.h:105
_settings_game
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition: settings.cpp:54
WC_VEHICLE_DETAILS
@ WC_VEHICLE_DETAILS
Vehicle details; Window numbers:
Definition: window_type.h:193
AirportFTA
Internal structure used in openttd - Finite sTate mAchine --> FTA.
Definition: airport.h:190
Game::NewEvent
static void NewEvent(class ScriptEvent *event)
Queue a new event for a Game Script.
Definition: game_core.cpp:146
VS_STOPPED
@ VS_STOPPED
Vehicle is stopped by the player.
Definition: vehicle_base.h:35
_local_company
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
Definition: company_cmd.cpp:46
Vehicle::GetEngine
const Engine * GetEngine() const
Retrieves the engine of the vehicle.
Definition: vehicle.cpp:741
safeguards.h
GetNewVehiclePosResult::new_tile
TileIndex new_tile
Tile of the vehicle after moving.
Definition: vehicle_func.h:78
Vehicle::reliability_spd_dec
uint16 reliability_spd_dec
Reliability decrease speed.
Definition: vehicle_base.h:277
Vehicle::last_loading_station
StationID last_loading_station
Last station the vehicle has stopped at and could possibly leave from with any cargo loaded.
Definition: vehicle_base.h:317
vehicle_cmd.h
Airport::flags
uint64 flags
stores which blocks on the airport are taken. was 16 bit earlier on, then 32
Definition: station_base.h:305
CommandCost::GetCost
Money GetCost() const
The costs as made up to this moment.
Definition: command_type.h:83
Aircraft::Crash
uint Crash(bool flooded=false)
Crash the (whole) vehicle chain.
Definition: aircraft_cmd.cpp:1307
Vehicle::profit_this_year
Money profit_this_year
Profit this year << 8, low 8 bits are fract.
Definition: vehicle_base.h:254
AircraftSpeedLimits
AircraftSpeedLimits
Special velocities for aircraft.
Definition: aircraft_cmd.cpp:620
ODTFB_PART_OF_ORDERS
@ ODTFB_PART_OF_ORDERS
This depot order is because of a regular order.
Definition: order_type.h:96
settings
fluid_settings_t * settings
FluidSynth settings handle.
Definition: fluidsynth.cpp:21
SPEED_LIMIT_HOLD
@ SPEED_LIMIT_HOLD
Maximum speed of an aircraft that flies the holding pattern.
Definition: aircraft_cmd.cpp:624
VAF_IN_MIN_HEIGHT_CORRECTION
@ VAF_IN_MIN_HEIGHT_CORRECTION
The vehicle is currently raising its altitude because it hit the lower bound.
Definition: aircraft.h:45
MovementTerminalMapping
Combination of aircraft state for going to a certain terminal and the airport flag for that terminal ...
Definition: aircraft_cmd.cpp:1910
OrderSettings::serviceathelipad
bool serviceathelipad
service helicopters at helipads automatically (no need to send to depot)
Definition: settings_type.h:482
GoodsEntry::rating
byte rating
Station rating for this cargo.
Definition: station_base.h:232
AirportFTAClass
Finite sTate mAchine (FTA) of an airport.
Definition: airport.h:143
SoundSettings::disaster
bool disaster
Play disaster and accident sounds.
Definition: settings_type.h:218
GetVehiclePosOnBuild
byte GetVehiclePosOnBuild(TileIndex hangar_tile)
Get the vehicle position when an aircraft is build at the given tile.
Definition: airport.cpp:218
HVOT_AIRCRAFT
@ HVOT_AIRCRAFT
Station has seen an aircraft.
Definition: station_type.h:68
MaybeCrashAirplane
static void MaybeCrashAirplane(Aircraft *v)
Decide whether aircraft v should crash.
Definition: aircraft_cmd.cpp:1358
GetNumTerminals
static uint GetNumTerminals(const AirportFTAClass *apc)
Get the number of terminals at the airport.
Definition: aircraft_cmd.cpp:1957
DirDiff
DirDiff
Enumeration for the difference between two directions.
Definition: direction_type.h:62
DiagDirection
DiagDirection
Enumeration for diagonal directions.
Definition: direction_type.h:77
NT_ACCIDENT_OTHER
@ NT_ACCIDENT_OTHER
An accident or disaster has occurred.
Definition: news_type.h:25
Vehicle::HandleLoading
void HandleLoading(bool mode=false)
Handle the loading of the vehicle; when not it skips through dummy orders and does nothing in all oth...
Definition: vehicle.cpp:2324
PFE_GL_AIRCRAFT
@ PFE_GL_AIRCRAFT
Time spent processing aircraft.
Definition: framerate_type.h:54
CreateEffectVehicleRel
EffectVehicle * CreateEffectVehicleRel(const Vehicle *v, int x, int y, int z, EffectVehicleType type)
Create an effect vehicle above a particular vehicle.
Definition: effectvehicle.cpp:638
TERM7_block
static const uint64 TERM7_block
Block belonging to terminal 7.
Definition: airport.h:115
date_func.h
stdafx.h
TERM5
@ TERM5
Heading for terminal 5.
Definition: airport.h:67
BaseConsist::vehicle_flags
uint16 vehicle_flags
Used for gradual loading and other miscellaneous things (.
Definition: base_consist.h:31
WID_VV_START_STOP
@ WID_VV_START_STOP
Start or stop this vehicle, and show information about the current state.
Definition: vehicle_widget.h:17
Vehicle::sprite_cache
MutableSpriteCache sprite_cache
Cache of sprites and values related to recalculating them, see MutableSpriteCache.
Definition: vehicle_base.h:347
landscape.h
Cheat::value
bool value
tells if the bool cheat is active or not
Definition: cheat_type.h:18
HELIPAD3
@ HELIPAD3
Heading for helipad 3.
Definition: airport.h:82
AirportHasBlock
static bool AirportHasBlock(Aircraft *v, const AirportFTA *current_pos, const AirportFTAClass *apc)
returns true if the road ahead is busy, eg.
Definition: aircraft_cmd.cpp:1837
Vehicle::y_offs
int8 y_offs
y offset for vehicle sprite
Definition: vehicle_base.h:301
Vehicle::colourmap
SpriteID colourmap
NOSAVE: cached colour mapping.
Definition: vehicle_base.h:269
AircraftLeaveHangar
void AircraftLeaveHangar(Aircraft *v, Direction exit_dir)
Aircraft is about to leave the hangar.
Definition: aircraft_cmd.cpp:1455
TERM1_block
static const uint64 TERM1_block
Movement Blocks on Airports blocks (eg_airport_flags).
Definition: airport.h:89
DisasterVehicle
Disasters, like submarines, skyrangers and their shadows, belong to this class.
Definition: disaster_vehicle.h:37
Aircraft::GetImage
void GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const
Gets the sprite to show for the given direction.
Definition: aircraft_cmd.cpp:172
VF_BUILT_AS_PROTOTYPE
@ VF_BUILT_AS_PROTOTYPE
Vehicle is a prototype (accepted as exclusive preview).
Definition: vehicle_base.h:48
Vehicle::direction
Direction direction
facing
Definition: vehicle_base.h:286
OrthogonalTileArea::h
uint16 h
The height of the area.
Definition: tilearea_type.h:21
MAX_TERMINALS
static const uint MAX_TERMINALS
Some airport-related constants.
Definition: airport.h:17
TERM2
@ TERM2
Heading for terminal 2.
Definition: airport.h:64
DistanceSquare
uint DistanceSquare(TileIndex t0, TileIndex t1)
Gets the 'Square' distance between the two given tiles.
Definition: map.cpp:174
AirportFTAClass::delta_z
byte delta_z
Z adjustment for helicopter pads.
Definition: airport.h:183
Aircraft::GetOrderStationLocation
TileIndex GetOrderStationLocation(StationID station)
Determine the location for the station where the vehicle goes to next.
Definition: aircraft_cmd.cpp:1286
PerformanceAccumulator
RAII class for measuring multi-step elements of performance.
Definition: framerate_type.h:114
AirportMovingData::x
int16 x
x-coordinate of the destination.
Definition: airport.h:132
ProcessOrders
bool ProcessOrders(Vehicle *v)
Handle the orders of a vehicle and determine the next place to go to if needed.
Definition: order_cmd.cpp:2090
VAF_DEST_TOO_FAR
@ VAF_DEST_TOO_FAR
Next destination is too far away.
Definition: aircraft.h:39
spritecache.h
AIRPORT_CLOSED_block
static const uint64 AIRPORT_CLOSED_block
Dummy block for indicating a closed airport.
Definition: airport.h:128
Vehicle::x_extent
byte x_extent
x-extent of vehicle bounding box
Definition: vehicle_base.h:295
HandleCrashedAircraft
static bool HandleCrashedAircraft(Aircraft *v)
Handle crashed aircraft v.
Definition: aircraft_cmd.cpp:1162
StringID
uint32 StringID
Numeric value that represents a string, independent of the selected language.
Definition: strings_type.h:16
Vehicle::vcache
VehicleCache vcache
Cache of often used vehicle values.
Definition: vehicle_base.h:345
_current_company
CompanyID _current_company
Company currently doing an action.
Definition: company_cmd.cpp:47
vehicle_func.h
NT_ACCIDENT
@ NT_ACCIDENT
An accident or disaster has occurred.
Definition: news_type.h:24
station_base.h
AircraftCache::cached_max_range_sqr
uint32 cached_max_range_sqr
Cached squared maximum range.
Definition: aircraft.h:67
newgrf_sound.h
Clamp
static T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition: math_func.hpp:77
AirportFTA::next
AirportFTA * next
possible extra movement choices from this position
Definition: airport.h:191
PALETTE_CRASH
static const PaletteID PALETTE_CRASH
Recolour sprite greying of crashed vehicles.
Definition: sprites.h:1598
strings_func.h
SmallStackItem::value
Titem value
Value of current item.
Definition: smallstack_type.hpp:97
AirportMovementStates
AirportMovementStates
Movement States on Airports (headings target)
Definition: airport.h:60
Vehicle::tick_counter
byte tick_counter
Increased by one for each tick.
Definition: vehicle_base.h:329
Vehicle::cargo_cap
uint16 cargo_cap
total capacity
Definition: vehicle_base.h:322
MapMaxY
static uint MapMaxY()
Gets the maximum Y coordinate within the map, including MP_VOID.
Definition: map_func.h:111
HELICOPTER_HOLD_MAX_FLYING_ALTITUDE
@ HELICOPTER_HOLD_MAX_FLYING_ALTITUDE
holding flying altitude above tile of helicopters.
Definition: aircraft.h:24
Vehicle::x_offs
int8 x_offs
x offset for vehicle sprite
Definition: vehicle_base.h:300
Vehicle::subspeed
byte subspeed
fractional speed
Definition: vehicle_base.h:308
SpecializedVehicle< Aircraft, VEH_AIRCRAFT >::From
static Aircraft * From(Vehicle *v)
Converts a Vehicle to SpecializedVehicle with type checking.
Definition: vehicle_base.h:1183
DIRDIFF_45RIGHT
@ DIRDIFF_45RIGHT
Angle of 45 degrees right.
Definition: direction_type.h:64
Aircraft::crashed_counter
uint16 crashed_counter
Timer for handling crash animations.
Definition: aircraft.h:75
Vehicle::z_extent
byte z_extent
z-extent of vehicle bounding box
Definition: vehicle_base.h:297
VehicleRandomBits
byte VehicleRandomBits()
Get a value for a vehicle's random_bits.
Definition: vehicle.cpp:363
Vehicle::InvalidateNewGRFCacheOfChain
void InvalidateNewGRFCacheOfChain()
Invalidates cached NewGRF variables of all vehicles in the chain (after the current vehicle)
Definition: vehicle_base.h:487
OrthogonalTileArea::tile
TileIndex tile
The base tile of the area.
Definition: tilearea_type.h:19
PaletteID
uint32 PaletteID
The number of the palette.
Definition: gfx_type.h:18
Aircraft::OnNewDay
void OnNewDay()
Calls the new day handler of the vehicle.
Definition: aircraft_cmd.cpp:443
AIR_HELICOPTER
@ AIR_HELICOPTER
an helicopter
Definition: aircraft.h:31
RemoveOrderFromAllVehicles
void RemoveOrderFromAllVehicles(OrderType type, DestinationID destination, bool hangar)
Removes an order from all vehicles.
Definition: order_cmd.cpp:1765
framerate_type.h
Aircraft::IsNormalAircraft
bool IsNormalAircraft() const
Check if the aircraft type is a normal flying device; eg not a rotor or a shadow.
Definition: aircraft.h:121
cheat_type.h
BaseConsist::current_order_time
uint32 current_order_time
How many ticks have passed since this order started.
Definition: base_consist.h:22
AircraftEntersTerminal
static void AircraftEntersTerminal(Aircraft *v)
Aircraft arrives at a terminal.
Definition: aircraft_cmd.cpp:1389
FreeTerminal
static bool FreeTerminal(Aircraft *v, byte i, byte last_terminal)
Find a free terminal or helipad, and if available, assign it.
Definition: aircraft_cmd.cpp:1937
OWNER_NONE
@ OWNER_NONE
The tile has no ownership.
Definition: company_type.h:25
UpdateAircraftCache
void UpdateAircraftCache(Aircraft *v, bool update_range)
Update cached values of an aircraft.
Definition: aircraft_cmd.cpp:590
GetNewVehiclePosResult
Position information of a vehicle after it moved.
Definition: vehicle_func.h:75
WC_VEHICLE_DEPOT
@ WC_VEHICLE_DEPOT
Depot view; Window numbers:
Definition: window_type.h:344
NUM_CARGO
@ NUM_CARGO
Maximal number of cargo types in a game.
Definition: cargo_type.h:65
GetStationIndex
static StationID GetStationIndex(TileIndex t)
Get StationID from a tile.
Definition: station_map.h:28
SpecializedStation< Station, false >::GetByTile
static Station * GetByTile(TileIndex tile)
Get the station belonging to a specific tile.
Definition: base_station_base.h:237
Vehicle::build_year
Year build_year
Year the vehicle has been built.
Definition: vehicle_base.h:272
Aircraft::previous_pos
byte previous_pos
Previous desired position of the aircraft.
Definition: aircraft.h:77
AircraftEventHandler_AtTerminal
static void AircraftEventHandler_AtTerminal(Aircraft *v, const AirportFTAClass *apc)
At one of the Airport's Terminals.
Definition: aircraft_cmd.cpp:1551
HELIPAD1
@ HELIPAD1
Heading for helipad 1.
Definition: airport.h:69
UpdateAirplanesOnNewStation
void UpdateAirplanesOnNewStation(const Station *st)
Updates the status of the Aircraft heading or in the station.
Definition: aircraft_cmd.cpp:2143
AirportMovingData::y
int16 y
y-coordinate of the destination.
Definition: airport.h:133
HELITAKEOFF
@ HELITAKEOFF
Helicopter wants to leave the airport.
Definition: airport.h:74
DAYS_IN_YEAR
static const int DAYS_IN_YEAR
days per year
Definition: date_type.h:29
AircraftNextAirportPos_and_Order
void AircraftNextAirportPos_and_Order(Aircraft *v)
set the right pos when heading to other airports after takeoff
Definition: aircraft_cmd.cpp:1435
SPEED_LIMIT_NONE
@ SPEED_LIMIT_NONE
No environmental speed limit. Speed limit is type dependent.
Definition: aircraft_cmd.cpp:625
BaseStation::xy
TileIndex xy
Base tile of the station.
Definition: base_station_base.h:53
GetTileMaxPixelZ
static int GetTileMaxPixelZ(TileIndex tile)
Get top height of the tile.
Definition: tile_map.h:304
VehicleCache::cached_max_speed
uint16 cached_max_speed
Maximum speed of the consist (minimum of the max speed of all vehicles in the consist).
Definition: vehicle_base.h:125
FindNearestHangar
static StationID FindNearestHangar(const Aircraft *v)
Find the nearest hangar to v INVALID_STATION is returned, if the company does not have any suitable a...
Definition: aircraft_cmd.cpp:122
company_func.h
ORIGINAL_SAMPLE_COUNT
static const uint ORIGINAL_SAMPLE_COUNT
The number of sounds in the original sample.cat.
Definition: sound_type.h:116
AircraftVehicleInfo::mail_capacity
byte mail_capacity
Mail capacity (bags).
Definition: engine_type.h:107
SpecializedVehicle< Aircraft, VEH_AIRCRAFT >::Iterate
static Pool::IterateWrapper< Aircraft > Iterate(size_t from=0)
Returns an iterable ensemble of all valid vehicles of type T.
Definition: vehicle_base.h:1252
MapMaxX
static uint MapMaxX()
Gets the maximum X coordinate within the map, including MP_VOID.
Definition: map_func.h:102
Engine::original_image_index
uint8 original_image_index
Original vehicle image index, thus the image index of the overridden vehicle.
Definition: engine_base.h:54
GetNewVehiclePosResult::old_tile
TileIndex old_tile
Current tile of the vehicle.
Definition: vehicle_func.h:77
PlayVehicleSound
bool PlayVehicleSound(const Vehicle *v, VehicleSoundEvent event, bool force)
Checks whether a NewGRF wants to play a different vehicle sound effect.
Definition: newgrf_sound.cpp:187
abs
static T abs(const T a)
Returns the absolute value of (scalar) variable.
Definition: math_func.hpp:21
AirportFTA::block
uint64 block
64 bit blocks (st->airport.flags), should be enough for the most complex airports
Definition: airport.h:192
error
void CDECL error(const char *s,...)
Error handling for fatal non-user errors.
Definition: openttd.cpp:134
Order::GetDepotOrderType
OrderDepotTypeFlags GetDepotOrderType() const
What caused us going to the depot?
Definition: order_base.h:145
Aircraft::pos
byte pos
Next desired position of the aircraft.
Definition: aircraft.h:76
AddVehicleAdviceNewsItem
static void AddVehicleAdviceNewsItem(StringID string, VehicleID vehicle)
Adds a vehicle-advice news item.
Definition: news_func.h:40
AIR_CTOL
@ AIR_CTOL
Conventional Take Off and Landing, i.e. planes.
Definition: engine_type.h:94
Vehicle::subtype
byte subtype
subtype (Filled with values from AircraftSubType/DisasterSubType/EffectVehicleType/GroundVehicleSubty...
Definition: vehicle_base.h:342
CommandHelper
Definition: command_func.h:94
Vehicle::day_counter
byte day_counter
Increased by one for each day.
Definition: vehicle_base.h:328
VS_UNCLICKABLE
@ VS_UNCLICKABLE
Vehicle is not clickable by the user (shadow vehicles).
Definition: vehicle_base.h:36
TERMGROUP
@ TERMGROUP
Aircraft is looking for a free terminal in a terminalgroup.
Definition: airport.h:84
window_func.h
Debug
#define Debug(name, level, format_string,...)
Ouptut a line of debugging information.
Definition: debug.h:37
SetBit
static T SetBit(T &x, const uint8 y)
Set a bit in a variable.
Definition: bitmath_func.hpp:121
TO_ALL
@ TO_ALL
Go in this direction for every target.
Definition: airport.h:61
AircraftController
static bool AircraftController(Aircraft *v)
Controls the movement of an aircraft.
Definition: aircraft_cmd.cpp:856
lengthof
#define lengthof(x)
Return the length of an fixed size array.
Definition: stdafx.h:386
random_func.hpp
AgeVehicle
void AgeVehicle(Vehicle *v)
Update age of a vehicle.
Definition: vehicle.cpp:1378
SpecializedStation< Station, false >::GetIfValid
static Station * GetIfValid(size_t index)
Returns station if the index is a valid index for this station type.
Definition: base_station_base.h:227
Vehicle::progress
byte progress
The percentage (if divided by 256) this vehicle already crossed the tile unit.
Definition: vehicle_base.h:311
AirportFTAClass::terminals
const byte * terminals
Array with the number of terminal groups, followed by the number of terminals in each group.
Definition: airport.h:178
STARTTAKEOFF
@ STARTTAKEOFF
Airplane has arrived at a runway for take-off.
Definition: airport.h:72
TILE_HEIGHT
static const uint TILE_HEIGHT
Height of a height level in world coordinate AND in pixels in #ZOOM_LVL_BASE.
Definition: tile_type.h:18
Engine::DetermineCapacity
uint DetermineCapacity(const Vehicle *v, uint16 *mail_capacity=nullptr) const
Determines capacity of a given vehicle from scratch.
Definition: engine.cpp:197
OverflowSafeInt< int64 >
TERM8_block
static const uint64 TERM8_block
Block belonging to terminal 8.
Definition: airport.h:116
Airport::type
byte type
Type of this airport,.
Definition: station_base.h:306
CargoID
byte CargoID
Cargo slots to indicate a cargo type within a game.
Definition: cargo_type.h:20
Chance16R
static bool Chance16R(const uint a, const uint b, uint32 &r)
Flips a coin with a given probability and saves the randomize-number in a variable.
Definition: random_func.hpp:155
engine_base.h
Vehicle::cargo_type
CargoID cargo_type
type of cargo this vehicle is carrying
Definition: vehicle_base.h:320
VehicleSettings::plane_speed
uint8 plane_speed
divisor for speed of aircraft
Definition: settings_type.h:499
Vehicle::spritenum
byte spritenum
currently displayed sprite index 0xfd == custom sprite, 0xfe == custom second head sprite 0xff == res...
Definition: vehicle_base.h:294
AMED_HELI_RAISE
@ AMED_HELI_RAISE
Helicopter take-off.
Definition: airport.h:54
AircraftCache::cached_max_range
uint16 cached_max_range
Cached maximum range.
Definition: aircraft.h:68
LANDING
@ LANDING
Airplane wants to land.
Definition: airport.h:76
CeilDiv
static uint CeilDiv(uint a, uint b)
Computes ceil(a / b) for non-negative a and b.
Definition: math_func.hpp:254
Aircraft::state
byte state
State of the airport.
Definition: aircraft.h:79
TERM4_block
static const uint64 TERM4_block
Block belonging to terminal 4.
Definition: airport.h:92
AirportFTA::position
byte position
the position that an airplane is at
Definition: airport.h:193
TERM6
@ TERM6
Heading for terminal 6.
Definition: airport.h:68
GameSettings::vehicle
VehicleSettings vehicle
options for vehicles
Definition: settings_type.h:595
BaseVehicle::type
VehicleType type
Type of vehicle.
Definition: vehicle_type.h:52
AirportFTAClass::entry_points
const byte * entry_points
when an airplane arrives at this airport, enter it at position entry_point, index depends on directio...
Definition: airport.h:182
Vehicle::UpdatePositionAndViewport
void UpdatePositionAndViewport()
Update the position of the vehicle, and update the viewport.
Definition: vehicle.cpp:1681
FACIL_AIRPORT
@ FACIL_AIRPORT
Station with an airport.
Definition: station_type.h:56
Vehicle::reliability
uint16 reliability
Reliability.
Definition: vehicle_base.h:276
PROP_AIRCRAFT_SPEED
@ PROP_AIRCRAFT_SPEED
Max. speed: 1 unit = 8 mph = 12.8 km-ish/h.
Definition: newgrf_properties.h:50
MovementTerminalMapping::state
AirportMovementStates state
Aircraft movement state when going to this terminal.
Definition: aircraft_cmd.cpp:1911
TERM8
@ TERM8
Heading for terminal 8.
Definition: airport.h:81
Vehicle::UpdatePosition
void UpdatePosition()
Update the position of the vehicle.
Definition: vehicle.cpp:1610
GetAircraftFlightLevelBounds
void GetAircraftFlightLevelBounds(const Vehicle *v, int *min_level, int *max_level)
Get the 'flight level' bounds, in pixels from 'z_pos' 0 for a particular vehicle for normal flight si...
Definition: aircraft_cmd.cpp:717
Engine::flags
byte flags
Flags of the engine.
Definition: engine_base.h:48
AirportFindFreeTerminal
static bool AirportFindFreeTerminal(Aircraft *v, const AirportFTAClass *apc)
Find a free terminal, and assign it if available.
Definition: aircraft_cmd.cpp:1972
Rect::Width
int Width() const
Get width of Rect.
Definition: geometry_type.hpp:79
CanVehicleUseStation
bool CanVehicleUseStation(EngineID engine_type, const Station *st)
Can this station be used by the given engine type?
Definition: vehicle.cpp:2861
AircraftLandAirplane
static void AircraftLandAirplane(Aircraft *v)
Aircraft touched down at the landing strip.
Definition: aircraft_cmd.cpp:1418
Vehicle::HandleBreakdown
bool HandleBreakdown()
Handle all of the aspects of a vehicle breakdown This includes adding smoke and sounds,...
Definition: vehicle.cpp:1312
AircraftVehicleInfo
Information about a aircraft vehicle.
Definition: engine_type.h:99
DecreaseVehicleValue
void DecreaseVehicleValue(Vehicle *v)
Decrease the value of a vehicle.
Definition: vehicle.cpp:1250
GetNewVehiclePosResult::y
int y
x and y position of the vehicle after moving
Definition: vehicle_func.h:76
disaster_vehicle.h
Aircraft::Tick
bool Tick()
Calls the tick handler of the vehicle.
Definition: aircraft_cmd.cpp:2100
DIAGDIR_NE
@ DIAGDIR_NE
Northeast, upper right on your monitor.
Definition: direction_type.h:79
TAKEOFF
@ TAKEOFF
Airplane wants to leave the airport.
Definition: airport.h:71
Rect
Specification of a rectangle with absolute coordinates of all edges.
Definition: geometry_type.hpp:69
AirportFTAClass::AIRPLANES
@ AIRPLANES
Can planes land on this airport type?
Definition: airport.h:147
DepotCommand::None
@ None
No special flags.
SPEED_LIMIT_BROKEN
@ SPEED_LIMIT_BROKEN
Maximum speed of an aircraft that is broken.
Definition: aircraft_cmd.cpp:623
SetWindowClassesDirty
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting)
Definition: window.cpp:3180
VehicleSpriteSeq::GetBounds
void GetBounds(Rect *bounds) const
Determine shared bounds of all sprites.
Definition: vehicle.cpp:98
Order::GetDepotActionType
OrderDepotActionFlags GetDepotActionType() const
What are we going to do when in the depot.
Definition: order_base.h:147
WC_AIRCRAFT_LIST
@ WC_AIRCRAFT_LIST
Aircraft list; Window numbers:
Definition: window_type.h:319
Aircraft::UpdateDeltaXY
void UpdateDeltaXY()
Updates the x and y offsets and the size of the sprite used for this vehicle.
Definition: aircraft_cmd.cpp:47
CLRBITS
#define CLRBITS(x, y)
Clears several bits in a variable.
Definition: bitmath_func.hpp:166
PROP_AIRCRAFT_RANGE
@ PROP_AIRCRAFT_RANGE
Aircraft range.
Definition: newgrf_properties.h:55
AirportFTAClass::MovingData
const AirportMovingData * MovingData(byte position) const
Get movement data at a position.
Definition: airport.h:170
HELIPAD2
@ HELIPAD2
Heading for helipad 2.
Definition: airport.h:70
HELIPAD1_block
static const uint64 HELIPAD1_block
Block belonging to helipad 1.
Definition: airport.h:95
SpecializedVehicle::UpdateViewport
void UpdateViewport(bool force_update, bool update_delta)
Update vehicle sprite- and position caches.
Definition: vehicle_base.h:1205
Aircraft::MarkDirty
void MarkDirty()
Marks the vehicles to be redrawn and updates cached variables.
Definition: aircraft_cmd.cpp:1297
Order
Definition: order_base.h:36
TERM3_block
static const uint64 TERM3_block
Block belonging to terminal 3.
Definition: airport.h:91
VS_SHADOW
@ VS_SHADOW
Vehicle is a shadow vehicle.
Definition: vehicle_base.h:39
AirportFTA::next_position
byte next_position
next position from this position
Definition: airport.h:194
Aircraft::flags
byte flags
Aircraft flags.
Definition: aircraft.h:83
TERM2_block
static const uint64 TERM2_block
Block belonging to terminal 2.
Definition: airport.h:90
StationCargoList::Truncate
uint Truncate(uint max_move=UINT_MAX, StationCargoAmountMap *cargo_per_source=nullptr)
Truncates where each destination loses roughly the same percentage of its cargo.
Definition: cargopacket.cpp:769
DAY_TICKS
static const int DAY_TICKS
1 day is 74 ticks; _date_fract used to be uint16 and incremented by 885.
Definition: date_type.h:28
TERM6_block
static const uint64 TERM6_block
Block belonging to terminal 6.
Definition: airport.h:94
AT_DUMMY
@ AT_DUMMY
Dummy airport.
Definition: airport.h:43
FLYING
@ FLYING
Vehicle is flying in the air.
Definition: airport.h:75
AMED_HELI_LOWER
@ AMED_HELI_LOWER
Helicopter landing.
Definition: airport.h:55
AIRCRAFT_MIN_FLYING_ALTITUDE
@ AIRCRAFT_MIN_FLYING_ALTITUDE
Minimum flying altitude above tile.
Definition: aircraft.h:21
CmdBuildAircraft
CommandCost CmdBuildAircraft(DoCommandFlag flags, TileIndex tile, const Engine *e, Vehicle **ret)
Build an aircraft.
Definition: aircraft_cmd.cpp:269
_aircraft_state_handlers
static AircraftStateHandler *const _aircraft_state_handlers[]
Array of handler functions for each target of the aircraft.
Definition: aircraft_cmd.cpp:1742
AT_OILRIG
@ AT_OILRIG
Oilrig airport.
Definition: airport.h:38
Engine::reliability
uint16 reliability
Current reliability of the engine.
Definition: engine_base.h:40
Vehicle::refit_cap
uint16 refit_cap
Capacity left over from before last refit.
Definition: vehicle_base.h:323
Vehicle::date_of_last_service
Date date_of_last_service
Last date the vehicle had a service at a depot.
Definition: vehicle_base.h:275
GetNewVehiclePos
GetNewVehiclePosResult GetNewVehiclePos(const Vehicle *v)
Get position information of a vehicle when moving one pixel in the direction it is facing.
Definition: vehicle.cpp:1701
SetAircraftPosition
void SetAircraftPosition(Aircraft *v, int x, int y, int z)
Set aircraft position.
Definition: aircraft_cmd.cpp:521
AMED_BRAKE
@ AMED_BRAKE
Taxiing at the airport.
Definition: airport.h:53
TERM4
@ TERM4
Heading for terminal 4.
Definition: airport.h:66
TileVirtXY
static TileIndex TileVirtXY(uint x, uint y)
Get a tile from the virtual XY-coordinate.
Definition: map_func.h:194
AIR_ROTOR
@ AIR_ROTOR
rotor of an helicopter
Definition: aircraft.h:34
Vehicle::GetNextStoppingStation
StationIDStack GetNextStoppingStation() const
Get the next station the vehicle will stop at.
Definition: vehicle_base.h:728
news_func.h
AMED_NOSPDCLAMP
@ AMED_NOSPDCLAMP
No speed restrictions.
Definition: airport.h:48
ROTOR_Z_OFFSET
static const int ROTOR_Z_OFFSET
Z Offset between helicopter- and rotorsprite.
Definition: aircraft.h:50
backup_type.hpp