-
Notifications
You must be signed in to change notification settings - Fork 85
/
CustomPathFind.cs
4436 lines (3992 loc) · 198 KB
/
CustomPathFind.cs
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
namespace TrafficManager.Custom.PathFinding {
using ColossalFramework.Math;
using ColossalFramework.UI;
using ColossalFramework;
using CSUtil.Commons;
using System.Diagnostics;
using System.Reflection;
using System.Threading;
using System;
using TrafficManager.API.Manager;
using TrafficManager.API.Traffic.Data;
using TrafficManager.API.Traffic.Enums;
using TrafficManager.Manager.Impl;
using TrafficManager.Manager;
using TrafficManager.State;
using UnityEngine;
using TrafficManager.Util;
using TrafficManager.Util.Extensions;
using TrafficManager.TrafficLight.Impl;
#if DEBUG
using System.Collections.Generic;
using State.ConfigData;
#endif
/// <summary>
/// This replaces game PathFind class
/// This is ALL targets except Benchmark
/// </summary>
public class CustomPathFind : PathFind {
private const float BYTE_TO_FLOAT_OFFSET_CONVERSION_FACTOR = Constants.BYTE_TO_FLOAT_SCALE;
private const float TICKET_COST_CONVERSION_FACTOR =
BYTE_TO_FLOAT_OFFSET_CONVERSION_FACTOR * 0.0001f;
#if ROUTING
private readonly RoutingManager routingManager = RoutingManager.Instance;
#endif
#if JUNCTIONRESTRICTIONS
private readonly JunctionRestrictionsManager junctionManager =
JunctionRestrictionsManager.Instance;
#endif
#if VEHICLERESTRICTIONS
private readonly VehicleRestrictionsManager vehicleRestrictionsManager =
VehicleRestrictionsManager.Instance;
#endif
#if SPEEDLIMITS
private readonly SpeedLimitManager speedLimitManager = SpeedLimitManager.Instance;
#endif
#if CUSTOMTRAFFICLIGHTS
private readonly CustomSegmentLightsManager customTrafficLightsManager =
CustomSegmentLightsManager.Instance;
#endif
#if ADVANCEDAI && ROUTING
private readonly TrafficMeasurementManager trafficMeasurementManager =
TrafficMeasurementManager.Instance;
#endif
//Cached value (vanilla uses property to access it)
private VehicleInfo.VehicleCategory vehicleCategory_;
private GlobalConfig globalConf_;
private SavedGameOptions savedGameOptions_;
private struct BufferItem {
public PathUnit.Position Position;
public float ComparisonValue;
public float MethodDistance;
public float Duration;
public uint LaneId;
public NetInfo.Direction Direction;
public NetInfo.LaneType LanesUsed;
public VehicleInfo.VehicleType VehiclesUsed;
#if ADVANCEDAI && ROUTING
public float TrafficRand;
#endif
public override string ToString() {
return "BufferItem {\n" +
$"\tposition=(s#({Position.m_segment}), l#({Position.m_lane}), o#({Position.m_offset}))\n" +
$"\tlaneID={LaneId}\n" +
$"\tcomparisonValue={ComparisonValue}\n" +
$"\tmethodDistance={MethodDistance}\n" +
$"\tduration={Duration}\n" +
$"\tdirection={Direction}\n" +
$"\tlanesUsed={LanesUsed}\n" +
$"\tvehiclesUsed={VehiclesUsed}\n" +
#if ADVANCEDAI && ROUTING
$"\ttrafficRand={TrafficRand}\n" +
#endif
"}";
}
}
// private stock fields
private Array32<PathUnit> pathUnits_;
private uint queueFirst_;
private uint queueLast_;
private uint calculating_;
private object queueLock_;
private Thread customPathFindThread_;
private bool terminated_;
public bool IsAvailable => customPathFindThread_.IsAlive;
// stock fields
public ThreadProfiler m_pathfindProfiler;
private object bufferLock_;
private int bufferMinPos_;
private int bufferMaxPos_;
private uint[] laneLocation_;
private PathUnit.Position[] laneTarget_;
private BufferItem[] buffer_;
private int[] bufferMin_;
private int[] bufferMax_;
private float maxLength_;
private uint startLaneA_;
private uint startLaneB_;
private uint endLaneA_;
private uint endLaneB_;
private uint vehicleLane_;
private byte startOffsetA_;
private byte startOffsetB_;
private byte vehicleOffset_;
private NetSegment.Flags carBanMask_;
private bool ignoreBlocked_;
private bool stablePath_;
private bool randomParking_;
private bool transportVehicle_;
private bool ignoreCost_;
private NetSegment.Flags disableMask_;
private Randomizer pathRandomizer_;
private uint pathFindIndex_;
private NetInfo.LaneType laneTypes_;
private VehicleInfo.VehicleType vehicleTypes_;
// custom fields
private PathUnitQueueItem queueItem_;
/// <summary>
/// Contains allowed extVehicle types, in normal conditions just QueueIten.vehicleType,
/// when path may include CargoVehicle lanes then it contains also respective cargo vehicle types
/// </summary>
private ExtVehicleType allowedPathVehicleTypes_;
private bool isHeavyVehicle_;
private bool debugLog_; // this will be false in non-Debug
#if DEBUG
public uint m_failedPathFinds;
public uint m_succeededPathFinds;
private IDictionary<ushort, IList<ushort>> debugPositions_;
#endif
private ushort startSegmentA_;
private ushort startSegmentB_;
#if ROUTING
private bool isRoadVehicle_;
private bool isLaneArrowObeyingEntity_;
// private bool m_isLaneConnectionObeyingEntity;
#endif
private void Awake() {
Log.Info("Pathfinder logic: Using CustomPathFind_Current");
Type stockPathFindType = typeof(PathFind);
const BindingFlags FIELD_FLAGS = BindingFlags.NonPublic | BindingFlags.Instance;
queueFirst_ = 0;
queueLast_ = 0;
terminated_ = false;
calculating_ = 0u;
m_pathfindProfiler = new ThreadProfiler();
laneLocation_ = new uint[262144];
laneTarget_ = new PathUnit.Position[262144];
buffer_ = new BufferItem[65536];
bufferMin_ = new int[1024];
bufferMax_ = new int[1024];
queueLock_ = new object();
bufferLock_ = Singleton<PathManager>.instance.m_bufferLock;
pathUnits_ = Singleton<PathManager>.instance.m_pathUnits;
customPathFindThread_= new Thread(PathFindThread);
customPathFindThread_.Name = "Pathfind";
customPathFindThread_.Priority = SimulationManager.SIMULATION_PRIORITY;
customPathFindThread_.Start();
stockPathFindType.GetField("m_queueLock", FIELD_FLAGS) .SetValue(this, queueLock_);
stockPathFindType.GetField("m_pathFindThread", FIELD_FLAGS).SetValue(this, customPathFindThread_);
if (!customPathFindThread_.IsAlive) {
CODebugBase<LogChannel>.Error(LogChannel.Core, "Path find thread failed to start!");
}
}
private void OnDestroy() {
Log.Info("Destroing CustomPathFind");
lock (queueLock_) {
terminated_ = true;
Monitor.PulseAll(queueLock_);
}
}
public new void WaitForAllPaths() {
while (!Monitor.TryEnter(queueLock_, SimulationManager.SYNCHRONIZE_TIMEOUT)) { }
try {
while ((queueFirst_ != 0U || calculating_ != 0U) && !terminated_)
Monitor.Wait(queueLock_);
} finally {
Monitor.Exit(queueLock_);
}
}
/// <summary>
/// Used internally to overwrite pathUnits array reference
/// </summary>
/// <param name="pathUnits"></param>
internal void SetPathUnits(Array32<PathUnit> pathUnits) {
pathUnits_ = pathUnits;
}
public new bool CalculatePath(uint unit, bool skipQueue) {
return ExtCalculatePath(unit, skipQueue);
}
private bool ExtCalculatePath(uint unit, bool skipQueue) {
if (!CustomPathManager._instance.AddPathReference(unit)) {
return false;
}
lock(queueLock_) {
if (skipQueue) {
if (queueLast_ == 0) {
queueLast_ = unit;
} else {
// NON-STOCK CODE START
CustomPathManager._instance.QueueItems[unit].nextPathUnitId = queueFirst_;
// NON-STOCK CODE END
// PathUnits.m_buffer[unit].m_nextPathUnit = queueFirst_; // stock code commented
}
queueFirst_ = unit;
} else {
if (queueLast_ == 0) {
queueFirst_ = unit;
} else {
// NON-STOCK CODE START
CustomPathManager._instance.QueueItems[queueLast_].nextPathUnitId = unit;
// NON-STOCK CODE END
// PathUnits.m_buffer[queueLast_].m_nextPathUnit = unit; // stock code commented
}
queueLast_ = unit;
}
pathUnits_.m_buffer[unit].m_pathFindFlags |= PathUnit.FLAG_CREATED;
m_queuedPathFindCount++;
Monitor.Pulse(queueLock_);
}
return true;
}
private void PathFindImplementation(uint unit, ref PathUnit data) {
globalConf_ = GlobalConfig.Instance; // NON-STOCK CODE
savedGameOptions_ = SavedGameOptions.Instance;
NetManager netManager = Singleton<NetManager>.instance;
laneTypes_ = (NetInfo.LaneType)pathUnits_.m_buffer[unit].m_laneTypes;
vehicleTypes_ = (VehicleInfo.VehicleType)pathUnits_.m_buffer[unit].m_vehicleTypes;
vehicleCategory_ = (VehicleInfo.VehicleCategory)pathUnits_.m_buffer[unit].m_vehicleCategories;
maxLength_ = pathUnits_.m_buffer[unit].m_length;
pathFindIndex_ = pathFindIndex_ + 1 & 0x7FFF;
pathRandomizer_ = new Randomizer(unit);
carBanMask_ = NetSegment.Flags.CarBan;
isHeavyVehicle_ =
(pathUnits_.m_buffer[unit].m_simulationFlags & PathUnit.FLAG_IS_HEAVY) !=
0; // NON-STOCK CODE (refactored)
if (isHeavyVehicle_) {
carBanMask_ |= NetSegment.Flags.HeavyBan;
}
if ((pathUnits_.m_buffer[unit].m_simulationFlags & PathUnit.FLAG_READY) != 0) {
carBanMask_ |= NetSegment.Flags.WaitingPath;
}
ignoreBlocked_ = (pathUnits_.m_buffer[unit].m_simulationFlags & PathUnit.FLAG_IGNORE_BLOCKED) != 0;
stablePath_ = (pathUnits_.m_buffer[unit].m_simulationFlags & PathUnit.FLAG_STABLE_PATH) != 0;
randomParking_ = (pathUnits_.m_buffer[unit].m_simulationFlags & PathUnit.FLAG_RANDOM_PARKING) != 0;
transportVehicle_ = (laneTypes_ & NetInfo.LaneType.TransportVehicle) != NetInfo.LaneType.None;
ignoreCost_ = stablePath_ ||
(pathUnits_.m_buffer[unit].m_simulationFlags &
PathUnit.FLAG_IGNORE_COST) != 0;
disableMask_ = NetSegment.Flags.Collapsed | NetSegment.Flags.PathFailed;
if ((pathUnits_.m_buffer[unit].m_simulationFlags & PathUnit.FLAG_IGNORE_FLOODED) == 0) {
disableMask_ |= NetSegment.Flags.Flooded;
}
allowedPathVehicleTypes_ = queueItem_.vehicleType;
if ((laneTypes_ & NetInfo.LaneType.Vehicle) != NetInfo.LaneType.None) {
laneTypes_ |= NetInfo.LaneType.TransportVehicle;
// allow mixed vehicle path when requested path is Vehicle + CargoVehicle (e.g.: CargoTruck and PostVanAI)
bool allowMixedCargoPath = (laneTypes_ & NetInfo.LaneType.CargoVehicle) != NetInfo.LaneType.None;
if (allowMixedCargoPath) {
allowedPathVehicleTypes_ |= VehicleTypesToMixedCargoExtVehicle(vehicleTypes_);
}
}
#if ROUTING
isRoadVehicle_ =
(queueItem_.vehicleType & ExtVehicleType.RoadVehicle) != ExtVehicleType.None;
isLaneArrowObeyingEntity_ =
(!savedGameOptions_.relaxedBusses || queueItem_.vehicleType != ExtVehicleType.Bus) &&
(vehicleTypes_ & LaneArrowManager.VEHICLE_TYPES) != VehicleInfo.VehicleType.None &&
(queueItem_.vehicleType & LaneArrowManager.EXT_VEHICLE_TYPES) != ExtVehicleType.None;
#if DEBUG
isLaneArrowObeyingEntity_ &= !savedGameOptions_.allRelaxed;
#endif
#endif
#if DEBUG
debugLog_ = DebugSwitch.PathFindingLog.Get()
&& (GlobalConfig.Instance.Debug.ApiExtVehicleType == ExtVehicleType.None
|| queueItem_.vehicleType == GlobalConfig.Instance.Debug.ApiExtVehicleType)
&& (DebugSettings.StartSegmentId == 0
|| data.m_position00.m_segment == DebugSettings.StartSegmentId
|| data.m_position02.m_segment == DebugSettings.StartSegmentId)
&& (DebugSettings.EndSegmentId == 0
|| data.m_position01.m_segment == DebugSettings.EndSegmentId
|| data.m_position03.m_segment == DebugSettings.EndSegmentId)
&& (DebugSettings.VehicleId == 0
|| queueItem_.vehicleId == DebugSettings.VehicleId);
if (debugLog_) {
debugPositions_ = new Dictionary<ushort, IList<ushort>>();
}
#endif
int posCount = pathUnits_.m_buffer[unit].m_positionCount & 0xF;
int vehiclePosIndicator = pathUnits_.m_buffer[unit].m_positionCount >> 4;
BufferItem bufferItemStartA = default(BufferItem);
if (data.m_position00.m_segment != 0 && posCount >= 1) {
startSegmentA_ = data.m_position00.m_segment; // NON-STOCK CODE
startLaneA_ = PathManager.GetLaneID(data.m_position00);
startOffsetA_ = data.m_position00.m_offset;
bufferItemStartA.LaneId = startLaneA_;
bufferItemStartA.Position = data.m_position00;
GetLaneDirection(
data.m_position00,
out bufferItemStartA.Direction,
out bufferItemStartA.LanesUsed,
out bufferItemStartA.VehiclesUsed);
bufferItemStartA.ComparisonValue = 0f;
bufferItemStartA.Duration = 0f;
} else {
startSegmentA_ = 0; // NON-STOCK CODE
startLaneA_ = 0u;
startOffsetA_ = 0;
}
BufferItem bufferItemStartB = default(BufferItem);
if (data.m_position02.m_segment != 0 && posCount >= 3) {
startSegmentB_ = data.m_position02.m_segment; // NON-STOCK CODE
startLaneB_ = PathManager.GetLaneID(data.m_position02);
startOffsetB_ = data.m_position02.m_offset;
bufferItemStartB.LaneId = startLaneB_;
bufferItemStartB.Position = data.m_position02;
GetLaneDirection(
data.m_position02,
out bufferItemStartB.Direction,
out bufferItemStartB.LanesUsed,
out bufferItemStartB.VehiclesUsed);
bufferItemStartB.ComparisonValue = 0f;
bufferItemStartB.Duration = 0f;
} else {
startSegmentB_ = 0; // NON-STOCK CODE
startLaneB_ = 0u;
startOffsetB_ = 0;
}
BufferItem bufferItemEndA = default(BufferItem);
if (data.m_position01.m_segment != 0 && posCount >= 2) {
endLaneA_ = PathManager.GetLaneID(data.m_position01);
bufferItemEndA.LaneId = endLaneA_;
bufferItemEndA.Position = data.m_position01;
GetLaneDirection(
data.m_position01,
out bufferItemEndA.Direction,
out bufferItemEndA.LanesUsed,
out bufferItemEndA.VehiclesUsed);
bufferItemEndA.MethodDistance = 0.01f;
bufferItemEndA.ComparisonValue = 0f;
bufferItemEndA.Duration = 0f;
} else {
endLaneA_ = 0u;
}
BufferItem bufferItemEndB = default(BufferItem);
if (data.m_position03.m_segment != 0 && posCount >= 4) {
endLaneB_ = PathManager.GetLaneID(data.m_position03);
bufferItemEndB.LaneId = endLaneB_;
bufferItemEndB.Position = data.m_position03;
GetLaneDirection(
data.m_position03,
out bufferItemEndB.Direction,
out bufferItemEndB.LanesUsed,
out bufferItemEndB.VehiclesUsed);
bufferItemEndB.MethodDistance = 0.01f;
bufferItemEndB.ComparisonValue = 0f;
bufferItemEndB.Duration = 0f;
} else {
endLaneB_ = 0u;
}
if (data.m_position11.m_segment != 0 && vehiclePosIndicator >= 1) {
vehicleLane_ = PathManager.GetLaneID(data.m_position11);
vehicleOffset_ = data.m_position11.m_offset;
} else {
vehicleLane_ = 0u;
vehicleOffset_ = 0;
}
#if DEBUG
bool detourMissing =
(vehicleTypes_ & (VehicleInfo.VehicleType.Car | VehicleInfo.VehicleType.Train |
VehicleInfo.VehicleType.Tram | VehicleInfo.VehicleType.Monorail |
VehicleInfo.VehicleType.Metro | VehicleInfo.VehicleType.Trolleybus)) != VehicleInfo.VehicleType.None &&
!queueItem_.queued;
if (detourMissing) {
Log.Warning("Path-finding for unhandled vehicle requested!");
}
if (debugLog_ || detourMissing) {
DebugLog(
unit,
"PathFindImplementation: Preparing calculation:\n" +
$"\tbufferItemStartA: segment={bufferItemStartA.Position.m_segment} " +
$"lane={bufferItemStartA.Position.m_lane} off={bufferItemStartA.Position.m_offset} " +
$"laneId={bufferItemStartA.LaneId}\n" +
$"\tbufferItemStartB: segment={bufferItemStartB.Position.m_segment} " +
$"lane={bufferItemStartB.Position.m_lane} " +
$"off={bufferItemStartB.Position.m_offset} " +
$"laneId={bufferItemStartB.LaneId}\n" +
$"\tbufferItemEndA: segment={bufferItemEndA.Position.m_segment} " +
$"lane={bufferItemEndA.Position.m_lane} off={bufferItemEndA.Position.m_offset} " +
$"laneId={bufferItemEndA.LaneId}\n" +
$"\tbufferItemEndB: segment={bufferItemEndB.Position.m_segment} " +
$"lane={bufferItemEndB.Position.m_lane} off={bufferItemEndB.Position.m_offset} " +
$"laneId={bufferItemEndB.LaneId}\n" +
$"\tvehicleItem: segment={data.m_position11.m_segment} " +
$"lane={data.m_position11.m_lane} off={data.m_position11.m_offset} " +
$"laneId={vehicleLane_} vehiclePosIndicator={vehiclePosIndicator}\n" +
"Properties:\n" +
$"\tm_maxLength={maxLength_}\n" +
$"\tm_startLaneA={startLaneA_}\n" +
$"\tm_startLaneB={startLaneB_}\n" +
$"\tm_endLaneA={endLaneA_}\n" +
$"\tm_endLaneB={endLaneB_}\n" +
$"\tm_startOffsetA={startOffsetA_}\n" +
$"\tm_startOffsetB={startOffsetB_}\n" +
$"\tm_vehicleLane={vehicleLane_}\n" +
$"\tm_vehicleOffset={vehicleOffset_}\n" +
$"\tm_carBanMask={carBanMask_}\n" +
$"\tm_disableMask={disableMask_}\n" +
$"\tm_ignoreBlocked={ignoreBlocked_}\n" +
$"\tm_stablePath={stablePath_}\n" +
$"\tm_randomParking={randomParking_}\n" +
$"\tm_transportVehicle={transportVehicle_}\n" +
$"\tm_ignoreCost={ignoreCost_}\n" +
$"\tm_pathFindIndex={pathFindIndex_}\n" +
$"\tm_laneTypes={laneTypes_}\n" +
$"\tm_vehicleTypes={vehicleTypes_}\n" +
$"\tm_queueItem={queueItem_}\n" +
$"\tm_isHeavyVehicle={isHeavyVehicle_}\n" +
$"\tm_failedPathFinds={m_failedPathFinds}\n" +
$"\tm_succeededPathFinds={m_succeededPathFinds}\n" +
$"\tm_startSegmentA={startSegmentA_}\n" +
$"\tm_startSegmentB={startSegmentB_}\n"
#if ROUTING
+ $"\tm_isRoadVehicle={isRoadVehicle_}\n"
+ $"\tm_isLaneArrowObeyingEntity={isLaneArrowObeyingEntity_}\n"
+ $"\tvehicleCategory={vehicleCategory_}"
#endif
);
}
#endif
BufferItem finalBufferItem = default(BufferItem);
byte startOffset = 0;
bufferMinPos_ = 0;
bufferMaxPos_ = -1;
if (pathFindIndex_ == 0) {
const uint NUM3 = 4294901760u;
for (int i = 0; i < 262144; i++) {
laneLocation_[i] = NUM3;
}
}
for (int j = 0; j < 1024; j++) {
bufferMin_[j] = 0;
bufferMax_[j] = -1;
}
if (bufferItemEndA.Position.m_segment != 0) {
bufferMax_[0]++;
buffer_[++bufferMaxPos_] = bufferItemEndA;
}
if (bufferItemEndB.Position.m_segment != 0) {
bufferMax_[0]++;
buffer_[++bufferMaxPos_] = bufferItemEndB;
}
bool canFindPath = false;
while (bufferMinPos_ <= bufferMaxPos_) {
int bufMin = bufferMin_[bufferMinPos_];
int bufMax = bufferMax_[bufferMinPos_];
if (bufMin > bufMax) {
bufferMinPos_++;
} else {
bufferMin_[bufferMinPos_] = bufMin + 1;
BufferItem candidateItem = buffer_[(bufferMinPos_ << 6) + bufMin];
if (candidateItem.Position.m_segment == bufferItemStartA.Position.m_segment &&
candidateItem.Position.m_lane == bufferItemStartA.Position.m_lane) {
if ((candidateItem.Direction & NetInfo.Direction.Forward) !=
NetInfo.Direction.None &&
candidateItem.Position.m_offset >= startOffsetA_) {
finalBufferItem = candidateItem;
startOffset = startOffsetA_;
canFindPath = true;
break;
}
if ((candidateItem.Direction & NetInfo.Direction.Backward) !=
NetInfo.Direction.None &&
candidateItem.Position.m_offset <= startOffsetA_) {
finalBufferItem = candidateItem;
startOffset = startOffsetA_;
canFindPath = true;
break;
}
}
if (candidateItem.Position.m_segment == bufferItemStartB.Position.m_segment &&
candidateItem.Position.m_lane == bufferItemStartB.Position.m_lane) {
if ((candidateItem.Direction & NetInfo.Direction.Forward) !=
NetInfo.Direction.None &&
candidateItem.Position.m_offset >= startOffsetB_) {
finalBufferItem = candidateItem;
startOffset = startOffsetB_;
canFindPath = true;
break;
}
if ((candidateItem.Direction & NetInfo.Direction.Backward) !=
NetInfo.Direction.None &&
candidateItem.Position.m_offset <= startOffsetB_) {
finalBufferItem = candidateItem;
startOffset = startOffsetB_;
canFindPath = true;
break;
}
}
ref NetSegment candidateItemPositionSegment = ref candidateItem.Position.m_segment.ToSegment();
ref NetLane candidateItemNetLane = ref candidateItem.LaneId.ToLane();
ushort startNodeId = candidateItemPositionSegment.m_startNode;
ref NetNode startNode = ref startNodeId.ToNode();
ushort endNodeId = candidateItemPositionSegment.m_endNode;
ref NetNode endNode = ref endNodeId.ToNode();
if ((candidateItem.Direction & NetInfo.Direction.Forward) !=
NetInfo.Direction.None) {
ProcessItemMain(
#if DEBUG
unit,
#endif
candidateItem,
ref candidateItemPositionSegment,
ref candidateItem.LaneId.ToLane(),
startNodeId,
ref startNode,
0,
false);
}
if ((candidateItem.Direction & NetInfo.Direction.Backward) !=
NetInfo.Direction.None) {
ProcessItemMain(
#if DEBUG
unit,
#endif
candidateItem,
ref candidateItemPositionSegment,
ref candidateItemNetLane,
endNodeId,
ref endNode,
255,
false);
}
int numIter = 0;
ushort specialNodeId = candidateItemNetLane.m_nodes;
if (specialNodeId == 0) {
continue;
}
bool nodesDisabled = ((startNode.m_flags | endNode.m_flags) & NetNode.Flags.Disabled) != NetNode.Flags.None;
while (specialNodeId != 0) {
ref NetNode specialNode = ref specialNodeId.ToNode();
NetInfo.Direction direction = NetInfo.Direction.None;
byte laneOffset = specialNode.m_laneOffset;
if (laneOffset <= candidateItem.Position.m_offset) {
direction |= NetInfo.Direction.Forward;
}
if (laneOffset >= candidateItem.Position.m_offset) {
direction |= NetInfo.Direction.Backward;
}
if ((candidateItem.Direction & direction) != NetInfo.Direction.None
&& (!nodesDisabled || (specialNode.m_flags & NetNode.Flags.Disabled) != NetNode.Flags.None)) {
#if DEBUG
if (debugLog_ && (DebugSettings.NodeId <= 0 || specialNodeId == DebugSettings.NodeId)) {
DebugLog(
unit,
"PathFindImplementation: Handling special node for " +
$"path unit {unit}, type {queueItem_.vehicleType}:\n" +
$"\tcandidateItem.Position.m_segment={candidateItem.Position.m_segment}\n" +
$"\tcandidateItem.Position.m_lane={candidateItem.Position.m_lane}\n" +
$"\tcandidateItem.m_laneID={candidateItem.LaneId}\n" +
$"\tspecialNodeId={specialNodeId}\n" +
$"\tstartNodeId={startNodeId}\n" +
$"\tendNodeId={endNodeId}\n");
}
#endif
ProcessItemMain(
#if DEBUG
unit,
#endif
candidateItem,
ref candidateItemPositionSegment,
ref candidateItemNetLane,
specialNodeId,
ref specialNode,
laneOffset,
true);
}
specialNodeId = specialNode.m_nextLaneNode;
if (++numIter == 32768) {
break;
}
}
}
}
if (!canFindPath) {
pathUnits_.m_buffer[unit].m_pathFindFlags |= PathUnit.FLAG_FAILED;
// NON-STOCK CODE START
#if DEBUG
++m_failedPathFinds;
if (!debugLog_) {
return;
}
DebugLog(unit, "PathFindImplementation: Path-find failed: Could not find path");
string reachableBuf = string.Empty;
string unreachableBuf = string.Empty;
// TODO: optimize: Building a list of positions is faster than string concat
foreach (KeyValuePair<ushort, IList<ushort>> e in debugPositions_) {
string buf = $"{e.Key} -> {e.Value.CollectionToString()}\n";
if (e.Value.Count <= 0) {
unreachableBuf += buf;
} else {
reachableBuf += buf;
}
}
DebugLog(
unit,
"PathFindImplementation: Reachability graph:\n== REACHABLE ==\n" +
reachableBuf + "\n== UNREACHABLE ==\n" + unreachableBuf);
#endif
// NON-STOCK CODE END
} else {
float duration =
laneTypes_ != NetInfo.LaneType.Pedestrian &&
(laneTypes_ & NetInfo.LaneType.Pedestrian) != NetInfo.LaneType.None
? finalBufferItem.Duration
: finalBufferItem.MethodDistance;
pathUnits_.m_buffer[unit].m_length = duration;
pathUnits_.m_buffer[unit].m_speed = (byte)Mathf.Clamp(
finalBufferItem.MethodDistance * 100f / Mathf.Max(
0.01f,
finalBufferItem.Duration),
0f,
255f);
pathUnits_.m_buffer[unit].m_laneTypes = (byte)finalBufferItem.LanesUsed;
pathUnits_.m_buffer[unit].m_vehicleTypes = (uint)finalBufferItem.VehiclesUsed;
uint currentPathUnitId = unit;
int currentItemPositionCount = 0;
int sumOfPositionCounts = 0;
PathUnit.Position currentPosition = finalBufferItem.Position;
if ((currentPosition.m_segment != bufferItemEndA.Position.m_segment ||
currentPosition.m_lane != bufferItemEndA.Position.m_lane ||
currentPosition.m_offset != bufferItemEndA.Position.m_offset) &&
(currentPosition.m_segment != bufferItemEndB.Position.m_segment ||
currentPosition.m_lane != bufferItemEndB.Position.m_lane ||
currentPosition.m_offset != bufferItemEndB.Position.m_offset)) {
if (startOffset != currentPosition.m_offset) {
PathUnit.Position position2 = currentPosition;
position2.m_offset = startOffset;
pathUnits_.m_buffer[currentPathUnitId].SetPosition(
currentItemPositionCount++,
position2);
}
pathUnits_.m_buffer[currentPathUnitId].SetPosition(
currentItemPositionCount++,
currentPosition);
currentPosition = laneTarget_[finalBufferItem.LaneId];
}
for (int k = 0; k < 262144; k++) {
pathUnits_.m_buffer[currentPathUnitId].SetPosition(
currentItemPositionCount++,
currentPosition);
if ((currentPosition.m_segment == bufferItemEndA.Position.m_segment &&
currentPosition.m_lane == bufferItemEndA.Position.m_lane &&
currentPosition.m_offset == bufferItemEndA.Position.m_offset) ||
(currentPosition.m_segment == bufferItemEndB.Position.m_segment &&
currentPosition.m_lane == bufferItemEndB.Position.m_lane &&
currentPosition.m_offset == bufferItemEndB.Position.m_offset))
{
pathUnits_.m_buffer[currentPathUnitId].m_positionCount =
(byte)currentItemPositionCount;
sumOfPositionCounts += currentItemPositionCount;
if (sumOfPositionCounts != 0) {
currentPathUnitId = pathUnits_.m_buffer[unit].m_nextPathUnit;
currentItemPositionCount = pathUnits_.m_buffer[unit].m_positionCount;
int numIter = 0;
while (currentPathUnitId != 0) {
pathUnits_.m_buffer[currentPathUnitId].m_length =
duration * (sumOfPositionCounts - currentItemPositionCount) /
sumOfPositionCounts;
currentItemPositionCount +=
pathUnits_.m_buffer[currentPathUnitId].m_positionCount;
currentPathUnitId =
pathUnits_.m_buffer[currentPathUnitId].m_nextPathUnit;
if (++numIter >= 262144) {
CODebugBase<LogChannel>.Error(
LogChannel.Core,
"Invalid list detected!\n" + Environment.StackTrace);
break;
}
}
}
pathUnits_.m_buffer[unit].m_pathFindFlags |= PathUnit.FLAG_READY;
// NON-STOCK CODE START
#if DEBUG
++m_succeededPathFinds;
if (debugLog_) {
DebugLog(unit, "PathFindImplementation: Path-find succeeded");
}
#endif
// NON-STOCK CODE END
return;
}
if (currentItemPositionCount == 12) {
uint createdPathUnitId;
lock(bufferLock_) {
if (!pathUnits_.CreateItem(out createdPathUnitId, ref pathRandomizer_)) {
pathUnits_.m_buffer[unit].m_pathFindFlags |= PathUnit.FLAG_FAILED;
// NON-STOCK CODE START
#if DEBUG
++m_failedPathFinds;
if (debugLog_) {
DebugLog(unit, "Path-finding failed: Could not create path unit");
}
#endif
// NON-STOCK CODE END
return;
}
pathUnits_.m_buffer[createdPathUnitId] = pathUnits_.m_buffer[currentPathUnitId];
pathUnits_.m_buffer[createdPathUnitId].m_referenceCount = 1;
pathUnits_.m_buffer[createdPathUnitId].m_pathFindFlags = PathUnit.FLAG_READY;
pathUnits_.m_buffer[currentPathUnitId].m_nextPathUnit = createdPathUnitId;
pathUnits_.m_buffer[currentPathUnitId].m_positionCount = (byte)currentItemPositionCount;
// (this is not accurate!)
pathUnits_.m_buffer[currentPathUnitId].m_laneTypes =
(byte)finalBufferItem.LanesUsed;
pathUnits_.m_buffer[currentPathUnitId].m_vehicleTypes =
(uint)finalBufferItem.VehiclesUsed;
sumOfPositionCounts += currentItemPositionCount;
Singleton<PathManager>.instance.m_pathUnitCount =
(int)(pathUnits_.ItemCount() - 1);
}
currentPathUnitId = createdPathUnitId;
currentItemPositionCount = 0;
}
uint laneId = PathManager.GetLaneID(currentPosition);
currentPosition = laneTarget_[laneId];
}
pathUnits_.m_buffer[unit].m_pathFindFlags |= PathUnit.FLAG_FAILED;
// NON-STOCK CODE START
#if DEBUG
++m_failedPathFinds;
if (debugLog_) {
DebugLog(unit, "Path-finding failed: Internal loop break error");
}
#endif
// NON-STOCK CODE END
}
}
[Conditional("DEBUG")]
private void DebugLog(uint unit, string message) {
Log._Debug(
$"PF T#({Thread.CurrentThread.ManagedThreadId}) IDX#({pathFindIndex_}):\n"
+ $"UNIT({unit})\n"
+ message);
}
[Conditional("DEBUG")]
private void DebugLog(uint unit, BufferItem item, string message) {
Log._Debug(
$"PF T#({Thread.CurrentThread.ManagedThreadId}) IDX#({pathFindIndex_}):\n"
+ $"UNIT({unit}): s#({item.Position.m_segment}), l#({item.Position.m_lane})\n"
+ $"ITEM({item})\n"
+ message);
}
[Conditional("DEBUG")]
private void DebugLog(uint unit, BufferItem item, ushort nextSegmentId, string message) {
Log._Debug(
$"PF T#({Thread.CurrentThread.ManagedThreadId}) IDX#({pathFindIndex_}):\n"
+ $"UNIT({unit}): s#({item.Position.m_segment}), l#({item.Position.m_lane}) -> " +
$"s#({nextSegmentId})\nITEM({item})\n"
+ message);
}
[Conditional("DEBUG")]
private void DebugLog(uint unit,
BufferItem item,
ushort nextSegmentId,
int nextLaneIndex,
uint nextLaneId,
string message) {
Log._Debug(
$"PF T#({Thread.CurrentThread.ManagedThreadId}) IDX#({pathFindIndex_}):\n"
+ $"UNIT({unit}): s#({item.Position.m_segment}), l#({item.Position.m_lane}) -> " +
$"s#({nextSegmentId}), l#({nextLaneIndex}), lid#({nextLaneId})\n"
+ $"ITEM({item})\n" + message);
}
// be aware:
// (1) path-finding works from target to start. the "next" segment is always the previous and the "previous" segment is always the next segment on the path!
// (2) when I use the term "lane index from outer" this means outer right lane for right-hand traffic systems and outer-left lane for left-hand traffic systems.
//
// main item processor
// 1
private void ProcessItemMain(
#if DEBUG
uint unitId,
#endif
BufferItem item,
ref NetSegment prevSegment,
ref NetLane prevLane,
ushort nextNodeId,
ref NetNode nextNode,
byte connectOffset,
bool isMiddle) {
#if DEBUG
bool isLogEnabled = debugLog_ &&
(DebugSettings.NodeId <= 0 || nextNodeId == DebugSettings.NodeId);
if (isLogEnabled) {
if (!debugPositions_.ContainsKey(item.Position.m_segment)) {
debugPositions_[item.Position.m_segment] = new List<ushort>();
}
}
if (isLogEnabled) {
DebugLog(
unitId,
item,
"ProcessItemMain called.\n" +
$"\tnextNodeId={nextNodeId}\n" +
$"\tconnectOffset={connectOffset}\n" +
$"\tisMiddle={isMiddle}");
}
#else
const bool isLogEnabled = false;
const uint unitId = 0;
#endif
NetManager netManager = Singleton<NetManager>.instance;
ushort prevSegmentId = item.Position.m_segment;
byte prevLaneIndex = item.Position.m_lane;
bool prevIsPedestrianLane = false;
bool prevIsBicycleLane = false;
bool prevIsCenterPlatform = false;
bool prevIsElevated = false;
#if ADVANCEDAI && ROUTING
// NON-STOCK CODE START
bool prevIsCarLane = false;
// NON-STOCK CODE END
#endif
int prevRelSimilarLaneIndex = 0;
// NON-STOCK CODE START
float prevMaxSpeed = 1f;
float prevLaneSpeed = 1f;
// NON-STOCK CODE END
NetInfo prevSegmentInfo = prevSegment.Info;
if (prevLaneIndex < prevSegmentInfo.m_lanes.Length) {
NetInfo.Lane prevLaneInfo = prevSegmentInfo.m_lanes[item.Position.m_lane];
prevIsPedestrianLane = prevLaneInfo.m_laneType == NetInfo.LaneType.Pedestrian;
prevIsBicycleLane = prevLaneInfo.m_laneType == NetInfo.LaneType.Vehicle &&
(prevLaneInfo.m_vehicleType & vehicleTypes_) ==
VehicleInfo.VehicleType.Bicycle;
prevIsCenterPlatform = prevLaneInfo.m_centerPlatform;
prevIsElevated = prevLaneInfo.m_elevated;
#if ADVANCEDAI && ROUTING
// NON-STOCK CODE START
prevIsCarLane =
(prevLaneInfo.m_laneType &
(NetInfo.LaneType.Vehicle | NetInfo.LaneType.TransportVehicle)) !=
NetInfo.LaneType.None &&
(prevLaneInfo.m_vehicleType & VehicleInfo.VehicleType.Car) !=
VehicleInfo.VehicleType.None;
// NON-STOCK CODE END
#endif
// NON-STOCK CODE START
#if SPEEDLIMITS
prevMaxSpeed = speedLimitManager.GetGameSpeedLimit(
prevSegmentId,
prevLaneIndex,
item.LaneId,
prevLaneInfo);
#else
prevMaxSpeed = prevLaneInfo.m_speedLimit;