[6982] Implemented gmlevel-based command security
[getmangos.git] / src / game / ThreatManager.cpp
blob0691154933d0dacdaba752b2cf80833ab00295c6
1 /*
2 * Copyright (C) 2005-2008 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 "ThreatManager.h"
20 #include "Unit.h"
21 #include "Creature.h"
22 #include "CreatureAI.h"
23 #include "Map.h"
24 #include "MapManager.h"
25 #include "Player.h"
26 #include "ObjectAccessor.h"
27 #include "UnitEvents.h"
29 //==============================================================
30 //================= ThreatCalcHelper ===========================
31 //==============================================================
33 // The pHatingUnit is not used yet
34 float ThreatCalcHelper::calcThreat(Unit* pHatedUnit, Unit* pHatingUnit, float pThreat, SpellSchoolMask schoolMask, SpellEntry const *pThreatSpell)
36 if(pThreatSpell)
38 if( Player* modOwner = pHatingUnit->GetSpellModOwner() )
39 modOwner->ApplySpellMod(pThreatSpell->Id, SPELLMOD_THREAT, pThreat);
42 float threat = pHatedUnit->ApplyTotalThreatModifier(pThreat, schoolMask);
43 return threat;
46 //============================================================
47 //================= HostilReference ==========================
48 //============================================================
50 HostilReference::HostilReference(Unit* pUnit, ThreatManager *pThreatManager, float pThreat)
52 iThreat = pThreat;
53 iTempThreatModifyer = 0.0f;
54 link(pUnit, pThreatManager);
55 iUnitGuid = pUnit->GetGUID();
56 iOnline = true;
57 iAccessible = true;
60 //============================================================
61 // Tell our refTo (target) object that we have a link
62 void HostilReference::targetObjectBuildLink()
64 getTarget()->addHatedBy(this);
67 //============================================================
68 // Tell our refTo (taget) object, that the link is cut
69 void HostilReference::targetObjectDestroyLink()
71 getTarget()->removeHatedBy(this);
74 //============================================================
75 // Tell our refFrom (source) object, that the link is cut (Target destroyed)
77 void HostilReference::sourceObjectDestroyLink()
79 setOnlineOfflineState(false);
82 //============================================================
83 // Inform the source, that the status of the reference changed
85 void HostilReference::fireStatusChanged(const ThreatRefStatusChangeEvent& pThreatRefStatusChangeEvent)
87 if(getSource())
88 getSource()->processThreatEvent(&pThreatRefStatusChangeEvent);
91 //============================================================
93 void HostilReference::addThreat(float pMod)
95 iThreat += pMod;
96 // the threat is changed. Source and target unit have to be availabe
97 // if the link was cut before relink it again
98 if(!isOnline())
99 updateOnlineStatus();
100 if(pMod != 0.0f)
101 fireStatusChanged(ThreatRefStatusChangeEvent(UEV_THREAT_REF_THREAT_CHANGE, this, pMod));
102 if(isValid() && pMod >= 0)
104 Unit* victim_owner = getTarget()->GetOwner();
105 if(victim_owner && victim_owner->isAlive())
106 getSource()->addThreat(victim_owner, 0.0f); // create a threat to the owner of a pet, if the pet attacks
110 //============================================================
111 // check, if source can reach target and set the status
113 void HostilReference::updateOnlineStatus()
115 bool online = false;
116 bool accessible = false;
118 if(!isValid())
120 Unit* target = ObjectAccessor::GetUnit(*getSourceUnit(), getUnitGuid());
121 if(target)
122 link(target, getSource());
124 // only check for online status if
125 // ref is valid
126 // target is no player or not gamemaster
127 // target is not in flight
128 if(isValid() &&
129 ((getTarget()->GetTypeId() != TYPEID_PLAYER || !((Player*)getTarget())->isGameMaster()) ||
130 !getTarget()->hasUnitState(UNIT_STAT_IN_FLIGHT)))
132 Creature* creature = (Creature* ) getSourceUnit();
133 online = getTarget()->isInAccessablePlaceFor(creature);
134 if(!online)
136 if(creature->AI()->canReachByRangeAttack(getTarget()))
137 online = true; // not accessable but stays online
139 else
140 accessible = true;
143 setAccessibleState(accessible);
144 setOnlineOfflineState(online);
147 //============================================================
148 // set the status and fire the event on status change
150 void HostilReference::setOnlineOfflineState(bool pIsOnline)
152 if(iOnline != pIsOnline)
154 iOnline = pIsOnline;
155 if(!iOnline)
156 setAccessibleState(false); // if not online that not accessable as well
157 fireStatusChanged(ThreatRefStatusChangeEvent(UEV_THREAT_REF_ONLINE_STATUS, this));
161 //============================================================
163 void HostilReference::setAccessibleState(bool pIsAccessible)
165 if(iAccessible != pIsAccessible)
167 iAccessible = pIsAccessible;
168 fireStatusChanged(ThreatRefStatusChangeEvent(UEV_THREAT_REF_ASSECCIBLE_STATUS, this));
172 //============================================================
173 // prepare the reference for deleting
174 // this is called be the target
176 void HostilReference::removeReference()
178 invalidate();
179 fireStatusChanged(ThreatRefStatusChangeEvent(UEV_THREAT_REF_REMOVE_FROM_LIST, this));
182 //============================================================
184 Unit* HostilReference::getSourceUnit()
186 return (getSource()->getOwner());
189 //============================================================
190 //================ ThreatContainer ===========================
191 //============================================================
193 void ThreatContainer::clearReferences()
195 for(std::list<HostilReference*>::iterator i = iThreatList.begin(); i != iThreatList.end(); ++i)
197 (*i)->unlink();
198 delete (*i);
200 iThreatList.clear();
203 //============================================================
204 // Return the HostilReference of NULL, if not found
205 HostilReference* ThreatContainer::getReferenceByTarget(Unit* pVictim)
207 HostilReference* result = NULL;
208 uint64 guid = pVictim->GetGUID();
209 for(std::list<HostilReference*>::iterator i = iThreatList.begin(); i != iThreatList.end(); ++i)
211 if((*i)->getUnitGuid() == guid)
213 result = (*i);
214 break;
218 return result;
221 //============================================================
222 // Add the threat, if we find the reference
224 HostilReference* ThreatContainer::addThreat(Unit* pVictim, float pThreat)
226 HostilReference* ref = getReferenceByTarget(pVictim);
227 if(ref)
228 ref->addThreat(pThreat);
229 return ref;
232 //============================================================
234 void ThreatContainer::modifyThreatPercent(Unit *pVictim, int32 pPercent)
236 if(HostilReference* ref = getReferenceByTarget(pVictim))
237 ref->addThreatPercent(pPercent);
240 //============================================================
242 bool HostilReferenceSortPredicate(const HostilReference* lhs, const HostilReference* rhs)
244 // std::list::sort ordering predicate must be: (Pred(x,y)&&Pred(y,x))==false
245 return lhs->getThreat() > rhs->getThreat(); // reverse sorting
248 //============================================================
249 // Check if the list is dirty and sort if necessary
251 void ThreatContainer::update()
253 if(iDirty && iThreatList.size() >1)
255 iThreatList.sort(HostilReferenceSortPredicate);
257 iDirty = false;
260 //============================================================
261 // return the next best victim
262 // could be the current victim
264 HostilReference* ThreatContainer::selectNextVictim(Creature* pAttacker, HostilReference* pCurrentVictim)
266 HostilReference* currentRef = NULL;
267 bool found = false;
269 std::list<HostilReference*>::iterator lastRef = iThreatList.end();
270 lastRef--;
272 for(std::list<HostilReference*>::iterator iter = iThreatList.begin(); iter != iThreatList.end() && !found; ++iter)
274 currentRef = (*iter);
276 Unit* target = currentRef->getTarget();
277 assert(target); // if the ref has status online the target must be there !
279 // some units are prefered in comparison to others
280 if(iter != lastRef && (target->IsImmunedToDamage(pAttacker->GetMeleeDamageSchoolMask(), false) ||
281 target->hasUnitState(UNIT_STAT_CONFUSED | UNIT_STAT_FLEEING)
284 // current victim is a second choice target, so don't compare threat with it below
285 if(currentRef == pCurrentVictim)
286 pCurrentVictim = NULL;
287 continue;
290 if(!pAttacker->IsOutOfThreatArea(target)) // skip non attackable currently targets
292 if(pCurrentVictim) // select 1.3/1.1 better target in comparison current target
294 // list sorted and and we check current target, then this is best case
295 if(pCurrentVictim == currentRef || currentRef->getThreat() <= 1.1f * pCurrentVictim->getThreat() )
297 currentRef = pCurrentVictim; // for second case
298 found = true;
299 break;
302 if( currentRef->getThreat() > 1.3f * pCurrentVictim->getThreat() ||
303 currentRef->getThreat() > 1.1f * pCurrentVictim->getThreat() && pAttacker->IsWithinDistInMap(target, ATTACK_DISTANCE) )
304 { //implement 110% threat rule for targets in melee range
305 found = true; //and 130% rule for targets in ranged distances
306 break; //for selecting alive targets
309 else // select any
311 found = true;
312 break;
316 if(!found)
317 currentRef = NULL;
319 return currentRef;
322 //============================================================
323 //=================== ThreatManager ==========================
324 //============================================================
326 ThreatManager::ThreatManager(Unit* owner) : iCurrentVictim(NULL), iOwner(owner)
330 //============================================================
332 void ThreatManager::clearReferences()
334 iThreatContainer.clearReferences();
335 iThreatOfflineContainer.clearReferences();
336 iCurrentVictim = NULL;
339 //============================================================
341 void ThreatManager::addThreat(Unit* pVictim, float pThreat, SpellSchoolMask schoolMask, SpellEntry const *pThreatSpell)
343 //function deals with adding threat and adding players and pets into ThreatList
344 //mobs, NPCs, guards have ThreatList and HateOfflineList
345 //players and pets have only InHateListOf
346 //HateOfflineList is used co contain unattackable victims (in-flight, in-water, GM etc.)
348 if (pVictim == getOwner()) // only for same creatures :)
349 return;
351 if(!pVictim || (pVictim->GetTypeId() == TYPEID_PLAYER && ((Player*)pVictim)->isGameMaster()) )
352 return;
354 assert(getOwner()->GetTypeId()== TYPEID_UNIT);
356 float threat = ThreatCalcHelper::calcThreat(pVictim, iOwner, pThreat, schoolMask, pThreatSpell);
358 HostilReference* ref = iThreatContainer.addThreat(pVictim, threat);
359 // Ref is not in the online refs, search the offline refs next
360 if(!ref)
361 ref = iThreatOfflineContainer.addThreat(pVictim, threat);
363 if(!ref) // there was no ref => create a new one
365 // threat has to be 0 here
366 HostilReference* hostilReference = new HostilReference(pVictim, this, 0);
367 iThreatContainer.addReference(hostilReference);
368 hostilReference->addThreat(threat); // now we add the real threat
369 if(pVictim->GetTypeId() == TYPEID_PLAYER && ((Player*)pVictim)->isGameMaster())
370 hostilReference->setOnlineOfflineState(false); // GM is always offline
374 //============================================================
376 void ThreatManager::modifyThreatPercent(Unit *pVictim, int32 pPercent)
378 iThreatContainer.modifyThreatPercent(pVictim, pPercent);
381 //============================================================
383 Unit* ThreatManager::getHostilTarget()
385 iThreatContainer.update();
386 HostilReference* nextVictim = iThreatContainer.selectNextVictim((Creature*) getOwner(), getCurrentVictim());
387 setCurrentVictim(nextVictim);
388 return getCurrentVictim() != NULL ? getCurrentVictim()->getTarget() : NULL;
391 //============================================================
393 float ThreatManager::getThreat(Unit *pVictim, bool pAlsoSearchOfflineList)
395 float threat = 0.0f;
396 HostilReference* ref = iThreatContainer.getReferenceByTarget(pVictim);
397 if(!ref && pAlsoSearchOfflineList)
398 ref = iThreatOfflineContainer.getReferenceByTarget(pVictim);
399 if(ref)
400 threat = ref->getThreat();
401 return threat;
404 //============================================================
406 void ThreatManager::tauntApply(Unit* pTaunter)
408 HostilReference* ref = iThreatContainer.getReferenceByTarget(pTaunter);
409 if(getCurrentVictim() && ref && (ref->getThreat() < getCurrentVictim()->getThreat()))
411 if(ref->getTempThreatModifyer() == 0.0f)
412 // Ok, temp threat is unused
413 ref->setTempThreat(getCurrentVictim()->getThreat());
417 //============================================================
419 void ThreatManager::tauntFadeOut(Unit *pTaunter)
421 HostilReference* ref = iThreatContainer.getReferenceByTarget(pTaunter);
422 if(ref)
423 ref->resetTempThreat();
426 //============================================================
428 void ThreatManager::setCurrentVictim(HostilReference* pHostilReference)
430 iCurrentVictim = pHostilReference;
433 //============================================================
434 // The hated unit is gone, dead or deleted
435 // return true, if the event is consumed
437 bool ThreatManager::processThreatEvent(const UnitBaseEvent* pUnitBaseEvent)
439 bool consumed = false;
441 ThreatRefStatusChangeEvent* threatRefStatusChangeEvent;
442 HostilReference* hostilReference;
444 threatRefStatusChangeEvent = (ThreatRefStatusChangeEvent*) pUnitBaseEvent;
445 threatRefStatusChangeEvent->setThreatManager(this); // now we can set the threat manager
446 hostilReference = threatRefStatusChangeEvent->getReference();
448 switch(pUnitBaseEvent->getType())
450 case UEV_THREAT_REF_THREAT_CHANGE:
451 if((getCurrentVictim() == hostilReference && threatRefStatusChangeEvent->getFValue()<0.0f) ||
452 (getCurrentVictim() != hostilReference && threatRefStatusChangeEvent->getFValue()>0.0f))
453 setDirty(true); // the order in the threat list might have changed
454 break;
455 case UEV_THREAT_REF_ONLINE_STATUS:
456 if(!hostilReference->isOnline())
458 if (hostilReference == getCurrentVictim())
460 setCurrentVictim(NULL);
461 setDirty(true);
463 iThreatContainer.remove(hostilReference);
464 iThreatOfflineContainer.addReference(hostilReference);
466 else
468 if(getCurrentVictim() && hostilReference->getThreat() > (1.1f * getCurrentVictim()->getThreat()))
469 setDirty(true);
470 iThreatContainer.addReference(hostilReference);
471 iThreatOfflineContainer.remove(hostilReference);
473 break;
474 case UEV_THREAT_REF_REMOVE_FROM_LIST:
475 if (hostilReference == getCurrentVictim())
477 setCurrentVictim(NULL);
478 setDirty(true);
480 if(hostilReference->isOnline())
481 iThreatContainer.remove(hostilReference);
482 else
483 iThreatOfflineContainer.remove(hostilReference);
484 break;
486 return consumed;