2
0

ObjectTemplate.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  1. /*
  2. * ObjectTemplate.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 "CObjectClassesHandler.h"
  12. #include "../filesystem/Filesystem.h"
  13. #include "../filesystem/CBinaryReader.h"
  14. #include "../VCMI_Lib.h"
  15. #include "../GameConstants.h"
  16. #include "../StringConstants.h"
  17. #include "../CGeneralTextHandler.h"
  18. #include "CObjectHandler.h"
  19. #include "../CModHandler.h"
  20. #include "../JsonNode.h"
  21. #include "../Terrain.h"
  22. #include "CRewardableConstructor.h"
  23. VCMI_LIB_NAMESPACE_BEGIN
  24. static bool isOnVisitableFromTopList(int identifier, int type)
  25. {
  26. if(type == 2 || type == 3 || type == 4 || type == 5) //creature, hero, artifact, resource
  27. return true;
  28. static const Obj visitableFromTop[] =
  29. {Obj::FLOTSAM,
  30. Obj::SEA_CHEST,
  31. Obj::SHIPWRECK_SURVIVOR,
  32. Obj::BUOY,
  33. Obj::OCEAN_BOTTLE,
  34. Obj::BOAT,
  35. Obj::WHIRLPOOL,
  36. Obj::GARRISON,
  37. Obj::GARRISON2,
  38. Obj::SCHOLAR,
  39. Obj::CAMPFIRE,
  40. Obj::BORDERGUARD,
  41. Obj::BORDER_GATE,
  42. Obj::QUEST_GUARD,
  43. Obj::CORPSE
  44. };
  45. return vstd::find_pos(visitableFromTop, identifier) != -1;
  46. }
  47. ObjectTemplate::ObjectTemplate():
  48. visitDir(8|16|32|64|128), // all but top
  49. id(Obj::NO_OBJ),
  50. subid(0),
  51. printPriority(0),
  52. width(0),
  53. height(0),
  54. visitable(false)
  55. {
  56. }
  57. ObjectTemplate::ObjectTemplate(const ObjectTemplate& other):
  58. visitDir(other.visitDir),
  59. allowedTerrains(other.allowedTerrains),
  60. id(other.id),
  61. subid(other.subid),
  62. printPriority(other.printPriority),
  63. animationFile(other.animationFile),
  64. editorAnimationFile(other.editorAnimationFile),
  65. stringID(other.stringID),
  66. width(other.width),
  67. height(other.height),
  68. visitable(other.visitable),
  69. blockedOffsets(other.blockedOffsets),
  70. blockMapOffset(other.blockMapOffset),
  71. visitableOffset(other.visitableOffset)
  72. {
  73. //default copy constructor is failing with usedTiles this for unknown reason
  74. usedTiles.resize(other.usedTiles.size());
  75. for(size_t i = 0; i < usedTiles.size(); i++)
  76. std::copy(other.usedTiles[i].begin(), other.usedTiles[i].end(), std::back_inserter(usedTiles[i]));
  77. }
  78. ObjectTemplate & ObjectTemplate::operator=(const ObjectTemplate & rhs)
  79. {
  80. visitDir = rhs.visitDir;
  81. allowedTerrains = rhs.allowedTerrains;
  82. id = rhs.id;
  83. subid = rhs.subid;
  84. printPriority = rhs.printPriority;
  85. animationFile = rhs.animationFile;
  86. editorAnimationFile = rhs.editorAnimationFile;
  87. stringID = rhs.stringID;
  88. width = rhs.width;
  89. height = rhs.height;
  90. visitable = rhs.visitable;
  91. blockedOffsets = rhs.blockedOffsets;
  92. blockMapOffset = rhs.blockMapOffset;
  93. visitableOffset = rhs.visitableOffset;
  94. usedTiles.clear();
  95. usedTiles.resize(rhs.usedTiles.size());
  96. for(size_t i = 0; i < usedTiles.size(); i++)
  97. std::copy(rhs.usedTiles[i].begin(), rhs.usedTiles[i].end(), std::back_inserter(usedTiles[i]));
  98. return *this;
  99. }
  100. void ObjectTemplate::afterLoadFixup()
  101. {
  102. if(id == Obj::EVENT)
  103. {
  104. setSize(1,1);
  105. usedTiles[0][0] = VISITABLE;
  106. visitDir = 0xFF;
  107. }
  108. boost::algorithm::replace_all(animationFile, "\\", "/");
  109. boost::algorithm::replace_all(editorAnimationFile, "\\", "/");
  110. }
  111. void ObjectTemplate::readTxt(CLegacyConfigParser & parser)
  112. {
  113. std::string data = parser.readString();
  114. std::vector<std::string> strings;
  115. boost::split(strings, data, boost::is_any_of(" "));
  116. assert(strings.size() == 9);
  117. animationFile = strings[0];
  118. stringID = strings[0];
  119. std::string & blockStr = strings[1]; //block map, 0 = blocked, 1 = unblocked
  120. std::string & visitStr = strings[2]; //visit map, 1 = visitable, 0 = not visitable
  121. assert(blockStr.size() == 6*8);
  122. assert(visitStr.size() == 6*8);
  123. setSize(8, 6);
  124. for(size_t i = 0; i < 6; i++) // 6 rows
  125. {
  126. for(size_t j = 0; j < 8; j++) // 8 columns
  127. {
  128. auto & tile = usedTiles[i][j];
  129. tile |= VISIBLE; // assume that all tiles are visible
  130. if (blockStr[i*8 + j] == '0')
  131. tile |= BLOCKED;
  132. if (visitStr[i*8 + j] == '1')
  133. tile |= VISITABLE;
  134. }
  135. }
  136. // strings[3] most likely - terrains on which this object can be placed in editor.
  137. // e.g. Whirpool can be placed manually only on water while mines can be placed everywhere despite terrain-specific gfx
  138. // so these two fields can be interpreted as "strong affinity" and "weak affinity" towards terrains
  139. std::string & terrStr = strings[4]; // allowed terrains, 1 = object can be placed on this terrain
  140. assert(terrStr.size() == TerrainId(ETerrainId::ROCK).getNum()); // all terrains but rock - counting from 0
  141. for(TerrainId i = TerrainId(0); i < ETerrainId::ROCK; ++i)
  142. {
  143. if (terrStr[8-i.getNum()] == '1')
  144. allowedTerrains.insert(i);
  145. }
  146. //assuming that object can be placed on other land terrains
  147. anyTerrain = allowedTerrains.size() >= 8 && !allowedTerrains.count(ETerrainId::WATER);
  148. id = Obj(boost::lexical_cast<int>(strings[5]));
  149. subid = boost::lexical_cast<int>(strings[6]);
  150. int type = boost::lexical_cast<int>(strings[7]);
  151. printPriority = boost::lexical_cast<int>(strings[8]) * 100; // to have some space in future
  152. if (isOnVisitableFromTopList(id, type))
  153. visitDir = 0xff;
  154. else
  155. visitDir = (8|16|32|64|128);
  156. readMsk();
  157. recalculate();
  158. }
  159. void ObjectTemplate::readMsk()
  160. {
  161. ResourceID resID("SPRITES/" + animationFile, EResType::MASK);
  162. if (CResourceHandler::get()->existsResource(resID))
  163. {
  164. auto msk = CResourceHandler::get()->load(resID)->readAll();
  165. setSize(msk.first.get()[0], msk.first.get()[1]);
  166. }
  167. else //maximum possible size of H3 object //TODO: remove hardcode and move this data into modding system
  168. {
  169. setSize(8, 6);
  170. }
  171. }
  172. void ObjectTemplate::readMap(CBinaryReader & reader)
  173. {
  174. animationFile = reader.readString();
  175. setSize(8, 6);
  176. ui8 blockMask[6];
  177. ui8 visitMask[6];
  178. for(auto & byte : blockMask)
  179. byte = reader.readUInt8();
  180. for(auto & byte : visitMask)
  181. byte = reader.readUInt8();
  182. for(size_t i = 0; i < 6; i++) // 6 rows
  183. {
  184. for(size_t j = 0; j < 8; j++) // 8 columns
  185. {
  186. auto & tile = usedTiles[5 - i][7 - j];
  187. tile |= VISIBLE; // assume that all tiles are visible
  188. if (((blockMask[i] >> j) & 1 ) == 0)
  189. tile |= BLOCKED;
  190. if (((visitMask[i] >> j) & 1 ) != 0)
  191. tile |= VISITABLE;
  192. }
  193. }
  194. reader.readUInt16();
  195. ui16 terrMask = reader.readUInt16();
  196. for(TerrainId i = ETerrainId::FIRST_REGULAR_TERRAIN; i < ETerrainId::ORIGINAL_TERRAIN_COUNT; ++i)
  197. {
  198. if (((terrMask >> i.getNum()) & 1 ) != 0)
  199. allowedTerrains.insert(i);
  200. }
  201. //assuming that object can be placed on other land terrains
  202. anyTerrain = allowedTerrains.size() >= 8 && !allowedTerrains.count(ETerrainId::WATER);
  203. id = Obj(reader.readUInt32());
  204. subid = reader.readUInt32();
  205. int type = reader.readUInt8();
  206. printPriority = reader.readUInt8() * 100; // to have some space in future
  207. if (isOnVisitableFromTopList(id, type))
  208. visitDir = 0xff;
  209. else
  210. visitDir = (8|16|32|64|128);
  211. reader.skip(16);
  212. readMsk();
  213. afterLoadFixup();
  214. recalculate();
  215. }
  216. void ObjectTemplate::readJson(const JsonNode &node, const bool withTerrain)
  217. {
  218. animationFile = node["animation"].String();
  219. editorAnimationFile = node["editorAnimation"].String();
  220. const JsonVector & visitDirs = node["visitableFrom"].Vector();
  221. if (!visitDirs.empty())
  222. {
  223. if (visitDirs[0].String()[0] == '+') visitDir |= 1;
  224. if (visitDirs[0].String()[1] == '+') visitDir |= 2;
  225. if (visitDirs[0].String()[2] == '+') visitDir |= 4;
  226. if (visitDirs[1].String()[2] == '+') visitDir |= 8;
  227. if (visitDirs[2].String()[2] == '+') visitDir |= 16;
  228. if (visitDirs[2].String()[1] == '+') visitDir |= 32;
  229. if (visitDirs[2].String()[0] == '+') visitDir |= 64;
  230. if (visitDirs[1].String()[0] == '+') visitDir |= 128;
  231. }
  232. else
  233. visitDir = 0x00;
  234. if(withTerrain && !node["allowedTerrains"].isNull())
  235. {
  236. for(auto& entry : node["allowedTerrains"].Vector())
  237. {
  238. VLC->modh->identifiers.requestIdentifier("terrain", entry, [this](int32_t identifier){
  239. allowedTerrains.insert(TerrainId(identifier));
  240. });
  241. }
  242. anyTerrain = false;
  243. }
  244. else
  245. {
  246. anyTerrain = true;
  247. }
  248. if(withTerrain && allowedTerrains.empty())
  249. logGlobal->warn("Loaded template %s without allowed terrains!", animationFile);
  250. auto charToTile = [&](const char & ch) -> ui8
  251. {
  252. switch (ch)
  253. {
  254. case ' ' : return 0;
  255. case '0' : return 0;
  256. case 'V' : return VISIBLE;
  257. case 'B' : return VISIBLE | BLOCKED;
  258. case 'H' : return BLOCKED;
  259. case 'A' : return VISIBLE | BLOCKED | VISITABLE;
  260. case 'T' : return BLOCKED | VISITABLE;
  261. default:
  262. logGlobal->error("Unrecognized char %s in template mask", ch);
  263. return 0;
  264. }
  265. };
  266. const JsonVector & mask = node["mask"].Vector();
  267. size_t height = mask.size();
  268. size_t width = 0;
  269. for(auto & line : mask)
  270. vstd::amax(width, line.String().size());
  271. setSize((ui32)width, (ui32)height);
  272. for(size_t i = 0; i < mask.size(); i++)
  273. {
  274. const std::string & line = mask[i].String();
  275. for(size_t j = 0; j < line.size(); j++)
  276. usedTiles[mask.size() - 1 - i][line.size() - 1 - j] = charToTile(line[j]);
  277. }
  278. printPriority = static_cast<si32>(node["zIndex"].Float());
  279. afterLoadFixup();
  280. recalculate();
  281. }
  282. void ObjectTemplate::writeJson(JsonNode & node, const bool withTerrain) const
  283. {
  284. node["animation"].String() = animationFile;
  285. node["editorAnimation"].String() = editorAnimationFile;
  286. if(visitDir != 0x0 && isVisitable())
  287. {
  288. JsonVector & visitDirs = node["visitableFrom"].Vector();
  289. visitDirs.resize(3);
  290. visitDirs[0].String().resize(3);
  291. visitDirs[1].String().resize(3);
  292. visitDirs[2].String().resize(3);
  293. visitDirs[0].String()[0] = (visitDir & 1) ? '+' : '-';
  294. visitDirs[0].String()[1] = (visitDir & 2) ? '+' : '-';
  295. visitDirs[0].String()[2] = (visitDir & 4) ? '+' : '-';
  296. visitDirs[1].String()[2] = (visitDir & 8) ? '+' : '-';
  297. visitDirs[2].String()[2] = (visitDir & 16) ? '+' : '-';
  298. visitDirs[2].String()[1] = (visitDir & 32) ? '+' : '-';
  299. visitDirs[2].String()[0] = (visitDir & 64) ? '+' : '-';
  300. visitDirs[1].String()[0] = (visitDir & 128) ? '+' : '-';
  301. visitDirs[1].String()[1] = '-';
  302. }
  303. if(withTerrain)
  304. {
  305. //assumed that ROCK and WATER terrains are not included
  306. if(allowedTerrains.size() < (VLC->terrainTypeHandler->objects.size() - 2))
  307. {
  308. JsonVector & data = node["allowedTerrains"].Vector();
  309. for(auto type : allowedTerrains)
  310. {
  311. JsonNode value(JsonNode::JsonType::DATA_STRING);
  312. value.String() = VLC->terrainTypeHandler->getById(type)->name;
  313. data.push_back(value);
  314. }
  315. }
  316. }
  317. auto tileToChar = [&](const ui8 & tile) -> char
  318. {
  319. if(tile & VISIBLE)
  320. {
  321. if(tile & BLOCKED)
  322. {
  323. if(tile & VISITABLE)
  324. return 'A';
  325. else
  326. return 'B';
  327. }
  328. else
  329. return 'V';
  330. }
  331. else
  332. {
  333. if(tile & BLOCKED)
  334. {
  335. if(tile & VISITABLE)
  336. return 'T';
  337. else
  338. return 'H';
  339. }
  340. else
  341. return '0';
  342. }
  343. };
  344. size_t height = getHeight();
  345. size_t width = getWidth();
  346. JsonVector & mask = node["mask"].Vector();
  347. for(size_t i=0; i < height; i++)
  348. {
  349. JsonNode lineNode(JsonNode::JsonType::DATA_STRING);
  350. std::string & line = lineNode.String();
  351. line.resize(width);
  352. for(size_t j=0; j < width; j++)
  353. line[j] = tileToChar(usedTiles[height - 1 - i][width - 1 - j]);
  354. mask.push_back(lineNode);
  355. }
  356. if(printPriority != 0)
  357. node["zIndex"].Float() = printPriority;
  358. }
  359. void ObjectTemplate::calculateWidth()
  360. {
  361. //TODO: Use 2D array
  362. for(const auto& row : usedTiles) //copy is expensive
  363. {
  364. width = std::max<ui32>(width, (ui32)row.size());
  365. }
  366. }
  367. void ObjectTemplate::calculateHeight()
  368. {
  369. //TODO: Use 2D array
  370. height = static_cast<ui32>(usedTiles.size());
  371. }
  372. void ObjectTemplate::setSize(ui32 width, ui32 height)
  373. {
  374. usedTiles.resize(height);
  375. for(auto & line : usedTiles)
  376. line.resize(width, 0);
  377. }
  378. void ObjectTemplate::calculateVsitable()
  379. {
  380. for(auto& line : usedTiles)
  381. {
  382. for(auto& tile : line)
  383. {
  384. if (tile & VISITABLE)
  385. {
  386. visitable = true;
  387. return;
  388. }
  389. }
  390. }
  391. visitable = false;
  392. }
  393. bool ObjectTemplate::isWithin(si32 X, si32 Y) const
  394. {
  395. if (X < 0 || Y < 0)
  396. return false;
  397. return !(X >= (si32)getWidth() || Y >= (si32)getHeight());
  398. }
  399. bool ObjectTemplate::isVisitableAt(si32 X, si32 Y) const
  400. {
  401. return isWithin(X, Y) && usedTiles[Y][X] & VISITABLE;
  402. }
  403. bool ObjectTemplate::isVisibleAt(si32 X, si32 Y) const
  404. {
  405. return isWithin(X, Y) && usedTiles[Y][X] & VISIBLE;
  406. }
  407. bool ObjectTemplate::isBlockedAt(si32 X, si32 Y) const
  408. {
  409. return isWithin(X, Y) && usedTiles[Y][X] & BLOCKED;
  410. }
  411. void ObjectTemplate::calculateBlockedOffsets()
  412. {
  413. blockedOffsets.clear();
  414. for(int w = 0; w < (int)getWidth(); ++w)
  415. {
  416. for(int h = 0; h < (int)getHeight(); ++h)
  417. {
  418. if (isBlockedAt(w, h))
  419. blockedOffsets.insert(int3(-w, -h, 0));
  420. }
  421. }
  422. }
  423. void ObjectTemplate::calculateBlockMapOffset()
  424. {
  425. for(int w = 0; w < (int)getWidth(); ++w)
  426. {
  427. for(int h = 0; h < (int)getHeight(); ++h)
  428. {
  429. if (isBlockedAt(w, h))
  430. {
  431. blockMapOffset = int3(w, h, 0);
  432. return;
  433. }
  434. }
  435. }
  436. blockMapOffset = int3(0, 0, 0);
  437. }
  438. bool ObjectTemplate::isVisitableFrom(si8 X, si8 Y) const
  439. {
  440. // visitDir uses format
  441. // 1 2 3
  442. // 8 4
  443. // 7 6 5
  444. //TODO: static? cached?
  445. int dirMap[3][3] =
  446. {
  447. { visitDir & 1, visitDir & 2, visitDir & 4 },
  448. { visitDir & 128, 1 , visitDir & 8 },
  449. { visitDir & 64, visitDir & 32, visitDir & 16 }
  450. };
  451. // map input values to range 0..2
  452. int dx = X < 0 ? 0 : X == 0 ? 1 : 2;
  453. int dy = Y < 0 ? 0 : Y == 0 ? 1 : 2;
  454. return dirMap[dy][dx] != 0;
  455. }
  456. void ObjectTemplate::calculateVisitableOffset()
  457. {
  458. for(int y = 0; y < (int)getHeight(); y++)
  459. {
  460. for(int x = 0; x < (int)getWidth(); x++)
  461. {
  462. if (isVisitableAt(x, y))
  463. {
  464. visitableOffset = int3(x, y, 0);
  465. return;
  466. }
  467. }
  468. }
  469. visitableOffset = int3(0, 0, 0);
  470. }
  471. bool ObjectTemplate::canBePlacedAt(TerrainId terrainID) const
  472. {
  473. if (anyTerrain)
  474. {
  475. auto const & terrain = VLC->terrainTypeHandler->getById(terrainID);
  476. return terrain->isLand() && terrain->isPassable();
  477. }
  478. return vstd::contains(allowedTerrains, terrainID);
  479. }
  480. void ObjectTemplate::recalculate()
  481. {
  482. calculateWidth();
  483. calculateHeight();
  484. calculateVsitable();
  485. //The lines below use width and height
  486. calculateBlockedOffsets();
  487. calculateBlockMapOffset();
  488. calculateVisitableOffset();
  489. }
  490. VCMI_LIB_NAMESPACE_END