-
Notifications
You must be signed in to change notification settings - Fork 89
/
Creature.cpp
2747 lines (2268 loc) · 92.9 KB
/
Creature.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 CMaNGOS 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "Creature.h"
#include "Database/DatabaseEnv.h"
#include "WorldPacket.h"
#include "World.h"
#include "ObjectMgr.h"
#include "ScriptMgr.h"
#include "ObjectGuid.h"
#include "SQLStorages.h"
#include "SpellMgr.h"
#include "QuestDef.h"
#include "GossipDef.h"
#include "Player.h"
#include "GameEventMgr.h"
#include "PoolManager.h"
#include "Opcodes.h"
#include "Log.h"
#include "LootMgr.h"
#include "MapManager.h"
#include "CreatureAI.h"
#include "CreatureAISelector.h"
#include "Formulas.h"
#include "WaypointMovementGenerator.h"
#include "InstanceData.h"
#include "MapPersistentStateMgr.h"
#include "BattleGround/BattleGroundMgr.h"
#include "OutdoorPvP/OutdoorPvP.h"
#include "Spell.h"
#include "Util.h"
#include "GridNotifiers.h"
#include "GridNotifiersImpl.h"
#include "CellImpl.h"
#include "movement/MoveSplineInit.h"
#include "CreatureLinkingMgr.h"
// apply implementation of the singletons
#include "Policies/Singleton.h"
ObjectGuid CreatureData::GetObjectGuid(uint32 lowguid) const
{
// info existence checked at loading
return ObjectMgr::GetCreatureTemplate(id)->GetObjectGuid(lowguid);
}
TrainerSpell const* TrainerSpellData::Find(uint32 spell_id) const
{
TrainerSpellMap::const_iterator itr = spellList.find(spell_id);
if (itr != spellList.end())
return &itr->second;
return NULL;
}
bool VendorItemData::RemoveItem(uint32 item_id, uint8 type)
{
bool found = false;
for (VendorItemList::iterator i = m_items.begin(); i != m_items.end();)
{
// can have many examples
if ((*i)->item == item_id && (*i)->type == type)
{
i = m_items.erase(i);
found = true;
}
else
++i;
}
return found;
}
VendorItem const* VendorItemData::FindItemCostPair(uint32 item_id, uint8 type, uint32 extendedCost) const
{
for (VendorItemList::const_iterator i = m_items.begin(); i != m_items.end(); ++i)
{
// Skip checking for conditions, condition system is powerfull enough to not require additional entries only for the conditions
if ((*i)->item == item_id && (*i)->ExtendedCost == extendedCost && (*i)->type == type)
return *i;
}
return NULL;
}
bool ForcedDespawnDelayEvent::Execute(uint64 /*e_time*/, uint32 /*p_time*/)
{
m_owner.ForcedDespawn();
return true;
}
void CreatureCreatePos::SelectFinalPoint(Creature* cr)
{
// if object provided then selected point at specific dist/angle from object forward look
if (m_closeObject)
{
if (m_dist == 0.0f)
{
m_pos.x = m_closeObject->GetPositionX();
m_pos.y = m_closeObject->GetPositionY();
m_pos.z = m_closeObject->GetPositionZ();
}
else
m_closeObject->GetClosePoint(m_pos.x, m_pos.y, m_pos.z, cr->GetObjectBoundingRadius(), m_dist, m_angle);
}
}
bool CreatureCreatePos::Relocate(Creature* cr) const
{
cr->Relocate(m_pos.x, m_pos.y, m_pos.z, m_pos.o);
if (!cr->IsPositionValid())
{
sLog.outError("%s not created. Suggested coordinates isn't valid (X: %f Y: %f)", cr->GetGuidStr().c_str(), cr->GetPositionX(), cr->GetPositionY());
return false;
}
return true;
}
Creature::Creature(CreatureSubtype subtype) : Unit(),
i_AI(NULL),
loot(this),
lootForPickPocketed(false), lootForBody(false), lootForSkin(false),
m_groupLootTimer(0), m_groupLootId(0),
m_lootMoney(0), m_lootGroupRecipientId(0),
m_corpseDecayTimer(0), m_respawnTime(0), m_respawnDelay(25), m_corpseDelay(60), m_aggroDelay(0), m_respawnradius(5.0f),
m_subtype(subtype), m_defaultMovementType(IDLE_MOTION_TYPE), m_equipmentId(0),
m_AlreadyCallAssistance(false), m_AlreadySearchedAssistance(false),
m_AI_locked(false), m_isDeadByDefault(false), m_temporaryFactionFlags(TEMPFACTION_NONE),
m_meleeDamageSchoolMask(SPELL_SCHOOL_MASK_NORMAL), m_originalEntry(0),
m_creatureInfo(NULL)
{
m_regenTimer = 200;
m_holyPowerRegenTimer = REGEN_TIME_HOLY_POWER;
m_valuesCount = UNIT_END;
for (int i = 0; i < CREATURE_MAX_SPELLS; ++i)
m_spells[i] = 0;
m_CreatureSpellCooldowns.clear();
m_CreatureCategoryCooldowns.clear();
SetWalk(true, true);
}
Creature::~Creature()
{
CleanupsBeforeDelete();
m_vendorItemCounts.clear();
delete i_AI;
i_AI = NULL;
}
void Creature::AddToWorld()
{
///- Register the creature for guid lookup
if (!IsInWorld() && GetObjectGuid().IsCreatureOrVehicle())
GetMap()->GetObjectsStore().insert<Creature>(GetObjectGuid(), (Creature*)this);
Unit::AddToWorld();
}
void Creature::RemoveFromWorld()
{
///- Remove the creature from the accessor
if (IsInWorld() && GetObjectGuid().IsCreatureOrVehicle())
GetMap()->GetObjectsStore().erase<Creature>(GetObjectGuid(), (Creature*)NULL);
Unit::RemoveFromWorld();
}
void Creature::RemoveCorpse()
{
// since pool system can fail to roll unspawned object, this one can remain spawned, so must set respawn nevertheless
if (uint16 poolid = sPoolMgr.IsPartOfAPool<Creature>(GetGUIDLow()))
sPoolMgr.UpdatePool<Creature>(*GetMap()->GetPersistentState(), poolid, GetGUIDLow());
if (!IsInWorld()) // can be despawned by update pool
return;
if ((getDeathState() != CORPSE && !m_isDeadByDefault) || (getDeathState() != ALIVE && m_isDeadByDefault))
return;
DEBUG_FILTER_LOG(LOG_FILTER_AI_AND_MOVEGENSS, "Removing corpse of %s ", GetGuidStr().c_str());
m_corpseDecayTimer = 0;
SetDeathState(DEAD);
UpdateObjectVisibility();
// stop loot rolling before loot clear and for close client dialogs
StopGroupLoot();
loot.clear();
uint32 respawnDelay = 0;
if (AI())
AI()->CorpseRemoved(respawnDelay);
// script can set time (in seconds) explicit, override the original
if (respawnDelay)
m_respawnTime = time(NULL) + respawnDelay;
float x, y, z, o;
GetRespawnCoord(x, y, z, &o);
GetMap()->CreatureRelocation(this, x, y, z, o);
// forced recreate creature object at clients
UnitVisibility currentVis = GetVisibility();
SetVisibility(VISIBILITY_REMOVE_CORPSE);
UpdateObjectVisibility();
SetVisibility(currentVis); // restore visibility state
UpdateObjectVisibility();
}
/**
* change the entry of creature until respawn
*/
bool Creature::InitEntry(uint32 Entry, CreatureData const* data /*=NULL*/, GameEventCreatureData const* eventData /*=NULL*/)
{
// use game event entry if any instead default suggested
if (eventData && eventData->entry_id)
Entry = eventData->entry_id;
CreatureInfo const* normalInfo = ObjectMgr::GetCreatureTemplate(Entry);
if (!normalInfo)
{
sLog.outErrorDb("Creature::UpdateEntry creature entry %u does not exist.", Entry);
return false;
}
CreatureInfo const* cinfo = normalInfo;
for (Difficulty diff = GetMap()->GetDifficulty(); diff > REGULAR_DIFFICULTY; diff = GetPrevDifficulty(diff, GetMap()->IsRaid()))
{
// we already have valid Map pointer for current creature!
if (normalInfo->DifficultyEntry[diff - 1])
{
cinfo = ObjectMgr::GetCreatureTemplate(normalInfo->DifficultyEntry[diff - 1]);
if (cinfo)
break; // template found
// check and reported at startup, so just ignore (restore normalInfo)
cinfo = normalInfo;
}
}
SetEntry(Entry); // normal entry always
m_creatureInfo = cinfo; // map mode related always
SetObjectScale(cinfo->Scale);
// equal to player Race field, but creature does not have race
SetByteValue(UNIT_FIELD_BYTES_0, 0, 0);
// known valid are: CLASS_WARRIOR,CLASS_PALADIN,CLASS_ROGUE,CLASS_MAGE
SetByteValue(UNIT_FIELD_BYTES_0, 1, uint8(cinfo->UnitClass));
uint32 display_id = ChooseDisplayId(GetCreatureInfo(), data, eventData);
if (!display_id) // Cancel load if no display id
{
sLog.outErrorDb("Creature (Entry: %u) has no model defined in table `creature_template`, can't load.", Entry);
return false;
}
CreatureModelInfo const* minfo = sObjectMgr.GetCreatureModelRandomGender(display_id);
if (!minfo) // Cancel load if no model defined
{
sLog.outErrorDb("Creature (Entry: %u) has no model info defined in table `creature_model_info`, can't load.", Entry);
return false;
}
display_id = minfo->modelid; // it can be different (for another gender)
SetNativeDisplayId(display_id);
// normally the same as native, but some has exceptions (Spell::DoSummonTotem)
SetDisplayId(display_id);
SetByteValue(UNIT_FIELD_BYTES_0, 2, minfo->gender);
// set PowerType based on unit class
switch (cinfo->UnitClass)
{
case CLASS_WARRIOR:
SetByteValue(UNIT_FIELD_BYTES_0, 3, POWER_RAGE);
break;
case CLASS_PALADIN:
case CLASS_MAGE:
SetByteValue(UNIT_FIELD_BYTES_0, 3, POWER_MANA);
break;
case CLASS_ROGUE:
SetByteValue(UNIT_FIELD_BYTES_0, 3, POWER_ENERGY);
break;
default:
sLog.outErrorDb("Creature (Entry: %u) has unhandled unit class. Power type will not be set!", Entry);
break;
}
// Load creature equipment
if (eventData && eventData->equipment_id)
{
LoadEquipment(eventData->equipment_id); // use event equipment if any for active event
}
else if (!data || data->equipmentId == 0)
{
if (cinfo->EquipmentTemplateId == 0)
LoadEquipment(normalInfo->EquipmentTemplateId); // use default from normal template if diff does not have any
else
LoadEquipment(cinfo->EquipmentTemplateId); // else use from diff template
}
else if (data && data->equipmentId != -1)
{
// override, -1 means no equipment
LoadEquipment(data->equipmentId);
}
SetName(normalInfo->Name); // at normal entry always
SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
// update speed for the new CreatureInfo base speed mods
UpdateSpeed(MOVE_WALK, false);
UpdateSpeed(MOVE_RUN, false);
SetLevitate(cinfo->InhabitType & INHABIT_AIR);
// checked at loading
m_defaultMovementType = MovementGeneratorType(cinfo->MovementType);
return true;
}
bool Creature::UpdateEntry(uint32 Entry, Team team, const CreatureData* data /*=NULL*/, GameEventCreatureData const* eventData /*=NULL*/, bool preserveHPAndPower /*=true*/)
{
if (!InitEntry(Entry, data, eventData))
return false;
// creatures always have melee weapon ready if any
SetSheath(SHEATH_STATE_MELEE);
SelectLevel(GetCreatureInfo(), preserveHPAndPower ? GetHealthPercent() : 100.0f, 100.0f);
if (team == HORDE)
setFaction(GetCreatureInfo()->FactionHorde);
else
setFaction(GetCreatureInfo()->FactionAlliance);
SetUInt32Value(UNIT_NPC_FLAGS, GetCreatureInfo()->NpcFlags);
uint32 attackTimer = GetCreatureInfo()->MeleeBaseAttackTime;
SetAttackTime(BASE_ATTACK, attackTimer);
SetAttackTime(OFF_ATTACK, attackTimer - attackTimer / 4);
SetAttackTime(RANGED_ATTACK, GetCreatureInfo()->RangedBaseAttackTime);
uint32 unitFlags = GetCreatureInfo()->UnitFlags;
// we may need to append or remove additional flags
if (HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT))
unitFlags |= UNIT_FLAG_IN_COMBAT;
SetUInt32Value(UNIT_FIELD_FLAGS, unitFlags);
// preserve all current dynamic flags if exist
uint32 dynFlags = GetUInt32Value(UNIT_DYNAMIC_FLAGS);
SetUInt32Value(UNIT_DYNAMIC_FLAGS, dynFlags ? dynFlags : GetCreatureInfo()->DynamicFlags);
SetModifierValue(UNIT_MOD_ARMOR, BASE_VALUE, float(GetCreatureInfo()->Armor));
SetModifierValue(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(GetCreatureInfo()->ResistanceHoly));
SetModifierValue(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(GetCreatureInfo()->ResistanceFire));
SetModifierValue(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(GetCreatureInfo()->ResistanceNature));
SetModifierValue(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(GetCreatureInfo()->ResistanceFrost));
SetModifierValue(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(GetCreatureInfo()->ResistanceShadow));
SetModifierValue(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(GetCreatureInfo()->ResistanceArcane));
SetCanModifyStats(true);
UpdateAllStats();
// checked and error show at loading templates
if (FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(GetCreatureInfo()->FactionAlliance))
{
if (factionTemplate->factionFlags & FACTION_TEMPLATE_FLAG_PVP)
SetPvP(true);
else
SetPvP(false);
}
// Try difficulty dependend version before falling back to base entry
CreatureTemplateSpells const* templateSpells = sCreatureTemplateSpellsStorage.LookupEntry<CreatureTemplateSpells>(GetCreatureInfo()->Entry);
if (!templateSpells)
templateSpells = sCreatureTemplateSpellsStorage.LookupEntry<CreatureTemplateSpells>(GetEntry());
if (templateSpells)
for (int i = 0; i < CREATURE_MAX_SPELLS; ++i)
m_spells[i] = templateSpells->spells[i];
SetVehicleId(GetCreatureInfo()->VehicleTemplateId, 0);
// if eventData set then event active and need apply spell_start
if (eventData)
ApplyGameEventSpells(eventData, true);
return true;
}
uint32 Creature::ChooseDisplayId(const CreatureInfo* cinfo, const CreatureData* data /*= NULL*/, GameEventCreatureData const* eventData /*=NULL*/)
{
// Use creature event model explicit, override any other static models
if (eventData && eventData->modelid)
return eventData->modelid;
// Use creature model explicit, override template (creature.modelid)
if (data && data->modelid_override)
return data->modelid_override;
// use defaults from the template
uint32 display_id = 0;
// models may be categorized as (in this order):
// if mod4 && mod3 && mod2 && mod1 use any, by 25%-chance (other gender is selected and replaced after this function)
// if mod3 && mod2 && mod1 use mod3 unless mod2 has modelid_alt_model (then all by 33%-chance)
// if mod2 use mod2 unless mod2 has modelid_alt_model (then both by 50%-chance)
// if mod1 use mod1
// model selected here may be replaced with other_gender using own function
if (cinfo->ModelId[3] && cinfo->ModelId[2] && cinfo->ModelId[1] && cinfo->ModelId[0])
{
display_id = cinfo->ModelId[urand(0, 3)];
}
else if (cinfo->ModelId[2] && cinfo->ModelId[1] && cinfo->ModelId[0])
{
uint32 modelid_tmp = sObjectMgr.GetCreatureModelAlternativeModel(cinfo->ModelId[1]);
display_id = modelid_tmp ? cinfo->ModelId[urand(0, 2)] : cinfo->ModelId[2];
}
else if (cinfo->ModelId[1])
{
// We use this to eliminate invisible models vs. "dummy" models (infernals, etc).
// Where it's expected to select one of two, model must have a alternative model defined (alternative model is normally the same as defined in ModelId1).
// Same pattern is used in the above model selection, but the result may be ModelId3 and not ModelId2 as here.
uint32 modelid_tmp = sObjectMgr.GetCreatureModelAlternativeModel(cinfo->ModelId[1]);
display_id = modelid_tmp ? cinfo->ModelId[urand(0, 1)] : cinfo->ModelId[1];
}
else if (cinfo->ModelId[0])
{
display_id = cinfo->ModelId[0];
}
// fail safe, we use creature entry 1 and make error
if (!display_id)
{
sLog.outErrorDb("Call customer support, ChooseDisplayId can not select native model for creature entry %u, model from creature entry 1 will be used instead.", cinfo->Entry);
if (const CreatureInfo* creatureDefault = ObjectMgr::GetCreatureTemplate(1))
display_id = creatureDefault->ModelId[0];
}
return display_id;
}
void Creature::Update(uint32 update_diff, uint32 diff)
{
switch (m_deathState)
{
case JUST_ALIVED:
// Don't must be called, see Creature::SetDeathState JUST_ALIVED -> ALIVE promoting.
sLog.outError("Creature (GUIDLow: %u Entry: %u ) in wrong state: JUST_ALIVED (4)", GetGUIDLow(), GetEntry());
break;
case JUST_DIED:
// Don't must be called, see Creature::SetDeathState JUST_DIED -> CORPSE promoting.
sLog.outError("Creature (GUIDLow: %u Entry: %u ) in wrong state: JUST_DEAD (1)", GetGUIDLow(), GetEntry());
break;
case DEAD:
{
if (m_respawnTime <= time(NULL) && (!m_isSpawningLinked || GetMap()->GetCreatureLinkingHolder()->CanSpawn(this)))
{
DEBUG_FILTER_LOG(LOG_FILTER_AI_AND_MOVEGENSS, "Respawning...");
m_respawnTime = 0;
m_aggroDelay = sWorld.getConfig(CONFIG_UINT32_CREATURE_RESPAWN_AGGRO_DELAY);
lootForPickPocketed = false;
lootForBody = false;
lootForSkin = false;
// Clear possible auras having IsDeathPersistent() attribute
RemoveAllAuras();
if (m_originalEntry != GetEntry())
{
// need preserver gameevent state
GameEventCreatureData const* eventData = sGameEventMgr.GetCreatureUpdateDataForActiveEvent(GetGUIDLow());
UpdateEntry(m_originalEntry, TEAM_NONE, NULL, eventData);
}
CreatureInfo const* cinfo = GetCreatureInfo();
SelectLevel(cinfo);
UpdateAllStats(); // to be sure stats is correct regarding level of the creature
SetUInt32Value(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_NONE);
if (m_isDeadByDefault)
{
SetDeathState(JUST_DIED);
SetHealth(0);
i_motionMaster.Clear();
clearUnitState(UNIT_STAT_ALL_STATE);
LoadCreatureAddon(true);
}
else
SetDeathState(JUST_ALIVED);
// Call AI respawn virtual function
if (AI())
AI()->JustRespawned();
if (m_isCreatureLinkingTrigger)
GetMap()->GetCreatureLinkingHolder()->DoCreatureLinkingEvent(LINKING_EVENT_RESPAWN, this);
GetMap()->Add(this);
}
break;
}
case CORPSE:
{
Unit::Update(update_diff, diff);
if (m_isDeadByDefault)
break;
if (m_corpseDecayTimer <= update_diff)
{
RemoveCorpse();
break;
}
else
m_corpseDecayTimer -= update_diff;
if (m_groupLootId) // Loot is stopped already if corpse got removed.
{
if (m_groupLootTimer <= update_diff)
StopGroupLoot();
else
m_groupLootTimer -= update_diff;
}
break;
}
case ALIVE:
{
if (m_aggroDelay <= update_diff)
m_aggroDelay = 0;
else
m_aggroDelay -= update_diff;
if (m_isDeadByDefault)
{
if (m_corpseDecayTimer <= update_diff)
{
RemoveCorpse();
break;
}
else
m_corpseDecayTimer -= update_diff;
}
Unit::Update(update_diff, diff);
// creature can be dead after Unit::Update call
// CORPSE/DEAD state will processed at next tick (in other case death timer will be updated unexpectedly)
if (!isAlive())
break;
if (!IsInEvadeMode())
{
if (AI())
{
// do not allow the AI to be changed during update
m_AI_locked = true;
AI()->UpdateAI(diff); // AI not react good at real update delays (while freeze in non-active part of map)
m_AI_locked = false;
}
}
// creature can be dead after UpdateAI call
// CORPSE/DEAD state will processed at next tick (in other case death timer will be updated unexpectedly)
if (!isAlive())
break;
RegenerateAll(update_diff);
break;
}
default:
break;
}
}
void Creature::StartGroupLoot(Group* group, uint32 timer)
{
m_groupLootId = group->GetId();
m_groupLootTimer = timer;
}
void Creature::StopGroupLoot()
{
if (!m_groupLootId)
return;
if (Group* group = sObjectMgr.GetGroupById(m_groupLootId))
group->EndRoll();
m_groupLootTimer = 0;
m_groupLootId = 0;
}
void Creature::RegenerateAll(uint32 update_diff)
{
if (m_regenTimer > 0)
{
if (update_diff >= m_regenTimer)
m_regenTimer = 0;
else
m_regenTimer -= update_diff;
}
if (m_regenTimer != 0)
return;
if (!isInCombat() || IsPolymorphed())
RegenerateHealth();
RegeneratePower();
m_regenTimer = REGEN_TIME_FULL;
}
void Creature::RegeneratePower()
{
if (!IsRegeneratingPower())
return;
Powers powerType = getPowerType();
uint32 curValue = GetPower(powerType);
uint32 maxValue = GetMaxPower(powerType);
if (curValue >= maxValue)
return;
float addValue = 0.0f;
switch (powerType)
{
case POWER_MANA:
// Combat and any controlled creature
if (isInCombat() || GetCharmerOrOwnerGuid())
{
float ManaIncreaseRate = sWorld.getConfig(CONFIG_FLOAT_RATE_POWER_MANA);
float Spirit = GetStat(STAT_SPIRIT);
addValue = uint32(Spirit / 5.0f + 17.0f) * ManaIncreaseRate;
}
else
addValue = maxValue / 3;
break;
case POWER_ENERGY:
// ToDo: for vehicle this is different - NEEDS TO BE FIXED!
addValue = 20 * sWorld.getConfig(CONFIG_FLOAT_RATE_POWER_ENERGY);
break;
case POWER_FOCUS:
addValue = 24 * sWorld.getConfig(CONFIG_FLOAT_RATE_POWER_FOCUS);
break;
default:
return;
}
// Apply modifiers (if any)
AuraList const& ModPowerRegenAuras = GetAurasByType(SPELL_AURA_MOD_POWER_REGEN);
for(AuraList::const_iterator i = ModPowerRegenAuras.begin(); i != ModPowerRegenAuras.end(); ++i)
if ((*i)->GetModifier()->m_miscvalue == int32(powerType))
addValue += (*i)->GetModifier()->m_amount;
AuraList const& ModPowerRegenPCTAuras = GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
for(AuraList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i)
if ((*i)->GetModifier()->m_miscvalue == int32(powerType))
addValue *= ((*i)->GetModifier()->m_amount + 100) / 100.0f;
ModifyPower(powerType, int32(addValue));
}
void Creature::RegenerateHealth()
{
if (!IsRegeneratingHealth())
return;
uint32 curValue = GetHealth();
uint32 maxValue = GetMaxHealth();
if (curValue >= maxValue)
return;
uint32 addvalue = 0;
// Not only pet, but any controlled creature
if (GetCharmerOrOwnerGuid())
{
float HealthIncreaseRate = sWorld.getConfig(CONFIG_FLOAT_RATE_HEALTH);
float Spirit = GetStat(STAT_SPIRIT);
if (GetPower(POWER_MANA) > 0)
addvalue = uint32(Spirit * 0.25 * HealthIncreaseRate);
else
addvalue = uint32(Spirit * 0.80 * HealthIncreaseRate);
}
else
addvalue = maxValue / 3;
ModifyHealth(addvalue);
}
void Creature::DoFleeToGetAssistance()
{
if (!getVictim())
return;
float radius = sWorld.getConfig(CONFIG_FLOAT_CREATURE_FAMILY_FLEE_ASSISTANCE_RADIUS);
if (radius > 0)
{
Creature* pCreature = NULL;
MaNGOS::NearestAssistCreatureInCreatureRangeCheck u_check(this, getVictim(), radius);
MaNGOS::CreatureLastSearcher<MaNGOS::NearestAssistCreatureInCreatureRangeCheck> searcher(pCreature, u_check);
Cell::VisitGridObjects(this, searcher, radius);
SetNoSearchAssistance(true);
UpdateSpeed(MOVE_RUN, false);
if (!pCreature)
SetFeared(true, getVictim()->GetObjectGuid(), 0 , sWorld.getConfig(CONFIG_UINT32_CREATURE_FAMILY_FLEE_DELAY));
else
GetMotionMaster()->MoveSeekAssistance(pCreature->GetPositionX(), pCreature->GetPositionY(), pCreature->GetPositionZ());
}
}
bool Creature::AIM_Initialize()
{
// make sure nothing can change the AI during AI update
if (m_AI_locked)
{
DEBUG_FILTER_LOG(LOG_FILTER_AI_AND_MOVEGENSS, "AIM_Initialize: failed to init, locked.");
return false;
}
CreatureAI* oldAI = i_AI;
i_motionMaster.Initialize();
i_AI = FactorySelector::selectAI(this);
delete oldAI;
return true;
}
bool Creature::Create(uint32 guidlow, CreatureCreatePos& cPos, CreatureInfo const* cinfo, Team team /*= TEAM_NONE*/, const CreatureData* data /*= NULL*/, GameEventCreatureData const* eventData /*= NULL*/)
{
SetMap(cPos.GetMap());
SetPhaseMask(cPos.GetPhaseMask(), false);
if (!CreateFromProto(guidlow, cinfo, team, data, eventData))
return false;
cPos.SelectFinalPoint(this);
if (!cPos.Relocate(this))
return false;
// Notify the outdoor pvp script
if (OutdoorPvP* outdoorPvP = sOutdoorPvPMgr.GetScript(GetZoneId()))
outdoorPvP->HandleCreatureCreate(this);
// Notify the map's instance data.
// Only works if you create the object in it, not if it is moves to that map.
// Normally non-players do not teleport to other maps.
if (InstanceData* iData = GetMap()->GetInstanceData())
iData->OnCreatureCreate(this);
switch (GetCreatureInfo()->Rank)
{
case CREATURE_ELITE_RARE:
m_corpseDelay = sWorld.getConfig(CONFIG_UINT32_CORPSE_DECAY_RARE);
break;
case CREATURE_ELITE_ELITE:
m_corpseDelay = sWorld.getConfig(CONFIG_UINT32_CORPSE_DECAY_ELITE);
break;
case CREATURE_ELITE_RAREELITE:
m_corpseDelay = sWorld.getConfig(CONFIG_UINT32_CORPSE_DECAY_RAREELITE);
break;
case CREATURE_ELITE_WORLDBOSS:
m_corpseDelay = sWorld.getConfig(CONFIG_UINT32_CORPSE_DECAY_WORLDBOSS);
break;
default:
m_corpseDelay = sWorld.getConfig(CONFIG_UINT32_CORPSE_DECAY_NORMAL);
break;
}
// Add to CreatureLinkingHolder if needed
if (sCreatureLinkingMgr.GetLinkedTriggerInformation(this))
cPos.GetMap()->GetCreatureLinkingHolder()->AddSlaveToHolder(this);
if (sCreatureLinkingMgr.IsLinkedEventTrigger(this))
{
m_isCreatureLinkingTrigger = true;
cPos.GetMap()->GetCreatureLinkingHolder()->AddMasterToHolder(this);
}
LoadCreatureAddon(false);
return true;
}
bool Creature::IsTrainerOf(Player* pPlayer, bool msg) const
{
if (!isTrainer())
return false;
// pet trainers not have spells in fact now
if (GetCreatureInfo()->TrainerType != TRAINER_TYPE_PETS)
{
TrainerSpellData const* cSpells = GetTrainerSpells();
TrainerSpellData const* tSpells = GetTrainerTemplateSpells();
// for not pet trainer expected not empty trainer list always
if ((!cSpells || cSpells->spellList.empty()) && (!tSpells || tSpells->spellList.empty()))
{
sLog.outErrorDb("Creature %u (Entry: %u) have UNIT_NPC_FLAG_TRAINER but have empty trainer spell list.",
GetGUIDLow(), GetEntry());
return false;
}
}
switch (GetCreatureInfo()->TrainerType)
{
case TRAINER_TYPE_CLASS:
if (pPlayer->getClass() != GetCreatureInfo()->TrainerClass)
{
if (msg)
{
pPlayer->PlayerTalkClass->ClearMenus();
switch (GetCreatureInfo()->TrainerClass)
{
case CLASS_DRUID: pPlayer->PlayerTalkClass->SendGossipMenu(4913, GetObjectGuid()); break;
case CLASS_HUNTER: pPlayer->PlayerTalkClass->SendGossipMenu(10090, GetObjectGuid()); break;
case CLASS_MAGE: pPlayer->PlayerTalkClass->SendGossipMenu(328, GetObjectGuid()); break;
case CLASS_PALADIN: pPlayer->PlayerTalkClass->SendGossipMenu(1635, GetObjectGuid()); break;
case CLASS_PRIEST: pPlayer->PlayerTalkClass->SendGossipMenu(4436, GetObjectGuid()); break;
case CLASS_ROGUE: pPlayer->PlayerTalkClass->SendGossipMenu(4797, GetObjectGuid()); break;
case CLASS_SHAMAN: pPlayer->PlayerTalkClass->SendGossipMenu(5003, GetObjectGuid()); break;
case CLASS_WARLOCK: pPlayer->PlayerTalkClass->SendGossipMenu(5836, GetObjectGuid()); break;
case CLASS_WARRIOR: pPlayer->PlayerTalkClass->SendGossipMenu(4985, GetObjectGuid()); break;
}
}
return false;
}
break;
case TRAINER_TYPE_PETS:
if (pPlayer->getClass() != CLASS_HUNTER)
{
if (msg)
{
pPlayer->PlayerTalkClass->ClearMenus();
pPlayer->PlayerTalkClass->SendGossipMenu(3620, GetObjectGuid());
}
return false;
}
break;
case TRAINER_TYPE_MOUNTS:
if (GetCreatureInfo()->TrainerRace && pPlayer->getRace() != GetCreatureInfo()->TrainerRace)
{
// Allowed to train if exalted
if (FactionTemplateEntry const* faction_template = getFactionTemplateEntry())
{
if (pPlayer->GetReputationRank(faction_template->faction) == REP_EXALTED)
return true;
}
if (msg)
{
pPlayer->PlayerTalkClass->ClearMenus();
switch (GetCreatureInfo()->TrainerClass)
{
case RACE_DWARF: pPlayer->PlayerTalkClass->SendGossipMenu(5865, GetObjectGuid()); break;
case RACE_GNOME: pPlayer->PlayerTalkClass->SendGossipMenu(4881, GetObjectGuid()); break;
case RACE_HUMAN: pPlayer->PlayerTalkClass->SendGossipMenu(5861, GetObjectGuid()); break;
case RACE_NIGHTELF: pPlayer->PlayerTalkClass->SendGossipMenu(5862, GetObjectGuid()); break;
case RACE_ORC: pPlayer->PlayerTalkClass->SendGossipMenu(5863, GetObjectGuid()); break;
case RACE_TAUREN: pPlayer->PlayerTalkClass->SendGossipMenu(5864, GetObjectGuid()); break;
case RACE_TROLL: pPlayer->PlayerTalkClass->SendGossipMenu(5816, GetObjectGuid()); break;
case RACE_UNDEAD: pPlayer->PlayerTalkClass->SendGossipMenu(624, GetObjectGuid()); break;
case RACE_BLOODELF: pPlayer->PlayerTalkClass->SendGossipMenu(5862, GetObjectGuid()); break;
case RACE_DRAENEI: pPlayer->PlayerTalkClass->SendGossipMenu(5864, GetObjectGuid()); break;
}
}
return false;
}
break;
case TRAINER_TYPE_TRADESKILLS:
if (GetCreatureInfo()->TrainerSpell && !pPlayer->HasSpell(GetCreatureInfo()->TrainerSpell))
{
if (msg)
{
pPlayer->PlayerTalkClass->ClearMenus();
pPlayer->PlayerTalkClass->SendGossipMenu(11031, GetObjectGuid());
}
return false;
}
break;
default:
return false; // checked and error output at creature_template loading
}
return true;
}
bool Creature::CanInteractWithBattleMaster(Player* pPlayer, bool msg) const
{
if (!isBattleMaster())
return false;
BattleGroundTypeId bgTypeId = sBattleGroundMgr.GetBattleMasterBG(GetEntry());
if (bgTypeId == BATTLEGROUND_TYPE_NONE)
return false;
if (!msg)
return pPlayer->GetBGAccessByLevel(bgTypeId);
if (!pPlayer->GetBGAccessByLevel(bgTypeId))
{
pPlayer->PlayerTalkClass->ClearMenus();
switch (bgTypeId)
{
case BATTLEGROUND_AV: pPlayer->PlayerTalkClass->SendGossipMenu(7616, GetObjectGuid()); break;
case BATTLEGROUND_WS: pPlayer->PlayerTalkClass->SendGossipMenu(7599, GetObjectGuid()); break;
case BATTLEGROUND_AB: pPlayer->PlayerTalkClass->SendGossipMenu(7642, GetObjectGuid()); break;
case BATTLEGROUND_EY:
case BATTLEGROUND_NA:
case BATTLEGROUND_BE:
case BATTLEGROUND_AA:
case BATTLEGROUND_RL:
case BATTLEGROUND_SA:
case BATTLEGROUND_DS:
case BATTLEGROUND_RV: pPlayer->PlayerTalkClass->SendGossipMenu(10024, GetObjectGuid()); break;
default: break;
}
return false;
}
return true;
}
bool Creature::CanTrainAndResetTalentsOf(Player* pPlayer) const
{
return pPlayer->getLevel() >= 10
&& GetCreatureInfo()->TrainerType == TRAINER_TYPE_CLASS
&& pPlayer->getClass() == GetCreatureInfo()->TrainerClass;
}
void Creature::PrepareBodyLootState()
{
loot.clear();
// if have normal loot then prepare it access
if (!lootForBody)
{
// have normal loot
if (GetCreatureInfo()->MaxLootGold > 0 || GetCreatureInfo()->LootId ||
// ... or can have skinning after
(GetCreatureInfo()->SkinningLootId && sWorld.getConfig(CONFIG_BOOL_CORPSE_EMPTY_LOOT_SHOW)))
{
SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE);
return;
}
}
lootForBody = true; // pass this loot mode
// if not have normal loot allow skinning if need
if (!lootForSkin && GetCreatureInfo()->SkinningLootId)
{
RemoveFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE);
SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
return;
}
RemoveFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE);
RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
}