Repository navigation
Expand file tree
/
Copy pathNavigationListHandler.cs
More file actions
3820 lines (3370 loc) · 163 KB
/
Copy pathNavigationListHandler.cs
File metadata and controls
3820 lines (3370 loc) · 163 KB
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
using Il2Cpp;
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
namespace DigimonNOAccess
{
/// <summary>
/// Provides categorized event/point-of-interest navigation for the current area.
/// Scans for NPCs, items, transitions, and enemies, then lets the player
/// cycle through categories and events via hotkeys with screen reader announcements.
/// </summary>
public class NavigationListHandler : IAccessibilityHandler
{
public int Priority => 998;
/// <summary>
/// Background handler - never owns the status announce.
/// </summary>
public bool IsOpen() => false;
/// <summary>
/// Background handler - never announces status.
/// </summary>
public void AnnounceStatus() { }
// Event categories
private enum EventCategory
{
NPCs,
Items,
Materials,
Quest,
Transitions,
Enemies,
Facilities
}
// Represents a single navigable point of interest
private class NavigationEvent
{
public string Name;
public Vector3 Position;
public GameObject Target;
public EventCategory Category;
public float DistanceToPlayer;
/// <summary>Completion flag set ID for quest items (from form 5 SSetFlagSetData). Checked via saved scenario flags.</summary>
public uint FlagSetId;
}
// Category order for cycling (only non-empty categories are used)
private static readonly EventCategory[] AllCategories = {
EventCategory.NPCs,
EventCategory.Items,
EventCategory.Materials,
EventCategory.Quest,
EventCategory.Transitions,
EventCategory.Enemies,
EventCategory.Facilities
};
// Event lists per category
private Dictionary<EventCategory, List<NavigationEvent>> _events = new Dictionary<EventCategory, List<NavigationEvent>>();
// Active (non-empty) categories for cycling
private List<EventCategory> _activeCategories = new List<EventCategory>();
// Current navigation state
private int _currentCategoryIndex = -1;
private int _currentEventIndex = 0;
private EventCategory _preferredCategory = EventCategory.NPCs; // Preserved across map changes
// Map change detection
private int _lastMapNo = -1;
private int _lastAreaNo = -1;
// Scan cooldown (don't scan every frame)
private float _lastScanTime = 0f;
private const float ScanInterval = 1.0f;
// Cached references
private PlayerCtrl _playerCtrl;
private NpcManager _npcManager;
private EnemyManager _enemyManager;
private float _lastSearchTime = 0f;
// Track if list has been built for current area
private bool _listBuilt = false;
// Track if async data has finished loading (items, NPCs, enemies load via coroutines)
private bool _itemsLoadComplete = false;
private bool _npcsLoadComplete = false;
private bool _enemiesLoadComplete = false;
// Continuous rescan after map change (objects load asynchronously)
private float _mapChangeTime = 0f;
private float _nextRescanTime = 0f;
private const float InitialScanDelay = 0.5f;
private const float RescanInterval = 0.5f;
private const float RescanDuration = 5.0f; // Keep rescanning for 5 seconds after map change
private bool _isRescanning = false;
private int _lastHookTrackedCount = 0; // Track AreaChangePatch state changes for transition rebuilds
// Track known GameObjects to avoid duplicate entries
private HashSet<GameObject> _knownTargets = new HashSet<GameObject>();
// Track NPC GameObjects that are actually facilities (to exclude from NPC list)
private HashSet<GameObject> _facilityNpcObjects = new HashSet<GameObject>();
// Cache for resolved quest item data: cmdBlock -> (item name, item ID, flag set ID)
private static Dictionary<string, (string name, uint itemId, uint flagSetId)> _questItemCache = new Dictionary<string, (string, uint, uint)>();
// Track field state to rescan after evolution/events
private bool _wasInField = false;
// Pathfinding beacon
private PathfindingBeacon _pathfindingBeacon;
private Vector3 _pathfindingDestination;
private Vector3 _pathfindingRawDestination; // Actual target position before NavMesh sampling
private GameObject _pathfindingTarget;
private float _lastPathRecalcTime;
private bool _isPathfinding;
private EventCategory _pathfindingCategory;
private const float PathRecalcInterval = 0.5f;
// Auto-walk state
private bool _autoWalkEnabled = false;
private bool _isAutoWalking = false;
private Vector3[] _autoWalkCorners;
private int _autoWalkCornerIndex;
private const float CornerReachDistance = 1.5f;
private const float FinalApproachDistance = 0.1f;
// Stuck detection: if player hasn't moved while auto-walking, they've arrived
private Vector3 _autoWalkCheckPosition;
private float _autoWalkCheckTime;
private const float StuckCheckInterval = 1.0f;
private const float StuckMovementThreshold = 0.3f;
private const float StuckArrivalDistance = 15f; // Within this range, stuck = arrived
// Obstacle avoidance: when stuck mid-path, find walkable detour to get around enemies/obstacles
private bool _isAvoidingObstacle;
private Vector3 _avoidanceDetourTarget;
private float _avoidanceStartTime;
private int _avoidanceAttempt; // Increments to alternate left/right
private const float AvoidanceTimeout = 10f; // Max seconds trying to reach detour point
// Virtual stick output for auto-walk (read by GamepadInputPatch)
public static bool AutoWalkActive { get; private set; }
public static float AutoWalkStickX { get; private set; }
public static float AutoWalkStickY { get; private set; }
public static float AutoWalkCameraStickX { get; private set; }
// Pitfall avoidance: EventTriggerScripts with PIT_ command blocks
private List<Vector3> _pitfallPositions = new List<Vector3>();
private const float PitfallAvoidanceRadius = 10f; // How far to route around pitfalls
// Evolution state (set by Main before Update)
private bool _evolutionActive = false;
public void SetEvolutionActive(bool active)
{
_evolutionActive = active;
}
public void Update()
{
// Find managers periodically
float currentTime = Time.time;
if (_playerCtrl == null || currentTime - _lastSearchTime > 2f)
{
_playerCtrl = UnityEngine.Object.FindObjectOfType<PlayerCtrl>();
_npcManager = UnityEngine.Object.FindObjectOfType<NpcManager>();
_enemyManager = UnityEngine.Object.FindObjectOfType<EnemyManager>();
_lastSearchTime = currentTime;
}
// Only work when player is in the field and in control
bool inField = IsPlayerInField();
if (!inField)
{
_wasInField = false;
// Pause pathfinding beacon audio when leaving the field.
if (_isPathfinding && _pathfindingBeacon != null && _pathfindingBeacon.IsActive)
_pathfindingBeacon.Stop();
// Auto-walk does NOT pause on its own. GamepadInputPatch reads
// AutoWalkActive from the game's own input path, which keeps running
// while this Update is short-circuited - so leaving the field mid-walk
// used to leave a stale stick value jammed on through battles, menus and
// events. Clear the injection flag here, but leave _isAutoWalking set so
// ResumePathfinding picks the route back up on return.
AutoWalkActive = false;
AutoWalkCameraStickX = 0;
return;
}
// Refresh lists when returning to field from any absence (battle, NPC talk,
// item pickup, facility, etc.) rather than polling every second while walking.
if (!_wasInField && _listBuilt)
{
// Any absence (battle, NPC talk, item pickup, etc.) - do additive rescan
// to catch newly activated quest triggers after accepting quests
_isRescanning = true;
_mapChangeTime = currentTime;
_nextRescanTime = currentTime + InitialScanDelay;
DebugLogger.Log("[NavList] Returned to field, rescanning (preserving lists)");
}
_wasInField = true;
// Check for map changes
CheckMapChange();
// During rescan period after map change, keep scanning for newly loaded objects
if (_isRescanning && currentTime >= _nextRescanTime)
{
RescanForNewObjects();
_nextRescanTime = currentTime + RescanInterval;
if (currentTime - _mapChangeTime > RescanDuration)
{
_isRescanning = false;
DebugLogger.Log($"[NavList] Rescan period ended. Final counts: " +
$"{_events[EventCategory.NPCs].Count} NPCs, " +
$"{_events[EventCategory.Items].Count} items, " +
$"{_events[EventCategory.Materials].Count} materials, " +
$"{_events[EventCategory.Quest].Count} quest, " +
$"{_events[EventCategory.Transitions].Count} transitions, " +
$"{_events[EventCategory.Enemies].Count} enemies, " +
$"{_events[EventCategory.Facilities].Count} facilities");
}
}
// Handle input
HandleInput();
// Update pathfinding beacon
if (_isPathfinding)
UpdatePathfinding();
}
/// <summary>
/// Check if the player is in the field (not in battle, not in menus, not in events).
/// Uses the player's actionState as the game's own movement check.
/// </summary>
private bool IsPlayerInField()
{
// Evolution plays on the field but disables items/transitions
if (_evolutionActive)
return false;
if (_playerCtrl == null) return false;
if (_playerCtrl.actionState != UnitCtrlBase.ActionState.ActionState_Idle)
return false;
if (GameStateService.IsInBattlePhase())
return false;
if (GameStateService.IsGamePaused())
return false;
return true;
}
/// <summary>
/// Detect when the player enters a new map/area and rebuild lists.
/// After map change, continuously rescans for 5 seconds since objects
/// load asynchronously via coroutines and appear at different times.
/// </summary>
private void CheckMapChange()
{
try
{
var mgm = MainGameManager.m_instance;
if (mgm == null) return;
int mapNo = mgm.mapNo;
int areaNo = mgm.areaNo;
if (mapNo != _lastMapNo || areaNo != _lastAreaNo)
{
_lastMapNo = mapNo;
_lastAreaNo = areaNo;
// Stop pathfinding on map change (target won't exist on new map)
if (_isPathfinding)
StopPathfinding(null);
// Reset for new map
_listBuilt = false;
_lastHookTrackedCount = 0;
_mapChangeTime = Time.time;
_nextRescanTime = Time.time + InitialScanDelay;
_isRescanning = true;
// Save preferred category before reset
var currentCat = GetCurrentCategory();
if (currentCat.HasValue)
_preferredCategory = currentCat.Value;
_currentEventIndex = 0;
_events.Clear();
_events[EventCategory.NPCs] = new List<NavigationEvent>();
_events[EventCategory.Items] = new List<NavigationEvent>();
_events[EventCategory.Materials] = new List<NavigationEvent>();
_events[EventCategory.Quest] = new List<NavigationEvent>();
_events[EventCategory.Transitions] = new List<NavigationEvent>();
_events[EventCategory.Enemies] = new List<NavigationEvent>();
_events[EventCategory.Facilities] = new List<NavigationEvent>();
_activeCategories.Clear();
_knownTargets.Clear();
_facilityNpcObjects.Clear();
_questItemCache.Clear();
_itemsLoadComplete = false;
_npcsLoadComplete = false;
_enemiesLoadComplete = false;
// Clear pitfall data from previous map
_pitfallPositions.Clear();
DebugLogger.Log($"[NavList] Map changed to {mapNo}/{areaNo}, will rescan for {RescanDuration}s");
}
// Initial build after delay
if (!_listBuilt && Time.time >= _nextRescanTime)
{
BuildLists();
_listBuilt = true;
_lastScanTime = Time.time;
_nextRescanTime = Time.time + RescanInterval;
}
}
catch (Exception ex)
{
DebugLogger.Log($"[NavList] CheckMapChange error: {ex.Message}");
}
}
/// <summary>
/// During the rescan period, look for newly spawned objects and add them to existing lists.
/// This catches NPCs, enemies, items, and transitions that load asynchronously.
/// </summary>
private void RescanForNewObjects()
{
if (_playerCtrl == null) return;
Vector3 playerPos = _playerCtrl.transform.position;
int newCount = 0;
// Scan facilities BEFORE NPCs so facility NPCs are excluded from NPC list
try
{
var rescanMgm = MainGameManager.m_instance;
// Strategy 1: EventTriggerManager dictionary + CSV (field areas)
var rescanEventTriggerMgr = rescanMgm?.m_EventTriggerMgr;
if (rescanEventTriggerMgr != null)
{
var triggerDict = rescanEventTriggerMgr.m_TriggerDictionary;
var placementData = rescanEventTriggerMgr.m_CsvbPlacementData;
if (triggerDict != null && placementData != null)
{
var enumerator = triggerDict.GetEnumerator();
while (enumerator.MoveNext())
{
var trigger = enumerator.Current.Value;
if (trigger == null || trigger.gameObject == null || !trigger.gameObject.activeInHierarchy)
continue;
if (_knownTargets.Contains(trigger.gameObject))
continue;
try
{
uint placementId = enumerator.Current.Key;
var npcData = HashIdSearchClass<ParameterPlacementNpc>.GetParam(placementData, placementId);
if (npcData == null) continue;
var facilityType = (MainGameManager.Facility)npcData.m_Facility;
if (facilityType == MainGameManager.Facility.None) continue;
string name = ResolveFacilityName(facilityType, npcData);
float dist = Vector3.Distance(playerPos, trigger.transform.position);
_events[EventCategory.Facilities].Add(new NavigationEvent
{
Name = name, Position = trigger.transform.position,
Target = trigger.gameObject, Category = EventCategory.Facilities,
DistanceToPlayer = dist
});
_knownTargets.Add(trigger.gameObject);
newCount++;
}
catch { }
}
}
}
// Strategy 2: NpcManager placement data (town facility NPCs)
if (_npcManager != null)
{
try
{
var placementList = _npcManager.m_placementNpcList;
if (placementList != null)
{
int placementCount = placementList.Count;
for (int i = 0; i < placementCount; i++)
{
try
{
var placement = placementList[i];
if (placement == null) continue;
var facilityType = (MainGameManager.Facility)placement.m_Facility;
if (facilityType == MainGameManager.Facility.None) continue;
uint placementId = placement.id;
NpcCtrl npcCtrl = null;
try { npcCtrl = _npcManager._GetNpcCtrlFromPlacementId(placementId); }
catch { }
if (npcCtrl == null || npcCtrl.gameObject == null || !npcCtrl.gameObject.activeInHierarchy)
continue;
if (_knownTargets.Contains(npcCtrl.gameObject))
continue;
string name = ResolveFacilityName(facilityType, placement);
float dist = Vector3.Distance(playerPos, npcCtrl.transform.position);
_events[EventCategory.Facilities].Add(new NavigationEvent
{
Name = name, Position = npcCtrl.transform.position,
Target = npcCtrl.gameObject, Category = EventCategory.Facilities,
DistanceToPlayer = dist
});
_knownTargets.Add(npcCtrl.gameObject);
_facilityNpcObjects.Add(npcCtrl.gameObject);
newCount++;
}
catch { }
}
}
}
catch { }
}
// Strategy 3: MapTriggerScript scan for fishing spots and toilets
var mapTriggers = UnityEngine.Object.FindObjectsOfType<MapTriggerScript>();
foreach (var trigger in mapTriggers)
{
if (trigger == null || trigger.gameObject == null || !trigger.gameObject.activeInHierarchy)
continue;
if (_knownTargets.Contains(trigger.gameObject))
continue;
string name = null;
if (trigger.enterID == MapTriggerManager.EVENT.Fishing)
name = "Fishing Spot";
else if (trigger.enterID == MapTriggerManager.EVENT.Toilet)
name = "Toilet";
if (name == null) continue;
float dist = Vector3.Distance(playerPos, trigger.transform.position);
_events[EventCategory.Facilities].Add(new NavigationEvent
{
Name = name, Position = trigger.transform.position,
Target = trigger.gameObject, Category = EventCategory.Facilities,
DistanceToPlayer = dist
});
_knownTargets.Add(trigger.gameObject);
newCount++;
}
}
catch (Exception ex)
{
DebugLogger.Log($"[NavList] Rescan Facilities error: {ex.Message}");
}
// Scan for new NPCs (excluding facility NPCs) - only if NPC data has finished loading
if (!_npcsLoadComplete)
{
try
{
var mgm = MainGameManager.m_instance;
if (mgm != null && mgm._IsLoadEndNpcPlacementData())
{
_npcsLoadComplete = true;
DebugLogger.Log("[NavList] NPC placement data load complete, scanning NPCs");
}
}
catch { }
}
try
{
if (_npcsLoadComplete && _npcManager != null && _npcManager.m_NpcCtrlArray != null)
{
foreach (var npc in _npcManager.m_NpcCtrlArray)
{
if (npc == null || npc.gameObject == null || !npc.gameObject.activeInHierarchy)
continue;
if (_knownTargets.Contains(npc.gameObject))
continue;
if (_facilityNpcObjects.Contains(npc.gameObject))
continue;
string name = GetNpcName(npc);
float dist = Vector3.Distance(playerPos, npc.transform.position);
_events[EventCategory.NPCs].Add(new NavigationEvent
{
Name = name, Position = npc.transform.position,
Target = npc.gameObject, Category = EventCategory.NPCs,
DistanceToPlayer = dist
});
_knownTargets.Add(npc.gameObject);
newCount++;
}
}
}
catch (Exception ex)
{
DebugLogger.Log($"[NavList] Rescan NPCs error: {ex.Message}");
}
// Scan for new items and materials (only if item data has finished loading)
if (!_itemsLoadComplete)
{
try
{
var mgm = MainGameManager.m_instance;
if (mgm != null && mgm._IsLoadEndItemPickPointData())
{
_itemsLoadComplete = true;
DebugLogger.Log("[NavList] Item pick point data load complete, scanning items");
}
}
catch { }
}
try
{
var itemManager = ItemPickPointManager.m_instance;
if (_itemsLoadComplete && itemManager != null && itemManager.m_itemPickPoints != null)
{
foreach (var point in itemManager.m_itemPickPoints)
{
if (point == null || point.gameObject == null)
continue;
if (!point.enableItemPickPoint)
continue;
if (_knownTargets.Contains(point.gameObject))
continue;
var category = GetItemCategory(point);
string name = GetItemName(point);
float dist = Vector3.Distance(playerPos, point.transform.position);
_events[category].Add(new NavigationEvent
{
Name = name, Position = point.transform.position,
Target = point.gameObject, Category = category,
DistanceToPlayer = dist
});
_knownTargets.Add(point.gameObject);
newCount++;
}
}
}
catch (Exception ex)
{
DebugLogger.Log($"[NavList] Rescan Items error: {ex.Message}");
}
// Rescan transitions - if AreaChangePatch hook count changed, rebuild from scratch
// (first scan may run before CSVB scripts fire EnableAreaChangeTrigger)
int currentHookCount = AreaChangePatch.TrackedCount;
if (currentHookCount != _lastHookTrackedCount)
{
// Hook state changed - remove old transition entries and rescan clean
foreach (var evt in _events[EventCategory.Transitions])
{
if (evt.Target != null)
_knownTargets.Remove(evt.Target);
}
_events[EventCategory.Transitions].Clear();
_lastHookTrackedCount = currentHookCount;
}
int transitionsBefore = _events[EventCategory.Transitions].Count;
ScanTransitions(playerPos);
newCount += _events[EventCategory.Transitions].Count - transitionsBefore;
// Scan for new enemies - only if enemy data has finished loading
if (!_enemiesLoadComplete)
{
try
{
var mgm = MainGameManager.m_instance;
if (mgm != null && mgm._IsLoadEndEnemyPlacementData())
{
_enemiesLoadComplete = true;
DebugLogger.Log("[NavList] Enemy placement data load complete, scanning enemies");
}
}
catch { }
}
try
{
if (_enemiesLoadComplete && _enemyManager != null && _enemyManager.m_EnemyCtrlArray != null)
{
foreach (var enemy in _enemyManager.m_EnemyCtrlArray)
{
if (!GameStateService.IsEnemyAlive(enemy))
continue;
if (_knownTargets.Contains(enemy.gameObject))
continue;
string name = GetEnemyName(enemy);
float dist = Vector3.Distance(playerPos, enemy.transform.position);
_events[EventCategory.Enemies].Add(new NavigationEvent
{
Name = name, Position = enemy.transform.position,
Target = enemy.gameObject, Category = EventCategory.Enemies,
DistanceToPlayer = dist
});
_knownTargets.Add(enemy.gameObject);
newCount++;
}
}
}
catch (Exception ex)
{
DebugLogger.Log($"[NavList] Rescan Enemies error: {ex.Message}");
}
// Scan for new quest triggers (EventTriggerScripts load asynchronously)
try
{
var eventTriggers = Resources.FindObjectsOfTypeAll<EventTriggerScript>();
var placementLookup = BuildPlacementLookup();
if (_debugQuestScan)
DebugLogger.Log($"[QuestRescan] Starting rescan: {eventTriggers.Count} triggers, {placementLookup.Count} placements");
foreach (var et in eventTriggers)
{
if (et == null || et.gameObject == null)
continue;
string goName = "?";
try { goName = et.gameObject.name; } catch { }
if (!et.gameObject.activeInHierarchy)
{
if (_debugQuestScan) DebugLogger.Log($"[QuestRescan] SKIP inactive: {goName} paramId={et.m_EventParamId}");
continue;
}
uint etParamId = 0;
try { etParamId = et.m_EventParamId; } catch { }
if (etParamId != 0 && EventTriggerPatch.IsDisabled(etParamId))
{
if (_debugQuestScan) DebugLogger.Log($"[QuestRescan] SKIP disabled: {goName} paramId={etParamId}");
continue;
}
if (_knownTargets.Contains(et.gameObject))
{
if (_debugQuestScan) DebugLogger.Log($"[QuestRescan] SKIP known: {goName}");
continue;
}
if (et.gameObject.GetComponent<NpcCtrl>() != null)
{
if (_debugQuestScan) DebugLogger.Log($"[QuestRescan] SKIP NPC: {goName}");
continue;
}
if (et.gameObject.GetComponent<EnemyCtrl>() != null)
{
if (_debugQuestScan) DebugLogger.Log($"[QuestRescan] SKIP enemy: {goName}");
continue;
}
string cmdBlock = null;
ParameterPlacementNpc placement = null;
if (placementLookup.TryGetValue(et.m_EventParamId, out placement))
cmdBlock = placement.m_CmdBlock;
if (string.IsNullOrEmpty(cmdBlock))
{
if (_debugQuestScan) DebugLogger.Log($"[QuestRescan] SKIP no cmdBlock: {goName} paramId={et.m_EventParamId}");
continue;
}
if (placement != null && (MainGameManager.Facility)placement.m_Facility != MainGameManager.Facility.None)
{
if (_debugQuestScan) DebugLogger.Log($"[QuestRescan] SKIP facility: {goName} cmd={cmdBlock}");
continue;
}
if (cmdBlock.StartsWith("VENDOR_") || cmdBlock.StartsWith("EVENT.") || cmdBlock.StartsWith("PIT"))
{
if (_debugQuestScan) DebugLogger.Log($"[QuestRescan] SKIP vendor/event/pit: {goName} cmd={cmdBlock}");
continue;
}
try
{
var eid = et.enterID;
if (eid == MapTriggerManager.EVENT.MapChange ||
eid == MapTriggerManager.EVENT.TownCamera ||
eid == MapTriggerManager.EVENT.Fishing ||
eid == MapTriggerManager.EVENT.Toilet)
{
if (_debugQuestScan) DebugLogger.Log($"[QuestRescan] SKIP enterID: {goName} cmd={cmdBlock} eid={eid}");
continue;
}
}
catch { }
if (_debugQuestScan) DebugLogger.Log($"[QuestRescan] Passed filters: {goName} cmd={cmdBlock} paramId={etParamId}");
if (cmdBlock.StartsWith("PICK_"))
{
var questInfo = ResolveQuestItem(cmdBlock);
string name = questInfo.name ?? "Quest Pickup";
uint flagSetId = questInfo.flagSetId;
if (_debugQuestScan) DebugLogger.Log($"[QuestRescan] PICK_ trigger: {goName} cmd={cmdBlock} name={name} flagSetId=0x{flagSetId:X}");
if (flagSetId != 0 && IsQuestFlagSet(flagSetId))
{
if (_debugQuestScan) DebugLogger.Log($"[QuestRescan] SKIP completed: {goName} flag=0x{flagSetId:X}");
continue;
}
// No acceptance check - show all uncompleted PICK_ items.
// The completion flag check above already filters finished quests.
float dist = Vector3.Distance(playerPos, et.transform.position);
if (_debugQuestScan) DebugLogger.Log($"[QuestRescan] ADDED PICK_: {goName} cmd={cmdBlock} name={name} dist={dist:F1}");
_events[EventCategory.Quest].Add(new NavigationEvent
{
Name = name, Position = et.transform.position,
Target = et.gameObject, Category = EventCategory.Quest,
DistanceToPlayer = dist, FlagSetId = flagSetId
});
}
else
{
uint completionFlag = GetCompletionFlagForCmdBlock(cmdBlock);
if (completionFlag != 0 && IsQuestFlagSet(completionFlag))
continue;
float dist = Vector3.Distance(playerPos, et.transform.position);
if (_debugQuestScan) DebugLogger.Log($"[QuestRescan] ADDED non-PICK: {goName} cmd={cmdBlock} flag=0x{completionFlag:X} dist={dist:F1}");
_events[EventCategory.Quest].Add(new NavigationEvent
{
Name = "Quest Event", Position = et.transform.position,
Target = et.gameObject, Category = EventCategory.Quest,
DistanceToPlayer = dist, FlagSetId = completionFlag
});
}
_knownTargets.Add(et.gameObject);
newCount++;
}
}
catch (Exception ex)
{
DebugLogger.Log($"[NavList] Rescan Quest error: {ex.Message}");
}
// Rescan for pitfalls if none found yet (placement data may not have been ready during BuildLists)
if (_pitfallPositions.Count == 0)
ScanPitfalls();
// Remove destroyed objects, picked-up items, and defeated enemies during rescan.
// Don't remove inactive non-item/non-enemy objects - the game deactivates distant objects for performance.
foreach (var cat in AllCategories)
{
if (_events.ContainsKey(cat))
{
_events[cat].RemoveAll(e =>
{
// Destroyed object
if (e.Target == null)
return true;
// Picked-up items/materials: enableItemPickPoint becomes false after pickup.
if (e.Category == EventCategory.Items || e.Category == EventCategory.Materials || e.Category == EventCategory.Quest)
{
var pickPoint = e.Target.GetComponent<ItemPickPointBase>();
if (pickPoint != null && !pickPoint.enableItemPickPoint)
{
_knownTargets.Remove(e.Target);
return true;
}
}
// Completed quests: completion flag is now set
if (e.Category == EventCategory.Quest && e.FlagSetId != 0 && IsQuestFlagSet(e.FlagSetId))
{
_knownTargets.Remove(e.Target);
return true;
}
// Defeated/inactive enemies: check actionState for dead/dying
if (e.Category == EventCategory.Enemies && !e.Target.activeInHierarchy)
{
_knownTargets.Remove(e.Target);
return true;
}
return false;
});
}
}
// Preserve selected item across sort
var selectedEvent = GetSelectedEvent();
// Always update categories after cleanup (items may have been removed)
foreach (var kvp in _events)
kvp.Value.Sort((a, b) => a.DistanceToPlayer.CompareTo(b.DistanceToPlayer));
UpdateActiveCategories();
RestoreSelectionAfterSort(selectedEvent);
if (newCount > 0)
{
DebugLogger.Log($"[NavList] Rescan found {newCount} new objects. Totals: " +
$"{_events[EventCategory.NPCs].Count} NPCs, " +
$"{_events[EventCategory.Items].Count} items, " +
$"{_events[EventCategory.Materials].Count} materials, " +
$"{_events[EventCategory.Transitions].Count} transitions, " +
$"{_events[EventCategory.Enemies].Count} enemies, " +
$"{_events[EventCategory.Facilities].Count} facilities");
}
}
/// <summary>
/// Build the full event lists by scanning the current area.
/// </summary>
private void BuildLists()
{
_events.Clear();
_events[EventCategory.NPCs] = new List<NavigationEvent>();
_events[EventCategory.Items] = new List<NavigationEvent>();
_events[EventCategory.Materials] = new List<NavigationEvent>();
_events[EventCategory.Quest] = new List<NavigationEvent>();
_events[EventCategory.Transitions] = new List<NavigationEvent>();
_events[EventCategory.Enemies] = new List<NavigationEvent>();
_events[EventCategory.Facilities] = new List<NavigationEvent>();
_knownTargets.Clear();
_facilityNpcObjects.Clear();
Vector3 playerPos = _playerCtrl != null ? _playerCtrl.transform.position : Vector3.zero;
// Scan facilities BEFORE NPCs so facility NPCs are excluded from the NPC list
ScanFacilities(playerPos);
// NPCs load asynchronously via coroutines - only scan once the game confirms loading is done
if (!_npcsLoadComplete)
{
try
{
var mgm = MainGameManager.m_instance;
if (mgm != null && mgm._IsLoadEndNpcPlacementData())
_npcsLoadComplete = true;
}
catch { }
}
if (_npcsLoadComplete)
ScanNPCs(playerPos);
else
DebugLogger.Log("[NavList] NPC placement data not yet loaded, skipping NPC scan");
// Items load asynchronously via coroutines - only scan once the game confirms loading is done
if (!_itemsLoadComplete)
{
try
{
var mgm = MainGameManager.m_instance;
if (mgm != null && mgm._IsLoadEndItemPickPointData())
_itemsLoadComplete = true;
}
catch { }
}
if (_itemsLoadComplete)
ScanItems(playerPos);
else
DebugLogger.Log("[NavList] Item pick point data not yet loaded, skipping item scan");
ScanTransitions(playerPos);
// Quest items use the Item MonoBehaviour and spawn based on scenario flags
ScanQuestItems(playerPos);
// Enemies load asynchronously via coroutines - only scan once the game confirms loading is done
if (!_enemiesLoadComplete)
{
try
{
var mgm = MainGameManager.m_instance;
if (mgm != null && mgm._IsLoadEndEnemyPlacementData())
_enemiesLoadComplete = true;
}
catch { }
}
if (_enemiesLoadComplete)
ScanEnemies(playerPos);
else
DebugLogger.Log("[NavList] Enemy placement data not yet loaded, skipping enemy scan");
// Scan for pitfall triggers (PIT_ command blocks) and place NavMesh obstacles
ScanPitfalls();
// Sort each category by distance
foreach (var kvp in _events)
{
kvp.Value.Sort((a, b) => a.DistanceToPlayer.CompareTo(b.DistanceToPlayer));
}
// Track all found objects
foreach (var kvp in _events)
{
foreach (var e in kvp.Value)
{
if (e.Target != null)
_knownTargets.Add(e.Target);
}
}
UpdateActiveCategories();
DebugLogger.Log($"[NavList] Built lists: {_events[EventCategory.NPCs].Count} NPCs, " +
$"{_events[EventCategory.Items].Count} items, " +
$"{_events[EventCategory.Materials].Count} materials, " +
$"{_events[EventCategory.Quest].Count} quest, " +
$"{_events[EventCategory.Transitions].Count} transitions, " +
$"{_events[EventCategory.Enemies].Count} enemies, " +
$"{_events[EventCategory.Facilities].Count} facilities");
}
/// <summary>
/// Refresh lists to catch items picked up, enemies defeated, etc.
/// </summary>
private void RefreshLists()
{
if (_playerCtrl == null) return;
Vector3 playerPos = _playerCtrl.transform.position;
// Refresh items and materials - remove picked up, add newly loaded.
// Items load via coroutines so some may appear after the initial scan.
Func<NavigationEvent, bool> removePickedUp = e =>
{
if (e.Target == null)
return true;
try
{
var pickPoint = e.Target.GetComponent<ItemPickPointBase>();
if (pickPoint != null && !pickPoint.enableItemPickPoint)
return true;
}
catch { }
return false;
};
var items = _events.ContainsKey(EventCategory.Items) ? _events[EventCategory.Items] : null;
var materials = _events.ContainsKey(EventCategory.Materials) ? _events[EventCategory.Materials] : null;
var keyItems = _events.ContainsKey(EventCategory.Quest) ? _events[EventCategory.Quest] : null;
items?.RemoveAll(e => removePickedUp(e));
materials?.RemoveAll(e => removePickedUp(e));
// Quest items (EventTrigger pickups) - remove if destroyed, inactive, or consumed
// Uses scenario completion flags from form 5 (SSetFlagSetData) which persist in save data
keyItems?.RemoveAll(e =>
{
if (e.Target == null || !e.Target.activeInHierarchy)
return true;
if (e.FlagSetId != 0 && IsQuestFlagSet(e.FlagSetId))
return true;
try
{
var pickPoint = e.Target.GetComponent<ItemPickPointBase>();
if (pickPoint != null && !pickPoint.enableItemPickPoint)
return true;
}
catch { }
return false;
});
// Check for new items/materials/quest that may have loaded since the last scan
if (!_itemsLoadComplete)
{
try
{
var mgm = MainGameManager.m_instance;
if (mgm != null && mgm._IsLoadEndItemPickPointData())
{
_itemsLoadComplete = true;
DebugLogger.Log("[NavList] Item pick point data load complete during refresh");
}
}
catch { }
}
var itemManager = ItemPickPointManager.m_instance;
if (_itemsLoadComplete && itemManager != null && itemManager.m_itemPickPoints != null)
{
var existingTargets = new HashSet<GameObject>();
if (items != null)
foreach (var e in items)
if (e.Target != null) existingTargets.Add(e.Target);