/
FormulaHelper.cs
3164 lines (2724 loc) · 149 KB
/
FormulaHelper.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-2023 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: Allofich, Hazelnut, ifkopifko, Numidium, TheLacus
//
// Notes:
//
using UnityEngine;
using System;
using DaggerfallConnect;
using DaggerfallWorkshop.Game.Guilds;
using DaggerfallWorkshop.Game.Entity;
using DaggerfallWorkshop.Game.MagicAndEffects;
using DaggerfallWorkshop.Game.MagicAndEffects.MagicEffects;
using System.Collections.Generic;
using DaggerfallConnect.Arena2;
using DaggerfallWorkshop.Game.Items;
using DaggerfallWorkshop.Utility;
using DaggerfallConnect.Save;
using DaggerfallWorkshop.Game.Utility;
using DaggerfallWorkshop.Game.Utility.ModSupport;
using DaggerfallWorkshop.Game.Banking;
namespace DaggerfallWorkshop.Game.Formulas
{
/// <summary>
/// Common formulas used throughout game.
/// Where the exact formula is unknown, a "best effort" approximation will be used.
/// Most formula can be overridden by registering a new method matching the appropriate delegate signature.
/// Other signatures can be added upon demand.
/// </summary>
public static class FormulaHelper
{
private struct FormulaOverride
{
internal readonly Delegate Formula;
internal readonly Mod Provider;
internal FormulaOverride(Delegate formula, Mod provider)
{
Formula = formula;
Provider = provider;
}
}
readonly static Dictionary<string, FormulaOverride> overrides = new Dictionary<string, FormulaOverride>();
public static float specialInfectionChance = 0.6f;
// Approximation of classic frame updates
public const int classicFrameUpdate = 980;
/// <summary>Struct for return values of formula that affect damage and to-hit chance.</summary>
public struct ToHitAndDamageMods
{
public int damageMod;
public int toHitMod;
}
#region Basic Formulas
public static int DamageModifier(int strength)
{
Func<int, int> del;
if (TryGetOverride("DamageModifier", out del))
return del(strength);
return (int)Mathf.Floor((float)(strength - 50) / 5f);
}
public static int MaxEncumbrance(int strength)
{
Func<int, int> del;
if (TryGetOverride("MaxEncumbrance", out del))
return del(strength);
return (int)Mathf.Floor((float)strength * 1.5f);
}
public static int SpellPoints(int intelligence, float multiplier)
{
Func<int, float, int> del;
if (TryGetOverride("SpellPoints", out del))
return del(intelligence, multiplier);
return (int)Mathf.Floor((float)intelligence * multiplier);
}
public static int MagicResist(int willpower)
{
Func<int, int> del;
if (TryGetOverride("MagicResist", out del))
return del(willpower);
return (int)Mathf.Floor((float)willpower / 10f);
}
public static int ToHitModifier(int agility)
{
Func<int, int> del;
if (TryGetOverride("ToHitModifier", out del))
return del(agility);
return (int)Mathf.Floor((float)agility / 10f) - 5;
}
public static int HitPointsModifier(int endurance)
{
Func<int, int> del;
if (TryGetOverride("HitPointsModifier", out del))
return del(endurance);
return (int)Mathf.Floor((float)endurance / 10f) - 5;
}
public static int HealingRateModifier(int endurance)
{
Func<int, int> del;
if (TryGetOverride("HealingRateModifier", out del))
return del(endurance);
// Original Daggerfall seems to have a bug where negative endurance modifiers on healing rate
// are applied as modifier + 1. Not recreating that here.
return (int)Mathf.Floor((float)endurance / 10f) - 5;
}
public static int MaxStatValue()
{
Func<int> del;
if (TryGetOverride("MaxStatValue", out del))
return del();
else
return 100;
}
public static int BonusPool()
{
Func<int> del;
if (TryGetOverride("BonusPool", out del))
return del();
const int minBonusPool = 4; // The minimum number of free points to allocate on level up
const int maxBonusPool = 6; // The maximum number of free points to allocate on level up
// Roll bonus pool for player to distribute
// Using maxBonusPool + 1 for inclusive range
UnityEngine.Random.InitState(Time.frameCount);
return UnityEngine.Random.Range(minBonusPool, maxBonusPool + 1);
}
#endregion
#region Player
// Generates player health based on level and career hit points per level
public static int RollMaxHealth(PlayerEntity player)
{
Func<PlayerEntity, int> del;
if (TryGetOverride("RollMaxHealth", out del))
return del(player);
const int baseHealth = 25;
int maxHealth = baseHealth + player.Career.HitPointsPerLevel;
for (int i = 1; i < player.Level; i++)
{
maxHealth += CalculateHitPointsPerLevelUp(player);
}
return maxHealth;
}
// Calculate how much health the player should recover per hour of rest
public static int CalculateHealthRecoveryRate(PlayerEntity player)
{
Func<PlayerEntity, int> del;
if (TryGetOverride("CalculateHealthRecoveryRate", out del))
return del(player);
short medical = player.Skills.GetLiveSkillValue(DFCareer.Skills.Medical);
int endurance = player.Stats.LiveEndurance;
int maxHealth = player.MaxHealth;
PlayerEnterExit playerEnterExit;
playerEnterExit = GameManager.Instance.PlayerGPS.GetComponent<PlayerEnterExit>();
DFCareer.RapidHealingFlags rapidHealingFlags = player.Career.RapidHealing;
short addToMedical = 60;
if (rapidHealingFlags == DFCareer.RapidHealingFlags.Always)
addToMedical = 100;
else if (DaggerfallUnity.Instance.WorldTime.DaggerfallDateTime.IsDay && !playerEnterExit.IsPlayerInside)
{
if (rapidHealingFlags == DFCareer.RapidHealingFlags.InLight)
addToMedical = 100;
}
else if (rapidHealingFlags == DFCareer.RapidHealingFlags.InDarkness)
addToMedical = 100;
medical += addToMedical;
return Mathf.Max((int)Mathf.Floor(HealingRateModifier(endurance) + medical * maxHealth / 1000), 1);
}
// Calculate how much fatigue the player should recover per hour of rest
public static int CalculateFatigueRecoveryRate(int maxFatigue)
{
Func<int, int> del;
if (TryGetOverride("CalculateFatigueRecoveryRate", out del))
return del(maxFatigue);
return Mathf.Max((int)Mathf.Floor(maxFatigue / 8), 1);
}
// Calculate how many spell points the player should recover per hour of rest
public static int CalculateSpellPointRecoveryRate(PlayerEntity player)
{
Func<PlayerEntity, int> del;
if (TryGetOverride("CalculateSpellPointRecoveryRate", out del))
return del(player);
if (player.Career.NoRegenSpellPoints)
return 0;
return Mathf.Max((int)Mathf.Floor(player.MaxMagicka / 8), 1);
}
// Calculate chance of successfully lockpicking a door in an interior (an animating door). If this is higher than a random number between 0 and 100 (inclusive), the lockpicking succeeds.
public static int CalculateInteriorLockpickingChance(int level, int lockvalue, int lockpickingSkill)
{
Func<int, int, int, int> del;
if (TryGetOverride("CalculateInteriorLockpickingChance", out del))
return del(level, lockvalue, lockpickingSkill);
int chance = (5 * (level - lockvalue) + lockpickingSkill);
return Mathf.Clamp(chance, 5, 95);
}
// Calculate chance of successfully lockpicking a door in an exterior (a door that leads to an interior). If this is higher than a random number between 0 and 100 (inclusive), the lockpicking succeeds.
public static int CalculateExteriorLockpickingChance(int lockvalue, int lockpickingSkill)
{
Func<int, int, int> del;
if (TryGetOverride("CalculateExteriorLockpickingChance", out del))
return del(lockvalue, lockpickingSkill);
int chance = lockpickingSkill - (5 * lockvalue);
return Mathf.Clamp(chance, 5, 95);
}
// Calculate chance of successfully pickpocketing a target
public static int CalculatePickpocketingChance(PlayerEntity player, EnemyEntity target)
{
Func<PlayerEntity, EnemyEntity, int> del;
if (TryGetOverride("CalculatePickpocketingChance", out del))
return del(player, target);
int chance = player.Skills.GetLiveSkillValue(DFCareer.Skills.Pickpocket);
// If target is an enemy mobile, apply level modifier.
if (target != null)
{
chance += 5 * ((player.Level) - (target.Level));
}
return Mathf.Clamp(chance, 5, 95);
}
// Calculate chance of being caught shoplifting items
public static int CalculateShopliftingChance(PlayerEntity player, int shopQuality, int weightAndNumItems)
{
Func<PlayerEntity, int, int, int> del;
if (TryGetOverride("CalculateShopliftingChance", out del))
return del(player, shopQuality, weightAndNumItems);
int chance = 100 - player.Skills.GetLiveSkillValue(DFCareer.Skills.Pickpocket);
chance += shopQuality + weightAndNumItems;
return Mathf.Clamp(chance, 5, 95);
}
// Calculate chance of stealth skill hiding the user.
public static int CalculateStealthChance(float distanceToTarget, DaggerfallEntityBehaviour target)
{
Func<float, DaggerfallEntityBehaviour, int> del;
if (TryGetOverride("CalculateStealthChance", out del))
return del(distanceToTarget, target);
int chance = 2 * ((int)(distanceToTarget / MeshReader.GlobalScale) * target.Entity.Skills.GetLiveSkillValue(DFCareer.Skills.Stealth) >> 10);
return chance;
}
// Calculate chance of successfully climbing - checked repeatedly while climbing
public static int CalculateClimbingChance(PlayerEntity player, int basePercentSuccess)
{
Func<PlayerEntity, int, int> del;
if (TryGetOverride("CalculateClimbingChance", out del))
return del(player, basePercentSuccess);
int skill = player.Skills.GetLiveSkillValue(DFCareer.Skills.Climbing);
int luck = player.Stats.GetLiveStatValue(DFCareer.Stats.Luck);
if (player.Race == Races.Khajiit)
skill += 30;
// Climbing effect states "target can climb twice as well" - doubling effective skill after racial applied
if (player.IsEnhancedClimbing)
skill *= 2;
// Clamp skill range
skill = Mathf.Clamp(skill, 5, 95);
float luckFactor = Mathf.Lerp(0, 10, luck * 0.01f);
// Skill Check
int chance = (int) (Mathf.Lerp(basePercentSuccess, 100, skill * .01f) + luckFactor);
return chance;
}
// Calculate how many uses a skill needs before its value will rise.
public static int CalculateSkillUsesForAdvancement(int skillValue, int skillAdvancementMultiplier, float careerAdvancementMultiplier, int level)
{
Func<int, int, float, int, int> del;
if (TryGetOverride("CalculateSkillUsesForAdvancement", out del))
return del(skillValue, skillAdvancementMultiplier, careerAdvancementMultiplier, level);
double levelMod = Math.Pow(1.04, level);
return (int)Math.Floor((skillValue * skillAdvancementMultiplier * careerAdvancementMultiplier * levelMod * 2 / 5) + 1);
}
// Calculate player level.
public static int CalculatePlayerLevel(int startingLevelUpSkillsSum, int currentLevelUpSkillsSum)
{
Func<int, int, int> del;
if (TryGetOverride("CalculatePlayerLevel", out del))
return del(startingLevelUpSkillsSum, currentLevelUpSkillsSum);
return (int)Mathf.Floor((currentLevelUpSkillsSum - startingLevelUpSkillsSum + 28) / 15);
}
// Calculate hit points player gains per level.
public static int CalculateHitPointsPerLevelUp(PlayerEntity player)
{
Func<PlayerEntity, int> del;
if (TryGetOverride("CalculateHitPointsPerLevelUp", out del))
return del(player);
int minRoll = player.Career.HitPointsPerLevel / 2;
int maxRoll = player.Career.HitPointsPerLevel;
DFRandom.Seed = (uint)Time.renderedFrameCount;
int addHitPoints = DFRandom.random_range_inclusive(minRoll, maxRoll);
addHitPoints += HitPointsModifier(player.Stats.PermanentEndurance);
if (addHitPoints < 1)
addHitPoints = 1;
return addHitPoints;
}
// Calculate whether the player is successful at pacifying an enemy.
public static bool CalculateEnemyPacification(PlayerEntity player, DFCareer.Skills languageSkill)
{
Func<PlayerEntity, DFCareer.Skills, bool> del;
if (TryGetOverride("CalculateEnemyPacification", out del))
return del(player, languageSkill);
double chance = 0;
if (languageSkill == DFCareer.Skills.Etiquette ||
languageSkill == DFCareer.Skills.Streetwise)
{
chance += player.Skills.GetLiveSkillValue(languageSkill) / 10;
chance += player.Stats.LivePersonality / 5;
}
else
{
chance += player.Skills.GetLiveSkillValue(languageSkill);
chance += player.Stats.LivePersonality / 10;
}
chance += GameManager.Instance.WeaponManager.Sheathed ? 10 : -25;
// Add chance from Comprehend Languages effect if present
ComprehendLanguages languagesEffect = (ComprehendLanguages)GameManager.Instance.PlayerEffectManager.FindIncumbentEffect<ComprehendLanguages>();
if (languagesEffect != null)
chance += languagesEffect.ChanceValue();
int roll = UnityEngine.Random.Range(0, 200);
bool success = (roll < chance);
//if (success)
// player.TallySkill(languageSkill, 1);
//else if (languageSkill != DFCareer.Skills.Etiquette && languageSkill != DFCareer.Skills.Streetwise)
// player.TallySkill(languageSkill, 1);
Debug.LogFormat("Pacification {3} using {0} skill: chance= {1} roll= {2}", languageSkill, chance, roll, success ? "success" : "failure");
return success;
}
// Calculate whether the player is blessed when donating to a Temple.
public static int CalculateTempleBlessing(int donationAmount, int deityRep)
{
return 1; // TODO Amount of stat boost, guessing what this formula might need...
}
// Gets vampire clan based on region
public static VampireClans GetVampireClan(int regionIndex)
{
FactionFile.FactionData factionData;
GameManager.Instance.PlayerEntity.FactionData.GetRegionFaction(regionIndex, out factionData);
switch ((FactionFile.FactionIDs) factionData.vam)
{
case FactionFile.FactionIDs.The_Vraseth:
return VampireClans.Vraseth;
case FactionFile.FactionIDs.The_Haarvenu:
return VampireClans.Haarvenu;
case FactionFile.FactionIDs.The_Thrafey:
return VampireClans.Thrafey;
case FactionFile.FactionIDs.The_Lyrezi:
return VampireClans.Lyrezi;
case FactionFile.FactionIDs.The_Montalion:
return VampireClans.Montalion;
case FactionFile.FactionIDs.The_Khulari:
return VampireClans.Khulari;
case FactionFile.FactionIDs.The_Garlythi:
return VampireClans.Garlythi;
case FactionFile.FactionIDs.The_Anthotis:
return VampireClans.Anthotis;
case FactionFile.FactionIDs.The_Selenu:
return VampireClans.Selenu;
}
// The Lyrezi are the default like in classic
return VampireClans.Lyrezi;
}
#endregion
#region Combat & Damage
public static int CalculateHandToHandMinDamage(int handToHandSkill)
{
Func<int, int> del;
if (TryGetOverride("CalculateHandToHandMinDamage", out del))
return del(handToHandSkill);
return (handToHandSkill / 10) + 1;
}
public static int CalculateHandToHandMaxDamage(int handToHandSkill)
{
Func<int, int> del;
if (TryGetOverride("CalculateHandToHandMaxDamage", out del))
return del(handToHandSkill);
// Daggerfall Chronicles table lists hand-to-hand skills of 80 and above (45 through 79 are omitted)
// as if they give max damage of (handToHandSkill / 5) + 2, but the hand-to-hand damage display in the character sheet
// in classic Daggerfall shows it as continuing to be (handToHandSkill / 5) + 1
return (handToHandSkill / 5) + 1;
}
public static int CalculateWeaponMinDamage(Weapons weapon)
{
Func<Weapons, int> del;
if (TryGetOverride("CalculateWeaponMinDamage", out del))
return del(weapon);
switch (weapon)
{
case Weapons.Dagger:
case Weapons.Tanto:
case Weapons.Wakazashi:
case Weapons.Shortsword:
case Weapons.Broadsword:
case Weapons.Staff:
case Weapons.Mace:
return 1;
case Weapons.Longsword:
case Weapons.Claymore:
case Weapons.Battle_Axe:
case Weapons.War_Axe:
case Weapons.Flail:
return 2;
case Weapons.Saber:
case Weapons.Katana:
case Weapons.Dai_Katana:
case Weapons.Warhammer:
return 3;
case Weapons.Short_Bow:
case Weapons.Long_Bow:
return 4;
default:
return 0;
}
}
public static int CalculateWeaponMaxDamage(Weapons weapon)
{
Func<Weapons, int> del;
if (TryGetOverride("CalculateWeaponMaxDamage", out del))
return del(weapon);
switch (weapon)
{
case Weapons.Dagger:
return 6;
case Weapons.Tanto:
case Weapons.Shortsword:
case Weapons.Staff:
return 8;
case Weapons.Wakazashi:
return 10;
case Weapons.Broadsword:
case Weapons.Saber:
case Weapons.Battle_Axe:
case Weapons.Mace:
return 12;
case Weapons.Flail:
return 14;
case Weapons.Longsword:
case Weapons.Katana:
case Weapons.War_Axe:
case Weapons.Short_Bow:
return 16;
case Weapons.Claymore:
case Weapons.Warhammer:
case Weapons.Long_Bow:
return 18;
case Weapons.Dai_Katana:
return 21;
default:
return 0;
}
}
/// <summary>
/// Calculate the damage caused by an attack.
/// </summary>
/// <param name="attacker">Attacking entity</param>
/// <param name="target">Target entity</param>
/// <param name="isEnemyFacingAwayFromPlayer">Whether enemy is facing away from player, used for backstabbing</param>
/// <param name="weaponAnimTime">Time the weapon animation lasted before the attack in ms, used for bow drawing </param>
/// <param name="weapon">The weapon item being used</param>
/// <returns>Damage inflicted to target, can be 0 for a miss or ineffective hit</returns>
public static int CalculateAttackDamage(DaggerfallEntity attacker, DaggerfallEntity target, bool isEnemyFacingAwayFromPlayer, int weaponAnimTime, DaggerfallUnityItem weapon)
{
if (attacker == null || target == null)
return 0;
Func<DaggerfallEntity, DaggerfallEntity, bool, int, DaggerfallUnityItem, int> del;
if (TryGetOverride("CalculateAttackDamage", out del))
return del(attacker, target, isEnemyFacingAwayFromPlayer, weaponAnimTime, weapon);
int damageModifiers = 0;
int damage = 0;
int chanceToHitMod = 0;
int backstabChance = 0;
PlayerEntity player = GameManager.Instance.PlayerEntity;
short skillID = 0;
// Choose whether weapon-wielding enemies use their weapons or weaponless attacks.
// In classic, weapon-wielding enemies use the damage values of their weapons
// instead of their weaponless values.
// For some enemies this gives lower damage than similar-tier monsters
// and the weaponless values seems more appropriate, so here
// enemies will choose to use their weaponless attack if it is more damaging.
EnemyEntity AIAttacker = attacker as EnemyEntity;
if (AIAttacker != null && weapon != null)
{
int weaponAverage = (weapon.GetBaseDamageMin() + weapon.GetBaseDamageMax()) / 2;
int noWeaponAverage = (AIAttacker.MobileEnemy.MinDamage + AIAttacker.MobileEnemy.MaxDamage) / 2;
if (noWeaponAverage > weaponAverage)
{
// Use hand-to-hand
weapon = null;
}
}
if (weapon != null)
{
// If the attacker is using a weapon, check if the material is high enough to damage the target
if (target.MinMetalToHit > (WeaponMaterialTypes)weapon.NativeMaterialValue)
{
if (attacker == player)
{
DaggerfallUI.Instance.PopupMessage(TextManager.Instance.GetLocalizedText("materialIneffective"));
}
return 0;
}
// Get weapon skill used
skillID = weapon.GetWeaponSkillIDAsShort();
}
else
{
skillID = (short)DFCareer.Skills.HandToHand;
}
chanceToHitMod = attacker.Skills.GetLiveSkillValue(skillID);
if (attacker == player)
{
// Apply swing modifiers
ToHitAndDamageMods swingMods = CalculateSwingModifiers(GameManager.Instance.WeaponManager.ScreenWeapon);
damageModifiers += swingMods.damageMod;
chanceToHitMod += swingMods.toHitMod;
// Apply proficiency modifiers
ToHitAndDamageMods proficiencyMods = CalculateProficiencyModifiers(attacker, weapon);
damageModifiers += proficiencyMods.damageMod;
chanceToHitMod += proficiencyMods.toHitMod;
// Apply racial bonuses
ToHitAndDamageMods racialMods = CalculateRacialModifiers(attacker, weapon, player);
damageModifiers += racialMods.damageMod;
chanceToHitMod += racialMods.toHitMod;
backstabChance = CalculateBackstabChance(player, null, isEnemyFacingAwayFromPlayer);
chanceToHitMod += backstabChance;
}
// Choose struck body part
int struckBodyPart = CalculateStruckBodyPart();
// Get damage for weaponless attacks
if (skillID == (short)DFCareer.Skills.HandToHand)
{
if (attacker == player || (AIAttacker != null && AIAttacker.EntityType == EntityTypes.EnemyClass))
{
if (CalculateSuccessfulHit(attacker, target, chanceToHitMod, struckBodyPart))
{
damage = CalculateHandToHandAttackDamage(attacker, target, damageModifiers, attacker == player);
damage = CalculateBackstabDamage(damage, backstabChance);
}
}
else if (AIAttacker != null) // attacker is a monster
{
// Handle multiple attacks by AI
int minBaseDamage = 0;
int maxBaseDamage = 0;
int attackNumber = 0;
while (attackNumber < 3) // Classic supports up to 5 attacks but no monster has more than 3
{
if (attackNumber == 0)
{
minBaseDamage = AIAttacker.MobileEnemy.MinDamage;
maxBaseDamage = AIAttacker.MobileEnemy.MaxDamage;
}
else if (attackNumber == 1)
{
minBaseDamage = AIAttacker.MobileEnemy.MinDamage2;
maxBaseDamage = AIAttacker.MobileEnemy.MaxDamage2;
}
else if (attackNumber == 2)
{
minBaseDamage = AIAttacker.MobileEnemy.MinDamage3;
maxBaseDamage = AIAttacker.MobileEnemy.MaxDamage3;
}
int reflexesChance = 50 - (10 * ((int)player.Reflexes - 2));
int hitDamage = 0;
if (DFRandom.rand() % 100 < reflexesChance && minBaseDamage > 0 && CalculateSuccessfulHit(attacker, target, chanceToHitMod, struckBodyPart))
{
hitDamage = UnityEngine.Random.Range(minBaseDamage, maxBaseDamage + 1);
// Apply special monster attack effects
if (hitDamage > 0)
OnMonsterHit(AIAttacker, target, hitDamage);
damage += hitDamage;
}
// Apply bonus damage only when monster has actually hit, or they will accumulate bonus damage even for missed attacks and zero-damage attacks
if (hitDamage > 0)
damage += GetBonusOrPenaltyByEnemyType(attacker, target);
++attackNumber;
}
}
}
// Handle weapon attacks
else if (weapon != null)
{
// Apply weapon material modifier.
chanceToHitMod += CalculateWeaponToHit(weapon);
// Mod hook for adjusting final hit chance mod and adding new elements to calculation. (no-op in DFU)
chanceToHitMod = AdjustWeaponHitChanceMod(attacker, target, chanceToHitMod, weaponAnimTime, weapon);
if (CalculateSuccessfulHit(attacker, target, chanceToHitMod, struckBodyPart))
{
damage = CalculateWeaponAttackDamage(attacker, target, damageModifiers, weaponAnimTime, weapon);
damage = CalculateBackstabDamage(damage, backstabChance);
}
// Handle poisoned weapons
if (damage > 0 && weapon.poisonType != Poisons.None)
{
InflictPoison(attacker, target, weapon.poisonType, false);
weapon.poisonType = Poisons.None;
}
}
damage = Mathf.Max(0, damage);
DamageEquipment(attacker, target, damage, weapon, struckBodyPart);
// Apply Ring of Namira effect
if (target == player)
{
DaggerfallUnityItem[] equippedItems = target.ItemEquipTable.EquipTable;
DaggerfallUnityItem item = null;
if (equippedItems.Length != 0)
{
if (IsRingOfNamira(equippedItems[(int)EquipSlots.Ring0]) || IsRingOfNamira(equippedItems[(int)EquipSlots.Ring1]))
{
IEntityEffect effectTemplate = GameManager.Instance.EntityEffectBroker.GetEffectTemplate(RingOfNamiraEffect.EffectKey);
effectTemplate.EnchantmentPayloadCallback(EnchantmentPayloadFlags.None,
targetEntity: AIAttacker.EntityBehaviour,
sourceItem: item,
sourceDamage: damage);
}
}
}
//Debug.LogFormat("Damage {0} applied, animTime={1} ({2})", damage, weaponAnimTime, GameManager.Instance.WeaponManager.ScreenWeapon.WeaponState);
return damage;
}
private static bool IsRingOfNamira(DaggerfallUnityItem item)
{
return item != null && item.ContainsEnchantment(DaggerfallConnect.FallExe.EnchantmentTypes.SpecialArtifactEffect, (int)ArtifactsSubTypes.Ring_of_Namira);
}
public static int CalculateWeaponAttackDamage(DaggerfallEntity attacker, DaggerfallEntity target, int damageModifier, int weaponAnimTime, DaggerfallUnityItem weapon)
{
Func<DaggerfallEntity, DaggerfallEntity, int, int, DaggerfallUnityItem, int> del;
if (TryGetOverride("CalculateWeaponAttackDamage", out del))
return del(attacker, target, damageModifier, weaponAnimTime, weapon);
int damage = UnityEngine.Random.Range(weapon.GetBaseDamageMin(), weapon.GetBaseDamageMax() + 1) + damageModifier;
if (target != GameManager.Instance.PlayerEntity)
{
if ((target as EnemyEntity).CareerIndex == (int)MonsterCareers.SkeletalWarrior)
{
// Apply edged-weapon damage modifier for Skeletal Warrior
if ((weapon.flags & 0x10) == 0)
damage /= 2;
// Apply silver weapon damage modifier for Skeletal Warrior
// Arena applies a silver weapon damage bonus for undead enemies, which is probably where this comes from.
if (weapon.NativeMaterialValue == (int)WeaponMaterialTypes.Silver)
damage *= 2;
}
}
// TODO: Apply strength bonus from Mace of Molag Bal
// Apply strength modifier
damage += DamageModifier(attacker.Stats.LiveStrength);
// Apply material modifier.
// The in-game display in Daggerfall of weapon damages with material modifiers is incorrect. The material modifier is half of what the display suggests.
damage += weapon.GetWeaponMaterialModifier();
if (damage < 1)
damage = 0;
damage += GetBonusOrPenaltyByEnemyType(attacker, target);
// Mod hook for adjusting final weapon damage. (no-op in DFU)
damage = AdjustWeaponAttackDamage(attacker, target, damage, weaponAnimTime, weapon);
return damage;
}
public static int CalculateHandToHandAttackDamage(DaggerfallEntity attacker, DaggerfallEntity target, int damageModifier, bool player)
{
Func<DaggerfallEntity, DaggerfallEntity, int, int> del;
if (TryGetOverride("CalculateHandToHandAttackDamage", out del))
return del(attacker, target, damageModifier);
int minBaseDamage = CalculateHandToHandMinDamage(attacker.Skills.GetLiveSkillValue(DFCareer.Skills.HandToHand));
int maxBaseDamage = CalculateHandToHandMaxDamage(attacker.Skills.GetLiveSkillValue(DFCareer.Skills.HandToHand));
int damage = UnityEngine.Random.Range(minBaseDamage, maxBaseDamage + 1);
// Apply damage modifiers.
damage += damageModifier;
// Apply strength modifier for players. It is not applied in classic despite what the in-game description for the Strength attribute says.
if (player)
damage += DamageModifier(attacker.Stats.LiveStrength);
damage += GetBonusOrPenaltyByEnemyType(attacker, target);
return damage;
}
/// <summary>
/// Calculates whether an attack on a target is successful or not.
/// </summary>
public static bool CalculateSuccessfulHit(DaggerfallEntity attacker, DaggerfallEntity target, int chanceToHitMod, int struckBodyPart)
{
if (attacker == null || target == null)
return false;
Func<DaggerfallEntity, DaggerfallEntity, int, int, bool> del;
if (TryGetOverride("CalculateSuccessfulHit", out del))
return del(attacker, target, chanceToHitMod, struckBodyPart);
int chanceToHit = chanceToHitMod;
// Get armor value for struck body part
chanceToHit += CalculateArmorToHit(target, struckBodyPart);
// Apply adrenaline rush modifiers.
chanceToHit += CalculateAdrenalineRushToHit(attacker, target);
// Apply enchantment modifier
chanceToHit += attacker.ChanceToHitModifier;
// Apply stat differential modifiers. (default: luck and agility)
chanceToHit += CalculateStatsToHit(attacker, target);
// Apply skill modifiers. (default: dodge and crit strike)
chanceToHit += CalculateSkillsToHit(attacker, target);
// Apply monster modifier and biography adjustments.
chanceToHit += CalculateAdjustmentsToHit(attacker, target);
chanceToHit = Mathf.Clamp(chanceToHit, 3, 97);
return Dice100.SuccessRoll(chanceToHit);
}
public static float GetMeleeWeaponAnimTime(PlayerEntity player, WeaponTypes weaponType, ItemHands weaponHands)
{
Func<PlayerEntity, WeaponTypes, ItemHands, float> del;
if (TryGetOverride("GetMeleeWeaponAnimTime", out del))
return del(player, weaponType, weaponHands);
float speed = 3 * (115 - player.Stats.LiveSpeed);
return speed / classicFrameUpdate;
}
public static float GetBowCooldownTime(PlayerEntity player)
{
Func<PlayerEntity, float> del;
if (TryGetOverride("GetBowCooldownTime", out del))
return del(player);
float cooldown = 10 * (100 - player.Stats.LiveSpeed) + 800;
return cooldown / classicFrameUpdate;
}
public static int CalculateCasterLevel(DaggerfallEntity caster, IEntityEffect effect)
{
Func<DaggerfallEntity, IEntityEffect, int> del;
if (TryGetOverride("CalculateCasterLevel", out del))
return del(caster, effect);
return caster != null ? caster.Level : 1;
}
#endregion
#region Combat & Damage: component sub-formula
public static int CalculateStruckBodyPart()
{
Func<int> del;
if (TryGetOverride("CalculateStruckBodyPart", out del))
return del();
int[] bodyParts = { 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 6 };
return bodyParts[UnityEngine.Random.Range(0, bodyParts.Length)];
}
public static ToHitAndDamageMods CalculateSwingModifiers(FPSWeapon onscreenWeapon)
{
Func<FPSWeapon, ToHitAndDamageMods> del;
if (TryGetOverride("CalculateSwingModifiers", out del))
return del(onscreenWeapon);
ToHitAndDamageMods mods = new ToHitAndDamageMods();
if (onscreenWeapon != null)
{
// The Daggerfall manual groups diagonal slashes to the left and right as if they are the same, but they are different.
// Classic does not apply swing modifiers to unarmed attacks.
if (onscreenWeapon.WeaponState == WeaponStates.StrikeUp)
{
mods.damageMod = -4;
mods.toHitMod = 10;
}
if (onscreenWeapon.WeaponState == WeaponStates.StrikeDownRight)
{
mods.damageMod = -2;
mods.toHitMod = 5;
}
if (onscreenWeapon.WeaponState == WeaponStates.StrikeDownLeft)
{
mods.damageMod = 2;
mods.toHitMod = -5;
}
if (onscreenWeapon.WeaponState == WeaponStates.StrikeDown)
{
mods.damageMod = 4;
mods.toHitMod = -10;
}
}
return mods;
}
public static ToHitAndDamageMods CalculateProficiencyModifiers(DaggerfallEntity attacker, DaggerfallUnityItem weapon)
{
Func<DaggerfallEntity, DaggerfallUnityItem, ToHitAndDamageMods> del;
if (TryGetOverride("CalculateProficiencyModifiers", out del))
return del(attacker, weapon);
ToHitAndDamageMods mods = new ToHitAndDamageMods();
if (weapon != null)
{
// Apply weapon proficiency
if (((int)attacker.Career.ExpertProficiencies & weapon.GetWeaponSkillUsed()) != 0)
{
mods.damageMod = (attacker.Level / 3) + 1;
mods.toHitMod = attacker.Level;
}
}
// Apply hand-to-hand proficiency. Hand-to-hand proficiency is not applied in classic.
else if (((int)attacker.Career.ExpertProficiencies & (int)DFCareer.ProficiencyFlags.HandToHand) != 0)
{
mods.damageMod = (attacker.Level / 3) + 1;
mods.toHitMod = attacker.Level;
}
return mods;
}
public static ToHitAndDamageMods CalculateRacialModifiers(DaggerfallEntity attacker, DaggerfallUnityItem weapon, PlayerEntity player)
{
Func<DaggerfallEntity, DaggerfallUnityItem, PlayerEntity, ToHitAndDamageMods> del;
if (TryGetOverride("CalculateRacialModifiers", out del))
return del(attacker, weapon, player);
ToHitAndDamageMods mods = new ToHitAndDamageMods();
if (weapon != null)
{
if (player.RaceTemplate.ID == (int)Races.DarkElf)
{
mods.damageMod = attacker.Level / 4;
mods.toHitMod = attacker.Level / 4;
}
else if (weapon.GetWeaponSkillIDAsShort() == (short)DFCareer.Skills.Archery)
{
if (player.RaceTemplate.ID == (int)Races.WoodElf)
{
mods.damageMod = attacker.Level / 3;
mods.toHitMod = attacker.Level / 3;
}
}
else if (player.RaceTemplate.ID == (int)Races.Redguard)
{
mods.damageMod = attacker.Level / 3;
mods.toHitMod = attacker.Level / 3;
}
}
return mods;
}
public static int CalculateBackstabChance(PlayerEntity player, DaggerfallEntity target, bool isEnemyFacingAwayFromPlayer)
{
Func<PlayerEntity, DaggerfallEntity, bool, int> del;
if (TryGetOverride("CalculateBackstabChance", out del))
return del(player, target, isEnemyFacingAwayFromPlayer);
if (isEnemyFacingAwayFromPlayer)
{
player.TallySkill(DFCareer.Skills.Backstabbing, 1);
return player.Skills.GetLiveSkillValue(DFCareer.Skills.Backstabbing);
}
return 0;
}
public static int CalculateBackstabDamage(int damage, int backstabbingLevel)
{
Func<int, int, int> del;
if (TryGetOverride("CalculateBackstabDamage", out del))
return del(damage, backstabbingLevel);
if (backstabbingLevel > 1 && Dice100.SuccessRoll(backstabbingLevel))
{
damage *= 3;
string backstabMessage = TextManager.Instance.GetLocalizedText("successfulBackstab");
DaggerfallUI.Instance.PopupMessage(backstabMessage);
}
return damage;
}
public static int GetBonusOrPenaltyByEnemyType(DaggerfallEntity attacker, DaggerfallEntity target)
{
Func<DaggerfallEntity, DaggerfallEntity, int> del;
if (TryGetOverride("GetBonusOrPenaltyByEnemyType", out del))
return del(attacker, target);
if (attacker == null || target == null)
return 0;