CObjectClassesHandler.cpp 13 KB

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