-
Notifications
You must be signed in to change notification settings - Fork 324
/
PlayerGPS.cs
1317 lines (1122 loc) · 50.5 KB
/
PlayerGPS.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
// Project: Daggerfall Unity
// Copyright: Copyright (C) 2009-2022 Daggerfall Workshop
// Web Site: http://www.dfworkshop.net
// License: MIT License (http://www.opensource.org/licenses/mit-license.php)
// Source Code: https://github.com/Interkarma/daggerfall-unity
// Original Author: Gavin Clayton (interkarma@dfworkshop.net)
// Contributors:
//
// Notes:
//
using UnityEngine;
using System;
using System.Linq;
using System.Collections.Generic;
using DaggerfallConnect;
using DaggerfallConnect.Arena2;
using DaggerfallConnect.Utility;
using DaggerfallWorkshop.Utility;
using DaggerfallWorkshop.Game;
using DaggerfallWorkshop.Game.Entity;
using DaggerfallWorkshop.Game.Utility;
using DaggerfallWorkshop.Game.UserInterfaceWindows;
using DaggerfallWorkshop.Game.Serialization;
using DaggerfallWorkshop.Game.Banking;
using DaggerfallWorkshop.Game.MagicAndEffects;
namespace DaggerfallWorkshop
{
/// <summary>
/// Tracks player position in virtual world space.
/// Provides information about world around the player.
/// </summary>
public class PlayerGPS : MonoBehaviour
{
#region Fields
const float refreshNearbyObjectsInterval = 0.33f;
// Default location is outside Privateer's Hold
[Range(0, 32735232)]
public int WorldX; // Player X coordinate in Daggerfall world units
[Range(0, 16351232)]
public int WorldZ; // Player Z coordinate in Daggerfall world units
DaggerfallUnity dfUnity;
int lastMapPixelX = -1;
int lastMapPixelY = -1;
int currentClimateIndex;
int currentPoliticIndex;
DFRegion currentRegion;
DFLocation currentLocation;
DFLocation.ClimateSettings climateSettings;
string regionName;
bool hasCurrentLocation;
bool isPlayerInLocationRect;
DFRegion.LocationTypes currentLocationType;
int locationWorldRectMinX;
int locationWorldRectMaxX;
int locationWorldRectMinZ;
int locationWorldRectMaxZ;
int lastRegionIndex;
int lastClimateIndex;
int lastPoliticIndex;
string locationRevealedByMapItem;
float nearbyObjectsUpdateTimer = 0f;
List<NearbyObject> nearbyObjects = new List<NearbyObject>();
Dictionary<int, DiscoveredLocation> discoveredLocations = new Dictionary<int, DiscoveredLocation>();
Vector3 lastFramePosition;
#endregion
#region Structs & Enums
public struct DiscoveredLocation
{
public int mapID;
public int mapPixelID;
public string regionName;
public string locationName;
public Dictionary<int, DiscoveredBuilding> discoveredBuildings;
}
[Serializable]
public struct DiscoveredBuilding
{
public int buildingKey;
public string displayName;
public string oldDisplayName;
public bool isOverrideName;
public int factionID;
public int quality;
public DFLocation.BuildingTypes buildingType;
public int lastLockpickAttempt;
public string customUserDisplayName;
}
public struct NearbyObject
{
public GameObject gameObject;
public NearbyObjectFlags flags;
public float distance;
}
[Flags]
public enum NearbyObjectFlags
{
None = 0,
Enemy = 1,
Treasure = 2,
Magic = 4,
Undead = 8,
Daedra = 16,
Humanoid = 32,
Animal = 64,
}
#endregion
#region Properties
/// <summary>
/// Gets current player map pixel.
/// </summary>
public DFPosition CurrentMapPixel
{
get { return MapsFile.WorldCoordToMapPixel(WorldX, WorldZ); }
}
/// <summary>
/// Gets climate index based on player world position.
/// </summary>
public int CurrentClimateIndex
{
get { return currentClimateIndex; }
}
/// <summary>
/// Gets political index based on player world position.
/// </summary>
public int CurrentPoliticIndex
{
get { return currentPoliticIndex; }
}
/// <summary>
/// Gets region index based on player world position.
/// </summary>
public int CurrentRegionIndex
{
get { if (currentPoliticIndex == 64)
return 31; // High Rock sea coast
else
return currentPoliticIndex - 128; }
}
/// <summary>
/// Gets current location index.
/// Returns -1 when HasCurrentLocation=false
/// </summary>
public int CurrentLocationIndex
{
get { return (hasCurrentLocation) ? currentLocation.LocationIndex : -1; }
}
/// <summary>
/// Gets climate properties based on player world position.
/// </summary>
public DFLocation.ClimateSettings ClimateSettings
{
get { return climateSettings; }
}
/// <summary>
/// Gets region data based on player world position.
/// </summary>
public DFRegion CurrentRegion
{
get { return currentRegion; }
}
/// <summary>
/// Gets location data based on player world position.
/// Location may be empty, check for Loaded=true.
/// </summary>
public DFLocation CurrentLocation
{
get { return currentLocation; }
}
/// <summary>
/// Gets current location type.
/// Undefined when HasCurrentLocation=false
/// </summary>
public DFRegion.LocationTypes CurrentLocationType
{
get { return currentLocationType; }
}
/// <summary>
/// Gets current location MapID.
/// Returns -1 when HasCurrentLocation=false
/// </summary>
public int CurrentMapID
{
get { return (hasCurrentLocation) ? currentLocation.MapTableData.MapId : -1; }
}
/// <summary>
/// Gets current region name based on world position.
/// </summary>
public string CurrentRegionName
{
get { return regionName; }
}
/// <summary>
/// True if CurrentLocation is valid.
/// </summary>
public bool HasCurrentLocation
{
get { return hasCurrentLocation; }
}
/// <summary>
/// True if player inside actual location rect.
/// </summary>
public bool IsPlayerInLocationRect
{
get { return isPlayerInLocationRect; }
}
/// <summary>
/// Gets current location rect.
/// Contents not valid when HasCurrentLocation=false
/// </summary>
public RectOffset LocationRect
{
get { return new RectOffset(locationWorldRectMinX, locationWorldRectMaxX, locationWorldRectMinZ, locationWorldRectMaxZ); }
}
/// <summary>
/// The name of the last location revealed by a map item. Used for %map macro.
/// </summary>
public string LocationRevealedByMapItem
{
get { return locationRevealedByMapItem; } set { locationRevealedByMapItem = value; }
}
#endregion
#region Constructors
public PlayerGPS()
{
StartGameBehaviour.OnNewGame += StartGameBehaviour_OnNewGame;
SaveLoadManager.OnStartLoad += SaveLoadManager_OnStartLoad;
DaggerfallTravelPopUp.OnPostFastTravel += DaggerfallTravelPopUp_OnPostFastTravel;
}
#endregion
#region Unity
void Awake()
{
dfUnity = DaggerfallUnity.Instance;
}
void Start()
{
// Init change trackers for event system
lastRegionIndex = CurrentRegionIndex;
lastClimateIndex = CurrentClimateIndex;
lastPoliticIndex = CurrentPoliticIndex;
}
void Update()
{
// Do nothing if not ready
if (!ReadyCheck())
return;
// Update local world information whenever player map pixel changes
DFPosition pos = CurrentMapPixel;
if (pos.X != lastMapPixelX || pos.Y != lastMapPixelY)
{
UpdateWorldInfo(pos.X, pos.Y);
RaiseOnMapPixelChangedEvent(pos);
// Clear non-permanent scenes from cache, unless going to/from owned ship
DFPosition shipCoords = DaggerfallBankManager.GetShipCoords();
if (shipCoords == null || (!(pos.X == shipCoords.X && pos.Y == shipCoords.Y) && !(lastMapPixelX == shipCoords.X && lastMapPixelY == shipCoords.Y)))
SaveLoadManager.ClearSceneCache(false);
lastMapPixelX = pos.X;
lastMapPixelY = pos.Y;
}
// Raise other events
RaiseEvents();
// Check if player is inside actual location rect
PlayerLocationRectCheck();
// Update nearby objects
nearbyObjectsUpdateTimer += Time.deltaTime;
if (nearbyObjectsUpdateTimer > refreshNearbyObjectsInterval)
{
UpdateNearbyObjects();
nearbyObjectsUpdateTimer = 0;
}
}
private void LateUpdate()
{
// Snap back to physical world boundary to prevent player running off edge of world
// Setting to approx. 10000 inches (254 metres) in from edge so end of world not so visible
if (WorldX < 10000 || // West
WorldZ > 16370000 || // North
WorldZ < 10000 || // South
WorldX > 32750000) // East
{
gameObject.transform.position = lastFramePosition;
}
// Record player's last frame position
lastFramePosition = gameObject.transform.position;
}
#endregion
#region Private Methods
private void StartGameBehaviour_OnNewGame()
{
// Reset state when loading a new game
ResetState();
}
private void SaveLoadManager_OnStartLoad(SaveData_v1 saveData)
{
// Reset state when starting a new load process
ResetState();
}
private void DaggerfallTravelPopUp_OnPostFastTravel()
{
// Reset state after fast travelling
ResetState();
}
void ResetState()
{
isPlayerInLocationRect = false;
}
#endregion
#region Public Methods
/// <summary>
/// Force update of world information (climate, politic, etc.) when Update() not running.
/// </summary>
public void UpdateWorldInfo()
{
DFPosition pos = CurrentMapPixel;
UpdateWorldInfo(pos.X, pos.Y);
}
/// <summary>
/// Gets NameHelper.BankType in player's current region.
/// In practice this will always be Redguard/Breton.
/// Supporting other name banks for possible diversity later.
/// </summary>
public NameHelper.BankTypes GetNameBankOfCurrentRegion()
{
if (GameManager.Instance.PlayerGPS.CurrentRegionIndex > -1)
return (NameHelper.BankTypes) MapsFile.RegionRaces[GameManager.Instance.PlayerGPS.CurrentRegionIndex];
return NameHelper.BankTypes.Breton;
}
/// <summary>
/// Gets the dominant race in player's current region.
/// </summary>
public Races GetRaceOfCurrentRegion()
{
return (Races) MapsFile.RegionRaces[GameManager.Instance.PlayerGPS.CurrentRegionIndex] + 1;
}
/// <summary>
/// Gets the factionID for "people of region" in player's current region.
/// </summary>
public int GetPeopleOfCurrentRegion()
{
// Find people of current region
FactionFile.FactionData[] factions = GameManager.Instance.PlayerEntity.FactionData.FindFactions(
(int)FactionFile.FactionTypes.People,
(int)FactionFile.SocialGroups.Commoners,
(int)FactionFile.GuildGroups.GeneralPopulace,
CurrentRegionIndex);
// Should always find a single people of
if (factions == null || factions.Length != 1)
throw new Exception("GetPeopleOfCurrentRegion() did not find exactly 1 match.");
return factions[0].id;
}
/// <summary>
/// Gets the factionID of player's current region.
/// </summary>
public int GetCurrentRegionFaction()
{
FactionFile.FactionData factionData;
GameManager.Instance.PlayerEntity.FactionData.GetRegionFaction(CurrentRegionIndex, out factionData);
return factionData.id;
}
/// <summary>
/// Gets the factionID of noble court in player's current region
/// </summary>
public int GetCourtOfCurrentRegion()
{
// Find court in current region
FactionFile.FactionData[] factions = GameManager.Instance.PlayerEntity.FactionData.FindFactions(
(int)FactionFile.FactionTypes.Courts,
(int)FactionFile.SocialGroups.Nobility,
(int)FactionFile.GuildGroups.Region,
CurrentRegionIndex);
// Should always find a single court
if (factions == null || factions.Length != 1)
throw new Exception("GetCourtOfCurrentRegion() did not find exactly 1 match.");
return factions[0].id;
}
public int GetCurrentRegionVampireClan()
{
FactionFile.FactionData factionData;
GameManager.Instance.PlayerEntity.FactionData.GetRegionFaction(CurrentRegionIndex, out factionData);
return factionData.vam;
}
/// <summary>
/// Gets the dominant temple in player's current region.
/// </summary>
public int GetTempleOfCurrentRegion()
{
return MapsFile.RegionTemples[GameManager.Instance.PlayerGPS.CurrentRegionIndex];
}
/// <summary>
/// Checks if player is inside a location world cell, optionally inside location rect, optionally outside
/// </summary>
/// <returns>True if player inside a township</returns>
public bool IsPlayerInTown(bool mustBeInLocationRect = false, bool mustBeOutside = false)
{
// Check if player inside a town cell
if (CurrentLocationType == DFRegion.LocationTypes.TownCity ||
CurrentLocationType == DFRegion.LocationTypes.TownHamlet ||
CurrentLocationType == DFRegion.LocationTypes.TownVillage ||
CurrentLocationType == DFRegion.LocationTypes.HomeFarms ||
CurrentLocationType == DFRegion.LocationTypes.HomeWealthy ||
CurrentLocationType == DFRegion.LocationTypes.Tavern ||
CurrentLocationType == DFRegion.LocationTypes.ReligionTemple)
{
// Optionally check if player inside location rect
if (mustBeInLocationRect && !IsPlayerInLocationRect)
return false;
// Optionally check if player outside
if (mustBeOutside && GameManager.Instance.IsPlayerInside)
return false;
return true;
}
return false;
}
/// <summary>
/// Gets nearby objects matching flags and within maxRange.
/// Can be used as needed, does not trigger a scene search.
/// This only searches pre-populated list of nearby objects which is updated at low frequency.
/// </summary>
/// <param name="flags">Flags to search for.</param>
/// <param name="maxRange">Max range for search. Not matched to classic range at this time.</param>
/// <param name="activeInHierarchy">Flag to get active or inactive objects.</param>
/// <returns>NearbyObject list. Can be null or empty.</returns>
public List<NearbyObject> GetNearbyObjects(NearbyObjectFlags flags, float maxRange = 14f, bool activeInHierarchy = true)
{
if (flags == NearbyObjectFlags.None)
return null;
var query =
from no in nearbyObjects
where ((no.flags & flags) == flags) && no.distance < maxRange && no.gameObject != null && no.gameObject.activeInHierarchy == activeInHierarchy
select no;
return query.ToList();
}
#endregion
#region Private Methods
private void RaiseEvents()
{
// Region index changed
if (CurrentRegionIndex != lastRegionIndex)
{
RaiseOnRegionIndexChangedEvent(CurrentRegionIndex);
lastRegionIndex = CurrentRegionIndex;
}
// Climate index changed
if (CurrentClimateIndex != lastClimateIndex)
{
RaiseOnClimateIndexChangedEvent(CurrentClimateIndex);
lastClimateIndex = CurrentClimateIndex;
}
// Politic index changed
if (CurrentPoliticIndex != lastPoliticIndex)
{
RaiseOnPoliticIndexChangedEvent(CurrentPoliticIndex);
lastPoliticIndex = CurrentPoliticIndex;
}
}
private void UpdateWorldInfo(int x, int y)
{
// Requires DaggerfallUnity to be ready
if (!ReadyCheck())
return;
// Requires MAPS.BSA connection
if (dfUnity.ContentReader.MapFileReader == null)
return;
// Get climate and politic data
currentClimateIndex = dfUnity.ContentReader.MapFileReader.GetClimateIndex(x, y);
currentPoliticIndex = dfUnity.ContentReader.MapFileReader.GetPoliticIndex(x, y);
climateSettings = MapsFile.GetWorldClimateSettings(currentClimateIndex);
if (currentPoliticIndex >= 128)
regionName = DaggerfallUnity.Instance.TextProvider.GetLocalizedRegionName(currentPoliticIndex - 128);
else if (currentPoliticIndex == 64)
regionName = TextManager.Instance.GetLocalizedText("ocean");
else
regionName = TextManager.Instance.GetLocalizedText("unknownUpper");
// Get region data
currentRegion = dfUnity.ContentReader.MapFileReader.GetRegion(CurrentRegionIndex);
// Get location data
ContentReader.MapSummary mapSummary;
if (dfUnity.ContentReader.HasLocation(x, y, out mapSummary))
{
currentLocation = dfUnity.ContentReader.MapFileReader.GetLocation(mapSummary.RegionIndex, mapSummary.MapIndex);
hasCurrentLocation = true;
CalculateWorldLocationRect();
}
else
{
currentLocation = new DFLocation();
hasCurrentLocation = false;
ClearWorldLocationRect();
}
// Get location type
if (hasCurrentLocation)
{
if (currentRegion.MapTable == null)
{
DaggerfallUnity.LogMessage(string.Format("PlayerGPS: Location {0} in region{1} has a null MapTable.", currentLocation.Name, currentLocation.RegionName));
}
else
{
currentLocationType = currentRegion.MapTable[mapSummary.MapIndex].LocationType;
}
}
}
// Calculate location rect in world units
private void CalculateWorldLocationRect()
{
if (!hasCurrentLocation)
return;
// Convert world coords to map pixel coords then back again
// This finds the absolute SW origin of this map pixel in world coords
DFPosition mapPixel = CurrentMapPixel;
DFPosition worldOrigin = MapsFile.MapPixelToWorldCoord(mapPixel.X, mapPixel.Y);
// Find tile offset point using same logic as terrain helper
DFPosition tileOrigin = TerrainHelper.GetLocationTerrainTileOrigin(CurrentLocation);
// Adjust world origin by tileorigin*2 in world units
worldOrigin.X += (tileOrigin.X * 2) * MapsFile.WorldMapTileDim;
worldOrigin.Y += (tileOrigin.Y * 2) * MapsFile.WorldMapTileDim;
// Get width and height of location in world units
int width = currentLocation.Exterior.ExteriorData.Width * MapsFile.WorldMapRMBDim;
int height = currentLocation.Exterior.ExteriorData.Height * MapsFile.WorldMapRMBDim;
// Set location rect in world coordinates
locationWorldRectMinX = worldOrigin.X;
locationWorldRectMaxX = worldOrigin.X + width;
locationWorldRectMinZ = worldOrigin.Y;
locationWorldRectMaxZ = worldOrigin.Y + height;
}
private void ClearWorldLocationRect()
{
locationWorldRectMinX = -1;
locationWorldRectMaxX = -1;
locationWorldRectMinZ = -1;
locationWorldRectMaxZ = -1;
}
private void PlayerLocationRectCheck()
{
int extraRect = 4096;
// Bail if no current location at this map pixel
if (!hasCurrentLocation)
{
// Raise exit event if player was in location rect
if (isPlayerInLocationRect)
{
RaiseOnExitLocationRectEvent();
}
// Clear flag and exit
isPlayerInLocationRect = false;
return;
}
// Player can be inside a map pixel with location but not inside location rect
// So check if player currently inside location rect
// Virtual location rect check is extended by 4096 units (size of a full city block) around physical town border to better match classic
bool check;
if (WorldX >= locationWorldRectMinX - extraRect && WorldX <= locationWorldRectMaxX + extraRect &&
WorldZ >= locationWorldRectMinZ - extraRect && WorldZ <= locationWorldRectMaxZ + extraRect)
{
check = true;
}
else
{
check = false;
}
// Call events based on location rect change
if (check && !isPlayerInLocationRect)
{
// Perform location discovery
DiscoverCurrentLocation();
// Player has entered location rect
isPlayerInLocationRect = check;
RaiseOnEnterLocationRectEvent(CurrentLocation);
}
else if (!check && isPlayerInLocationRect)
{
// Player has left a location rect
isPlayerInLocationRect = check;
RaiseOnExitLocationRectEvent();
}
}
public bool ReadyCheck()
{
// Ensure we have a DaggerfallUnity reference
if (dfUnity == null)
{
dfUnity = DaggerfallUnity.Instance;
}
// Do nothing until DaggerfallUnity is ready
if (!dfUnity.IsReady)
return false;
return true;
}
#endregion
#region Nearby Objects
/// <summary>
/// Refresh list of nearby objects to service related systems.
/// </summary>
void UpdateNearbyObjects()
{
nearbyObjects.Clear();
// Get entities
DaggerfallEntityBehaviour[] entities = FindObjectsOfType<DaggerfallEntityBehaviour>();
if (entities != null)
{
for (int i = 0; i < entities.Length; i++)
{
if (entities[i] == GameManager.Instance.PlayerEntityBehaviour)
continue;
NearbyObject no = new NearbyObject()
{
gameObject = entities[i].gameObject,
distance = Vector3.Distance(transform.position, entities[i].transform.position),
};
no.flags = GetEntityFlags(entities[i]);
nearbyObjects.Add(no);
}
}
// Get treasure - this assumes loot containers will never carry entity component
DaggerfallLoot[] lootContainers = FindObjectsOfType<DaggerfallLoot>();
if (lootContainers != null)
{
for (int i = 0; i < lootContainers.Length; i++)
{
NearbyObject no = new NearbyObject()
{
gameObject = lootContainers[i].gameObject,
distance = Vector3.Distance(transform.position, lootContainers[i].transform.position),
};
no.flags = GetLootFlags(lootContainers[i]);
nearbyObjects.Add(no);
}
}
}
public NearbyObjectFlags GetEntityFlags(DaggerfallEntityBehaviour entity)
{
NearbyObjectFlags result = NearbyObjectFlags.None;
if (!entity)
return result;
if (entity.EntityType == EntityTypes.EnemyClass || entity.EntityType == EntityTypes.EnemyMonster)
{
result |= NearbyObjectFlags.Enemy;
DFCareer.EnemyGroups enemyGroup = (entity.Entity as EnemyEntity).GetEnemyGroup();
switch (enemyGroup)
{
case DFCareer.EnemyGroups.Undead:
result |= NearbyObjectFlags.Undead;
break;
case DFCareer.EnemyGroups.Daedra:
result |= NearbyObjectFlags.Daedra;
break;
case DFCareer.EnemyGroups.Humanoid:
result |= NearbyObjectFlags.Humanoid;
break;
case DFCareer.EnemyGroups.Animals:
result |= NearbyObjectFlags.Animal;
break;
}
}
else if (entity.EntityType == EntityTypes.CivilianNPC)
{
result |= NearbyObjectFlags.Humanoid;
}
// Set magic flag
// Not completely sure what conditions should flag entity for "detect magic"
// Currently just assuming entity has active effects
EntityEffectManager manager = entity.GetComponent<EntityEffectManager>();
if (manager && manager.EffectCount > 0)
{
result |= NearbyObjectFlags.Magic;
}
return result;
}
public NearbyObjectFlags GetLootFlags(DaggerfallLoot loot)
{
NearbyObjectFlags result = NearbyObjectFlags.None;
if (!loot)
return result;
// Set treasure flag when container not empty
// Are any other conditions required?
// Should corspes loot container be filtered out?
if (loot.Items.Count > 0)
{
result |= NearbyObjectFlags.Treasure;
}
return result;
}
#endregion
#region Location Discovery
/// <summary>
/// Discover current location.
/// Does nothing if player in wilderness or location already dicovered.
/// This is performed automatically by PlayerGPS when player enters a location rect.
/// </summary>
void DiscoverCurrentLocation()
{
// Must have a location loaded
if (!CurrentLocation.Loaded)
return;
// Check if already discovered
int mapPixelID = MapsFile.GetMapPixelIDFromLongitudeLatitude((int)CurrentLocation.MapTableData.Longitude, CurrentLocation.MapTableData.Latitude);
if (HasDiscoveredLocation(mapPixelID))
return;
// Add to discovered locations dict
DiscoveredLocation dl = new DiscoveredLocation();
dl.mapID = CurrentLocation.MapTableData.MapId;
dl.mapPixelID = mapPixelID;
dl.regionName = CurrentLocation.RegionName;
dl.locationName = CurrentLocation.Name;
discoveredLocations.Add(mapPixelID, dl);
}
/// <summary>
/// Discover location with regionName and locationName.
/// </summary>
public void DiscoverLocation(string regionName, string locationName)
{
DFLocation location;
bool found = dfUnity.ContentReader.GetLocation(regionName, locationName, out location);
if (!found)
throw new Exception(String.Format("Error finding location {0} : {1}", regionName, locationName));
// Check if already discovered
int mapPixelID = MapsFile.GetMapPixelIDFromLongitudeLatitude((int)location.MapTableData.Longitude, location.MapTableData.Latitude);
if (HasDiscoveredLocation(mapPixelID))
return;
// Add to discovered locations dict
DiscoveredLocation dl = new DiscoveredLocation();
dl.mapID = location.MapTableData.MapId;
dl.mapPixelID = mapPixelID;
dl.regionName = location.RegionName;
dl.locationName = location.Name;
discoveredLocations.Add(mapPixelID, dl);
}
public DFLocation DiscoverRandomLocation()
{
// Get all undiscovered locations that exist in the current region
List<int> undiscoveredLocIdxs = new List<int>();
for (int i = 0; i < currentRegion.LocationCount; i++)
if (currentRegion.MapTable[i].Discovered == false && !HasDiscoveredLocation(currentRegion.MapTable[i].MapId & 0x000fffff))
undiscoveredLocIdxs.Add(i);
// If there aren't any left, there's nothing to find. Classic will just keep returning a particular location over and over if this happens.
if (undiscoveredLocIdxs.Count == 0)
return new DFLocation();
// Choose a random location and discover it
int locIdx = UnityEngine.Random.Range(0, undiscoveredLocIdxs.Count);
DFLocation location = dfUnity.ContentReader.MapFileReader.GetLocation(CurrentRegionIndex, undiscoveredLocIdxs[locIdx]);
DiscoverLocation(CurrentRegionName, location.Name);
return location;
}
/// <summary>
/// Discover the specified building in current location.
/// Does nothing if player not inside a location or building already discovered.
/// </summary>
/// <param name="buildingKey">Building key of building to be discovered</param>
/// <param name="overrideName">If provided, ignore previous discovery and override the name</param>
public void DiscoverBuilding(int buildingKey, string overrideName = null)
{
// Ensure current location also discovered before processing building
DiscoverCurrentLocation();
// Must have a location loaded
if (!CurrentLocation.Loaded)
return;
// Do nothing if building already discovered, unless overriding name
if (overrideName == null && HasDiscoveredBuilding(buildingKey))
return;
// Get building information
DiscoveredBuilding db;
if (!GetBaseBuildingDiscoveryData(buildingKey, out db))
return;
// Get location discovery
int mapPixelID = MapsFile.GetMapPixelIDFromLongitudeLatitude((int)CurrentLocation.MapTableData.Longitude, CurrentLocation.MapTableData.Latitude);
DiscoveredLocation dl = new DiscoveredLocation();
if (discoveredLocations.ContainsKey(mapPixelID))
{
dl = discoveredLocations[mapPixelID];
}
// Ensure the building dict is created
if (dl.discoveredBuildings == null)
dl.discoveredBuildings = new Dictionary<int, DiscoveredBuilding>();
// check if building is used in quest (but only if no override name was provided (which will have priority))
if (overrideName == null)
{
bool pcLearnedAboutExistence = false;
bool receivedDirectionalHints = false;
bool locationWasMarkedOnMapByNPC = false;
string overrideBuildingName = string.Empty;
if (GameManager.Instance.TalkManager.IsBuildingQuestResource(CurrentMapID, buildingKey, ref overrideBuildingName, ref pcLearnedAboutExistence, ref receivedDirectionalHints, ref locationWasMarkedOnMapByNPC))
{
// if pc learned about building existance (was told the name) and quest building has (override) building name different than current building display name
if (pcLearnedAboutExistence && overrideBuildingName != db.displayName)
overrideName = overrideBuildingName; // set override name for use
}
}
// Add the building and store back to discovered location, overriding name if requested
if (overrideName != null)
{
if (!db.isOverrideName)
db.oldDisplayName = db.displayName;
db.displayName = overrideName;
db.isOverrideName = true;
}
if (db.oldDisplayName == db.displayName)
db.isOverrideName = false;
dl.discoveredBuildings[db.buildingKey] = db;
discoveredLocations[mapPixelID] = dl;
}
/// <summary>
/// Undiscover the specified building in current location.
/// used to undiscover residences when they are a quest resource (named residence) when "add dialog" is done for this quest resource or on quest startup or on quest tombstone
/// otherwise previously discovered residences will automatically show up on the automap when used in a quest
/// </summary>
/// <param name="buildingKey">Building key of building to be undiscovered</param>
/// <param name="onlyIfResidence">gets undiscovered only if buildingType is residence</param>
/// <param name="matchName">use a name for matching (only undiscover if building name matches matchName) - this is used if two quests "occupy" the same residence with different names, and one tries to hide residence on map but other quest's residence name was used and is still running</param>
public void UndiscoverBuilding(int buildingKey, bool onlyIfResidence = false, string matchName = null)
{
// Must have a location loaded
if (!CurrentLocation.Loaded)
return;
// Get location discovery
int mapPixelID = MapsFile.GetMapPixelIDFromLongitudeLatitude((int)CurrentLocation.MapTableData.Longitude, CurrentLocation.MapTableData.Latitude);
DiscoveredLocation dl = new DiscoveredLocation();
if (discoveredLocations.ContainsKey(mapPixelID))
{
dl = discoveredLocations[mapPixelID];
}
if (dl.discoveredBuildings == null || !dl.discoveredBuildings.ContainsKey(buildingKey))
return;
DiscoveredBuilding db = dl.discoveredBuildings[buildingKey];
// do nothing if only residences should be undiscovered but building is no residence
if (onlyIfResidence && !RMBLayout.IsResidence(db.buildingType))
return;
// Do not undiscover residence if it's a Thieves Guild or Dark Brotherhood hideout
if (db.factionID == (int)FactionFile.FactionIDs.The_Thieves_Guild ||
db.factionID == (int)FactionFile.FactionIDs.The_Dark_Brotherhood)
return;
// do nothing if matchName was provided but matchName does not match displayName of building
if (matchName != null && matchName != db.displayName)
return;
dl.discoveredBuildings.Remove(db.buildingKey);
}
/// <summary>
/// Check if player has discovered location.
/// MapPixelID is derived from longitude/latitude or MapPixelX, MapPixelY.
/// See MapsFile.GetMapPixelID() and MapsFile.GetMapPixelIDFromLongitudeLatitude().
/// </summary>
/// <param name="mapPixelID">ID of location pixel.</param>
/// <returns>True if already discovered.</returns>
public bool HasDiscoveredLocation(int mapPixelID)
{
return discoveredLocations.ContainsKey(mapPixelID);
}
/// <summary>
/// Check if player has discovered building in current location.
/// </summary>