No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

localplayer.cpp 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  1. /*
  2. * Copyright (c) 2010-2014 OTClient <https://github.com/edubart/otclient>
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. * THE SOFTWARE.
  21. */
  22. #include "localplayer.h"
  23. #include "map.h"
  24. #include "game.h"
  25. #include "tile.h"
  26. #include <framework/core/eventdispatcher.h>
  27. #include <framework/graphics/graphics.h>
  28. LocalPlayer::LocalPlayer()
  29. {
  30. m_states = 0;
  31. m_vocation = 0;
  32. m_blessings = Otc::BlessingNone;
  33. m_walkLockExpiration = 0;
  34. m_skillsLevel.fill(-1);
  35. m_skillsBaseLevel.fill(-1);
  36. m_skillsLevelPercent.fill(-1);
  37. m_health = -1;
  38. m_maxHealth = -1;
  39. m_freeCapacity = -1;
  40. m_experience = -1;
  41. m_level = -1;
  42. m_levelPercent = -1;
  43. m_mana = -1;
  44. m_maxMana = -1;
  45. m_magicLevel = -1;
  46. m_magicLevelPercent = -1;
  47. m_baseMagicLevel = -1;
  48. m_soul = -1;
  49. m_stamina = -1;
  50. m_baseSpeed = -1;
  51. m_regenerationTime = -1;
  52. m_offlineTrainingTime = -1;
  53. m_totalCapacity = -1;
  54. }
  55. void LocalPlayer::lockWalk(int millis)
  56. {
  57. m_walkLockExpiration = std::max<int>(m_walkLockExpiration, (ticks_t) g_clock.millis() + millis);
  58. }
  59. bool LocalPlayer::canWalk(Otc::Direction direction)
  60. {
  61. // cannot walk while locked
  62. if(m_walkLockExpiration != 0 && g_clock.millis() < m_walkLockExpiration)
  63. return false;
  64. // paralyzed
  65. if(m_speed == 0)
  66. return false;
  67. // last walk is not done yet
  68. if((m_walkTimer.ticksElapsed() < getStepDuration()) && !isAutoWalking())
  69. return false;
  70. // prewalk has a timeout, because for some reason that I don't know yet the server sometimes doesn't answer the prewalk
  71. bool prewalkTimeouted = m_walking && m_preWalking && m_walkTimer.ticksElapsed() >= getStepDuration() + PREWALK_TIMEOUT;
  72. // avoid doing more walks than wanted when receiving a lot of walks from server
  73. if(!m_lastPrewalkDone && m_preWalking && !prewalkTimeouted)
  74. return false;
  75. // cannot walk while already walking
  76. if((m_walking && !isAutoWalking()) && (!prewalkTimeouted || m_secondPreWalk))
  77. return false;
  78. return true;
  79. }
  80. void LocalPlayer::walk(const Position& oldPos, const Position& newPos)
  81. {
  82. // a prewalk was going on
  83. if(m_preWalking) {
  84. // switch to normal walking
  85. m_preWalking = false;
  86. m_secondPreWalk = false;
  87. m_lastPrewalkDone = true;
  88. // if is to the last prewalk destination, updates the walk preserving the animation
  89. if(newPos == m_lastPrewalkDestination) {
  90. updateWalk();
  91. // was to another direction, replace the walk
  92. } else
  93. Creature::walk(oldPos, newPos);
  94. }
  95. // no prewalk was going on, this must be an server side automated walk
  96. else {
  97. m_serverWalking = true;
  98. if(m_serverWalkEndEvent)
  99. m_serverWalkEndEvent->cancel();
  100. Creature::walk(oldPos, newPos);
  101. }
  102. }
  103. void LocalPlayer::preWalk(Otc::Direction direction)
  104. {
  105. Position newPos = m_position.translatedToDirection(direction);
  106. // avoid reanimating prewalks
  107. if(m_preWalking) {
  108. m_secondPreWalk = true;
  109. return;
  110. }
  111. m_preWalking = true;
  112. if(m_serverWalkEndEvent)
  113. m_serverWalkEndEvent->cancel();
  114. // start walking to direction
  115. m_lastPrewalkDone = false;
  116. m_lastPrewalkDestination = newPos;
  117. Creature::walk(m_position, newPos);
  118. }
  119. void LocalPlayer::cancelWalk(Otc::Direction direction)
  120. {
  121. // only cancel client side walks
  122. if(m_walking && m_preWalking)
  123. stopWalk();
  124. m_lastPrewalkDone = true;
  125. m_idleTimer.restart();
  126. lockWalk();
  127. if(m_autoWalkDestination.isValid()) {
  128. g_game.stop();
  129. auto self = asLocalPlayer();
  130. if(m_autoWalkContinueEvent)
  131. m_autoWalkContinueEvent->cancel();
  132. m_autoWalkContinueEvent = g_dispatcher.scheduleEvent([self]() {
  133. if(self->m_autoWalkDestination.isValid())
  134. self->autoWalk(self->m_autoWalkDestination);
  135. }, 500);
  136. }
  137. // turn to the cancel direction
  138. if(direction != Otc::InvalidDirection)
  139. setDirection(direction);
  140. callLuaField("onCancelWalk", direction);
  141. }
  142. bool LocalPlayer::autoWalk(const Position& destination)
  143. {
  144. bool tryKnownPath = false;
  145. if(destination != m_autoWalkDestination) {
  146. m_knownCompletePath = false;
  147. tryKnownPath = true;
  148. }
  149. std::tuple<std::vector<Otc::Direction>, Otc::PathFindResult> result;
  150. std::vector<Otc::Direction> limitedPath;
  151. if(destination == m_position)
  152. return true;
  153. // try to find a path that we know
  154. if(tryKnownPath || m_knownCompletePath) {
  155. result = g_map.findPath(m_position, destination, 50000, 0);
  156. if(std::get<1>(result) == Otc::PathFindResultOk) {
  157. limitedPath = std::get<0>(result);
  158. // limit to 127 steps
  159. if(limitedPath.size() > 127)
  160. limitedPath.resize(127);
  161. m_knownCompletePath = true;
  162. }
  163. }
  164. // no known path found, try to discover one
  165. if(limitedPath.empty()) {
  166. result = g_map.findPath(m_position, destination, 50000, Otc::PathFindAllowNotSeenTiles);
  167. if(std::get<1>(result) != Otc::PathFindResultOk) {
  168. callLuaField("onAutoWalkFail", std::get<1>(result));
  169. stopAutoWalk();
  170. return false;
  171. }
  172. Position currentPos = m_position;
  173. for(auto dir : std::get<0>(result)) {
  174. currentPos = currentPos.translatedToDirection(dir);
  175. if(!hasSight(currentPos))
  176. break;
  177. else
  178. limitedPath.push_back(dir);
  179. }
  180. }
  181. m_autoWalkDestination = destination;
  182. m_lastAutoWalkPosition = m_position.translatedToDirections(limitedPath).back();
  183. /*
  184. // debug calculated path using minimap
  185. for(auto pos : m_position.translatedToDirections(limitedPath)) {
  186. g_map.getOrCreateTile(pos)->overwriteMinimapColor(215);
  187. g_map.notificateTileUpdate(pos);
  188. }
  189. */
  190. g_game.autoWalk(limitedPath);
  191. return true;
  192. }
  193. void LocalPlayer::stopAutoWalk()
  194. {
  195. m_autoWalkDestination = Position();
  196. m_lastAutoWalkPosition = Position();
  197. m_knownCompletePath = false;
  198. if(m_autoWalkContinueEvent)
  199. m_autoWalkContinueEvent->cancel();
  200. }
  201. void LocalPlayer::stopWalk()
  202. {
  203. Creature::stopWalk(); // will call terminateWalk
  204. m_lastPrewalkDone = true;
  205. m_lastPrewalkDestination = Position();
  206. }
  207. void LocalPlayer::updateWalkOffset(int totalPixelsWalked)
  208. {
  209. // pre walks offsets are calculated in the oposite direction
  210. if(m_preWalking) {
  211. m_walkOffset = Point(0,0);
  212. if(m_direction == Otc::North || m_direction == Otc::NorthEast || m_direction == Otc::NorthWest)
  213. m_walkOffset.y = -totalPixelsWalked;
  214. else if(m_direction == Otc::South || m_direction == Otc::SouthEast || m_direction == Otc::SouthWest)
  215. m_walkOffset.y = totalPixelsWalked;
  216. if(m_direction == Otc::East || m_direction == Otc::NorthEast || m_direction == Otc::SouthEast)
  217. m_walkOffset.x = totalPixelsWalked;
  218. else if(m_direction == Otc::West || m_direction == Otc::NorthWest || m_direction == Otc::SouthWest)
  219. m_walkOffset.x = -totalPixelsWalked;
  220. } else
  221. Creature::updateWalkOffset(totalPixelsWalked);
  222. }
  223. void LocalPlayer::updateWalk()
  224. {
  225. int stepDuration = getStepDuration();
  226. float walkTicksPerPixel = getStepDuration(true) / 32.0f;
  227. int totalPixelsWalked = std::min<int>(m_walkTimer.ticksElapsed() / walkTicksPerPixel, 32.0f);
  228. // update walk animation and offsets
  229. updateWalkAnimation(totalPixelsWalked);
  230. updateWalkOffset(totalPixelsWalked);
  231. updateWalkingTile();
  232. // terminate walk only when client and server side walk are completed
  233. if(m_walking && !m_preWalking && m_walkTimer.ticksElapsed() >= stepDuration)
  234. terminateWalk();
  235. }
  236. void LocalPlayer::terminateWalk()
  237. {
  238. Creature::terminateWalk();
  239. m_preWalking = false;
  240. m_secondPreWalk = false;
  241. m_idleTimer.restart();
  242. auto self = asLocalPlayer();
  243. if(m_serverWalking) {
  244. if(m_serverWalkEndEvent)
  245. m_serverWalkEndEvent->cancel();
  246. m_serverWalkEndEvent = g_dispatcher.scheduleEvent([self] {
  247. self->m_serverWalking = false;
  248. }, 100);
  249. }
  250. }
  251. void LocalPlayer::onAppear()
  252. {
  253. Creature::onAppear();
  254. /* Does not seem to be needed anymore
  255. // on teleports lock the walk
  256. if(!m_oldPosition.isInRange(m_position,1,1))
  257. lockWalk();
  258. */
  259. }
  260. void LocalPlayer::onPositionChange(const Position& newPos, const Position& oldPos)
  261. {
  262. Creature::onPositionChange(newPos, oldPos);
  263. if(newPos == m_autoWalkDestination)
  264. stopAutoWalk();
  265. else if(m_autoWalkDestination.isValid() && newPos == m_lastAutoWalkPosition)
  266. autoWalk(m_autoWalkDestination);
  267. }
  268. void LocalPlayer::setStates(int states)
  269. {
  270. if(m_states != states) {
  271. int oldStates = m_states;
  272. m_states = states;
  273. callLuaField("onStatesChange", states, oldStates);
  274. }
  275. }
  276. void LocalPlayer::setSkill(Otc::Skill skill, int level, int levelPercent)
  277. {
  278. if(skill >= Otc::LastSkill) {
  279. g_logger.traceError("invalid skill");
  280. return;
  281. }
  282. int oldLevel = m_skillsLevel[skill];
  283. int oldLevelPercent = m_skillsLevelPercent[skill];
  284. if(level != oldLevel || levelPercent != oldLevelPercent) {
  285. m_skillsLevel[skill] = level;
  286. m_skillsLevelPercent[skill] = levelPercent;
  287. callLuaField("onSkillChange", skill, level, levelPercent, oldLevel, oldLevelPercent);
  288. }
  289. }
  290. void LocalPlayer::setBaseSkill(Otc::Skill skill, int baseLevel)
  291. {
  292. if(skill >= Otc::LastSkill) {
  293. g_logger.traceError("invalid skill");
  294. return;
  295. }
  296. int oldBaseLevel = m_skillsBaseLevel[skill];
  297. if(baseLevel != oldBaseLevel) {
  298. m_skillsBaseLevel[skill] = baseLevel;
  299. callLuaField("onBaseSkillChange", skill, baseLevel, oldBaseLevel);
  300. }
  301. }
  302. void LocalPlayer::setHealth(double health, double maxHealth)
  303. {
  304. if(m_health != health || m_maxHealth != maxHealth) {
  305. double oldHealth = m_health;
  306. double oldMaxHealth = m_maxHealth;
  307. m_health = health;
  308. m_maxHealth = maxHealth;
  309. callLuaField("onHealthChange", health, maxHealth, oldHealth, oldMaxHealth);
  310. // cannot walk while dying
  311. if(health == 0) {
  312. if(isPreWalking())
  313. stopWalk();
  314. lockWalk();
  315. }
  316. }
  317. }
  318. void LocalPlayer::setFreeCapacity(double freeCapacity)
  319. {
  320. if(m_freeCapacity != freeCapacity) {
  321. double oldFreeCapacity = m_freeCapacity;
  322. m_freeCapacity = freeCapacity;
  323. callLuaField("onFreeCapacityChange", freeCapacity, oldFreeCapacity);
  324. }
  325. }
  326. void LocalPlayer::setTotalCapacity(double totalCapacity)
  327. {
  328. if(m_totalCapacity != totalCapacity) {
  329. double oldTotalCapacity = m_totalCapacity;
  330. m_totalCapacity = totalCapacity;
  331. callLuaField("onTotalCapacityChange", totalCapacity, oldTotalCapacity);
  332. }
  333. }
  334. void LocalPlayer::setExperience(double experience)
  335. {
  336. if(m_experience != experience) {
  337. double oldExperience = m_experience;
  338. m_experience = experience;
  339. callLuaField("onExperienceChange", experience, oldExperience);
  340. }
  341. }
  342. void LocalPlayer::setLevel(double level, double levelPercent)
  343. {
  344. if(m_level != level || m_levelPercent != levelPercent) {
  345. double oldLevel = m_level;
  346. double oldLevelPercent = m_levelPercent;
  347. m_level = level;
  348. m_levelPercent = levelPercent;
  349. callLuaField("onLevelChange", level, levelPercent, oldLevel, oldLevelPercent);
  350. }
  351. }
  352. void LocalPlayer::setMana(double mana, double maxMana)
  353. {
  354. if(m_mana != mana || m_maxMana != maxMana) {
  355. double oldMana = m_mana;
  356. double oldMaxMana;
  357. m_mana = mana;
  358. m_maxMana = maxMana;
  359. callLuaField("onManaChange", mana, maxMana, oldMana, oldMaxMana);
  360. }
  361. }
  362. void LocalPlayer::setMagicLevel(double magicLevel, double magicLevelPercent)
  363. {
  364. if(m_magicLevel != magicLevel || m_magicLevelPercent != magicLevelPercent) {
  365. double oldMagicLevel = m_magicLevel;
  366. double oldMagicLevelPercent = m_magicLevelPercent;
  367. m_magicLevel = magicLevel;
  368. m_magicLevelPercent = magicLevelPercent;
  369. callLuaField("onMagicLevelChange", magicLevel, magicLevelPercent, oldMagicLevel, oldMagicLevelPercent);
  370. }
  371. }
  372. void LocalPlayer::setBaseMagicLevel(double baseMagicLevel)
  373. {
  374. if(m_baseMagicLevel != baseMagicLevel) {
  375. double oldBaseMagicLevel = m_baseMagicLevel;
  376. m_baseMagicLevel = baseMagicLevel;
  377. callLuaField("onBaseMagicLevelChange", baseMagicLevel, oldBaseMagicLevel);
  378. }
  379. }
  380. void LocalPlayer::setSoul(double soul)
  381. {
  382. if(m_soul != soul) {
  383. double oldSoul = m_soul;
  384. m_soul = soul;
  385. callLuaField("onSoulChange", soul, oldSoul);
  386. }
  387. }
  388. void LocalPlayer::setStamina(double stamina)
  389. {
  390. if(m_stamina != stamina) {
  391. double oldStamina = m_stamina;
  392. m_stamina = stamina;
  393. callLuaField("onStaminaChange", stamina, oldStamina);
  394. }
  395. }
  396. void LocalPlayer::setInventoryItem(Otc::InventorySlot inventory, const ItemPtr& item)
  397. {
  398. if(inventory >= Otc::LastInventorySlot) {
  399. g_logger.traceError("invalid slot");
  400. return;
  401. }
  402. if(m_inventoryItems[inventory] != item) {
  403. ItemPtr oldItem = m_inventoryItems[inventory];
  404. m_inventoryItems[inventory] = item;
  405. callLuaField("onInventoryChange", inventory, item, oldItem);
  406. }
  407. }
  408. void LocalPlayer::setVocation(int vocation)
  409. {
  410. if(m_vocation != vocation) {
  411. int oldVocation = m_vocation;
  412. m_vocation = vocation;
  413. callLuaField("onVocationChange", vocation, oldVocation);
  414. }
  415. }
  416. void LocalPlayer::setPremium(bool premium)
  417. {
  418. if(m_premium != premium) {
  419. m_premium = premium;
  420. callLuaField("onPremiumChange", premium);
  421. }
  422. }
  423. void LocalPlayer::setRegenerationTime(double regenerationTime)
  424. {
  425. if(m_regenerationTime != regenerationTime) {
  426. double oldRegenerationTime = m_regenerationTime;
  427. m_regenerationTime = regenerationTime;
  428. callLuaField("onRegenerationChange", regenerationTime, oldRegenerationTime);
  429. }
  430. }
  431. void LocalPlayer::setOfflineTrainingTime(double offlineTrainingTime)
  432. {
  433. if(m_offlineTrainingTime != offlineTrainingTime) {
  434. double oldOfflineTrainingTime = m_offlineTrainingTime;
  435. m_offlineTrainingTime = offlineTrainingTime;
  436. callLuaField("onOfflineTrainingChange", offlineTrainingTime, oldOfflineTrainingTime);
  437. }
  438. }
  439. void LocalPlayer::setSpells(const std::vector<int>& spells)
  440. {
  441. if(m_spells != spells) {
  442. std::vector<int> oldSpells = m_spells;
  443. m_spells = spells;
  444. callLuaField("onSpellsChange", spells, oldSpells);
  445. }
  446. }
  447. void LocalPlayer::setBlessings(int blessings)
  448. {
  449. if(blessings != m_blessings) {
  450. int oldBlessings = m_blessings;
  451. m_blessings = blessings;
  452. callLuaField("onBlessingsChange", blessings, oldBlessings);
  453. }
  454. }
  455. bool LocalPlayer::hasSight(const Position& pos)
  456. {
  457. return m_position.isInRange(pos, g_map.getAwareRange().left - 1, g_map.getAwareRange().top - 1);
  458. }