2
0

CObjectClassesHandler.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  1. #include "StdInc.h"
  2. #include "CObjectClassesHandler.h"
  3. #include "filesystem/Filesystem.h"
  4. #include "filesystem/CBinaryReader.h"
  5. #include "../lib/VCMI_Lib.h"
  6. #include "GameConstants.h"
  7. #include "StringConstants.h"
  8. #include "CGeneralTextHandler.h"
  9. #include "CObjectHandler.h"
  10. #include "CModHandler.h"
  11. #include "JsonNode.h"
  12. #include "CObjectConstructor.h"
  13. /*
  14. * CObjectClassesHandler.cpp, part of VCMI engine
  15. *
  16. * Authors: listed in file AUTHORS in main folder
  17. *
  18. * License: GNU General Public License v2.0 or later
  19. * Full text of license available in license.txt file, in main folder
  20. *
  21. */
  22. static bool isVisitableFromTop(int identifier, int type)
  23. {
  24. if(type == 2 || type == 3 || type == 4 || type == 5) //creature, hero, artifact, resource
  25. return true;
  26. static const Obj visitableFromTop[] =
  27. {Obj::FLOTSAM,
  28. Obj::SEA_CHEST,
  29. Obj::SHIPWRECK_SURVIVOR,
  30. Obj::BUOY,
  31. Obj::OCEAN_BOTTLE,
  32. Obj::BOAT,
  33. Obj::WHIRLPOOL,
  34. Obj::GARRISON,
  35. Obj::GARRISON2,
  36. Obj::SCHOLAR,
  37. Obj::CAMPFIRE,
  38. Obj::BORDERGUARD,
  39. Obj::BORDER_GATE,
  40. Obj::QUEST_GUARD,
  41. Obj::CORPSE
  42. };
  43. if (vstd::find_pos(visitableFromTop, identifier) != -1)
  44. return true;
  45. return false;
  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. {
  53. }
  54. void ObjectTemplate::readTxt(CLegacyConfigParser & parser)
  55. {
  56. std::string data = parser.readString();
  57. std::vector<std::string> strings;
  58. boost::split(strings, data, boost::is_any_of(" "));
  59. assert(strings.size() == 9);
  60. animationFile = strings[0];
  61. stringID = strings[0];
  62. std::string & blockStr = strings[1]; //block map, 0 = blocked, 1 = unblocked
  63. std::string & visitStr = strings[2]; //visit map, 1 = visitable, 0 = not visitable
  64. assert(blockStr.size() == 6*8);
  65. assert(visitStr.size() == 6*8);
  66. setSize(8, 6);
  67. for (size_t i=0; i<6; i++) // 6 rows
  68. {
  69. for (size_t j=0; j<8; j++) // 8 columns
  70. {
  71. auto & tile = usedTiles[i][j];
  72. tile |= VISIBLE; // assume that all tiles are visible
  73. if (blockStr[i*8 + j] == '0')
  74. tile |= BLOCKED;
  75. if (visitStr[i*8 + j] == '1')
  76. tile |= VISITABLE;
  77. }
  78. }
  79. // strings[3] most likely - terrains on which this object can be placed in editor.
  80. // e.g. Whirpool can be placed manually only on water while mines can be placed everywhere despite terrain-specific gfx
  81. // so these two fields can be interpreted as "strong affinity" and "weak affinity" towards terrains
  82. std::string & terrStr = strings[4]; // allowed terrains, 1 = object can be placed on this terrain
  83. assert(terrStr.size() == 9); // all terrains but rock
  84. for (size_t i=0; i<9; i++)
  85. {
  86. if (terrStr[8-i] == '1')
  87. allowedTerrains.insert(ETerrainType(i));
  88. }
  89. id = Obj(boost::lexical_cast<int>(strings[5]));
  90. subid = boost::lexical_cast<int>(strings[6]);
  91. int type = boost::lexical_cast<int>(strings[7]);
  92. printPriority = boost::lexical_cast<int>(strings[8]) * 100; // to have some space in future
  93. if (isVisitableFromTop(id, type))
  94. visitDir = 0xff;
  95. else
  96. visitDir = (8|16|32|64|128);
  97. readMsk();
  98. }
  99. void ObjectTemplate::readMsk()
  100. {
  101. ResourceID resID("SPRITES/" + animationFile, EResType::MASK);
  102. if (CResourceHandler::get()->existsResource(resID))
  103. {
  104. auto msk = CResourceHandler::get()->load(resID)->readAll();
  105. setSize(msk.first.get()[0], msk.first.get()[1]);
  106. }
  107. else //maximum possible size of H3 object //TODO: remove hardcode and move this data into modding system
  108. {
  109. setSize(8, 6);
  110. }
  111. }
  112. void ObjectTemplate::readMap(CBinaryReader & reader)
  113. {
  114. animationFile = reader.readString();
  115. setSize(8, 6);
  116. ui8 blockMask[6];
  117. ui8 visitMask[6];
  118. for(auto & byte : blockMask)
  119. byte = reader.readUInt8();
  120. for(auto & byte : visitMask)
  121. byte = reader.readUInt8();
  122. for (size_t i=0; i<6; i++) // 6 rows
  123. {
  124. for (size_t j=0; j<8; j++) // 8 columns
  125. {
  126. auto & tile = usedTiles[5 - i][7 - j];
  127. tile |= VISIBLE; // assume that all tiles are visible
  128. if (((blockMask[i] >> j) & 1 ) == 0)
  129. tile |= BLOCKED;
  130. if (((visitMask[i] >> j) & 1 ) != 0)
  131. tile |= VISITABLE;
  132. }
  133. }
  134. reader.readUInt16();
  135. ui16 terrMask = reader.readUInt16();
  136. for (size_t i=0; i<9; i++)
  137. {
  138. if (((terrMask >> i) & 1 ) != 0)
  139. allowedTerrains.insert(ETerrainType(i));
  140. }
  141. id = Obj(reader.readUInt32());
  142. subid = reader.readUInt32();
  143. int type = reader.readUInt8();
  144. printPriority = reader.readUInt8() * 100; // to have some space in future
  145. if (isVisitableFromTop(id, type))
  146. visitDir = 0xff;
  147. else
  148. visitDir = (8|16|32|64|128);
  149. reader.skip(16);
  150. readMsk();
  151. if (id == Obj::EVENT)
  152. {
  153. setSize(1,1);
  154. usedTiles[0][0] = VISITABLE;
  155. }
  156. }
  157. void ObjectTemplate::readJson(const JsonNode &node)
  158. {
  159. //id = Obj(node["basebase"].Float()); // temporary, should be removed and determined indirectly via object type parent (e.g. base->base)
  160. //subid = node["base"].Float();
  161. animationFile = node["animation"].String();
  162. const JsonVector & visitDirs = node["visitableFrom"].Vector();
  163. if (!visitDirs.empty())
  164. {
  165. if (visitDirs[0].String()[0] == '+') visitDir |= 1;
  166. if (visitDirs[0].String()[1] == '+') visitDir |= 2;
  167. if (visitDirs[0].String()[2] == '+') visitDir |= 4;
  168. if (visitDirs[1].String()[2] == '+') visitDir |= 8;
  169. if (visitDirs[2].String()[2] == '+') visitDir |= 16;
  170. if (visitDirs[2].String()[1] == '+') visitDir |= 32;
  171. if (visitDirs[2].String()[0] == '+') visitDir |= 64;
  172. if (visitDirs[1].String()[0] == '+') visitDir |= 128;
  173. }
  174. else
  175. visitDir = 0x00;
  176. if (!node["allowedTerrains"].isNull())
  177. {
  178. for (auto & entry : node["allowedTerrains"].Vector())
  179. allowedTerrains.insert(ETerrainType(vstd::find_pos(GameConstants::TERRAIN_NAMES, entry.String())));
  180. }
  181. else
  182. {
  183. for (size_t i=0; i< GameConstants::TERRAIN_TYPES; i++)
  184. allowedTerrains.insert(ETerrainType(i));
  185. }
  186. auto charToTile = [&](const char & ch) -> ui8
  187. {
  188. switch (ch)
  189. {
  190. case ' ' : return 0;
  191. case '0' : return 0;
  192. case 'V' : return VISIBLE;
  193. case 'B' : return VISIBLE | BLOCKED;
  194. case 'H' : return BLOCKED;
  195. case 'A' : return VISIBLE | BLOCKED | VISITABLE;
  196. case 'T' : return BLOCKED | VISITABLE;
  197. default:
  198. logGlobal->errorStream() << "Unrecognized char " << ch << " in template mask";
  199. return 0;
  200. }
  201. };
  202. const JsonVector & mask = node["mask"].Vector();
  203. size_t height = mask.size();
  204. size_t width = 0;
  205. for (auto & line : mask)
  206. vstd::amax(width, line.String().size());
  207. setSize(width, height);
  208. for (size_t i=0; i<mask.size(); i++)
  209. {
  210. const std::string & line = mask[i].String();
  211. for (size_t j=0; j < line.size(); j++)
  212. usedTiles[mask.size() - 1 - i][line.size() - 1 - j] = charToTile(line[j]);
  213. }
  214. printPriority = node["zIndex"].Float();
  215. }
  216. ui32 ObjectTemplate::getWidth() const
  217. {
  218. return usedTiles.empty() ? 0 : usedTiles.front().size();
  219. }
  220. ui32 ObjectTemplate::getHeight() const
  221. {
  222. return usedTiles.size();
  223. }
  224. void ObjectTemplate::setSize(ui32 width, ui32 height)
  225. {
  226. usedTiles.resize(height);
  227. for (auto & line : usedTiles)
  228. line.resize(width, 0);
  229. }
  230. bool ObjectTemplate::isVisitable() const
  231. {
  232. for (auto & line : usedTiles)
  233. for (auto & tile : line)
  234. if (tile & VISITABLE)
  235. return true;
  236. return false;
  237. }
  238. bool ObjectTemplate::isWithin(si32 X, si32 Y) const
  239. {
  240. if (X < 0 || Y < 0)
  241. return false;
  242. if (X >= getWidth() || Y >= getHeight())
  243. return false;
  244. return true;
  245. }
  246. bool ObjectTemplate::isVisitableAt(si32 X, si32 Y) const
  247. {
  248. if (isWithin(X, Y))
  249. return usedTiles[Y][X] & VISITABLE;
  250. return false;
  251. }
  252. bool ObjectTemplate::isVisibleAt(si32 X, si32 Y) const
  253. {
  254. if (isWithin(X, Y))
  255. return usedTiles[Y][X] & VISIBLE;
  256. return false;
  257. }
  258. bool ObjectTemplate::isBlockedAt(si32 X, si32 Y) const
  259. {
  260. if (isWithin(X, Y))
  261. return usedTiles[Y][X] & BLOCKED;
  262. return false;
  263. }
  264. bool ObjectTemplate::isVisitableFrom(si8 X, si8 Y) const
  265. {
  266. // visitDir uses format
  267. // 1 2 3
  268. // 8 4
  269. // 7 6 5
  270. int dirMap[3][3] =
  271. {
  272. { visitDir & 1, visitDir & 2, visitDir & 4 },
  273. { visitDir & 128, 1 , visitDir & 8 },
  274. { visitDir & 64, visitDir & 32, visitDir & 16 }
  275. };
  276. // map input values to range 0..2
  277. int dx = X < 0 ? 0 : X == 0 ? 1 : 2;
  278. int dy = Y < 0 ? 0 : Y == 0 ? 1 : 2;
  279. return dirMap[dy][dx] != 0;
  280. }
  281. bool ObjectTemplate::canBePlacedAt(ETerrainType terrain) const
  282. {
  283. return allowedTerrains.count(terrain) != 0;
  284. }
  285. CObjectClassesHandler::CObjectClassesHandler()
  286. {
  287. #define SET_HANDLER_CLASS(STRING, CLASSNAME) handlerConstructors[STRING] = std::make_shared<CLASSNAME>;
  288. #define SET_HANDLER(STRING, TYPENAME) handlerConstructors[STRING] = std::make_shared<CDefaultObjectTypeHandler<TYPENAME> >
  289. // list of all known handlers, hardcoded for now since the only way to add new objects is via C++ code
  290. SET_HANDLER_CLASS("configurable", CObjectWithRewardConstructor);
  291. SET_HANDLER("", CGObjectInstance);
  292. SET_HANDLER("generic", CGObjectInstance);
  293. SET_HANDLER("market", CGMarket);
  294. SET_HANDLER("bank", CBank);
  295. SET_HANDLER("cartographer", CCartographer);
  296. SET_HANDLER("artifact", CGArtifact);
  297. SET_HANDLER("blackMarket", CGBlackMarket);
  298. SET_HANDLER("boat", CGBoat);
  299. SET_HANDLER("bonusingObject", CGBonusingObject);
  300. SET_HANDLER("borderGate", CGBorderGate);
  301. SET_HANDLER("borderGuard", CGBorderGuard);
  302. SET_HANDLER("monster", CGCreature);
  303. SET_HANDLER("denOfThieves", CGDenOfthieves);
  304. SET_HANDLER("dwelling", CGDwelling);
  305. SET_HANDLER("event", CGEvent);
  306. SET_HANDLER("garrison", CGGarrison);
  307. SET_HANDLER("hero", CGHeroInstance);
  308. SET_HANDLER("heroPlaceholder", CGHeroPlaceholder);
  309. SET_HANDLER("keymaster", CGKeymasterTent);
  310. SET_HANDLER("lighthouse", CGLighthouse);
  311. SET_HANDLER("magi", CGMagi);
  312. SET_HANDLER("magicSpring", CGMagicSpring);
  313. SET_HANDLER("magicWell", CGMagicWell);
  314. SET_HANDLER("market", CGMarket);
  315. SET_HANDLER("mine", CGMine);
  316. SET_HANDLER("obelisk", CGObelisk);
  317. SET_HANDLER("observatory", CGObservatory);
  318. SET_HANDLER("onceVisitable", CGOnceVisitable);
  319. SET_HANDLER("pandora", CGPandoraBox);
  320. SET_HANDLER("pickable", CGPickable);
  321. SET_HANDLER("pyramid", CGPyramid);
  322. SET_HANDLER("questGuard", CGQuestGuard);
  323. SET_HANDLER("resource", CGResource);
  324. SET_HANDLER("scholar", CGScholar);
  325. SET_HANDLER("seerHut", CGSeerHut);
  326. SET_HANDLER("shipyard", CGShipyard);
  327. SET_HANDLER("shrine", CGShrine);
  328. SET_HANDLER("sign", CGSignBottle);
  329. SET_HANDLER("siren", CGSirens);
  330. SET_HANDLER("teleport", CGTeleport);
  331. SET_HANDLER("town", CGTownInstance);
  332. SET_HANDLER("university", CGUniversity);
  333. SET_HANDLER("oncePerHero", CGVisitableOPH);
  334. SET_HANDLER("oncePerWeek", CGVisitableOPW);
  335. SET_HANDLER("witch", CGWitchHut);
  336. #undef SET_HANDLER_CLASS
  337. #undef SET_HANDLER
  338. }
  339. template<typename Container>
  340. void readTextFile(Container objects, std::string path)
  341. {
  342. CLegacyConfigParser parser(path);
  343. size_t totalNumber = parser.readNumber(); // first line contains number of objects to read and nothing else
  344. parser.endLine();
  345. for (size_t i=0; i<totalNumber; i++)
  346. {
  347. ObjectTemplate templ;
  348. templ.readTxt(parser);
  349. parser.endLine();
  350. typename Container::key_type key(templ.id.num, templ.subid);
  351. objects.insert(std::make_pair(key, templ));
  352. }
  353. }
  354. std::vector<JsonNode> CObjectClassesHandler::loadLegacyData(size_t dataSize)
  355. {
  356. readTextFile(legacyTemplates, "Data/Objects.txt");
  357. readTextFile(legacyTemplates, "Data/Heroes.txt");
  358. std::vector<JsonNode> ret(dataSize);// create storage for 256 objects
  359. assert(dataSize == 256);
  360. CLegacyConfigParser parser("Data/ObjNames.txt");
  361. for (size_t i=0; i<256; i++)
  362. {
  363. ret[i]["name"].String() = parser.readString();
  364. parser.endLine();
  365. }
  366. return ret;
  367. }
  368. /// selects preferred ID (or subID) for new object
  369. template<typename Map>
  370. si32 selectNextID(const JsonNode & fixedID, const Map & map, si32 defaultID)
  371. {
  372. if (!fixedID.isNull() && fixedID.Float() < defaultID)
  373. return fixedID.Float(); // H3M object with fixed ID
  374. if (map.empty())
  375. return defaultID; // no objects loaded, keep gap for H3M objects
  376. if (map.rbegin()->first > defaultID)
  377. return map.rbegin()->first + 1; // some modded objects loaded, return next available
  378. return defaultID; // some H3M objects loaded, first modded found
  379. }
  380. void CObjectClassesHandler::loadObjectEntry(const JsonNode & entry, ObjectContainter * obj)
  381. {
  382. auto handler = handlerConstructors.at(obj->handlerName)();
  383. handler->init(entry);
  384. si32 id = selectNextID(entry["index"], obj->objects, 256);
  385. handler->setType(obj->id, id);
  386. if (handler->getTemplates().empty())
  387. {
  388. auto range = legacyTemplates.equal_range(std::make_pair(obj->id, si32(entry["index"].Float())));
  389. for (auto & templ : boost::make_iterator_range(range.first, range.second))
  390. handler->addTemplate(templ.second);
  391. }
  392. obj->objects[id] = handler;
  393. }
  394. CObjectClassesHandler::ObjectContainter * CObjectClassesHandler::loadFromJson(const JsonNode & json)
  395. {
  396. auto obj = new ObjectContainter();
  397. obj->name = json["name"].String();
  398. obj->handlerName = json["handler"].String();
  399. obj->base = json["base"]; // FIXME: when this data will be actually merged?
  400. obj->id = selectNextID(json["index"], objects, 256);
  401. for (auto entry : json["types"].Struct())
  402. {
  403. loadObjectEntry(entry.second, obj);
  404. }
  405. return obj;
  406. }
  407. void CObjectClassesHandler::loadObject(std::string scope, std::string name, const JsonNode & data)
  408. {
  409. auto object = loadFromJson(data);
  410. objects[object->id] = object;
  411. VLC->modh->identifiers.registerObject(scope, "object", name, object->id);
  412. }
  413. void CObjectClassesHandler::loadObject(std::string scope, std::string name, const JsonNode & data, size_t index)
  414. {
  415. auto object = loadFromJson(data);
  416. assert(objects[index] == nullptr); // ensure that this id was not loaded before
  417. objects[index] = object;
  418. VLC->modh->identifiers.registerObject(scope, "object", name, object->id);
  419. }
  420. void CObjectClassesHandler::createObject(std::string name, JsonNode config, si32 ID, boost::optional<si32> subID)
  421. {
  422. assert(objects.count(ID));
  423. if (subID)
  424. {
  425. assert(objects.at(ID)->objects.count(subID.get()) == 0);
  426. assert(config["index"].isNull());
  427. config["index"].Float() = subID.get();
  428. }
  429. loadObjectEntry(config, objects[ID]);
  430. }
  431. std::vector<bool> CObjectClassesHandler::getDefaultAllowed() const
  432. {
  433. return std::vector<bool>(); //TODO?
  434. }
  435. TObjectTypeHandler CObjectClassesHandler::getHandlerFor(si32 type, si32 subtype) const
  436. {
  437. if (objects.count(type))
  438. {
  439. if (objects.at(type)->objects.count(subtype))
  440. return objects.at(type)->objects.at(subtype);
  441. }
  442. logGlobal->errorStream() << "Failed to find object of type " << type << ":" << subtype;
  443. assert(0); // FIXME: throw error?
  444. return nullptr;
  445. }
  446. void CObjectClassesHandler::afterLoadFinalization()
  447. {
  448. legacyTemplates.clear(); // whatever left there is no longer needed
  449. }
  450. std::string CObjectClassesHandler::getObjectName(si32 type) const
  451. {
  452. assert(objects.count(type));
  453. return objects.at(type)->name;
  454. }
  455. void AObjectTypeHandler::setType(si32 type, si32 subtype)
  456. {
  457. this->type = type;
  458. this->subtype = subtype;
  459. }
  460. void AObjectTypeHandler::init(const JsonNode & input)
  461. {
  462. for (auto entry : input["templates"].Struct())
  463. {
  464. JsonNode data = input["base"];
  465. JsonUtils::merge(data, entry.second);
  466. ObjectTemplate tmpl;
  467. tmpl.id = Obj(type);
  468. tmpl.subid = subtype;
  469. tmpl.stringID = entry.first; // FIXME: create "fullID" - type.object.template?
  470. tmpl.readJson(data);
  471. templates.push_back(tmpl);
  472. }
  473. }
  474. bool AObjectTypeHandler::objectFilter(const CGObjectInstance *, const ObjectTemplate &) const
  475. {
  476. return true; // by default - accept all.
  477. }
  478. void AObjectTypeHandler::addTemplate(const ObjectTemplate & templ)
  479. {
  480. templates.push_back(templ);
  481. }
  482. std::vector<ObjectTemplate> AObjectTypeHandler::getTemplates() const
  483. {
  484. return templates;
  485. }
  486. std::vector<ObjectTemplate> AObjectTypeHandler::getTemplates(si32 terrainType) const// FIXME: replace with ETerrainType
  487. {
  488. std::vector<ObjectTemplate> ret = getTemplates();
  489. std::vector<ObjectTemplate> filtered;
  490. std::copy_if(ret.begin(), ret.end(), std::back_inserter(filtered), [&](const ObjectTemplate & obj)
  491. {
  492. return obj.canBePlacedAt(ETerrainType(terrainType));
  493. });
  494. // it is possible that there are no templates usable on specific terrain. In this case - return list before filtering
  495. return filtered.empty() ? ret : filtered;
  496. }
  497. boost::optional<ObjectTemplate> AObjectTypeHandler::getOverride(si32 terrainType, const CGObjectInstance * object) const
  498. {
  499. std::vector<ObjectTemplate> ret = getTemplates(terrainType);
  500. for (auto & tmpl : ret)
  501. {
  502. if (objectFilter(object, tmpl))
  503. return tmpl;
  504. }
  505. return boost::optional<ObjectTemplate>();
  506. }