CObjectClassesHandler.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  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("prison", CGHeroInstance);
  70. SET_HANDLER("questGuard", CGQuestGuard);
  71. SET_HANDLER("resource", CGResource);
  72. SET_HANDLER("scholar", CGScholar);
  73. SET_HANDLER("seerHut", CGSeerHut);
  74. SET_HANDLER("shipyard", CGShipyard);
  75. SET_HANDLER("shrine", CGShrine);
  76. SET_HANDLER("sign", CGSignBottle);
  77. SET_HANDLER("siren", CGSirens);
  78. SET_HANDLER("monolith", CGMonolith);
  79. SET_HANDLER("subterraneanGate", CGSubterraneanGate);
  80. SET_HANDLER("whirlpool", CGWhirlpool);
  81. SET_HANDLER("university", CGUniversity);
  82. SET_HANDLER("oncePerHero", CGVisitableOPH);
  83. SET_HANDLER("oncePerWeek", CGVisitableOPW);
  84. SET_HANDLER("witch", CGWitchHut);
  85. #undef SET_HANDLER_CLASS
  86. #undef SET_HANDLER
  87. }
  88. std::vector<JsonNode> CObjectClassesHandler::loadLegacyData(size_t dataSize)
  89. {
  90. CLegacyConfigParser parser("Data/Objects.txt");
  91. size_t totalNumber = parser.readNumber(); // first line contains number of objects to read and nothing else
  92. parser.endLine();
  93. for (size_t i=0; i<totalNumber; i++)
  94. {
  95. ObjectTemplate templ;
  96. templ.readTxt(parser);
  97. parser.endLine();
  98. std::pair<si32, si32> key(templ.id.num, templ.subid);
  99. legacyTemplates.insert(std::make_pair(key, templ));
  100. }
  101. std::vector<JsonNode> ret(dataSize);// create storage for 256 objects
  102. assert(dataSize == 256);
  103. CLegacyConfigParser namesParser("Data/ObjNames.txt");
  104. for (size_t i=0; i<256; i++)
  105. {
  106. ret[i]["name"].String() = namesParser.readString();
  107. namesParser.endLine();
  108. }
  109. CLegacyConfigParser cregen1Parser("data/crgen1");
  110. do
  111. customNames[Obj::CREATURE_GENERATOR1].push_back(cregen1Parser.readString());
  112. while(cregen1Parser.endLine());
  113. CLegacyConfigParser cregen4Parser("data/crgen4");
  114. do
  115. customNames[Obj::CREATURE_GENERATOR4].push_back(cregen4Parser.readString());
  116. while(cregen4Parser.endLine());
  117. return ret;
  118. }
  119. /// selects preferred ID (or subID) for new object
  120. template<typename Map>
  121. si32 selectNextID(const JsonNode & fixedID, const Map & map, si32 defaultID)
  122. {
  123. if (!fixedID.isNull() && fixedID.Float() < defaultID)
  124. return fixedID.Float(); // H3M object with fixed ID
  125. if (map.empty())
  126. return defaultID; // no objects loaded, keep gap for H3M objects
  127. if (map.rbegin()->first >= defaultID)
  128. return map.rbegin()->first + 1; // some modded objects loaded, return next available
  129. return defaultID; // some H3M objects loaded, first modded found
  130. }
  131. void CObjectClassesHandler::loadObjectEntry(const JsonNode & entry, ObjectContainter * obj)
  132. {
  133. if (!handlerConstructors.count(obj->handlerName))
  134. {
  135. logGlobal->errorStream() << "Handler with name " << obj->handlerName << " was not found!";
  136. return;
  137. }
  138. si32 id = selectNextID(entry["index"], obj->objects, 1000);
  139. auto handler = handlerConstructors.at(obj->handlerName)();
  140. handler->setType(obj->id, id);
  141. if (customNames.count(obj->id) && customNames.at(obj->id).size() > id)
  142. handler->init(entry, customNames.at(obj->id).at(id));
  143. else
  144. handler->init(entry);
  145. if (handler->getTemplates().empty())
  146. {
  147. auto range = legacyTemplates.equal_range(std::make_pair(obj->id, id));
  148. for (auto & templ : boost::make_iterator_range(range.first, range.second))
  149. {
  150. handler->addTemplate(templ.second);
  151. }
  152. legacyTemplates.erase(range.first, range.second);
  153. }
  154. logGlobal->debugStream() << "Loaded object " << obj->id << ":" << id;
  155. assert(!obj->objects.count(id)); // DO NOT override
  156. obj->objects[id] = handler;
  157. }
  158. CObjectClassesHandler::ObjectContainter * CObjectClassesHandler::loadFromJson(const JsonNode & json)
  159. {
  160. auto obj = new ObjectContainter();
  161. obj->name = json["name"].String();
  162. obj->handlerName = json["handler"].String();
  163. obj->base = json["base"];
  164. obj->id = selectNextID(json["index"], objects, 256);
  165. for (auto entry : json["types"].Struct())
  166. {
  167. loadObjectEntry(entry.second, obj);
  168. }
  169. return obj;
  170. }
  171. void CObjectClassesHandler::loadObject(std::string scope, std::string name, const JsonNode & data)
  172. {
  173. auto object = loadFromJson(data);
  174. objects[object->id] = object;
  175. VLC->modh->identifiers.registerObject(scope, "object", name, object->id);
  176. }
  177. void CObjectClassesHandler::loadObject(std::string scope, std::string name, const JsonNode & data, size_t index)
  178. {
  179. auto object = loadFromJson(data);
  180. assert(objects[index] == nullptr); // ensure that this id was not loaded before
  181. objects[index] = object;
  182. VLC->modh->identifiers.registerObject(scope, "object", name, object->id);
  183. }
  184. void CObjectClassesHandler::loadSubObject(std::string name, JsonNode config, si32 ID, boost::optional<si32> subID)
  185. {
  186. config.setType(JsonNode::DATA_STRUCT); // ensure that input is not NULL
  187. assert(objects.count(ID));
  188. if (subID)
  189. {
  190. assert(objects.at(ID)->objects.count(subID.get()) == 0);
  191. assert(config["index"].isNull());
  192. config["index"].Float() = subID.get();
  193. }
  194. std::string oldMeta = config.meta; // FIXME: move into inheritNode?
  195. JsonUtils::inherit(config, objects.at(ID)->base);
  196. config.setMeta(oldMeta);
  197. loadObjectEntry(config, objects[ID]);
  198. }
  199. void CObjectClassesHandler::removeSubObject(si32 ID, si32 subID)
  200. {
  201. assert(objects.count(ID));
  202. assert(objects.at(ID)->objects.count(subID));
  203. objects.at(ID)->objects.erase(subID);
  204. }
  205. std::vector<bool> CObjectClassesHandler::getDefaultAllowed() const
  206. {
  207. return std::vector<bool>(); //TODO?
  208. }
  209. TObjectTypeHandler CObjectClassesHandler::getHandlerFor(si32 type, si32 subtype) const
  210. {
  211. if (objects.count(type))
  212. {
  213. if (objects.at(type)->objects.count(subtype))
  214. return objects.at(type)->objects.at(subtype);
  215. }
  216. logGlobal->errorStream() << "Failed to find object of type " << type << ":" << subtype;
  217. assert(0); // FIXME: throw error?
  218. return nullptr;
  219. }
  220. std::set<si32> CObjectClassesHandler::knownObjects() const
  221. {
  222. std::set<si32> ret;
  223. for (auto entry : objects)
  224. ret.insert(entry.first);
  225. return ret;
  226. }
  227. std::set<si32> CObjectClassesHandler::knownSubObjects(si32 primaryID) const
  228. {
  229. std::set<si32> ret;
  230. if (objects.count(primaryID))
  231. {
  232. for (auto entry : objects.at(primaryID)->objects)
  233. ret.insert(entry.first);
  234. }
  235. return ret;
  236. }
  237. void CObjectClassesHandler::beforeValidate(JsonNode & object)
  238. {
  239. for (auto & entry : object["types"].Struct())
  240. {
  241. JsonUtils::inherit(entry.second, object["base"]);
  242. for (auto & templ : entry.second["templates"].Struct())
  243. {
  244. JsonUtils::inherit(templ.second, entry.second["base"]);
  245. }
  246. }
  247. }
  248. void CObjectClassesHandler::afterLoadFinalization()
  249. {
  250. for (auto entry : objects)
  251. {
  252. for (auto obj : entry.second->objects)
  253. {
  254. obj.second->afterLoadFinalization();
  255. if (obj.second->getTemplates().empty())
  256. logGlobal->warnStream() << "No templates found for " << entry.first << ":" << obj.first;
  257. }
  258. }
  259. }
  260. std::string CObjectClassesHandler::getObjectName(si32 type) const
  261. {
  262. if (objects.count(type))
  263. return objects.at(type)->name;
  264. logGlobal->errorStream() << "Access to non existing object of type " << type;
  265. return "";
  266. }
  267. std::string CObjectClassesHandler::getObjectName(si32 type, si32 subtype) const
  268. {
  269. if (knownSubObjects(type).count(subtype))
  270. {
  271. auto name = getHandlerFor(type, subtype)->getCustomName();
  272. if (name)
  273. return name.get();
  274. }
  275. return getObjectName(type);
  276. }
  277. std::string CObjectClassesHandler::getObjectHandlerName(si32 type) const
  278. {
  279. return objects.at(type)->handlerName;
  280. }
  281. void AObjectTypeHandler::setType(si32 type, si32 subtype)
  282. {
  283. this->type = type;
  284. this->subtype = subtype;
  285. }
  286. static ui32 loadJsonOrMax(const JsonNode & input)
  287. {
  288. if (input.isNull())
  289. return std::numeric_limits<ui32>::max();
  290. else
  291. return input.Float();
  292. }
  293. void AObjectTypeHandler::init(const JsonNode & input, boost::optional<std::string> name)
  294. {
  295. base = input["base"];
  296. if (!input["rmg"].isNull())
  297. {
  298. rmgInfo.value = input["rmg"]["value"].Float();
  299. rmgInfo.mapLimit = loadJsonOrMax(input["rmg"]["mapLimit"]);
  300. rmgInfo.zoneLimit = loadJsonOrMax(input["rmg"]["zoneLimit"]);
  301. rmgInfo.rarity = input["rmg"]["rarity"].Float();
  302. } // else block is not needed - set in constructor
  303. for (auto entry : input["templates"].Struct())
  304. {
  305. entry.second.setType(JsonNode::DATA_STRUCT);
  306. JsonUtils::inherit(entry.second, base);
  307. ObjectTemplate tmpl;
  308. tmpl.id = Obj(type);
  309. tmpl.subid = subtype;
  310. tmpl.stringID = entry.first; // FIXME: create "fullID" - type.object.template?
  311. tmpl.readJson(entry.second);
  312. templates.push_back(tmpl);
  313. }
  314. if (input["name"].isNull())
  315. objectName = name;
  316. else
  317. objectName.reset(input["name"].String());
  318. initTypeData(input);
  319. }
  320. bool AObjectTypeHandler::objectFilter(const CGObjectInstance *, const ObjectTemplate &) const
  321. {
  322. return false; // by default there are no overrides
  323. }
  324. void AObjectTypeHandler::initTypeData(const JsonNode & input)
  325. {
  326. // empty implementation for overrides
  327. }
  328. boost::optional<std::string> AObjectTypeHandler::getCustomName() const
  329. {
  330. return objectName;
  331. }
  332. void AObjectTypeHandler::addTemplate(ObjectTemplate templ)
  333. {
  334. templ.id = Obj(type);
  335. templ.subid = subtype;
  336. templates.push_back(templ);
  337. }
  338. void AObjectTypeHandler::addTemplate(JsonNode config)
  339. {
  340. config.setType(JsonNode::DATA_STRUCT); // ensure that input is not null
  341. JsonUtils::inherit(config, base);
  342. ObjectTemplate tmpl;
  343. tmpl.id = Obj(type);
  344. tmpl.subid = subtype;
  345. tmpl.stringID = ""; // TODO?
  346. tmpl.readJson(config);
  347. addTemplate(tmpl);
  348. }
  349. std::vector<ObjectTemplate> AObjectTypeHandler::getTemplates() const
  350. {
  351. return templates;
  352. }
  353. std::vector<ObjectTemplate> AObjectTypeHandler::getTemplates(si32 terrainType) const// FIXME: replace with ETerrainType
  354. {
  355. std::vector<ObjectTemplate> templates = getTemplates();
  356. std::vector<ObjectTemplate> filtered;
  357. std::copy_if(templates.begin(), templates.end(), std::back_inserter(filtered), [&](const ObjectTemplate & obj)
  358. {
  359. return obj.canBePlacedAt(ETerrainType(terrainType));
  360. });
  361. // H3 defines allowed terrains in a weird way - artifacts, monsters and resources have faulty masks here
  362. // Perhaps we should re-define faulty templates and remove this workaround (already done for resources)
  363. if (type == Obj::ARTIFACT || type == Obj::MONSTER)
  364. return templates;
  365. else
  366. return filtered;
  367. }
  368. boost::optional<ObjectTemplate> AObjectTypeHandler::getOverride(si32 terrainType, const CGObjectInstance * object) const
  369. {
  370. std::vector<ObjectTemplate> ret = getTemplates(terrainType);
  371. for (auto & tmpl : ret)
  372. {
  373. if (objectFilter(object, tmpl))
  374. return tmpl;
  375. }
  376. return boost::optional<ObjectTemplate>();
  377. }
  378. const RandomMapInfo & AObjectTypeHandler::getRMGInfo()
  379. {
  380. return rmgInfo;
  381. }
  382. bool AObjectTypeHandler::isStaticObject()
  383. {
  384. return false; // most of classes are not static
  385. }
  386. void AObjectTypeHandler::afterLoadFinalization()
  387. {
  388. }