NPC_AI.cpp 29 KB

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