NPC_AI.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885
  1. /*
  2. EQ2Emulator: Everquest II Server Emulator
  3. Copyright (C) 2007 EQ2EMulator Development Team (http://www.eq2emulator.net)
  4. This file is part of EQ2Emulator.
  5. EQ2Emulator is free software: you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation, either version 3 of the License, or
  8. (at your option) any later version.
  9. EQ2Emulator 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.
  13. You should have received a copy of the GNU General Public License
  14. along with EQ2Emulator. If not, see <http://www.gnu.org/licenses/>.
  15. */
  16. #include "NPC_AI.h"
  17. #include "Combat.h"
  18. #include "zoneserver.h"
  19. #include "Spells.h"
  20. #include "../common/Log.h"
  21. #include "LuaInterface.h"
  22. #include "World.h"
  23. #include "Rules/Rules.h"
  24. extern RuleManager rule_manager;
  25. extern LuaInterface* lua_interface;
  26. extern World world;
  27. /* The NEW AI code */
  28. Brain::Brain(NPC* npc) {
  29. // Set the npc this brain will controll
  30. m_body = npc;
  31. // Set the default time between calls to think to 250 miliseconds (1/4 a second)
  32. m_tick = 250;
  33. m_lastTick = Timer::GetCurrentTime2();
  34. m_spellRecovery = 0;
  35. m_playerInEncounter = false;
  36. // Set up the mutex for the hate list
  37. MHateList.SetName("Brain::m_hatelist");
  38. // Set up the mutex for the encounter list
  39. MEncounter.SetName("Brain::m_encounter");
  40. }
  41. Brain::~Brain() {
  42. }
  43. void Brain::Think() {
  44. if (m_body->IsPet() && m_body->GetOwner() && m_body->GetOwner()->IsPlayer()) {
  45. Player* player = (Player*)m_body->GetOwner();
  46. if(player->GetInfoStruct()->get_pet_id() == 0) {
  47. player->GetInfoStruct()->set_pet_id(player->GetIDWithPlayerSpawn(m_body));
  48. player->SetCharSheetChanged(true);
  49. }
  50. }
  51. // Get the entity this NPC hates the most,
  52. // GetMostHated() will handle dead spawns so no need to check the health in this function
  53. Entity* target = GetMostHated();
  54. // If mezzed, stunned or feared we can't do anything so skip
  55. if (!m_body->IsMezzedOrStunned()) {
  56. // Not mezzed or stunned
  57. // Get the distance to the runback location
  58. float run_back_distance = m_body->GetRunbackDistance();
  59. if (target) {
  60. LogWrite(NPC_AI__DEBUG, 7, "NPC_AI", "%s has %s targeted.", m_body->GetName(), target->GetName());
  61. // NPC has an entity that it hates
  62. // Set the NPC's target to the most hated entity if it is not already.
  63. if (m_body->GetTarget() != target) {
  64. m_body->SetTarget(target);
  65. }
  66. m_body->FaceTarget(target, false);
  67. // target needs to be set before in combat is engaged
  68. // If the NPC is not in combat then put them in combat
  69. if (!m_body->EngagedInCombat()) {
  70. m_body->ClearRunningLocations();
  71. m_body->InCombat(true);
  72. m_body->cast_on_aggro_completed = false;
  73. m_body->GetZone()->CallSpawnScript(m_body, SPAWN_SCRIPT_AGGRO, target);
  74. }
  75. bool breakWaterPursuit = false;
  76. if (m_body->IsWaterCreature() && !m_body->IsFlyingCreature() && !target->InWater())
  77. breakWaterPursuit = true;
  78. // Check to see if the NPC has exceeded the max chase distance
  79. if (run_back_distance > MAX_CHASE_DISTANCE || breakWaterPursuit) {
  80. LogWrite(NPC_AI__DEBUG, 7, "NPC_AI", "Run back distance is greater then max chase distance, run_back_distance = %f", run_back_distance);
  81. // Over the max chase distance, Check to see if the target is is a client
  82. Client* client = target->GetZone()->GetClientBySpawn(target);
  83. if (client)
  84. {
  85. // Target is a client so send encounter break messages
  86. if (m_body->HasSpawnGroup())
  87. client->SimpleMessage(CHANNEL_NARRATIVE, "This encounter will no longer give encounter rewards.");
  88. else
  89. client->Message(CHANNEL_NARRATIVE, "%s is no longer worth any experience or treasure.", m_body->GetName());
  90. }
  91. // Clear the hate list for this NPC
  92. ClearHate();
  93. // Clear the encounter list
  94. ClearEncounter();
  95. }
  96. else {
  97. // Still within max chase distance lets to the combat stuff now
  98. float distance = m_body->GetDistance(target);
  99. if(!m_body->IsCasting() && (!HasRecovered() || !ProcessSpell(target, distance))) {
  100. LogWrite(NPC_AI__DEBUG, 7, "NPC_AI", "%s is attempting melee on %s.", m_body->GetName(), target->GetName());
  101. m_body->FaceTarget(target, false);
  102. ProcessMelee(target, distance);
  103. }
  104. }
  105. }
  106. else {
  107. // Nothing in the hate list
  108. bool wasInCombat = m_body->EngagedInCombat();
  109. // Check to see if the NPC is still flagged as in combat for some reason
  110. if (m_body->EngagedInCombat()) {
  111. // If it is set the combat flag to false
  112. m_body->InCombat(false);
  113. // Do not set a players pet to full health once they stop combat
  114. if (!m_body->IsPet() || (m_body->IsPet() && m_body->GetOwner() && !m_body->GetOwner()->IsPlayer()))
  115. m_body->SetHP(m_body->GetTotalHP());
  116. }
  117. CheckBuffs();
  118. // If run back distance is greater then 0 then run back
  119. if(!m_body->EngagedInCombat() && !m_body->IsPauseMovementTimerActive())
  120. {
  121. if (run_back_distance > 1 || (m_body->m_call_runback && !m_body->following)) {
  122. m_body->SetLockedNoLoot(ENCOUNTER_STATE_BROKEN);
  123. m_body->UpdateEncounterState(ENCOUNTER_STATE_BROKEN);
  124. m_body->GetZone()->AddChangedSpawn(m_body);
  125. m_body->Runback(run_back_distance);
  126. m_body->m_call_runback = false;
  127. }
  128. else if (m_body->GetRunbackLocation())
  129. {
  130. switch(m_body->GetRunbackLocation()->stage)
  131. {
  132. case 0:
  133. m_body->GetZone()->movementMgr->StopNavigation((Entity*)m_body);
  134. m_body->ClearRunningLocations();
  135. m_body->SetX(m_body->GetRunbackLocation()->x,false);
  136. m_body->SetZ(m_body->GetRunbackLocation()->z,false);
  137. m_body->SetY(m_body->GetRunbackLocation()->y,false);
  138. m_body->CalculateRunningLocation(true);
  139. m_body->GetRunbackLocation()->stage = 1;
  140. m_body->GetZone()->AddChangedSpawn(m_body);
  141. break;
  142. case 6: // artificially 1500ms per 250ms Think() call
  143. if (m_body->GetRunbackLocation()->gridid > 0)
  144. m_body->SetLocation(m_body->GetRunbackLocation()->gridid);
  145. if(m_body->GetTempActionState() == 0)
  146. m_body->SetTempActionState(-1);
  147. m_body->SetHeading(m_body->m_runbackHeadingDir1,m_body->m_runbackHeadingDir2,false);
  148. if(m_body->GetRunbackLocation()->reset_hp_on_runback)
  149. m_body->SetHP(m_body->GetTotalHP());
  150. m_body->ClearRunback();
  151. if(m_body->GetLockedNoLoot() != ENCOUNTER_STATE_AVAILABLE && m_body->Alive()) {
  152. m_body->SetLockedNoLoot(ENCOUNTER_STATE_AVAILABLE);
  153. m_body->UpdateEncounterState(ENCOUNTER_STATE_AVAILABLE);
  154. }
  155. m_body->GetZone()->AddChangedSpawn(m_body);
  156. break;
  157. default: // captures case 1 up to case 5 to turn around / reset hp
  158. m_body->GetRunbackLocation()->stage++; // artificially delay
  159. break;
  160. }
  161. }
  162. }
  163. // If encounter size is greater then 0 then clear it
  164. if (GetEncounterSize() > 0)
  165. ClearEncounter();
  166. }
  167. }
  168. }
  169. sint32 Brain::GetHate(Entity* entity) {
  170. // We will use this variable to return the value, default to 0
  171. sint32 ret = 0;
  172. // Lock the hate list, not altering it so do a read lock
  173. MHateList.readlock(__FUNCTION__, __LINE__);
  174. // First check to see if the given entity is even in the hate list
  175. if (m_hatelist.count(entity->GetID()) > 0)
  176. // Entity in the hate list so get the hate value for the entity
  177. ret = m_hatelist[entity->GetID()];
  178. // Unlock the hate list
  179. MHateList.releasereadlock(__FUNCTION__, __LINE__);
  180. // return the hate
  181. return ret;
  182. }
  183. void Brain::AddHate(Entity* entity, sint32 hate) {
  184. // do not aggro when running back, despite taking damage
  185. if (m_body->IsNPC() && ((NPC*)m_body)->m_runningBack)
  186. return;
  187. else if (m_body->IsPet() && m_body->IsEntity() && ((Entity*)m_body)->GetOwner() == entity)
  188. return;
  189. if(m_body->IsImmune(IMMUNITY_TYPE_TAUNT))
  190. {
  191. LogWrite(NPC_AI__DEBUG, 7, "NPC_AI", "%s is immune to taunt from entity %s.", m_body->GetName(), entity ? entity->GetName() : "(null)");
  192. if(entity && entity->IsPlayer())
  193. ((Player*)entity)->GetClient()->GetCurrentZone()->SendDamagePacket((Spawn*)entity, (Spawn*)m_body, DAMAGE_PACKET_TYPE_RANGE_SPELL_DMG, DAMAGE_PACKET_RESULT_IMMUNE, 0, 0, "Hate");
  194. return;
  195. }
  196. // Lock the hate list, we are altering the list so use write lock
  197. MHateList.writelock(__FUNCTION__, __LINE__);
  198. if (m_hatelist.count(entity->GetID()) > 0)
  199. m_hatelist[entity->GetID()] += hate;
  200. else
  201. m_hatelist.insert(std::pair<int32, sint32>(entity->GetID(), hate));
  202. entity->MHatedBy.lock();
  203. if (entity->HatedBy.count(m_body->GetID()) == 0)
  204. entity->HatedBy.insert(m_body->GetID());
  205. entity->MHatedBy.unlock();
  206. // Unlock the list
  207. bool ownerExistsAddHate = false;
  208. if(entity->IsPet() && entity->GetOwner()) {
  209. map<int32, sint32>::iterator itr = m_hatelist.find(entity->GetOwner()->GetID());
  210. if(itr == m_hatelist.end()) {
  211. ownerExistsAddHate = true;
  212. }
  213. }
  214. MHateList.releasewritelock(__FUNCTION__, __LINE__);
  215. if(ownerExistsAddHate) {
  216. AddHate(entity->GetOwner(), 0);
  217. }
  218. }
  219. void Brain::ClearHate() {
  220. // Lock the hate list, we are altering the list so use a write lock
  221. MHateList.writelock(__FUNCTION__, __LINE__);
  222. map<int32, sint32>::iterator itr;
  223. for (itr = m_hatelist.begin(); itr != m_hatelist.end(); itr++) {
  224. Spawn* spawn = m_body->GetZone()->GetSpawnByID(itr->first);
  225. if (spawn && spawn->IsEntity())
  226. {
  227. ((Entity*)spawn)->MHatedBy.lock();
  228. ((Entity*)spawn)->HatedBy.erase(m_body->GetID());
  229. ((Entity*)spawn)->MHatedBy.unlock();
  230. }
  231. }
  232. // Clear the list
  233. m_hatelist.clear();
  234. // Unlock the hate list
  235. MHateList.releasewritelock(__FUNCTION__, __LINE__);
  236. }
  237. void Brain::ClearHate(Entity* entity) {
  238. // Lock the hate list, we could potentially modify the list so use write lock
  239. MHateList.writelock(__FUNCTION__, __LINE__);
  240. // Check to see if the given entity is in the hate list
  241. if (m_hatelist.count(entity->GetID()) > 0)
  242. // Erase the entity from the hate list
  243. m_hatelist.erase(entity->GetID());
  244. entity->MHatedBy.lock();
  245. entity->HatedBy.erase(m_body->GetID());
  246. entity->MHatedBy.unlock();
  247. // Unlock the hate list
  248. MHateList.releasewritelock(__FUNCTION__, __LINE__);
  249. }
  250. Entity* Brain::GetMostHated() {
  251. map<int32, sint32>::iterator itr;
  252. int32 ret = 0;
  253. sint32 hate = 0;
  254. // Lock the hate list, not going to alter it so use a read lock
  255. MHateList.readlock(__FUNCTION__, __LINE__);
  256. if (m_hatelist.size() > 0) {
  257. // Loop through the list looking for the entity that this NPC hates the most
  258. for(itr = m_hatelist.begin(); itr != m_hatelist.end(); itr++) {
  259. // Compare the hate value for the current iteration to our stored highest value
  260. if(itr->second > hate) {
  261. // New high value store the entity
  262. ret = itr->first;
  263. // Store the value to compare with the rest of the entities
  264. hate = itr->second;
  265. }
  266. }
  267. }
  268. // Unlock the list
  269. MHateList.releasereadlock(__FUNCTION__, __LINE__);
  270. Entity* hated = (Entity*)GetBody()->GetZone()->GetSpawnByID(ret);
  271. // Check the reult to see if it is still alive
  272. if(hated && hated->GetHP() <= 0) {
  273. // Entity we got was dead so remove it from the list
  274. ClearHate(hated);
  275. // Call this function again now that we removed the dead entity
  276. hated = GetMostHated();
  277. }
  278. // Return our result
  279. return hated;
  280. }
  281. sint8 Brain::GetHatePercentage(Entity* entity) {
  282. float percentage = 0.0;
  283. MHateList.readlock(__FUNCTION__, __LINE__);
  284. if (entity && m_hatelist.count(entity->GetID()) > 0 && m_hatelist[entity->GetID()] > 0) {
  285. sint32 total_hate = 0;
  286. map<int32, sint32>::iterator itr;
  287. for (itr = m_hatelist.begin(); itr != m_hatelist.end(); itr++)
  288. total_hate += itr->second;
  289. percentage = m_hatelist[entity->GetID()] / total_hate;
  290. }
  291. MHateList.releasereadlock(__FUNCTION__, __LINE__);
  292. return (sint8)(percentage * 100);
  293. }
  294. void Brain::SendHateList(Client* client) {
  295. MHateList.readlock(__FUNCTION__, __LINE__);
  296. client->Message(CHANNEL_COLOR_YELLOW, "%s's HateList", m_body->GetName());
  297. client->Message(CHANNEL_COLOR_YELLOW, "-------------------");
  298. map<int32, sint32>::iterator itr;
  299. if (m_hatelist.size() > 0) {
  300. // Loop through the list looking for the entity that this NPC hates the most
  301. for(itr = m_hatelist.begin(); itr != m_hatelist.end(); itr++) {
  302. Entity* ent = (Entity*)GetBody()->GetZone()->GetSpawnByID(itr->first);
  303. // Compare the hate value for the current iteration to our stored highest value
  304. if(ent) {
  305. client->Message(CHANNEL_COLOR_YELLOW, "%s : %i", ent->GetName(), itr->second);
  306. }
  307. else {
  308. client->Message(CHANNEL_COLOR_YELLOW, "%u (cannot identity spawn id->entity) : %i", itr->first, itr->second);
  309. }
  310. }
  311. }
  312. client->Message(CHANNEL_COLOR_YELLOW, "-------------------");
  313. MHateList.releasereadlock(__FUNCTION__, __LINE__);
  314. }
  315. vector<Entity*>* Brain::GetHateList() {
  316. vector<Entity*>* ret = new vector<Entity*>;
  317. map<int32, sint32>::iterator itr;
  318. // Lock the list
  319. MHateList.readlock(__FUNCTION__, __LINE__);
  320. // Loop over the list storing the values into the new list
  321. for (itr = m_hatelist.begin(); itr != m_hatelist.end(); itr++) {
  322. Entity* ent = (Entity*)GetBody()->GetZone()->GetSpawnByID(itr->first);
  323. if (ent)
  324. ret->push_back(ent);
  325. }
  326. // Unlock the list
  327. MHateList.releasereadlock(__FUNCTION__, __LINE__);
  328. // Return the copy of the list
  329. return ret;
  330. }
  331. void Brain::MoveCloser(Spawn* target) {
  332. if (target && m_body->GetFollowTarget() != target)
  333. m_body->SetFollowTarget(target, rule_manager.GetGlobalRule(R_Combat, MaxCombatRange)->GetFloat());
  334. if (m_body->GetFollowTarget() && !m_body->following) {
  335. m_body->CalculateRunningLocation(true);
  336. //m_body->ClearRunningLocations();
  337. m_body->following = true;
  338. }
  339. }
  340. bool Brain::ProcessSpell(Entity* target, float distance) {
  341. if(rand()%100 > m_body->GetCastPercentage() || m_body->IsStifled() || m_body->IsFeared())
  342. return false;
  343. Spell* spell = m_body->GetNextSpell(target, distance);
  344. if(spell){
  345. Spawn* spell_target = 0;
  346. if(spell->GetSpellData()->friendly_spell == 1){
  347. vector<Spawn*>* group = m_body->GetSpawnGroup();
  348. if(group && group->size() > 0){
  349. vector<Spawn*>::iterator itr;
  350. for(itr = group->begin(); itr != group->end(); itr++){
  351. if((!spell_target && (*itr)->GetHP() > 0 && (*itr)->GetHP() < (*itr)->GetTotalHP()) || (spell_target && (*itr)->GetHP() > 0 && spell_target->GetHP() > (*itr)->GetHP()))
  352. spell_target = *itr;
  353. }
  354. }
  355. if(!spell_target)
  356. spell_target = m_body;
  357. safe_delete(group);
  358. }
  359. else
  360. spell_target = target;
  361. BrainCastSpell(spell, spell_target, false);
  362. return true;
  363. }
  364. return false;
  365. }
  366. bool Brain::BrainCastSpell(Spell* spell, Spawn* cast_on, bool calculate_run_loc) {
  367. if (spell) {
  368. if(calculate_run_loc) {
  369. m_body->CalculateRunningLocation(true);
  370. }
  371. m_body->GetZone()->ProcessSpell(spell, m_body, cast_on);
  372. m_spellRecovery = (int32)(Timer::GetCurrentTime2() + (spell->GetSpellData()->cast_time * 10) + (spell->GetSpellData()->recovery * 10) + 2000);
  373. return true;
  374. }
  375. return false;
  376. }
  377. bool Brain::CheckBuffs() {
  378. if (!m_body->GetZone()->GetSpellProcess() || m_body->EngagedInCombat() || m_body->IsCasting() || m_body->IsMezzedOrStunned() || !m_body->Alive() || m_body->IsStifled() || !HasRecovered())
  379. return false;
  380. Spell* spell = m_body->GetNextBuffSpell(m_body);
  381. bool casted_on = false;
  382. if(!(casted_on = BrainCastSpell(spell, m_body)) && m_body->IsNPC() && ((NPC*)m_body)->HasSpells()) {
  383. Spawn* target = nullptr;
  384. vector<Spawn*>* group = m_body->GetSpawnGroup();
  385. if(group && group->size() > 0){
  386. vector<Spawn*>::iterator itr;
  387. for(itr = group->begin(); itr != group->end(); itr++){
  388. Spawn* spawn = (*itr);
  389. if(spawn->IsEntity() && spawn != m_body) {
  390. if(target) {
  391. Spell* spell = m_body->GetNextBuffSpell(spawn);
  392. SpellEffects* se = ((Entity*)spawn)->GetSpellEffect(spell->GetSpellData()->id);
  393. if(!se && BrainCastSpell(spell, spawn)) {
  394. casted_on = true;
  395. break;
  396. }
  397. }
  398. }
  399. }
  400. }
  401. safe_delete(group);
  402. }
  403. return casted_on;
  404. }
  405. void Brain::ProcessMelee(Entity* target, float distance) {
  406. if(distance > rule_manager.GetGlobalRule(R_Combat, MaxCombatRange)->GetFloat())
  407. MoveCloser((Spawn*)target);
  408. else {
  409. if (target) {
  410. LogWrite(NPC_AI__DEBUG, 7, "NPC_AI", "%s is within melee range of %s.", m_body->GetName(), target->GetName());
  411. if (m_body->AttackAllowed(target)) {
  412. LogWrite(NPC_AI__DEBUG, 7, "NPC_AI", "%s is allowed to attack %s.", m_body->GetName(), target->GetName());
  413. if (m_body->PrimaryWeaponReady() && !m_body->IsDazed() && !m_body->IsFeared()) {
  414. LogWrite(NPC_AI__DEBUG, 7, "NPC_AI", "%s swings its primary weapon at %s.", m_body->GetName(), target->GetName());
  415. m_body->SetPrimaryLastAttackTime(Timer::GetCurrentTime2());
  416. m_body->MeleeAttack(target, distance, true);
  417. m_body->GetZone()->CallSpawnScript(m_body, SPAWN_SCRIPT_AUTO_ATTACK_TICK, target);
  418. }
  419. if (m_body->SecondaryWeaponReady() && !m_body->IsDazed()) {
  420. m_body->SetSecondaryLastAttackTime(Timer::GetCurrentTime2());
  421. m_body->MeleeAttack(target, distance, false);
  422. }
  423. }
  424. }
  425. }
  426. }
  427. bool Brain::HasRecovered() {
  428. if(m_spellRecovery > Timer::GetCurrentTime2())
  429. return false;
  430. m_spellRecovery = 0;
  431. return true;
  432. }
  433. void Brain::AddToEncounter(Entity* entity) {
  434. // If player pet then set the entity to the pets owner
  435. if (entity->IsPet() && entity->GetOwner() && !entity->IsBot()) {
  436. MEncounter.writelock(__FUNCTION__, __LINE__);
  437. bool success = AddToEncounter(entity->GetID());
  438. MEncounter.releasewritelock(__FUNCTION__, __LINE__);
  439. if(!success)
  440. return;
  441. entity = entity->GetOwner();
  442. }
  443. else if(entity->HasPet() && entity->GetPet()) {
  444. MEncounter.writelock(__FUNCTION__, __LINE__);
  445. bool success = AddToEncounter(entity->GetPet()->GetID());
  446. MEncounter.releasewritelock(__FUNCTION__, __LINE__);
  447. if(!success)
  448. return;
  449. }
  450. // If player or bot then get the group
  451. int32 group_id = 0;
  452. if (entity->IsPlayer() || entity->IsBot()) {
  453. m_playerInEncounter = true;
  454. if (entity->GetGroupMemberInfo())
  455. group_id = entity->GetGroupMemberInfo()->group_id;
  456. }
  457. // Insert the entity into the encounter list, if there is a group add all group members as well
  458. // TODO: add raid members
  459. MEncounter.writelock(__FUNCTION__, __LINE__);
  460. if (group_id > 0) {
  461. world.GetGroupManager()->GroupLock(__FUNCTION__, __LINE__);
  462. deque<GroupMemberInfo*>::iterator itr;
  463. PlayerGroup* group = world.GetGroupManager()->GetGroup(group_id);
  464. if (group)
  465. {
  466. group->MGroupMembers.readlock(__FUNCTION__, __LINE__);
  467. deque<GroupMemberInfo*>* members = group->GetMembers();
  468. for (itr = members->begin(); itr != members->end(); itr++) {
  469. if ((*itr)->member)
  470. {
  471. bool success = AddToEncounter((*itr)->member->GetID());
  472. if((*itr)->client && success) {
  473. m_encounter_playerlist.insert(make_pair((*itr)->client->GetPlayer()->GetCharacterID(), (*itr)->client->GetPlayer()->GetID()));
  474. }
  475. }
  476. }
  477. group->MGroupMembers.releasereadlock(__FUNCTION__, __LINE__);
  478. }
  479. world.GetGroupManager()->ReleaseGroupLock(__FUNCTION__, __LINE__);
  480. }
  481. else {
  482. bool success = AddToEncounter(entity->GetID());
  483. if (success && entity->IsPlayer())
  484. {
  485. Player* plyr = (Player*)entity;
  486. m_encounter_playerlist.insert(make_pair(plyr->GetCharacterID(), entity->GetID()));
  487. }
  488. }
  489. MEncounter.releasewritelock(__FUNCTION__, __LINE__);
  490. }
  491. bool Brain::CheckLootAllowed(Entity* entity) {
  492. bool ret = false;
  493. vector<int32>::iterator itr;
  494. if(m_body)
  495. {
  496. if(rule_manager.GetGlobalRule(R_Loot, AllowChestUnlockByDropTime)->GetInt8()
  497. && m_body->GetChestDropTime() > 0 && Timer::GetCurrentTime2() >= m_body->GetChestDropTime()+(rule_manager.GetGlobalRule(R_Loot, ChestUnlockedTimeDrop)->GetInt32()*1000))
  498. return true;
  499. if(rule_manager.GetGlobalRule(R_Loot, AllowChestUnlockByTrapTime)->GetInt8()
  500. && m_body->GetTrapOpenedTime() > 0 && Timer::GetCurrentTime2() >= m_body->GetChestDropTime()+(rule_manager.GetGlobalRule(R_Loot, ChestUnlockedTimeTrap)->GetInt32()*1000))
  501. return true;
  502. }
  503. // Check the encounter list to see if the given entity is in it, if so return true.
  504. MEncounter.readlock(__FUNCTION__, __LINE__);
  505. if (entity->IsPlayer())
  506. {
  507. Player* plyr = (Player*)entity;
  508. map<int32, int32>::iterator itr = m_encounter_playerlist.find(plyr->GetCharacterID());
  509. if (itr != m_encounter_playerlist.end())
  510. {
  511. MEncounter.releasereadlock(__FUNCTION__, __LINE__);
  512. return true;
  513. }
  514. MEncounter.releasereadlock(__FUNCTION__, __LINE__);
  515. return false;
  516. }
  517. for (itr = m_encounter.begin(); itr != m_encounter.end(); itr++) {
  518. if ((*itr) == entity->GetID()) {
  519. // found the entity in the encounter list, set return value to true and break the loop
  520. ret = true;
  521. break;
  522. }
  523. }
  524. MEncounter.releasereadlock(__FUNCTION__, __LINE__);
  525. return ret;
  526. }
  527. int8 Brain::GetEncounterSize() {
  528. int8 ret = 0;
  529. MEncounter.readlock(__FUNCTION__, __LINE__);
  530. ret = (int8)m_encounter.size();
  531. MEncounter.releasereadlock(__FUNCTION__, __LINE__);
  532. return ret;
  533. }
  534. vector<int32>* Brain::GetEncounter() {
  535. vector<int32>* ret = new vector<int32>;
  536. vector<int32>::iterator itr;
  537. // Lock the list
  538. MEncounter.readlock(__FUNCTION__, __LINE__);
  539. // Loop over the list storing the values into the new list
  540. for (itr = m_encounter.begin(); itr != m_encounter.end(); itr++)
  541. ret->push_back(*itr);
  542. // Unlock the list
  543. MEncounter.releasereadlock(__FUNCTION__, __LINE__);
  544. // Return the copy of the list
  545. return ret;
  546. }
  547. bool Brain::IsPlayerInEncounter(int32 char_id) {
  548. bool ret = false;
  549. MEncounter.readlock(__FUNCTION__, __LINE__);
  550. std::map<int32,int32>::iterator itr = m_encounter_playerlist.find(char_id);
  551. if(itr != m_encounter_playerlist.end()) {
  552. ret = true;
  553. }
  554. MEncounter.releasereadlock(__FUNCTION__, __LINE__);
  555. return ret;
  556. }
  557. bool Brain::IsEntityInEncounter(int32 id, bool skip_read_lock) {
  558. bool ret = false;
  559. if(!skip_read_lock) {
  560. MEncounter.readlock(__FUNCTION__, __LINE__);
  561. }
  562. vector<int32>::iterator itr;
  563. for (itr = m_encounter.begin(); itr != m_encounter.end(); itr++) {
  564. if ((*itr) == id) {
  565. // found the entity in the encounter list, set return value to true and break the loop
  566. ret = true;
  567. break;
  568. }
  569. }
  570. if(!skip_read_lock) {
  571. MEncounter.releasereadlock(__FUNCTION__, __LINE__);
  572. }
  573. return ret;
  574. }
  575. int32 Brain::CountPlayerBotInEncounter() {
  576. int32 count = 0;
  577. vector<int32>::iterator itr;
  578. MEncounter.readlock(__FUNCTION__, __LINE__);
  579. for (itr = m_encounter.begin(); itr != m_encounter.end(); itr++) {
  580. Entity* ent = (Entity*)GetBody()->GetZone()->GetSpawnByID((*itr));
  581. if (ent && (ent->IsPlayer() || ent->IsBot())) {
  582. count++;
  583. }
  584. }
  585. MEncounter.releasereadlock(__FUNCTION__, __LINE__);
  586. return count;
  587. }
  588. bool Brain::AddToEncounter(int32 id) {
  589. if(!IsEntityInEncounter(id, true)) {
  590. m_encounter.push_back(id);
  591. return true;
  592. }
  593. return false;
  594. }
  595. void Brain::ClearEncounter() {
  596. MEncounter.writelock(__FUNCTION__, __LINE__);
  597. m_encounter.clear();
  598. m_encounter_playerlist.clear();
  599. m_playerInEncounter = false;
  600. MEncounter.releasewritelock(__FUNCTION__, __LINE__);
  601. }
  602. void Brain::SendEncounterList(Client* client) {
  603. client->Message(CHANNEL_COLOR_YELLOW, "%s's EncounterList", m_body->GetName());
  604. client->Message(CHANNEL_COLOR_YELLOW, "-------------------");
  605. vector<int32>::iterator itr;
  606. // Check the encounter list to see if the given entity is in it, if so return true.
  607. MEncounter.readlock(__FUNCTION__, __LINE__);
  608. for (itr = m_encounter.begin(); itr != m_encounter.end(); itr++) {
  609. Entity* ent = (Entity*)GetBody()->GetZone()->GetSpawnByID((*itr));
  610. // Compare the hate value for the current iteration to our stored highest value
  611. if(ent) {
  612. client->Message(CHANNEL_COLOR_YELLOW, "%s", ent->GetName());
  613. }
  614. else {
  615. client->Message(CHANNEL_COLOR_YELLOW, "%u (cannot identity spawn id->entity)", (*itr));
  616. }
  617. }
  618. client->Message(CHANNEL_COLOR_YELLOW, "-------------------");
  619. MEncounter.releasereadlock(__FUNCTION__, __LINE__);
  620. }
  621. /* Example of how to extend the default AI */
  622. CombatPetBrain::CombatPetBrain(NPC* body) : Brain(body) {
  623. // Make sure to have the " : Brain(body)" so it calls the parent class constructor
  624. // to set up the AI properly
  625. }
  626. CombatPetBrain::~CombatPetBrain() {
  627. }
  628. void CombatPetBrain::Think() {
  629. // We are extending the base brain so make sure to call the parent Think() function.
  630. // If we want to override then we could remove Brain::Think()
  631. Brain::Think();
  632. // All this Brain does is make the pet follow its owner, the combat comes from the default brain
  633. if (GetBody()->EngagedInCombat() || !GetBody()->IsPet() || GetBody()->IsMezzedOrStunned())
  634. return;
  635. LogWrite(NPC_AI__DEBUG, 7, "NPC_AI", "Pet AI code called for %s", GetBody()->GetName());
  636. // If owner is a player and player has stay set then return out
  637. if (GetBody()->GetOwner() && GetBody()->GetOwner()->IsPlayer() && ((Player*)GetBody()->GetOwner())->GetInfoStruct()->get_pet_movement() == 1)
  638. return;
  639. // Set target to owner
  640. Entity* target = GetBody()->GetOwner();
  641. GetBody()->SetTarget(target);
  642. // Get distance from the owner
  643. float distance = GetBody()->GetDistance(target);
  644. // If out of melee range then move closer
  645. if (distance > rule_manager.GetGlobalRule(R_Combat, MaxCombatRange)->GetFloat())
  646. MoveCloser((Spawn*)target);
  647. }
  648. /* Example of how to override the default AI */
  649. NonCombatPetBrain::NonCombatPetBrain(NPC* body) : Brain(body) {
  650. // Make sure to have the " : Brain(body)" so it calls the parent class constructor
  651. // to set up the AI properly
  652. }
  653. NonCombatPetBrain::~NonCombatPetBrain() {
  654. }
  655. void NonCombatPetBrain::Think() {
  656. // All this Brain does is make the pet follow its owner
  657. if (!GetBody()->IsPet() || GetBody()->IsMezzedOrStunned())
  658. return;
  659. LogWrite(NPC_AI__DEBUG, 7, "NPC_AI", "Pet AI code called for %s", GetBody()->GetName());
  660. // Set target to owner
  661. Entity* target = GetBody()->GetOwner();
  662. GetBody()->SetTarget(target);
  663. // Get distance from the owner
  664. float distance = GetBody()->GetDistance(target);
  665. // If out of melee range then move closer
  666. if (distance > rule_manager.GetGlobalRule(R_Combat, MaxCombatRange)->GetFloat())
  667. MoveCloser((Spawn*)target);
  668. }
  669. BlankBrain::BlankBrain(NPC* body) : Brain(body) {
  670. // Make sure to have the " : Brain(body)" so it calls the parent class constructor
  671. // to set up the AI properly
  672. SetTick(50000);
  673. }
  674. BlankBrain::~BlankBrain() {
  675. }
  676. void BlankBrain::Think() {
  677. }
  678. LuaBrain::LuaBrain(NPC* body) : Brain(body) {
  679. }
  680. LuaBrain::~LuaBrain() {
  681. }
  682. void LuaBrain::Think() {
  683. if (!lua_interface)
  684. return;
  685. const char* script = GetBody()->GetSpawnScript();
  686. if(script) {
  687. if (!lua_interface->RunSpawnScript(script, "Think", GetBody(), GetBody()->GetTarget())) {
  688. lua_interface->LogError("LUA LuaBrain error: was unable to call the Think function in the spawn script (%s)", script);
  689. }
  690. }
  691. else {
  692. LogWrite(NPC_AI__ERROR, 0, "NPC_AI", "Lua brain set on a spawn that doesn't have a script...");
  693. }
  694. }
  695. DumbFirePetBrain::DumbFirePetBrain(NPC* body, Entity* target, int32 expire_time) : Brain(body) {
  696. m_expireTime = Timer::GetCurrentTime2() + expire_time;
  697. AddHate(target, INT_MAX);
  698. }
  699. DumbFirePetBrain::~DumbFirePetBrain() {
  700. }
  701. void DumbFirePetBrain::AddHate(Entity* entity, sint32 hate) {
  702. if (!GetMostHated())
  703. Brain::AddHate(entity, hate);
  704. }
  705. void DumbFirePetBrain::Think() {
  706. Entity* target = GetMostHated();
  707. if (target) {
  708. if (!GetBody()->IsMezzedOrStunned()) {
  709. // Set the NPC's target to the most hated entity if it is not already.
  710. if (GetBody()->GetTarget() != target) {
  711. GetBody()->SetTarget(target);
  712. GetBody()->FaceTarget(target, false);
  713. }
  714. // target needs to be identified before combat setting
  715. // If the NPC is not in combat then put them in combat
  716. if (!GetBody()->EngagedInCombat()) {
  717. //GetBody()->ClearRunningLocations();
  718. GetBody()->CalculateRunningLocation(true);
  719. GetBody()->InCombat(true);
  720. }
  721. float distance = GetBody()->GetDistance(target);
  722. if(GetBody()->CheckLoS(target) && !GetBody()->IsCasting() && (!HasRecovered() || !ProcessSpell(target, distance))) {
  723. LogWrite(NPC_AI__DEBUG, 7, "NPC_AI", "%s is attempting melee on %s.", GetBody()->GetName(), target->GetName());
  724. GetBody()->FaceTarget(target, false);
  725. ProcessMelee(target, distance);
  726. }
  727. }
  728. }
  729. else {
  730. // No hated target or time expired, kill this mob
  731. if (GetBody()->GetHP() > 0) {
  732. GetBody()->KillSpawn(GetBody());
  733. LogWrite(NPC_AI__DEBUG, 7, "NPC AI", "Dumbfire being killed because there is no target.");
  734. }
  735. }
  736. if (Timer::GetCurrentTime2() > m_expireTime) {
  737. if (GetBody()->GetHP() > 0) {
  738. GetBody()->KillSpawn(GetBody());
  739. LogWrite(NPC_AI__DEBUG, 7, "NPC AI", "Dumbfire being killed because timer expired.");
  740. }
  741. }
  742. }