2
0

CObjectClassesHandler.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. #include "StdInc.h"
  2. #include "CObjectClassesHandler.h"
  3. #include "../filesystem/Filesystem.h"
  4. #include "../filesystem/CBinaryReader.h"
  5. #include "../VCMI_Lib.h"
  6. #include "../GameConstants.h"
  7. #include "../StringConstants.h"
  8. #include "../CGeneralTextHandler.h"
  9. #include "../CModHandler.h"
  10. #include "../JsonNode.h"
  11. #include "CRewardableConstructor.h"
  12. #include "CommonConstructors.h"
  13. #include "MapObjects.h"
  14. /*
  15. * CObjectClassesHandler.cpp, part of VCMI engine
  16. *
  17. * Authors: listed in file AUTHORS in main folder
  18. *
  19. * License: GNU General Public License v2.0 or later
  20. * Full text of license available in license.txt file, in main folder
  21. *
  22. */
  23. CObjectClassesHandler::CObjectClassesHandler()
  24. {
  25. #define SET_HANDLER_CLASS(STRING, CLASSNAME) handlerConstructors[STRING] = std::make_shared<CLASSNAME>;
  26. #define SET_HANDLER(STRING, TYPENAME) handlerConstructors[STRING] = std::make_shared<CDefaultObjectTypeHandler<TYPENAME> >
  27. // list of all known handlers, hardcoded for now since the only way to add new objects is via C++ code
  28. //Note: should be in sync with registerTypesMapObjectTypes function
  29. SET_HANDLER_CLASS("configurable", CRewardableConstructor);
  30. SET_HANDLER_CLASS("dwelling", CDwellingInstanceConstructor);
  31. SET_HANDLER_CLASS("hero", CHeroInstanceConstructor);
  32. SET_HANDLER_CLASS("town", CTownInstanceConstructor);
  33. SET_HANDLER_CLASS("bank", CBankInstanceConstructor);
  34. SET_HANDLER_CLASS("static", CObstacleConstructor);
  35. SET_HANDLER_CLASS("", CObstacleConstructor);
  36. SET_HANDLER("randomArtifact", CGArtifact);
  37. SET_HANDLER("randomHero", CGHeroInstance);
  38. SET_HANDLER("randomResource", CGResource);
  39. SET_HANDLER("randomTown", CGTownInstance);
  40. SET_HANDLER("randomMonster", CGCreature);
  41. SET_HANDLER("randomDwelling", CGDwelling);
  42. SET_HANDLER("generic", CGObjectInstance);
  43. SET_HANDLER("market", CGMarket);
  44. SET_HANDLER("cartographer", CCartographer);
  45. SET_HANDLER("artifact", CGArtifact);
  46. SET_HANDLER("blackMarket", CGBlackMarket);
  47. SET_HANDLER("boat", CGBoat);
  48. SET_HANDLER("bonusingObject", CGBonusingObject);
  49. SET_HANDLER("borderGate", CGBorderGate);
  50. SET_HANDLER("borderGuard", CGBorderGuard);
  51. SET_HANDLER("monster", CGCreature);
  52. SET_HANDLER("denOfThieves", CGDenOfthieves);
  53. SET_HANDLER("event", CGEvent);
  54. SET_HANDLER("garrison", CGGarrison);
  55. SET_HANDLER("heroPlaceholder", CGHeroPlaceholder);
  56. SET_HANDLER("keymaster", CGKeymasterTent);
  57. SET_HANDLER("lighthouse", CGLighthouse);
  58. SET_HANDLER("magi", CGMagi);
  59. SET_HANDLER("magicSpring", CGMagicSpring);
  60. SET_HANDLER("magicWell", CGMagicWell);
  61. SET_HANDLER("market", CGMarket);
  62. SET_HANDLER("mine", CGMine);
  63. SET_HANDLER("obelisk", CGObelisk);
  64. SET_HANDLER("observatory", CGObservatory);
  65. SET_HANDLER("onceVisitable", CGOnceVisitable);
  66. SET_HANDLER("pandora", CGPandoraBox);
  67. SET_HANDLER("pickable", CGPickable);
  68. SET_HANDLER("prison", CGHeroInstance);
  69. SET_HANDLER("questGuard", CGQuestGuard);
  70. SET_HANDLER("resource", CGResource);
  71. SET_HANDLER("scholar", CGScholar);
  72. SET_HANDLER("seerHut", CGSeerHut);
  73. SET_HANDLER("shipyard", CGShipyard);
  74. SET_HANDLER("shrine", CGShrine);
  75. SET_HANDLER("sign", CGSignBottle);
  76. SET_HANDLER("siren", CGSirens);
  77. SET_HANDLER("monolith", CGMonolith);
  78. SET_HANDLER("subterraneanGate", CGSubterraneanGate);
  79. SET_HANDLER("whirlpool", CGWhirlpool);
  80. SET_HANDLER("university", CGUniversity);
  81. SET_HANDLER("oncePerHero", CGVisitableOPH);
  82. SET_HANDLER("oncePerWeek", CGVisitableOPW);
  83. SET_HANDLER("witch", CGWitchHut);
  84. #undef SET_HANDLER_CLASS
  85. #undef SET_HANDLER
  86. }
  87. CObjectClassesHandler::~CObjectClassesHandler()
  88. {
  89. for(auto p : objects)
  90. delete p.second;
  91. }
  92. std::vector<JsonNode> CObjectClassesHandler::loadLegacyData(size_t dataSize)
  93. {
  94. CLegacyConfigParser parser("Data/Objects.txt");
  95. size_t totalNumber = parser.readNumber(); // first line contains number of objects to read and nothing else
  96. parser.endLine();
  97. for (size_t i=0; i<totalNumber; i++)
  98. {
  99. ObjectTemplate templ;
  100. templ.readTxt(parser);
  101. parser.endLine();
  102. std::pair<si32, si32> key(templ.id.num, templ.subid);
  103. legacyTemplates.insert(std::make_pair(key, templ));
  104. }
  105. std::vector<JsonNode> ret(dataSize);// create storage for 256 objects
  106. assert(dataSize == 256);
  107. CLegacyConfigParser namesParser("Data/ObjNames.txt");
  108. for (size_t i=0; i<256; i++)
  109. {
  110. ret[i]["name"].String() = namesParser.readString();
  111. namesParser.endLine();
  112. }
  113. CLegacyConfigParser cregen1Parser("data/crgen1");
  114. do
  115. customNames[Obj::CREATURE_GENERATOR1].push_back(cregen1Parser.readString());
  116. while(cregen1Parser.endLine());
  117. CLegacyConfigParser cregen4Parser("data/crgen4");
  118. do
  119. customNames[Obj::CREATURE_GENERATOR4].push_back(cregen4Parser.readString());
  120. while(cregen4Parser.endLine());
  121. return ret;
  122. }
  123. /// selects preferred ID (or subID) for new object
  124. template<typename Map>
  125. si32 selectNextID(const JsonNode & fixedID, const Map & map, si32 defaultID)
  126. {
  127. if (!fixedID.isNull() && fixedID.Float() < defaultID)
  128. return fixedID.Float(); // H3M object with fixed ID
  129. if (map.empty())
  130. return defaultID; // no objects loaded, keep gap for H3M objects
  131. if (map.rbegin()->first >= defaultID)
  132. return map.rbegin()->first + 1; // some modded objects loaded, return next available
  133. return defaultID; // some H3M objects loaded, first modded found
  134. }
  135. void CObjectClassesHandler::loadObjectEntry(const std::string & identifier, const JsonNode & entry, ObjectContainter * obj)
  136. {
  137. if (!handlerConstructors.count(obj->handlerName))
  138. {
  139. logGlobal->errorStream() << "Handler with name " << obj->handlerName << " was not found!";
  140. return;
  141. }
  142. std::string convertedId = VLC->modh->normalizeIdentifier(entry.meta, "core", identifier);
  143. si32 id = selectNextID(entry["index"], obj->subObjects, 1000);
  144. auto handler = handlerConstructors.at(obj->handlerName)();
  145. handler->setType(obj->id, id);
  146. handler->setTypeName(obj->identifier, convertedId);
  147. if (customNames.count(obj->id) && customNames.at(obj->id).size() > id)
  148. handler->init(entry, customNames.at(obj->id).at(id));
  149. else
  150. handler->init(entry);
  151. if (handler->getTemplates().empty())
  152. {
  153. auto range = legacyTemplates.equal_range(std::make_pair(obj->id, id));
  154. for (auto & templ : boost::make_iterator_range(range.first, range.second))
  155. {
  156. handler->addTemplate(templ.second);
  157. }
  158. legacyTemplates.erase(range.first, range.second);
  159. }
  160. logGlobal->debugStream() << "Loaded object " << obj->identifier << "(" << obj->id << ")" << ":" << convertedId << "(" << id << ")" ;
  161. assert(!obj->subObjects.count(id)); // DO NOT override
  162. obj->subObjects[id] = handler;
  163. obj->subIds[convertedId] = id;
  164. }
  165. CObjectClassesHandler::ObjectContainter * CObjectClassesHandler::loadFromJson(const JsonNode & json, const std::string & name)
  166. {
  167. auto obj = new ObjectContainter();
  168. obj->identifier = name;
  169. obj->name = json["name"].String();
  170. obj->handlerName = json["handler"].String();
  171. obj->base = json["base"];
  172. obj->id = selectNextID(json["index"], objects, 256);
  173. for (auto entry : json["types"].Struct())
  174. {
  175. loadObjectEntry(entry.first, entry.second, obj);
  176. }
  177. return obj;
  178. }
  179. void CObjectClassesHandler::loadObject(std::string scope, std::string name, const JsonNode & data)
  180. {
  181. auto object = loadFromJson(data, normalizeIdentifier(scope, "core", name));
  182. objects[object->id] = object;
  183. VLC->modh->identifiers.registerObject(scope, "object", name, object->id);
  184. }
  185. void CObjectClassesHandler::loadObject(std::string scope, std::string name, const JsonNode & data, size_t index)
  186. {
  187. auto object = loadFromJson(data, normalizeIdentifier(scope, "core", name));
  188. assert(objects[index] == nullptr); // ensure that this id was not loaded before
  189. objects[index] = object;
  190. VLC->modh->identifiers.registerObject(scope, "object", name, object->id);
  191. }
  192. void CObjectClassesHandler::loadSubObject(const std::string & identifier, JsonNode config, si32 ID, boost::optional<si32> subID)
  193. {
  194. config.setType(JsonNode::DATA_STRUCT); // ensure that input is not NULL
  195. assert(objects.count(ID));
  196. if (subID)
  197. {
  198. assert(objects.at(ID)->subObjects.count(subID.get()) == 0);
  199. assert(config["index"].isNull());
  200. config["index"].Float() = subID.get();
  201. }
  202. std::string oldMeta = config.meta; // FIXME: move into inheritNode?
  203. JsonUtils::inherit(config, objects.at(ID)->base);
  204. config.setMeta(oldMeta);
  205. loadObjectEntry(identifier, config, objects[ID]);
  206. }
  207. void CObjectClassesHandler::removeSubObject(si32 ID, si32 subID)
  208. {
  209. assert(objects.count(ID));
  210. assert(objects.at(ID)->subObjects.count(subID));
  211. objects.at(ID)->subObjects.erase(subID); //TODO: cleanup string id map
  212. }
  213. std::vector<bool> CObjectClassesHandler::getDefaultAllowed() const
  214. {
  215. return std::vector<bool>(); //TODO?
  216. }
  217. TObjectTypeHandler CObjectClassesHandler::getHandlerFor(si32 type, si32 subtype) const
  218. {
  219. if (objects.count(type))
  220. {
  221. if (objects.at(type)->subObjects.count(subtype))
  222. return objects.at(type)->subObjects.at(subtype);
  223. }
  224. logGlobal->errorStream() << "Failed to find object of type " << type << ":" << subtype;
  225. throw std::runtime_error("Object type handler not found");
  226. return nullptr;
  227. }
  228. TObjectTypeHandler CObjectClassesHandler::getHandlerFor(std::string type, std::string subtype) const
  229. {
  230. boost::optional<si32> id = VLC->modh->identifiers.getIdentifier("core", "object", type, false);
  231. if(id)
  232. {
  233. si32 subId = objects.at(id.get())->subIds.at(subtype);
  234. return objects.at(id.get())->subObjects.at(subId);
  235. }
  236. logGlobal->errorStream() << "Failed to find object of type " << type << ":" << subtype;
  237. throw std::runtime_error("Object type handler not found");
  238. return nullptr;
  239. }
  240. std::set<si32> CObjectClassesHandler::knownObjects() const
  241. {
  242. std::set<si32> ret;
  243. for (auto entry : objects)
  244. ret.insert(entry.first);
  245. return ret;
  246. }
  247. std::set<si32> CObjectClassesHandler::knownSubObjects(si32 primaryID) const
  248. {
  249. std::set<si32> ret;
  250. if (objects.count(primaryID))
  251. {
  252. for (auto entry : objects.at(primaryID)->subObjects)
  253. ret.insert(entry.first);
  254. }
  255. return ret;
  256. }
  257. void CObjectClassesHandler::beforeValidate(JsonNode & object)
  258. {
  259. for (auto & entry : object["types"].Struct())
  260. {
  261. JsonUtils::inherit(entry.second, object["base"]);
  262. for (auto & templ : entry.second["templates"].Struct())
  263. {
  264. JsonUtils::inherit(templ.second, entry.second["base"]);
  265. }
  266. }
  267. }
  268. void CObjectClassesHandler::afterLoadFinalization()
  269. {
  270. for (auto entry : objects)
  271. {
  272. for (auto obj : entry.second->subObjects)
  273. {
  274. obj.second->afterLoadFinalization();
  275. if (obj.second->getTemplates().empty())
  276. logGlobal->warnStream() << "No templates found for " << entry.first << ":" << obj.first;
  277. }
  278. }
  279. //duplicate existing two-way portals to make reserve for RMG
  280. auto& portalVec = objects[Obj::MONOLITH_TWO_WAY]->subObjects;
  281. size_t portalCount = portalVec.size();
  282. size_t currentIndex = portalCount;
  283. while (portalVec.size() < 100)
  284. {
  285. portalVec[currentIndex] = portalVec[currentIndex % portalCount];
  286. currentIndex++;
  287. }
  288. }
  289. std::string CObjectClassesHandler::getObjectName(si32 type) const
  290. {
  291. if (objects.count(type))
  292. return objects.at(type)->name;
  293. logGlobal->errorStream() << "Access to non existing object of type " << type;
  294. return "";
  295. }
  296. std::string CObjectClassesHandler::getObjectName(si32 type, si32 subtype) const
  297. {
  298. if (knownSubObjects(type).count(subtype))
  299. {
  300. auto name = getHandlerFor(type, subtype)->getCustomName();
  301. if (name)
  302. return name.get();
  303. }
  304. return getObjectName(type);
  305. }
  306. std::string CObjectClassesHandler::getObjectHandlerName(si32 type) const
  307. {
  308. return objects.at(type)->handlerName;
  309. }
  310. void AObjectTypeHandler::setType(si32 type, si32 subtype)
  311. {
  312. this->type = type;
  313. this->subtype = subtype;
  314. }
  315. void AObjectTypeHandler::setTypeName(std::string type, std::string subtype)
  316. {
  317. this->typeName = type;
  318. this->subTypeName = subtype;
  319. }
  320. static ui32 loadJsonOrMax(const JsonNode & input)
  321. {
  322. if (input.isNull())
  323. return std::numeric_limits<ui32>::max();
  324. else
  325. return input.Float();
  326. }
  327. void AObjectTypeHandler::init(const JsonNode & input, boost::optional<std::string> name)
  328. {
  329. base = input["base"];
  330. if (!input["rmg"].isNull())
  331. {
  332. rmgInfo.value = input["rmg"]["value"].Float();
  333. rmgInfo.mapLimit = loadJsonOrMax(input["rmg"]["mapLimit"]);
  334. rmgInfo.zoneLimit = loadJsonOrMax(input["rmg"]["zoneLimit"]);
  335. rmgInfo.rarity = input["rmg"]["rarity"].Float();
  336. } // else block is not needed - set in constructor
  337. for (auto entry : input["templates"].Struct())
  338. {
  339. entry.second.setType(JsonNode::DATA_STRUCT);
  340. JsonUtils::inherit(entry.second, base);
  341. ObjectTemplate tmpl;
  342. tmpl.id = Obj(type);
  343. tmpl.subid = subtype;
  344. tmpl.stringID = entry.first; // FIXME: create "fullID" - type.object.template?
  345. tmpl.readJson(entry.second);
  346. templates.push_back(tmpl);
  347. }
  348. if (input["name"].isNull())
  349. objectName = name;
  350. else
  351. objectName.reset(input["name"].String());
  352. initTypeData(input);
  353. }
  354. bool AObjectTypeHandler::objectFilter(const CGObjectInstance *, const ObjectTemplate &) const
  355. {
  356. return false; // by default there are no overrides
  357. }
  358. void AObjectTypeHandler::preInitObject(CGObjectInstance * obj) const
  359. {
  360. obj->ID = Obj(type);
  361. obj->subID = subtype;
  362. obj->typeName = typeName;
  363. obj->subTypeName = subTypeName;
  364. }
  365. void AObjectTypeHandler::initTypeData(const JsonNode & input)
  366. {
  367. // empty implementation for overrides
  368. }
  369. boost::optional<std::string> AObjectTypeHandler::getCustomName() const
  370. {
  371. return objectName;
  372. }
  373. void AObjectTypeHandler::addTemplate(const ObjectTemplate & templ)
  374. {
  375. templates.push_back(templ);
  376. templates.back().id = Obj(type);
  377. templates.back().subid = subtype;
  378. }
  379. void AObjectTypeHandler::addTemplate(JsonNode config)
  380. {
  381. config.setType(JsonNode::DATA_STRUCT); // ensure that input is not null
  382. JsonUtils::inherit(config, base);
  383. ObjectTemplate tmpl;
  384. tmpl.id = Obj(type);
  385. tmpl.subid = subtype;
  386. tmpl.stringID = ""; // TODO?
  387. tmpl.readJson(config);
  388. templates.push_back(tmpl);
  389. }
  390. std::vector<ObjectTemplate> AObjectTypeHandler::getTemplates() const
  391. {
  392. return templates;
  393. }
  394. std::vector<ObjectTemplate> AObjectTypeHandler::getTemplates(si32 terrainType) const// FIXME: replace with ETerrainType
  395. {
  396. std::vector<ObjectTemplate> templates = getTemplates();
  397. std::vector<ObjectTemplate> filtered;
  398. std::copy_if(templates.begin(), templates.end(), std::back_inserter(filtered), [&](const ObjectTemplate & obj)
  399. {
  400. return obj.canBePlacedAt(ETerrainType(terrainType));
  401. });
  402. // H3 defines allowed terrains in a weird way - artifacts, monsters and resources have faulty masks here
  403. // Perhaps we should re-define faulty templates and remove this workaround (already done for resources)
  404. if (type == Obj::ARTIFACT || type == Obj::MONSTER)
  405. return templates;
  406. else
  407. return filtered;
  408. }
  409. boost::optional<ObjectTemplate> AObjectTypeHandler::getOverride(si32 terrainType, const CGObjectInstance * object) const
  410. {
  411. std::vector<ObjectTemplate> ret = getTemplates(terrainType);
  412. for (auto & tmpl : ret)
  413. {
  414. if (objectFilter(object, tmpl))
  415. return tmpl;
  416. }
  417. return boost::optional<ObjectTemplate>();
  418. }
  419. const RandomMapInfo & AObjectTypeHandler::getRMGInfo()
  420. {
  421. return rmgInfo;
  422. }
  423. bool AObjectTypeHandler::isStaticObject()
  424. {
  425. return false; // most of classes are not static
  426. }
  427. void AObjectTypeHandler::afterLoadFinalization()
  428. {
  429. }