CObjectClassesHandler.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  1. /*
  2. * CObjectClassesHandler.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 "../json/JsonUtils.h"
  15. #include "../VCMI_Lib.h"
  16. #include "../GameConstants.h"
  17. #include "../constants/StringConstants.h"
  18. #include "../CGeneralTextHandler.h"
  19. #include "../GameSettings.h"
  20. #include "../CSoundBase.h"
  21. #include "../mapObjectConstructors/CBankInstanceConstructor.h"
  22. #include "../mapObjectConstructors/CRewardableConstructor.h"
  23. #include "../mapObjectConstructors/CommonConstructors.h"
  24. #include "../mapObjectConstructors/DwellingInstanceConstructor.h"
  25. #include "../mapObjectConstructors/HillFortInstanceConstructor.h"
  26. #include "../mapObjectConstructors/ShipyardInstanceConstructor.h"
  27. #include "../mapObjects/CGCreature.h"
  28. #include "../mapObjects/CGPandoraBox.h"
  29. #include "../mapObjects/CQuest.h"
  30. #include "../mapObjects/ObjectTemplate.h"
  31. #include "../mapObjects/CGMarket.h"
  32. #include "../mapObjects/MiscObjects.h"
  33. #include "../mapObjects/CGHeroInstance.h"
  34. #include "../mapObjects/CGTownInstance.h"
  35. #include "../mapObjects/ObstacleSetHandler.h"
  36. #include "../modding/IdentifierStorage.h"
  37. #include "../modding/CModHandler.h"
  38. #include "../modding/ModScope.h"
  39. VCMI_LIB_NAMESPACE_BEGIN
  40. CObjectClassesHandler::CObjectClassesHandler()
  41. {
  42. #define SET_HANDLER_CLASS(STRING, CLASSNAME) handlerConstructors[STRING] = std::make_shared<CLASSNAME>
  43. #define SET_HANDLER(STRING, TYPENAME) handlerConstructors[STRING] = std::make_shared<CDefaultObjectTypeHandler<TYPENAME>>
  44. // list of all known handlers, hardcoded for now since the only way to add new objects is via C++ code
  45. //Note: should be in sync with registerTypesMapObjectTypes function
  46. SET_HANDLER_CLASS("configurable", CRewardableConstructor);
  47. SET_HANDLER_CLASS("dwelling", DwellingInstanceConstructor);
  48. SET_HANDLER_CLASS("hero", CHeroInstanceConstructor);
  49. SET_HANDLER_CLASS("town", CTownInstanceConstructor);
  50. SET_HANDLER_CLASS("bank", CBankInstanceConstructor);
  51. SET_HANDLER_CLASS("boat", BoatInstanceConstructor);
  52. SET_HANDLER_CLASS("market", MarketInstanceConstructor);
  53. SET_HANDLER_CLASS("hillFort", HillFortInstanceConstructor);
  54. SET_HANDLER_CLASS("shipyard", ShipyardInstanceConstructor);
  55. SET_HANDLER_CLASS("monster", CreatureInstanceConstructor);
  56. SET_HANDLER_CLASS("resource", ResourceInstanceConstructor);
  57. SET_HANDLER_CLASS("static", CObstacleConstructor);
  58. SET_HANDLER_CLASS("", CObstacleConstructor);
  59. SET_HANDLER("randomArtifact", CGArtifact);
  60. SET_HANDLER("randomHero", CGHeroInstance);
  61. SET_HANDLER("randomResource", CGResource);
  62. SET_HANDLER("randomTown", CGTownInstance);
  63. SET_HANDLER("randomMonster", CGCreature);
  64. SET_HANDLER("randomDwelling", CGDwelling);
  65. SET_HANDLER("generic", CGObjectInstance);
  66. SET_HANDLER("artifact", CGArtifact);
  67. SET_HANDLER("borderGate", CGBorderGate);
  68. SET_HANDLER("borderGuard", CGBorderGuard);
  69. SET_HANDLER("denOfThieves", CGDenOfthieves);
  70. SET_HANDLER("event", CGEvent);
  71. SET_HANDLER("garrison", CGGarrison);
  72. SET_HANDLER("heroPlaceholder", CGHeroPlaceholder);
  73. SET_HANDLER("keymaster", CGKeymasterTent);
  74. SET_HANDLER("lighthouse", CGLighthouse);
  75. SET_HANDLER("magi", CGMagi);
  76. SET_HANDLER("mine", CGMine);
  77. SET_HANDLER("obelisk", CGObelisk);
  78. SET_HANDLER("pandora", CGPandoraBox);
  79. SET_HANDLER("prison", CGHeroInstance);
  80. SET_HANDLER("questGuard", CGQuestGuard);
  81. SET_HANDLER("seerHut", CGSeerHut);
  82. SET_HANDLER("sign", CGSignBottle);
  83. SET_HANDLER("siren", CGSirens);
  84. SET_HANDLER("monolith", CGMonolith);
  85. SET_HANDLER("subterraneanGate", CGSubterraneanGate);
  86. SET_HANDLER("whirlpool", CGWhirlpool);
  87. SET_HANDLER("terrain", CGTerrainPatch);
  88. #undef SET_HANDLER_CLASS
  89. #undef SET_HANDLER
  90. }
  91. CObjectClassesHandler::~CObjectClassesHandler() = default;
  92. std::vector<JsonNode> CObjectClassesHandler::loadLegacyData()
  93. {
  94. size_t dataSize = VLC->settings()->getInteger(EGameSettings::TEXTS_OBJECT);
  95. CLegacyConfigParser parser(TextPath::builtin("Data/Objects.txt"));
  96. auto totalNumber = static_cast<size_t>(parser.readNumber()); // first line contains number of objects to read and nothing else
  97. parser.endLine();
  98. std::map<TerrainId, std::map<MapObjectID, std::map<MapObjectSubID, ObstacleSet>>> obstacleSets;
  99. for (size_t i = 0; i < totalNumber; i++)
  100. {
  101. auto tmpl = std::make_shared<ObjectTemplate>();
  102. tmpl->readTxt(parser);
  103. parser.endLine();
  104. std::pair key(tmpl->id, tmpl->subid);
  105. legacyTemplates.insert(std::make_pair(key, tmpl));
  106. // Populate ObstacleSetHandler on our way
  107. if (!tmpl->isVisitable())
  108. {
  109. // Create obstacle sets. Group by terrain for now
  110. for (auto terrain : tmpl->getAllowedTerrains())
  111. {
  112. auto &obstacleMap = obstacleSets[terrain][tmpl->id];
  113. auto it = obstacleMap.find(tmpl->subid);
  114. if (it == obstacleMap.end())
  115. {
  116. // FIXME: This means this set will be available only on one terrain
  117. auto type = VLC->biomeHandler->convertObstacleClass(tmpl->id);
  118. auto newIt = obstacleMap.insert(std::make_pair(tmpl->subid, ObstacleSet(type, terrain)));
  119. newIt.first->second.addObstacle(tmpl);
  120. }
  121. else
  122. {
  123. it->second.addObstacle(tmpl);
  124. }
  125. }
  126. }
  127. }
  128. size_t count = 0;
  129. for (auto terrain : obstacleSets)
  130. {
  131. for (auto obstacleType : terrain.second)
  132. {
  133. for (auto obstacleSet : obstacleType.second)
  134. {
  135. VLC->biomeHandler->addObstacleSet(obstacleSet.second);
  136. count++;
  137. }
  138. }
  139. }
  140. logGlobal->info("Obstacle sets loaded: %d", count);
  141. objects.resize(256);
  142. std::vector<JsonNode> ret(dataSize);// create storage for 256 objects
  143. assert(dataSize == 256);
  144. CLegacyConfigParser namesParser(TextPath::builtin("Data/ObjNames.txt"));
  145. for (size_t i=0; i<256; i++)
  146. {
  147. ret[i]["name"].String() = namesParser.readString();
  148. namesParser.endLine();
  149. }
  150. JsonNode cregen1;
  151. JsonNode cregen4;
  152. CLegacyConfigParser cregen1Parser(TextPath::builtin("data/crgen1"));
  153. do
  154. {
  155. JsonNode subObject;
  156. subObject["name"].String() = cregen1Parser.readString();
  157. cregen1.Vector().push_back(subObject);
  158. }
  159. while(cregen1Parser.endLine());
  160. CLegacyConfigParser cregen4Parser(TextPath::builtin("data/crgen4"));
  161. do
  162. {
  163. JsonNode subObject;
  164. subObject["name"].String() = cregen4Parser.readString();
  165. cregen4.Vector().push_back(subObject);
  166. }
  167. while(cregen4Parser.endLine());
  168. ret[Obj::CREATURE_GENERATOR1]["subObjects"] = cregen1;
  169. ret[Obj::CREATURE_GENERATOR4]["subObjects"] = cregen4;
  170. ret[Obj::REFUGEE_CAMP]["subObjects"].Vector().push_back(ret[Obj::REFUGEE_CAMP]);
  171. ret[Obj::WAR_MACHINE_FACTORY]["subObjects"].Vector().push_back(ret[Obj::WAR_MACHINE_FACTORY]);
  172. return ret;
  173. }
  174. void CObjectClassesHandler::loadSubObject(const std::string & scope, const std::string & identifier, const JsonNode & entry, ObjectClass * obj)
  175. {
  176. auto object = loadSubObjectFromJson(scope, identifier, entry, obj, obj->objects.size());
  177. assert(object);
  178. obj->objects.push_back(object);
  179. registerObject(scope, obj->getJsonKey(), object->getSubTypeName(), object->subtype);
  180. for(const auto & compatID : entry["compatibilityIdentifiers"].Vector())
  181. registerObject(scope, obj->getJsonKey(), compatID.String(), object->subtype);
  182. }
  183. void CObjectClassesHandler::loadSubObject(const std::string & scope, const std::string & identifier, const JsonNode & entry, ObjectClass * obj, size_t index)
  184. {
  185. auto object = loadSubObjectFromJson(scope, identifier, entry, obj, index);
  186. assert(object);
  187. if (obj->objects.at(index) != nullptr)
  188. throw std::runtime_error("Attempt to load already loaded object:" + identifier);
  189. obj->objects.at(index) = object;
  190. registerObject(scope, obj->getJsonKey(), object->getSubTypeName(), object->subtype);
  191. for(const auto & compatID : entry["compatibilityIdentifiers"].Vector())
  192. registerObject(scope, obj->getJsonKey(), compatID.String(), object->subtype);
  193. }
  194. TObjectTypeHandler CObjectClassesHandler::loadSubObjectFromJson(const std::string & scope, const std::string & identifier, const JsonNode & entry, ObjectClass * obj, size_t index)
  195. {
  196. assert(identifier.find(':') == std::string::npos);
  197. assert(!scope.empty());
  198. std::string handler = obj->handlerName;
  199. if(!handlerConstructors.count(handler))
  200. {
  201. logMod->error("Handler with name %s was not found!", handler);
  202. // workaround for potential crash - if handler does not exists, continue with generic handler that is used for objects without any custom logc
  203. handler = "generic";
  204. assert(handlerConstructors.count(handler) != 0);
  205. }
  206. auto createdObject = handlerConstructors.at(handler)();
  207. createdObject->modScope = scope;
  208. createdObject->typeName = obj->identifier;
  209. createdObject->subTypeName = identifier;
  210. createdObject->type = obj->id;
  211. createdObject->subtype = index;
  212. createdObject->init(entry);
  213. auto range = legacyTemplates.equal_range(std::make_pair(obj->id, index));
  214. for (auto & templ : boost::make_iterator_range(range.first, range.second))
  215. {
  216. createdObject->addTemplate(templ.second);
  217. }
  218. legacyTemplates.erase(range.first, range.second);
  219. logGlobal->debug("Loaded object %s(%d)::%s(%d)", obj->getJsonKey(), obj->id, identifier, index);
  220. return createdObject;
  221. }
  222. ObjectClass::ObjectClass() = default;
  223. ObjectClass::~ObjectClass() = default;
  224. std::string ObjectClass::getJsonKey() const
  225. {
  226. return modScope + ':' + identifier;
  227. }
  228. std::string ObjectClass::getNameTextID() const
  229. {
  230. return TextIdentifier("object", modScope, identifier, "name").get();
  231. }
  232. std::string ObjectClass::getNameTranslated() const
  233. {
  234. return VLC->generaltexth->translate(getNameTextID());
  235. }
  236. std::unique_ptr<ObjectClass> CObjectClassesHandler::loadFromJson(const std::string & scope, const JsonNode & json, const std::string & name, size_t index)
  237. {
  238. auto obj = std::make_unique<ObjectClass>();
  239. obj->modScope = scope;
  240. obj->identifier = name;
  241. obj->handlerName = json["handler"].String();
  242. obj->base = json["base"];
  243. obj->id = index;
  244. VLC->generaltexth->registerString(scope, obj->getNameTextID(), json["name"].String());
  245. obj->objects.resize(json["lastReservedIndex"].Float() + 1);
  246. for (auto subData : json["types"].Struct())
  247. {
  248. if (!subData.second["index"].isNull())
  249. {
  250. const std::string & subMeta = subData.second["index"].getModScope();
  251. if ( subMeta == "core")
  252. {
  253. size_t subIndex = subData.second["index"].Integer();
  254. loadSubObject(subData.second.getModScope(), subData.first, subData.second, obj.get(), subIndex);
  255. }
  256. else
  257. {
  258. logMod->error("Object %s:%s.%s - attempt to load object with preset index! This option is reserved for built-in mod", subMeta, name, subData.first );
  259. loadSubObject(subData.second.getModScope(), subData.first, subData.second, obj.get());
  260. }
  261. }
  262. else
  263. loadSubObject(subData.second.getModScope(), subData.first, subData.second, obj.get());
  264. }
  265. if (obj->id == MapObjectID::MONOLITH_TWO_WAY)
  266. generateExtraMonolithsForRMG(obj.get());
  267. return obj;
  268. }
  269. void CObjectClassesHandler::loadObject(std::string scope, std::string name, const JsonNode & data)
  270. {
  271. objects.push_back(loadFromJson(scope, data, name, objects.size()));
  272. VLC->identifiersHandler->registerObject(scope, "object", name, objects.back()->id);
  273. }
  274. void CObjectClassesHandler::loadObject(std::string scope, std::string name, const JsonNode & data, size_t index)
  275. {
  276. assert(objects.at(index) == nullptr); // ensure that this id was not loaded before
  277. objects.at(index) = loadFromJson(scope, data, name, index);
  278. VLC->identifiersHandler->registerObject(scope, "object", name, objects.at(index)->id);
  279. }
  280. void CObjectClassesHandler::loadSubObject(const std::string & identifier, JsonNode config, MapObjectID ID, MapObjectSubID subID)
  281. {
  282. config.setType(JsonNode::JsonType::DATA_STRUCT); // ensure that input is not NULL
  283. assert(objects.at(ID.getNum()));
  284. if ( subID.getNum() >= objects.at(ID.getNum())->objects.size())
  285. objects.at(ID.getNum())->objects.resize(subID.getNum()+1);
  286. JsonUtils::inherit(config, objects.at(ID.getNum())->base);
  287. loadSubObject(config.getModScope(), identifier, config, objects.at(ID.getNum()).get(), subID.getNum());
  288. }
  289. void CObjectClassesHandler::removeSubObject(MapObjectID ID, MapObjectSubID subID)
  290. {
  291. assert(objects.at(ID.getNum()));
  292. objects.at(ID.getNum())->objects.at(subID.getNum()) = nullptr;
  293. }
  294. TObjectTypeHandler CObjectClassesHandler::getHandlerFor(MapObjectID type, MapObjectSubID subtype) const
  295. {
  296. try
  297. {
  298. if (objects.at(type.getNum()) == nullptr)
  299. return objects.front()->objects.front();
  300. auto subID = subtype.getNum();
  301. if (type == Obj::PRISON)
  302. subID = 0;
  303. auto result = objects.at(type.getNum())->objects.at(subID);
  304. if (result != nullptr)
  305. return result;
  306. }
  307. catch (std::out_of_range & e)
  308. {
  309. // Leave catch block silently
  310. }
  311. std::string errorString = "Failed to find object of type " + std::to_string(type.getNum()) + "::" + std::to_string(subtype.getNum());
  312. logGlobal->error(errorString);
  313. throw std::runtime_error(errorString);
  314. }
  315. TObjectTypeHandler CObjectClassesHandler::getHandlerFor(const std::string & scope, const std::string & type, const std::string & subtype) const
  316. {
  317. std::optional<si32> id = VLC->identifiers()->getIdentifier(scope, "object", type);
  318. if(id)
  319. {
  320. const auto & object = objects.at(id.value());
  321. std::optional<si32> subID = VLC->identifiers()->getIdentifier(scope, object->getJsonKey(), subtype);
  322. if (subID)
  323. return object->objects.at(subID.value());
  324. }
  325. std::string errorString = "Failed to find object of type " + type + "::" + subtype;
  326. logGlobal->error(errorString);
  327. throw std::runtime_error(errorString);
  328. }
  329. TObjectTypeHandler CObjectClassesHandler::getHandlerFor(CompoundMapObjectID compoundIdentifier) const
  330. {
  331. return getHandlerFor(compoundIdentifier.primaryID, compoundIdentifier.secondaryID);
  332. }
  333. std::set<MapObjectID> CObjectClassesHandler::knownObjects() const
  334. {
  335. std::set<MapObjectID> ret;
  336. for(auto & entry : objects)
  337. if (entry)
  338. ret.insert(entry->id);
  339. return ret;
  340. }
  341. std::set<MapObjectSubID> CObjectClassesHandler::knownSubObjects(MapObjectID primaryID) const
  342. {
  343. std::set<MapObjectSubID> ret;
  344. if (!objects.at(primaryID.getNum()))
  345. {
  346. logGlobal->error("Failed to find object %d", primaryID);
  347. return ret;
  348. }
  349. for(const auto & entry : objects.at(primaryID.getNum())->objects)
  350. if (entry)
  351. ret.insert(entry->subtype);
  352. return ret;
  353. }
  354. void CObjectClassesHandler::beforeValidate(JsonNode & object)
  355. {
  356. for (auto & entry : object["types"].Struct())
  357. {
  358. if (object.Struct().count("subObjects"))
  359. {
  360. const auto & vector = object["subObjects"].Vector();
  361. if (entry.second.Struct().count("index"))
  362. {
  363. size_t index = entry.second["index"].Integer();
  364. if (index < vector.size())
  365. JsonUtils::inherit(entry.second, vector[index]);
  366. }
  367. }
  368. JsonUtils::inherit(entry.second, object["base"]);
  369. for (auto & templ : entry.second["templates"].Struct())
  370. JsonUtils::inherit(templ.second, entry.second["base"]);
  371. }
  372. object.Struct().erase("subObjects");
  373. }
  374. void CObjectClassesHandler::afterLoadFinalization()
  375. {
  376. for(auto & entry : objects)
  377. {
  378. if (!entry)
  379. continue;
  380. for(const auto & obj : entry->objects)
  381. {
  382. if (!obj)
  383. continue;
  384. obj->afterLoadFinalization();
  385. if(obj->getTemplates().empty())
  386. logGlobal->warn("No templates found for %s:%s", entry->getJsonKey(), obj->getJsonKey());
  387. }
  388. }
  389. }
  390. void CObjectClassesHandler::generateExtraMonolithsForRMG(ObjectClass * container)
  391. {
  392. //duplicate existing two-way portals to make reserve for RMG
  393. auto& portalVec = container->objects;
  394. //FIXME: Monoliths in this vector can be already not useful for every terrain
  395. const size_t portalCount = portalVec.size();
  396. //Invalid portals will be skipped and portalVec size stays unchanged
  397. for (size_t i = portalCount; portalVec.size() < 100; ++i)
  398. {
  399. auto index = static_cast<si32>(i % portalCount);
  400. auto portal = portalVec[index];
  401. auto templates = portal->getTemplates();
  402. if (templates.empty() || !templates[0]->canBePlacedAtAnyTerrain())
  403. {
  404. continue; //Do not clone HoTA water-only portals or any others we can't use
  405. }
  406. //deep copy of noncopyable object :?
  407. auto newPortal = std::make_shared<CDefaultObjectTypeHandler<CGMonolith>>();
  408. newPortal->rmgInfo = portal->getRMGInfo();
  409. newPortal->templates = portal->getTemplates();
  410. newPortal->sounds = portal->getSounds();
  411. newPortal->aiValue = portal->getAiValue();
  412. newPortal->battlefield = portal->battlefield; //getter is not initialized at this point
  413. newPortal->modScope = portal->modScope; //private
  414. newPortal->typeName = portal->getTypeName();
  415. newPortal->subTypeName = std::string("monolith") + std::to_string(portalVec.size());
  416. newPortal->type = portal->getIndex();
  417. // Inconsintent original indexing: monolith1 has index 0
  418. newPortal->subtype = portalVec.size() - 1; //indexes must be unique, they are returned as a set
  419. newPortal->blockVisit = portal->blockVisit;
  420. newPortal->removable = portal->removable;
  421. portalVec.push_back(newPortal);
  422. registerObject(newPortal->modScope, container->getJsonKey(), newPortal->subTypeName, newPortal->subtype);
  423. }
  424. }
  425. std::string CObjectClassesHandler::getObjectName(MapObjectID type, MapObjectSubID subtype) const
  426. {
  427. const auto handler = getHandlerFor(type, subtype);
  428. if (handler && handler->hasNameTextID())
  429. return handler->getNameTranslated();
  430. if (objects.at(type.getNum()))
  431. return objects.at(type.getNum())->getNameTranslated();
  432. return objects.front()->getNameTranslated();
  433. }
  434. SObjectSounds CObjectClassesHandler::getObjectSounds(MapObjectID type, MapObjectSubID subtype) const
  435. {
  436. // TODO: these objects may have subID's that does not have associated handler:
  437. // Prison: uses hero type as subID
  438. // Hero: uses hero type as subID, but registers hero classes as subtypes
  439. // Spell scroll: uses spell ID as subID
  440. if(type == Obj::PRISON || type == Obj::HERO || type == Obj::SPELL_SCROLL)
  441. subtype = 0;
  442. if(objects.at(type.getNum()))
  443. return getHandlerFor(type, subtype)->getSounds();
  444. else
  445. return objects.front()->objects.front()->getSounds();
  446. }
  447. std::string CObjectClassesHandler::getObjectHandlerName(MapObjectID type) const
  448. {
  449. if (objects.at(type.getNum()))
  450. return objects.at(type.getNum())->handlerName;
  451. else
  452. return objects.front()->handlerName;
  453. }
  454. std::string CObjectClassesHandler::getJsonKey(MapObjectID type) const
  455. {
  456. if (objects.at(type.getNum()) != nullptr)
  457. return objects.at(type.getNum())->getJsonKey();
  458. logGlobal->warn("Unknown object of type %d!", type);
  459. return objects.front()->getJsonKey();
  460. }
  461. VCMI_LIB_NAMESPACE_END