/
vehicle.cpp
2880 lines (2461 loc) · 97.3 KB
/
vehicle.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* $Id$ */
/*
* This file is part of OpenTTD.
* 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.
* 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.
* 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/>.
*/
/** @file vehicle.cpp Base implementations of all vehicles. */
#include "stdafx.h"
#include "error.h"
#include "roadveh.h"
#include "ship.h"
#include "spritecache.h"
#include "timetable.h"
#include "viewport_func.h"
#include "news_func.h"
#include "command_func.h"
#include "company_func.h"
#include "train.h"
#include "aircraft.h"
#include "newgrf_debug.h"
#include "newgrf_sound.h"
#include "newgrf_station.h"
#include "group_gui.h"
#include "strings_func.h"
#include "zoom_func.h"
#include "date_func.h"
#include "vehicle_func.h"
#include "autoreplace_func.h"
#include "autoreplace_gui.h"
#include "station_base.h"
#include "ai/ai.hpp"
#include "depot_func.h"
#include "network/network.h"
#include "core/pool_func.hpp"
#include "economy_base.h"
#include "articulated_vehicles.h"
#include "roadstop_base.h"
#include "core/random_func.hpp"
#include "core/backup_type.hpp"
#include "order_backup.h"
#include "sound_func.h"
#include "effectvehicle_func.h"
#include "effectvehicle_base.h"
#include "vehiclelist.h"
#include "bridge_map.h"
#include "tunnel_map.h"
#include "depot_map.h"
#include "gamelog.h"
#include "linkgraph/linkgraph.h"
#include "linkgraph/refresh.h"
#include "table/strings.h"
#include "safeguards.h"
/* Number of bits in the hash to use from each vehicle coord */
static const uint GEN_HASHX_BITS = 6;
static const uint GEN_HASHY_BITS = 6;
/* Size of each hash bucket */
static const uint GEN_HASHX_BUCKET_BITS = 7;
static const uint GEN_HASHY_BUCKET_BITS = 6;
/* Compute hash for vehicle coord */
#define GEN_HASHX(x) GB((x), GEN_HASHX_BUCKET_BITS + ZOOM_LVL_SHIFT, GEN_HASHX_BITS)
#define GEN_HASHY(y) (GB((y), GEN_HASHY_BUCKET_BITS + ZOOM_LVL_SHIFT, GEN_HASHY_BITS) << GEN_HASHX_BITS)
#define GEN_HASH(x, y) (GEN_HASHY(y) + GEN_HASHX(x))
/* Maximum size until hash repeats */
static const int GEN_HASHX_SIZE = 1 << (GEN_HASHX_BUCKET_BITS + GEN_HASHX_BITS + ZOOM_LVL_SHIFT);
static const int GEN_HASHY_SIZE = 1 << (GEN_HASHY_BUCKET_BITS + GEN_HASHY_BITS + ZOOM_LVL_SHIFT);
/* Increments to reach next bucket in hash table */
static const int GEN_HASHX_INC = 1;
static const int GEN_HASHY_INC = 1 << GEN_HASHX_BITS;
/* Mask to wrap-around buckets */
static const uint GEN_HASHX_MASK = (1 << GEN_HASHX_BITS) - 1;
static const uint GEN_HASHY_MASK = ((1 << GEN_HASHY_BITS) - 1) << GEN_HASHX_BITS;
VehicleID _new_vehicle_id;
uint16 _returned_refit_capacity; ///< Stores the capacity after a refit operation.
uint16 _returned_mail_refit_capacity; ///< Stores the mail capacity after a refit operation (Aircraft only).
/** The pool with all our precious vehicles. */
VehiclePool _vehicle_pool("Vehicle");
INSTANTIATE_POOL_METHODS(Vehicle)
/**
* Determine shared bounds of all sprites.
* @param [out] bounds Shared bounds.
*/
void VehicleSpriteSeq::GetBounds(Rect *bounds) const
{
bounds->left = bounds->top = bounds->right = bounds->bottom = 0;
for (uint i = 0; i < this->count; ++i) {
const Sprite *spr = GetSprite(this->seq[i].sprite, ST_NORMAL);
if (i == 0) {
bounds->left = spr->x_offs;
bounds->top = spr->y_offs;
bounds->right = spr->width + spr->x_offs - 1;
bounds->bottom = spr->height + spr->y_offs - 1;
} else {
if (spr->x_offs < bounds->left) bounds->left = spr->x_offs;
if (spr->y_offs < bounds->top) bounds->top = spr->y_offs;
int right = spr->width + spr->x_offs - 1;
int bottom = spr->height + spr->y_offs - 1;
if (right > bounds->right) bounds->right = right;
if (bottom > bounds->bottom) bounds->bottom = bottom;
}
}
}
/**
* Draw the sprite sequence.
* @param x X position
* @param y Y position
* @param default_pal Vehicle palette
* @param force_pal Whether to ignore individual palettes, and draw everything with \a default_pal.
*/
void VehicleSpriteSeq::Draw(int x, int y, PaletteID default_pal, bool force_pal) const
{
for (uint i = 0; i < this->count; ++i) {
PaletteID pal = force_pal || !this->seq[i].pal ? default_pal : this->seq[i].pal;
DrawSprite(this->seq[i].sprite, pal, x, y);
}
}
/**
* Function to tell if a vehicle needs to be autorenewed
* @param *c The vehicle owner
* @param use_renew_setting Should the company renew setting be considered?
* @return true if the vehicle is old enough for replacement
*/
bool Vehicle::NeedsAutorenewing(const Company *c, bool use_renew_setting) const
{
/* We can always generate the Company pointer when we have the vehicle.
* However this takes time and since the Company pointer is often present
* when this function is called then it's faster to pass the pointer as an
* argument rather than finding it again. */
assert(c == Company::Get(this->owner));
if (use_renew_setting && !c->settings.engine_renew) return false;
if (this->age - this->max_age < (c->settings.engine_renew_months * 30)) return false;
/* Only engines need renewing */
if (this->type == VEH_TRAIN && !Train::From(this)->IsEngine()) return false;
return true;
}
/**
* Service a vehicle and all subsequent vehicles in the consist
*
* @param *v The vehicle or vehicle chain being serviced
*/
void VehicleServiceInDepot(Vehicle *v)
{
assert(v != NULL);
SetWindowDirty(WC_VEHICLE_DETAILS, v->index); // ensure that last service date and reliability are updated
do {
v->date_of_last_service = _date;
v->breakdowns_since_last_service = 0;
v->reliability = v->GetEngine()->reliability;
/* Prevent vehicles from breaking down directly after exiting the depot. */
v->breakdown_chance /= 4;
v = v->Next();
} while (v != NULL && v->HasEngineType());
}
/**
* Check if the vehicle needs to go to a depot in near future (if a opportunity presents itself) for service or replacement.
*
* @see NeedsAutomaticServicing()
* @return true if the vehicle should go to a depot if a opportunity presents itself.
*/
bool Vehicle::NeedsServicing() const
{
/* Stopped or crashed vehicles will not move, as such making unmovable
* vehicles to go for service is lame. */
if (this->vehstatus & (VS_STOPPED | VS_CRASHED)) return false;
/* Are we ready for the next service cycle? */
const Company *c = Company::Get(this->owner);
if (this->ServiceIntervalIsPercent() ?
(this->reliability >= this->GetEngine()->reliability * (100 - this->GetServiceInterval()) / 100) :
(this->date_of_last_service + this->GetServiceInterval() >= _date)) {
return false;
}
/* If we're servicing anyway, because we have not disabled servicing when
* there are no breakdowns or we are playing with breakdowns, bail out. */
if (!_settings_game.order.no_servicing_if_no_breakdowns ||
_settings_game.difficulty.vehicle_breakdowns != 0) {
return true;
}
/* Test whether there is some pending autoreplace.
* Note: We do this after the service-interval test.
* There are a lot more reasons for autoreplace to fail than we can test here reasonably. */
bool pending_replace = false;
Money needed_money = c->settings.engine_renew_money;
if (needed_money > c->money) return false;
for (const Vehicle *v = this; v != NULL; v = (v->type == VEH_TRAIN) ? Train::From(v)->GetNextUnit() : NULL) {
bool replace_when_old = false;
EngineID new_engine = EngineReplacementForCompany(c, v->engine_type, v->group_id, &replace_when_old);
/* Check engine availability */
if (new_engine == INVALID_ENGINE || !HasBit(Engine::Get(new_engine)->company_avail, v->owner)) continue;
/* Is the vehicle old if we are not always replacing? */
if (replace_when_old && !v->NeedsAutorenewing(c, false)) continue;
/* Check refittability */
uint32 available_cargo_types, union_mask;
GetArticulatedRefitMasks(new_engine, true, &union_mask, &available_cargo_types);
/* Is there anything to refit? */
if (union_mask != 0) {
CargoID cargo_type;
/* We cannot refit to mixed cargoes in an automated way */
if (IsArticulatedVehicleCarryingDifferentCargoes(v, &cargo_type)) continue;
/* Did the old vehicle carry anything? */
if (cargo_type != CT_INVALID) {
/* We can't refit the vehicle to carry the cargo we want */
if (!HasBit(available_cargo_types, cargo_type)) continue;
}
}
/* Check money.
* We want 2*(the price of the new vehicle) without looking at the value of the vehicle we are going to sell. */
pending_replace = true;
needed_money += 2 * Engine::Get(new_engine)->GetCost();
if (needed_money > c->money) return false;
}
return pending_replace;
}
/**
* Checks if the current order should be interrupted for a service-in-depot order.
* @see NeedsServicing()
* @return true if the current order should be interrupted.
*/
bool Vehicle::NeedsAutomaticServicing() const
{
if (this->HasDepotOrder()) return false;
if (this->current_order.IsType(OT_LOADING)) return false;
if (this->current_order.IsType(OT_GOTO_DEPOT) && this->current_order.GetDepotOrderType() != ODTFB_SERVICE) return false;
return NeedsServicing();
}
uint Vehicle::Crash(bool flooded)
{
assert((this->vehstatus & VS_CRASHED) == 0);
assert(this->Previous() == NULL); // IsPrimaryVehicle fails for free-wagon-chains
uint pass = 0;
/* Stop the vehicle. */
if (this->IsPrimaryVehicle()) this->vehstatus |= VS_STOPPED;
/* crash all wagons, and count passengers */
for (Vehicle *v = this; v != NULL; v = v->Next()) {
/* We do not transfer reserver cargo back, so TotalCount() instead of StoredCount() */
if (IsCargoInClass(v->cargo_type, CC_PASSENGERS)) pass += v->cargo.TotalCount();
v->vehstatus |= VS_CRASHED;
v->MarkAllViewportsDirty();
}
/* Dirty some windows */
InvalidateWindowClassesData(GetWindowClassForVehicleType(this->type), 0);
SetWindowWidgetDirty(WC_VEHICLE_VIEW, this->index, WID_VV_START_STOP);
SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
SetWindowDirty(WC_VEHICLE_DEPOT, this->tile);
delete this->cargo_payment;
assert(this->cargo_payment == NULL); // cleared by ~CargoPayment
return RandomRange(pass + 1); // Randomise deceased passengers.
}
/**
* Displays a "NewGrf Bug" error message for a engine, and pauses the game if not networking.
* @param engine The engine that caused the problem
* @param part1 Part 1 of the error message, taking the grfname as parameter 1
* @param part2 Part 2 of the error message, taking the engine as parameter 2
* @param bug_type Flag to check and set in grfconfig
* @param critical Shall the "OpenTTD might crash"-message be shown when the player tries to unpause?
*/
void ShowNewGrfVehicleError(EngineID engine, StringID part1, StringID part2, GRFBugs bug_type, bool critical)
{
const Engine *e = Engine::Get(engine);
GRFConfig *grfconfig = GetGRFConfig(e->GetGRFID());
/* Missing GRF. Nothing useful can be done in this situation. */
if (grfconfig == NULL) return;
if (!HasBit(grfconfig->grf_bugs, bug_type)) {
SetBit(grfconfig->grf_bugs, bug_type);
SetDParamStr(0, grfconfig->GetName());
SetDParam(1, engine);
ShowErrorMessage(part1, part2, WL_CRITICAL);
if (!_networking) DoCommand(0, critical ? PM_PAUSED_ERROR : PM_PAUSED_NORMAL, 1, DC_EXEC, CMD_PAUSE);
}
/* debug output */
char buffer[512];
SetDParamStr(0, grfconfig->GetName());
GetString(buffer, part1, lastof(buffer));
DEBUG(grf, 0, "%s", buffer + 3);
SetDParam(1, engine);
GetString(buffer, part2, lastof(buffer));
DEBUG(grf, 0, "%s", buffer + 3);
}
/**
* Logs a bug in GRF and shows a warning message if this
* is for the first time this happened.
* @param u first vehicle of chain
*/
void VehicleLengthChanged(const Vehicle *u)
{
/* show a warning once for each engine in whole game and once for each GRF after each game load */
const Engine *engine = u->GetEngine();
uint32 grfid = engine->grf_prop.grffile->grfid;
GRFConfig *grfconfig = GetGRFConfig(grfid);
if (GamelogGRFBugReverse(grfid, engine->grf_prop.local_id) || !HasBit(grfconfig->grf_bugs, GBUG_VEH_LENGTH)) {
ShowNewGrfVehicleError(u->engine_type, STR_NEWGRF_BROKEN, STR_NEWGRF_BROKEN_VEHICLE_LENGTH, GBUG_VEH_LENGTH, true);
}
}
/**
* Vehicle constructor.
* @param type Type of the new vehicle.
*/
Vehicle::Vehicle(VehicleType type)
{
this->type = type;
this->coord.left = INVALID_COORD;
this->group_id = DEFAULT_GROUP;
this->fill_percent_te_id = INVALID_TE_ID;
this->first = this;
this->colourmap = PAL_NONE;
this->cargo_age_counter = 1;
this->last_station_visited = INVALID_STATION;
this->last_loading_station = INVALID_STATION;
}
/**
* Get a value for a vehicle's random_bits.
* @return A random value from 0 to 255.
*/
byte VehicleRandomBits()
{
return GB(Random(), 0, 8);
}
/* Size of the hash, 6 = 64 x 64, 7 = 128 x 128. Larger sizes will (in theory) reduce hash
* lookup times at the expense of memory usage. */
const int HASH_BITS = 7;
const int HASH_SIZE = 1 << HASH_BITS;
const int HASH_MASK = HASH_SIZE - 1;
const int TOTAL_HASH_SIZE = 1 << (HASH_BITS * 2);
const int TOTAL_HASH_MASK = TOTAL_HASH_SIZE - 1;
/* Resolution of the hash, 0 = 1*1 tile, 1 = 2*2 tiles, 2 = 4*4 tiles, etc.
* Profiling results show that 0 is fastest. */
const int HASH_RES = 0;
static Vehicle *_vehicle_tile_hash[TOTAL_HASH_SIZE];
static Vehicle *VehicleFromTileHash(int xl, int yl, int xu, int yu, void *data, VehicleFromPosProc *proc, bool find_first)
{
for (int y = yl; ; y = (y + (1 << HASH_BITS)) & (HASH_MASK << HASH_BITS)) {
for (int x = xl; ; x = (x + 1) & HASH_MASK) {
Vehicle *v = _vehicle_tile_hash[(x + y) & TOTAL_HASH_MASK];
for (; v != NULL; v = v->hash_tile_next) {
Vehicle *a = proc(v, data);
if (find_first && a != NULL) return a;
}
if (x == xu) break;
}
if (y == yu) break;
}
return NULL;
}
/**
* Helper function for FindVehicleOnPos/HasVehicleOnPos.
* @note Do not call this function directly!
* @param x The X location on the map
* @param y The Y location on the map
* @param data Arbitrary data passed to proc
* @param proc The proc that determines whether a vehicle will be "found".
* @param find_first Whether to return on the first found or iterate over
* all vehicles
* @return the best matching or first vehicle (depending on find_first).
*/
static Vehicle *VehicleFromPosXY(int x, int y, void *data, VehicleFromPosProc *proc, bool find_first)
{
const int COLL_DIST = 6;
/* Hash area to scan is from xl,yl to xu,yu */
int xl = GB((x - COLL_DIST) / TILE_SIZE, HASH_RES, HASH_BITS);
int xu = GB((x + COLL_DIST) / TILE_SIZE, HASH_RES, HASH_BITS);
int yl = GB((y - COLL_DIST) / TILE_SIZE, HASH_RES, HASH_BITS) << HASH_BITS;
int yu = GB((y + COLL_DIST) / TILE_SIZE, HASH_RES, HASH_BITS) << HASH_BITS;
return VehicleFromTileHash(xl, yl, xu, yu, data, proc, find_first);
}
/**
* Find a vehicle from a specific location. It will call proc for ALL vehicles
* on the tile and YOU must make SURE that the "best one" is stored in the
* data value and is ALWAYS the same regardless of the order of the vehicles
* where proc was called on!
* When you fail to do this properly you create an almost untraceable DESYNC!
* @note The return value of proc will be ignored.
* @note Use this when you have the intention that all vehicles
* should be iterated over.
* @param x The X location on the map
* @param y The Y location on the map
* @param data Arbitrary data passed to proc
* @param proc The proc that determines whether a vehicle will be "found".
*/
void FindVehicleOnPosXY(int x, int y, void *data, VehicleFromPosProc *proc)
{
VehicleFromPosXY(x, y, data, proc, false);
}
/**
* Checks whether a vehicle in on a specific location. It will call proc for
* vehicles until it returns non-NULL.
* @note Use FindVehicleOnPosXY when you have the intention that all vehicles
* should be iterated over.
* @param x The X location on the map
* @param y The Y location on the map
* @param data Arbitrary data passed to proc
* @param proc The proc that determines whether a vehicle will be "found".
* @return True if proc returned non-NULL.
*/
bool HasVehicleOnPosXY(int x, int y, void *data, VehicleFromPosProc *proc)
{
return VehicleFromPosXY(x, y, data, proc, true) != NULL;
}
/**
* Helper function for FindVehicleOnPos/HasVehicleOnPos.
* @note Do not call this function directly!
* @param tile The location on the map
* @param data Arbitrary data passed to \a proc.
* @param proc The proc that determines whether a vehicle will be "found".
* @param find_first Whether to return on the first found or iterate over
* all vehicles
* @return the best matching or first vehicle (depending on find_first).
*/
static Vehicle *VehicleFromPos(TileIndex tile, void *data, VehicleFromPosProc *proc, bool find_first)
{
int x = GB(TileX(tile), HASH_RES, HASH_BITS);
int y = GB(TileY(tile), HASH_RES, HASH_BITS) << HASH_BITS;
Vehicle *v = _vehicle_tile_hash[(x + y) & TOTAL_HASH_MASK];
for (; v != NULL; v = v->hash_tile_next) {
if (v->tile != tile) continue;
Vehicle *a = proc(v, data);
if (find_first && a != NULL) return a;
}
return NULL;
}
/**
* Find a vehicle from a specific location. It will call \a proc for ALL vehicles
* on the tile and YOU must make SURE that the "best one" is stored in the
* data value and is ALWAYS the same regardless of the order of the vehicles
* where proc was called on!
* When you fail to do this properly you create an almost untraceable DESYNC!
* @note The return value of \a proc will be ignored.
* @note Use this function when you have the intention that all vehicles
* should be iterated over.
* @param tile The location on the map
* @param data Arbitrary data passed to \a proc.
* @param proc The proc that determines whether a vehicle will be "found".
*/
void FindVehicleOnPos(TileIndex tile, void *data, VehicleFromPosProc *proc)
{
VehicleFromPos(tile, data, proc, false);
}
/**
* Checks whether a vehicle is on a specific location. It will call \a proc for
* vehicles until it returns non-NULL.
* @note Use #FindVehicleOnPos when you have the intention that all vehicles
* should be iterated over.
* @param tile The location on the map
* @param data Arbitrary data passed to \a proc.
* @param proc The \a proc that determines whether a vehicle will be "found".
* @return True if proc returned non-NULL.
*/
bool HasVehicleOnPos(TileIndex tile, void *data, VehicleFromPosProc *proc)
{
return VehicleFromPos(tile, data, proc, true) != NULL;
}
/**
* Callback that returns 'real' vehicles lower or at height \c *(int*)data .
* @param v Vehicle to examine.
* @param data Pointer to height data.
* @return \a v if conditions are met, else \c NULL.
*/
static Vehicle *EnsureNoVehicleProcZ(Vehicle *v, void *data)
{
int z = *(int*)data;
if (v->type == VEH_DISASTER || (v->type == VEH_AIRCRAFT && v->subtype == AIR_SHADOW)) return NULL;
if (v->z_pos > z) return NULL;
return v;
}
/**
* Ensure there is no vehicle at the ground at the given position.
* @param tile Position to examine.
* @return Succeeded command (ground is free) or failed command (a vehicle is found).
*/
CommandCost EnsureNoVehicleOnGround(TileIndex tile)
{
int z = GetTileMaxPixelZ(tile);
/* Value v is not safe in MP games, however, it is used to generate a local
* error message only (which may be different for different machines).
* Such a message does not affect MP synchronisation.
*/
Vehicle *v = VehicleFromPos(tile, &z, &EnsureNoVehicleProcZ, true);
if (v != NULL) return_cmd_error(STR_ERROR_TRAIN_IN_THE_WAY + v->type);
return CommandCost();
}
/** Procedure called for every vehicle found in tunnel/bridge in the hash map */
static Vehicle *GetVehicleTunnelBridgeProc(Vehicle *v, void *data)
{
if (v->type != VEH_TRAIN && v->type != VEH_ROAD && v->type != VEH_SHIP) return NULL;
if (v == (const Vehicle *)data) return NULL;
return v;
}
/**
* Finds vehicle in tunnel / bridge
* @param tile first end
* @param endtile second end
* @param ignore Ignore this vehicle when searching
* @return Succeeded command (if tunnel/bridge is free) or failed command (if a vehicle is using the tunnel/bridge).
*/
CommandCost TunnelBridgeIsFree(TileIndex tile, TileIndex endtile, const Vehicle *ignore)
{
/* Value v is not safe in MP games, however, it is used to generate a local
* error message only (which may be different for different machines).
* Such a message does not affect MP synchronisation.
*/
Vehicle *v = VehicleFromPos(tile, const_cast<Vehicle *>(ignore), &GetVehicleTunnelBridgeProc, true);
if (v == NULL) v = VehicleFromPos(endtile, const_cast<Vehicle *>(ignore), &GetVehicleTunnelBridgeProc, true);
if (v != NULL) return_cmd_error(STR_ERROR_TRAIN_IN_THE_WAY + v->type);
return CommandCost();
}
static Vehicle *EnsureNoTrainOnTrackProc(Vehicle *v, void *data)
{
TrackBits rail_bits = *(TrackBits *)data;
if (v->type != VEH_TRAIN) return NULL;
Train *t = Train::From(v);
if ((t->track != rail_bits) && !TracksOverlap(t->track | rail_bits)) return NULL;
return v;
}
/**
* Tests if a vehicle interacts with the specified track bits.
* All track bits interact except parallel #TRACK_BIT_HORZ or #TRACK_BIT_VERT.
*
* @param tile The tile.
* @param track_bits The track bits.
* @return \c true if no train that interacts, is found. \c false if a train is found.
*/
CommandCost EnsureNoTrainOnTrackBits(TileIndex tile, TrackBits track_bits)
{
/* Value v is not safe in MP games, however, it is used to generate a local
* error message only (which may be different for different machines).
* Such a message does not affect MP synchronisation.
*/
Vehicle *v = VehicleFromPos(tile, &track_bits, &EnsureNoTrainOnTrackProc, true);
if (v != NULL) return_cmd_error(STR_ERROR_TRAIN_IN_THE_WAY + v->type);
return CommandCost();
}
static void UpdateVehicleTileHash(Vehicle *v, bool remove)
{
Vehicle **old_hash = v->hash_tile_current;
Vehicle **new_hash;
if (remove) {
new_hash = NULL;
} else {
int x = GB(TileX(v->tile), HASH_RES, HASH_BITS);
int y = GB(TileY(v->tile), HASH_RES, HASH_BITS) << HASH_BITS;
new_hash = &_vehicle_tile_hash[(x + y) & TOTAL_HASH_MASK];
}
if (old_hash == new_hash) return;
/* Remove from the old position in the hash table */
if (old_hash != NULL) {
if (v->hash_tile_next != NULL) v->hash_tile_next->hash_tile_prev = v->hash_tile_prev;
*v->hash_tile_prev = v->hash_tile_next;
}
/* Insert vehicle at beginning of the new position in the hash table */
if (new_hash != NULL) {
v->hash_tile_next = *new_hash;
if (v->hash_tile_next != NULL) v->hash_tile_next->hash_tile_prev = &v->hash_tile_next;
v->hash_tile_prev = new_hash;
*new_hash = v;
}
/* Remember current hash position */
v->hash_tile_current = new_hash;
}
static Vehicle *_vehicle_viewport_hash[1 << (GEN_HASHX_BITS + GEN_HASHY_BITS)];
static void UpdateVehicleViewportHash(Vehicle *v, int x, int y)
{
Vehicle **old_hash, **new_hash;
int old_x = v->coord.left;
int old_y = v->coord.top;
new_hash = (x == INVALID_COORD) ? NULL : &_vehicle_viewport_hash[GEN_HASH(x, y)];
old_hash = (old_x == INVALID_COORD) ? NULL : &_vehicle_viewport_hash[GEN_HASH(old_x, old_y)];
if (old_hash == new_hash) return;
/* remove from hash table? */
if (old_hash != NULL) {
if (v->hash_viewport_next != NULL) v->hash_viewport_next->hash_viewport_prev = v->hash_viewport_prev;
*v->hash_viewport_prev = v->hash_viewport_next;
}
/* insert into hash table? */
if (new_hash != NULL) {
v->hash_viewport_next = *new_hash;
if (v->hash_viewport_next != NULL) v->hash_viewport_next->hash_viewport_prev = &v->hash_viewport_next;
v->hash_viewport_prev = new_hash;
*new_hash = v;
}
}
void ResetVehicleHash()
{
Vehicle *v;
FOR_ALL_VEHICLES(v) { v->hash_tile_current = NULL; }
memset(_vehicle_viewport_hash, 0, sizeof(_vehicle_viewport_hash));
memset(_vehicle_tile_hash, 0, sizeof(_vehicle_tile_hash));
}
void ResetVehicleColourMap()
{
Vehicle *v;
FOR_ALL_VEHICLES(v) { v->colourmap = PAL_NONE; }
}
/**
* List of vehicles that should check for autoreplace this tick.
* Mapping of vehicle -> leave depot immediately after autoreplace.
*/
typedef SmallMap<Vehicle *, bool, 4> AutoreplaceMap;
static AutoreplaceMap _vehicles_to_autoreplace;
void InitializeVehicles()
{
_vehicles_to_autoreplace.Reset();
ResetVehicleHash();
}
uint CountVehiclesInChain(const Vehicle *v)
{
uint count = 0;
do count++; while ((v = v->Next()) != NULL);
return count;
}
/**
* Check if a vehicle is counted in num_engines in each company struct
* @return true if the vehicle is counted in num_engines
*/
bool Vehicle::IsEngineCountable() const
{
switch (this->type) {
case VEH_AIRCRAFT: return Aircraft::From(this)->IsNormalAircraft(); // don't count plane shadows and helicopter rotors
case VEH_TRAIN:
return !this->IsArticulatedPart() && // tenders and other articulated parts
!Train::From(this)->IsRearDualheaded(); // rear parts of multiheaded engines
case VEH_ROAD: return RoadVehicle::From(this)->IsFrontEngine();
case VEH_SHIP: return true;
default: return false; // Only count company buildable vehicles
}
}
/**
* Check whether Vehicle::engine_type has any meaning.
* @return true if the vehicle has a useable engine type.
*/
bool Vehicle::HasEngineType() const
{
switch (this->type) {
case VEH_AIRCRAFT: return Aircraft::From(this)->IsNormalAircraft();
case VEH_TRAIN:
case VEH_ROAD:
case VEH_SHIP: return true;
default: return false;
}
}
/**
* Retrieves the engine of the vehicle.
* @return Engine of the vehicle.
* @pre HasEngineType() == true
*/
const Engine *Vehicle::GetEngine() const
{
return Engine::Get(this->engine_type);
}
/**
* Retrieve the NewGRF the vehicle is tied to.
* This is the GRF providing the Action 3 for the engine type.
* @return NewGRF associated to the vehicle.
*/
const GRFFile *Vehicle::GetGRF() const
{
return this->GetEngine()->GetGRF();
}
/**
* Retrieve the GRF ID of the NewGRF the vehicle is tied to.
* This is the GRF providing the Action 3 for the engine type.
* @return GRF ID of the associated NewGRF.
*/
uint32 Vehicle::GetGRFID() const
{
return this->GetEngine()->GetGRFID();
}
/**
* Handle the pathfinding result, especially the lost status.
* If the vehicle is now lost and wasn't previously fire an
* event to the AIs and a news message to the user. If the
* vehicle is not lost anymore remove the news message.
* @param path_found Whether the vehicle has a path to its destination.
*/
void Vehicle::HandlePathfindingResult(bool path_found)
{
if (path_found) {
/* Route found, is the vehicle marked with "lost" flag? */
if (!HasBit(this->vehicle_flags, VF_PATHFINDER_LOST)) return;
/* Clear the flag as the PF's problem was solved. */
ClrBit(this->vehicle_flags, VF_PATHFINDER_LOST);
/* Delete the news item. */
DeleteVehicleNews(this->index, STR_NEWS_VEHICLE_IS_LOST);
return;
}
/* Were we already lost? */
if (HasBit(this->vehicle_flags, VF_PATHFINDER_LOST)) return;
/* It is first time the problem occurred, set the "lost" flag. */
SetBit(this->vehicle_flags, VF_PATHFINDER_LOST);
/* Notify user about the event. */
AI::NewEvent(this->owner, new ScriptEventVehicleLost(this->index));
if (_settings_client.gui.lost_vehicle_warn && this->owner == _local_company) {
SetDParam(0, this->index);
AddVehicleAdviceNewsItem(STR_NEWS_VEHICLE_IS_LOST, this->index);
}
}
/** Destroy all stuff that (still) needs the virtual functions to work properly */
void Vehicle::PreDestructor()
{
if (CleaningPool()) return;
if (Station::IsValidID(this->last_station_visited)) {
Station *st = Station::Get(this->last_station_visited);
st->loading_vehicles.remove(this);
HideFillingPercent(&this->fill_percent_te_id);
this->CancelReservation(INVALID_STATION, st);
delete this->cargo_payment;
assert(this->cargo_payment == NULL); // cleared by ~CargoPayment
}
if (this->IsEngineCountable()) {
GroupStatistics::CountEngine(this, -1);
if (this->IsPrimaryVehicle()) GroupStatistics::CountVehicle(this, -1);
GroupStatistics::UpdateAutoreplace(this->owner);
if (this->owner == _local_company) InvalidateAutoreplaceWindow(this->engine_type, this->group_id);
DeleteGroupHighlightOfVehicle(this);
}
if (this->type == VEH_AIRCRAFT && this->IsPrimaryVehicle()) {
Aircraft *a = Aircraft::From(this);
Station *st = GetTargetAirportIfValid(a);
if (st != NULL) {
const AirportFTA *layout = st->airport.GetFTA()->layout;
CLRBITS(st->airport.flags, layout[a->previous_pos].block | layout[a->pos].block);
}
}
if (this->type == VEH_ROAD && this->IsPrimaryVehicle()) {
RoadVehicle *v = RoadVehicle::From(this);
if (!(v->vehstatus & VS_CRASHED) && IsInsideMM(v->state, RVSB_IN_DT_ROAD_STOP, RVSB_IN_DT_ROAD_STOP_END)) {
/* Leave the drive through roadstop, when you have not already left it. */
RoadStop::GetByTile(v->tile, GetRoadStopType(v->tile))->Leave(v);
}
}
if (this->Previous() == NULL) {
InvalidateWindowData(WC_VEHICLE_DEPOT, this->tile);
}
if (this->IsPrimaryVehicle()) {
DeleteWindowById(WC_VEHICLE_VIEW, this->index);
DeleteWindowById(WC_VEHICLE_ORDERS, this->index);
DeleteWindowById(WC_VEHICLE_REFIT, this->index);
DeleteWindowById(WC_VEHICLE_DETAILS, this->index);
DeleteWindowById(WC_VEHICLE_TIMETABLE, this->index);
SetWindowDirty(WC_COMPANY, this->owner);
OrderBackup::ClearVehicle(this);
}
InvalidateWindowClassesData(GetWindowClassForVehicleType(this->type), 0);
this->cargo.Truncate();
DeleteVehicleOrders(this);
DeleteDepotHighlightOfVehicle(this);
extern void StopGlobalFollowVehicle(const Vehicle *v);
StopGlobalFollowVehicle(this);
ReleaseDisastersTargetingVehicle(this->index);
}
Vehicle::~Vehicle()
{
if (CleaningPool()) {
this->cargo.OnCleanPool();
return;
}
/* sometimes, eg. for disaster vehicles, when company bankrupts, when removing crashed/flooded vehicles,
* it may happen that vehicle chain is deleted when visible */
if (!(this->vehstatus & VS_HIDDEN)) this->MarkAllViewportsDirty();
Vehicle *v = this->Next();
this->SetNext(NULL);
delete v;
UpdateVehicleTileHash(this, true);
UpdateVehicleViewportHash(this, INVALID_COORD, 0);
DeleteVehicleNews(this->index, INVALID_STRING_ID);
DeleteNewGRFInspectWindow(GetGrfSpecFeature(this->type), this->index);
}
/**
* Adds a vehicle to the list of vehicles that visited a depot this tick
* @param *v vehicle to add
*/
void VehicleEnteredDepotThisTick(Vehicle *v)
{
/* Vehicle should stop in the depot if it was in 'stopping' state */
_vehicles_to_autoreplace[v] = !(v->vehstatus & VS_STOPPED);
/* We ALWAYS set the stopped state. Even when the vehicle does not plan on
* stopping in the depot, so we stop it to ensure that it will not reserve
* the path out of the depot before we might autoreplace it to a different
* engine. The new engine would not own the reserved path we store that we
* stopped the vehicle, so autoreplace can start it again */
v->vehstatus |= VS_STOPPED;
}
/**
* Increases the day counter for all vehicles and calls 1-day and 32-day handlers.
* Each tick, it processes vehicles with "index % DAY_TICKS == _date_fract",
* so each day, all vehicles are processes in DAY_TICKS steps.
*/
static void RunVehicleDayProc()
{
if (_game_mode != GM_NORMAL) return;
/* Run the day_proc for every DAY_TICKS vehicle starting at _date_fract. */
for (size_t i = _date_fract; i < Vehicle::GetPoolSize(); i += DAY_TICKS) {
Vehicle *v = Vehicle::Get(i);
if (v == NULL) continue;
/* Call the 32-day callback if needed */
if ((v->day_counter & 0x1F) == 0 && v->HasEngineType()) {
uint16 callback = GetVehicleCallback(CBID_VEHICLE_32DAY_CALLBACK, 0, 0, v->engine_type, v);
if (callback != CALLBACK_FAILED) {
if (HasBit(callback, 0)) {
TriggerVehicle(v, VEHICLE_TRIGGER_CALLBACK_32); // Trigger vehicle trigger 10
}
/* After a vehicle trigger, the graphics and properties of the vehicle could change.
* Note: MarkDirty also invalidates the palette, which is the meaning of bit 1. So, nothing special there. */
if (callback != 0) v->First()->MarkDirty();
if (callback & ~3) ErrorUnknownCallbackResult(v->GetGRFID(), CBID_VEHICLE_32DAY_CALLBACK, callback);
}
}
/* This is called once per day for each vehicle, but not in the first tick of the day */
v->OnNewDay();
}
}
void CallVehicleTicks()
{
_vehicles_to_autoreplace.Clear();
RunVehicleDayProc();
Station *st;
FOR_ALL_STATIONS(st) LoadUnloadStation(st);
Vehicle *v;
FOR_ALL_VEHICLES(v) {
/* Vehicle could be deleted in this tick */
if (!v->Tick()) {
assert(Vehicle::Get(vehicle_index) == NULL);
continue;
}
assert(Vehicle::Get(vehicle_index) == v);
switch (v->type) {
default: break;
case VEH_TRAIN:
case VEH_ROAD:
case VEH_AIRCRAFT:
case VEH_SHIP: {
Vehicle *front = v->First();
if (v->vcache.cached_cargo_age_period != 0) {
v->cargo_age_counter = min(v->cargo_age_counter, v->vcache.cached_cargo_age_period);
if (--v->cargo_age_counter == 0) {
v->cargo.AgeCargo();
v->cargo_age_counter = v->vcache.cached_cargo_age_period;
}
}
/* Do not play any sound when crashed */
if (front->vehstatus & VS_CRASHED) continue;
/* Do not play any sound when in depot or tunnel */
if (v->vehstatus & VS_HIDDEN) continue;
/* Do not play any sound when stopped */
if ((front->vehstatus & VS_STOPPED) && (front->type != VEH_TRAIN || front->cur_speed == 0)) continue;
/* Check vehicle type specifics */
switch (v->type) {
case VEH_TRAIN:
if (Train::From(v)->IsWagon()) continue;
break;
case VEH_ROAD:
if (!RoadVehicle::From(v)->IsFrontEngine()) continue;
break;
case VEH_AIRCRAFT:
if (!Aircraft::From(v)->IsNormalAircraft()) continue;
break;