NPC_AI.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892
  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(rule_manager.GetGlobalRule(R_Loot, AllowChestUnlockByDropTime)->GetInt8()
  501. && m_body->GetChestDropTime() > 0 && Timer::GetCurrentTime2() >= m_body->GetChestDropTime()+(rule_manager.GetGlobalRule(R_Loot, ChestUnlockedTimeDrop)->GetInt32()*1000))
  502. return true;
  503. if(rule_manager.GetGlobalRule(R_Loot, AllowChestUnlockByTrapTime)->GetInt8()
  504. && m_body->GetTrapOpenedTime() > 0 && Timer::GetCurrentTime2() >= m_body->GetChestDropTime()+(rule_manager.GetGlobalRule(R_Loot, ChestUnlockedTimeTrap)->GetInt32()*1000))
  505. return true;
  506. }
  507. // Check the encounter list to see if the given entity is in it, if so return true.
  508. MEncounter.readlock(__FUNCTION__, __LINE__);
  509. if (entity->IsPlayer())
  510. {
  511. Player* plyr = (Player*)entity;
  512. map<int32, int32>::iterator itr = m_encounter_playerlist.find(plyr->GetCharacterID());
  513. if (itr != m_encounter_playerlist.end())
  514. {
  515. MEncounter.releasereadlock(__FUNCTION__, __LINE__);
  516. return true;
  517. }
  518. MEncounter.releasereadlock(__FUNCTION__, __LINE__);
  519. return false;
  520. }
  521. for (itr = m_encounter.begin(); itr != m_encounter.end(); itr++) {
  522. if ((*itr) == entity->GetID()) {
  523. // found the entity in the encounter list, set return value to true and break the loop
  524. ret = true;
  525. break;
  526. }
  527. }
  528. MEncounter.releasereadlock(__FUNCTION__, __LINE__);
  529. return ret;
  530. }
  531. int8 Brain::GetEncounterSize() {
  532. int8 ret = 0;
  533. MEncounter.readlock(__FUNCTION__, __LINE__);
  534. ret = (int8)m_encounter.size();
  535. MEncounter.releasereadlock(__FUNCTION__, __LINE__);
  536. return ret;
  537. }
  538. vector<int32>* Brain::GetEncounter() {
  539. vector<int32>* ret = new vector<int32>;
  540. vector<int32>::iterator itr;
  541. // Lock the list
  542. MEncounter.readlock(__FUNCTION__, __LINE__);
  543. // Loop over the list storing the values into the new list
  544. for (itr = m_encounter.begin(); itr != m_encounter.end(); itr++)
  545. ret->push_back(*itr);
  546. // Unlock the list
  547. MEncounter.releasereadlock(__FUNCTION__, __LINE__);
  548. // Return the copy of the list
  549. return ret;
  550. }
  551. bool Brain::IsPlayerInEncounter(int32 char_id) {
  552. bool ret = false;
  553. MEncounter.readlock(__FUNCTION__, __LINE__);
  554. std::map<int32,int32>::iterator itr = m_encounter_playerlist.find(char_id);
  555. if(itr != m_encounter_playerlist.end()) {
  556. ret = true;
  557. }
  558. MEncounter.releasereadlock(__FUNCTION__, __LINE__);
  559. return ret;
  560. }
  561. bool Brain::IsEntityInEncounter(int32 id, bool skip_read_lock) {
  562. bool ret = false;
  563. if(!skip_read_lock) {
  564. MEncounter.readlock(__FUNCTION__, __LINE__);
  565. }
  566. vector<int32>::iterator itr;
  567. for (itr = m_encounter.begin(); itr != m_encounter.end(); itr++) {
  568. if ((*itr) == id) {
  569. // found the entity in the encounter list, set return value to true and break the loop
  570. ret = true;
  571. break;
  572. }
  573. }
  574. if(!skip_read_lock) {
  575. MEncounter.releasereadlock(__FUNCTION__, __LINE__);
  576. }
  577. return ret;
  578. }
  579. int32 Brain::CountPlayerBotInEncounter() {
  580. int32 count = 0;
  581. vector<int32>::iterator itr;
  582. MEncounter.readlock(__FUNCTION__, __LINE__);
  583. for (itr = m_encounter.begin(); itr != m_encounter.end(); itr++) {
  584. Entity* ent = (Entity*)GetBody()->GetZone()->GetSpawnByID((*itr));
  585. if (ent && (ent->IsPlayer() || ent->IsBot())) {
  586. count++;
  587. }
  588. }
  589. MEncounter.releasereadlock(__FUNCTION__, __LINE__);
  590. return count;
  591. }
  592. bool Brain::AddToEncounter(int32 id) {
  593. if(!IsEntityInEncounter(id, true)) {
  594. m_encounter.push_back(id);
  595. return true;
  596. }
  597. return false;
  598. }
  599. void Brain::ClearEncounter() {
  600. MEncounter.writelock(__FUNCTION__, __LINE__);
  601. if(m_body) {
  602. m_body->RemoveSpells(true);
  603. }
  604. m_encounter.clear();
  605. m_encounter_playerlist.clear();
  606. m_playerInEncounter = false;
  607. MEncounter.releasewritelock(__FUNCTION__, __LINE__);
  608. }
  609. void Brain::SendEncounterList(Client* client) {
  610. client->Message(CHANNEL_COLOR_YELLOW, "%s's EncounterList", m_body->GetName());
  611. client->Message(CHANNEL_COLOR_YELLOW, "-------------------");
  612. vector<int32>::iterator itr;
  613. // Check the encounter list to see if the given entity is in it, if so return true.
  614. MEncounter.readlock(__FUNCTION__, __LINE__);
  615. for (itr = m_encounter.begin(); itr != m_encounter.end(); itr++) {
  616. Entity* ent = (Entity*)GetBody()->GetZone()->GetSpawnByID((*itr));
  617. // Compare the hate value for the current iteration to our stored highest value
  618. if(ent) {
  619. client->Message(CHANNEL_COLOR_YELLOW, "%s", ent->GetName());
  620. }
  621. else {
  622. client->Message(CHANNEL_COLOR_YELLOW, "%u (cannot identity spawn id->entity)", (*itr));
  623. }
  624. }
  625. client->Message(CHANNEL_COLOR_YELLOW, "-------------------");
  626. MEncounter.releasereadlock(__FUNCTION__, __LINE__);
  627. }
  628. /* Example of how to extend the default AI */
  629. CombatPetBrain::CombatPetBrain(NPC* body) : Brain(body) {
  630. // Make sure to have the " : Brain(body)" so it calls the parent class constructor
  631. // to set up the AI properly
  632. }
  633. CombatPetBrain::~CombatPetBrain() {
  634. }
  635. void CombatPetBrain::Think() {
  636. // We are extending the base brain so make sure to call the parent Think() function.
  637. // If we want to override then we could remove Brain::Think()
  638. Brain::Think();
  639. // All this Brain does is make the pet follow its owner, the combat comes from the default brain
  640. if (GetBody()->EngagedInCombat() || !GetBody()->IsPet() || GetBody()->IsMezzedOrStunned())
  641. return;
  642. LogWrite(NPC_AI__DEBUG, 7, "NPC_AI", "Pet AI code called for %s", GetBody()->GetName());
  643. // If owner is a player and player has stay set then return out
  644. if (GetBody()->GetOwner() && GetBody()->GetOwner()->IsPlayer() && ((Player*)GetBody()->GetOwner())->GetInfoStruct()->get_pet_movement() == 1)
  645. return;
  646. // Set target to owner
  647. Entity* target = GetBody()->GetOwner();
  648. GetBody()->SetTarget(target);
  649. // Get distance from the owner
  650. float distance = GetBody()->GetDistance(target);
  651. // If out of melee range then move closer
  652. if (distance > rule_manager.GetGlobalRule(R_Combat, MaxCombatRange)->GetFloat())
  653. MoveCloser((Spawn*)target);
  654. }
  655. /* Example of how to override the default AI */
  656. NonCombatPetBrain::NonCombatPetBrain(NPC* body) : Brain(body) {
  657. // Make sure to have the " : Brain(body)" so it calls the parent class constructor
  658. // to set up the AI properly
  659. }
  660. NonCombatPetBrain::~NonCombatPetBrain() {
  661. }
  662. void NonCombatPetBrain::Think() {
  663. // All this Brain does is make the pet follow its owner
  664. if (!GetBody()->IsPet() || GetBody()->IsMezzedOrStunned())
  665. return;
  666. LogWrite(NPC_AI__DEBUG, 7, "NPC_AI", "Pet AI code called for %s", GetBody()->GetName());
  667. // Set target to owner
  668. Entity* target = GetBody()->GetOwner();
  669. GetBody()->SetTarget(target);
  670. // Get distance from the owner
  671. float distance = GetBody()->GetDistance(target);
  672. // If out of melee range then move closer
  673. if (distance > rule_manager.GetGlobalRule(R_Combat, MaxCombatRange)->GetFloat())
  674. MoveCloser((Spawn*)target);
  675. }
  676. BlankBrain::BlankBrain(NPC* body) : Brain(body) {
  677. // Make sure to have the " : Brain(body)" so it calls the parent class constructor
  678. // to set up the AI properly
  679. SetTick(50000);
  680. }
  681. BlankBrain::~BlankBrain() {
  682. }
  683. void BlankBrain::Think() {
  684. }
  685. LuaBrain::LuaBrain(NPC* body) : Brain(body) {
  686. }
  687. LuaBrain::~LuaBrain() {
  688. }
  689. void LuaBrain::Think() {
  690. if (!lua_interface)
  691. return;
  692. const char* script = GetBody()->GetSpawnScript();
  693. if(script) {
  694. if (!lua_interface->RunSpawnScript(script, "Think", GetBody(), GetBody()->GetTarget())) {
  695. lua_interface->LogError("LUA LuaBrain error: was unable to call the Think function in the spawn script (%s)", script);
  696. }
  697. }
  698. else {
  699. LogWrite(NPC_AI__ERROR, 0, "NPC_AI", "Lua brain set on a spawn that doesn't have a script...");
  700. }
  701. }
  702. DumbFirePetBrain::DumbFirePetBrain(NPC* body, Entity* target, int32 expire_time) : Brain(body) {
  703. m_expireTime = Timer::GetCurrentTime2() + expire_time;
  704. AddHate(target, INT_MAX);
  705. }
  706. DumbFirePetBrain::~DumbFirePetBrain() {
  707. }
  708. void DumbFirePetBrain::AddHate(Entity* entity, sint32 hate) {
  709. if (!GetMostHated())
  710. Brain::AddHate(entity, hate);
  711. }
  712. void DumbFirePetBrain::Think() {
  713. Entity* target = GetMostHated();
  714. if (target) {
  715. if (!GetBody()->IsMezzedOrStunned()) {
  716. // Set the NPC's target to the most hated entity if it is not already.
  717. if (GetBody()->GetTarget() != target) {
  718. GetBody()->SetTarget(target);
  719. GetBody()->FaceTarget(target, false);
  720. }
  721. // target needs to be identified before combat setting
  722. // If the NPC is not in combat then put them in combat
  723. if (!GetBody()->EngagedInCombat()) {
  724. //GetBody()->ClearRunningLocations();
  725. GetBody()->CalculateRunningLocation(true);
  726. GetBody()->InCombat(true);
  727. }
  728. float distance = GetBody()->GetDistance(target);
  729. if(GetBody()->CheckLoS(target) && !GetBody()->IsCasting() && (!HasRecovered() || !ProcessSpell(target, distance))) {
  730. LogWrite(NPC_AI__DEBUG, 7, "NPC_AI", "%s is attempting melee on %s.", GetBody()->GetName(), target->GetName());
  731. GetBody()->FaceTarget(target, false);
  732. ProcessMelee(target, distance);
  733. }
  734. }
  735. }
  736. else {
  737. // No hated target or time expired, kill this mob
  738. if (GetBody()->GetHP() > 0) {
  739. GetBody()->KillSpawn(GetBody());
  740. LogWrite(NPC_AI__DEBUG, 7, "NPC AI", "Dumbfire being killed because there is no target.");
  741. }
  742. }
  743. if (Timer::GetCurrentTime2() > m_expireTime) {
  744. if (GetBody()->GetHP() > 0) {
  745. GetBody()->KillSpawn(GetBody());
  746. LogWrite(NPC_AI__DEBUG, 7, "NPC AI", "Dumbfire being killed because timer expired.");
  747. }
  748. }
  749. }