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 30KB

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