-
Notifications
You must be signed in to change notification settings - Fork 6k
/
Unit.cpp
13820 lines (11643 loc) · 487 KB
/
Unit.cpp
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
/*
* This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Unit.h"
#include "AbstractFollower.h"
#include "Battlefield.h"
#include "BattlefieldMgr.h"
#include "Battleground.h"
#include "BattlegroundPackets.h"
#include "BattlegroundScore.h"
#include "BattlePetMgr.h"
#include "CellImpl.h"
#include "CharacterCache.h"
#include "CharmInfo.h"
#include "ChatPackets.h"
#include "ChatTextBuilder.h"
#include "CombatLogPackets.h"
#include "CombatPackets.h"
#include "Common.h"
#include "ConditionMgr.h"
#include "Containers.h"
#include "Creature.h"
#include "CreatureAI.h"
#include "CreatureAIImpl.h"
#include "CreatureAIFactory.h"
#include "CreatureGroups.h"
#include "DB2Stores.h"
#include "Formulas.h"
#include "GameObjectAI.h"
#include "GameTime.h"
#include "GridNotifiersImpl.h"
#include "Group.h"
#include "InstanceScript.h"
#include "Item.h"
#include "ItemBonusMgr.h"
#include "KillRewarder.h"
#include "ListUtils.h"
#include "Log.h"
#include "Loot.h"
#include "LootMgr.h"
#include "LootPackets.h"
#include "MiscPackets.h"
#include "MotionMaster.h"
#include "MovementGenerator.h"
#include "MovementPackets.h"
#include "MoveSpline.h"
#include "MoveSplineInit.h"
#include "ObjectAccessor.h"
#include "ObjectMgr.h"
#include "Opcodes.h"
#include "OutdoorPvP.h"
#include "PartyPackets.h"
#include "Pet.h"
#include "PetPackets.h"
#include "PhasingHandler.h"
#include "Player.h"
#include "PlayerAI.h"
#include "QuestDef.h"
#include "Spell.h"
#include "ScheduledChangeAI.h"
#include "SpellAuraEffects.h"
#include "SpellAuras.h"
#include "SpellHistory.h"
#include "SpellInfo.h"
#include "SpellMgr.h"
#include "SpellPackets.h"
#include "StringConvert.h"
#include "TemporarySummon.h"
#include "Totem.h"
#include "Transport.h"
#include "Util.h"
#include "Vehicle.h"
#include "VehiclePackets.h"
#include "Vignette.h"
#include "VignettePackets.h"
#include "World.h"
#include "WorldPacket.h"
#include "WorldSession.h"
#include <queue>
#include <sstream>
#include <cmath>
float baseMoveSpeed[MAX_MOVE_TYPE] =
{
2.5f, // MOVE_WALK
7.0f, // MOVE_RUN
4.5f, // MOVE_RUN_BACK
4.722222f, // MOVE_SWIM
2.5f, // MOVE_SWIM_BACK
3.141594f, // MOVE_TURN_RATE
7.0f, // MOVE_FLIGHT
4.5f, // MOVE_FLIGHT_BACK
3.14f // MOVE_PITCH_RATE
};
float playerBaseMoveSpeed[MAX_MOVE_TYPE] =
{
2.5f, // MOVE_WALK
7.0f, // MOVE_RUN
4.5f, // MOVE_RUN_BACK
4.722222f, // MOVE_SWIM
2.5f, // MOVE_SWIM_BACK
3.141594f, // MOVE_TURN_RATE
7.0f, // MOVE_FLIGHT
4.5f, // MOVE_FLIGHT_BACK
3.14f // MOVE_PITCH_RATE
};
DispelableAura::DispelableAura(Aura* aura, int32 dispelChance, uint8 dispelCharges) :
_aura(aura), _chance(dispelChance), _charges(dispelCharges)
{
}
DispelableAura::~DispelableAura() = default;
bool DispelableAura::RollDispel() const
{
return roll_chance_i(_chance);
}
DamageInfo::DamageInfo(Unit* attacker, Unit* victim, uint32 damage, SpellInfo const* spellInfo, SpellSchoolMask schoolMask, DamageEffectType damageType, WeaponAttackType attackType)
: m_attacker(attacker), m_victim(victim), m_damage(damage), m_originalDamage(damage), m_spellInfo(spellInfo), m_schoolMask(schoolMask), m_damageType(damageType), m_attackType(attackType),
m_absorb(0), m_resist(0), m_block(0), m_hitMask(PROC_HIT_NONE)
{
}
DamageInfo::DamageInfo(CalcDamageInfo const& dmgInfo)
: m_attacker(dmgInfo.Attacker), m_victim(dmgInfo.Target), m_damage(dmgInfo.Damage), m_originalDamage(dmgInfo.Damage), m_spellInfo(nullptr), m_schoolMask(SpellSchoolMask(dmgInfo.DamageSchoolMask)),
m_damageType(DIRECT_DAMAGE), m_attackType(dmgInfo.AttackType), m_absorb(dmgInfo.Absorb), m_resist(dmgInfo.Resist), m_block(dmgInfo.Blocked), m_hitMask(PROC_HIT_NONE)
{
switch (dmgInfo.TargetState)
{
case VICTIMSTATE_IS_IMMUNE:
m_hitMask |= PROC_HIT_IMMUNE;
break;
case VICTIMSTATE_BLOCKS:
m_hitMask |= PROC_HIT_FULL_BLOCK;
break;
}
if (dmgInfo.HitInfo & (HITINFO_PARTIAL_ABSORB | HITINFO_FULL_ABSORB))
m_hitMask |= PROC_HIT_ABSORB;
if (dmgInfo.HitInfo & HITINFO_FULL_RESIST)
m_hitMask |= PROC_HIT_FULL_RESIST;
if (m_block)
m_hitMask |= PROC_HIT_BLOCK;
bool const damageNullified = (dmgInfo.HitInfo & (HITINFO_FULL_ABSORB | HITINFO_FULL_RESIST)) != 0 ||
(m_hitMask & (PROC_HIT_IMMUNE | PROC_HIT_FULL_BLOCK)) != 0;
switch (dmgInfo.HitOutCome)
{
case MELEE_HIT_MISS:
m_hitMask |= PROC_HIT_MISS;
break;
case MELEE_HIT_DODGE:
m_hitMask |= PROC_HIT_DODGE;
break;
case MELEE_HIT_PARRY:
m_hitMask |= PROC_HIT_PARRY;
break;
case MELEE_HIT_EVADE:
m_hitMask |= PROC_HIT_EVADE;
break;
case MELEE_HIT_BLOCK:
case MELEE_HIT_CRUSHING:
case MELEE_HIT_GLANCING:
case MELEE_HIT_NORMAL:
if (!damageNullified)
m_hitMask |= PROC_HIT_NORMAL;
break;
case MELEE_HIT_CRIT:
if (!damageNullified)
m_hitMask |= PROC_HIT_CRITICAL;
break;
}
}
DamageInfo::DamageInfo(SpellNonMeleeDamage const& spellNonMeleeDamage, DamageEffectType damageType, WeaponAttackType attackType, ProcFlagsHit hitMask)
: m_attacker(spellNonMeleeDamage.attacker), m_victim(spellNonMeleeDamage.target), m_damage(spellNonMeleeDamage.damage), m_originalDamage(spellNonMeleeDamage.originalDamage),
m_spellInfo(spellNonMeleeDamage.Spell), m_schoolMask(SpellSchoolMask(spellNonMeleeDamage.schoolMask)), m_damageType(damageType),
m_attackType(attackType), m_absorb(spellNonMeleeDamage.absorb), m_resist(spellNonMeleeDamage.resist), m_block(spellNonMeleeDamage.blocked), m_hitMask(hitMask)
{
if (spellNonMeleeDamage.blocked)
m_hitMask |= PROC_HIT_BLOCK;
if (spellNonMeleeDamage.absorb)
m_hitMask |= PROC_HIT_ABSORB;
}
void DamageInfo::ModifyDamage(int32 amount)
{
amount = std::max(amount, -static_cast<int32>(GetDamage()));
m_damage += amount;
}
void DamageInfo::AbsorbDamage(uint32 amount)
{
amount = std::min(amount, GetDamage());
m_absorb += amount;
m_damage -= amount;
m_hitMask |= PROC_HIT_ABSORB;
}
void DamageInfo::ResistDamage(uint32 amount)
{
amount = std::min(amount, GetDamage());
m_resist += amount;
m_damage -= amount;
if (!m_damage)
{
m_hitMask |= PROC_HIT_FULL_RESIST;
m_hitMask &= ~(PROC_HIT_NORMAL | PROC_HIT_CRITICAL);
}
}
void DamageInfo::BlockDamage(uint32 amount)
{
amount = std::min(amount, GetDamage());
m_block += amount;
m_damage -= amount;
m_hitMask |= PROC_HIT_BLOCK;
if (!m_damage)
{
m_hitMask |= PROC_HIT_FULL_BLOCK;
m_hitMask &= ~(PROC_HIT_NORMAL | PROC_HIT_CRITICAL);
}
}
ProcFlagsHit DamageInfo::GetHitMask() const
{
return m_hitMask;
}
HealInfo::HealInfo(Unit* healer, Unit* target, uint32 heal, SpellInfo const* spellInfo, SpellSchoolMask schoolMask)
: _healer(healer), _target(target), _heal(heal), _originalHeal(heal), _effectiveHeal(0), _absorb(0), _spellInfo(spellInfo), _schoolMask(schoolMask), _hitMask(0)
{
}
void HealInfo::AbsorbHeal(uint32 amount)
{
amount = std::min(amount, GetHeal());
_absorb += amount;
_heal -= amount;
amount = std::min(amount, GetEffectiveHeal());
_effectiveHeal -= amount;
_hitMask |= PROC_HIT_ABSORB;
}
uint32 HealInfo::GetHitMask() const
{
return _hitMask;
}
ProcEventInfo::ProcEventInfo(Unit* actor, Unit* actionTarget, Unit* procTarget,
ProcFlagsInit const& typeMask, ProcFlagsSpellType spellTypeMask,
ProcFlagsSpellPhase spellPhaseMask, ProcFlagsHit hitMask,
Spell* spell, DamageInfo* damageInfo,
HealInfo* healInfo) :
_actor(actor), _actionTarget(actionTarget), _procTarget(procTarget),
_typeMask(typeMask), _spellTypeMask(spellTypeMask),
_spellPhaseMask(spellPhaseMask), _hitMask(hitMask), _spell(spell),
_damageInfo(damageInfo), _healInfo(healInfo)
{ }
SpellInfo const* ProcEventInfo::GetSpellInfo() const
{
if (_spell)
return _spell->GetSpellInfo();
if (_damageInfo)
return _damageInfo->GetSpellInfo();
if (_healInfo)
return _healInfo->GetSpellInfo();
return nullptr;
}
SpellSchoolMask ProcEventInfo::GetSchoolMask() const
{
if (_spell)
return _spell->GetSpellInfo()->GetSchoolMask();
if (_damageInfo)
return _damageInfo->GetSchoolMask();
if (_healInfo)
return _healInfo->GetSchoolMask();
return SPELL_SCHOOL_MASK_NONE;
}
SpellNonMeleeDamage::SpellNonMeleeDamage(Unit* _attacker, Unit* _target, SpellInfo const* _spellInfo, SpellCastVisual spellVisual, uint32 _schoolMask, ObjectGuid _castId)
: target(_target), attacker(_attacker), castId(_castId), Spell(_spellInfo), SpellVisual(spellVisual), damage(0), originalDamage(0),
schoolMask(_schoolMask), absorb(0), resist(0), periodicLog(false), blocked(0), HitInfo(0), cleanDamage(0), fullBlock(false), preHitHealth(_target->GetHealth())
{
}
Unit::Unit(bool isWorldObject) :
WorldObject(isWorldObject), m_lastSanctuaryTime(0), LastCharmerGUID(), movespline(std::make_unique<Movement::MoveSpline>()),
m_ControlledByPlayer(false), m_procDeep(0), m_procChainLength(0), m_transformSpell(0),
m_removedAurasCount(0), m_interruptMask(SpellAuraInterruptFlags::None), m_interruptMask2(SpellAuraInterruptFlags2::None),
m_unitMovedByMe(nullptr), m_playerMovingMe(nullptr), m_charmer(nullptr), m_charmed(nullptr),
i_motionMaster(std::make_unique<MotionMaster>(this)), m_regenTimer(0), m_vehicle(nullptr),
m_unitTypeMask(UNIT_MASK_NONE), m_Diminishing(), m_combatManager(this),
m_threatManager(this), m_aiLocked(false), _playHoverAnim(false), _aiAnimKitId(0), _movementAnimKitId(0), _meleeAnimKitId(0),
_spellHistory(std::make_unique<SpellHistory>(this))
{
m_objectType |= TYPEMASK_UNIT;
m_objectTypeId = TYPEID_UNIT;
m_updateFlag.MovementUpdate = true;
m_baseAttackSpeed = { };
m_attackTimer = { };
m_modAttackSpeedPct.fill(1.0f);
m_canDualWield = false;
m_movementCounter = 0;
m_state = 0;
m_deathState = ALIVE;
m_currentSpells = { };
m_auraUpdateIterator = m_ownedAuras.end();
m_canModifyStats = false;
for (uint8 i = 0; i < UNIT_MOD_END; ++i)
{
m_auraFlatModifiersGroup[i][BASE_VALUE] = 0.0f;
m_auraFlatModifiersGroup[i][BASE_PCT_EXCLUDE_CREATE] = 100.0f;
m_auraFlatModifiersGroup[i][TOTAL_VALUE] = 0.0f;
m_auraPctModifiersGroup[i][BASE_PCT] = 1.0f;
m_auraPctModifiersGroup[i][TOTAL_PCT] = 1.0f;
}
// implement 50% base damage from offhand
m_auraPctModifiersGroup[UNIT_MOD_DAMAGE_OFFHAND][TOTAL_PCT] = 0.5f;
for (uint8 i = 0; i < MAX_ATTACK; ++i)
{
m_weaponDamage[i][MINDAMAGE] = BASE_MINDAMAGE;
m_weaponDamage[i][MAXDAMAGE] = BASE_MAXDAMAGE;
}
m_createStats = { };
m_floatStatPosBuff = { };
m_floatStatNegBuff = { };
m_attacking = nullptr;
m_modMeleeHitChance = 0.0f;
m_modRangedHitChance = 0.0f;
m_modSpellHitChance = 0.0f;
m_baseSpellCritChance = 5.0f;
m_speed_rate.fill(1.0f);
// remove aurastates allowing special moves
m_reactiveTimer = { };
m_cleanupDone = false;
m_duringRemoveFromWorld = false;
m_serverSideVisibility.SetValue(SERVERSIDE_VISIBILITY_GHOST, GHOST_VISIBILITY_ALIVE);
_lastLiquid = nullptr;
_oldFactionId = 0;
_isWalkingBeforeCharm = false;
_instantCast = false;
_isCombatDisallowed = false;
_lastExtraAttackSpell = 0;
}
////////////////////////////////////////////////////////////
// Methods of class Unit
Unit::~Unit()
{
// set current spells as deletable
for (size_t i = 0; i < m_currentSpells.size(); ++i)
{
if (m_currentSpells[i])
{
m_currentSpells[i]->SetReferencedFromCurrent(false);
m_currentSpells[i] = nullptr;
}
}
m_Events.KillAllEvents(true);
_DeleteRemovedAuras();
ASSERT(!m_duringRemoveFromWorld);
ASSERT(!m_attacking);
ASSERT(m_attackers.empty());
ASSERT(m_sharedVision.empty());
ASSERT(m_Controlled.empty());
ASSERT(m_appliedAuras.empty());
ASSERT(m_ownedAuras.empty());
ASSERT(m_removedAuras.empty());
ASSERT(m_dynObj.empty());
ASSERT(m_gameObj.empty());
ASSERT(m_areaTrigger.empty());
ASSERT(!m_unitMovedByMe || (m_unitMovedByMe == this));
ASSERT(!m_playerMovingMe || (m_playerMovingMe == this));
}
void Unit::Update(uint32 p_time)
{
// WARNING! Order of execution here is important, do not change.
// Spells must be processed with event system BEFORE they go to _UpdateSpells.
// Or else we may have some SPELL_STATE_FINISHED spells stalled in pointers, that is bad.
WorldObject::Update(p_time);
if (!IsInWorld())
return;
_UpdateSpells(p_time);
// If this is set during update SetCantProc(false) call is missing somewhere in the code
// Having this would prevent spells from being proced, so let's crash
ASSERT(!m_procDeep);
m_combatManager.Update(p_time);
_lastDamagedTargetGuid = ObjectGuid::Empty;
if (_lastExtraAttackSpell)
{
while (!extraAttacksTargets.empty())
{
auto itr = extraAttacksTargets.begin();
ObjectGuid targetGuid = itr->first;
uint32 count = itr->second;
extraAttacksTargets.erase(itr);
if (Unit* victim = ObjectAccessor::GetUnit(*this, targetGuid))
HandleProcExtraAttackFor(victim, count);
}
_lastExtraAttackSpell = 0;
}
auto spellPausesCombatTimer = [&](CurrentSpellTypes type)
{
return GetCurrentSpell(type) && GetCurrentSpell(type)->GetSpellInfo()->HasAttribute(SPELL_ATTR6_DELAY_COMBAT_TIMER_DURING_CAST);
};
if (!spellPausesCombatTimer(CURRENT_GENERIC_SPELL) && !spellPausesCombatTimer(CURRENT_CHANNELED_SPELL))
{
if (uint32 base_att = getAttackTimer(BASE_ATTACK))
setAttackTimer(BASE_ATTACK, (p_time >= base_att ? 0 : base_att - p_time));
if (uint32 off_att = getAttackTimer(OFF_ATTACK))
setAttackTimer(OFF_ATTACK, (p_time >= off_att ? 0 : off_att - p_time));
if (uint32 ranged_att = getAttackTimer(RANGED_ATTACK))
setAttackTimer(RANGED_ATTACK, (p_time >= ranged_att ? 0 : ranged_att - p_time));
}
// update abilities available only for fraction of time
UpdateReactives(p_time);
if (IsAlive())
{
ModifyAuraState(AURA_STATE_WOUNDED_20_PERCENT, HealthBelowPct(20));
ModifyAuraState(AURA_STATE_WOUNDED_25_PERCENT, HealthBelowPct(25));
ModifyAuraState(AURA_STATE_WOUNDED_35_PERCENT, HealthBelowPct(35));
ModifyAuraState(AURA_STATE_WOUND_HEALTH_20_80, HealthBelowPct(20) || HealthAbovePct(80));
ModifyAuraState(AURA_STATE_HEALTHY_75_PERCENT, HealthAbovePct(75));
ModifyAuraState(AURA_STATE_WOUND_HEALTH_35_80, HealthBelowPct(35) || HealthAbovePct(80));
}
UpdateSplineMovement(p_time);
i_motionMaster->Update(p_time);
// Wait with the aura interrupts until we have updated our movement generators and position
if (GetTypeId() == TYPEID_PLAYER)
InterruptMovementBasedAuras();
else if (!movespline->Finalized())
InterruptMovementBasedAuras();
// All position info based actions have been executed, reset info
_positionUpdateInfo.Reset();
if (HasScheduledAIChange() && (GetTypeId() != TYPEID_PLAYER || (IsCharmed() && GetCharmerGUID().IsCreature())))
UpdateCharmAI();
RefreshAI();
}
bool Unit::haveOffhandWeapon() const
{
if (Player const* player = ToPlayer())
return player->GetWeaponForAttack(OFF_ATTACK, true) != nullptr;
return CanDualWield();
}
void Unit::MonsterMoveWithSpeed(float x, float y, float z, float speed, bool generatePath, bool forceDestination)
{
std::function<void(Movement::MoveSplineInit&)> initializer = [=](Movement::MoveSplineInit& init)
{
init.MoveTo(x, y, z, generatePath, forceDestination);
init.SetVelocity(speed);
};
GetMotionMaster()->LaunchMoveSpline(std::move(initializer), 0, MOTION_PRIORITY_NORMAL, POINT_MOTION_TYPE);
}
void Unit::AtStartOfEncounter(EncounterType type)
{
RemoveAurasWithInterruptFlags(SpellAuraInterruptFlags2::StartOfEncounter);
switch (type)
{
case EncounterType::DungeonEncounter:
RemoveAurasWithInterruptFlags(SpellAuraInterruptFlags2::StartOfDungeonEncounter);
break;
case EncounterType::MythicPlusRun:
RemoveAurasWithInterruptFlags(SpellAuraInterruptFlags2::StartOfMythicPlusRun);
break;
default:
break;
}
if (IsAlive())
Unit::ProcSkillsAndAuras(this, nullptr, PROC_FLAG_ENCOUNTER_START, PROC_FLAG_NONE, PROC_SPELL_TYPE_MASK_ALL, PROC_SPELL_PHASE_NONE, PROC_HIT_NONE, nullptr, nullptr, nullptr);
}
void Unit::AtEndOfEncounter(EncounterType type)
{
RemoveAurasWithInterruptFlags(SpellAuraInterruptFlags2::EndOfEncounter);
switch (type)
{
case EncounterType::DungeonEncounter:
RemoveAurasWithInterruptFlags(SpellAuraInterruptFlags2::EndOfDungeonEncounter);
break;
default:
break;
}
GetSpellHistory()->ResetCooldowns([](SpellHistory::CooldownStorageType::iterator itr)
{
SpellInfo const* spellInfo = sSpellMgr->AssertSpellInfo(itr->first, DIFFICULTY_NONE);
return spellInfo->HasAttribute(SPELL_ATTR10_RESET_COOLDOWN_ON_ENCOUNTER_END);
}, true);
}
void Unit::UpdateSplineMovement(uint32 t_diff)
{
if (movespline->Finalized())
return;
movespline->updateState(t_diff);
bool arrived = movespline->Finalized();
if (movespline->isCyclic())
{
m_splineSyncTimer.Update(t_diff);
if (m_splineSyncTimer.Passed())
{
m_splineSyncTimer.Reset(5000); // Retail value, do not change
WorldPackets::Movement::FlightSplineSync flightSplineSync;
flightSplineSync.Guid = GetGUID();
flightSplineSync.SplineDist = (float)movespline->timePassed() / movespline->Duration();
SendMessageToSet(flightSplineSync.Write(), true);
}
}
if (arrived)
{
DisableSpline();
if (Optional<AnimTier> animTier = movespline->GetAnimation())
SetAnimTier(*animTier);
}
UpdateSplinePosition();
}
void Unit::UpdateSplinePosition()
{
Movement::Location loc = movespline->ComputePosition();
if (movespline->onTransport)
{
Position& pos = m_movementInfo.transport.pos;
pos.m_positionX = loc.x;
pos.m_positionY = loc.y;
pos.m_positionZ = loc.z;
pos.SetOrientation(loc.orientation);
if (TransportBase* transport = GetDirectTransport())
transport->CalculatePassengerPosition(loc.x, loc.y, loc.z, &loc.orientation);
else
return;
}
if (HasUnitState(UNIT_STATE_LOST_CONTROL | UNIT_STATE_FOCUSING))
loc.orientation = GetOrientation();
UpdatePosition(loc.x, loc.y, loc.z, loc.orientation);
}
void Unit::InterruptMovementBasedAuras()
{
// TODO: Check if orientation transport offset changed instead of only global orientation
if (_positionUpdateInfo.Turned)
RemoveAurasWithInterruptFlags(SpellAuraInterruptFlags::Turning);
if (_positionUpdateInfo.Relocated && !GetVehicle())
RemoveAurasWithInterruptFlags(SpellAuraInterruptFlags::Moving);
}
void Unit::DisableSpline()
{
m_movementInfo.RemoveMovementFlag(MOVEMENTFLAG_FORWARD);
movespline->_Interrupt();
}
void Unit::resetAttackTimer(WeaponAttackType type)
{
m_attackTimer[type] = uint32(GetBaseAttackTime(type) * m_modAttackSpeedPct[type]);
}
bool Unit::IsWithinCombatRange(Unit const* obj, float dist2compare) const
{
if (!obj || !IsInMap(obj) || !InSamePhase(obj))
return false;
float dx = GetPositionX() - obj->GetPositionX();
float dy = GetPositionY() - obj->GetPositionY();
float dz = GetPositionZ() - obj->GetPositionZ();
float distsq = dx * dx + dy * dy + dz * dz;
float sizefactor = GetCombatReach() + obj->GetCombatReach();
float maxdist = dist2compare + sizefactor;
return distsq < maxdist * maxdist;
}
bool Unit::IsWithinMeleeRangeAt(Position const& pos, Unit const* obj) const
{
if (!obj || !IsInMap(obj) || !InSamePhase(obj))
return false;
float dx = pos.GetPositionX() - obj->GetPositionX();
float dy = pos.GetPositionY() - obj->GetPositionY();
float dz = pos.GetPositionZ() - obj->GetPositionZ();
float distsq = dx*dx + dy*dy + dz*dz;
float maxdist = GetMeleeRange(obj) + GetTotalAuraModifier(SPELL_AURA_MOD_AUTOATTACK_RANGE);
return distsq <= maxdist * maxdist;
}
float Unit::GetMeleeRange(Unit const* target) const
{
float range = GetCombatReach() + target->GetCombatReach() + 4.0f / 3.0f;
return std::max(range, NOMINAL_MELEE_RANGE);
}
bool Unit::IsWithinBoundaryRadius(const Unit* obj) const
{
if (!obj || !IsInMap(obj) || !InSamePhase(obj))
return false;
float objBoundaryRadius = std::max(obj->GetBoundingRadius(), MIN_MELEE_REACH);
return IsInDist(obj, objBoundaryRadius);
}
void Unit::SetVisibleAura(AuraApplication* aurApp)
{
m_visibleAuras.insert(aurApp);
m_visibleAurasToUpdate.insert(aurApp);
UpdateAuraForGroup();
}
void Unit::RemoveVisibleAura(AuraApplication* aurApp)
{
m_visibleAuras.erase(aurApp);
m_visibleAurasToUpdate.erase(aurApp);
UpdateAuraForGroup();
}
void Unit::UpdateInterruptMask()
{
m_interruptMask = SpellAuraInterruptFlags::None;
m_interruptMask2 = SpellAuraInterruptFlags2::None;
for (AuraApplication const* aurApp : m_interruptableAuras)
{
m_interruptMask |= aurApp->GetBase()->GetSpellInfo()->AuraInterruptFlags;
m_interruptMask2 |= aurApp->GetBase()->GetSpellInfo()->AuraInterruptFlags2;
}
if (Spell* spell = m_currentSpells[CURRENT_CHANNELED_SPELL])
{
if (spell->getState() == SPELL_STATE_CASTING)
{
m_interruptMask |= spell->m_spellInfo->ChannelInterruptFlags;
m_interruptMask2 |= spell->m_spellInfo->ChannelInterruptFlags2;
}
}
}
bool Unit::HasAuraTypeWithFamilyFlags(AuraType auraType, uint32 familyName, flag128 familyFlags) const
{
for (AuraEffect const* aura : GetAuraEffectsByType(auraType))
if (aura->GetSpellInfo()->SpellFamilyName == familyName && aura->GetSpellInfo()->SpellFamilyFlags & familyFlags)
return true;
return false;
}
bool Unit::HasBreakableByDamageAuraType(AuraType type, uint32 excludeAura) const
{
AuraEffectList const& auras = GetAuraEffectsByType(type);
for (AuraEffectList::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
if ((!excludeAura || excludeAura != (*itr)->GetSpellInfo()->Id) && //Avoid self interrupt of channeled Crowd Control spells like Seduction
(*itr)->GetSpellInfo()->HasAuraInterruptFlag(SpellAuraInterruptFlags::Damage))
return true;
return false;
}
bool Unit::HasBreakableByDamageCrowdControlAura(Unit* excludeCasterChannel) const
{
uint32 excludeAura = 0;
if (Spell* currentChanneledSpell = excludeCasterChannel ? excludeCasterChannel->GetCurrentSpell(CURRENT_CHANNELED_SPELL) : nullptr)
excludeAura = currentChanneledSpell->GetSpellInfo()->Id; //Avoid self interrupt of channeled Crowd Control spells like Seduction
return ( HasBreakableByDamageAuraType(SPELL_AURA_MOD_CONFUSE, excludeAura)
|| HasBreakableByDamageAuraType(SPELL_AURA_MOD_FEAR, excludeAura)
|| HasBreakableByDamageAuraType(SPELL_AURA_MOD_STUN, excludeAura)
|| HasBreakableByDamageAuraType(SPELL_AURA_MOD_ROOT, excludeAura)
|| HasBreakableByDamageAuraType(SPELL_AURA_MOD_ROOT_2, excludeAura)
|| HasBreakableByDamageAuraType(SPELL_AURA_TRANSFORM, excludeAura));
}
/*static*/ void Unit::DealDamageMods(Unit const* attacker, Unit const* victim, uint32& damage, uint32* absorb)
{
if (!victim || !victim->IsAlive() || victim->HasUnitState(UNIT_STATE_IN_FLIGHT) || (victim->GetTypeId() == TYPEID_UNIT && victim->ToCreature()->IsEvadingAttacks()))
{
if (absorb)
*absorb += damage;
damage = 0;
return;
}
if (attacker)
damage *= attacker->GetDamageMultiplierForTarget(victim);
}
/*static*/ AuraEffectVector Unit::CopyAuraEffectList(Unit::AuraEffectList const& list)
{
AuraEffectVector effects;
std::copy(list.begin(), list.end(), std::back_inserter(effects));
return effects;
}
/*static*/ uint32 Unit::DealDamage(Unit* attacker, Unit* victim, uint32 damage, CleanDamage const* cleanDamage, DamageEffectType damagetype, SpellSchoolMask damageSchoolMask, SpellInfo const* spellProto, bool durabilityLoss)
{
uint32 damageDone = damage;
uint32 damageTaken = damage;
if (attacker)
damageTaken = damage / victim->GetHealthMultiplierForTarget(attacker);
// call script hooks
{
uint32 tmpDamage = damageTaken;
// sparring
if (Creature* victimCreature = victim->ToCreature())
tmpDamage = victimCreature->CalculateDamageForSparring(attacker, tmpDamage);
if (UnitAI* victimAI = victim->GetAI())
victimAI->DamageTaken(attacker, tmpDamage, damagetype, spellProto);
if (UnitAI* attackerAI = attacker ? attacker->GetAI() : nullptr)
attackerAI->DamageDealt(victim, tmpDamage, damagetype);
// Hook for OnDamage Event
sScriptMgr->OnDamage(attacker, victim, tmpDamage);
// if any script modified damage, we need to also apply the same modification to unscaled damage value
if (tmpDamage != damageTaken)
{
if (attacker)
damageDone = tmpDamage * victim->GetHealthMultiplierForTarget(attacker);
else
damageDone = tmpDamage;
damageTaken = tmpDamage;
}
}
// Signal to pets that their owner was attacked - except when DOT.
if (attacker != victim && damagetype != DOT)
{
for (Unit* controlled : victim->m_Controlled)
if (Creature* cControlled = controlled->ToCreature())
if (CreatureAI* controlledAI = cControlled->AI())
controlledAI->OwnerAttackedBy(attacker);
}
if (Player* player = victim->ToPlayer())
if (player->GetCommandStatus(CHEAT_GOD))
return 0;
if (damagetype != NODAMAGE)
{
// interrupting auras with SpellAuraInterruptFlags::Damage before checking !damage (absorbed damage breaks that type of auras)
if (spellProto)
{
if (!spellProto->HasAttribute(SPELL_ATTR4_REACTIVE_DAMAGE_PROC))
victim->RemoveAurasWithInterruptFlags(SpellAuraInterruptFlags::Damage, spellProto);
}
else
victim->RemoveAurasWithInterruptFlags(SpellAuraInterruptFlags::Damage);
if (!damageTaken && damagetype != DOT && cleanDamage && cleanDamage->absorbed_damage)
if (victim != attacker && victim->GetTypeId() == TYPEID_PLAYER)
if (Spell* spell = victim->m_currentSpells[CURRENT_GENERIC_SPELL])
if (spell->getState() == SPELL_STATE_PREPARING && spell->m_spellInfo->InterruptFlags.HasFlag(SpellInterruptFlags::DamageAbsorb))
victim->InterruptNonMeleeSpells(false);
// We're going to call functions which can modify content of the list during iteration over it's elements
// Let's copy the list so we can prevent iterator invalidation
AuraEffectVector vCopyDamageCopy = CopyAuraEffectList(victim->GetAuraEffectsByType(SPELL_AURA_SHARE_DAMAGE_PCT));
// copy damage to casters of this aura
for (auto i = vCopyDamageCopy.begin(); i != vCopyDamageCopy.end(); ++i)
{
// Check if aura was removed during iteration - we don't need to work on such auras
if (!((*i)->GetBase()->IsAppliedOnTarget(victim->GetGUID())))
continue;
// check damage school mask
if (((*i)->GetMiscValue() & damageSchoolMask) == 0)
continue;
Unit* shareDamageTarget = (*i)->GetCaster();
if (!shareDamageTarget)
continue;
SpellInfo const* spell = (*i)->GetSpellInfo();
uint32 share = CalculatePct(damageDone, (*i)->GetAmount());
/// @todo check packets if damage is done by victim, or by attacker of victim
Unit::DealDamageMods(attacker, shareDamageTarget, share, nullptr);
Unit::DealDamage(attacker, shareDamageTarget, share, nullptr, NODAMAGE, spell->GetSchoolMask(), spell, false);
}
}
// Rage from Damage made (only from direct weapon damage)
if (attacker && cleanDamage && (cleanDamage->attackType == BASE_ATTACK || cleanDamage->attackType == OFF_ATTACK) && damagetype == DIRECT_DAMAGE && attacker != victim && attacker->GetPowerType() == POWER_RAGE)
{
uint32 rage = uint32(attacker->GetBaseAttackTime(cleanDamage->attackType) / 1000.f * 1.75f);
if (cleanDamage->attackType == OFF_ATTACK)
rage /= 2;
attacker->RewardRage(rage);
}
if (!damageDone)
return 0;
uint32 health = victim->GetHealth();
// duel ends when player has 1 or less hp
bool duel_hasEnded = false;
bool duel_wasMounted = false;
if (victim->GetTypeId() == TYPEID_PLAYER && victim->ToPlayer()->duel && damageTaken >= (health-1))
{
if (!attacker)
return 0;
// prevent kill only if killed in duel and killed by opponent or opponent controlled creature
if (victim->ToPlayer()->duel->Opponent == attacker->GetControllingPlayer())
damageTaken = health - 1;
duel_hasEnded = true;
}
else if (victim->IsCreature() && victim != attacker && damageTaken >= health && victim->ToCreature()->HasFlag(CREATURE_STATIC_FLAG_UNKILLABLE))
{
damageTaken = health - 1;
// If we had damage (aka health was not 1 already) trigger OnHealthDepleted
if (damageTaken > 0)
{
if (CreatureAI* victimAI = victim->ToCreature()->AI())
victimAI->OnHealthDepleted(attacker, false);
}
}
else if (victim->IsVehicle() && damageTaken >= (health-1) && victim->GetCharmer() && victim->GetCharmer()->GetTypeId() == TYPEID_PLAYER)
{
Player* victimRider = victim->GetCharmer()->ToPlayer();
if (victimRider && victimRider->duel && victimRider->duel->IsMounted)
{
if (!attacker)
return 0;
// prevent kill only if killed in duel and killed by opponent or opponent controlled creature
if (victimRider->duel->Opponent == attacker->GetControllingPlayer())
damageTaken = health - 1;
duel_wasMounted = true;
duel_hasEnded = true;
}
}
if (attacker && attacker != victim)
{
if (Player* killer = attacker->ToPlayer())
{
// in bg, count dmg if victim is also a player
if (victim->GetTypeId() == TYPEID_PLAYER && !(spellProto && spellProto->HasAttribute(SPELL_ATTR7_DO_NOT_COUNT_FOR_PVP_SCOREBOARD)))
if (Battleground* bg = killer->GetBattleground())
bg->UpdatePlayerScore(killer, SCORE_DAMAGE_DONE, damageDone);
killer->UpdateCriteria(CriteriaType::DamageDealt, health > damageDone ? damageDone : health, 0, 0, victim);
killer->UpdateCriteria(CriteriaType::HighestDamageDone, damageDone);
}
}
if (victim->GetTypeId() == TYPEID_PLAYER)
victim->ToPlayer()->UpdateCriteria(CriteriaType::HighestDamageTaken, damageTaken);
if (victim->GetTypeId() != TYPEID_PLAYER && (!victim->IsControlledByPlayer() || victim->IsVehicle()))
{
victim->ToCreature()->SetTappedBy(attacker);
if (!attacker || attacker->IsControlledByPlayer())
victim->ToCreature()->LowerPlayerDamageReq(health < damageTaken ? health : damageTaken);
}
bool killed = false;
bool skipSettingDeathState = false;
if (health <= damageTaken)
{
killed = true;
if (victim->GetTypeId() == TYPEID_PLAYER && victim != attacker)
victim->ToPlayer()->UpdateCriteria(CriteriaType::TotalDamageTaken, health);
if (damagetype != NODAMAGE && damagetype != SELF_DAMAGE && victim->HasAuraType(SPELL_AURA_SCHOOL_ABSORB_OVERKILL))
{
AuraEffectVector vAbsorbOverkill = CopyAuraEffectList(victim->GetAuraEffectsByType(SPELL_AURA_SCHOOL_ABSORB_OVERKILL));
DamageInfo damageInfo = DamageInfo(attacker, victim, damageTaken, spellProto, damageSchoolMask, damagetype,
cleanDamage ? cleanDamage->attackType : BASE_ATTACK);
for (AuraEffect* absorbAurEff : vAbsorbOverkill)
{
Aura* base = absorbAurEff->GetBase();
AuraApplication const* aurApp = base->GetApplicationOfTarget(victim->GetGUID());
if (!aurApp)
continue;
if (!(absorbAurEff->GetMiscValue() & damageInfo.GetSchoolMask()))
continue;
// cannot absorb over limit
if (damageTaken >= victim->CountPctFromMaxHealth(100 + absorbAurEff->GetMiscValueB()))
continue;
// absorb all damage by default
uint32 currentAbsorb = damageInfo.GetDamage();
// This aura type is used both by Spirit of Redemption (death not really prevented, must grant all credit immediately) and Cheat Death (death prevented)
// repurpose PreventDefaultAction for this
bool deathFullyPrevented = false;
absorbAurEff->GetBase()->CallScriptEffectAbsorbHandlers(absorbAurEff, aurApp, damageInfo, currentAbsorb, deathFullyPrevented);
// absorb must be smaller than the damage itself
currentAbsorb = std::min(currentAbsorb, damageInfo.GetDamage());
// if nothing is absorbed (for example because of a scripted cooldown) then skip this aura and proceed with dying
if (!currentAbsorb)
continue;
damageInfo.AbsorbDamage(currentAbsorb);
if (deathFullyPrevented)
killed = false;
skipSettingDeathState = true;
if (currentAbsorb)
{
WorldPackets::CombatLog::SpellAbsorbLog absorbLog;
absorbLog.Attacker = attacker ? attacker->GetGUID() : ObjectGuid::Empty;
absorbLog.Victim = victim->GetGUID();
absorbLog.Caster = base->GetCasterGUID();