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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  1. /*
  2. * Copyright (c) 2010-2017 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. if(g_game.getClientVersion() <= 740 && m_position.isInRange(destination, 1, 1))
  145. return g_game.walk(m_position.getDirectionFromPosition(destination));
  146. bool tryKnownPath = false;
  147. if(destination != m_autoWalkDestination) {
  148. m_knownCompletePath = false;
  149. tryKnownPath = true;
  150. }
  151. std::tuple<std::vector<Otc::Direction>, Otc::PathFindResult> result;
  152. std::vector<Otc::Direction> limitedPath;
  153. if(destination == m_position)
  154. return true;
  155. // try to find a path that we know
  156. if(tryKnownPath || m_knownCompletePath) {
  157. result = g_map.findPath(m_position, destination, 50000, 0);
  158. if(std::get<1>(result) == Otc::PathFindResultOk) {
  159. limitedPath = std::get<0>(result);
  160. // limit to 127 steps
  161. if(limitedPath.size() > 127)
  162. limitedPath.resize(127);
  163. m_knownCompletePath = true;
  164. }
  165. }
  166. // no known path found, try to discover one
  167. if(limitedPath.empty()) {
  168. result = g_map.findPath(m_position, destination, 50000, Otc::PathFindAllowNotSeenTiles);
  169. if(std::get<1>(result) != Otc::PathFindResultOk) {
  170. callLuaField("onAutoWalkFail", std::get<1>(result));
  171. stopAutoWalk();
  172. return false;
  173. }
  174. Position currentPos = m_position;
  175. for(auto dir : std::get<0>(result)) {
  176. currentPos = currentPos.translatedToDirection(dir);
  177. if(!hasSight(currentPos))
  178. break;
  179. else
  180. limitedPath.push_back(dir);
  181. }
  182. }
  183. m_autoWalkDestination = destination;
  184. m_lastAutoWalkPosition = m_position.translatedToDirections(limitedPath).back();
  185. /*
  186. // debug calculated path using minimap
  187. for(auto pos : m_position.translatedToDirections(limitedPath)) {
  188. g_map.getOrCreateTile(pos)->overwriteMinimapColor(215);
  189. g_map.notificateTileUpdate(pos);
  190. }
  191. */
  192. g_game.autoWalk(limitedPath);
  193. return true;
  194. }
  195. void LocalPlayer::stopAutoWalk()
  196. {
  197. m_autoWalkDestination = Position();
  198. m_lastAutoWalkPosition = Position();
  199. m_knownCompletePath = false;
  200. if(m_autoWalkContinueEvent)
  201. m_autoWalkContinueEvent->cancel();
  202. }
  203. void LocalPlayer::stopWalk()
  204. {
  205. Creature::stopWalk(); // will call terminateWalk
  206. m_lastPrewalkDone = true;
  207. m_lastPrewalkDestination = Position();
  208. }
  209. void LocalPlayer::updateWalkOffset(int totalPixelsWalked)
  210. {
  211. // pre walks offsets are calculated in the oposite direction
  212. if(m_preWalking) {
  213. m_walkOffset = Point(0,0);
  214. if(m_direction == Otc::North || m_direction == Otc::NorthEast || m_direction == Otc::NorthWest)
  215. m_walkOffset.y = -totalPixelsWalked;
  216. else if(m_direction == Otc::South || m_direction == Otc::SouthEast || m_direction == Otc::SouthWest)
  217. m_walkOffset.y = totalPixelsWalked;
  218. if(m_direction == Otc::East || m_direction == Otc::NorthEast || m_direction == Otc::SouthEast)
  219. m_walkOffset.x = totalPixelsWalked;
  220. else if(m_direction == Otc::West || m_direction == Otc::NorthWest || m_direction == Otc::SouthWest)
  221. m_walkOffset.x = -totalPixelsWalked;
  222. } else
  223. Creature::updateWalkOffset(totalPixelsWalked);
  224. }
  225. void LocalPlayer::updateWalk()
  226. {
  227. int stepDuration = getStepDuration();
  228. float walkTicksPerPixel = getStepDuration(true) / 32.0f;
  229. int totalPixelsWalked = std::min<int>(m_walkTimer.ticksElapsed() / walkTicksPerPixel, 32.0f);
  230. // update walk animation and offsets
  231. updateWalkAnimation(totalPixelsWalked);
  232. updateWalkOffset(totalPixelsWalked);
  233. updateWalkingTile();
  234. // terminate walk only when client and server side walk are completed
  235. if(m_walking && !m_preWalking && m_walkTimer.ticksElapsed() >= stepDuration)
  236. terminateWalk();
  237. }
  238. void LocalPlayer::terminateWalk()
  239. {
  240. Creature::terminateWalk();
  241. m_preWalking = false;
  242. m_secondPreWalk = false;
  243. m_idleTimer.restart();
  244. auto self = asLocalPlayer();
  245. if(m_serverWalking) {
  246. if(m_serverWalkEndEvent)
  247. m_serverWalkEndEvent->cancel();
  248. m_serverWalkEndEvent = g_dispatcher.scheduleEvent([self] {
  249. self->m_serverWalking = false;
  250. }, 100);
  251. }
  252. }
  253. void LocalPlayer::onAppear()
  254. {
  255. Creature::onAppear();
  256. /* Does not seem to be needed anymore
  257. // on teleports lock the walk
  258. if(!m_oldPosition.isInRange(m_position,1,1))
  259. lockWalk();
  260. */
  261. }
  262. void LocalPlayer::onPositionChange(const Position& newPos, const Position& oldPos)
  263. {
  264. Creature::onPositionChange(newPos, oldPos);
  265. if(newPos == m_autoWalkDestination)
  266. stopAutoWalk();
  267. else if(m_autoWalkDestination.isValid() && newPos == m_lastAutoWalkPosition)
  268. autoWalk(m_autoWalkDestination);
  269. }
  270. void LocalPlayer::setStates(int states)
  271. {
  272. if(m_states != states) {
  273. int oldStates = m_states;
  274. m_states = states;
  275. callLuaField("onStatesChange", states, oldStates);
  276. }
  277. }
  278. void LocalPlayer::setSkill(Otc::Skill skill, int level, int levelPercent)
  279. {
  280. if(skill >= Otc::LastSkill) {
  281. g_logger.traceError("invalid skill");
  282. return;
  283. }
  284. int oldLevel = m_skillsLevel[skill];
  285. int oldLevelPercent = m_skillsLevelPercent[skill];
  286. if(level != oldLevel || levelPercent != oldLevelPercent) {
  287. m_skillsLevel[skill] = level;
  288. m_skillsLevelPercent[skill] = levelPercent;
  289. callLuaField("onSkillChange", skill, level, levelPercent, oldLevel, oldLevelPercent);
  290. }
  291. }
  292. void LocalPlayer::setBaseSkill(Otc::Skill skill, int baseLevel)
  293. {
  294. if(skill >= Otc::LastSkill) {
  295. g_logger.traceError("invalid skill");
  296. return;
  297. }
  298. int oldBaseLevel = m_skillsBaseLevel[skill];
  299. if(baseLevel != oldBaseLevel) {
  300. m_skillsBaseLevel[skill] = baseLevel;
  301. callLuaField("onBaseSkillChange", skill, baseLevel, oldBaseLevel);
  302. }
  303. }
  304. void LocalPlayer::setHealth(double health, double maxHealth)
  305. {
  306. if(m_health != health || m_maxHealth != maxHealth) {
  307. double oldHealth = m_health;
  308. double oldMaxHealth = m_maxHealth;
  309. m_health = health;
  310. m_maxHealth = maxHealth;
  311. callLuaField("onHealthChange", health, maxHealth, oldHealth, oldMaxHealth);
  312. // cannot walk while dying
  313. if(health == 0) {
  314. if(isPreWalking())
  315. stopWalk();
  316. lockWalk();
  317. }
  318. }
  319. }
  320. void LocalPlayer::setFreeCapacity(double freeCapacity)
  321. {
  322. if(m_freeCapacity != freeCapacity) {
  323. double oldFreeCapacity = m_freeCapacity;
  324. m_freeCapacity = freeCapacity;
  325. callLuaField("onFreeCapacityChange", freeCapacity, oldFreeCapacity);
  326. }
  327. }
  328. void LocalPlayer::setTotalCapacity(double totalCapacity)
  329. {
  330. if(m_totalCapacity != totalCapacity) {
  331. double oldTotalCapacity = m_totalCapacity;
  332. m_totalCapacity = totalCapacity;
  333. callLuaField("onTotalCapacityChange", totalCapacity, oldTotalCapacity);
  334. }
  335. }
  336. void LocalPlayer::setExperience(double experience)
  337. {
  338. if(m_experience != experience) {
  339. double oldExperience = m_experience;
  340. m_experience = experience;
  341. callLuaField("onExperienceChange", experience, oldExperience);
  342. }
  343. }
  344. void LocalPlayer::setLevel(double level, double levelPercent)
  345. {
  346. if(m_level != level || m_levelPercent != levelPercent) {
  347. double oldLevel = m_level;
  348. double oldLevelPercent = m_levelPercent;
  349. m_level = level;
  350. m_levelPercent = levelPercent;
  351. callLuaField("onLevelChange", level, levelPercent, oldLevel, oldLevelPercent);
  352. }
  353. }
  354. void LocalPlayer::setMana(double mana, double maxMana)
  355. {
  356. if(m_mana != mana || m_maxMana != maxMana) {
  357. double oldMana = m_mana;
  358. double oldMaxMana;
  359. m_mana = mana;
  360. m_maxMana = maxMana;
  361. callLuaField("onManaChange", mana, maxMana, oldMana, oldMaxMana);
  362. }
  363. }
  364. void LocalPlayer::setMagicLevel(double magicLevel, double magicLevelPercent)
  365. {
  366. if(m_magicLevel != magicLevel || m_magicLevelPercent != magicLevelPercent) {
  367. double oldMagicLevel = m_magicLevel;
  368. double oldMagicLevelPercent = m_magicLevelPercent;
  369. m_magicLevel = magicLevel;
  370. m_magicLevelPercent = magicLevelPercent;
  371. callLuaField("onMagicLevelChange", magicLevel, magicLevelPercent, oldMagicLevel, oldMagicLevelPercent);
  372. }
  373. }
  374. void LocalPlayer::setBaseMagicLevel(double baseMagicLevel)
  375. {
  376. if(m_baseMagicLevel != baseMagicLevel) {
  377. double oldBaseMagicLevel = m_baseMagicLevel;
  378. m_baseMagicLevel = baseMagicLevel;
  379. callLuaField("onBaseMagicLevelChange", baseMagicLevel, oldBaseMagicLevel);
  380. }
  381. }
  382. void LocalPlayer::setSoul(double soul)
  383. {
  384. if(m_soul != soul) {
  385. double oldSoul = m_soul;
  386. m_soul = soul;
  387. callLuaField("onSoulChange", soul, oldSoul);
  388. }
  389. }
  390. void LocalPlayer::setStamina(double stamina)
  391. {
  392. if(m_stamina != stamina) {
  393. double oldStamina = m_stamina;
  394. m_stamina = stamina;
  395. callLuaField("onStaminaChange", stamina, oldStamina);
  396. }
  397. }
  398. void LocalPlayer::setInventoryItem(Otc::InventorySlot inventory, const ItemPtr& item)
  399. {
  400. if(inventory >= Otc::LastInventorySlot) {
  401. g_logger.traceError("invalid slot");
  402. return;
  403. }
  404. if(m_inventoryItems[inventory] != item) {
  405. ItemPtr oldItem = m_inventoryItems[inventory];
  406. m_inventoryItems[inventory] = item;
  407. callLuaField("onInventoryChange", inventory, item, oldItem);
  408. }
  409. }
  410. void LocalPlayer::setVocation(int vocation)
  411. {
  412. if(m_vocation != vocation) {
  413. int oldVocation = m_vocation;
  414. m_vocation = vocation;
  415. callLuaField("onVocationChange", vocation, oldVocation);
  416. }
  417. }
  418. void LocalPlayer::setPremium(bool premium)
  419. {
  420. if(m_premium != premium) {
  421. m_premium = premium;
  422. callLuaField("onPremiumChange", premium);
  423. }
  424. }
  425. void LocalPlayer::setRegenerationTime(double regenerationTime)
  426. {
  427. if(m_regenerationTime != regenerationTime) {
  428. double oldRegenerationTime = m_regenerationTime;
  429. m_regenerationTime = regenerationTime;
  430. callLuaField("onRegenerationChange", regenerationTime, oldRegenerationTime);
  431. }
  432. }
  433. void LocalPlayer::setOfflineTrainingTime(double offlineTrainingTime)
  434. {
  435. if(m_offlineTrainingTime != offlineTrainingTime) {
  436. double oldOfflineTrainingTime = m_offlineTrainingTime;
  437. m_offlineTrainingTime = offlineTrainingTime;
  438. callLuaField("onOfflineTrainingChange", offlineTrainingTime, oldOfflineTrainingTime);
  439. }
  440. }
  441. void LocalPlayer::setSpells(const std::vector<int>& spells)
  442. {
  443. if(m_spells != spells) {
  444. std::vector<int> oldSpells = m_spells;
  445. m_spells = spells;
  446. callLuaField("onSpellsChange", spells, oldSpells);
  447. }
  448. }
  449. void LocalPlayer::setBlessings(int blessings)
  450. {
  451. if(blessings != m_blessings) {
  452. int oldBlessings = m_blessings;
  453. m_blessings = blessings;
  454. callLuaField("onBlessingsChange", blessings, oldBlessings);
  455. }
  456. }
  457. bool LocalPlayer::hasSight(const Position& pos)
  458. {
  459. return m_position.isInRange(pos, g_map.getAwareRange().left - 1, g_map.getAwareRange().top - 1);
  460. }