CObjectHandler.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. /*
  2. * CObjectHandler.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "CObjectHandler.h"
  12. #include "../NetPacks.h"
  13. #include "../CGeneralTextHandler.h"
  14. #include "../CHeroHandler.h"
  15. #include "../CSoundBase.h"
  16. #include "../filesystem/ResourceID.h"
  17. #include "../IGameCallback.h"
  18. #include "../CGameState.h"
  19. #include "../StringConstants.h"
  20. #include "../mapping/CMap.h"
  21. #include "../TerrainHandler.h"
  22. #include "CObjectClassesHandler.h"
  23. #include "CGTownInstance.h"
  24. #include "../serializer/JsonSerializeFormat.h"
  25. VCMI_LIB_NAMESPACE_BEGIN
  26. IGameCallback * IObjectInterface::cb = nullptr;
  27. ///helpers
  28. void IObjectInterface::openWindow(const EOpenWindowMode type, const int id1, const int id2)
  29. {
  30. OpenWindow ow;
  31. ow.window = type;
  32. ow.id1 = id1;
  33. ow.id2 = id2;
  34. IObjectInterface::cb->sendAndApply(&ow);
  35. }
  36. void IObjectInterface::showInfoDialog(const ui32 txtID, const ui16 soundID, EInfoWindowMode mode) const
  37. {
  38. InfoWindow iw;
  39. iw.soundID = soundID;
  40. iw.player = getOwner();
  41. iw.type = mode;
  42. iw.text.addTxt(MetaString::ADVOB_TXT,txtID);
  43. IObjectInterface::cb->sendAndApply(&iw);
  44. }
  45. ///IObjectInterface
  46. void IObjectInterface::onHeroVisit(const CGHeroInstance * h) const
  47. {}
  48. void IObjectInterface::onHeroLeave(const CGHeroInstance * h) const
  49. {}
  50. void IObjectInterface::newTurn(CRandomGenerator & rand) const
  51. {}
  52. void IObjectInterface::initObj(CRandomGenerator & rand)
  53. {}
  54. void IObjectInterface::setProperty( ui8 what, ui32 val )
  55. {}
  56. bool IObjectInterface::wasVisited (PlayerColor player) const
  57. {
  58. return false;
  59. }
  60. bool IObjectInterface::wasVisited (const CGHeroInstance * h) const
  61. {
  62. return false;
  63. }
  64. void IObjectInterface::postInit()
  65. {}
  66. void IObjectInterface::preInit()
  67. {}
  68. void IObjectInterface::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  69. {}
  70. void IObjectInterface::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  71. {}
  72. void IObjectInterface::garrisonDialogClosed(const CGHeroInstance *hero) const
  73. {}
  74. void IObjectInterface::heroLevelUpDone(const CGHeroInstance *hero) const
  75. {}
  76. CObjectHandler::CObjectHandler()
  77. {
  78. logGlobal->trace("\t\tReading resources prices ");
  79. const JsonNode config2(ResourceID("config/resources.json"));
  80. for(const JsonNode &price : config2["resources_prices"].Vector())
  81. {
  82. resVals.push_back(static_cast<ui32>(price.Float()));
  83. }
  84. logGlobal->trace("\t\tDone loading resource prices!");
  85. }
  86. //TODO: remove constructor
  87. CGObjectInstance::CGObjectInstance():
  88. pos(-1,-1,-1),
  89. ID(Obj::NO_OBJ),
  90. subID(-1),
  91. tempOwner(PlayerColor::UNFLAGGABLE),
  92. blockVisit(false)
  93. {
  94. }
  95. //must be instantiated in .cpp file for access to complete types of all member fields
  96. CGObjectInstance::~CGObjectInstance() = default;
  97. int32_t CGObjectInstance::getObjGroupIndex() const
  98. {
  99. return ID.num;
  100. }
  101. int32_t CGObjectInstance::getObjTypeIndex() const
  102. {
  103. return subID;
  104. }
  105. int3 CGObjectInstance::getPosition() const
  106. {
  107. return pos;
  108. }
  109. void CGObjectInstance::setOwner(const PlayerColor & ow)
  110. {
  111. tempOwner = ow;
  112. }
  113. int CGObjectInstance::getWidth() const//returns width of object graphic in tiles
  114. {
  115. return appearance->getWidth();
  116. }
  117. int CGObjectInstance::getHeight() const //returns height of object graphic in tiles
  118. {
  119. return appearance->getHeight();
  120. }
  121. bool CGObjectInstance::visitableAt(int x, int y) const //returns true if object is visitable at location (x, y) form left top tile of image (x, y in tiles)
  122. {
  123. return appearance->isVisitableAt(pos.x - x, pos.y - y);
  124. }
  125. bool CGObjectInstance::blockingAt(int x, int y) const
  126. {
  127. return appearance->isBlockedAt(pos.x - x, pos.y - y);
  128. }
  129. bool CGObjectInstance::coveringAt(int x, int y) const
  130. {
  131. return appearance->isVisibleAt(pos.x - x, pos.y - y);
  132. }
  133. std::set<int3> CGObjectInstance::getBlockedPos() const
  134. {
  135. std::set<int3> ret;
  136. for(int w=0; w<getWidth(); ++w)
  137. {
  138. for(int h=0; h<getHeight(); ++h)
  139. {
  140. if(appearance->isBlockedAt(w, h))
  141. ret.insert(int3(pos.x - w, pos.y - h, pos.z));
  142. }
  143. }
  144. return ret;
  145. }
  146. std::set<int3> CGObjectInstance::getBlockedOffsets() const
  147. {
  148. return appearance->getBlockedOffsets();
  149. }
  150. void CGObjectInstance::setType(si32 ID, si32 subID)
  151. {
  152. auto position = visitablePos();
  153. auto oldOffset = getVisitableOffset();
  154. auto &tile = cb->gameState()->map->getTile(position);
  155. //recalculate blockvis tiles - new appearance might have different blockmap than before
  156. cb->gameState()->map->removeBlockVisTiles(this, true);
  157. auto handler = VLC->objtypeh->getHandlerFor(ID, subID);
  158. if(!handler)
  159. {
  160. logGlobal->error("Unknown object type %d:%d at %s", ID, subID, visitablePos().toString());
  161. return;
  162. }
  163. if(!handler->getTemplates(tile.terType->getId()).empty())
  164. {
  165. appearance = handler->getTemplates(tile.terType->getId())[0];
  166. }
  167. else
  168. {
  169. logGlobal->warn("Object %d:%d at %s has no templates suitable for terrain %s", ID, subID, visitablePos().toString(), tile.terType->getNameTranslated());
  170. appearance = handler->getTemplates()[0]; // get at least some appearance since alternative is crash
  171. }
  172. if(this->ID == Obj::PRISON && ID == Obj::HERO)
  173. {
  174. auto newOffset = getVisitableOffset();
  175. // FIXME: potentially unused code - setType is NOT called when releasing hero from prison
  176. // instead, appearance update & pos adjustment occurs in GiveHero::applyGs
  177. // adjust position since hero and prison may have different visitable offset
  178. pos = pos - oldOffset + newOffset;
  179. }
  180. this->ID = Obj(ID);
  181. this->subID = subID;
  182. cb->gameState()->map->addBlockVisTiles(this);
  183. }
  184. void CGObjectInstance::initObj(CRandomGenerator & rand)
  185. {
  186. switch(ID)
  187. {
  188. case Obj::TAVERN:
  189. blockVisit = true;
  190. break;
  191. }
  192. }
  193. void CGObjectInstance::setProperty( ui8 what, ui32 val )
  194. {
  195. setPropertyDer(what, val); // call this before any actual changes (needed at least for dwellings)
  196. switch(what)
  197. {
  198. case ObjProperty::OWNER:
  199. tempOwner = PlayerColor(val);
  200. break;
  201. case ObjProperty::BLOCKVIS:
  202. blockVisit = val;
  203. break;
  204. case ObjProperty::ID:
  205. ID = Obj(val);
  206. break;
  207. case ObjProperty::SUBID:
  208. subID = val;
  209. break;
  210. }
  211. }
  212. void CGObjectInstance::setPropertyDer( ui8 what, ui32 val )
  213. {}
  214. int3 CGObjectInstance::getSightCenter() const
  215. {
  216. return visitablePos();
  217. }
  218. int CGObjectInstance::getSightRadius() const
  219. {
  220. return 3;
  221. }
  222. int3 CGObjectInstance::getVisitableOffset() const
  223. {
  224. return appearance->getVisitableOffset();
  225. }
  226. void CGObjectInstance::giveDummyBonus(const ObjectInstanceID & heroID, ui8 duration) const
  227. {
  228. GiveBonus gbonus;
  229. gbonus.bonus.type = Bonus::NONE;
  230. gbonus.id = heroID.getNum();
  231. gbonus.bonus.duration = static_cast<Bonus::BonusDuration>(duration);
  232. gbonus.bonus.source = Bonus::OBJECT;
  233. gbonus.bonus.sid = ID;
  234. cb->giveHeroBonus(&gbonus);
  235. }
  236. std::string CGObjectInstance::getObjectName() const
  237. {
  238. return VLC->objtypeh->getObjectName(ID, subID);
  239. }
  240. boost::optional<std::string> CGObjectInstance::getAmbientSound() const
  241. {
  242. const auto & sounds = VLC->objtypeh->getObjectSounds(ID, subID).ambient;
  243. if(!sounds.empty())
  244. return sounds.front(); // TODO: Support randomization of ambient sounds
  245. return boost::none;
  246. }
  247. boost::optional<std::string> CGObjectInstance::getVisitSound() const
  248. {
  249. const auto & sounds = VLC->objtypeh->getObjectSounds(ID, subID).visit;
  250. if(!sounds.empty())
  251. return *RandomGeneratorUtil::nextItem(sounds, CRandomGenerator::getDefault());
  252. return boost::none;
  253. }
  254. boost::optional<std::string> CGObjectInstance::getRemovalSound() const
  255. {
  256. const auto & sounds = VLC->objtypeh->getObjectSounds(ID, subID).removal;
  257. if(!sounds.empty())
  258. return *RandomGeneratorUtil::nextItem(sounds, CRandomGenerator::getDefault());
  259. return boost::none;
  260. }
  261. std::string CGObjectInstance::getHoverText(PlayerColor player) const
  262. {
  263. auto text = getObjectName();
  264. if (tempOwner.isValidPlayer())
  265. text += "\n" + VLC->generaltexth->arraytxt[23 + tempOwner.getNum()];
  266. return text;
  267. }
  268. std::string CGObjectInstance::getHoverText(const CGHeroInstance * hero) const
  269. {
  270. return getHoverText(hero->tempOwner);
  271. }
  272. void CGObjectInstance::onHeroVisit( const CGHeroInstance * h ) const
  273. {
  274. switch(ID)
  275. {
  276. case Obj::HILL_FORT:
  277. {
  278. openWindow(EOpenWindowMode::HILL_FORT_WINDOW,id.getNum(),h->id.getNum());
  279. }
  280. break;
  281. case Obj::SANCTUARY:
  282. {
  283. //You enter the sanctuary and immediately feel as if a great weight has been lifted off your shoulders. You feel safe here.
  284. h->showInfoDialog(114);
  285. }
  286. break;
  287. case Obj::TAVERN:
  288. {
  289. openWindow(EOpenWindowMode::TAVERN_WINDOW,h->id.getNum(),id.getNum());
  290. }
  291. break;
  292. }
  293. }
  294. int3 CGObjectInstance::visitablePos() const
  295. {
  296. return pos - getVisitableOffset();
  297. }
  298. bool CGObjectInstance::isVisitable() const
  299. {
  300. return appearance->isVisitable();
  301. }
  302. bool CGObjectInstance::passableFor(PlayerColor color) const
  303. {
  304. return false;
  305. }
  306. void CGObjectInstance::updateFrom(const JsonNode & data)
  307. {
  308. }
  309. void CGObjectInstance::serializeJson(JsonSerializeFormat & handler)
  310. {
  311. //only save here, loading is handled by map loader
  312. if(handler.saving)
  313. {
  314. handler.serializeString("type", typeName);
  315. handler.serializeString("subtype", subTypeName);
  316. handler.serializeInt("x", pos.x);
  317. handler.serializeInt("y", pos.y);
  318. handler.serializeInt("l", pos.z);
  319. JsonNode app;
  320. appearance->writeJson(app, false);
  321. handler.serializeRaw("template",app, boost::none);
  322. }
  323. {
  324. auto options = handler.enterStruct("options");
  325. serializeJsonOptions(handler);
  326. }
  327. }
  328. void CGObjectInstance::afterAddToMap(CMap * map)
  329. {
  330. //nothing here
  331. }
  332. void CGObjectInstance::afterRemoveFromMap(CMap * map)
  333. {
  334. //nothing here
  335. }
  336. void CGObjectInstance::serializeJsonOptions(JsonSerializeFormat & handler)
  337. {
  338. //nothing here
  339. }
  340. void CGObjectInstance::serializeJsonOwner(JsonSerializeFormat & handler)
  341. {
  342. ui8 temp = tempOwner.getNum();
  343. handler.serializeEnum("owner", temp, PlayerColor::NEUTRAL.getNum(), GameConstants::PLAYER_COLOR_NAMES);
  344. if(!handler.saving)
  345. tempOwner = PlayerColor(temp);
  346. }
  347. BattleField CGObjectInstance::getBattlefield() const
  348. {
  349. return VLC->objtypeh->getHandlerFor(ID, subID)->getBattlefield();
  350. }
  351. CGObjectInstanceBySubIdFinder::CGObjectInstanceBySubIdFinder(CGObjectInstance * obj) : obj(obj)
  352. {
  353. }
  354. bool CGObjectInstanceBySubIdFinder::operator()(CGObjectInstance * obj) const
  355. {
  356. return this->obj->subID == obj->subID;
  357. }
  358. int3 IBoatGenerator::bestLocation() const
  359. {
  360. std::vector<int3> offsets;
  361. getOutOffsets(offsets);
  362. for (auto & offset : offsets)
  363. {
  364. if(const TerrainTile *tile = IObjectInterface::cb->getTile(o->pos + offset, false)) //tile is in the map
  365. {
  366. if(tile->terType->isWater() && (!tile->blocked || tile->blockingObjects.front()->ID == Obj::BOAT)) //and is water and is not blocked or is blocked by boat
  367. return o->pos + offset;
  368. }
  369. }
  370. return int3 (-1,-1,-1);
  371. }
  372. IBoatGenerator::EGeneratorState IBoatGenerator::shipyardStatus() const
  373. {
  374. int3 tile = bestLocation();
  375. const TerrainTile *t = IObjectInterface::cb->getTile(tile);
  376. if(!t)
  377. return TILE_BLOCKED; //no available water
  378. else if(t->blockingObjects.empty())
  379. return GOOD; //OK
  380. else if(t->blockingObjects.front()->ID == Obj::BOAT)
  381. return BOAT_ALREADY_BUILT; //blocked with boat
  382. else
  383. return TILE_BLOCKED; //blocked
  384. }
  385. int IBoatGenerator::getBoatType() const
  386. {
  387. //We make good ships by default
  388. return 1;
  389. }
  390. IBoatGenerator::IBoatGenerator(const CGObjectInstance *O)
  391. : o(O)
  392. {
  393. }
  394. void IBoatGenerator::getProblemText(MetaString &out, const CGHeroInstance *visitor) const
  395. {
  396. switch(shipyardStatus())
  397. {
  398. case BOAT_ALREADY_BUILT:
  399. out.addTxt(MetaString::GENERAL_TXT, 51);
  400. break;
  401. case TILE_BLOCKED:
  402. if(visitor)
  403. {
  404. out.addTxt(MetaString::GENERAL_TXT, 134);
  405. out.addReplacement(visitor->getNameTranslated());
  406. }
  407. else
  408. out.addTxt(MetaString::ADVOB_TXT, 189);
  409. break;
  410. case NO_WATER:
  411. logGlobal->error("Shipyard without water! %s \t %d", o->pos.toString(), o->id.getNum());
  412. return;
  413. }
  414. }
  415. void IShipyard::getBoatCost(TResources & cost) const
  416. {
  417. cost[EGameResID::WOOD] = 10;
  418. cost[EGameResID::GOLD] = 1000;
  419. }
  420. IShipyard::IShipyard(const CGObjectInstance *O)
  421. : IBoatGenerator(O)
  422. {
  423. }
  424. IShipyard * IShipyard::castFrom( CGObjectInstance *obj )
  425. {
  426. if(!obj)
  427. return nullptr;
  428. if(obj->ID == Obj::TOWN)
  429. {
  430. return dynamic_cast<CGTownInstance *>(obj);
  431. }
  432. else if(obj->ID == Obj::SHIPYARD)
  433. {
  434. return dynamic_cast<CGShipyard *>(obj);
  435. }
  436. else
  437. {
  438. return nullptr;
  439. }
  440. }
  441. const IShipyard * IShipyard::castFrom( const CGObjectInstance *obj )
  442. {
  443. return castFrom(const_cast<CGObjectInstance*>(obj));
  444. }
  445. VCMI_LIB_NAMESPACE_END