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.

creature.cpp 31KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965
  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 "creature.h"
  23. #include "thingtypemanager.h"
  24. #include "localplayer.h"
  25. #include "map.h"
  26. #include "tile.h"
  27. #include "item.h"
  28. #include "game.h"
  29. #include "effect.h"
  30. #include "luavaluecasts.h"
  31. #include "lightview.h"
  32. #include <framework/graphics/graphics.h>
  33. #include <framework/core/eventdispatcher.h>
  34. #include <framework/core/clock.h>
  35. #include <framework/graphics/paintershaderprogram.h>
  36. #include <framework/graphics/ogl/painterogl2_shadersources.h>
  37. #include <framework/graphics/texturemanager.h>
  38. #include <framework/graphics/framebuffermanager.h>
  39. #include "spritemanager.h"
  40. Creature::Creature() : Thing()
  41. {
  42. m_id = 0;
  43. m_healthPercent = 100;
  44. m_speed = 200;
  45. m_direction = Otc::South;
  46. m_walkAnimationPhase = 0;
  47. m_walkedPixels = 0;
  48. m_walkTurnDirection = Otc::InvalidDirection;
  49. m_skull = Otc::SkullNone;
  50. m_shield = Otc::ShieldNone;
  51. m_emblem = Otc::EmblemNone;
  52. m_icon = Otc::NpcIconNone;
  53. m_lastStepDirection = Otc::InvalidDirection;
  54. m_nameCache.setFont(g_fonts.getFont("verdana-11px-rounded"));
  55. m_nameCache.setAlign(Fw::AlignTopCenter);
  56. m_footStep = 0;
  57. m_speedFormula.fill(-1);
  58. m_outfitColor = Color::white;
  59. }
  60. void Creature::draw(const Point& dest, float scaleFactor, bool animate, LightView *lightView)
  61. {
  62. if(!canBeSeen())
  63. return;
  64. Point animationOffset = animate ? m_walkOffset : Point(0,0);
  65. if(m_showTimedSquare && animate) {
  66. g_painter->setColor(m_timedSquareColor);
  67. g_painter->drawBoundingRect(Rect(dest + (animationOffset - getDisplacement() + 2)*scaleFactor, Size(28, 28)*scaleFactor), std::max<int>((int)(2*scaleFactor), 1));
  68. g_painter->setColor(Color::white);
  69. }
  70. if(m_showStaticSquare && animate) {
  71. g_painter->setColor(m_staticSquareColor);
  72. g_painter->drawBoundingRect(Rect(dest + (animationOffset - getDisplacement())*scaleFactor, Size(Otc::TILE_PIXELS, Otc::TILE_PIXELS)*scaleFactor), std::max<int>((int)(2*scaleFactor), 1));
  73. g_painter->setColor(Color::white);
  74. }
  75. internalDrawOutfit(dest + animationOffset * scaleFactor, scaleFactor, animate, animate, m_direction);
  76. m_footStepDrawn = true;
  77. if(lightView) {
  78. Light light = rawGetThingType()->getLight();
  79. if(m_light.intensity != light.intensity || m_light.color != light.color)
  80. light = m_light;
  81. // local player always have a minimum light in complete darkness
  82. if(isLocalPlayer() && (g_map.getLight().intensity < 64 || m_position.z > Otc::SEA_FLOOR)) {
  83. light.intensity = std::max<uint8>(light.intensity, 3);
  84. if(light.color == 0 || light.color > 215)
  85. light.color = 215;
  86. }
  87. if(light.intensity > 0)
  88. lightView->addLightSource(dest + (animationOffset + Point(16,16)) * scaleFactor, scaleFactor, light);
  89. }
  90. }
  91. void Creature::internalDrawOutfit(Point dest, float scaleFactor, bool animateWalk, bool animateIdle, Otc::Direction direction, LightView *lightView)
  92. {
  93. g_painter->setColor(m_outfitColor);
  94. // outfit is a real creature
  95. if(m_outfit.getCategory() == ThingCategoryCreature) {
  96. int animationPhase = animateWalk ? m_walkAnimationPhase : 0;
  97. if(isAnimateAlways() && animateIdle) {
  98. int ticksPerFrame = 1000 / getAnimationPhases();
  99. animationPhase = (g_clock.millis() % (ticksPerFrame * getAnimationPhases())) / ticksPerFrame;
  100. }
  101. // xPattern => creature direction
  102. int xPattern;
  103. if(direction == Otc::NorthEast || direction == Otc::SouthEast)
  104. xPattern = Otc::East;
  105. else if(direction == Otc::NorthWest || direction == Otc::SouthWest)
  106. xPattern = Otc::West;
  107. else
  108. xPattern = direction;
  109. int zPattern = 0;
  110. if(m_outfit.getMount() != 0) {
  111. auto datType = g_things.rawGetThingType(m_outfit.getMount(), ThingCategoryCreature);
  112. dest -= datType->getDisplacement() * scaleFactor;
  113. datType->draw(dest, scaleFactor, 0, xPattern, 0, 0, animationPhase, lightView);
  114. dest += getDisplacement() * scaleFactor;
  115. zPattern = std::min<int>(1, getNumPatternZ() - 1);
  116. }
  117. PointF jumpOffset = m_jumpOffset * scaleFactor;
  118. dest -= Point(stdext::round(jumpOffset.x), stdext::round(jumpOffset.y));
  119. // yPattern => creature addon
  120. for(int yPattern = 0; yPattern < getNumPatternY(); yPattern++) {
  121. // continue if we dont have this addon
  122. if(yPattern > 0 && !(m_outfit.getAddons() & (1 << (yPattern-1))))
  123. continue;
  124. auto datType = rawGetThingType();
  125. datType->draw(dest, scaleFactor, 0, xPattern, yPattern, zPattern, animationPhase, yPattern == 0 ? lightView : nullptr);
  126. if(getLayers() > 1) {
  127. Color oldColor = g_painter->getColor();
  128. Painter::CompositionMode oldComposition = g_painter->getCompositionMode();
  129. g_painter->setCompositionMode(Painter::CompositionMode_Multiply);
  130. g_painter->setColor(m_outfit.getHeadColor());
  131. datType->draw(dest, scaleFactor, SpriteMaskYellow, xPattern, yPattern, zPattern, animationPhase);
  132. g_painter->setColor(m_outfit.getBodyColor());
  133. datType->draw(dest, scaleFactor, SpriteMaskRed, xPattern, yPattern, zPattern, animationPhase);
  134. g_painter->setColor(m_outfit.getLegsColor());
  135. datType->draw(dest, scaleFactor, SpriteMaskGreen, xPattern, yPattern, zPattern, animationPhase);
  136. g_painter->setColor(m_outfit.getFeetColor());
  137. datType->draw(dest, scaleFactor, SpriteMaskBlue, xPattern, yPattern, zPattern, animationPhase);
  138. g_painter->setColor(oldColor);
  139. g_painter->setCompositionMode(oldComposition);
  140. }
  141. }
  142. // outfit is a creature imitating an item or the invisible effect
  143. } else {
  144. ThingType *type = g_things.rawGetThingType(m_outfit.getAuxId(), m_outfit.getCategory());
  145. int animationPhase = 0;
  146. int animationPhases = type->getAnimationPhases();
  147. int animateTicks = Otc::ITEM_TICKS_PER_FRAME;
  148. // when creature is an effect we cant render the first and last animation phase,
  149. // instead we should loop in the phases between
  150. if(m_outfit.getCategory() == ThingCategoryEffect) {
  151. animationPhases = std::max<int>(1, animationPhases-2);
  152. animateTicks = Otc::INVISIBLE_TICKS_PER_FRAME;
  153. }
  154. if(animationPhases > 1) {
  155. if(animateIdle)
  156. animationPhase = (g_clock.millis() % (animateTicks * animationPhases)) / animateTicks;
  157. else
  158. animationPhase = animationPhases-1;
  159. }
  160. if(m_outfit.getCategory() == ThingCategoryEffect)
  161. animationPhase = std::min<int>(animationPhase+1, animationPhases);
  162. type->draw(dest - (getDisplacement() * scaleFactor), scaleFactor, 0, 0, 0, 0, animationPhase, lightView);
  163. }
  164. g_painter->resetColor();
  165. }
  166. void Creature::drawOutfit(const Rect& destRect, bool resize)
  167. {
  168. int exactSize;
  169. if(m_outfit.getCategory() == ThingCategoryCreature)
  170. exactSize = getExactSize();
  171. else
  172. exactSize = g_things.rawGetThingType(m_outfit.getAuxId(), m_outfit.getCategory())->getExactSize();
  173. int frameSize;
  174. if(!resize)
  175. frameSize = std::max<int>(exactSize * 0.75f, 2 * Otc::TILE_PIXELS * 0.75f);
  176. else if(!(frameSize = exactSize))
  177. return;
  178. if(g_graphics.canUseFBO()) {
  179. const FrameBufferPtr& outfitBuffer = g_framebuffers.getTemporaryFrameBuffer();
  180. outfitBuffer->resize(Size(frameSize, frameSize));
  181. outfitBuffer->bind();
  182. g_painter->setAlphaWriting(true);
  183. g_painter->clear(Color::alpha);
  184. internalDrawOutfit(Point(frameSize - Otc::TILE_PIXELS, frameSize - Otc::TILE_PIXELS) + getDisplacement(), 1, false, true, Otc::South);
  185. outfitBuffer->release();
  186. outfitBuffer->draw(destRect, Rect(0,0,frameSize,frameSize));
  187. } else {
  188. float scaleFactor = destRect.width() / (float)frameSize;
  189. Point dest = destRect.bottomRight() - (Point(Otc::TILE_PIXELS,Otc::TILE_PIXELS) - getDisplacement()) * scaleFactor;
  190. internalDrawOutfit(dest, scaleFactor, false, true, Otc::South);
  191. }
  192. }
  193. void Creature::drawInformation(const Point& point, bool useGray, const Rect& parentRect, int drawFlags)
  194. {
  195. if(m_healthPercent < 1) // creature is dead
  196. return;
  197. Color fillColor = Color(96, 96, 96);
  198. if(!useGray)
  199. fillColor = m_informationColor;
  200. // calculate main rects
  201. Rect backgroundRect = Rect(point.x-(13.5), point.y, 27, 4);
  202. backgroundRect.bind(parentRect);
  203. Size nameSize = m_nameCache.getTextSize();
  204. Rect textRect = Rect(point.x - nameSize.width() / 2.0, point.y-12, nameSize);
  205. textRect.bind(parentRect);
  206. // distance them
  207. uint32 offset = 12;
  208. if(isLocalPlayer()) {
  209. offset *= 2;
  210. }
  211. if(textRect.top() == parentRect.top())
  212. backgroundRect.moveTop(textRect.top() + offset);
  213. if(backgroundRect.bottom() == parentRect.bottom())
  214. textRect.moveTop(backgroundRect.top() - offset);
  215. // health rect is based on background rect, so no worries
  216. Rect healthRect = backgroundRect.expanded(-1);
  217. healthRect.setWidth((m_healthPercent / 100.0) * 25);
  218. // draw
  219. if(g_game.getFeature(Otc::GameBlueNpcNameColor) && isNpc() && m_healthPercent == 100 && !useGray)
  220. fillColor = Color(0x66, 0xcc, 0xff);
  221. if(drawFlags & Otc::DrawBars && (!isNpc() || !g_game.getFeature(Otc::GameHideNpcNames))) {
  222. g_painter->setColor(Color::black);
  223. g_painter->drawFilledRect(backgroundRect);
  224. g_painter->setColor(fillColor);
  225. g_painter->drawFilledRect(healthRect);
  226. if(drawFlags & Otc::DrawManaBar && isLocalPlayer()) {
  227. LocalPlayerPtr player = g_game.getLocalPlayer();
  228. if(player) {
  229. backgroundRect.moveTop(backgroundRect.bottom());
  230. g_painter->setColor(Color::black);
  231. g_painter->drawFilledRect(backgroundRect);
  232. Rect manaRect = backgroundRect.expanded(-1);
  233. double maxMana = player->getMaxMana();
  234. if(maxMana == 0) {
  235. manaRect.setWidth(25);
  236. } else {
  237. manaRect.setWidth(player->getMana() / (maxMana * 1.0) * 25);
  238. }
  239. g_painter->setColor(Color::blue);
  240. g_painter->drawFilledRect(manaRect);
  241. }
  242. }
  243. }
  244. if(drawFlags & Otc::DrawNames) {
  245. if(g_painter->getColor() != fillColor)
  246. g_painter->setColor(fillColor);
  247. m_nameCache.draw(textRect);
  248. }
  249. if(m_skull != Otc::SkullNone && m_skullTexture) {
  250. g_painter->setColor(Color::white);
  251. Rect skullRect = Rect(backgroundRect.x() + 13.5 + 12, backgroundRect.y() + 5, m_skullTexture->getSize());
  252. g_painter->drawTexturedRect(skullRect, m_skullTexture);
  253. }
  254. if(m_shield != Otc::ShieldNone && m_shieldTexture && m_showShieldTexture) {
  255. g_painter->setColor(Color::white);
  256. Rect shieldRect = Rect(backgroundRect.x() + 13.5, backgroundRect.y() + 5, m_shieldTexture->getSize());
  257. g_painter->drawTexturedRect(shieldRect, m_shieldTexture);
  258. }
  259. if(m_emblem != Otc::EmblemNone && m_emblemTexture) {
  260. g_painter->setColor(Color::white);
  261. Rect emblemRect = Rect(backgroundRect.x() + 13.5 + 12, backgroundRect.y() + 16, m_emblemTexture->getSize());
  262. g_painter->drawTexturedRect(emblemRect, m_emblemTexture);
  263. }
  264. if(m_icon != Otc::NpcIconNone && m_iconTexture) {
  265. g_painter->setColor(Color::white);
  266. Rect iconRect = Rect(backgroundRect.x() + 13.5 + 12, backgroundRect.y() + 5, m_iconTexture->getSize());
  267. g_painter->drawTexturedRect(iconRect, m_iconTexture);
  268. }
  269. }
  270. void Creature::turn(Otc::Direction direction)
  271. {
  272. // if is not walking change the direction right away
  273. if(!m_walking)
  274. setDirection(direction);
  275. // schedules to set the new direction when walk ends
  276. else
  277. m_walkTurnDirection = direction;
  278. }
  279. void Creature::walk(const Position& oldPos, const Position& newPos)
  280. {
  281. if(oldPos == newPos)
  282. return;
  283. // get walk direction
  284. m_lastStepDirection = oldPos.getDirectionFromPosition(newPos);
  285. m_lastStepFromPosition = oldPos;
  286. m_lastStepToPosition = newPos;
  287. // set current walking direction
  288. setDirection(m_lastStepDirection);
  289. // starts counting walk
  290. m_walking = true;
  291. m_walkTimer.restart();
  292. m_walkedPixels = 0;
  293. if(m_walkFinishAnimEvent) {
  294. m_walkFinishAnimEvent->cancel();
  295. m_walkFinishAnimEvent = nullptr;
  296. }
  297. // no direction need to be changed when the walk ends
  298. m_walkTurnDirection = Otc::InvalidDirection;
  299. // starts updating walk
  300. nextWalkUpdate();
  301. }
  302. void Creature::stopWalk()
  303. {
  304. if(!m_walking)
  305. return;
  306. // stops the walk right away
  307. terminateWalk();
  308. }
  309. void Creature::jump(int height, int duration)
  310. {
  311. if(!m_jumpOffset.isNull())
  312. return;
  313. m_jumpTimer.restart();
  314. m_jumpHeight = height;
  315. m_jumpDuration = duration;
  316. updateJump();
  317. }
  318. void Creature::updateJump()
  319. {
  320. int t = m_jumpTimer.ticksElapsed();
  321. double a = -4 * m_jumpHeight / (m_jumpDuration * m_jumpDuration);
  322. double b = +4 * m_jumpHeight / (m_jumpDuration);
  323. double height = a*t*t + b*t;
  324. int roundHeight = stdext::round(height);
  325. int halfJumpDuration = m_jumpDuration / 2;
  326. // schedules next update
  327. if(m_jumpTimer.ticksElapsed() < m_jumpDuration) {
  328. m_jumpOffset = PointF(height, height);
  329. int diff = 0;
  330. if(m_jumpTimer.ticksElapsed() < halfJumpDuration)
  331. diff = 1;
  332. else if(m_jumpTimer.ticksElapsed() > halfJumpDuration)
  333. diff = -1;
  334. int nextT, i = 1;
  335. do {
  336. nextT = stdext::round((-b + std::sqrt(std::max<int>(b*b + 4*a*(roundHeight+diff*i), 0.0)) * diff) / (2*a));
  337. ++i;
  338. if(nextT < halfJumpDuration)
  339. diff = 1;
  340. else if(nextT > halfJumpDuration)
  341. diff = -1;
  342. } while(nextT - m_jumpTimer.ticksElapsed() == 0 && i < 3);
  343. auto self = static_self_cast<Creature>();
  344. g_dispatcher.scheduleEvent([self] {
  345. self->updateJump();
  346. }, nextT - m_jumpTimer.ticksElapsed());
  347. }
  348. else
  349. m_jumpOffset = PointF(0, 0);
  350. }
  351. void Creature::onPositionChange(const Position& newPos, const Position& oldPos)
  352. {
  353. callLuaField("onPositionChange", newPos, oldPos);
  354. }
  355. void Creature::onAppear()
  356. {
  357. // cancel any disappear event
  358. if(m_disappearEvent) {
  359. m_disappearEvent->cancel();
  360. m_disappearEvent = nullptr;
  361. }
  362. // creature appeared the first time or wasn't seen for a long time
  363. if(m_removed) {
  364. stopWalk();
  365. m_removed = false;
  366. callLuaField("onAppear");
  367. // walk
  368. } else if(m_oldPosition != m_position && m_oldPosition.isInRange(m_position,1,1) && m_allowAppearWalk) {
  369. m_allowAppearWalk = false;
  370. walk(m_oldPosition, m_position);
  371. callLuaField("onWalk", m_oldPosition, m_position);
  372. // teleport
  373. } else if(m_oldPosition != m_position) {
  374. stopWalk();
  375. callLuaField("onDisappear");
  376. callLuaField("onAppear");
  377. } // else turn
  378. }
  379. void Creature::onDisappear()
  380. {
  381. if(m_disappearEvent)
  382. m_disappearEvent->cancel();
  383. m_oldPosition = m_position;
  384. // a pair onDisappear and onAppear events are fired even when creatures walks or turns,
  385. // so we must filter
  386. auto self = static_self_cast<Creature>();
  387. m_disappearEvent = g_dispatcher.addEvent([self] {
  388. self->m_removed = true;
  389. self->stopWalk();
  390. self->callLuaField("onDisappear");
  391. // invalidate this creature position
  392. if(!self->isLocalPlayer())
  393. self->setPosition(Position());
  394. self->m_oldPosition = Position();
  395. self->m_disappearEvent = nullptr;
  396. });
  397. }
  398. void Creature::onDeath()
  399. {
  400. callLuaField("onDeath");
  401. }
  402. void Creature::updateWalkAnimation(int totalPixelsWalked)
  403. {
  404. // update outfit animation
  405. if(m_outfit.getCategory() != ThingCategoryCreature)
  406. return;
  407. int footAnimPhases = getAnimationPhases() - 1;
  408. int footDelay = getStepDuration(true) / 3;
  409. // Since mount is a different outfit we need to get the mount animation phases
  410. if(m_outfit.getMount() != 0) {
  411. ThingType *type = g_things.rawGetThingType(m_outfit.getMount(), m_outfit.getCategory());
  412. footAnimPhases = type->getAnimationPhases() - 1;
  413. }
  414. if(footAnimPhases == 0)
  415. m_walkAnimationPhase = 0;
  416. else if(m_footStepDrawn && m_footTimer.ticksElapsed() >= footDelay && totalPixelsWalked < 32) {
  417. m_footStep++;
  418. m_walkAnimationPhase = 1 + (m_footStep % footAnimPhases);
  419. m_footStepDrawn = false;
  420. m_footTimer.restart();
  421. } else if(m_walkAnimationPhase == 0 && totalPixelsWalked < 32) {
  422. m_walkAnimationPhase = 1 + (m_footStep % footAnimPhases);
  423. }
  424. if(totalPixelsWalked == 32 && !m_walkFinishAnimEvent) {
  425. auto self = static_self_cast<Creature>();
  426. m_walkFinishAnimEvent = g_dispatcher.scheduleEvent([self] {
  427. if(!self->m_walking || self->m_walkTimer.ticksElapsed() >= self->getStepDuration(true))
  428. self->m_walkAnimationPhase = 0;
  429. self->m_walkFinishAnimEvent = nullptr;
  430. }, std::min<int>(footDelay, 200));
  431. }
  432. }
  433. void Creature::updateWalkOffset(int totalPixelsWalked)
  434. {
  435. m_walkOffset = Point(0,0);
  436. if(m_direction == Otc::North || m_direction == Otc::NorthEast || m_direction == Otc::NorthWest)
  437. m_walkOffset.y = 32 - totalPixelsWalked;
  438. else if(m_direction == Otc::South || m_direction == Otc::SouthEast || m_direction == Otc::SouthWest)
  439. m_walkOffset.y = totalPixelsWalked - 32;
  440. if(m_direction == Otc::East || m_direction == Otc::NorthEast || m_direction == Otc::SouthEast)
  441. m_walkOffset.x = totalPixelsWalked - 32;
  442. else if(m_direction == Otc::West || m_direction == Otc::NorthWest || m_direction == Otc::SouthWest)
  443. m_walkOffset.x = 32 - totalPixelsWalked;
  444. }
  445. void Creature::updateWalkingTile()
  446. {
  447. // determine new walking tile
  448. TilePtr newWalkingTile;
  449. Rect virtualCreatureRect(Otc::TILE_PIXELS + (m_walkOffset.x - getDisplacementX()),
  450. Otc::TILE_PIXELS + (m_walkOffset.y - getDisplacementY()),
  451. Otc::TILE_PIXELS, Otc::TILE_PIXELS);
  452. for(int xi = -1; xi <= 1 && !newWalkingTile; ++xi) {
  453. for(int yi = -1; yi <= 1 && !newWalkingTile; ++yi) {
  454. Rect virtualTileRect((xi+1)*Otc::TILE_PIXELS, (yi+1)*Otc::TILE_PIXELS, Otc::TILE_PIXELS, Otc::TILE_PIXELS);
  455. // only render creatures where bottom right is inside tile rect
  456. if(virtualTileRect.contains(virtualCreatureRect.bottomRight())) {
  457. newWalkingTile = g_map.getOrCreateTile(m_position.translated(xi, yi, 0));
  458. }
  459. }
  460. }
  461. if(newWalkingTile != m_walkingTile) {
  462. if(m_walkingTile)
  463. m_walkingTile->removeWalkingCreature(static_self_cast<Creature>());
  464. if(newWalkingTile) {
  465. newWalkingTile->addWalkingCreature(static_self_cast<Creature>());
  466. // recache visible tiles in map views
  467. if(newWalkingTile->isEmpty())
  468. g_map.notificateTileUpdate(newWalkingTile->getPosition());
  469. }
  470. m_walkingTile = newWalkingTile;
  471. }
  472. }
  473. void Creature::nextWalkUpdate()
  474. {
  475. // remove any previous scheduled walk updates
  476. if(m_walkUpdateEvent)
  477. m_walkUpdateEvent->cancel();
  478. // do the update
  479. updateWalk();
  480. // schedules next update
  481. if(m_walking) {
  482. auto self = static_self_cast<Creature>();
  483. m_walkUpdateEvent = g_dispatcher.scheduleEvent([self] {
  484. self->m_walkUpdateEvent = nullptr;
  485. self->nextWalkUpdate();
  486. }, getStepDuration() / 32);
  487. }
  488. }
  489. void Creature::updateWalk()
  490. {
  491. float walkTicksPerPixel = getStepDuration(true) / 32;
  492. int totalPixelsWalked = std::min<int>(m_walkTimer.ticksElapsed() / walkTicksPerPixel, 32.0f);
  493. // needed for paralyze effect
  494. m_walkedPixels = std::max<int>(m_walkedPixels, totalPixelsWalked);
  495. // update walk animation and offsets
  496. updateWalkAnimation(totalPixelsWalked);
  497. updateWalkOffset(m_walkedPixels);
  498. updateWalkingTile();
  499. // terminate walk
  500. if(m_walking && m_walkTimer.ticksElapsed() >= getStepDuration())
  501. terminateWalk();
  502. }
  503. void Creature::terminateWalk()
  504. {
  505. // remove any scheduled walk update
  506. if(m_walkUpdateEvent) {
  507. m_walkUpdateEvent->cancel();
  508. m_walkUpdateEvent = nullptr;
  509. }
  510. // now the walk has ended, do any scheduled turn
  511. if(m_walkTurnDirection != Otc::InvalidDirection) {
  512. setDirection(m_walkTurnDirection);
  513. m_walkTurnDirection = Otc::InvalidDirection;
  514. }
  515. if(m_walkingTile) {
  516. m_walkingTile->removeWalkingCreature(static_self_cast<Creature>());
  517. m_walkingTile = nullptr;
  518. }
  519. m_walking = false;
  520. m_walkedPixels = 0;
  521. // reset walk animation states
  522. m_walkOffset = Point(0,0);
  523. m_walkAnimationPhase = 0;
  524. }
  525. void Creature::setName(const std::string& name)
  526. {
  527. m_nameCache.setText(name);
  528. m_name = name;
  529. }
  530. void Creature::setHealthPercent(uint8 healthPercent)
  531. {
  532. if(healthPercent > 92)
  533. m_informationColor = Color(0x00, 0xBC, 0x00);
  534. else if(healthPercent > 60)
  535. m_informationColor = Color(0x50, 0xA1, 0x50);
  536. else if(healthPercent > 30)
  537. m_informationColor = Color(0xA1, 0xA1, 0x00);
  538. else if(healthPercent > 8)
  539. m_informationColor = Color(0xBF, 0x0A, 0x0A);
  540. else if(healthPercent > 3)
  541. m_informationColor = Color(0x91, 0x0F, 0x0F);
  542. else
  543. m_informationColor = Color(0x85, 0x0C, 0x0C);
  544. m_healthPercent = healthPercent;
  545. callLuaField("onHealthPercentChange", healthPercent);
  546. if(healthPercent <= 0)
  547. onDeath();
  548. }
  549. void Creature::setDirection(Otc::Direction direction)
  550. {
  551. assert(direction != Otc::InvalidDirection);
  552. m_direction = direction;
  553. }
  554. void Creature::setOutfit(const Outfit& outfit)
  555. {
  556. Outfit oldOutfit = m_outfit;
  557. if(outfit.getCategory() != ThingCategoryCreature) {
  558. if(!g_things.isValidDatId(outfit.getAuxId(), outfit.getCategory()))
  559. return;
  560. m_outfit.setAuxId(outfit.getAuxId());
  561. m_outfit.setCategory(outfit.getCategory());
  562. } else {
  563. if(outfit.getId() > 0 && !g_things.isValidDatId(outfit.getId(), ThingCategoryCreature))
  564. return;
  565. m_outfit = outfit;
  566. }
  567. m_walkAnimationPhase = 0; // might happen when player is walking and outfit is changed.
  568. callLuaField("onOutfitChange", m_outfit, oldOutfit);
  569. }
  570. void Creature::setOutfitColor(const Color& color, int duration)
  571. {
  572. if(m_outfitColorUpdateEvent) {
  573. m_outfitColorUpdateEvent->cancel();
  574. m_outfitColorUpdateEvent = nullptr;
  575. }
  576. if(duration > 0) {
  577. Color delta = (color - m_outfitColor) / (float)duration;
  578. m_outfitColorTimer.restart();
  579. updateOutfitColor(m_outfitColor, color, delta, duration);
  580. }
  581. else
  582. m_outfitColor = color;
  583. }
  584. void Creature::updateOutfitColor(Color color, Color finalColor, Color delta, int duration)
  585. {
  586. if(m_outfitColorTimer.ticksElapsed() < duration) {
  587. m_outfitColor = color + delta * m_outfitColorTimer.ticksElapsed();
  588. auto self = static_self_cast<Creature>();
  589. m_outfitColorUpdateEvent = g_dispatcher.scheduleEvent([=] {
  590. self->updateOutfitColor(color, finalColor, delta, duration);
  591. }, 100);
  592. }
  593. else {
  594. m_outfitColor = finalColor;
  595. }
  596. }
  597. void Creature::setSpeed(uint16 speed)
  598. {
  599. uint16 oldSpeed = m_speed;
  600. m_speed = speed;
  601. // speed can change while walking (utani hur, paralyze, etc..)
  602. if(m_walking)
  603. nextWalkUpdate();
  604. callLuaField("onSpeedChange", m_speed, oldSpeed);
  605. }
  606. void Creature::setBaseSpeed(double baseSpeed)
  607. {
  608. if(m_baseSpeed != baseSpeed) {
  609. double oldBaseSpeed = m_baseSpeed;
  610. m_baseSpeed = baseSpeed;
  611. callLuaField("onBaseSpeedChange", baseSpeed, oldBaseSpeed);
  612. }
  613. }
  614. void Creature::setSkull(uint8 skull)
  615. {
  616. m_skull = skull;
  617. callLuaField("onSkullChange", m_skull);
  618. }
  619. void Creature::setShield(uint8 shield)
  620. {
  621. m_shield = shield;
  622. callLuaField("onShieldChange", m_shield);
  623. }
  624. void Creature::setEmblem(uint8 emblem)
  625. {
  626. m_emblem = emblem;
  627. callLuaField("onEmblemChange", m_emblem);
  628. }
  629. void Creature::setIcon(uint8 icon)
  630. {
  631. m_icon = icon;
  632. callLuaField("onIconChange", m_icon);
  633. }
  634. void Creature::setSkullTexture(const std::string& filename)
  635. {
  636. m_skullTexture = g_textures.getTexture(filename);
  637. }
  638. void Creature::setShieldTexture(const std::string& filename, bool blink)
  639. {
  640. m_shieldTexture = g_textures.getTexture(filename);
  641. m_showShieldTexture = true;
  642. if(blink && !m_shieldBlink) {
  643. auto self = static_self_cast<Creature>();
  644. g_dispatcher.scheduleEvent([self]() {
  645. self->updateShield();
  646. }, SHIELD_BLINK_TICKS);
  647. }
  648. m_shieldBlink = blink;
  649. }
  650. void Creature::setEmblemTexture(const std::string& filename)
  651. {
  652. m_emblemTexture = g_textures.getTexture(filename);
  653. }
  654. void Creature::setIconTexture(const std::string& filename)
  655. {
  656. m_iconTexture = g_textures.getTexture(filename);
  657. }
  658. void Creature::setSpeedFormula(double speedA, double speedB, double speedC)
  659. {
  660. m_speedFormula[Otc::SpeedFormulaA] = speedA;
  661. m_speedFormula[Otc::SpeedFormulaB] = speedB;
  662. m_speedFormula[Otc::SpeedFormulaC] = speedC;
  663. }
  664. bool Creature::hasSpeedFormula()
  665. {
  666. return m_speedFormula[Otc::SpeedFormulaA] != -1 && m_speedFormula[Otc::SpeedFormulaB] != -1
  667. && m_speedFormula[Otc::SpeedFormulaC] != -1;
  668. }
  669. void Creature::addTimedSquare(uint8 color)
  670. {
  671. m_showTimedSquare = true;
  672. m_timedSquareColor = Color::from8bit(color);
  673. // schedule removal
  674. auto self = static_self_cast<Creature>();
  675. g_dispatcher.scheduleEvent([self]() {
  676. self->removeTimedSquare();
  677. }, VOLATILE_SQUARE_DURATION);
  678. }
  679. void Creature::updateShield()
  680. {
  681. m_showShieldTexture = !m_showShieldTexture;
  682. if(m_shield != Otc::ShieldNone && m_shieldBlink) {
  683. auto self = static_self_cast<Creature>();
  684. g_dispatcher.scheduleEvent([self]() {
  685. self->updateShield();
  686. }, SHIELD_BLINK_TICKS);
  687. }
  688. else if(!m_shieldBlink)
  689. m_showShieldTexture = true;
  690. }
  691. Point Creature::getDrawOffset()
  692. {
  693. Point drawOffset;
  694. if(m_walking) {
  695. if(m_walkingTile)
  696. drawOffset -= Point(1,1) * m_walkingTile->getDrawElevation();
  697. drawOffset += m_walkOffset;
  698. } else {
  699. const TilePtr& tile = getTile();
  700. if(tile)
  701. drawOffset -= Point(1,1) * tile->getDrawElevation();
  702. }
  703. return drawOffset;
  704. }
  705. int Creature::getStepDuration(bool ignoreDiagonal, Otc::Direction dir)
  706. {
  707. int speed = m_speed;
  708. if(speed < 1)
  709. return 0;
  710. if(g_game.getFeature(Otc::GameNewSpeedLaw))
  711. speed *= 2;
  712. int groundSpeed = 0;
  713. Position tilePos;
  714. if(dir == Otc::InvalidDirection)
  715. tilePos = m_lastStepToPosition;
  716. else
  717. tilePos = m_position.translatedToDirection(dir);
  718. if(!tilePos.isValid())
  719. tilePos = m_position;
  720. const TilePtr& tile = g_map.getTile(tilePos);
  721. if(tile) {
  722. groundSpeed = tile->getGroundSpeed();
  723. if(groundSpeed == 0)
  724. groundSpeed = 150;
  725. }
  726. int interval = 1000;
  727. if(groundSpeed > 0 && speed > 0)
  728. interval = 1000 * groundSpeed;
  729. if(g_game.getFeature(Otc::GameNewSpeedLaw) && hasSpeedFormula()) {
  730. int formulatedSpeed = 1;
  731. if(speed > -m_speedFormula[Otc::SpeedFormulaB]) {
  732. formulatedSpeed = std::max<int>(1, (int)floor((m_speedFormula[Otc::SpeedFormulaA] * log((speed / 2)
  733. + m_speedFormula[Otc::SpeedFormulaB]) + m_speedFormula[Otc::SpeedFormulaC]) + 0.5));
  734. }
  735. interval = std::floor(interval / (double)formulatedSpeed);
  736. }
  737. else
  738. interval /= speed;
  739. if(g_game.getClientVersion() >= 900)
  740. interval = (interval / g_game.getServerBeat()) * g_game.getServerBeat();
  741. float factor = 3;
  742. if(g_game.getClientVersion() <= 810)
  743. factor = 2;
  744. interval = std::max<int>(interval, g_game.getServerBeat());
  745. if(!ignoreDiagonal && (m_lastStepDirection == Otc::NorthWest || m_lastStepDirection == Otc::NorthEast ||
  746. m_lastStepDirection == Otc::SouthWest || m_lastStepDirection == Otc::SouthEast))
  747. interval *= factor;
  748. return interval;
  749. }
  750. Point Creature::getDisplacement()
  751. {
  752. if(m_outfit.getCategory() == ThingCategoryEffect)
  753. return Point(8, 8);
  754. else if(m_outfit.getCategory() == ThingCategoryItem)
  755. return Point(0, 0);
  756. return Thing::getDisplacement();
  757. }
  758. int Creature::getDisplacementX()
  759. {
  760. if(m_outfit.getCategory() == ThingCategoryEffect)
  761. return 8;
  762. else if(m_outfit.getCategory() == ThingCategoryItem)
  763. return 0;
  764. if(m_outfit.getMount() != 0) {
  765. auto datType = g_things.rawGetThingType(m_outfit.getMount(), ThingCategoryCreature);
  766. return datType->getDisplacementX();
  767. }
  768. return Thing::getDisplacementX();
  769. }
  770. int Creature::getDisplacementY()
  771. {
  772. if(m_outfit.getCategory() == ThingCategoryEffect)
  773. return 8;
  774. else if(m_outfit.getCategory() == ThingCategoryItem)
  775. return 0;
  776. if(m_outfit.getMount() != 0) {
  777. auto datType = g_things.rawGetThingType(m_outfit.getMount(), ThingCategoryCreature);
  778. return datType->getDisplacementY();
  779. }
  780. return Thing::getDisplacementY();
  781. }
  782. int Creature::getExactSize(int layer, int xPattern, int yPattern, int zPattern, int animationPhase)
  783. {
  784. int exactSize = 0;
  785. animationPhase = 0;
  786. xPattern = Otc::South;
  787. zPattern = 0;
  788. if(m_outfit.getMount() != 0)
  789. zPattern = 1;
  790. for(yPattern = 0; yPattern < getNumPatternY(); yPattern++) {
  791. if(yPattern > 0 && !(m_outfit.getAddons() & (1 << (yPattern-1))))
  792. continue;
  793. for(layer = 0; layer < getLayers(); ++layer)
  794. exactSize = std::max<int>(exactSize, Thing::getExactSize(layer, xPattern, yPattern, zPattern, animationPhase));
  795. }
  796. return exactSize;
  797. }
  798. const ThingTypePtr& Creature::getThingType()
  799. {
  800. return g_things.getThingType(m_outfit.getId(), ThingCategoryCreature);
  801. }
  802. ThingType* Creature::rawGetThingType()
  803. {
  804. return g_things.rawGetThingType(m_outfit.getId(), ThingCategoryCreature);
  805. }