-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathPlayerActivate.cs
1501 lines (1337 loc) · 71.4 KB
/
PlayerActivate.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 Tools For Unity
// Copyright: Copyright (C) 2009-2020 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 ([email protected])
// Contributors: Allofich, Numidium, TheLacus
//
// Notes:
//
using UnityEngine;
using DaggerfallConnect;
using DaggerfallConnect.Arena2;
using DaggerfallWorkshop.Game.UserInterface;
using DaggerfallWorkshop.Game.UserInterfaceWindows;
using DaggerfallWorkshop.Game.Entity;
using DaggerfallWorkshop.Utility;
using DaggerfallWorkshop.Game.Questing;
using DaggerfallWorkshop.Game.Items;
using DaggerfallWorkshop.Game.Banking;
using DaggerfallWorkshop.Game.Guilds;
using DaggerfallWorkshop.Game.MagicAndEffects.MagicEffects;
using System.Collections.Generic;
using DaggerfallWorkshop.Utility.AssetInjection;
using DaggerfallWorkshop.Game.Utility;
using DaggerfallWorkshop.Game.Formulas;
using DaggerfallWorkshop.Game.Utility.ModSupport;
namespace DaggerfallWorkshop.Game
{
/// <summary>
/// Defines a <see cref="MonoBehaviour"/> component that can be activated by player interaction.
/// Activation is detected when a ray cast hits a collider or trigger collider on the GameObject on which the component is instantiated.
/// </summary>
public interface IPlayerActivable
{
/// <summary>
/// Fired when the player activate this object. This method can be called more than once if the collider is not disabled by implementation.
/// </summary>
/// <param name="hit">The hit that caused the activation.</param>
void Activate(RaycastHit hit);
}
/// <summary>
/// Example class to handle activation of doors, switches, etc. from Fire1 input.
/// </summary>
public class PlayerActivate : MonoBehaviour
{
PlayerGPS playerGPS;
PlayerEnterExit playerEnterExit; // Example component to enter/exit buildings
GameObject mainCamera;
int playerLayerMask = 0;
Transform deferredInteriorDoorOwner; // Used to defer interior transition after popup message
StaticDoor deferredInteriorDoor;
PlayerActivateModes currentMode = PlayerActivateModes.Grab;
bool castPending = false;
float clickDelay = 0;
float clickDelayStartTime = 0;
const float RayDistance = 3072 * MeshReader.GlobalScale; // Classic's farthest view distance (outside, clear weather).
// This is needed for using "Info" mode and clicking on buildings, which can
// be done in classic for as far as the view distance.
// Maximum distance from which different object types can be activated, converted from classic units (divided by 40)
public const float DefaultActivationDistance = 128 * MeshReader.GlobalScale;
public const float DoorActivationDistance = 128 * MeshReader.GlobalScale;
public const float TreasureActivationDistance = 128 * MeshReader.GlobalScale;
public const float PickpocketDistance = 128 * MeshReader.GlobalScale;
public const float CorpseActivationDistance = 150 * MeshReader.GlobalScale;
//const float TouchSpellActivationDistance = 160 * MeshReader.GlobalScale;
public const float StaticNPCActivationDistance = 256 * MeshReader.GlobalScale;
public const float MobileNPCActivationDistance = 256 * MeshReader.GlobalScale;
// Opening and closing hours by building type
static byte[] openHours = { 7, 8, 9, 8, 0, 9, 10, 10, 9, 6, 9, 11, 9, 9, 0, 0, 10, 0 };
static byte[] closeHours = { 22, 16, 19, 15, 25, 21, 19, 20, 18, 23, 23, 23, 20, 20, 25, 25, 16, 0 };
const int PrivatePropertyId = 37;
public PlayerActivateModes CurrentMode
{
get { return currentMode; }
}
// Public opening hours; Guilds' HallAccessAnytime can override that
public static bool IsBuildingOpen(DFLocation.BuildingTypes buildingType)
{
return (openHours[(int)buildingType] <= DaggerfallUnity.Instance.WorldTime.Now.Hour &&
closeHours[(int)buildingType] > DaggerfallUnity.Instance.WorldTime.Now.Hour);
}
#region custom mod activation
private struct CustomModActivation
{
internal readonly CustomActivation Action;
internal readonly float ActivationDistance;
internal readonly Mod Provider;
internal CustomModActivation(CustomActivation action, float activationDistance, Mod provider)
{
Action = action;
ActivationDistance = activationDistance;
Provider = provider;
}
}
readonly static Dictionary<string, CustomModActivation> customModActivations = new Dictionary<string, CustomModActivation>();
// Allow mods to register custom flat / model activation methods.
public delegate void CustomActivation(RaycastHit hit);
/// <summary>
/// Registers a custom activation for a model object. Uses the modelID parameter to retrieve the correct object name
/// </summary>
/// <param name="provider">The mod that provides this override; used to enforce load order.</param>
/// <param name="modelID">The model ID of the object that will trigger the custom action upon activation.</param>
/// <param name="customActivation">A callback that implements the custom action.</param>
public static void RegisterCustomActivation(Mod provider, uint modelID, CustomActivation customActivation, float activationDistance = DefaultActivationDistance)
{
string goModelName = GameObjectHelper.GetGoModelName(modelID);
HandleRegisterCustomActivation(provider, goModelName, customActivation, activationDistance);
}
/// <summary>
/// Registers a custom activation for a flat object. Uses the textureArchive and textureRecord parameters to retrieve the correct object name
/// </summary>
/// <param name="provider">The mod that provides this override; used to enforce load order.</param>
/// <param name="textureArchive">The texture archive of the flat object that will trigger the custom action upon activation.</param>
/// <param name="textureRecord">The texture record of the flat object that will trigger the custom action upon activation.</param>
/// <param name="customActivation">A callback that implements the custom action.</param>
public static void RegisterCustomActivation(Mod provider, int textureArchive, int textureRecord, CustomActivation customActivation, float activationDistance = DefaultActivationDistance)
{
string goFlatName = GameObjectHelper.GetGoFlatName(textureArchive, textureRecord);
HandleRegisterCustomActivation(provider, goFlatName, customActivation, activationDistance);
}
/// <summary>
/// Registers a custom activation for a flat object
/// </summary>
/// <param name="provider">The mod that provides this override; used to enforce load order.</param>
/// <param name="textureArchive">The texture archive of the flat object that will trigger the custom action upon activation.</param>
/// <param name="textureRecord">The texture record of the flat object that will trigger the custom action upon activation.</param>
/// <param name="customActivation">A callback that implements the custom action.</param>
private static void HandleRegisterCustomActivation(Mod provider, string goFlatModelName, CustomActivation customActivation, float activationDistance)
{
DaggerfallUnity.LogMessage("HandleRegisterCustomActivation: " + goFlatModelName, true);
CustomModActivation existingActivation;
if (customModActivations.TryGetValue(goFlatModelName, out existingActivation) && existingActivation.Provider.LoadPriority > provider.LoadPriority) {
Debug.Log("Denied custom activation registration from " + provider.Title + " for " + goFlatModelName + " | " + existingActivation.Provider.Title + " has higher load priority");
} else {
customModActivations[goFlatModelName] = new CustomModActivation(customActivation, activationDistance, provider);
}
}
/// <summary>
/// Checks if a model object has a custom activation assigned
/// </summary>
/// <param name="modelID">The model ID of the object to check.</param>
public static bool HasCustomActivation(uint modelID)
{
string goModelName = GameObjectHelper.GetGoModelName(modelID);
return HasCustomActivation(goModelName);
}
/// <summary>
/// Checks if a model object has a custom activation assigned
/// </summary>
/// <param name="textureArchive">The texture archive of the flat object to check.</param>
/// <param name="textureRecord">The texture record of the flat object to check.</param>
public static bool HasCustomActivation(int textureArchive, int textureRecord)
{
string goFlatName = GameObjectHelper.GetGoFlatName(textureArchive, textureRecord);
return HasCustomActivation(goFlatName);
}
/// <summary>
/// Checks if an object has a custom activation assigned
/// </summary>
/// <param name="goFlatModelName">The name of the flat / model object to check.</param>
public static bool HasCustomActivation(string goFlatModelName) {
return customModActivations.ContainsKey(goFlatModelName);
}
#endregion
void Start()
{
playerGPS = GetComponent<PlayerGPS>();
playerEnterExit = GetComponent<PlayerEnterExit>();
mainCamera = GameObject.FindGameObjectWithTag("MainCamera");
playerLayerMask = ~(1 << LayerMask.NameToLayer("Player"));
}
void Update()
{
if (mainCamera == null)
return;
// Do nothing further if player has spell ready to cast as activate button is now used to fire spell
// The exception is a readied touch spell where player can activate doors, etc.
// Touch spells only fire once a target entity is in range
if (GameManager.Instance.PlayerEffectManager)
{
// Handle pending spell cast
if (GameManager.Instance.PlayerEffectManager.HasReadySpell)
{
// Exclude touch spells from this check
MagicAndEffects.EntityEffectBundle spell = GameManager.Instance.PlayerEffectManager.ReadySpell;
if (spell.Settings.TargetType != MagicAndEffects.TargetTypes.ByTouch)
{
castPending = true;
return;
}
}
// Prevents last spell cast click from falling through to normal click handling this frame
if (castPending)
{
castPending = false;
return;
}
}
// Change activate mode
if (InputManager.Instance.ActionStarted(InputManager.Actions.StealMode))
ChangeInteractionMode(PlayerActivateModes.Steal);
else if (InputManager.Instance.ActionStarted(InputManager.Actions.GrabMode))
ChangeInteractionMode(PlayerActivateModes.Grab);
else if (InputManager.Instance.ActionStarted(InputManager.Actions.InfoMode))
ChangeInteractionMode(PlayerActivateModes.Info);
else if (InputManager.Instance.ActionStarted(InputManager.Actions.TalkMode))
ChangeInteractionMode(PlayerActivateModes.Talk);
// Handle click delay
if (clickDelay > 0 && Time.realtimeSinceStartup < clickDelayStartTime + clickDelay)
{
return;
}
else
{
clickDelay = 0;
clickDelayStartTime = 0;
}
// Fire ray into scene
if (InputManager.Instance.ActionComplete(InputManager.Actions.ActivateCenterObject))
{
// Fire ray into scene for hit tests (excluding player so their ray does not intersect self)
Ray ray = new Ray(mainCamera.transform.position, mainCamera.transform.forward);
RaycastHit hit;
bool hitSomething = Physics.Raycast(ray, out hit, RayDistance, playerLayerMask);
// Debug.DrawRay(ray.origin, ray.direction, Color.yellow, 2f);
if (hitSomething)
{
bool hitBuilding = false;
bool buildingUnlocked = false;
int buildingLockValue = 0;
DFLocation.BuildingTypes buildingType = DFLocation.BuildingTypes.AllValid;
StaticBuilding building = new StaticBuilding();
#region Hit Checks
// Trigger quest resource behaviour click on anything but NPCs
QuestResourceBehaviour questResourceBehaviour;
if (QuestResourceBehaviourCheck(hit, out questResourceBehaviour) && !(questResourceBehaviour.TargetResource is Person))
{
if (hit.distance > DefaultActivationDistance)
{
DaggerfallUI.SetMidScreenText(HardStrings.youAreTooFarAway);
return;
}
// Only trigger click when not in info mode
if (currentMode != PlayerActivateModes.Info)
{
TriggerQuestResourceBehaviourClick(questResourceBehaviour);
}
}
// Check for a static building hit
Transform buildingOwner;
DaggerfallStaticBuildings buildings = GetBuildings(hit.transform, out buildingOwner);
if (buildings && buildings.HasHit(hit.point, out building))
{
hitBuilding = true;
// Get building directory for location
BuildingDirectory buildingDirectory = GameManager.Instance.StreamingWorld.GetCurrentBuildingDirectory();
if (!buildingDirectory)
return;
// Get detailed building data from directory
BuildingSummary buildingSummary;
if (!buildingDirectory.GetBuildingSummary(building.buildingKey, out buildingSummary))
return;
buildingUnlocked = BuildingIsUnlocked(buildingSummary);
buildingLockValue = GetBuildingLockValue(buildingSummary);
buildingType = buildingSummary.BuildingType;
ActivateBuilding(building, buildingType, buildingUnlocked);
}
// Check for a static door hit
Transform doorOwner;
DaggerfallStaticDoors doors = GetDoors(hit.transform, out doorOwner);
if (doors && playerEnterExit)
{
ActivateStaticDoor(doors, hit, hitBuilding, building, buildingType, buildingUnlocked, buildingLockValue, doorOwner);
}
// Check for an action door hit
DaggerfallActionDoor actionDoor;
if (ActionDoorCheck(hit, out actionDoor))
{
ActivateActionDoor(hit, actionDoor);
}
// Check for action record hit
DaggerfallAction action;
if (ActionCheck(hit, out action) && hit.distance <= DefaultActivationDistance)
{
action.Receive(this.gameObject, DaggerfallAction.TriggerTypes.Direct);
}
// Check for lootable object hit
DaggerfallLoot loot;
if (LootCheck(hit, out loot))
{
ActivateLootContainer(hit, loot);
}
// Check for bulletin board object hit
DaggerfallBulletinBoard bulletinBoard;
if (BulletinBoardCheck(hit, out bulletinBoard))
{
Debug.Log("Player clicked bulletin board");
}
// Check for static NPC hit
StaticNPC npc;
if (NPCCheck(hit, out npc))
{
ActivateStaticNPC(hit, npc);
}
// Check for mobile NPC hit
MobilePersonNPC mobileNpc = null;
if (MobilePersonMotorCheck(hit, out mobileNpc))
{
ActivateMobileNPC(hit, mobileNpc);
}
// Check for mobile enemy hit
DaggerfallEntityBehaviour mobileEnemyBehaviour;
if (MobileEnemyCheck(hit, out mobileEnemyBehaviour))
{
ActivateMobileEnemy(hit, mobileEnemyBehaviour);
}
// Check for functional interior furniture: Ladders, Bookshelves.
ActivateLaddersAndShelves(hit);
// Invoke any matched custom flat / model activations registered by mods.
string flatModelName = hit.transform.gameObject.name;
int pos = flatModelName.IndexOf(']');
if (pos > 0 && pos < flatModelName.Length - 1)
flatModelName = flatModelName.Remove(pos + 1);
CustomModActivation customActivation;
if (customModActivations.TryGetValue(flatModelName, out customActivation))
{
if(hit.distance <= customActivation.ActivationDistance) {
customActivation.Action(hit);
}
}
// Check for custom activation
var playerActivable = hit.transform.GetComponent<IPlayerActivable>();
if (playerActivable != null)
playerActivable.Activate(hit);
// Debug for identifying interior furniture model ids.
Debug.Log(string.Format("hit='{0}' static={1}", hit.transform, GameObjectHelper.IsStaticGeometry(hit.transform.gameObject)));
#endregion
}
}
}
#region Activation Logic
void ActivateBuilding(
StaticBuilding building,
DFLocation.BuildingTypes buildingType,
bool buildingUnlocked)
{
if (currentMode == PlayerActivateModes.Info)
{
// Discover building
GameManager.Instance.PlayerGPS.DiscoverBuilding(building.buildingKey);
// Get discovered building
PlayerGPS.DiscoveredBuilding db;
if (GameManager.Instance.PlayerGPS.GetDiscoveredBuilding(building.buildingKey, out db))
{
// Check against quest system for an overriding quest-assigned display name for this building
DaggerfallUI.AddHUDText(db.displayName);
if (!buildingUnlocked && buildingType < DFLocation.BuildingTypes.Temple
&& buildingType != DFLocation.BuildingTypes.HouseForSale)
{
string buildingClosedMessage = (buildingType == DFLocation.BuildingTypes.GuildHall) ? HardStrings.guildClosed : HardStrings.storeClosed;
buildingClosedMessage = buildingClosedMessage.Replace("%d1", openHours[(int)buildingType].ToString());
buildingClosedMessage = buildingClosedMessage.Replace("%d2", closeHours[(int)buildingType].ToString());
DaggerfallUI.Instance.PopupMessage(buildingClosedMessage);
}
}
}
}
void ActivateStaticDoor(
DaggerfallStaticDoors doors,
RaycastHit hit,
bool hitBuilding,
StaticBuilding building,
DFLocation.BuildingTypes buildingType,
bool buildingUnlocked,
int buildingLockValue,
Transform doorOwner)
{
StaticDoor door;
if (doors.HasHit(hit.point, out door) || CustomDoor.HasHit(hit, out door))
{
// Check if close enough to activate
if (hit.distance > DoorActivationDistance)
{
DaggerfallUI.SetMidScreenText(HardStrings.youAreTooFarAway);
return;
}
if (door.doorType == DoorTypes.Building && !playerEnterExit.IsPlayerInside)
{
// Discover building
GameManager.Instance.PlayerGPS.DiscoverBuilding(building.buildingKey);
// Handle clicking exterior door with Open spell active
if (HandleOpenEffectOnExteriorDoor(buildingLockValue))
buildingUnlocked = true;
// TODO: Implement lockpicking and door bashing for exterior doors
// For now, any locked building door can be entered by using steal mode
if (!buildingUnlocked)
{
if (currentMode != PlayerActivateModes.Steal)
{
DaggerfallUI.Instance.PopupMessage(TextManager.Instance.GetText("GeneralText", "lockedExteriorDoor"));
LookAtInteriorLock(buildingLockValue);
return;
}
else // Breaking into building
{
// Reject if player has already failed this building at current skill level
PlayerEntity player = GameManager.Instance.PlayerEntity;
int skillValue = player.Skills.GetLiveSkillValue(DFCareer.Skills.Lockpicking);
int lastAttempt = GameManager.Instance.PlayerGPS.GetLastLockpickAttempt(building.buildingKey);
if (skillValue <= lastAttempt)
{
LookAtInteriorLock(buildingLockValue);
return;
}
// Attempt to unlock building
Random.InitState(Time.frameCount);
player.TallySkill(DFCareer.Skills.Lockpicking, 1);
int chance = FormulaHelper.CalculateExteriorLockpickingChance(buildingLockValue, skillValue);
int roll = Random.Range(1, 101);
Debug.LogFormat("Attempting pick against lock strength {0}. Chance={1}, Roll={2}.", buildingLockValue, chance, roll);
if (chance > roll)
{
// Show success and play unlock sound
player.TallyCrimeGuildRequirements(true, 1);
DaggerfallUI.Instance.PopupMessage(HardStrings.lockpickingSuccess);
DaggerfallAudioSource dfAudioSource = GetComponent<DaggerfallAudioSource>();
if (dfAudioSource != null)
dfAudioSource.PlayOneShot(SoundClips.ActivateLockUnlock);
}
else
{
// Show failure and record attempt skill level in discovery data
// Have not been able to create a guard response in classic, even when early morning NPCs are nearby
// Assuming for now that exterior lockpicking is discrete enough that no response on failure is required
DaggerfallUI.Instance.PopupMessage(HardStrings.lockpickingFailure);
GameManager.Instance.PlayerGPS.SetLastLockpickAttempt(building.buildingKey, skillValue);
return;
}
}
}
// If entering a shop let player know the quality level
// If entering an open home, show greeting
if (hitBuilding)
{
const int houseGreetingsTextId = 256;
DaggerfallMessageBox mb;
PlayerGPS.DiscoveredBuilding buildingData;
GameManager.Instance.PlayerGPS.GetDiscoveredBuilding(building.buildingKey, out buildingData);
if (buildingUnlocked &&
buildingType >= DFLocation.BuildingTypes.House1 &&
buildingType <= DFLocation.BuildingTypes.House4 &&
buildingData.factionID != (int)FactionFile.FactionIDs.The_Thieves_Guild &&
buildingData.factionID != (int)FactionFile.FactionIDs.The_Dark_Brotherhood &&
!DaggerfallBankManager.IsHouseOwned(building.buildingKey))
{
string greetingText = DaggerfallUnity.Instance.TextProvider.GetRandomText(houseGreetingsTextId);
mb = DaggerfallUI.MessageBox(greetingText);
}
else
mb = PresentShopQuality(building);
if (mb != null)
{
// Defer transition to interior to after user closes messagebox
deferredInteriorDoorOwner = doorOwner;
deferredInteriorDoor = door;
mb.OnClose += BuildingGreetingPopup_OnClose;
return;
}
}
// Hit door while outside, transition inside
TransitionInterior(doorOwner, door, true);
return;
}
else if (door.doorType == DoorTypes.Building && playerEnterExit.IsPlayerInside)
{
// Hit door while inside, transition outside
playerEnterExit.TransitionExterior(true);
return;
}
else if (door.doorType == DoorTypes.DungeonEntrance && !playerEnterExit.IsPlayerInside)
{
if (playerGPS)
{
// Hit dungeon door while outside, transition inside
playerEnterExit.TransitionDungeonInterior(doorOwner, door, playerGPS.CurrentLocation, true);
return;
}
}
else if (door.doorType == DoorTypes.DungeonExit && playerEnterExit.IsPlayerInside)
{
// Hit dungeon exit while inside, ask if access wagon or transition outside
if (GameManager.Instance.PlayerEntity.Items.Contains(ItemGroups.Transportation, (int)Transportation.Small_cart) && DaggerfallUnity.Settings.DungeonExitWagonPrompt)
{
DaggerfallMessageBox messageBox = new DaggerfallMessageBox(DaggerfallUI.UIManager, DaggerfallMessageBox.CommonMessageBoxButtons.YesNo, 38, DaggerfallUI.UIManager.TopWindow);
messageBox.OnButtonClick += DungeonWagonAccess_OnButtonClick;
DaggerfallUI.UIManager.PushWindow(messageBox);
return;
}
else
{
playerEnterExit.TransitionDungeonExterior(true);
}
}
}
}
int GetBuildingLockValue(int quality)
{
// Currently unknown how classic calculates building lock value but suspect related to building quality level
// No exterior buildings are known to have magically held locks, so 20 quality buildings (e.g. The Odd Blades) must have a lower lock value
// Using building quality / 2 for now until a more accurate method is known
return quality / 2;
}
int GetBuildingLockValue(BuildingSummary buildingSummary)
{
return GetBuildingLockValue(buildingSummary.Quality);
}
void ActivateActionDoor(RaycastHit hit, DaggerfallActionDoor actionDoor)
{
// Check if close enough to activate
if (hit.distance > DoorActivationDistance)
{
DaggerfallUI.SetMidScreenText(HardStrings.youAreTooFarAway);
return;
}
// Handle Lock/Open spell effects (if active)
if (HandleLockEffect(actionDoor))
return;
if (HandleOpenEffect(actionDoor))
return;
if (currentMode == PlayerActivateModes.Steal && actionDoor.IsLocked && !actionDoor.IsOpen)
{
actionDoor.AttemptLockpicking();
}
else
actionDoor.ToggleDoor(true);
}
void ActivateStaticNPC(RaycastHit hit, StaticNPC npc)
{
// Do not activate static NPCs carrying specific non-dialog actions as these usually have some bespoke task to perform
// Note: currently only ShowText and ShowTextWithInput NPCs are excluded
// Examples are guard at entrance of Daggerfall Castle and Benefactor and Sheogorath in Mantellan Crux
DaggerfallAction action = npc.GetComponent<DaggerfallAction>();
if (action &&
(action.ActionFlag == DFBlock.RdbActionFlags.ShowTextWithInput ||
action.ActionFlag == DFBlock.RdbActionFlags.ShowText))
return;
switch (currentMode)
{
case PlayerActivateModes.Info:
PresentNPCInfo(npc);
break;
case PlayerActivateModes.Grab:
case PlayerActivateModes.Talk:
case PlayerActivateModes.Steal:
if (hit.distance > StaticNPCActivationDistance)
{
DaggerfallUI.SetMidScreenText(HardStrings.youAreTooFarAway);
break;
}
StaticNPCClick(npc);
break;
}
}
void ActivateMobileNPC(RaycastHit hit, MobilePersonNPC mobileNpc)
{
switch (currentMode)
{
case PlayerActivateModes.Info:
case PlayerActivateModes.Grab:
case PlayerActivateModes.Talk:
if (hit.distance > MobileNPCActivationDistance)
{
DaggerfallUI.SetMidScreenText(HardStrings.youAreTooFarAway);
break;
}
GameManager.Instance.TalkManager.TalkToMobileNPC(mobileNpc);
break;
case PlayerActivateModes.Steal:
if (!mobileNpc.PickpocketByPlayerAttempted)
{
if (hit.distance > PickpocketDistance)
{
DaggerfallUI.SetMidScreenText(HardStrings.youAreTooFarAway);
break;
}
mobileNpc.PickpocketByPlayerAttempted = true;
Pickpocket();
}
break;
}
}
void ActivateMobileEnemy(RaycastHit hit, DaggerfallEntityBehaviour mobileEnemyBehaviour)
{
EnemyEntity enemyEntity = mobileEnemyBehaviour.Entity as EnemyEntity;
switch (currentMode)
{
case PlayerActivateModes.Info:
case PlayerActivateModes.Grab:
case PlayerActivateModes.Talk:
if (enemyEntity != null)
{
MobileEnemy mobileEnemy = enemyEntity.MobileEnemy;
bool startsWithVowel = "aeiouAEIOU".Contains(mobileEnemy.Name[0].ToString());
string message;
if (startsWithVowel)
message = HardStrings.youSeeAn;
else
message = HardStrings.youSeeA;
message = message.Replace("%s", mobileEnemy.Name);
DaggerfallUI.Instance.PopupMessage(message);
}
break;
case PlayerActivateModes.Steal:
// Classic allows pickpocketing of NPC mobiles and enemy mobiles.
// In early versions the only enemy mobiles that can be pickpocketed are classes,
// but patch 1.07.212 allows pickpocketing of creatures.
// For now, the only enemy mobiles being allowed by DF Unity are classes.
if (mobileEnemyBehaviour && (mobileEnemyBehaviour.EntityType != EntityTypes.EnemyClass))
break;
// Classic doesn't set any flag when pickpocketing enemy mobiles, so infinite attempts are possible
if (enemyEntity != null && !enemyEntity.PickpocketByPlayerAttempted)
{
if (hit.distance > PickpocketDistance)
{
DaggerfallUI.SetMidScreenText(HardStrings.youAreTooFarAway);
break;
}
enemyEntity.PickpocketByPlayerAttempted = true;
Pickpocket(mobileEnemyBehaviour);
}
break;
}
}
void ActivateLaddersAndShelves(RaycastHit hit)
{
DaggerfallLadder ladder = hit.transform.GetComponent<DaggerfallLadder>();
DaggerfallBookshelf bookshelf = hit.transform.GetComponent<DaggerfallBookshelf>();
if (ladder || bookshelf)
{
if (hit.distance > DefaultActivationDistance)
{
DaggerfallUI.SetMidScreenText(HardStrings.youAreTooFarAway);
return;
}
if (ladder)
{ // Ladders:
ladder.ClimbLadder();
}
else if (bookshelf)
{ // Bookshelves:
bookshelf.ReadBook();
}
}
}
void ActivateLootContainer(RaycastHit hit, DaggerfallLoot loot)
{
// Check if close enough to activate for all types, except for corpses
if (loot.ContainerType != LootContainerTypes.CorpseMarker &&
hit.distance > TreasureActivationDistance)
{
DaggerfallUI.SetMidScreenText(HardStrings.youAreTooFarAway);
return;
}
Random.InitState(Time.frameCount);
UserInterfaceManager uiManager = DaggerfallUI.Instance.UserInterfaceManager;
switch (loot.ContainerType)
{
// Handle shop shelves: stock shelf if needed, then open trade window with activated loot container as remote target
case LootContainerTypes.ShopShelves:
// Stock shop shelf on first access
if (loot.stockedDate < DaggerfallLoot.CreateStockedDate(DaggerfallUnity.Instance.WorldTime.Now))
loot.StockShopShelf(playerEnterExit.BuildingDiscoveryData);
// Open Trade Window if shop is open
if (GameManager.Instance.PlayerEnterExit.IsPlayerInsideOpenShop)
{
DaggerfallTradeWindow tradeWindow = (DaggerfallTradeWindow) UIWindowFactory.GetInstanceWithArgs(UIWindowType.Trade, new object[] { uiManager, null, DaggerfallTradeWindow.WindowModes.Buy, null });
tradeWindow.MerchantItems = loot.Items;
uiManager.PushWindow(tradeWindow);
return;
}
else
{ // Open Inventory if shop closed, i.e. stealing
DaggerfallUI.Instance.InventoryWindow.SetShopShelfStealing();
break;
}
// Handle house furniture containers: ask player if they want to look through private property
case LootContainerTypes.HouseContainers:
// Allow access for player owned interiors. (not distinguishing between ships)
if ((playerEnterExit.BuildingType == DFLocation.BuildingTypes.Ship && DaggerfallBankManager.OwnsShip) ||
DaggerfallBankManager.IsHouseOwned(playerEnterExit.BuildingDiscoveryData.buildingKey))
{
loot.stockedDate = 1; // Ensure it gets serialized
break;
}
// Stock house container on first access
if (loot.stockedDate < DaggerfallLoot.CreateStockedDate(DaggerfallUnity.Instance.WorldTime.Now))
loot.StockHouseContainer(playerEnterExit.BuildingDiscoveryData);
// If no contents, do nothing
if (loot.Items.Count == 0)
return;
loot.houseOwned = true;
DaggerfallMessageBox messageBox = new DaggerfallMessageBox(uiManager, DaggerfallMessageBox.CommonMessageBoxButtons.YesNo, PrivatePropertyId, uiManager.TopWindow);
messageBox.OnButtonClick += PrivateProperty_OnButtonClick;
uiManager.PushWindow(messageBox);
DaggerfallUI.Instance.InventoryWindow.LootTarget = loot;
return;
// Handle corpses: info mode gives a description
case LootContainerTypes.CorpseMarker:
if (currentMode == PlayerActivateModes.Info)
{ // Corpse info mode
if (!string.IsNullOrEmpty(loot.entityName))
DaggerfallUI.AddHUDText((loot.isEnemyClass) ? HardStrings.youSeeADeadPerson : HardStrings.youSeeADead.Replace("%s", loot.entityName));
return;
}
else
{ // Check if close enough to activate and that corpse has items
if (hit.distance > CorpseActivationDistance)
{
DaggerfallUI.SetMidScreenText(HardStrings.youAreTooFarAway);
return;
}
else if (loot.Items.Count == 0)
{
DaggerfallUI.AddHUDText(HardStrings.theBodyHasNoTreasure);
DisableEmptyCorpseContainer(loot.gameObject);
return;
}
else if (loot.Items.Count == 1 && loot.Items.Contains(ItemGroups.Weapons, (int)Weapons.Arrow))
{ // If only one item and it's arrows, then auto-pickup.
GameManager.Instance.PlayerEntity.Items.TransferAll(loot.Items);
DaggerfallUI.AddHUDText(HardStrings.youCollectArrows);
return;
}
break;
}
// No special handling for all other loot container types: (Nothing, RandomTreasure, DroppedLoot)
}
// Open inventory window with activated loot container as remote target (if we fall through to here)
DaggerfallUI.Instance.InventoryWindow.LootTarget = loot;
DaggerfallUI.PostMessage(DaggerfallUIMessages.dfuiOpenInventoryWindow);
}
void DisableEmptyCorpseContainer(GameObject go)
{
if (go)
{
SphereCollider sphereCollider = go.GetComponent<SphereCollider>();
if (sphereCollider)
sphereCollider.enabled = false;
}
}
#endregion
#region Public Static Methods
public static void LookAtInteriorLock(int lockValue)
{
if (lockValue < 20)
{
PlayerEntity player = Game.GameManager.Instance.PlayerEntity;
// There seems to be an oversight in classic. It uses two separate lockpicking functions (seems to be one for animated doors in interiors and one for exterior doors)
// but the difficulty text is always based on the exterior function.
// DF Unity doesn't have exterior locked doors yet, so the below uses the interior function.
// TODO: Implement LookAtExteriorLock variant for exterior doors
int chance = FormulaHelper.CalculateInteriorLockpickingChance(player.Level, lockValue, player.Skills.GetLiveSkillValue(DFCareer.Skills.Lockpicking));
if (chance >= 30)
if (chance >= 35)
if (chance >= 95)
Game.DaggerfallUI.SetMidScreenText(HardStrings.lockpickChance[9]);
else if (chance >= 45)
Game.DaggerfallUI.SetMidScreenText(HardStrings.lockpickChance[(chance - 45) / 5]);
else
Game.DaggerfallUI.SetMidScreenText(HardStrings.lockpickChance3);
else
Game.DaggerfallUI.SetMidScreenText(HardStrings.lockpickChance2);
else
Game.DaggerfallUI.SetMidScreenText(HardStrings.lockpickChance1);
}
else
Game.DaggerfallUI.SetMidScreenText(HardStrings.magicLock);
}
#endregion
bool HandleLockEffect(DaggerfallActionDoor actionDoor)
{
// Check if player has Lock effect running
Lock lockEffect = (Lock)GameManager.Instance.PlayerEffectManager.FindIncumbentEffect<Lock>();
if (lockEffect == null)
return false;
lockEffect.TriggerLockEffect(actionDoor);
return true;
}
bool HandleOpenEffect(DaggerfallActionDoor actionDoor)
{
// Check if player has Open effect running
Open openEffect = (Open)GameManager.Instance.PlayerEffectManager.FindIncumbentEffect<Open>();
if (openEffect == null)
return false;
openEffect.TriggerOpenEffect(actionDoor);
return true;
}
// NOTE: Open effect currently ALWAYS works on exterior doors, should operate on lock level
// Lockpick and lock level not fully implemented on exterior doors
bool HandleOpenEffectOnExteriorDoor(int buildingLockValue)
{
// Check if player has Open effect running
Open openEffect = (Open)GameManager.Instance.PlayerEffectManager.FindIncumbentEffect<Open>();
if (openEffect == null)
return false;
// Cancel effect
openEffect.CancelEffect();
// Player level must meet or exceed lock level for success
if (GameManager.Instance.PlayerEntity.Level < buildingLockValue)
{
DaggerfallUI.AddHUDText(TextManager.Instance.GetText("ClassicEffects", "openFailed"), 1.5f);
return false;
}
return true;
}
/// <summary>
/// Set a click delay before new clicks are accepted, usually when exiting UI.
/// </summary>
/// <param name="delay">Delay in seconds. Valid range is 0.0 - 1.0</param>
public void SetClickDelay(float delay = 0.3f)
{
clickDelay = Mathf.Clamp01(delay);
clickDelayStartTime = Time.realtimeSinceStartup;
}
public bool AttemptExteriorDoorBash(RaycastHit hit)
{
Transform doorOwner;
DaggerfallStaticDoors doors = GetDoors(hit.transform, out doorOwner);
StaticDoor door;
if (doors && doors.HasHit(hit.point, out door))
{
// Discover building - this is needed to check lock level and transition to interior
GameManager.Instance.PlayerGPS.DiscoverBuilding(door.buildingKey);
// Play bashing sound
DaggerfallAudioSource dfAudioSource = GetComponent<DaggerfallAudioSource>();
if (dfAudioSource != null)
dfAudioSource.PlayOneShot(SoundClips.PlayerDoorBash);
// Get lock value from discovered building
int lockValue = 0;
PlayerGPS.DiscoveredBuilding discoveredBuilding;
if (GameManager.Instance.PlayerGPS.GetDiscoveredBuilding(door.buildingKey, out discoveredBuilding))
lockValue = GetBuildingLockValue(discoveredBuilding.quality);
// Roll for chance to open - Lower lock values have a higher chance
PlayerEntity playerEntity = GameManager.Instance.PlayerEntity;
Random.InitState(Time.frameCount);
int chance = 25 - lockValue;
if (Dice100.SuccessRoll(chance))
{
// Success - player has forced their way into building
playerEntity.TallyCrimeGuildRequirements(true, 1);
TransitionInterior(doorOwner, door, true);
return true;
}
else
{
// Bashing doors in cities is a crime - 10% chance of summoning guards on each failed bash attempt
if (Dice100.SuccessRoll(10))
{
Debug.Log("Breaking and entering detected - spawning city guards.");
playerEntity.CrimeCommitted = PlayerEntity.Crimes.Attempted_Breaking_And_Entering;
playerEntity.SpawnCityGuards(true);
}
}
}
return false;
}
public void PrivateProperty_OnButtonClick(DaggerfallMessageBox sender, DaggerfallMessageBox.MessageBoxButtons messageBoxButton)
{
sender.CloseWindow();
if (messageBoxButton == DaggerfallMessageBox.MessageBoxButtons.Yes)
{
// Open inventory window with activated private container as remote target (pre-set)
DaggerfallUI.PostMessage(DaggerfallUIMessages.dfuiOpenInventoryWindow);
}
else
DaggerfallUI.Instance.InventoryWindow.LootTarget = null;
}
// Custom transition to store building data before entering building
private void TransitionInterior(Transform doorOwner, StaticDoor door, bool doFade = false)
{
// Get building directory for location
BuildingDirectory buildingDirectory = GameManager.Instance.StreamingWorld.GetCurrentBuildingDirectory();
if (!buildingDirectory)
{
Debug.LogError("PlayerActivate.TransitionInterior() could not retrieve BuildingDirectory.");
return;
}
// Get building discovery data - this is added when player clicks door at exterior
PlayerGPS.DiscoveredBuilding db;
if (!GameManager.Instance.PlayerGPS.GetDiscoveredBuilding(door.buildingKey, out db))
{
Debug.LogErrorFormat("PlayerActivate.TransitionInterior() could not retrieve DiscoveredBuilding for key {0}.", door.buildingKey);
return;
}
// Perform transition
playerEnterExit.BuildingDiscoveryData = db;
playerEnterExit.IsPlayerInsideOpenShop = RMBLayout.IsShop(db.buildingType) && IsBuildingOpen(db.buildingType);
playerEnterExit.TransitionInterior(doorOwner, door, doFade, false);
}