-
Notifications
You must be signed in to change notification settings - Fork 3k
/
Copy pathControlPathfinder.java
1633 lines (1306 loc) · 64.4 KB
/
ControlPathfinder.java
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
package mindustry.ai;
import arc.*;
import arc.graphics.*;
import arc.graphics.g2d.*;
import arc.math.*;
import arc.math.geom.*;
import arc.struct.*;
import arc.util.*;
import mindustry.annotations.Annotations.*;
import mindustry.content.*;
import mindustry.core.*;
import mindustry.game.EventType.*;
import mindustry.game.*;
import mindustry.gen.*;
import mindustry.graphics.*;
import mindustry.world.*;
import static mindustry.Vars.*;
import static mindustry.ai.Pathfinder.*;
//https://webdocs.cs.ualberta.ca/~mmueller/ps/hpastar.pdf
//https://www.gameaipro.com/GameAIPro/GameAIPro_Chapter23_Crowd_Pathfinding_and_Steering_Using_Flow_Field_Tiles.pdf
public class ControlPathfinder implements Runnable{
private static final int wallImpassableCap = 1_000_000;
private static final int solidCap = 7000;
public static boolean showDebug;
public static final PathCost
costGround = (team, tile) ->
//deep is impassable
PathTile.allDeep(tile) ? impassable :
//impassable same-team or neutral block
PathTile.solid(tile) && ((PathTile.team(tile) == team && !PathTile.teamPassable(tile)) || PathTile.team(tile) == 0) ? impassable :
//impassable synthetic enemy block
((PathTile.team(tile) != team && PathTile.team(tile) != 0) && PathTile.solid(tile) ? wallImpassableCap : 0) +
1 +
(PathTile.nearSolid(tile) ? 6 : 0) +
(PathTile.nearLiquid(tile) ? 8 : 0) +
(PathTile.deep(tile) ? 6000 : 0) +
(PathTile.damages(tile) ? 50 : 0),
//same as ground but ignores liquids/deep stuff
costHover = (team, tile) ->
//impassable same-team or neutral block
PathTile.solid(tile) && ((PathTile.team(tile) == team && !PathTile.teamPassable(tile)) || PathTile.team(tile) == 0) ? impassable :
//impassable synthetic enemy block
((PathTile.team(tile) != team && PathTile.team(tile) != 0) && PathTile.solid(tile) ? wallImpassableCap : 0) +
1 +
(PathTile.nearSolid(tile) ? 6 : 0),
costLegs = (team, tile) ->
PathTile.legSolid(tile) ? impassable : 1 +
(PathTile.deep(tile) ? 6000 : 0) +
(PathTile.nearLegSolid(tile) ? 3 : 0),
costNaval = (team, tile) ->
//impassable same-team neutral block, or non-liquid
(PathTile.solid(tile) && ((PathTile.team(tile) == team && !PathTile.teamPassable(tile)) || PathTile.team(tile) == 0)) ? impassable :
(!PathTile.liquid(tile) ? 6000 : 1) +
//impassable synthetic enemy block
((PathTile.team(tile) != team && PathTile.team(tile) != 0) && PathTile.solid(tile) ? wallImpassableCap : 0) +
(PathTile.nearGround(tile) || PathTile.nearSolid(tile) ? 6 : 0);
public static final int
costIdGround = 0,
costIdHover = 1,
costIdLegs = 2,
costIdNaval = 3;
public static final Seq<PathCost> costTypes = Seq.with(
costGround,
costHover,
costLegs,
costNaval
);
private static final long maxUpdate = Time.millisToNanos(12);
private static final int updateStepInterval = 200;
private static final int updateFPS = 30;
private static final int updateInterval = 1000 / updateFPS, invalidateCheckInterval = 1000;
static final int clusterSize = 12;
static final int[] offsets = {
1, 0, //right: bottom to top
0, 1, //top: left to right
0, 0, //left: bottom to top
0, 0 //bottom: left to right
};
static final int[] moveDirs = {
0, 1,
1, 0,
0, 1,
1, 0
};
static final int[] nextOffsets = {
1, 0,
0, 1,
-1, 0,
0, -1
};
//maps team -> pathCost -> flattened array of clusters in 2D
//(what about teams? different path costs?)
Cluster[][][] clusters;
int cwidth, cheight;
//temporarily used for resolving connections for intra-edges
IntSet usedEdges = new IntSet();
//tasks to run on pathfinding thread
TaskQueue queue = new TaskQueue();
//individual requests based on unit - MAIN THREAD ONLY
ObjectMap<Unit, PathRequest> unitRequests = new ObjectMap<>();
Seq<PathRequest> threadPathRequests = new Seq<>(false);
//TODO: very dangerous usage;
//TODO - it is accessed from the main thread
//TODO - it is written to on the pathfinding thread
//maps position in world in (x + y * width format) | path type | team (bitpacked to long with FieldIndex.get) to a cache of flow fields
LongMap<FieldCache> fields = new LongMap<>();
//MAIN THREAD ONLY
Seq<FieldCache> fieldList = new Seq<>(false);
//these are for inner edge A* (temporary!)
IntFloatMap innerCosts = new IntFloatMap();
PathfindQueue innerFrontier = new PathfindQueue();
//ONLY modify on pathfinding thread.
IntSet clustersToUpdate = new IntSet();
IntSet clustersToInnerUpdate = new IntSet();
//PATHFINDING THREAD - requests that should be recomputed
ObjectSet<PathRequest> invalidRequests = new ObjectSet<>();
/** Current pathfinding thread */
@Nullable Thread thread;
//path requests are per-unit
static class PathRequest{
final Unit unit;
final int destination, team, costId;
//resulting path of nodes
final IntSeq resultPath = new IntSeq();
//node index -> total cost
@Nullable IntFloatMap costs = new IntFloatMap();
//node index (NodeIndex struct) -> node it came from TODO merge them, make properties of FieldCache?
@Nullable IntIntMap cameFrom = new IntIntMap();
//frontier for A*
@Nullable PathfindQueue frontier = new PathfindQueue();
//main thread only!
long lastUpdateId = state.updateId;
//both threads
volatile boolean notFound = false;
volatile boolean invalidated = false;
//old field assigned before everything was recomputed
@Nullable volatile FieldCache oldCache;
boolean lastRaycastResult = false;
int lastRaycastTile, lastWorldUpdate;
int lastTile;
@Nullable Tile lastTargetTile;
PathRequest(Unit unit, int team, int costId, int destination){
this.unit = unit;
this.costId = costId;
this.team = team;
this.destination = destination;
}
}
static class FieldCache{
final PathCost cost;
final int costId;
final int team;
final int goalPos;
//frontier for flow fields
final IntQueue frontier = new IntQueue();
//maps cluster index to field weights; 0 means uninitialized
final IntMap<int[]> fields = new IntMap<>();
//packed (goalPos | costId | team) long key to use in the global fields map
final long mapKey;
//main thread only!
long lastUpdateId = state.updateId;
//TODO: how are the nodes merged? CAN they be merged?
FieldCache(PathCost cost, int costId, int team, int goalPos){
this.cost = cost;
this.team = team;
this.goalPos = goalPos;
this.costId = costId;
this.mapKey = FieldIndex.get(goalPos, costId, team);
}
}
static class Cluster{
IntSeq[] portals = new IntSeq[4];
//maps rotation + index of portal to list of IntraEdge objects
LongSeq[][] portalConnections = new LongSeq[4][];
}
public ControlPathfinder(){
Events.on(ResetEvent.class, event -> stop());
Events.on(WorldLoadEvent.class, event -> {
stop();
//TODO: can the pathfinding thread even see these?
unitRequests = new ObjectMap<>();
fields = new LongMap<>();
fieldList = new Seq<>(false);
clusters = new Cluster[256][][];
cwidth = Mathf.ceil((float)world.width() / clusterSize);
cheight = Mathf.ceil((float)world.height() / clusterSize);
start();
});
Events.on(TileChangeEvent.class, e -> {
updateTile(e.tile);
//TODO: recalculate affected flow fields? or just all of them? how to reflow?
});
//invalidate paths
Events.run(Trigger.update, () -> {
for(var req : unitRequests.values()){
//skipped N update -> drop it
if(req.lastUpdateId <= state.updateId - 10 || !req.unit.isAdded()){
req.invalidated = true;
//concurrent modification!
queue.post(() -> threadPathRequests.remove(req));
Core.app.post(() -> unitRequests.remove(req.unit));
}
}
for(var field : fieldList){
//skipped N update -> drop it
if(field.lastUpdateId <= state.updateId - 30){
//make sure it's only modified on the main thread...? but what about calling get() on this thread??
queue.post(() -> fields.remove(field.mapKey));
Core.app.post(() -> fieldList.remove(field));
}
}
});
if(showDebug){
Events.run(Trigger.draw, () -> {
int team = player.team().id;
int cost = 0;
Draw.draw(Layer.overlayUI, () -> {
Lines.stroke(1f);
if(clusters[team] != null && clusters[team][cost] != null){
for(int cx = 0; cx < cwidth; cx++){
for(int cy = 0; cy < cheight; cy++){
var cluster = clusters[team][cost][cy * cwidth + cx];
if(cluster != null){
Lines.stroke(0.5f);
Draw.color(Color.gray);
Lines.stroke(1f);
Lines.rect(cx * clusterSize * tilesize - tilesize/2f, cy * clusterSize * tilesize - tilesize/2f, clusterSize * tilesize, clusterSize * tilesize);
for(int d = 0; d < 4; d++){
IntSeq portals = cluster.portals[d];
if(portals != null){
for(int i = 0; i < portals.size; i++){
int pos = portals.items[i];
int from = Point2.x(pos), to = Point2.y(pos);
float width = tilesize * (Math.abs(from - to) + 1), height = tilesize;
portalToVec(cluster, cx, cy, d, i, Tmp.v1);
Draw.color(Color.brown);
Lines.ellipse(30, Tmp.v1.x, Tmp.v1.y, width / 2f, height / 2f, d * 90f - 90f);
LongSeq connections = cluster.portalConnections[d] == null ? null : cluster.portalConnections[d][i];
if(connections != null){
Draw.color(Color.forest);
for(int coni = 0; coni < connections.size; coni ++){
long con = connections.items[coni];
portalToVec(cluster, cx, cy, IntraEdge.dir(con), IntraEdge.portal(con), Tmp.v2);
float
x1 = Tmp.v1.x, y1 = Tmp.v1.y,
x2 = Tmp.v2.x, y2 = Tmp.v2.y;
Lines.line(x1, y1, x2, y2);
}
}
}
}
}
}
}
}
}
for(var fields : fieldList){
try{
for(var entry : fields.fields){
int cx = entry.key % cwidth, cy = entry.key / cwidth;
for(int y = 0; y < clusterSize; y++){
for(int x = 0; x < clusterSize; x++){
int value = entry.value[x + y * clusterSize];
Tmp.c1.a = 1f;
Lines.stroke(0.8f, Tmp.c1.fromHsv(value * 3f, 1f, 1f));
Draw.alpha(0.5f);
Fill.square((x + cx * clusterSize) * tilesize, (y + cy * clusterSize) * tilesize, tilesize / 2f);
}
}
}
}catch(Exception ignored){} //probably has some concurrency issues when iterating but I don't care, this is for debugging
}
});
Draw.reset();
});
}
}
public void updateTile(Tile tile){
tile.getLinkedTiles(this::updateSingleTile);
}
public void updateSingleTile(Tile t){
int x = t.x, y = t.y, mx = x % clusterSize, my = y % clusterSize, cx = x / clusterSize, cy = y / clusterSize, cluster = cx + cy * cwidth;
//is at the edge of a cluster; this means the portals may have changed.
if(mx == 0 || my == 0 || mx == clusterSize - 1 || my == clusterSize - 1){
if(mx == 0) queueClusterUpdate(cx - 1, cy); //left
if(my == 0) queueClusterUpdate(cx, cy - 1); //bottom
if(mx == clusterSize - 1) queueClusterUpdate(cx + 1, cy); //right
if(my == clusterSize - 1) queueClusterUpdate(cx, cy + 1); //top
queueClusterUpdate(cx, cy);
//TODO: recompute edge clusters too.
}else{
//there is no need to recompute portals for block updates that are not on the edge.
queue.post(() -> clustersToInnerUpdate.add(cluster));
}
}
void queueClusterUpdate(int cx, int cy){
if(cx >= 0 && cy >= 0 && cx < cwidth && cy < cheight){
queue.post(() -> clustersToUpdate.add(cx + cy * cwidth));
}
}
//debugging only!
void portalToVec(Cluster cluster, int cx, int cy, int direction, int portalIndex, Vec2 out){
int pos = cluster.portals[direction].items[portalIndex];
int from = Point2.x(pos), to = Point2.y(pos);
int addX = moveDirs[direction * 2], addY = moveDirs[direction * 2 + 1];
float average = (from + to) / 2f;
float
x = (addX * average + cx * clusterSize + offsets[direction * 2] * (clusterSize - 1) + nextOffsets[direction * 2] / 2f) * tilesize,
y = (addY * average + cy * clusterSize + offsets[direction * 2 + 1] * (clusterSize - 1) + nextOffsets[direction * 2 + 1] / 2f) * tilesize;
out.set(x, y);
}
/** Starts or restarts the pathfinding thread. */
private void start(){
stop();
if(net.client()) return;
thread = new Thread(this, "Control Pathfinder");
thread.setPriority(Thread.MIN_PRIORITY);
thread.setDaemon(true);
thread.start();
}
/** Stops the pathfinding thread. */
private void stop(){
if(thread != null){
thread.interrupt();
thread = null;
}
queue.clear();
}
/** @return a cluster at coordinates; can be null if not cluster was created yet*/
@Nullable Cluster getCluster(int team, int pathCost, int cx, int cy){
return getCluster(team, pathCost, cx + cy * cwidth);
}
/** @return a cluster at coordinates; can be null if not cluster was created yet*/
@Nullable Cluster getCluster(int team, int pathCost, int clusterIndex){
if(clusters == null) return null;
Cluster[][] dim1 = clusters[team];
if(dim1 == null) return null;
Cluster[] dim2 = dim1[pathCost];
//TODO: how can index out of bounds happen? || clusterIndex >= dim2.length
if(dim2 == null) return null;
return dim2[clusterIndex];
}
/** @return the cluster at specified coordinates; never null. */
Cluster getCreateCluster(int team, int pathCost, int cx, int cy){
return getCreateCluster(team, pathCost, cx + cy * cwidth);
}
/** @return the cluster at specified coordinates; never null. */
Cluster getCreateCluster(int team, int pathCost, int clusterIndex){
Cluster result = getCluster(team, pathCost, clusterIndex);
if(result == null){
return updateCluster(team, pathCost, clusterIndex % cwidth, clusterIndex / cwidth);
}else{
return result;
}
}
Cluster updateCluster(int team, int pathCost, int cx, int cy){
//TODO: what if clusters are null for thread visibility reasons?
Cluster[][] dim1 = clusters[team];
if(dim1 == null){
dim1 = clusters[team] = new Cluster[Team.all.length][];
}
Cluster[] dim2 = dim1[pathCost];
if(dim2 == null){
dim2 = dim1[pathCost] = new Cluster[cwidth * cheight];
}
Cluster cluster = dim2[cy * cwidth + cx];
if(cluster == null){
cluster = dim2[cy * cwidth + cx] = new Cluster();
}else{
//reset data
for(var p : cluster.portals){
if(p != null){
p.clear();
}
}
}
PathCost cost = idToCost(pathCost);
for(int direction = 0; direction < 4; direction++){
int otherX = cx + Geometry.d4x(direction), otherY = cy + Geometry.d4y(direction);
//out of bounds, no portals in this direction
if(otherX < 0 || otherY < 0 || otherX >= cwidth || otherY >= cheight){
continue;
}
Cluster other = dim2[otherX + otherY * cwidth];
IntSeq portals;
if(other == null){
//create new portals at direction
portals = cluster.portals[direction] = new IntSeq(4);
}else{
//share portals with the other cluster
portals = cluster.portals[direction] = other.portals[(direction + 2) % 4];
//clear the portals, they're being recalculated now
portals.clear();
}
int addX = moveDirs[direction * 2], addY = moveDirs[direction * 2 + 1];
int
baseX = cx * clusterSize + offsets[direction * 2] * (clusterSize - 1),
baseY = cy * clusterSize + offsets[direction * 2 + 1] * (clusterSize - 1),
nextBaseX = baseX + Geometry.d4[direction].x,
nextBaseY = baseY + Geometry.d4[direction].y;
int lastPortal = -1;
boolean prevSolid = true;
for(int i = 0; i < clusterSize; i++){
int x = baseX + addX * i, y = baseY + addY * i;
//scan for portals
if(solid(team, cost, x, y) || solid(team, cost, nextBaseX + addX * i, nextBaseY + addY * i)){
int previous = i - 1;
//hit a wall, create portals between the two points
if(!prevSolid && previous >= lastPortal){
//portals are an inclusive range
portals.add(Point2.pack(previous, lastPortal));
}
prevSolid = true;
}else{
//empty area encountered, mark the location of portal start
if(prevSolid){
lastPortal = i;
}
prevSolid = false;
}
}
//at the end of the loop, close any un-initialized portals; this is copy pasted code
int previous = clusterSize - 1;
if(!prevSolid && previous >= lastPortal){
//portals are an inclusive range
portals.add(Point2.pack(previous, lastPortal));
}
}
updateInnerEdges(team, cost, cx, cy, cluster);
return cluster;
}
void updateInnerEdges(int team, int cost, int cx, int cy, Cluster cluster){
updateInnerEdges(team, idToCost(cost), cx, cy, cluster);
}
void updateInnerEdges(int team, PathCost cost, int cx, int cy, Cluster cluster){
int minX = cx * clusterSize, minY = cy * clusterSize, maxX = Math.min(minX + clusterSize - 1, wwidth - 1), maxY = Math.min(minY + clusterSize - 1, wheight - 1);
usedEdges.clear();
//clear all connections, since portals changed, they need to be recomputed.
cluster.portalConnections = new LongSeq[4][];
for(int direction = 0; direction < 4; direction++){
var portals = cluster.portals[direction];
if(portals == null) continue;
int addX = moveDirs[direction * 2], addY = moveDirs[direction * 2 + 1];
for(int i = 0; i < portals.size; i++){
usedEdges.add(Point2.pack(direction, i));
int
portal = portals.items[i],
from = Point2.x(portal), to = Point2.y(portal),
average = (from + to) / 2,
x = (addX * average + cx * clusterSize + offsets[direction * 2] * (clusterSize - 1)),
y = (addY * average + cy * clusterSize + offsets[direction * 2 + 1] * (clusterSize - 1));
for(int otherDir = 0; otherDir < 4; otherDir++){
var otherPortals = cluster.portals[otherDir];
if(otherPortals == null) continue;
for(int j = 0; j < otherPortals.size; j++){
if(!usedEdges.contains(Point2.pack(otherDir, j))){
int
other = otherPortals.items[j],
otherFrom = Point2.x(other), otherTo = Point2.y(other),
otherAverage = (otherFrom + otherTo) / 2,
ox = cx * clusterSize + offsets[otherDir * 2] * (clusterSize - 1),
oy = cy * clusterSize + offsets[otherDir * 2 + 1] * (clusterSize - 1),
otherX = (moveDirs[otherDir * 2] * otherAverage + ox),
otherY = (moveDirs[otherDir * 2 + 1] * otherAverage + oy);
//duplicate portal; should never happen.
if(Point2.pack(x, y) == Point2.pack(otherX, otherY)){
continue;
}
float connectionCost = innerAstar(
team, cost,
minX, minY, maxX, maxY,
x + y * wwidth,
otherX + otherY * wwidth,
(moveDirs[otherDir * 2] * otherFrom + ox),
(moveDirs[otherDir * 2 + 1] * otherFrom + oy),
(moveDirs[otherDir * 2] * otherTo + ox),
(moveDirs[otherDir * 2 + 1] * otherTo + oy)
);
if(connectionCost != -1f){
if(cluster.portalConnections[direction] == null) cluster.portalConnections[direction] = new LongSeq[cluster.portals[direction].size];
if(cluster.portalConnections[otherDir] == null) cluster.portalConnections[otherDir] = new LongSeq[cluster.portals[otherDir].size];
if(cluster.portalConnections[direction][i] == null) cluster.portalConnections[direction][i] = new LongSeq(8);
if(cluster.portalConnections[otherDir][j] == null) cluster.portalConnections[otherDir][j] = new LongSeq(8);
//TODO: can there be duplicate edges??
cluster.portalConnections[direction][i].add(IntraEdge.get(otherDir, j, connectionCost));
cluster.portalConnections[otherDir][j].add(IntraEdge.get(direction, i, connectionCost));
}
}
}
}
}
}
}
//distance heuristic: manhattan
private static float heuristic(int a, int b){
int x = a % wwidth, x2 = b % wwidth, y = a / wwidth, y2 = b / wwidth;
return Math.abs(x - x2) + Math.abs(y - y2);
}
private static int tcost(int team, PathCost cost, int tilePos){
return cost.getCost(team, pathfinder.tiles[tilePos]);
}
private static float tileCost(int team, PathCost type, int a, int b){
//currently flat cost
return cost(team, type, b);
}
/** @return -1 if no path was found */
float innerAstar(int team, PathCost cost, int minX, int minY, int maxX, int maxY, int startPos, int goalPos, int goalX1, int goalY1, int goalX2, int goalY2){
var frontier = innerFrontier;
var costs = innerCosts;
frontier.clear();
costs.clear();
//TODO: this can be faster and more memory efficient by making costs a NxN array... probably?
costs.put(startPos, 0);
frontier.add(startPos, 0);
if(goalX2 < goalX1){
int tmp = goalX1;
goalX1 = goalX2;
goalX2 = tmp;
}
if(goalY2 < goalY1){
int tmp = goalY1;
goalY1 = goalY2;
goalY2 = tmp;
}
while(frontier.size > 0){
int current = frontier.poll();
int cx = current % wwidth, cy = current / wwidth;
//found the goal (it's in the portal rectangle)
if((cx >= goalX1 && cy >= goalY1 && cx <= goalX2 && cy <= goalY2) || current == goalPos){
return costs.get(current);
}
for(Point2 point : Geometry.d4){
int newx = cx + point.x, newy = cy + point.y;
int next = newx + wwidth * newy;
if(newx > maxX || newy > maxY || newx < minX || newy < minY || tcost(team, cost, next) == impassable) continue;
float add = tileCost(team, cost, current, next);
if(add < 0) continue;
float newCost = costs.get(current) + add;
if(newCost < costs.get(next, Float.POSITIVE_INFINITY)){
costs.put(next, newCost);
float priority = newCost + heuristic(next, goalPos);
frontier.add(next, priority);
}
}
}
return -1f;
}
int makeNodeIndex(int cx, int cy, int dir, int portal){
//to make sure there's only one way to refer to each node, the direction must be 0 or 1 (referring to portals on the top or right edge)
//direction can only be 2 if cluster X is 0 (left edge of map)
if(dir == 2 && cx != 0){
dir = 0;
cx --;
}
//direction can only be 3 if cluster Y is 0 (bottom edge of map)
if(dir == 3 && cy != 0){
dir = 1;
cy --;
}
return NodeIndex.get(cx + cy * cwidth, dir, portal);
}
//uses A* to find the closest node index to specified coordinates
//this node is used in cluster A*
/** @return MAX_VALUE if no node is found */
private int findClosestNode(int team, int pathCost, int tileX, int tileY){
int cx = tileX / clusterSize, cy = tileY / clusterSize;
if(cx < 0 || cy < 0 || cx >= cwidth || cy >= cheight){
return Integer.MAX_VALUE;
}
PathCost cost = idToCost(pathCost);
Cluster cluster = getCreateCluster(team, pathCost, cx, cy);
int minX = cx * clusterSize, minY = cy * clusterSize, maxX = Math.min(minX + clusterSize - 1, wwidth - 1), maxY = Math.min(minY + clusterSize - 1, wheight - 1);
int bestPortalPair = Integer.MAX_VALUE;
float bestCost = Float.MAX_VALUE;
//A* to every node, find the best one (I know there's a better algorithm for this, probably dijkstra)
for(int dir = 0; dir < 4; dir++){
var portals = cluster.portals[dir];
if(portals == null) continue;
for(int j = 0; j < portals.size; j++){
int
other = portals.items[j],
otherFrom = Point2.x(other), otherTo = Point2.y(other),
otherAverage = (otherFrom + otherTo) / 2,
ox = cx * clusterSize + offsets[dir * 2] * (clusterSize - 1),
oy = cy * clusterSize + offsets[dir * 2 + 1] * (clusterSize - 1),
otherX = (moveDirs[dir * 2] * otherAverage + ox),
otherY = (moveDirs[dir * 2 + 1] * otherAverage + oy);
float connectionCost = innerAstar(
team, cost,
minX, minY, maxX, maxY,
tileX + tileY * wwidth,
otherX + otherY * wwidth,
(moveDirs[dir * 2] * otherFrom + ox),
(moveDirs[dir * 2 + 1] * otherFrom + oy),
(moveDirs[dir * 2] * otherTo + ox),
(moveDirs[dir * 2 + 1] * otherTo + oy)
);
//better cost found, update and return
if(connectionCost != -1f && connectionCost < bestCost){
bestPortalPair = Point2.pack(dir, j);
bestCost = connectionCost;
}
}
}
if(bestPortalPair != Integer.MAX_VALUE){
return makeNodeIndex(cx, cy, Point2.x(bestPortalPair), Point2.y(bestPortalPair));
}
return Integer.MAX_VALUE;
}
//distance heuristic: manhattan
private float clusterNodeHeuristic(int team, int pathCost, int nodeA, int nodeB){
int
clusterA = NodeIndex.cluster(nodeA),
dirA = NodeIndex.dir(nodeA),
portalA = NodeIndex.portal(nodeA),
clusterB = NodeIndex.cluster(nodeB),
dirB = NodeIndex.dir(nodeB),
portalB = NodeIndex.portal(nodeB),
rangeA = getCreateCluster(team, pathCost, clusterA).portals[dirA].items[portalA],
rangeB = getCreateCluster(team, pathCost, clusterB).portals[dirB].items[portalB];
float
averageA = (Point2.x(rangeA) + Point2.y(rangeA)) / 2f,
x1 = (moveDirs[dirA * 2] * averageA + (clusterA % cwidth) * clusterSize + offsets[dirA * 2] * (clusterSize - 1) + nextOffsets[dirA * 2] / 2f),
y1 = (moveDirs[dirA * 2 + 1] * averageA + (clusterA / cwidth) * clusterSize + offsets[dirA * 2 + 1] * (clusterSize - 1) + nextOffsets[dirA * 2 + 1] / 2f),
averageB = (Point2.x(rangeB) + Point2.y(rangeB)) / 2f,
x2 = (moveDirs[dirB * 2] * averageB + (clusterB % cwidth) * clusterSize + offsets[dirB * 2] * (clusterSize - 1) + nextOffsets[dirB * 2] / 2f),
y2 = (moveDirs[dirB * 2 + 1] * averageB + (clusterB / cwidth) * clusterSize + offsets[dirB * 2 + 1] * (clusterSize - 1) + nextOffsets[dirB * 2 + 1] / 2f);
return Math.abs(x1 - x2) + Math.abs(y1 - y2);
}
@Nullable IntSeq clusterAstar(PathRequest request, int pathCost, int startNodeIndex, int endNodeIndex){
var result = request.resultPath;
if(startNodeIndex == endNodeIndex){
result.clear();
result.add(startNodeIndex);
return result;
}
var team = request.team;
if(request.costs == null) request.costs = new IntFloatMap();
if(request.cameFrom == null) request.cameFrom = new IntIntMap();
if(request.frontier == null) request.frontier = new PathfindQueue();
//note: these are NOT cleared, it is assumed that this function cleans up after itself at the end
//is this a good idea? don't know, might hammer the GC with unnecessary objects too
var costs = request.costs;
var cameFrom = request.cameFrom;
var frontier = request.frontier;
cameFrom.put(startNodeIndex, startNodeIndex);
costs.put(startNodeIndex, 0);
frontier.add(startNodeIndex, 0);
boolean foundEnd = false;
while(frontier.size > 0){
int current = frontier.poll();
if(current == endNodeIndex){
foundEnd = true;
break;
}
int cluster = NodeIndex.cluster(current), dir = NodeIndex.dir(current), portal = NodeIndex.portal(current);
int cx = cluster % cwidth, cy = cluster / cwidth;
//invalid cluster index (TODO: how?)
if(cx >= cwidth || cy >= cheight || cx < 0 || cy < 0) continue;
Cluster clust = getCreateCluster(team, pathCost, cluster);
LongSeq innerCons = clust.portalConnections[dir] == null || portal >= clust.portalConnections[dir].length ? null : clust.portalConnections[dir][portal];
//edges for the cluster the node is 'in'
if(innerCons != null){
checkEdges(request, team, pathCost, current, endNodeIndex, cx, cy, innerCons);
}
//edges that this node 'faces' from the other side
int nextCx = cx + Geometry.d4[dir].x, nextCy = cy + Geometry.d4[dir].y;
if(nextCx >= 0 && nextCy >= 0 && nextCx < cwidth && nextCy < cheight){
Cluster nextCluster = getCreateCluster(team, pathCost, nextCx, nextCy);
int relativeDir = (dir + 2) % 4;
LongSeq outerCons = nextCluster.portalConnections[relativeDir] == null || nextCluster.portalConnections[relativeDir].length <= portal ? null : nextCluster.portalConnections[relativeDir][portal];
if(outerCons != null){
checkEdges(request, team, pathCost, current, endNodeIndex, nextCx, nextCy, outerCons);
}
}
}
//null them out, so they get GC'ed later
//there's no reason to keep them around and waste memory, since this path may never be recalculated
request.costs = null;
request.cameFrom = null;
request.frontier = null;
if(foundEnd){
result.clear();
int cur = endNodeIndex;
while(cur != startNodeIndex){
result.add(cur);
cur = cameFrom.get(cur);
}
result.reverse();
return result;
}
return null;
}
private void checkEdges(PathRequest request, int team, int pathCost, int current, int goal, int cx, int cy, LongSeq connections){
for(int i = 0; i < connections.size; i++){
long con = connections.items[i];
float cost = IntraEdge.cost(con);
int otherDir = IntraEdge.dir(con), otherPortal = IntraEdge.portal(con);
int next = makeNodeIndex(cx, cy, otherDir, otherPortal);
float newCost = request.costs.get(current) + cost;
if(newCost < request.costs.get(next, Float.POSITIVE_INFINITY)){
request.costs.put(next, newCost);
request.frontier.add(next, newCost + clusterNodeHeuristic(team, pathCost, next, goal));
request.cameFrom.put(next, current);
}
}
}
private void updateFields(FieldCache cache, long nsToRun){
var frontier = cache.frontier;
var fields = cache.fields;
var goalPos = cache.goalPos;
var pcost = cache.cost;
var team = cache.team;
long start = Time.nanos();
int counter = 0;
//actually do the flow field part
while(frontier.size > 0){
int tile = frontier.removeLast();
int baseX = tile % wwidth, baseY = tile / wwidth;
int curWeightIndex = (baseX / clusterSize) + (baseY / clusterSize) * cwidth;
//TODO: how can this be null??? serious problem!
int[] curWeights = fields.get(curWeightIndex);
if(curWeights == null) continue;
int cost = curWeights[baseX % clusterSize + ((baseY % clusterSize) * clusterSize)];
if(cost != impassable){
for(Point2 point : Geometry.d4){
int
dx = baseX + point.x, dy = baseY + point.y,
clx = dx / clusterSize, cly = dy / clusterSize;
if(clx < 0 || cly < 0 || dx >= wwidth || dy >= wheight) continue;
int nextWeightIndex = clx + cly * cwidth;
int[] weights = nextWeightIndex == curWeightIndex ? curWeights : fields.get(nextWeightIndex);
//out of bounds; not allowed to move this way because no weights were registered here
if(weights == null) continue;
int newPos = tile + point.x + point.y * wwidth;
//can't move back to the goal
if(newPos == goalPos) continue;
if(dx - clx * clusterSize < 0 || dy - cly * clusterSize < 0) continue;
int newPosArray = (dx - clx * clusterSize) + (dy - cly * clusterSize) * clusterSize;
int otherCost = pcost.getCost(team, pathfinder.tiles[newPos]);
int oldCost = weights[newPosArray];
//a cost of 0 means uninitialized, OR it means we're at the goal position, but that's handled above
if((oldCost == 0 || oldCost > cost + otherCost) && otherCost != impassable){
frontier.addFirst(newPos);
weights[newPosArray] = cost + otherCost;
}
}
}
//every N iterations, check the time spent - this prevents extra calls to nano time, which itself is slow
if(nsToRun >= 0 && (counter++) >= updateStepInterval){
counter = 0;
if(Time.timeSinceNanos(start) >= nsToRun){
return;
}
}
}
}
private void addFlowCluster(FieldCache cache, int cluster, boolean addingFrontier){
addFlowCluster(cache, cluster % cwidth, cluster / cwidth, addingFrontier);
}
private void addFlowCluster(FieldCache cache, int cx, int cy, boolean addingFrontier){
//out of bounds
if(cx < 0 || cy < 0 || cx >= cwidth || cy >= cheight) return;
var fields = cache.fields;
int key = cx + cy * cwidth;
if(!fields.containsKey(key)){
fields.put(key, new int[clusterSize * clusterSize]);
if(addingFrontier){
for(int dir = 0; dir < 4; dir++){
int ox = cx + nextOffsets[dir * 2], oy = cy + nextOffsets[dir * 2 + 1];
if(ox < 0 || oy < 0 || ox >= cwidth || oy >= cheight) continue;
var otherField = fields.get(ox + oy * cwidth);
if(otherField == null) continue;
int
relOffset = (dir + 2) % 4,
movex = moveDirs[relOffset * 2],
movey = moveDirs[relOffset * 2 + 1],
otherx1 = offsets[relOffset * 2] * (clusterSize - 1),
othery1 = offsets[relOffset * 2 + 1] * (clusterSize - 1);
//scan the edge of the cluster
for(int i = 0; i < clusterSize; i++){
int x = otherx1 + movex * i, y = othery1 + movey * i;
//check to make sure it's not 0 (uninitialized flowfield data)
if(otherField[x + y * clusterSize] > 0){
int worldX = x + ox * clusterSize, worldY = y + oy * clusterSize;
//add the world-relative position to the frontier, so it recalculates
cache.frontier.addFirst(worldX + worldY * wwidth);