ObjectTemplate.cpp 14 KB

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