ObjectTemplate.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  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() == Terrain::ROCK - 1); // all terrains but rock
  141. for(TerrainId i = Terrain::FIRST_REGULAR_TERRAIN; i < Terrain::ROCK; i++)
  142. {
  143. if (terrStr[8-i] == '1')
  144. allowedTerrains.insert(i);
  145. }
  146. //assuming that object can be placed on other land terrains
  147. if(allowedTerrains.size() >= 8 && !allowedTerrains.count(Terrain::WATER))
  148. {
  149. for(const auto & terrain : VLC->terrainTypeHandler->terrains())
  150. {
  151. if(terrain.isLand() && terrain.isPassable())
  152. allowedTerrains.insert(terrain.id);
  153. }
  154. }
  155. id = Obj(boost::lexical_cast<int>(strings[5]));
  156. subid = boost::lexical_cast<int>(strings[6]);
  157. int type = boost::lexical_cast<int>(strings[7]);
  158. printPriority = boost::lexical_cast<int>(strings[8]) * 100; // to have some space in future
  159. if (isOnVisitableFromTopList(id, type))
  160. visitDir = 0xff;
  161. else
  162. visitDir = (8|16|32|64|128);
  163. readMsk();
  164. recalculate();
  165. }
  166. void ObjectTemplate::readMsk()
  167. {
  168. ResourceID resID("SPRITES/" + animationFile, EResType::MASK);
  169. if (CResourceHandler::get()->existsResource(resID))
  170. {
  171. auto msk = CResourceHandler::get()->load(resID)->readAll();
  172. setSize(msk.first.get()[0], msk.first.get()[1]);
  173. }
  174. else //maximum possible size of H3 object //TODO: remove hardcode and move this data into modding system
  175. {
  176. setSize(8, 6);
  177. }
  178. }
  179. void ObjectTemplate::readMap(CBinaryReader & reader)
  180. {
  181. animationFile = reader.readString();
  182. setSize(8, 6);
  183. ui8 blockMask[6];
  184. ui8 visitMask[6];
  185. for(auto & byte : blockMask)
  186. byte = reader.readUInt8();
  187. for(auto & byte : visitMask)
  188. byte = reader.readUInt8();
  189. for(size_t i = 0; i < 6; i++) // 6 rows
  190. {
  191. for(size_t j = 0; j < 8; j++) // 8 columns
  192. {
  193. auto & tile = usedTiles[5 - i][7 - j];
  194. tile |= VISIBLE; // assume that all tiles are visible
  195. if (((blockMask[i] >> j) & 1 ) == 0)
  196. tile |= BLOCKED;
  197. if (((visitMask[i] >> j) & 1 ) != 0)
  198. tile |= VISITABLE;
  199. }
  200. }
  201. reader.readUInt16();
  202. ui16 terrMask = reader.readUInt16();
  203. for(size_t i = Terrain::FIRST_REGULAR_TERRAIN; i < Terrain::ROCK; i++)
  204. {
  205. if (((terrMask >> i) & 1 ) != 0)
  206. allowedTerrains.insert(i);
  207. }
  208. //assuming that object can be placed on other land terrains
  209. if(allowedTerrains.size() >= 8 && !allowedTerrains.count(Terrain::WATER))
  210. {
  211. for(const auto & terrain : VLC->terrainTypeHandler->terrains())
  212. {
  213. if(terrain.isLand() && terrain.isPassable())
  214. allowedTerrains.insert(terrain.id);
  215. }
  216. }
  217. id = Obj(reader.readUInt32());
  218. subid = reader.readUInt32();
  219. int type = reader.readUInt8();
  220. printPriority = reader.readUInt8() * 100; // to have some space in future
  221. if (isOnVisitableFromTopList(id, type))
  222. visitDir = 0xff;
  223. else
  224. visitDir = (8|16|32|64|128);
  225. reader.skip(16);
  226. readMsk();
  227. afterLoadFixup();
  228. recalculate();
  229. }
  230. void ObjectTemplate::readJson(const JsonNode &node, const bool withTerrain)
  231. {
  232. animationFile = node["animation"].String();
  233. editorAnimationFile = node["editorAnimation"].String();
  234. const JsonVector & visitDirs = node["visitableFrom"].Vector();
  235. if (!visitDirs.empty())
  236. {
  237. if (visitDirs[0].String()[0] == '+') visitDir |= 1;
  238. if (visitDirs[0].String()[1] == '+') visitDir |= 2;
  239. if (visitDirs[0].String()[2] == '+') visitDir |= 4;
  240. if (visitDirs[1].String()[2] == '+') visitDir |= 8;
  241. if (visitDirs[2].String()[2] == '+') visitDir |= 16;
  242. if (visitDirs[2].String()[1] == '+') visitDir |= 32;
  243. if (visitDirs[2].String()[0] == '+') visitDir |= 64;
  244. if (visitDirs[1].String()[0] == '+') visitDir |= 128;
  245. }
  246. else
  247. visitDir = 0x00;
  248. if(withTerrain && !node["allowedTerrains"].isNull())
  249. {
  250. for(auto& entry : node["allowedTerrains"].Vector())
  251. allowedTerrains.insert(VLC->terrainTypeHandler->getInfoByName(entry.String())->id);
  252. }
  253. else
  254. {
  255. for(const auto & terrain : VLC->terrainTypeHandler->terrains())
  256. {
  257. if(!terrain.isPassable() || terrain.isWater())
  258. continue;
  259. allowedTerrains.insert(terrain.id);
  260. }
  261. }
  262. if(withTerrain && allowedTerrains.empty())
  263. logGlobal->warn("Loaded template without allowed terrains!");
  264. auto charToTile = [&](const char & ch) -> ui8
  265. {
  266. switch (ch)
  267. {
  268. case ' ' : return 0;
  269. case '0' : return 0;
  270. case 'V' : return VISIBLE;
  271. case 'B' : return VISIBLE | BLOCKED;
  272. case 'H' : return BLOCKED;
  273. case 'A' : return VISIBLE | BLOCKED | VISITABLE;
  274. case 'T' : return BLOCKED | VISITABLE;
  275. default:
  276. logGlobal->error("Unrecognized char %s in template mask", ch);
  277. return 0;
  278. }
  279. };
  280. const JsonVector & mask = node["mask"].Vector();
  281. size_t height = mask.size();
  282. size_t width = 0;
  283. for(auto & line : mask)
  284. vstd::amax(width, line.String().size());
  285. setSize((ui32)width, (ui32)height);
  286. for(size_t i = 0; i < mask.size(); i++)
  287. {
  288. const std::string & line = mask[i].String();
  289. for(size_t j = 0; j < line.size(); j++)
  290. usedTiles[mask.size() - 1 - i][line.size() - 1 - j] = charToTile(line[j]);
  291. }
  292. printPriority = static_cast<si32>(node["zIndex"].Float());
  293. afterLoadFixup();
  294. recalculate();
  295. }
  296. void ObjectTemplate::writeJson(JsonNode & node, const bool withTerrain) const
  297. {
  298. node["animation"].String() = animationFile;
  299. node["editorAnimation"].String() = editorAnimationFile;
  300. if(visitDir != 0x0 && isVisitable())
  301. {
  302. JsonVector & visitDirs = node["visitableFrom"].Vector();
  303. visitDirs.resize(3);
  304. visitDirs[0].String().resize(3);
  305. visitDirs[1].String().resize(3);
  306. visitDirs[2].String().resize(3);
  307. visitDirs[0].String()[0] = (visitDir & 1) ? '+' : '-';
  308. visitDirs[0].String()[1] = (visitDir & 2) ? '+' : '-';
  309. visitDirs[0].String()[2] = (visitDir & 4) ? '+' : '-';
  310. visitDirs[1].String()[2] = (visitDir & 8) ? '+' : '-';
  311. visitDirs[2].String()[2] = (visitDir & 16) ? '+' : '-';
  312. visitDirs[2].String()[1] = (visitDir & 32) ? '+' : '-';
  313. visitDirs[2].String()[0] = (visitDir & 64) ? '+' : '-';
  314. visitDirs[1].String()[0] = (visitDir & 128) ? '+' : '-';
  315. visitDirs[1].String()[1] = '-';
  316. }
  317. if(withTerrain)
  318. {
  319. //assumed that ROCK and WATER terrains are not included
  320. if(allowedTerrains.size() < (VLC->terrainTypeHandler->terrains().size() - 2))
  321. {
  322. JsonVector & data = node["allowedTerrains"].Vector();
  323. for(auto type : allowedTerrains)
  324. {
  325. JsonNode value(JsonNode::JsonType::DATA_STRING);
  326. value.String() = type;
  327. data.push_back(value);
  328. }
  329. }
  330. }
  331. auto tileToChar = [&](const ui8 & tile) -> char
  332. {
  333. if(tile & VISIBLE)
  334. {
  335. if(tile & BLOCKED)
  336. {
  337. if(tile & VISITABLE)
  338. return 'A';
  339. else
  340. return 'B';
  341. }
  342. else
  343. return 'V';
  344. }
  345. else
  346. {
  347. if(tile & BLOCKED)
  348. {
  349. if(tile & VISITABLE)
  350. return 'T';
  351. else
  352. return 'H';
  353. }
  354. else
  355. return '0';
  356. }
  357. };
  358. size_t height = getHeight();
  359. size_t width = getWidth();
  360. JsonVector & mask = node["mask"].Vector();
  361. for(size_t i=0; i < height; i++)
  362. {
  363. JsonNode lineNode(JsonNode::JsonType::DATA_STRING);
  364. std::string & line = lineNode.String();
  365. line.resize(width);
  366. for(size_t j=0; j < width; j++)
  367. line[j] = tileToChar(usedTiles[height - 1 - i][width - 1 - j]);
  368. mask.push_back(lineNode);
  369. }
  370. if(printPriority != 0)
  371. node["zIndex"].Float() = printPriority;
  372. }
  373. void ObjectTemplate::calculateWidth()
  374. {
  375. //TODO: Use 2D array
  376. for(const auto& row : usedTiles) //copy is expensive
  377. {
  378. width = std::max<ui32>(width, (ui32)row.size());
  379. }
  380. }
  381. void ObjectTemplate::calculateHeight()
  382. {
  383. //TODO: Use 2D array
  384. height = static_cast<ui32>(usedTiles.size());
  385. }
  386. void ObjectTemplate::setSize(ui32 width, ui32 height)
  387. {
  388. usedTiles.resize(height);
  389. for(auto & line : usedTiles)
  390. line.resize(width, 0);
  391. }
  392. void ObjectTemplate::calculateVsitable()
  393. {
  394. for(auto& line : usedTiles)
  395. {
  396. for(auto& tile : line)
  397. {
  398. if (tile & VISITABLE)
  399. {
  400. visitable = true;
  401. return;
  402. }
  403. }
  404. }
  405. visitable = false;
  406. }
  407. bool ObjectTemplate::isWithin(si32 X, si32 Y) const
  408. {
  409. if (X < 0 || Y < 0)
  410. return false;
  411. return !(X >= (si32)getWidth() || Y >= (si32)getHeight());
  412. }
  413. bool ObjectTemplate::isVisitableAt(si32 X, si32 Y) const
  414. {
  415. return isWithin(X, Y) && usedTiles[Y][X] & VISITABLE;
  416. }
  417. bool ObjectTemplate::isVisibleAt(si32 X, si32 Y) const
  418. {
  419. return isWithin(X, Y) && usedTiles[Y][X] & VISIBLE;
  420. }
  421. bool ObjectTemplate::isBlockedAt(si32 X, si32 Y) const
  422. {
  423. return isWithin(X, Y) && usedTiles[Y][X] & BLOCKED;
  424. }
  425. void ObjectTemplate::calculateBlockedOffsets()
  426. {
  427. blockedOffsets.clear();
  428. for(int w = 0; w < (int)getWidth(); ++w)
  429. {
  430. for(int h = 0; h < (int)getHeight(); ++h)
  431. {
  432. if (isBlockedAt(w, h))
  433. blockedOffsets.insert(int3(-w, -h, 0));
  434. }
  435. }
  436. }
  437. void ObjectTemplate::calculateBlockMapOffset()
  438. {
  439. for(int w = 0; w < (int)getWidth(); ++w)
  440. {
  441. for(int h = 0; h < (int)getHeight(); ++h)
  442. {
  443. if (isBlockedAt(w, h))
  444. {
  445. blockMapOffset = int3(w, h, 0);
  446. return;
  447. }
  448. }
  449. }
  450. blockMapOffset = int3(0, 0, 0);
  451. }
  452. bool ObjectTemplate::isVisitableFrom(si8 X, si8 Y) const
  453. {
  454. // visitDir uses format
  455. // 1 2 3
  456. // 8 4
  457. // 7 6 5
  458. //TODO: static? cached?
  459. int dirMap[3][3] =
  460. {
  461. { visitDir & 1, visitDir & 2, visitDir & 4 },
  462. { visitDir & 128, 1 , visitDir & 8 },
  463. { visitDir & 64, visitDir & 32, visitDir & 16 }
  464. };
  465. // map input values to range 0..2
  466. int dx = X < 0 ? 0 : X == 0 ? 1 : 2;
  467. int dy = Y < 0 ? 0 : Y == 0 ? 1 : 2;
  468. return dirMap[dy][dx] != 0;
  469. }
  470. void ObjectTemplate::calculateVisitableOffset()
  471. {
  472. for(int y = 0; y < (int)getHeight(); y++)
  473. {
  474. for(int x = 0; x < (int)getWidth(); x++)
  475. {
  476. if (isVisitableAt(x, y))
  477. {
  478. visitableOffset = int3(x, y, 0);
  479. return;
  480. }
  481. }
  482. }
  483. visitableOffset = int3(0, 0, 0);
  484. }
  485. bool ObjectTemplate::canBePlacedAt(TerrainId terrain) const
  486. {
  487. return vstd::contains(allowedTerrains, terrain);
  488. }
  489. void ObjectTemplate::recalculate()
  490. {
  491. calculateWidth();
  492. calculateHeight();
  493. calculateVsitable();
  494. //The lines below use width and height
  495. calculateBlockedOffsets();
  496. calculateBlockMapOffset();
  497. calculateVisitableOffset();
  498. }
  499. VCMI_LIB_NAMESPACE_END