CStackBasicDescriptor.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /*
  2. * CStackBasicDescriptor.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 "CStackBasicDescriptor.h"
  12. #include "../../CCreatureHandler.h"
  13. #include "../../GameLibrary.h"
  14. #include "../../serializer/JsonSerializeFormat.h"
  15. VCMI_LIB_NAMESPACE_BEGIN
  16. //This constructor should be placed here to avoid side effects
  17. CStackBasicDescriptor::CStackBasicDescriptor() = default;
  18. CStackBasicDescriptor::CStackBasicDescriptor(const CreatureID & id, TQuantity Count):
  19. typeID(id),
  20. count(Count)
  21. {
  22. }
  23. CStackBasicDescriptor::CStackBasicDescriptor(const CCreature *c, TQuantity Count)
  24. : typeID(c ? c->getId() : CreatureID()), count(Count)
  25. {
  26. }
  27. const CCreature * CStackBasicDescriptor::getCreature() const
  28. {
  29. return typeID.hasValue() ? typeID.toCreature() : nullptr;
  30. }
  31. const Creature * CStackBasicDescriptor::getType() const
  32. {
  33. return typeID.hasValue() ? typeID.toEntity(LIBRARY) : nullptr;
  34. }
  35. CreatureID CStackBasicDescriptor::getId() const
  36. {
  37. return typeID;
  38. }
  39. TQuantity CStackBasicDescriptor::getCount() const
  40. {
  41. return count;
  42. }
  43. void CStackBasicDescriptor::setType(const CCreature * c)
  44. {
  45. typeID = c ? c->getId() : CreatureID();
  46. }
  47. void CStackBasicDescriptor::setCount(TQuantity newCount)
  48. {
  49. assert(newCount >= 0);
  50. count = newCount;
  51. }
  52. bool operator== (const CStackBasicDescriptor & l, const CStackBasicDescriptor & r)
  53. {
  54. return l.typeID == r.typeID && l.count == r.count;
  55. }
  56. void CStackBasicDescriptor::serializeJson(JsonSerializeFormat & handler)
  57. {
  58. handler.serializeInt("amount", count);
  59. if(handler.saving)
  60. {
  61. if(typeID.hasValue())
  62. {
  63. std::string typeName = typeID.toEntity(LIBRARY)->getJsonKey();
  64. handler.serializeString("type", typeName);
  65. }
  66. }
  67. else
  68. {
  69. std::string typeName;
  70. handler.serializeString("type", typeName);
  71. if(!typeName.empty())
  72. setType(CreatureID(CreatureID::decode(typeName)).toCreature());
  73. }
  74. }
  75. VCMI_LIB_NAMESPACE_END