-
Notifications
You must be signed in to change notification settings - Fork 0
/
builder_network.nut
958 lines (806 loc) · 27.5 KB
/
builder_network.nut
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
class BuildNewNetwork extends Task {
static MAX_ATTEMPTS = 50;
network = null;
constructor(parentTask, minDistance = MIN_DISTANCE, maxDistance = MAX_DISTANCE) {
Task.constructor(parentTask);
//this.network = Network(AIRailTypeList().Begin(), RAIL_STATION_PLATFORM_LENGTH, minDistance, maxDistance);
this.network = Network(AIRailTypeList().Begin(), 3, minDistance, maxDistance);
}
function Run() {
local tile;
local count = 0;
if (!subtasks) {
while (true) {
tile = RandomTile();
SetConstructionSign(tile, this);
if (AIMap.IsValidTile(tile) &&
AITile.IsBuildableRectangle(
tile - AIMap.GetTileIndex(Crossing.WIDTH, Crossing.WIDTH),
Crossing.WIDTH*3, Crossing.WIDTH*3) &&
EstimateNetworkStationCount(tile) >= 3) break;
count++;
if (count >= MAX_ATTEMPTS) {
Warning("Tried " + count + " locations to start a new network, map may be full. Trying again tomorrow...");
throw TaskRetryException(TICKS_PER_DAY);
} else {
AIController.Sleep(1);
}
}
AIRail.SetCurrentRailType(network.railType);
subtasks = [
LevelTerrain(this, tile, Rotation.ROT_0, [1, 1], [Crossing.WIDTH-2, Crossing.WIDTH-2]),
BuildCrossing(this, tile, network)
];
}
RunSubtasks();
}
function _tostring() {
return "BuildNewNetwork";
}
function EstimateNetworkStationCount(tile) {
local stationCount = 0;
local estimationNetwork = Network(network.railType, RAIL_STATION_PLATFORM_LENGTH, network.minDistance, network.maxDistance);
foreach (direction in [Direction.NE, Direction.SW, Direction.NW, Direction.SE]) {
stationCount += EstimateCrossing(tile, direction, estimationNetwork);
}
Debug("Estimated stations for crossing at " + TileToString(tile) + ": " + stationCount);
return stationCount;
}
function EstimateCrossing(tile, direction, estimationNetwork) {
// for now, ignore potential gains from newly built crossings
local extender = ExtendCrossing(this, tile, direction, estimationNetwork);
local towns = extender.FindTowns();
local town = null;
local stationTile = null;
for (town = towns.Begin(); !towns.IsEnd(); town = towns.Next()) {
stationTile = FindStationSite(town, BuildTerminusStation.StationRotationForDirection(direction), tile);
if (stationTile) {
return 1;
}
}
return 0;
}
}
class BuildCrossing extends Builder {
static counter = Counter()
network = null;
extenders = null;
constructor(parentTask, location, network) {
Builder.constructor(parentTask, location);
this.network = network;
// expand in opposite directions first, to maximize potential gains
this.extenders = [
ExtendCrossing(null, location, Direction.NE, network),
ExtendCrossing(null, location, Direction.SW, network),
ExtendCrossing(null, location, Direction.NW, network),
ExtendCrossing(null, location, Direction.SE, network),
]
}
function Run() {
SetConstructionSign(location, this);
// four segments of track
BuildSegment([0,1], [3,1]);
BuildSegment([0,2], [3,2]);
BuildSegment([1,0], [1,3]);
BuildSegment([2,0], [2,3]);
// outer diagonals (clockwise)
BuildRail([1,0], [1,1], [0,1]);
BuildRail([0,2], [1,2], [1,3]);
BuildRail([3,2], [2,2], [2,3]);
BuildRail([2,0], [2,1], [3,1]);
// long inner diagonals
//BuildRail([0,1], [1,1], [2,3]);
//BuildRail([0,2], [1,2], [2,0]);
//BuildRail([1,3], [1,2], [3,1]);
//BuildRail([3,2], [2,2], [1,0]);
// inner diagonals (clockwise)
BuildRail([2,1], [1,1], [1,2]);
BuildRail([1,1], [1,2], [2,2]);
BuildRail([2,1], [2,2], [1,2]);
BuildRail([1,1], [2,1], [2,2]);
// signals (clockwise)
// initially, all signals face outwards to block trains off from unfinished tracks
// after an exit is connected, we open it up by either flipping or removing the signal
local type = AIRail.SIGNALTYPE_PBS_ONEWAY;
BuildSignal([0,1], [-1, 1], type);
BuildSignal([0,2], [-1, 2], type);
BuildSignal([1,3], [ 1, 4], type);
BuildSignal([2,3], [ 2, 4], type);
BuildSignal([3,2], [ 4, 2], type);
BuildSignal([3,1], [ 4, 1], type);
BuildSignal([2,0], [ 2,-1], type);
BuildSignal([1,0], [ 1,-1], type);
subtasks.extend(extenders);
if (!HaveHQ()) {
subtasks.append(BuildHQ(null, location));
}
}
function _tostring() {
return "BuildCrossing " + TileToString(location);
}
function Failed() {
Task.Failed();
// cancel ExtendCrossing tasks we created
foreach (task in extenders) {
subtask.Cancel();
}
// one exit should have a waypoint which we need to demolish
Demolish([0,2])
Demolish([2,3])
Demolish([3,1])
Demolish([1,0])
// four segments of track
RemoveSegment([0,1], [3,1]);
RemoveSegment([0,2], [3,2]);
RemoveSegment([1,0], [1,3]);
RemoveSegment([2,0], [2,3]);
// outer diagonals (clockwise)
RemoveRail([1,0], [1,1], [0,1]);
RemoveRail([0,2], [1,2], [1,3]);
RemoveRail([3,2], [2,2], [2,3]);
RemoveRail([2,0], [2,1], [3,1]);
// long inner diagonals
//RemoveRail([0,1], [1,1], [2,3]);
//RemoveRail([0,2], [1,2], [2,0]);
//RemoveRail([1,3], [1,2], [3,1]);
//RemoveRail([3,2], [2,2], [1,0]);
// inner diagonals (clockwise)
RemoveRail([2,1], [1,1], [1,2]);
RemoveRail([1,1], [1,2], [2,2]);
RemoveRail([2,1], [2,2], [1,2]);
RemoveRail([1,1], [2,1], [2,2]);
}
}
class ConnectStation extends Task {
crossingTile = null;
direction = null;
stationTile = null;
network = null;
constructor(parentTask, crossingTile, direction, stationTile, network) {
Task.constructor(parentTask);
this.crossingTile = crossingTile;
this.direction = direction;
this.stationTile = stationTile;
this.network = network;
}
function Run() {
SetConstructionSign(crossingTile, this);
local crossing = Crossing(crossingTile);
if (!subtasks) {
subtasks = [];
local station = TerminusStation.AtLocation(stationTile, RAIL_STATION_PLATFORM_LENGTH);
local reserved = station.GetReservedEntranceSpace();
reserved.extend(crossing.GetReservedExitSpace(direction));
foreach (d in [Direction.NE, Direction.SW, Direction.NW, Direction.SE]) {
if (d != direction) {
reserved.extend(crossing.GetReservedEntranceSpace(d));
reserved.extend(crossing.GetReservedExitSpace(d));
}
}
local first = BuildTrack(this,
station.GetExit(), crossing.GetEntrance(direction),
reserved, SignalMode.FORWARD, network);
subtasks.append(first);
// we don't have to reserve space for the path we just connected
//local reserved = station.GetReservedExitSpace();
//reserved.extend(crossing.GetReservedEntranceSpace(direction));
local reserved = [];
foreach (d in [Direction.NE, Direction.SW, Direction.NW, Direction.SE]) {
if (d != direction) {
reserved.extend(crossing.GetReservedEntranceSpace(d));
reserved.extend(crossing.GetReservedExitSpace(d));
}
}
subtasks.append(BuildTrack(this,
Swap(station.GetEntrance()), Swap(crossing.GetExit(direction)),
reserved, SignalMode.BACKWARD, network,
BuildTrack.FOLLOW, first));
}
RunSubtasks();
// open up the exit by removing the signal
local exit = crossing.GetExit(direction);
AIRail.RemoveSignal(exit[0], exit[1]);
if (StartsWith(crossing.GetName(), "unnamed") && AIController.GetSetting("JunctionNames")) {
BuildWaypoint(exit[0]);
}
}
function BuildWaypoint(tile) {
local town = AITile.GetClosestTown(tile);
if (AIRail.BuildRailWaypoint(tile) ) {
local waypoint = AIWaypoint.GetWaypointID(tile);
local suffixes = ["Junction", "Crossing", "Point", "Union", "Switch", "Cross", "Points"]
foreach (suffix in suffixes) {
if (AIWaypoint.SetName(waypoint, AITown.GetName(town) + " " + suffix)) {
break;
}
}
}
}
function _tostring() {
local station = AIStation.GetStationID(stationTile);
local name = AIStation.IsValidStation(station) ? AIStation.GetName(station) : "unnamed";
return "ConnectStation " + name + " to " + Crossing(crossingTile) + " " + DirectionName(direction);
}
}
class ConnectCrossing extends Task {
fromCrossingTile = null;
fromDirection = null;
toCrossingTile = null;
toDirection = null;
network = null;
constructor(parentTask, fromCrossingTile, fromDirection, toCrossingTile, toDirection, network) {
Task.constructor(parentTask);
this.fromCrossingTile = fromCrossingTile;
this.fromDirection = fromDirection;
this.toCrossingTile = toCrossingTile;
this.toDirection = toDirection;
this.network = network;
}
function Run() {
SetConstructionSign(fromCrossingTile, this);
local fromCrossing = Crossing(fromCrossingTile);
local toCrossing = Crossing(toCrossingTile);
if (!subtasks) {
subtasks = [];
local reserved = toCrossing.GetReservedEntranceSpace(toDirection);
reserved.extend(fromCrossing.GetReservedExitSpace(fromDirection));
foreach (d in [Direction.NE, Direction.SW, Direction.NW, Direction.SE]) {
if (d != fromDirection) {
reserved.extend(fromCrossing.GetReservedEntranceSpace(d));
reserved.extend(fromCrossing.GetReservedExitSpace(d));
}
if (d != toDirection) {
reserved.extend(toCrossing.GetReservedEntranceSpace(d));
reserved.extend(toCrossing.GetReservedExitSpace(d));
}
}
local first = BuildTrack(this,
toCrossing.GetExit(toDirection), fromCrossing.GetEntrance(fromDirection),
reserved, SignalMode.FORWARD, network);
subtasks.append(first);
//local reserved = toCrossing.GetReservedExitSpace(toDirection);
//reserved.extend(fromCrossing.GetReservedEntranceSpace(fromDirection));
local reserved = [];
foreach (d in [Direction.NE, Direction.SW, Direction.NW, Direction.SE]) {
if (d != fromDirection) {
reserved.extend(fromCrossing.GetReservedEntranceSpace(d));
reserved.extend(fromCrossing.GetReservedExitSpace(d));
}
if (d != toDirection) {
reserved.extend(toCrossing.GetReservedEntranceSpace(d));
reserved.extend(toCrossing.GetReservedExitSpace(d));
}
}
subtasks.append(BuildTrack(this,
Swap(toCrossing.GetEntrance(toDirection)), Swap(fromCrossing.GetExit(fromDirection)),
reserved, SignalMode.BACKWARD, network,
BuildTrack.FOLLOW, first));
}
RunSubtasks();
// open up both crossings' exits
local exit = fromCrossing.GetExit(fromDirection);
AIRail.RemoveSignal(exit[0], exit[1]);
if (StartsWith(fromCrossing.GetName(), "unnamed") && AIController.GetSetting("JunctionNames")) {
BuildWaypoint(exit[0]);
}
exit = toCrossing.GetExit(toDirection);
AIRail.RemoveSignal(exit[0], exit[1]);
if (StartsWith(toCrossing.GetName(), "unnamed") && AIController.GetSetting("JunctionNames")) {
BuildWaypoint(exit[0]);
}
}
function BuildWaypoint(tile) {
local town = AITile.GetClosestTown(tile);
if (AIRail.BuildRailWaypoint(tile)) {
local waypoint = AIWaypoint.GetWaypointID(tile);
local suffixes = ["Junction", "Crossing", "Point", "Union", "Switch", "Cross", "Points"]
foreach (suffix in suffixes) {
if (AIWaypoint.SetName(waypoint, AITown.GetName(town) + " " + suffix)) {
break;
}
}
}
}
function _tostring() {
return "ConnectCrossing " + Crossing(fromCrossingTile) + " " + DirectionName(fromDirection) + " to " + Crossing(toCrossingTile);
}
}
class ExtendCrossing extends Builder {
static MIN_TOWN_POPULATION = 300;
crossing = null;
direction = null;
network = null;
cancelled = null;
town = null;
stationTile = null;
constructor(parentTask, crossing, direction, network) {
Builder.constructor(parentTask, crossing);
this.crossing = crossing;
this.direction = direction;
this.network = network;
this.cancelled = false;
this.town = null;
this.stationTile = null;
}
function _tostring() {
return "ExtendCrossing " + Crossing(crossing) + " " + DirectionName(direction);
}
function Cancel() {
this.cancelled = true;
}
function Run() {
// we can be cancelled if BuildCrossing failed
if (cancelled) return;
// see if we've not already built this direction
// if we have subtasks but we do find rails, assume we're still building
local exit = Crossing(crossing).GetExit(direction);
if (!subtasks && AIRail.IsRailTile(exit[1])) {
return;
}
if (!subtasks) {
SetConstructionSign(crossing, this);
local towns = FindTowns();
local stationRotation = BuildTerminusStation.StationRotationForDirection(direction);
// TODO: try more than station site per town, and more than one town per direction
// NOTE: give up on a town if pathfinding fails or you might try to pathfound around the sea over and over and over...
town = null;
stationTile = null;
for (town = towns.Begin(); !towns.IsEnd(); town = towns.Next()) {
stationTile = FindStationSite(town, stationRotation, crossing);
if (stationTile) break;
}
if (!stationTile) {
throw TaskFailedException("no towns " + DirectionName(direction) + " of " + Crossing(crossing) + " where we can build a station");
}
// TODO: proper cost estimate
// building stations is fairly cheap, but it's no use to start
// construction if we don't have the money for pathfinding, tracks and trains
local costEstimate = 80000;
local crossingTile = FindCrossingSite(stationTile);
if (crossingTile) {
local crossingEntranceDirection = InverseDirection(direction);
local crossingExitDirection = CrossingExitDirection(crossingTile, stationTile);
subtasks = [
WaitForMoney(this, costEstimate),
AppeaseLocalAuthority(this, town),
BuildTownBusStation(this, town),
LevelTerrain(this, stationTile, stationRotation, [0, 0], [RAIL_STATION_WIDTH-1, RAIL_STATION_LENGTH-2], true),
AppeaseLocalAuthority(this, town),
BuildTerminusStation(this, stationTile, direction, network, town),
AppeaseLocalAuthority(this, town),
BuildBusStations(this, stationTile, town),
LevelTerrain(this, crossingTile, Rotation.ROT_0, [1, 1], [Crossing.WIDTH-2, Crossing.WIDTH-2]),
BuildCrossing(this, crossingTile, network),
ConnectCrossing(this, crossing, direction, crossingTile, crossingEntranceDirection, network),
ConnectStation(this, crossingTile, crossingExitDirection, stationTile, network),
BuildTrains(this, stationTile, network, PAX),
];
} else {
subtasks = [
WaitForMoney(this, costEstimate),
AppeaseLocalAuthority(this, town),
BuildTownBusStation(this, town),
LevelTerrain(this, stationTile, stationRotation, [0, 0], [RAIL_STATION_WIDTH-1, RAIL_STATION_LENGTH-2], true),
AppeaseLocalAuthority(this, town),
BuildTerminusStation(this, stationTile, direction, network, town),
AppeaseLocalAuthority(this, town),
BuildBusStations(this, stationTile, town),
ConnectStation(this, crossing, direction, stationTile, network),
BuildTrains(this, stationTile, network, PAX),
];
}
// build an extra train for the second station in a network
// at this point, that means we only have one station in the network
if (network.stations.len() == 1) {
local firstStation = AIStation.GetLocation(network.stations[0]);
subtasks.append(BuildTrains(this, firstStation, network, PAX));
}
}
RunSubtasks();
// TODO: append instead? before or after bus?
//tasks.insert(1, ExtendStation(stationTile, direction, network));
local towns = AITownList();
towns.Valuate(AITown.GetDistanceManhattanToTile, stationTile);
towns.KeepBelowValue(MAX_BUS_ROUTE_DISTANCE);
// sort descending, then append back-to-front so the closest actually goes first
towns.Sort(AIList.SORT_BY_VALUE, false);
for (local town = towns.Begin(); !towns.IsEnd(); town = towns.Next()) {
tasks.insert(1, BuildBusService(null, stationTile, town));
}
}
function CrossingExitDirection(crossingTile, stationTile) {
local dx = AIMap.GetTileX(stationTile) - AIMap.GetTileX(crossingTile);
local dy = AIMap.GetTileY(stationTile) - AIMap.GetTileY(crossingTile);
// leave the new crossing in a direction perpendicular to the one we came in through
switch (direction) {
case Direction.NE: return dy > 0 ? Direction.SE : Direction.NW;
case Direction.SE: return dx > 0 ? Direction.SW : Direction.NE;
case Direction.SW: return dy > 0 ? Direction.SE : Direction.NW;
case Direction.NW: return dx > 0 ? Direction.SW : Direction.NE;
default: throw "invalid direction";
}
}
/*
* Find towns in the expansion direction that don't already have a station.
*/
function FindTowns() {
local towns = AIList();
towns.AddList(AITownList());
// filter out the tiny ones
towns.Valuate(AITown.GetPopulation);
towns.KeepAboveValue(MIN_TOWN_POPULATION);
local stations = AIStationList(AIStation.STATION_TRAIN);
for (local station = stations.Begin(); !stations.IsEnd(); station = stations.Next()) {
towns.RemoveItem(AIStation.GetNearestTown(station));
}
switch (direction) {
case Direction.NE:
// negative X
FilterTowns(towns, crossing, GetXDistance, false, GetYDistance);
break;
case Direction.SE:
// positive Y
FilterTowns(towns, crossing, GetYDistance, true, GetXDistance);
break;
case Direction.SW:
// positive X
FilterTowns(towns, crossing, GetXDistance, true, GetYDistance);
break;
case Direction.NW:
// negative Y
FilterTowns(towns, crossing, GetYDistance, false, GetXDistance);
break;
default: throw "invalid direction";
}
//towns.Valuate(AITown.GetDistanceManhattanToTile, fromStationTile);
//towns.Sort(AIList.SORT_BY_VALUE, true);
towns.Valuate(AITown.GetPopulation);
towns.Sort(AIList.SORT_BY_VALUE, false);
return towns;
}
function FilterTowns(towns, location, lengthValuator, positive, widthValuator) {
// remove that are too close or too far
towns.Valuate(lengthValuator, location);
if (positive) {
towns.RemoveBelowValue(network.minDistance);
towns.RemoveAboveValue(network.maxDistance);
} else {
towns.RemoveAboveValue(-network.minDistance);
towns.RemoveBelowValue(-network.maxDistance);
}
// remove towns too far off to the side
towns.Valuate(widthValuator, location);
towns.KeepBetweenValue(-network.maxDistance/2, network.maxDistance/2);
}
function GetXDistance(town, tile) {
return AIMap.GetTileX(AITown.GetLocation(town)) - AIMap.GetTileX(tile);
}
function GetYDistance(town, tile) {
return AIMap.GetTileY(AITown.GetLocation(town)) - AIMap.GetTileY(tile);
}
function FindCrossingSite(stationTile) {
local dx = AIMap.GetTileX(stationTile) - AIMap.GetTileX(crossing);
local dy = AIMap.GetTileY(stationTile) - AIMap.GetTileY(crossing);
if (abs(dx) < Crossing.WIDTH || abs(dy) < Crossing.WIDTH) return null;
local centerTile = crossing;
if (direction == Direction.NE || direction == Direction.SW) {
centerTile += AIMap.GetTileIndex(dx - Sign(dx) * (RAIL_STATION_LENGTH + 1), 0);
} else {
centerTile += AIMap.GetTileIndex(0, dy - Sign(dy) * (RAIL_STATION_LENGTH + 1));
}
// find a buildable area closest to ideal tile, or crossing (testing)
local tiles = AITileList();
SafeAddRectangle(tiles, centerTile, Crossing.WIDTH + 2);
tiles.Valuate(IsBuildableRectangle, Rotation.ROT_0, [-2, -2], [Crossing.WIDTH + 2, Crossing.WIDTH + 2], false);
tiles.KeepValue(1);
//tiles.Valuate(AIMap.DistanceManhattan, centerTile);
tiles.Valuate(AIMap.DistanceManhattan, crossing);
tiles.KeepBottom(1);
return tiles.IsEmpty() ? null : tiles.Begin();
}
function Failed() {
Task.Failed();
// either we didn't find a town, or one of our subtasks failed
local entrance = Crossing(crossing).GetEntrance(direction);
local exit = Crossing(crossing).GetExit(direction);
// use the NE direction as a template and derive the others
// by rotation and offset
local rotation;
local offset;
switch (direction) {
case Direction.NE:
rotation = Rotation.ROT_0;
offset = [0,0];
break;
case Direction.SE:
rotation = Rotation.ROT_270;
offset = [0,3];
break;
case Direction.SW:
rotation = Rotation.ROT_180;
offset = [3,3];
break;
case Direction.NW:
rotation = Rotation.ROT_90;
offset = [3,0];
break;
}
// move coordinate system
SetLocalCoordinateSystem(GetTile(offset), rotation);
// the exit might have a waypoint
Demolish([0,2]);
RemoveRail([-1,1], [0,1], [1,1]);
RemoveRail([-1,2], [0,2], [1,2]);
RemoveRail([0,1], [1,1], [1,0]);
RemoveRail([0,1], [1,1], [2,1]);
RemoveRail([0,2], [1,2], [2,2]);
RemoveRail([0,2], [1,2], [1,3]);
RemoveRail([2,2], [2,1], [1,1]);
RemoveRail([2,1], [2,2], [1,2]);
// we can remove more bits if another direction is already gone
if (!HasRail([1,3])) {
RemoveRail([1,1], [2,1], [3,1]);
RemoveRail([2,0], [2,1], [2,2]);
RemoveRail([2,1], [2,2], [2,3]);
}
if (!HasRail([1,0])) {
RemoveRail([1,2], [2,2], [3,2]);
RemoveRail([2,0], [2,1], [2,2]);
RemoveRail([2,1], [2,2], [2,3]);
}
}
function HasRail(tileCoords) {
return AIRail.IsRailTile(GetTile(tileCoords));
}
}
class Route extends Task {
locations = [];
cargo = null;
vtype = null;
vgroup = null;
stations = [];
depots = [];
maxvehicles = 10;
vehicles = [];
subtasks = [];
constructor(parentTask, locations, cargo, vtype=AIVehicle.VT_ROAD) {
Task.constructor(parentTask, null);
this.locations = locations; // an array of locations
this.cargo = cargo;
vtype = vtype;
vgroup = AIGroup.CreateGroup(vtype);
stations = [];
depots = [];
maxvehicles = 10;
vehicles = [];
subtasks = [];
}
function _tostring() {
return "Route";
}
// most basic route assumes a 1-to-1 mapping, a producer (and depot)
// and a consumer
function Run() {
local producer = locations[0];
local consumer = locations[1];
local depot = FindClosestDepot(producer);
if (depot == null) {
local d = BuildTruckDepot(this, producer);
d.Run();
depot = d.depot;
if (depot == null) {
throw TaskFailedException("unable to build depot");
}
}
depots.append(depot);
local pobj = BuildTruckStation(this, producer);
local cobj = BuildTruckStation(this, consumer);
subtasks.extend([
pobj,
cobj,
]);
RunSubtasks();
Debug("pobj.station is ", pobj.station, " cobj.station is ", cobj.station);
if (pobj.station == null) {
throw TaskFailedException("pobj.station is null");
} else if (cobj.station == null) {
throw TaskFailedException("cobj.station is null");
}
stations.extend([
pobj.station,
cobj.station,
]);
subtasks.append(BuildTruckRoad(this, pobj.station, depot));
local town = GetBetweenTown(pobj.station, cobj.station);
if (town != null) {
local town_loc = AITown.GetLocation(town);
subtasks.extend([
BuildTruckRoad(this, pobj.station, town_loc),
BuildTruckRoad(this, cobj.station, town_loc),
]);
} else {
subtasks.append(BuildTruckRoad(this, cobj.station, pobj.station));
}
RunSubtasks();
local veh = AddVehicle(depot);
Debug("vehicle count is", vehicles.len());
if (vehicles.len() == 1) {
// only give orders to the first vehicle
// the rest just share those orders
AddOrders(veh);
} else {
AIOrder.ShareOrders(veh, vehicles[0]);
}
AIVehicle.StartStopVehicle(veh);
}
function AddVehicle(depot) {
if (maxvehicles > 0 && vehicles.len() >= maxvehicles) {
local msg = "Max vehicles of " + maxvehicles + " reached";
throw TaskRouteTooManyVehicles(msg);
}
local eID = AllocateTruck(this.cargo);
local veh = AIVehicle.BuildVehicle(depot, eID);
vehicles.append(veh);
AIGroup.MoveVehicle(this.vgroup, veh);
return veh;
}
function AddVehicleAtStation(station) {
local s;
foreach (s in this.stations) {
if (s == station) {
local veh = AddVehicle(this.depots[0]);
AIOrder.ShareOrders(veh, vehicles[0]);
StartOrderAtStation(veh, s);
AIVehicle.StartStopVehicle(veh);
}
}
}
function StartOrderAtStation(veh, station) {
local i;
local oct = AIOrder.GetOrderCount(veh);
for (i=0; i < oct; i++) {
local loc = AIOrder.GetOrderDestination(veh, i);
if (loc == station) {
AIOrder.SkipToOrder(veh, i);
return;
}
}
}
// need to sort stations and depots by distance from one another
function AddOrders(veh) {
local i;
local stops = [];
stops.extend(depots);
stops.extend(stations);
stops = SortByDistance(stops);
local max = stops.len();
// 1 -> 2 -> 3 -> 4 -> 5 -> 4 -> 3 -> 2
for (i=0; i < max; i++) {
local sID = AIStation.GetStationID(stops[i]);
Debug("stop is", i, stops[i], AIStation.GetName(sID));
AddStation(veh, stops[i]);
}
if (max <= 3) { return }
for (i=i-2; i > 0; i--) {
Debug("stop is ", i, " ", stops[i]);
AddStation(veh, stops[i]);
}
}
function AddStation(veh, station) {
local flag = AIRoad.IsRoadDepotTile(station) ?
AIOrder.OF_SERVICE_IF_NEEDED : AIOrder.OF_NON_STOP_INTERMEDIATE;
AIOrder.AppendOrder(veh, station, flag);
}
function SortByDistance(arr) {
local newarr = [];
local l = ArrayToList(arr);
local loc1 = l.Begin();
l.RemoveItem(loc1);
newarr.append(loc1);
while (l.Count() > 0) {
l.Valuate(AITile.GetDistanceManhattanToTile, loc1);
l.Sort(AIList.SORT_BY_VALUE, false);
local loc2 = l.Begin();
l.RemoveItem(loc2);
newarr.append(loc2);
loc1 = loc2;
}
return newarr;
}
}
class RateBasedRoute extends Route {
desc = "Route that expands number of stations based on cargo rating";
depotct = 1;
throttles = null;
constructor(parentTask, locations, cargo, vtype=AIVehicle.VT_ROAD) {
Route.constructor(parentTask, locations, cargo, vtype);
throttles = {};
}
function _tostring() {
return "RateBasedRoute";
}
function Wake() {
local station;
foreach (station in stations) {
local stationID = AIStation.GetStationID(station);
local rating = GetRating(stationID, cargo);
if (rating < 50) {
if (ShouldAddVehicle(stationID)) {
Debug("Add another vehicle to route");
AddVehicleAtStation(station);
}
}
local vct = vehicles.len();
//Debug("((vct / 4.0) > this.depotct) is " + ((vct / 4.0) > this.depotct));
if ((vct / 4.0) > this.depotct) {
Debug(vct, " vehicles, try to expand the station");
local ret = ExpandStation(station);
}
}
}
function ShouldAddVehicle(stationID) {
local now = AIController.GetTick();
local future = now + (TICKS_PER_DAY * 15);
if (stationID in throttles) {
local next_tick = throttles[stationID];
if (next_tick > now) {
throttles[stationID] = future;
return true;
}
} else {
throttles[stationID] <- future;
return true;
}
return false;
}
function ExpandStation(stationloc) {
local ret = false;
local stationfront = AIRoad.GetRoadStationFrontTile(stationloc);
local stationID = AIStation.GetStationID(stationloc);
local roadtype = AIRoad.ROADVEHTYPE_TRUCK;
local tiles = AITileList();
SafeAddRectangle(tiles, stationfront, 3);
tiles.RemoveValue(stationfront);
tiles.Valuate(AIRoad.IsRoadTile);
tiles.KeepValue(1);
tiles.Valuate(AITile.GetSlope);
tiles.KeepValue(AITile.SLOPE_FLAT);
tiles.Valuate(AITile.GetDistanceManhattanToTile, stationloc);
tiles.Sort(AIList.SORT_BY_VALUE, AIList.SORT_ASCENDING);
Debug("tile count=", tiles.Count());
if (tiles.IsEmpty()) {
Debug("no available tiles found to expand station");
return false;
}
local t, front;
local i = 1;
foreach (front,_ in tiles) {
foreach (t,_ in FindPlaceAlongRoad(front)) {
ret = AIRoad.BuildRoadStation(t, front, roadtype, stationID);
PrintError(ret);
if (ret) {
this.depotct++;
subtasks = [
BuildTruckRoad(this, stationfront, front),
BuildTruckRoad(this, t, front),
];
RunSubtasks();
return ret;
}
}
}
return ret;
}
function FindPlaceAlongRoad(front) {
local tiles = AITileList();
SafeAddRectangle(tiles, front, 1);
tiles.RemoveValue(front);
tiles.Valuate(AIRoad.IsRoadTile);
tiles.RemoveValue(1);
tiles.Valuate(AITile.IsBuildable);
tiles.KeepValue(1);
tiles.Valuate(AITile.GetSlope);
tiles.KeepValue(AITile.SLOPE_FLAT);
return tiles;
}
}