/
rail_cmd.cpp
3121 lines (2670 loc) · 113 KB
/
rail_cmd.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 rail_cmd.cpp Handling of rail tiles. */
#include "stdafx.h"
#include "cmd_helper.h"
#include "viewport_func.h"
#include "command_func.h"
#include "depot_base.h"
#include "pathfinder/yapf/yapf_cache.h"
#include "newgrf_debug.h"
#include "newgrf_railtype.h"
#include "train.h"
#include "autoslope.h"
#include "water.h"
#include "tunnelbridge_map.h"
#include "vehicle_func.h"
#include "sound_func.h"
#include "tunnelbridge.h"
#include "elrail_func.h"
#include "town.h"
#include "pbs.h"
#include "company_base.h"
#include "core/backup_type.hpp"
#include "date_func.h"
#include "strings_func.h"
#include "company_gui.h"
#include "object_map.h"
#include "table/strings.h"
#include "table/railtypes.h"
#include "table/track_land.h"
#include "safeguards.h"
/** Helper type for lists/vectors of trains */
typedef std::vector<Train *> TrainList;
RailtypeInfo _railtypes[RAILTYPE_END];
std::vector<RailType> _sorted_railtypes;
RailTypes _railtypes_hidden_mask;
/** Enum holding the signal offset in the sprite sheet according to the side it is representing. */
enum SignalOffsets {
SIGNAL_TO_SOUTHWEST,
SIGNAL_TO_NORTHEAST,
SIGNAL_TO_SOUTHEAST,
SIGNAL_TO_NORTHWEST,
SIGNAL_TO_EAST,
SIGNAL_TO_WEST,
SIGNAL_TO_SOUTH,
SIGNAL_TO_NORTH,
};
/**
* Reset all rail type information to its default values.
*/
void ResetRailTypes()
{
assert_compile(lengthof(_original_railtypes) <= lengthof(_railtypes));
uint i = 0;
for (; i < lengthof(_original_railtypes); i++) _railtypes[i] = _original_railtypes[i];
static const RailtypeInfo empty_railtype = {
{0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,{}},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0},
0, RAILTYPES_NONE, RAILTYPES_NONE, 0, 0, 0, RTFB_NONE, 0, 0, 0, 0, 0,
RailTypeLabelList(), 0, 0, RAILTYPES_NONE, RAILTYPES_NONE, 0,
{}, {} };
for (; i < lengthof(_railtypes); i++) _railtypes[i] = empty_railtype;
_railtypes_hidden_mask = RAILTYPES_NONE;
}
void ResolveRailTypeGUISprites(RailtypeInfo *rti)
{
SpriteID cursors_base = GetCustomRailSprite(rti, INVALID_TILE, RTSG_CURSORS);
if (cursors_base != 0) {
rti->gui_sprites.build_ns_rail = cursors_base + 0;
rti->gui_sprites.build_x_rail = cursors_base + 1;
rti->gui_sprites.build_ew_rail = cursors_base + 2;
rti->gui_sprites.build_y_rail = cursors_base + 3;
rti->gui_sprites.auto_rail = cursors_base + 4;
rti->gui_sprites.build_depot = cursors_base + 5;
rti->gui_sprites.build_tunnel = cursors_base + 6;
rti->gui_sprites.convert_rail = cursors_base + 7;
rti->cursor.rail_ns = cursors_base + 8;
rti->cursor.rail_swne = cursors_base + 9;
rti->cursor.rail_ew = cursors_base + 10;
rti->cursor.rail_nwse = cursors_base + 11;
rti->cursor.autorail = cursors_base + 12;
rti->cursor.depot = cursors_base + 13;
rti->cursor.tunnel = cursors_base + 14;
rti->cursor.convert = cursors_base + 15;
}
/* Array of default GUI signal sprite numbers. */
const SpriteID _signal_lookup[2][SIGTYPE_END] = {
{SPR_IMG_SIGNAL_ELECTRIC_NORM, SPR_IMG_SIGNAL_ELECTRIC_ENTRY, SPR_IMG_SIGNAL_ELECTRIC_EXIT,
SPR_IMG_SIGNAL_ELECTRIC_COMBO, SPR_IMG_SIGNAL_ELECTRIC_PBS, SPR_IMG_SIGNAL_ELECTRIC_PBS_OWAY},
{SPR_IMG_SIGNAL_SEMAPHORE_NORM, SPR_IMG_SIGNAL_SEMAPHORE_ENTRY, SPR_IMG_SIGNAL_SEMAPHORE_EXIT,
SPR_IMG_SIGNAL_SEMAPHORE_COMBO, SPR_IMG_SIGNAL_SEMAPHORE_PBS, SPR_IMG_SIGNAL_SEMAPHORE_PBS_OWAY},
};
for (SignalType type = SIGTYPE_NORMAL; type < SIGTYPE_END; type = (SignalType)(type + 1)) {
for (SignalVariant var = SIG_ELECTRIC; var <= SIG_SEMAPHORE; var = (SignalVariant)(var + 1)) {
SpriteID red = GetCustomSignalSprite(rti, INVALID_TILE, type, var, SIGNAL_STATE_RED, true);
SpriteID green = GetCustomSignalSprite(rti, INVALID_TILE, type, var, SIGNAL_STATE_GREEN, true);
rti->gui_sprites.signals[type][var][0] = (red != 0) ? red + SIGNAL_TO_SOUTH : _signal_lookup[var][type];
rti->gui_sprites.signals[type][var][1] = (green != 0) ? green + SIGNAL_TO_SOUTH : _signal_lookup[var][type] + 1;
}
}
}
/**
* Compare railtypes based on their sorting order.
* @param first The railtype to compare to.
* @param second The railtype to compare.
* @return True iff the first should be sorted before the second.
*/
static bool CompareRailTypes(const RailType &first, const RailType &second)
{
return GetRailTypeInfo(first)->sorting_order < GetRailTypeInfo(second)->sorting_order;
}
/**
* Resolve sprites of custom rail types
*/
void InitRailTypes()
{
for (RailType rt = RAILTYPE_BEGIN; rt != RAILTYPE_END; rt++) {
RailtypeInfo *rti = &_railtypes[rt];
ResolveRailTypeGUISprites(rti);
if (HasBit(rti->flags, RTF_HIDDEN)) SetBit(_railtypes_hidden_mask, rt);
}
_sorted_railtypes.clear();
for (RailType rt = RAILTYPE_BEGIN; rt != RAILTYPE_END; rt++) {
if (_railtypes[rt].label != 0 && !HasBit(_railtypes_hidden_mask, rt)) {
_sorted_railtypes.push_back(rt);
}
}
std::sort(_sorted_railtypes.begin(), _sorted_railtypes.end(), CompareRailTypes);
}
/**
* Allocate a new rail type label
*/
RailType AllocateRailType(RailTypeLabel label)
{
for (RailType rt = RAILTYPE_BEGIN; rt != RAILTYPE_END; rt++) {
RailtypeInfo *rti = &_railtypes[rt];
if (rti->label == 0) {
/* Set up new rail type */
*rti = _original_railtypes[RAILTYPE_RAIL];
rti->label = label;
rti->alternate_labels.clear();
/* Make us compatible with ourself. */
rti->powered_railtypes = (RailTypes)(1LL << rt);
rti->compatible_railtypes = (RailTypes)(1LL << rt);
/* We also introduce ourself. */
rti->introduces_railtypes = (RailTypes)(1LL << rt);
/* Default sort order; order of allocation, but with some
* offsets so it's easier for NewGRF to pick a spot without
* changing the order of other (original) rail types.
* The << is so you can place other railtypes in between the
* other railtypes, the 7 is to be able to place something
* before the first (default) rail type. */
rti->sorting_order = rt << 4 | 7;
return rt;
}
}
return INVALID_RAILTYPE;
}
static const byte _track_sloped_sprites[14] = {
14, 15, 22, 13,
0, 21, 17, 12,
23, 0, 18, 20,
19, 16
};
/* 4
* ---------
* |\ /|
* | \ 1/ |
* | \ / |
* | \ / |
* 16| \ |32
* | / \2 |
* | / \ |
* | / \ |
* |/ \|
* ---------
* 8
*/
/* MAP2 byte: abcd???? => Signal On? Same coding as map3lo
* MAP3LO byte: abcd???? => Signal Exists?
* a and b are for diagonals, upper and left,
* one for each direction. (ie a == NE->SW, b ==
* SW->NE, or v.v., I don't know. b and c are
* similar for lower and right.
* MAP2 byte: ????abcd => Type of ground.
* MAP3LO byte: ????abcd => Type of rail.
* MAP5: 00abcdef => rail
* 01abcdef => rail w/ signals
* 10uuuuuu => unused
* 11uuuudd => rail depot
*/
/**
* Tests if a vehicle interacts with the specified track.
* All track bits interact except parallel #TRACK_BIT_HORZ or #TRACK_BIT_VERT.
*
* @param tile The tile.
* @param track The track.
* @return Succeeded command (no train found), or a failed command (a train was found).
*/
static CommandCost EnsureNoTrainOnTrack(TileIndex tile, Track track)
{
TrackBits rail_bits = TrackToTrackBits(track);
return EnsureNoTrainOnTrackBits(tile, rail_bits);
}
/**
* Check that the new track bits may be built.
* @param tile %Tile to build on.
* @param to_build New track bits.
* @param flags Flags of the operation.
* @return Succeeded or failed command.
*/
static CommandCost CheckTrackCombination(TileIndex tile, TrackBits to_build, uint flags)
{
if (!IsPlainRail(tile)) return_cmd_error(STR_ERROR_IMPOSSIBLE_TRACK_COMBINATION);
/* So, we have a tile with tracks on it (and possibly signals). Let's see
* what tracks first */
TrackBits current = GetTrackBits(tile); // The current track layout.
TrackBits future = current | to_build; // The track layout we want to build.
/* Are we really building something new? */
if (current == future) {
/* Nothing new is being built */
return_cmd_error(STR_ERROR_ALREADY_BUILT);
}
/* Let's see if we may build this */
if ((flags & DC_NO_RAIL_OVERLAP) || HasSignals(tile)) {
/* If we are not allowed to overlap (flag is on for ai companies or we have
* signals on the tile), check that */
if (future != TRACK_BIT_HORZ && future != TRACK_BIT_VERT) {
return_cmd_error((flags & DC_NO_RAIL_OVERLAP) ? STR_ERROR_IMPOSSIBLE_TRACK_COMBINATION : STR_ERROR_MUST_REMOVE_SIGNALS_FIRST);
}
}
/* Normally, we may overlap and any combination is valid */
return CommandCost();
}
/** Valid TrackBits on a specific (non-steep)-slope without foundation */
static const TrackBits _valid_tracks_without_foundation[15] = {
TRACK_BIT_ALL,
TRACK_BIT_RIGHT,
TRACK_BIT_UPPER,
TRACK_BIT_X,
TRACK_BIT_LEFT,
TRACK_BIT_NONE,
TRACK_BIT_Y,
TRACK_BIT_LOWER,
TRACK_BIT_LOWER,
TRACK_BIT_Y,
TRACK_BIT_NONE,
TRACK_BIT_LEFT,
TRACK_BIT_X,
TRACK_BIT_UPPER,
TRACK_BIT_RIGHT,
};
/** Valid TrackBits on a specific (non-steep)-slope with leveled foundation */
static const TrackBits _valid_tracks_on_leveled_foundation[15] = {
TRACK_BIT_NONE,
TRACK_BIT_LEFT,
TRACK_BIT_LOWER,
TRACK_BIT_Y | TRACK_BIT_LOWER | TRACK_BIT_LEFT,
TRACK_BIT_RIGHT,
TRACK_BIT_ALL,
TRACK_BIT_X | TRACK_BIT_LOWER | TRACK_BIT_RIGHT,
TRACK_BIT_ALL,
TRACK_BIT_UPPER,
TRACK_BIT_X | TRACK_BIT_UPPER | TRACK_BIT_LEFT,
TRACK_BIT_ALL,
TRACK_BIT_ALL,
TRACK_BIT_Y | TRACK_BIT_UPPER | TRACK_BIT_RIGHT,
TRACK_BIT_ALL,
TRACK_BIT_ALL
};
/**
* Checks if a track combination is valid on a specific slope and returns the needed foundation.
*
* @param tileh Tile slope.
* @param bits Trackbits.
* @return Needed foundation or FOUNDATION_INVALID if track/slope combination is not allowed.
*/
Foundation GetRailFoundation(Slope tileh, TrackBits bits)
{
if (bits == TRACK_BIT_NONE) return FOUNDATION_NONE;
if (IsSteepSlope(tileh)) {
/* Test for inclined foundations */
if (bits == TRACK_BIT_X) return FOUNDATION_INCLINED_X;
if (bits == TRACK_BIT_Y) return FOUNDATION_INCLINED_Y;
/* Get higher track */
Corner highest_corner = GetHighestSlopeCorner(tileh);
TrackBits higher_track = CornerToTrackBits(highest_corner);
/* Only higher track? */
if (bits == higher_track) return HalftileFoundation(highest_corner);
/* Overlap with higher track? */
if (TracksOverlap(bits | higher_track)) return FOUNDATION_INVALID;
/* either lower track or both higher and lower track */
return ((bits & higher_track) != 0 ? FOUNDATION_STEEP_BOTH : FOUNDATION_STEEP_LOWER);
} else {
if ((~_valid_tracks_without_foundation[tileh] & bits) == 0) return FOUNDATION_NONE;
bool valid_on_leveled = ((~_valid_tracks_on_leveled_foundation[tileh] & bits) == 0);
Corner track_corner;
switch (bits) {
case TRACK_BIT_LEFT: track_corner = CORNER_W; break;
case TRACK_BIT_LOWER: track_corner = CORNER_S; break;
case TRACK_BIT_RIGHT: track_corner = CORNER_E; break;
case TRACK_BIT_UPPER: track_corner = CORNER_N; break;
case TRACK_BIT_HORZ:
if (tileh == SLOPE_N) return HalftileFoundation(CORNER_N);
if (tileh == SLOPE_S) return HalftileFoundation(CORNER_S);
return (valid_on_leveled ? FOUNDATION_LEVELED : FOUNDATION_INVALID);
case TRACK_BIT_VERT:
if (tileh == SLOPE_W) return HalftileFoundation(CORNER_W);
if (tileh == SLOPE_E) return HalftileFoundation(CORNER_E);
return (valid_on_leveled ? FOUNDATION_LEVELED : FOUNDATION_INVALID);
case TRACK_BIT_X:
if (IsSlopeWithOneCornerRaised(tileh)) return FOUNDATION_INCLINED_X;
return (valid_on_leveled ? FOUNDATION_LEVELED : FOUNDATION_INVALID);
case TRACK_BIT_Y:
if (IsSlopeWithOneCornerRaised(tileh)) return FOUNDATION_INCLINED_Y;
return (valid_on_leveled ? FOUNDATION_LEVELED : FOUNDATION_INVALID);
default:
return (valid_on_leveled ? FOUNDATION_LEVELED : FOUNDATION_INVALID);
}
/* Single diagonal track */
/* Track must be at least valid on leveled foundation */
if (!valid_on_leveled) return FOUNDATION_INVALID;
/* If slope has three raised corners, build leveled foundation */
if (IsSlopeWithThreeCornersRaised(tileh)) return FOUNDATION_LEVELED;
/* If neighboured corners of track_corner are lowered, build halftile foundation */
if ((tileh & SlopeWithThreeCornersRaised(OppositeCorner(track_corner))) == SlopeWithOneCornerRaised(track_corner)) return HalftileFoundation(track_corner);
/* else special anti-zig-zag foundation */
return SpecialRailFoundation(track_corner);
}
}
/**
* Tests if a track can be build on a tile.
*
* @param tileh Tile slope.
* @param rail_bits Tracks to build.
* @param existing Tracks already built.
* @param tile Tile (used for water test)
* @return Error message or cost for foundation building.
*/
static CommandCost CheckRailSlope(Slope tileh, TrackBits rail_bits, TrackBits existing, TileIndex tile)
{
/* don't allow building on the lower side of a coast */
if (GetFloodingBehaviour(tile) != FLOOD_NONE) {
if (!IsSteepSlope(tileh) && ((~_valid_tracks_on_leveled_foundation[tileh] & (rail_bits | existing)) != 0)) return_cmd_error(STR_ERROR_CAN_T_BUILD_ON_WATER);
}
Foundation f_new = GetRailFoundation(tileh, rail_bits | existing);
/* check track/slope combination */
if ((f_new == FOUNDATION_INVALID) ||
((f_new != FOUNDATION_NONE) && (!_settings_game.construction.build_on_slopes))) {
return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
}
Foundation f_old = GetRailFoundation(tileh, existing);
return CommandCost(EXPENSES_CONSTRUCTION, f_new != f_old ? _price[PR_BUILD_FOUNDATION] : (Money)0);
}
/* Validate functions for rail building */
static inline bool ValParamTrackOrientation(Track track)
{
return IsValidTrack(track);
}
/**
* Build a single piece of rail
* @param tile tile to build on
* @param flags operation to perform
* @param p1 railtype of being built piece (normal, mono, maglev)
* @param p2 rail track to build
* @param text unused
* @return the cost of this operation or an error
*/
CommandCost CmdBuildSingleRail(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
RailType railtype = Extract<RailType, 0, 6>(p1);
Track track = Extract<Track, 0, 3>(p2);
CommandCost cost(EXPENSES_CONSTRUCTION);
if (!ValParamRailtype(railtype) || !ValParamTrackOrientation(track)) return CMD_ERROR;
Slope tileh = GetTileSlope(tile);
TrackBits trackbit = TrackToTrackBits(track);
switch (GetTileType(tile)) {
case MP_RAILWAY: {
CommandCost ret = CheckTileOwnership(tile);
if (ret.Failed()) return ret;
if (!IsPlainRail(tile)) return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR); // just get appropriate error message
if (!IsCompatibleRail(GetRailType(tile), railtype)) return_cmd_error(STR_ERROR_IMPOSSIBLE_TRACK_COMBINATION);
ret = CheckTrackCombination(tile, trackbit, flags);
if (ret.Succeeded()) ret = EnsureNoTrainOnTrack(tile, track);
if (ret.Failed()) return ret;
ret = CheckRailSlope(tileh, trackbit, GetTrackBits(tile), tile);
if (ret.Failed()) return ret;
cost.AddCost(ret);
/* If the rail types don't match, try to convert only if engines of
* the new rail type are not powered on the present rail type and engines of
* the present rail type are powered on the new rail type. */
if (GetRailType(tile) != railtype && !HasPowerOnRail(railtype, GetRailType(tile))) {
if (HasPowerOnRail(GetRailType(tile), railtype)) {
ret = DoCommand(tile, tile, railtype, flags, CMD_CONVERT_RAIL);
if (ret.Failed()) return ret;
cost.AddCost(ret);
} else {
return CMD_ERROR;
}
}
if (flags & DC_EXEC) {
SetRailGroundType(tile, RAIL_GROUND_BARREN);
TrackBits bits = GetTrackBits(tile);
SetTrackBits(tile, bits | trackbit);
/* Subtract old infrastructure count. */
uint pieces = CountBits(bits);
if (TracksOverlap(bits)) pieces *= pieces;
Company::Get(GetTileOwner(tile))->infrastructure.rail[GetRailType(tile)] -= pieces;
/* Add new infrastructure count. */
pieces = CountBits(bits | trackbit);
if (TracksOverlap(bits | trackbit)) pieces *= pieces;
Company::Get(GetTileOwner(tile))->infrastructure.rail[GetRailType(tile)] += pieces;
DirtyCompanyInfrastructureWindows(GetTileOwner(tile));
}
break;
}
case MP_ROAD: {
/* Level crossings may only be built on these slopes */
if (!HasBit(VALID_LEVEL_CROSSING_SLOPES, tileh)) return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
CommandCost ret = EnsureNoVehicleOnGround(tile);
if (ret.Failed()) return ret;
if (IsNormalRoad(tile)) {
if (HasRoadWorks(tile)) return_cmd_error(STR_ERROR_ROAD_WORKS_IN_PROGRESS);
if (GetDisallowedRoadDirections(tile) != DRD_NONE) return_cmd_error(STR_ERROR_CROSSING_ON_ONEWAY_ROAD);
if (RailNoLevelCrossings(railtype)) return_cmd_error(STR_ERROR_CROSSING_DISALLOWED_RAIL);
RoadType roadtype_road = GetRoadTypeRoad(tile);
RoadType roadtype_tram = GetRoadTypeTram(tile);
if (roadtype_road != INVALID_ROADTYPE && RoadNoLevelCrossing(roadtype_road)) return_cmd_error(STR_ERROR_CROSSING_DISALLOWED_ROAD);
if (roadtype_tram != INVALID_ROADTYPE && RoadNoLevelCrossing(roadtype_tram)) return_cmd_error(STR_ERROR_CROSSING_DISALLOWED_ROAD);
RoadBits road = GetRoadBits(tile, RTT_ROAD);
RoadBits tram = GetRoadBits(tile, RTT_TRAM);
if ((track == TRACK_X && ((road | tram) & ROAD_X) == 0) ||
(track == TRACK_Y && ((road | tram) & ROAD_Y) == 0)) {
Owner road_owner = GetRoadOwner(tile, RTT_ROAD);
Owner tram_owner = GetRoadOwner(tile, RTT_TRAM);
/* Disallow breaking end-of-line of someone else
* so trams can still reverse on this tile. */
if (Company::IsValidID(tram_owner) && HasExactlyOneBit(tram)) {
CommandCost ret = CheckOwnership(tram_owner);
if (ret.Failed()) return ret;
}
uint num_new_road_pieces = (road != ROAD_NONE) ? 2 - CountBits(road) : 0;
if (num_new_road_pieces > 0) {
cost.AddCost(num_new_road_pieces * RoadBuildCost(roadtype_road));
}
uint num_new_tram_pieces = (tram != ROAD_NONE) ? 2 - CountBits(tram) : 0;
if (num_new_tram_pieces > 0) {
cost.AddCost(num_new_tram_pieces * RoadBuildCost(roadtype_tram));
}
if (flags & DC_EXEC) {
MakeRoadCrossing(tile, road_owner, tram_owner, _current_company, (track == TRACK_X ? AXIS_Y : AXIS_X), railtype, roadtype_road, roadtype_tram, GetTownIndex(tile));
UpdateLevelCrossing(tile, false);
Company::Get(_current_company)->infrastructure.rail[railtype] += LEVELCROSSING_TRACKBIT_FACTOR;
DirtyCompanyInfrastructureWindows(_current_company);
if (num_new_road_pieces > 0 && Company::IsValidID(road_owner)) {
Company::Get(road_owner)->infrastructure.road[roadtype_road] += num_new_road_pieces;
DirtyCompanyInfrastructureWindows(road_owner);
}
if (num_new_tram_pieces > 0 && Company::IsValidID(tram_owner)) {
Company::Get(tram_owner)->infrastructure.road[roadtype_tram] += num_new_tram_pieces;
DirtyCompanyInfrastructureWindows(tram_owner);
}
}
break;
}
}
if (IsLevelCrossing(tile) && GetCrossingRailBits(tile) == trackbit) {
return_cmd_error(STR_ERROR_ALREADY_BUILT);
}
FALLTHROUGH;
}
default: {
/* Will there be flat water on the lower halftile? */
bool water_ground = IsTileType(tile, MP_WATER) && IsSlopeWithOneCornerRaised(tileh);
bool docking = IsPossibleDockingTile(tile) && IsDockingTile(tile);
CommandCost ret = CheckRailSlope(tileh, trackbit, TRACK_BIT_NONE, tile);
if (ret.Failed()) return ret;
cost.AddCost(ret);
ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
if (ret.Failed()) return ret;
cost.AddCost(ret);
if (water_ground) {
cost.AddCost(-_price[PR_CLEAR_WATER]);
cost.AddCost(_price[PR_CLEAR_ROUGH]);
}
if (flags & DC_EXEC) {
MakeRailNormal(tile, _current_company, trackbit, railtype);
if (water_ground) {
SetRailGroundType(tile, RAIL_GROUND_WATER);
SetDockingTile(tile, docking);
}
Company::Get(_current_company)->infrastructure.rail[railtype]++;
DirtyCompanyInfrastructureWindows(_current_company);
}
break;
}
}
if (flags & DC_EXEC) {
MarkTileDirtyByTile(tile);
AddTrackToSignalBuffer(tile, track, _current_company);
YapfNotifyTrackLayoutChange(tile, track);
}
cost.AddCost(RailBuildCost(railtype));
return cost;
}
/**
* Remove a single piece of track
* @param tile tile to remove track from
* @param flags operation to perform
* @param p1 unused
* @param p2 rail orientation
* @param text unused
* @return the cost of this operation or an error
*/
CommandCost CmdRemoveSingleRail(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
Track track = Extract<Track, 0, 3>(p2);
CommandCost cost(EXPENSES_CONSTRUCTION);
bool crossing = false;
if (!ValParamTrackOrientation(track)) return CMD_ERROR;
TrackBits trackbit = TrackToTrackBits(track);
/* Need to read tile owner now because it may change when the rail is removed
* Also, in case of floods, _current_company != owner
* There may be invalid tiletype even in exec run (when removing long track),
* so do not call GetTileOwner(tile) in any case here */
Owner owner = INVALID_OWNER;
Train *v = nullptr;
switch (GetTileType(tile)) {
case MP_ROAD: {
if (!IsLevelCrossing(tile) || GetCrossingRailBits(tile) != trackbit) return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK);
if (_current_company != OWNER_WATER) {
CommandCost ret = CheckTileOwnership(tile);
if (ret.Failed()) return ret;
}
if (!(flags & DC_BANKRUPT)) {
CommandCost ret = EnsureNoVehicleOnGround(tile);
if (ret.Failed()) return ret;
}
cost.AddCost(RailClearCost(GetRailType(tile)));
if (flags & DC_EXEC) {
if (HasReservedTracks(tile, trackbit)) {
v = GetTrainForReservation(tile, track);
if (v != nullptr) FreeTrainTrackReservation(v);
}
owner = GetTileOwner(tile);
Company::Get(owner)->infrastructure.rail[GetRailType(tile)] -= LEVELCROSSING_TRACKBIT_FACTOR;
DirtyCompanyInfrastructureWindows(owner);
MakeRoadNormal(tile, GetCrossingRoadBits(tile), GetRoadTypeRoad(tile), GetRoadTypeTram(tile), GetTownIndex(tile), GetRoadOwner(tile, RTT_ROAD), GetRoadOwner(tile, RTT_TRAM));
DeleteNewGRFInspectWindow(GSF_RAILTYPES, tile);
}
break;
}
case MP_RAILWAY: {
TrackBits present;
/* There are no rails present at depots. */
if (!IsPlainRail(tile)) return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK);
if (_current_company != OWNER_WATER) {
CommandCost ret = CheckTileOwnership(tile);
if (ret.Failed()) return ret;
}
CommandCost ret = EnsureNoTrainOnTrack(tile, track);
if (ret.Failed()) return ret;
present = GetTrackBits(tile);
if ((present & trackbit) == 0) return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK);
if (present == (TRACK_BIT_X | TRACK_BIT_Y)) crossing = true;
cost.AddCost(RailClearCost(GetRailType(tile)));
/* Charge extra to remove signals on the track, if they are there */
if (HasSignalOnTrack(tile, track)) {
cost.AddCost(DoCommand(tile, track, 0, flags, CMD_REMOVE_SIGNALS));
}
if (flags & DC_EXEC) {
if (HasReservedTracks(tile, trackbit)) {
v = GetTrainForReservation(tile, track);
if (v != nullptr) FreeTrainTrackReservation(v);
}
owner = GetTileOwner(tile);
/* Subtract old infrastructure count. */
uint pieces = CountBits(present);
if (TracksOverlap(present)) pieces *= pieces;
Company::Get(owner)->infrastructure.rail[GetRailType(tile)] -= pieces;
/* Add new infrastructure count. */
present ^= trackbit;
pieces = CountBits(present);
if (TracksOverlap(present)) pieces *= pieces;
Company::Get(owner)->infrastructure.rail[GetRailType(tile)] += pieces;
DirtyCompanyInfrastructureWindows(owner);
if (present == 0) {
Slope tileh = GetTileSlope(tile);
/* If there is flat water on the lower halftile, convert the tile to shore so the water remains */
if (GetRailGroundType(tile) == RAIL_GROUND_WATER && IsSlopeWithOneCornerRaised(tileh)) {
bool docking = IsDockingTile(tile);
MakeShore(tile);
SetDockingTile(tile, docking);
} else {
DoClearSquare(tile);
}
DeleteNewGRFInspectWindow(GSF_RAILTYPES, tile);
} else {
SetTrackBits(tile, present);
SetTrackReservation(tile, GetRailReservationTrackBits(tile) & present);
}
}
break;
}
default: return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK);
}
if (flags & DC_EXEC) {
/* if we got that far, 'owner' variable is set correctly */
assert(Company::IsValidID(owner));
MarkTileDirtyByTile(tile);
if (crossing) {
/* crossing is set when only TRACK_BIT_X and TRACK_BIT_Y are set. As we
* are removing one of these pieces, we'll need to update signals for
* both directions explicitly, as after the track is removed it won't
* 'connect' with the other piece. */
AddTrackToSignalBuffer(tile, TRACK_X, owner);
AddTrackToSignalBuffer(tile, TRACK_Y, owner);
YapfNotifyTrackLayoutChange(tile, TRACK_X);
YapfNotifyTrackLayoutChange(tile, TRACK_Y);
} else {
AddTrackToSignalBuffer(tile, track, owner);
YapfNotifyTrackLayoutChange(tile, track);
}
if (v != nullptr) TryPathReserve(v, true);
}
return cost;
}
/**
* Called from water_cmd if a non-flat rail-tile gets flooded and should be converted to shore.
* The function floods the lower halftile, if the tile has a halftile foundation.
*
* @param t The tile to flood.
* @return true if something was flooded.
*/
bool FloodHalftile(TileIndex t)
{
assert(IsPlainRailTile(t));
bool flooded = false;
if (GetRailGroundType(t) == RAIL_GROUND_WATER) return flooded;
Slope tileh = GetTileSlope(t);
TrackBits rail_bits = GetTrackBits(t);
if (IsSlopeWithOneCornerRaised(tileh)) {
TrackBits lower_track = CornerToTrackBits(OppositeCorner(GetHighestSlopeCorner(tileh)));
TrackBits to_remove = lower_track & rail_bits;
if (to_remove != 0) {
Backup<CompanyID> cur_company(_current_company, OWNER_WATER, FILE_LINE);
flooded = DoCommand(t, 0, FIND_FIRST_BIT(to_remove), DC_EXEC, CMD_REMOVE_SINGLE_RAIL).Succeeded();
cur_company.Restore();
if (!flooded) return flooded; // not yet floodable
rail_bits = rail_bits & ~to_remove;
if (rail_bits == 0) {
MakeShore(t);
MarkTileDirtyByTile(t);
return flooded;
}
}
if (IsNonContinuousFoundation(GetRailFoundation(tileh, rail_bits))) {
flooded = true;
SetRailGroundType(t, RAIL_GROUND_WATER);
MarkTileDirtyByTile(t);
}
} else {
/* Make shore on steep slopes and 'three-corners-raised'-slopes. */
if (ApplyFoundationToSlope(GetRailFoundation(tileh, rail_bits), &tileh) == 0) {
if (IsSteepSlope(tileh) || IsSlopeWithThreeCornersRaised(tileh)) {
flooded = true;
SetRailGroundType(t, RAIL_GROUND_WATER);
MarkTileDirtyByTile(t);
}
}
}
return flooded;
}
static const TileIndexDiffC _trackdelta[] = {
{ -1, 0 }, { 0, 1 }, { -1, 0 }, { 0, 1 }, { 1, 0 }, { 0, 1 },
{ 0, 0 },
{ 0, 0 },
{ 1, 0 }, { 0, -1 }, { 0, -1 }, { 1, 0 }, { 0, -1 }, { -1, 0 },
{ 0, 0 },
{ 0, 0 }
};
static CommandCost ValidateAutoDrag(Trackdir *trackdir, TileIndex start, TileIndex end)
{
int x = TileX(start);
int y = TileY(start);
int ex = TileX(end);
int ey = TileY(end);
if (!ValParamTrackOrientation(TrackdirToTrack(*trackdir))) return CMD_ERROR;
/* calculate delta x,y from start to end tile */
int dx = ex - x;
int dy = ey - y;
/* calculate delta x,y for the first direction */
int trdx = _trackdelta[*trackdir].x;
int trdy = _trackdelta[*trackdir].y;
if (!IsDiagonalTrackdir(*trackdir)) {
trdx += _trackdelta[*trackdir ^ 1].x;
trdy += _trackdelta[*trackdir ^ 1].y;
}
/* validate the direction */
while ((trdx <= 0 && dx > 0) ||
(trdx >= 0 && dx < 0) ||
(trdy <= 0 && dy > 0) ||
(trdy >= 0 && dy < 0)) {
if (!HasBit(*trackdir, 3)) { // first direction is invalid, try the other
SetBit(*trackdir, 3); // reverse the direction
trdx = -trdx;
trdy = -trdy;
} else { // other direction is invalid too, invalid drag
return CMD_ERROR;
}
}
/* (for diagonal tracks, this is already made sure of by above test), but:
* for non-diagonal tracks, check if the start and end tile are on 1 line */
if (!IsDiagonalTrackdir(*trackdir)) {
trdx = _trackdelta[*trackdir].x;
trdy = _trackdelta[*trackdir].y;
if (abs(dx) != abs(dy) && abs(dx) + abs(trdy) != abs(dy) + abs(trdx)) return CMD_ERROR;
}
return CommandCost();
}
/**
* Build or remove a stretch of railroad tracks.
* @param tile start tile of drag
* @param flags operation to perform
* @param p1 end tile of drag
* @param p2 various bitstuffed elements
* - p2 = (bit 0-5) - railroad type normal/maglev (0 = normal, 1 = mono, 2 = maglev), only used for building
* - p2 = (bit 6-8) - track-orientation, valid values: 0-5 (Track enum)
* - p2 = (bit 9) - 0 = build, 1 = remove tracks
* - p2 = (bit 10) - 0 = build up to an obstacle, 1 = fail if an obstacle is found (used for AIs).
* @param text unused
* @return the cost of this operation or an error
*/
static CommandCost CmdRailTrackHelper(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
CommandCost total_cost(EXPENSES_CONSTRUCTION);
Track track = Extract<Track, 6, 3>(p2);
bool remove = HasBit(p2, 9);
RailType railtype = Extract<RailType, 0, 6>(p2);
if ((!remove && !ValParamRailtype(railtype)) || !ValParamTrackOrientation(track)) return CMD_ERROR;
if (p1 >= MapSize()) return CMD_ERROR;
TileIndex end_tile = p1;
Trackdir trackdir = TrackToTrackdir(track);
CommandCost ret = ValidateAutoDrag(&trackdir, tile, end_tile);
if (ret.Failed()) return ret;
bool had_success = false;
CommandCost last_error = CMD_ERROR;
for (;;) {
CommandCost ret = DoCommand(tile, remove ? 0 : railtype, TrackdirToTrack(trackdir), flags, remove ? CMD_REMOVE_SINGLE_RAIL : CMD_BUILD_SINGLE_RAIL);
if (ret.Failed()) {
last_error = ret;
if (last_error.GetErrorMessage() != STR_ERROR_ALREADY_BUILT && !remove) {
if (HasBit(p2, 10)) return last_error;
break;
}
/* Ownership errors are more important. */
if (last_error.GetErrorMessage() == STR_ERROR_OWNED_BY && remove) break;
} else {
had_success = true;
total_cost.AddCost(ret);
}
if (tile == end_tile) break;
tile += ToTileIndexDiff(_trackdelta[trackdir]);
/* toggle railbit for the non-diagonal tracks */
if (!IsDiagonalTrackdir(trackdir)) ToggleBit(trackdir, 0);
}
if (had_success) return total_cost;
return last_error;
}
/**
* Build rail on a stretch of track.
* Stub for the unified rail builder/remover
* @param tile start tile of drag
* @param flags operation to perform
* @param p1 end tile of drag
* @param p2 various bitstuffed elements
* - p2 = (bit 0-5) - railroad type normal/maglev (0 = normal, 1 = mono, 2 = maglev)
* - p2 = (bit 6-8) - track-orientation, valid values: 0-5 (Track enum)
* - p2 = (bit 9) - 0 = build, 1 = remove tracks
* @param text unused
* @return the cost of this operation or an error
* @see CmdRailTrackHelper
*/
CommandCost CmdBuildRailroadTrack(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
return CmdRailTrackHelper(tile, flags, p1, ClrBit(p2, 9), text);
}
/**
* Build rail on a stretch of track.
* Stub for the unified rail builder/remover
* @param tile start tile of drag
* @param flags operation to perform
* @param p1 end tile of drag
* @param p2 various bitstuffed elements
* - p2 = (bit 0-5) - railroad type normal/maglev (0 = normal, 1 = mono, 2 = maglev), only used for building
* - p2 = (bit 6-8) - track-orientation, valid values: 0-5 (Track enum)
* - p2 = (bit 9) - 0 = build, 1 = remove tracks
* @param text unused
* @return the cost of this operation or an error
* @see CmdRailTrackHelper
*/
CommandCost CmdRemoveRailroadTrack(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
return CmdRailTrackHelper(tile, flags, p1, SetBit(p2, 9), text);
}
/**
* Build a train depot
* @param tile position of the train depot
* @param flags operation to perform
* @param p1 rail type
* @param p2 bit 0..1 entrance direction (DiagDirection)
* @param text unused
* @return the cost of this operation or an error
*
* @todo When checking for the tile slope,
* distinguish between "Flat land required" and "land sloped in wrong direction"
*/
CommandCost CmdBuildTrainDepot(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
/* check railtype and valid direction for depot (0 through 3), 4 in total */
RailType railtype = Extract<RailType, 0, 6>(p1);
if (!ValParamRailtype(railtype)) return CMD_ERROR;
Slope tileh = GetTileSlope(tile);
DiagDirection dir = Extract<DiagDirection, 0, 2>(p2);
CommandCost cost(EXPENSES_CONSTRUCTION);
/* Prohibit construction if
* The tile is non-flat AND
* 1) build-on-slopes is disabled
* 2) the tile is steep i.e. spans two height levels
* 3) the exit points in the wrong direction
*/
if (tileh != SLOPE_FLAT) {
if (!_settings_game.construction.build_on_slopes || !CanBuildDepotByTileh(dir, tileh)) {
return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
}
cost.AddCost(_price[PR_BUILD_FOUNDATION]);