[7847] Replace paramter unions by uniton of event ai action type structures. Add...
[getmangos.git] / src / game / CreatureEventAI.cpp
blob688460212d5497427847097734d5bfe9957634d0
1 /*
2 * Copyright (C) 2009 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #include "Common.h"
20 #include "CreatureEventAI.h"
21 #include "CreatureEventAIMgr.h"
22 #include "ObjectMgr.h"
23 #include "Spell.h"
24 #include "World.h"
25 #include "Cell.h"
26 #include "CellImpl.h"
27 #include "GameEventMgr.h"
28 #include "GridNotifiers.h"
29 #include "GridNotifiersImpl.h"
30 #include "WorldPacket.h"
31 #include "InstanceData.h"
33 int CreatureEventAI::Permissible(const Creature *creature)
35 if( creature->GetAIName() == "EventAI" )
36 return PERMIT_BASE_SPECIAL;
37 return PERMIT_BASE_NO;
40 CreatureEventAI::CreatureEventAI(Creature *c ) : CreatureAI(c)
42 // Need make copy for filter unneeded steps and safe in case table reload
43 CreatureEventAI_Event_Map::const_iterator CreatureEvents = CreatureEAI_Mgr.GetCreatureEventAIMap().find(m_creature->GetEntry());
44 if (CreatureEvents != CreatureEAI_Mgr.GetCreatureEventAIMap().end())
46 std::vector<CreatureEventAI_Event>::const_iterator i;
47 for (i = (*CreatureEvents).second.begin(); i != (*CreatureEvents).second.end(); ++i)
50 //Debug check
51 #ifndef MANGOS_DEBUG
52 if ((*i).event_flags & EFLAG_DEBUG_ONLY)
53 continue;
54 #endif
55 if (m_creature->GetMap()->IsDungeon())
57 if( (m_creature->GetMap()->IsHeroic() && (*i).event_flags & EFLAG_HEROIC) ||
58 (!m_creature->GetMap()->IsHeroic() && (*i).event_flags & EFLAG_NORMAL))
60 //event flagged for instance mode
61 CreatureEventAIList.push_back(CreatureEventAIHolder(*i));
63 continue;
65 CreatureEventAIList.push_back(CreatureEventAIHolder(*i));
67 //EventMap had events but they were not added because they must be for instance
68 if (CreatureEventAIList.empty())
69 sLog.outError("CreatureEventAI: Creature %u has events but no events added to list because of instance flags.", m_creature->GetEntry());
71 else
72 sLog.outError("CreatureEventAI: EventMap for Creature %u is empty but creature is using CreatureEventAI.", m_creature->GetEntry());
74 bEmptyList = CreatureEventAIList.empty();
75 Phase = 0;
76 CombatMovementEnabled = true;
77 MeleeEnabled = true;
78 AttackDistance = 0;
79 AttackAngle = 0.0f;
81 //Handle Spawned Events
82 if (!bEmptyList)
84 for (std::list<CreatureEventAIHolder>::iterator i = CreatureEventAIList.begin(); i != CreatureEventAIList.end(); ++i)
86 if ((*i).Event.event_type == EVENT_T_SPAWNED)
87 ProcessEvent(*i);
90 Reset();
93 bool CreatureEventAI::ProcessEvent(CreatureEventAIHolder& pHolder, Unit* pActionInvoker)
95 if (!pHolder.Enabled || pHolder.Time)
96 return false;
98 //Check the inverse phase mask (event doesn't trigger if current phase bit is set in mask)
99 if (pHolder.Event.event_inverse_phase_mask & (1 << Phase))
100 return false;
102 //Store random here so that all random actions match up
103 uint32 rnd = rand();
105 //Return if chance for event is not met
106 if (pHolder.Event.event_chance <= rnd % 100)
107 return false;
109 uint32 param1 = pHolder.Event.event_param1;
110 uint32 param2 = pHolder.Event.event_param2;
111 uint32 param3 = pHolder.Event.event_param3;
112 uint32 param4 = pHolder.Event.event_param4;
114 //Check event conditions based on the event type, also reset events
115 switch (pHolder.Event.event_type)
117 case EVENT_T_TIMER:
119 if (!m_creature->isInCombat())
120 return false;
122 //Repeat Timers
123 if (param3 == param4)
125 pHolder.Time = param3;
127 }else if (param4 > param3)
128 pHolder.Time = urand(param3, param4);
129 else
131 sLog.outErrorDb("CreatureEventAI: Creature %u using Event %u (Type = %u) has RandomMax < RandomMin. Event repeating disabled.", m_creature->GetEntry(), pHolder.Event.event_id, pHolder.Event.event_type);
132 pHolder.Enabled = false;
135 break;
136 case EVENT_T_TIMER_OOC:
138 if (m_creature->isInCombat())
139 return false;
141 //Repeat Timers
142 if (param3 == param4)
144 pHolder.Time = param3;
146 }else if (param4 > param3)
147 pHolder.Time = urand(param3, param4);
148 else
151 sLog.outErrorDb("CreatureEventAI: Creature %u using Event %u (Type = %u) has RandomMax < RandomMin. Event repeating disabled.", m_creature->GetEntry(), pHolder.Event.event_id, pHolder.Event.event_type);
152 pHolder.Enabled = false;
155 break;
156 case EVENT_T_HP:
158 if (!m_creature->isInCombat() || !m_creature->GetMaxHealth())
159 return false;
161 uint32 perc = (m_creature->GetHealth()*100) / m_creature->GetMaxHealth();
163 if (perc > param1 || perc < param2)
164 return false;
166 //Repeat Timers
167 if (param3 == param4)
169 pHolder.Time = param3;
171 }else if (param4 > param3)
172 pHolder.Time = urand(param3, param4);
173 else
176 sLog.outErrorDb("CreatureEventAI: Creature %u using Event %u (Type = %u) has RandomMax < RandomMin. Event repeating disabled.", m_creature->GetEntry(), pHolder.Event.event_id, pHolder.Event.event_type);
177 pHolder.Enabled = false;
180 break;
181 case EVENT_T_MANA:
183 if (!m_creature->isInCombat() || !m_creature->GetMaxPower(POWER_MANA))
184 return false;
186 uint32 perc = (m_creature->GetPower(POWER_MANA)*100) / m_creature->GetMaxPower(POWER_MANA);
188 if (perc > param1 || perc < param2)
189 return false;
191 //Repeat Timers
192 if (param3 == param4)
194 pHolder.Time = param3;
196 }else if (param4 > param3)
197 pHolder.Time = urand(param3, param4);
198 else
201 sLog.outErrorDb("CreatureEventAI: Creature %u using Event %u (Type = %u) has RandomMax < RandomMin. Event repeating disabled.", m_creature->GetEntry(), pHolder.Event.event_id, pHolder.Event.event_type);
202 pHolder.Enabled = false;
205 break;
206 case EVENT_T_AGGRO:
209 break;
210 case EVENT_T_KILL:
212 //Repeat Timers
213 if (param1 == param2)
215 pHolder.Time = param1;
217 }else if (param2 > param1)
218 pHolder.Time = urand(param1, param2);
219 else
222 sLog.outErrorDb("CreatureEventAI: Creature %u using Event %u (Type = %u) has RandomMax < RandomMin. Event repeating disabled.", m_creature->GetEntry(), pHolder.Event.event_id, pHolder.Event.event_type);
223 pHolder.Enabled = false;
226 case EVENT_T_DEATH:
229 break;
230 case EVENT_T_EVADE:
233 break;
234 case EVENT_T_SPELLHIT:
236 //Spell hit is special case, param1 and param2 handled within CreatureEventAI::SpellHit
238 //Repeat Timers
239 if (param3 == param4)
241 pHolder.Time = param3;
243 }else if (param4 > param3)
244 pHolder.Time = urand(param3, param4);
245 else
248 sLog.outErrorDb("CreatureEventAI: Creature %u using Event %u (Type = %u) has RandomMax < RandomMin. Event repeating disabled.", m_creature->GetEntry(), pHolder.Event.event_id, pHolder.Event.event_type);
249 pHolder.Enabled = false;
252 break;
253 case EVENT_T_RANGE:
255 //Repeat Timers
256 if (param3 == param4)
258 pHolder.Time = param3;
260 }else if (param4 > param3)
261 pHolder.Time = urand(param3, param4);
262 else
265 sLog.outErrorDb("CreatureEventAI: Creature %u using Event %u (Type = %u) has RandomMax < RandomMin. Event repeating disabled.", m_creature->GetEntry(), pHolder.Event.event_id, pHolder.Event.event_type);
266 pHolder.Enabled = false;
269 break;
270 case EVENT_T_OOC_LOS:
272 //Repeat Timers
273 if (param3 == param4)
275 pHolder.Time = param3;
277 }else if (param4 > param3)
278 pHolder.Time = urand(param3, param4);
279 else
282 sLog.outErrorDb("CreatureEventAI: Creature %u using Event %u (Type = %u) has RandomMax < RandomMin. Event repeating disabled.", m_creature->GetEntry(), pHolder.Event.event_id, pHolder.Event.event_type);
283 pHolder.Enabled = false;
286 break;
287 case EVENT_T_SPAWNED:
290 break;
291 case EVENT_T_TARGET_HP:
293 if (!m_creature->isInCombat() || !m_creature->getVictim() || !m_creature->getVictim()->GetMaxHealth())
294 return false;
296 uint32 perc = (m_creature->getVictim()->GetHealth()*100) / m_creature->getVictim()->GetMaxHealth();
298 if (perc > param1 || perc < param2)
299 return false;
301 //Repeat Timers
302 if (param3 == param4)
304 pHolder.Time = param3;
306 }else if (param4 > param3)
307 pHolder.Time = urand(param3, param4);
308 else
311 sLog.outErrorDb("CreatureEventAI: Creature %u using Event %u (Type = %u) has RandomMax < RandomMin. Event repeating disabled.", m_creature->GetEntry(), pHolder.Event.event_id, pHolder.Event.event_type);
312 pHolder.Enabled = false;
315 break;
316 case EVENT_T_TARGET_CASTING:
318 if (!m_creature->isInCombat() || !m_creature->getVictim() || !m_creature->getVictim()->IsNonMeleeSpellCasted(false, false, true))
319 return false;
321 //Repeat Timers
322 if (param1 == param2)
324 pHolder.Time = param1;
326 }else if (param2 > param1)
327 pHolder.Time = urand(param1, param2);
328 else
331 sLog.outErrorDb("CreatureEventAI: Creature %u using Event %u (Type = %u) has RandomMax < RandomMin. Event repeating disabled.", m_creature->GetEntry(), pHolder.Event.event_id, pHolder.Event.event_type);
332 pHolder.Enabled = false;
335 break;
336 case EVENT_T_FRIENDLY_HP:
338 if (!m_creature->isInCombat())
339 return false;
341 Unit* pUnit = DoSelectLowestHpFriendly(param2, param1);
343 if (!pUnit)
344 return false;
346 pActionInvoker = pUnit;
348 //Repeat Timers
349 if (param3 == param4)
351 pHolder.Time = param3;
353 }else if (param4 > param3)
354 pHolder.Time = urand(param3, param4);
355 else
358 sLog.outErrorDb("CreatureEventAI: Creature %u using Event %u (Type = %u) has RandomMax < RandomMin. Event repeating disabled.", m_creature->GetEntry(), pHolder.Event.event_id, pHolder.Event.event_type);
359 pHolder.Enabled = false;
362 break;
363 case EVENT_T_FRIENDLY_IS_CC:
365 if (!m_creature->isInCombat())
366 return false;
368 std::list<Creature*> pList;
369 DoFindFriendlyCC(pList, param2);
371 //List is empty
372 if (pList.empty())
373 return false;
375 //We don't really care about the whole list, just return first available
376 pActionInvoker = *(pList.begin());
378 //Repeat Timers
379 if (param3 == param4)
381 pHolder.Time = param3;
383 }else if (param4 > param3)
384 pHolder.Time = urand(param3, param4);
385 else
387 sLog.outErrorDb("CreatureEventAI: Creature %u using Event %u (Type = %u) has RandomMax < RandomMin. Event repeating disabled.", m_creature->GetEntry(), pHolder.Event.event_id, pHolder.Event.event_type);
388 pHolder.Enabled = false;
391 break;
392 case EVENT_T_FRIENDLY_MISSING_BUFF:
394 std::list<Creature*> pList;
395 DoFindFriendlyMissingBuff(pList, param2, param1);
397 //List is empty
398 if (pList.empty())
399 return false;
401 //We don't really care about the whole list, just return first available
402 pActionInvoker = *(pList.begin());
404 //Repeat Timers
405 if (param3 == param4)
407 pHolder.Time = param3;
409 }else if (param4 > param3)
410 pHolder.Time = urand(param3, param4);
411 else
414 sLog.outErrorDb("CreatureEventAI: Creature %u using Event %u (Type = %u) has RandomMax < RandomMin. Event repeating disabled.", m_creature->GetEntry(), pHolder.Event.event_id, pHolder.Event.event_type);
415 pHolder.Enabled = false;
418 break;
419 case EVENT_T_SUMMONED_UNIT:
421 //Prevent event from occuring on no unit or non creatures
422 if (!pActionInvoker || pActionInvoker->GetTypeId()!=TYPEID_UNIT)
423 return false;
425 //Creature id doesn't match up
426 if (param1 && ((Creature*)pActionInvoker)->GetEntry() != param1)
427 return false;
429 //Repeat Timers
430 if (param2 == param3)
432 pHolder.Time = param2;
434 }else if (param3 > param2)
435 pHolder.Time = urand(param2, param3);
436 else
439 sLog.outErrorDb("CreatureEventAI: Creature %u using Event %u (Type = %u) has RandomMax < RandomMin. Event repeating disabled.", m_creature->GetEntry(), pHolder.Event.event_id, pHolder.Event.event_type);
440 pHolder.Enabled = false;
443 break;
444 case EVENT_T_REACHED_HOME:
447 break;
448 case EVENT_T_RECEIVE_EMOTE:
451 break;
452 default:
454 sLog.outErrorDb("CreatureEventAI: Creature %u using Event %u has invalid Event Type(%u), missing from ProcessEvent() Switch.", m_creature->GetEntry(), pHolder.Event.event_id, pHolder.Event.event_type);
455 break;
458 //Disable non-repeatable events
459 if (!(pHolder.Event.event_flags & EFLAG_REPEATABLE))
460 pHolder.Enabled = false;
462 //Process actions
463 for (uint32 j = 0; j < MAX_ACTIONS; j++)
464 ProcessAction(pHolder.Event.action[j], rnd, pHolder.Event.event_id, pActionInvoker);
466 return true;
469 void CreatureEventAI::ProcessAction(CreatureEventAI_Action const& action, uint32 rnd, uint32 EventId, Unit* pActionInvoker)
471 switch (action.type)
473 case ACTION_T_TEXT:
475 if (!action.text.TextId1)
476 return;
478 int32 temp = 0;
480 if (action.text.TextId2 && action.text.TextId3)
482 switch( rand()%3 )
484 case 0: temp = action.text.TextId1; break;
485 case 2: temp = action.text.TextId2; break;
486 case 3: temp = action.text.TextId3; break;
489 else if (action.text.TextId2 && urand(0,1))
490 temp = action.text.TextId2;
491 else
492 temp = action.text.TextId1;
494 if (temp)
496 Unit* target = NULL;
498 if (pActionInvoker)
500 if (pActionInvoker->GetTypeId() == TYPEID_PLAYER)
501 target = pActionInvoker;
502 else if (Unit* owner = pActionInvoker->GetOwner())
504 if (owner->GetTypeId() == TYPEID_PLAYER)
505 target = owner;
508 else if (target = m_creature->getVictim())
510 if (target->GetTypeId() != TYPEID_PLAYER)
511 if (Unit* owner = target->GetOwner())
512 if (owner->GetTypeId() == TYPEID_PLAYER)
513 target = owner;
516 DoScriptText(temp, m_creature, target);
518 break;
520 case ACTION_T_SET_FACTION:
522 if (action.set_faction.factionId)
523 m_creature->setFaction(action.set_faction.factionId);
524 else
526 if (CreatureInfo const* ci = GetCreatureTemplateStore(m_creature->GetEntry()))
528 //if no id provided, assume reset and then use default
529 if (m_creature->getFaction() != ci->faction_A)
530 m_creature->setFaction(ci->faction_A);
533 break;
535 case ACTION_T_MORPH_TO_ENTRY_OR_MODEL:
537 if (action.morph.creatireId || action.morph.modelId)
539 //set model based on entry from creature_template
540 if (action.morph.creatireId)
542 if (CreatureInfo const* ci = GetCreatureTemplateStore(action.morph.creatireId))
544 //use default display
545 if (ci->DisplayID_A)
546 m_creature->SetDisplayId(ci->DisplayID_A);
549 //if no param1, then use value from param2 (modelId)
550 else
551 m_creature->SetDisplayId(action.morph.modelId);
553 else
554 m_creature->DeMorph();
555 break;
557 case ACTION_T_SOUND:
558 m_creature->PlayDirectSound(action.sound.soundId);
559 break;
560 case ACTION_T_EMOTE:
561 m_creature->HandleEmoteCommand(action.emote.emoteId);
562 break;
563 case ACTION_T_RANDOM_SOUND:
565 int32 temp = GetRandActionParam(rnd, action.random_sound.soundId1, action.random_sound.soundId2, action.random_sound.soundId3);
566 if (temp >= 0)
567 m_creature->PlayDirectSound(temp);
568 break;
570 case ACTION_T_RANDOM_EMOTE:
572 int32 temp = GetRandActionParam(rnd, action.random_emote.emoteId1, action.random_emote.emoteId2, action.random_emote.emoteId3);
573 if (temp >= 0)
574 m_creature->HandleEmoteCommand(temp);
575 break;
577 case ACTION_T_CAST:
579 Unit* target = GetTargetByType(action.cast.target, pActionInvoker);
580 Unit* caster = m_creature;
582 if (!target)
583 return;
585 if (action.cast.castFlags & CAST_FORCE_TARGET_SELF)
586 caster = target;
588 //Allowed to cast only if not casting (unless we interrupt ourself) or if spell is triggered
589 bool canCast = !caster->IsNonMeleeSpellCasted(false) || (action.cast.castFlags & (CAST_TRIGGERED | CAST_INTURRUPT_PREVIOUS));
591 // If cast flag CAST_AURA_NOT_PRESENT is active, check if target already has aura on them
592 if(action.cast.castFlags & CAST_AURA_NOT_PRESENT)
594 for(uint8 i = 0; i < 3; ++i)
595 if(target->HasAura(action.cast.spellId, i))
596 return;
599 if (canCast)
601 const SpellEntry* tSpell = GetSpellStore()->LookupEntry(action.cast.spellId);
603 //Verify that spell exists
604 if (tSpell)
606 //Check if cannot cast spell
607 if (!(action.cast.castFlags & (CAST_FORCE_TARGET_SELF | CAST_FORCE_CAST)) &&
608 !CanCast(target, tSpell, (action.cast.castFlags & CAST_TRIGGERED)))
610 //Melee current victim if flag not set
611 if (!(action.cast.castFlags & CAST_NO_MELEE_IF_OOM))
613 if (m_creature->GetMotionMaster()->GetCurrentMovementGeneratorType() == TARGETED_MOTION_TYPE)
615 AttackDistance = 0;
616 AttackAngle = 0;
618 m_creature->GetMotionMaster()->Clear(false);
619 m_creature->GetMotionMaster()->MoveChase(m_creature->getVictim(), AttackDistance, AttackAngle);
624 else
626 //Interrupt any previous spell
627 if (caster->IsNonMeleeSpellCasted(false) && action.cast.castFlags & CAST_INTURRUPT_PREVIOUS)
628 caster->InterruptNonMeleeSpells(false);
630 caster->CastSpell(target, action.cast.spellId, (action.cast.castFlags & CAST_TRIGGERED));
634 else
635 sLog.outErrorDb("CreatureEventAI: event %d creature %d attempt to cast spell that doesn't exist %d", EventId, m_creature->GetEntry(), action.cast.spellId);
637 break;
639 case ACTION_T_SUMMON:
641 Unit* target = GetTargetByType(action.summon.target, pActionInvoker);
643 Creature* pCreature = NULL;
645 if (action.summon.duration)
646 pCreature = m_creature->SummonCreature(action.summon.creatured, 0.0f, 0.0f, 0.0f, 0.0f, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, action.summon.duration);
647 else
648 pCreature = m_creature->SummonCreature(action.summon.creatured, 0.0f, 0.0f, 0.0f, 0.0f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 0);
650 if (!pCreature)
651 sLog.outErrorDb( "CreatureEventAI: failed to spawn creature %u. Spawn event %d is on creature %d", action.summon.creatured, EventId, m_creature->GetEntry());
652 else if (action.summon.target != TARGET_T_SELF && target)
653 pCreature->AI()->AttackStart(target);
654 break;
656 case ACTION_T_THREAT_SINGLE_PCT:
657 if (Unit* target = GetTargetByType(action.threat_single_pct.target, pActionInvoker))
658 m_creature->getThreatManager().modifyThreatPercent(target, action.threat_single_pct.percent);
659 break;
660 case ACTION_T_THREAT_ALL_PCT:
662 std::list<HostilReference*>& threatList = m_creature->getThreatManager().getThreatList();
663 for (std::list<HostilReference*>::iterator i = threatList.begin(); i != threatList.end(); ++i)
664 if(Unit* Temp = Unit::GetUnit(*m_creature,(*i)->getUnitGuid()))
665 m_creature->getThreatManager().modifyThreatPercent(Temp, action.threat_all_pct.percent);
666 break;
668 case ACTION_T_QUEST_EVENT:
669 if (Unit* target = GetTargetByType(action.quest_event.target, pActionInvoker))
670 if (target->GetTypeId() == TYPEID_PLAYER)
671 ((Player*)target)->AreaExploredOrEventHappens(action.quest_event.questId);
672 break;
673 case ACTION_T_CAST_EVENT:
674 if (Unit* target = GetTargetByType(action.cast_event.target, pActionInvoker))
675 if (target->GetTypeId() == TYPEID_PLAYER)
676 ((Player*)target)->CastedCreatureOrGO(action.cast_event.creatureId, m_creature->GetGUID(), action.cast_event.spellId);
677 break;
678 case ACTION_T_SET_UNIT_FIELD:
680 Unit* target = GetTargetByType(action.set_unit_field.target, pActionInvoker);
682 // not allow modify important for integrity object fields
683 if (action.set_unit_field.field < OBJECT_END || action.set_unit_field.field >= UNIT_END)
684 return;
686 if (target)
687 target->SetUInt32Value(action.set_unit_field.field, action.set_unit_field.value);
689 break;
691 case ACTION_T_SET_UNIT_FLAG:
692 if (Unit* target = GetTargetByType(action.unit_flag.target, pActionInvoker))
693 target->SetFlag(UNIT_FIELD_FLAGS, action.unit_flag.value);
694 break;
695 case ACTION_T_REMOVE_UNIT_FLAG:
696 if (Unit* target = GetTargetByType(action.unit_flag.target, pActionInvoker))
697 target->RemoveFlag(UNIT_FIELD_FLAGS, action.unit_flag.value);
698 break;
699 case ACTION_T_AUTO_ATTACK:
700 MeleeEnabled = action.auto_attack.state != 0;
701 break;
702 case ACTION_T_COMBAT_MOVEMENT:
703 CombatMovementEnabled = action.combat_movement.state != 0;
705 //Allow movement (create new targeted movement gen only if idle)
706 if (CombatMovementEnabled)
708 if (m_creature->GetMotionMaster()->GetCurrentMovementGeneratorType() == IDLE_MOTION_TYPE)
710 m_creature->GetMotionMaster()->Clear(false);
711 m_creature->GetMotionMaster()->MoveChase(m_creature->getVictim(), AttackDistance, AttackAngle);
714 else
715 if (m_creature->GetMotionMaster()->GetCurrentMovementGeneratorType() == TARGETED_MOTION_TYPE)
717 m_creature->GetMotionMaster()->Clear(false);
718 m_creature->GetMotionMaster()->MoveIdle();
719 m_creature->StopMoving();
721 break;
722 case ACTION_T_SET_PHASE:
723 Phase = action.set_phase.phase;
724 break;
725 case ACTION_T_INC_PHASE:
727 int32 new_phase = int32(Phase)+action.set_inc_phase.step;
728 if (new_phase < 0)
730 sLog.outErrorDb( "CreatureEventAI: Event %d decrease Phase under 0. CreatureEntry = %d", EventId, m_creature->GetEntry());
731 Phase = 0;
733 else if (new_phase >= MAX_PHASE)
735 sLog.outErrorDb( "CreatureEventAI: Event %d incremented Phase above %u. Phase mask cannot be used with phases past %u. CreatureEntry = %d", EventId, MAX_PHASE-1, MAX_PHASE-1, m_creature->GetEntry());
736 Phase = MAX_PHASE-1;
738 else
739 Phase = new_phase;
741 break;
743 case ACTION_T_EVADE:
744 EnterEvadeMode();
745 break;
746 case ACTION_T_FLEE:
747 //TODO: Replace with Flee movement generator
748 m_creature->CastSpell(m_creature, SPELL_RUN_AWAY, true);
749 break;
750 case ACTION_T_QUEST_EVENT_ALL:
751 if (pActionInvoker && pActionInvoker->GetTypeId() == TYPEID_PLAYER)
753 if (Unit* Temp = Unit::GetUnit(*m_creature,pActionInvoker->GetGUID()))
754 if (Temp->GetTypeId() == TYPEID_PLAYER)
755 ((Player*)Temp)->GroupEventHappens(action.quest_event_all.questId,m_creature);
757 break;
758 case ACTION_T_CAST_EVENT_ALL:
760 std::list<HostilReference*>& threatList = m_creature->getThreatManager().getThreatList();
761 for (std::list<HostilReference*>::iterator i = threatList.begin(); i != threatList.end(); ++i)
762 if (Unit* Temp = Unit::GetUnit(*m_creature,(*i)->getUnitGuid()))
763 if (Temp->GetTypeId() == TYPEID_PLAYER)
764 ((Player*)Temp)->CastedCreatureOrGO(action.cast_event_all.creatureId, m_creature->GetGUID(), action.cast_event_all.spellId);
765 break;
767 case ACTION_T_REMOVEAURASFROMSPELL:
768 if (Unit* target = GetTargetByType(action.remove_aura.target, pActionInvoker))
769 target->RemoveAurasDueToSpell(action.remove_aura.spellId);
770 break;
771 case ACTION_T_RANGED_MOVEMENT:
772 AttackDistance = action.ranged_movement.distance;
773 AttackAngle = ((float)action.ranged_movement.angle/180)*M_PI;
775 if (CombatMovementEnabled)
777 if (m_creature->GetMotionMaster()->GetCurrentMovementGeneratorType() == TARGETED_MOTION_TYPE)
779 //Drop current movement gen
780 m_creature->GetMotionMaster()->Clear(false);
781 m_creature->GetMotionMaster()->MoveChase(m_creature->getVictim(), AttackDistance, AttackAngle);
784 break;
785 case ACTION_T_RANDOM_PHASE:
786 Phase = GetRandActionParam(rnd, action.random_phase.phase1, action.random_phase.phase2, action.random_phase.phase3);
787 break;
788 case ACTION_T_RANDOM_PHASE_RANGE:
789 if (action.random_phase_range.phaseMax > action.random_phase_range.phaseMin)
790 Phase = action.random_phase_range.phaseMin + (rnd % (action.random_phase_range.phaseMax - action.random_phase_range.phaseMin));
791 else
792 sLog.outErrorDb( "CreatureEventAI: ACTION_T_RANDOM_PHASE_RANGE cannot have Param2 <= Param1. Divide by Zero. Event = %d. CreatureEntry = %d", EventId, m_creature->GetEntry());
793 break;
794 case ACTION_T_SUMMON_ID:
796 Unit* target = GetTargetByType(action.summon_id.target, pActionInvoker);
798 CreatureEventAI_Summon_Map::const_iterator i = CreatureEAI_Mgr.GetCreatureEventAISummonMap().find(action.summon_id.spawnId);
799 if (i == CreatureEAI_Mgr.GetCreatureEventAISummonMap().end())
801 sLog.outErrorDb( "CreatureEventAI: failed to spawn creature %u. Summon map index %u does not exist. EventID %d. CreatureID %d", action.summon_id.creatureId, action.summon_id.spawnId, EventId, m_creature->GetEntry());
802 return;
805 Creature* pCreature = NULL;
806 if ((*i).second.SpawnTimeSecs)
807 pCreature = m_creature->SummonCreature(action.summon_id.creatureId, (*i).second.position_x, (*i).second.position_y, (*i).second.position_z, (*i).second.orientation, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, (*i).second.SpawnTimeSecs);
808 else
809 pCreature = m_creature->SummonCreature(action.summon_id.creatureId, (*i).second.position_x, (*i).second.position_y, (*i).second.position_z, (*i).second.orientation, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 0);
811 if (!pCreature)
812 sLog.outErrorDb( "CreatureEventAI: failed to spawn creature %u. EventId %d.Creature %d", action.summon_id.creatureId, EventId, m_creature->GetEntry());
813 else if (action.summon_id.target != TARGET_T_SELF && target)
814 pCreature->AI()->AttackStart(target);
816 break;
818 case ACTION_T_KILLED_MONSTER:
819 //first attempt player who tapped creature
820 if (Player* pPlayer = m_creature->GetLootRecipient())
821 pPlayer->RewardPlayerAndGroupAtEvent(action.killed_monster.creatureId, m_creature);
822 else
824 //if not available, use pActionInvoker
825 if (Unit* pTarget = GetTargetByType(action.killed_monster.target, pActionInvoker))
826 if (Player* pPlayer2 = pTarget->GetCharmerOrOwnerPlayerOrPlayerItself())
827 pPlayer2->RewardPlayerAndGroupAtEvent(action.killed_monster.creatureId, m_creature);
829 break;
830 case ACTION_T_SET_INST_DATA:
832 InstanceData* pInst = (InstanceData*)m_creature->GetInstanceData();
833 if (!pInst)
835 sLog.outErrorDb("CreatureEventAI: Event %d attempt to set instance data without instance script. Creature %d", EventId, m_creature->GetEntry());
836 return;
839 pInst->SetData(action.set_inst_data.field, action.set_inst_data.value);
840 break;
842 case ACTION_T_SET_INST_DATA64:
844 Unit* target = GetTargetByType(action.set_inst_data64.target, pActionInvoker);
845 if (!target)
847 sLog.outErrorDb("CreatureEventAI: Event %d attempt to set instance data64 but Target == NULL. Creature %d", EventId, m_creature->GetEntry());
848 return;
851 InstanceData* pInst = (InstanceData*)m_creature->GetInstanceData();
852 if (!pInst)
854 sLog.outErrorDb("CreatureEventAI: Event %d attempt to set instance data64 without instance script. Creature %d", EventId, m_creature->GetEntry());
855 return;
858 pInst->SetData64(action.set_inst_data64.field, target->GetGUID());
859 break;
861 case ACTION_T_UPDATE_TEMPLATE:
863 if (m_creature->GetEntry() == action.update_template.creatureId)
866 sLog.outErrorDb("CreatureEventAI: Event %d ACTION_T_UPDATE_TEMPLATE call with param1 == current entry. Creature %d", EventId, m_creature->GetEntry());
867 return;
870 m_creature->UpdateEntry(action.update_template.creatureId, action.update_template.team ? HORDE : ALLIANCE);
872 break;
873 case ACTION_T_DIE:
875 if (m_creature->isDead())
878 sLog.outErrorDb("CreatureEventAI: Event %d ACTION_T_DIE on dead creature. Creature %d", EventId, m_creature->GetEntry());
879 return;
881 m_creature->DealDamage(m_creature, m_creature->GetMaxHealth(),NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
883 break;
884 case ACTION_T_ZONE_COMBAT_PULSE:
886 if (!m_creature->isInCombat() || !m_creature->GetMap()->IsDungeon())
889 sLog.outErrorDb("CreatureEventAI: Event %d ACTION_T_ZONE_COMBAT_PULSE on creature out of combat or in non-dungeon map. Creature %d", EventId, m_creature->GetEntry());
890 return;
893 DoZoneInCombat(m_creature);
895 break;
899 void CreatureEventAI::JustRespawned()
901 Reset();
903 if (bEmptyList)
904 return;
906 //Handle Spawned Events
907 for (std::list<CreatureEventAIHolder>::iterator i = CreatureEventAIList.begin(); i != CreatureEventAIList.end(); ++i)
909 if ((*i).Event.event_type == EVENT_T_SPAWNED)
910 ProcessEvent(*i);
914 void CreatureEventAI::Reset()
916 EventUpdateTime = EVENT_UPDATE_TIME;
917 EventDiff = 0;
919 if (bEmptyList)
920 return;
922 //Reset all events to enabled
923 for (std::list<CreatureEventAIHolder>::iterator i = CreatureEventAIList.begin(); i != CreatureEventAIList.end(); ++i)
925 switch ((*i).Event.event_type)
927 //Reset all out of combat timers
928 case EVENT_T_TIMER_OOC:
930 if ((*i).Event.event_param2 == (*i).Event.event_param1)
932 (*i).Time = (*i).Event.event_param1;
933 (*i).Enabled = true;
935 else if ((*i).Event.event_param2 > (*i).Event.event_param1)
937 (*i).Time = urand((*i).Event.event_param1, (*i).Event.event_param2);
938 (*i).Enabled = true;
940 else
941 sLog.outErrorDb("CreatureEventAI: Creature %u using Event %u (Type = %u) has InitialMax < InitialMin. Event disabled.", m_creature->GetEntry(), (*i).Event.event_id, (*i).Event.event_type);
943 break;
944 //default:
945 //TODO: enable below code line / verify this is correct to enable events previously disabled (ex. aggro yell), instead of enable this in void Aggro()
946 //(*i).Enabled = true;
947 //(*i).Time = 0;
948 //break;
953 void CreatureEventAI::JustReachedHome()
955 m_creature->LoadCreaturesAddon();
957 if (!bEmptyList)
959 for (std::list<CreatureEventAIHolder>::iterator i = CreatureEventAIList.begin(); i != CreatureEventAIList.end(); ++i)
961 if ((*i).Event.event_type == EVENT_T_REACHED_HOME)
962 ProcessEvent(*i);
966 Reset();
969 void CreatureEventAI::EnterEvadeMode()
971 m_creature->RemoveAllAuras();
972 m_creature->DeleteThreatList();
973 m_creature->CombatStop(true);
975 if (m_creature->isAlive())
976 m_creature->GetMotionMaster()->MoveTargetedHome();
978 m_creature->SetLootRecipient(NULL);
980 if (bEmptyList)
981 return;
983 //Handle Evade events
984 for (std::list<CreatureEventAIHolder>::iterator i = CreatureEventAIList.begin(); i != CreatureEventAIList.end(); ++i)
986 if ((*i).Event.event_type == EVENT_T_EVADE)
987 ProcessEvent(*i);
991 void CreatureEventAI::JustDied(Unit* killer)
993 Reset();
995 if (bEmptyList)
996 return;
998 //Handle Evade events
999 for (std::list<CreatureEventAIHolder>::iterator i = CreatureEventAIList.begin(); i != CreatureEventAIList.end(); ++i)
1001 if ((*i).Event.event_type == EVENT_T_DEATH)
1002 ProcessEvent(*i, killer);
1006 void CreatureEventAI::KilledUnit(Unit* victim)
1008 if (bEmptyList || victim->GetTypeId() != TYPEID_PLAYER)
1009 return;
1011 for (std::list<CreatureEventAIHolder>::iterator i = CreatureEventAIList.begin(); i != CreatureEventAIList.end(); ++i)
1013 if ((*i).Event.event_type == EVENT_T_KILL)
1014 ProcessEvent(*i, victim);
1018 void CreatureEventAI::JustSummoned(Creature* pUnit)
1020 if (bEmptyList || !pUnit)
1021 return;
1023 for (std::list<CreatureEventAIHolder>::iterator i = CreatureEventAIList.begin(); i != CreatureEventAIList.end(); ++i)
1025 if ((*i).Event.event_type == EVENT_T_SUMMONED_UNIT)
1026 ProcessEvent(*i, pUnit);
1030 void CreatureEventAI::EnterCombat(Unit *enemy)
1032 //Check for on combat start events
1033 if (!bEmptyList)
1035 for (std::list<CreatureEventAIHolder>::iterator i = CreatureEventAIList.begin(); i != CreatureEventAIList.end(); ++i)
1037 switch ((*i).Event.event_type)
1039 case EVENT_T_AGGRO:
1040 (*i).Enabled = true;
1041 ProcessEvent(*i, enemy);
1042 break;
1043 //Reset all in combat timers
1044 case EVENT_T_TIMER:
1045 if ((*i).Event.event_param2 == (*i).Event.event_param1)
1047 (*i).Time = (*i).Event.event_param1;
1048 (*i).Enabled = true;
1050 else if ((*i).Event.event_param2 > (*i).Event.event_param1)
1052 (*i).Time = urand((*i).Event.event_param1, (*i).Event.event_param2);
1053 (*i).Enabled = true;
1055 else
1056 sLog.outErrorDb("CreatureEventAI: Creature %u using Event %u (Type = %u) has InitialMax < InitialMin. Event disabled.", m_creature->GetEntry(), (*i).Event.event_id, (*i).Event.event_type);
1057 break;
1058 //All normal events need to be re-enabled and their time set to 0
1059 default:
1060 (*i).Enabled = true;
1061 (*i).Time = 0;
1062 break;
1067 EventUpdateTime = EVENT_UPDATE_TIME;
1068 EventDiff = 0;
1071 void CreatureEventAI::AttackStart(Unit *who)
1073 if (!who)
1074 return;
1076 if (m_creature->Attack(who, MeleeEnabled))
1078 m_creature->AddThreat(who, 0.0f);
1079 m_creature->SetInCombatWith(who);
1080 who->SetInCombatWith(m_creature);
1082 if (CombatMovementEnabled)
1084 m_creature->GetMotionMaster()->MoveChase(who, AttackDistance, AttackAngle);
1086 else
1088 m_creature->GetMotionMaster()->MoveIdle();
1089 m_creature->StopMoving();
1094 void CreatureEventAI::MoveInLineOfSight(Unit *who)
1096 if (!who)
1097 return;
1099 //Check for OOC LOS Event
1100 if (!bEmptyList && !m_creature->getVictim())
1102 for (std::list<CreatureEventAIHolder>::iterator itr = CreatureEventAIList.begin(); itr != CreatureEventAIList.end(); ++itr)
1104 if ((*itr).Event.event_type == EVENT_T_OOC_LOS)
1106 //can trigger if closer than fMaxAllowedRange
1107 float fMaxAllowedRange = (*itr).Event.event_param2;
1109 //if range is ok and we are actually in LOS
1110 if (m_creature->IsWithinDistInMap(who, fMaxAllowedRange) && m_creature->IsWithinLOSInMap(who))
1112 //if friendly event&&who is not hostile OR hostile event&&who is hostile
1113 if (((*itr).Event.event_param1 && !m_creature->IsHostileTo(who)) ||
1114 ((!(*itr).Event.event_param1) && m_creature->IsHostileTo(who)))
1115 ProcessEvent(*itr, who);
1121 if (m_creature->isCivilian() || m_creature->IsNeutralToAll())
1122 return;
1124 if (!m_creature->hasUnitState(UNIT_STAT_STUNNED) && who->isTargetableForAttack() &&
1125 m_creature->IsHostileTo(who) && who->isInAccessablePlaceFor(m_creature))
1127 if (!m_creature->canFly() && m_creature->GetDistanceZ(who) > CREATURE_Z_ATTACK_RANGE)
1128 return;
1130 float attackRadius = m_creature->GetAttackDistance(who);
1131 if (m_creature->IsWithinDistInMap(who, attackRadius) && m_creature->IsWithinLOSInMap(who))
1133 if (!m_creature->getVictim())
1135 AttackStart(who);
1136 who->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
1138 else if (m_creature->GetMap()->IsDungeon())
1140 m_creature->AddThreat(who, 0.0f);
1141 who->SetInCombatWith(m_creature);
1147 void CreatureEventAI::SpellHit(Unit* pUnit, const SpellEntry* pSpell)
1150 if (bEmptyList)
1151 return;
1153 for (std::list<CreatureEventAIHolder>::iterator i = CreatureEventAIList.begin(); i != CreatureEventAIList.end(); ++i)
1155 if ((*i).Event.event_type == EVENT_T_SPELLHIT)
1157 //If spell id matches (or no spell id) & if spell school matches (or no spell school)
1158 if (!(*i).Event.event_param1 || pSpell->Id == (*i).Event.event_param1)
1160 if ((*i).Event.event_param2_s == -1 || pSpell->SchoolMask == (*i).Event.event_param2)
1161 ProcessEvent(*i, pUnit);
1167 void CreatureEventAI::UpdateAI(const uint32 diff)
1169 //Check if we are in combat (also updates calls threat update code)
1170 bool Combat = m_creature->SelectHostilTarget() && m_creature->getVictim();
1172 //Must return if creature isn't alive. Normally select hostil target and get victim prevent this
1173 if (!m_creature->isAlive())
1174 return;
1176 if (!bEmptyList)
1178 //Events are only updated once every EVENT_UPDATE_TIME ms to prevent lag with large amount of events
1179 if (EventUpdateTime < diff)
1181 EventDiff += diff;
1183 //Check for time based events
1184 for (std::list<CreatureEventAIHolder>::iterator i = CreatureEventAIList.begin(); i != CreatureEventAIList.end(); ++i)
1186 //Decrement Timers
1187 if ((*i).Time)
1189 if ((*i).Time > EventDiff)
1191 //Do not decrement timers if event cannot trigger in this phase
1192 if (!((*i).Event.event_inverse_phase_mask & (1 << Phase)))
1193 (*i).Time -= EventDiff;
1195 //Skip processing of events that have time remaining
1196 continue;
1198 else (*i).Time = 0;
1201 //Events that are updated every EVENT_UPDATE_TIME
1202 switch ((*i).Event.event_type)
1204 case EVENT_T_TIMER_OOC:
1205 ProcessEvent(*i);
1206 break;
1207 case EVENT_T_TIMER:
1208 case EVENT_T_MANA:
1209 case EVENT_T_HP:
1210 case EVENT_T_TARGET_HP:
1211 case EVENT_T_TARGET_CASTING:
1212 case EVENT_T_FRIENDLY_HP:
1213 if (Combat)
1214 ProcessEvent(*i);
1215 break;
1216 case EVENT_T_RANGE:
1217 if (Combat)
1218 if (m_creature->IsInMap(m_creature->getVictim()))
1219 if (m_creature->IsInRange(m_creature->getVictim(),
1220 (float)(*i).Event.event_param1,(float)(*i).Event.event_param2))
1221 ProcessEvent(*i);
1222 break;
1226 EventDiff = 0;
1227 EventUpdateTime = EVENT_UPDATE_TIME;
1229 else
1231 EventDiff += diff;
1232 EventUpdateTime -= diff;
1236 //Melee Auto-Attack
1237 if (Combat && MeleeEnabled)
1238 DoMeleeAttackIfReady();
1241 bool CreatureEventAI::IsVisible(Unit *pl) const
1243 return m_creature->IsWithinDist(pl,sWorld.getConfig(CONFIG_SIGHT_MONSTER))
1244 && pl->isVisibleForOrDetect(m_creature,true);
1247 inline Unit* CreatureEventAI::SelectUnit(AttackingTarget target, uint32 position)
1249 //ThreatList m_threatlist;
1250 std::list<HostilReference*>& m_threatlist = m_creature->getThreatManager().getThreatList();
1251 std::list<HostilReference*>::iterator i = m_threatlist.begin();
1252 std::list<HostilReference*>::reverse_iterator r = m_threatlist.rbegin();
1254 if (position >= m_threatlist.size() || !m_threatlist.size())
1255 return NULL;
1257 switch (target)
1259 case ATTACKING_TARGET_RANDOM:
1261 advance ( i , position + (rand() % (m_threatlist.size() - position ) ));
1262 return Unit::GetUnit(*m_creature,(*i)->getUnitGuid());
1264 case ATTACKING_TARGET_TOPAGGRO:
1266 advance ( i , position);
1267 return Unit::GetUnit(*m_creature,(*i)->getUnitGuid());
1269 case ATTACKING_TARGET_BOTTOMAGGRO:
1271 advance ( r , position);
1272 return Unit::GetUnit(*m_creature,(*r)->getUnitGuid());
1275 return NULL;
1278 inline uint32 CreatureEventAI::GetRandActionParam(uint32 rnd, uint32 param1, uint32 param2, uint32 param3)
1280 switch (rnd % 3)
1282 case 0: return param1;
1283 case 1: return param2;
1284 case 2: return param3;
1286 return 0;
1289 inline int32 CreatureEventAI::GetRandActionParam(uint32 rnd, int32 param1, int32 param2, int32 param3)
1291 switch (rnd % 3)
1293 case 0: return param1;
1294 case 1: return param2;
1295 case 2: return param3;
1297 return 0;
1300 inline Unit* CreatureEventAI::GetTargetByType(uint32 Target, Unit* pActionInvoker)
1302 switch (Target)
1304 case TARGET_T_SELF:
1305 return m_creature;
1306 case TARGET_T_HOSTILE:
1307 return m_creature->getVictim();
1308 case TARGET_T_HOSTILE_SECOND_AGGRO:
1309 return SelectUnit(ATTACKING_TARGET_TOPAGGRO,1);
1310 case TARGET_T_HOSTILE_LAST_AGGRO:
1311 return SelectUnit(ATTACKING_TARGET_BOTTOMAGGRO,0);
1312 case TARGET_T_HOSTILE_RANDOM:
1313 return SelectUnit(ATTACKING_TARGET_RANDOM,0);
1314 case TARGET_T_HOSTILE_RANDOM_NOT_TOP:
1315 return SelectUnit(ATTACKING_TARGET_RANDOM,1);
1316 case TARGET_T_ACTION_INVOKER:
1317 return pActionInvoker;
1318 default:
1319 return NULL;
1323 Unit* CreatureEventAI::DoSelectLowestHpFriendly(float range, uint32 MinHPDiff)
1325 CellPair p(MaNGOS::ComputeCellPair(m_creature->GetPositionX(), m_creature->GetPositionY()));
1326 Cell cell(p);
1327 cell.data.Part.reserved = ALL_DISTRICT;
1328 cell.SetNoCreate();
1330 Unit* pUnit = NULL;
1332 MaNGOS::MostHPMissingInRange u_check(m_creature, range, MinHPDiff);
1333 MaNGOS::UnitLastSearcher<MaNGOS::MostHPMissingInRange> searcher(m_creature, pUnit, u_check);
1336 typedef TYPELIST_4(GameObject, Creature*except pets*, DynamicObject, Corpse*Bones*) AllGridObjectTypes;
1337 This means that if we only search grid then we cannot possibly return pets or players so this is safe
1339 TypeContainerVisitor<MaNGOS::UnitLastSearcher<MaNGOS::MostHPMissingInRange>, GridTypeMapContainer > grid_unit_searcher(searcher);
1341 CellLock<GridReadGuard> cell_lock(cell, p);
1342 cell_lock->Visit(cell_lock, grid_unit_searcher, *m_creature->GetMap());
1343 return pUnit;
1346 void CreatureEventAI::DoFindFriendlyCC(std::list<Creature*>& _list, float range)
1348 CellPair p(MaNGOS::ComputeCellPair(m_creature->GetPositionX(), m_creature->GetPositionY()));
1349 Cell cell(p);
1350 cell.data.Part.reserved = ALL_DISTRICT;
1351 cell.SetNoCreate();
1353 MaNGOS::FriendlyCCedInRange u_check(m_creature, range);
1354 MaNGOS::CreatureListSearcher<MaNGOS::FriendlyCCedInRange> searcher(m_creature, _list, u_check);
1356 TypeContainerVisitor<MaNGOS::CreatureListSearcher<MaNGOS::FriendlyCCedInRange>, GridTypeMapContainer > grid_creature_searcher(searcher);
1358 CellLock<GridReadGuard> cell_lock(cell, p);
1359 cell_lock->Visit(cell_lock, grid_creature_searcher, *m_creature->GetMap());
1362 void CreatureEventAI::DoFindFriendlyMissingBuff(std::list<Creature*>& _list, float range, uint32 spellid)
1364 CellPair p(MaNGOS::ComputeCellPair(m_creature->GetPositionX(), m_creature->GetPositionY()));
1365 Cell cell(p);
1366 cell.data.Part.reserved = ALL_DISTRICT;
1367 cell.SetNoCreate();
1369 MaNGOS::FriendlyMissingBuffInRange u_check(m_creature, range, spellid);
1370 MaNGOS::CreatureListSearcher<MaNGOS::FriendlyMissingBuffInRange> searcher(m_creature, _list, u_check);
1372 TypeContainerVisitor<MaNGOS::CreatureListSearcher<MaNGOS::FriendlyMissingBuffInRange>, GridTypeMapContainer > grid_creature_searcher(searcher);
1374 CellLock<GridReadGuard> cell_lock(cell, p);
1375 cell_lock->Visit(cell_lock, grid_creature_searcher, *m_creature->GetMap());
1378 //*********************************
1379 //*** Functions used globally ***
1381 void CreatureEventAI::DoScriptText(int32 textEntry, WorldObject* pSource, Unit* target)
1383 if (!pSource)
1385 sLog.outErrorDb("CreatureEventAI: DoScriptText entry %i, invalid Source pointer.",textEntry);
1386 return;
1389 if (textEntry >= 0)
1391 sLog.outErrorDb("CreatureEventAI: DoScriptText with source entry %u (TypeId=%u, guid=%u) attempts to process text entry %i, but text entry must be negative.",pSource->GetEntry(),pSource->GetTypeId(),pSource->GetGUIDLow(),textEntry);
1392 return;
1395 CreatureEventAI_TextMap::const_iterator i = CreatureEAI_Mgr.GetCreatureEventAITextMap().find(textEntry);
1397 if (i == CreatureEAI_Mgr.GetCreatureEventAITextMap().end())
1399 sLog.outErrorDb("CreatureEventAI: DoScriptText with source entry %u (TypeId=%u, guid=%u) could not find text entry %i.",pSource->GetEntry(),pSource->GetTypeId(),pSource->GetGUIDLow(),textEntry);
1400 return;
1403 sLog.outDebug("CreatureEventAI: DoScriptText: text entry=%i, Sound=%u, Type=%u, Language=%u, Emote=%u",textEntry,(*i).second.SoundId,(*i).second.Type,(*i).second.Language,(*i).second.Emote);
1405 if((*i).second.SoundId)
1407 if (GetSoundEntriesStore()->LookupEntry((*i).second.SoundId))
1408 pSource->PlayDirectSound((*i).second.SoundId);
1409 else
1410 sLog.outErrorDb("CreatureEventAI: DoScriptText entry %i tried to process invalid sound id %u.",textEntry,(*i).second.SoundId);
1413 if((*i).second.Emote)
1415 if (pSource->GetTypeId() == TYPEID_UNIT || pSource->GetTypeId() == TYPEID_PLAYER)
1417 ((Unit*)pSource)->HandleEmoteCommand((*i).second.Emote);
1419 else
1420 sLog.outErrorDb("CreatureEventAI: DoScriptText entry %i tried to process emote for invalid TypeId (%u).",textEntry,pSource->GetTypeId());
1423 switch((*i).second.Type)
1425 case CHAT_TYPE_SAY:
1426 pSource->MonsterSay(textEntry, (*i).second.Language, target ? target->GetGUID() : 0);
1427 break;
1428 case CHAT_TYPE_YELL:
1429 pSource->MonsterYell(textEntry, (*i).second.Language, target ? target->GetGUID() : 0);
1430 break;
1431 case CHAT_TYPE_TEXT_EMOTE:
1432 pSource->MonsterTextEmote(textEntry, target ? target->GetGUID() : 0);
1433 break;
1434 case CHAT_TYPE_BOSS_EMOTE:
1435 pSource->MonsterTextEmote(textEntry, target ? target->GetGUID() : 0, true);
1436 break;
1437 case CHAT_TYPE_WHISPER:
1439 if (target && target->GetTypeId() == TYPEID_PLAYER)
1440 pSource->MonsterWhisper(textEntry, target->GetGUID());
1441 else sLog.outErrorDb("CreatureEventAI: DoScriptText entry %i cannot whisper without target unit (TYPEID_PLAYER).", textEntry);
1442 }break;
1443 case CHAT_TYPE_BOSS_WHISPER:
1445 if (target && target->GetTypeId() == TYPEID_PLAYER)
1446 pSource->MonsterWhisper(textEntry, target->GetGUID(), true);
1447 else sLog.outErrorDb("CreatureEventAI: DoScriptText entry %i cannot whisper without target unit (TYPEID_PLAYER).", textEntry);
1448 }break;
1449 case CHAT_TYPE_ZONE_YELL:
1450 pSource->MonsterYellToZone(textEntry, (*i).second.Language, target ? target->GetGUID() : 0);
1451 break;
1455 void CreatureEventAI::DoZoneInCombat(Unit* pUnit)
1457 if (!pUnit)
1458 pUnit = m_creature;
1460 Map *map = pUnit->GetMap();
1462 if (!map->IsDungeon()) //use IsDungeon instead of Instanceable, in case battlegrounds will be instantiated
1464 sLog.outErrorDb("CreatureEventAI: DoZoneInCombat call for map that isn't an instance (pUnit entry = %d)", pUnit->GetTypeId() == TYPEID_UNIT ? ((Creature*)pUnit)->GetEntry() : 0);
1465 return;
1468 if (!pUnit->CanHaveThreatList() || pUnit->getThreatManager().isThreatListEmpty())
1470 sLog.outErrorDb("CreatureEventAI: DoZoneInCombat called for creature that either cannot have threat list or has empty threat list (pUnit entry = %d)", pUnit->GetTypeId() == TYPEID_UNIT ? ((Creature*)pUnit)->GetEntry() : 0);
1472 return;
1475 Map::PlayerList const &PlayerList = map->GetPlayers();
1476 for(Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i)
1477 if (Player* i_pl = i->getSource())
1478 if (!i_pl->isGameMaster())
1479 pUnit->AddThreat(i_pl, 0.0f);
1482 void CreatureEventAI::DoMeleeAttackIfReady()
1484 //Make sure our attack is ready before checking distance
1485 if (m_creature->isAttackReady())
1487 //If we are within range melee the target
1488 if (m_creature->IsWithinDistInMap(m_creature->getVictim(), ATTACK_DISTANCE))
1490 m_creature->AttackerStateUpdate(m_creature->getVictim());
1491 m_creature->resetAttackTimer();
1496 bool CreatureEventAI::CanCast(Unit* Target, SpellEntry const *Spell, bool Triggered)
1498 //No target so we can't cast
1499 if (!Target || !Spell)
1500 return false;
1502 //Silenced so we can't cast
1503 if (!Triggered && m_creature->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED))
1504 return false;
1506 //Check for power
1507 if (!Triggered && m_creature->GetPower((Powers)Spell->powerType) < Spell->manaCost)
1508 return false;
1510 SpellRangeEntry const *TempRange = NULL;
1512 TempRange = GetSpellRangeStore()->LookupEntry(Spell->rangeIndex);
1514 //Spell has invalid range store so we can't use it
1515 if (!TempRange)
1516 return false;
1518 //Unit is out of range of this spell
1519 if (!m_creature->IsInRange(Target,TempRange->minRange,TempRange->maxRange))
1520 return false;
1522 return true;
1525 void CreatureEventAI::ReceiveEmote(Player* pPlayer, uint32 text_emote)
1527 if (bEmptyList)
1528 return;
1530 for (std::list<CreatureEventAIHolder>::iterator itr = CreatureEventAIList.begin(); itr != CreatureEventAIList.end(); ++itr)
1532 if ((*itr).Event.event_type == EVENT_T_RECEIVE_EMOTE)
1534 if ((*itr).Event.event_param1 != text_emote)
1535 return;
1537 bool bProcess = false;
1539 switch((*itr).Event.event_param2)
1541 //enum ConditionType
1542 case CONDITION_NONE: // 0 0
1543 bProcess = true;
1544 break;
1545 case CONDITION_AURA: // spell_id effindex
1546 if (pPlayer->HasAura((*itr).Event.event_param3,(*itr).Event.event_param4))
1547 bProcess = true;
1548 break;
1549 case CONDITION_ITEM: // item_id count
1550 if (pPlayer->HasItemCount((*itr).Event.event_param3,(*itr).Event.event_param4))
1551 bProcess = true;
1552 break;
1553 case CONDITION_ITEM_EQUIPPED: // item_id count
1554 if (pPlayer->HasItemOrGemWithIdEquipped((*itr).Event.event_param3,(*itr).Event.event_param4))
1555 bProcess = true;
1556 break;
1557 case CONDITION_ZONEID: // zone_id 0
1558 if (pPlayer->GetZoneId() == (*itr).Event.event_param3)
1559 bProcess = true;
1560 break;
1561 case CONDITION_REPUTATION_RANK: // faction_id min_rank
1562 if (pPlayer->GetReputationRank((*itr).Event.event_param3) >= (*itr).Event.event_param4)
1563 bProcess = true;
1564 break;
1565 case CONDITION_TEAM: // player_team 0, (469 - Alliance 67 - Horde)
1566 if (pPlayer->GetTeam() == (*itr).Event.event_param3)
1567 bProcess = true;
1568 break;
1569 case CONDITION_SKILL: // skill_id min skill_value
1570 if (pPlayer->HasSkill((*itr).Event.event_param3) && pPlayer->GetSkillValue((*itr).Event.event_param3) >= (*itr).Event.event_param4)
1571 bProcess = true;
1572 break;
1573 case CONDITION_QUESTREWARDED: // quest_id 0
1574 if (pPlayer->GetQuestRewardStatus((*itr).Event.event_param3))
1575 bProcess = true;
1576 break;
1577 case CONDITION_QUESTTAKEN: // quest_id 0, for condition true while quest active.
1578 if (pPlayer->GetQuestStatus((*itr).Event.event_param3) == QUEST_STATUS_INCOMPLETE)
1579 bProcess = true;
1580 break;
1581 case CONDITION_ACTIVE_EVENT: // event_id 0
1582 if (IsHolidayActive(HolidayIds((*itr).Event.event_param3)))
1583 bProcess = true;
1584 break;
1587 if (bProcess)
1589 sLog.outDebug("CreatureEventAI: ReceiveEmote CreatureEventAI: Condition ok, processing");
1590 ProcessEvent(*itr, pPlayer);