1
0
mirror of https://github.com/vcmi/vcmi.git synced 2024-11-24 08:32:34 +02:00

Dividing rewarbadle objects into separate files

This commit is contained in:
nordsoft 2023-04-30 04:39:31 +04:00
parent 67bfacfcf7
commit ac8f390cf8
9 changed files with 1063 additions and 987 deletions

View File

@ -65,11 +65,13 @@ macro(add_main_lib TARGET_NAME LIBRARY_TYPE)
${MAIN_LIB_DIR}/mapObjects/CObjectHandler.cpp
${MAIN_LIB_DIR}/mapObjects/CommonConstructors.cpp
${MAIN_LIB_DIR}/mapObjects/CQuest.cpp
${MAIN_LIB_DIR}/mapObjects/CRandomRewardObjectInfo.cpp
${MAIN_LIB_DIR}/mapObjects/CRewardableConstructor.cpp
${MAIN_LIB_DIR}/mapObjects/CRewardableObject.cpp
${MAIN_LIB_DIR}/mapObjects/JsonRandom.cpp
${MAIN_LIB_DIR}/mapObjects/MiscObjects.cpp
${MAIN_LIB_DIR}/mapObjects/ObjectTemplate.cpp
${MAIN_LIB_DIR}/mapObjects/Rewardable.cpp
${MAIN_LIB_DIR}/mapping/CCampaignHandler.cpp
${MAIN_LIB_DIR}/mapping/CDrawRoadsOperation.cpp
@ -337,12 +339,14 @@ macro(add_main_lib TARGET_NAME LIBRARY_TYPE)
${MAIN_LIB_DIR}/mapObjects/CObjectHandler.h
${MAIN_LIB_DIR}/mapObjects/CommonConstructors.h
${MAIN_LIB_DIR}/mapObjects/CQuest.h
${MAIN_LIB_DIR}/mapObjects/CRandomRewardObjectInfo.h
${MAIN_LIB_DIR}/mapObjects/CRewardableConstructor.h
${MAIN_LIB_DIR}/mapObjects/CRewardableObject.h
${MAIN_LIB_DIR}/mapObjects/JsonRandom.h
${MAIN_LIB_DIR}/mapObjects/MapObjects.h
${MAIN_LIB_DIR}/mapObjects/MiscObjects.h
${MAIN_LIB_DIR}/mapObjects/ObjectTemplate.h
${MAIN_LIB_DIR}/mapObjects/Rewardable.h
${MAIN_LIB_DIR}/mapping/CCampaignHandler.h
${MAIN_LIB_DIR}/mapping/CDrawRoadsOperation.h

View File

@ -0,0 +1,310 @@
/*
* CRandomRewardObjectInfo.cpp, part of VCMI engine
*
* Authors: listed in file AUTHORS in main folder
*
* License: GNU General Public License v2.0 or later
* Full text of license available in license.txt file, in main folder
*
*/
#include "StdInc.h"
#include "CRandomRewardObjectInfo.h"
#include "../CRandomGenerator.h"
#include "../StringConstants.h"
#include "../CCreatureHandler.h"
#include "../CModHandler.h"
#include "JsonRandom.h"
#include "../IGameCallback.h"
#include "../CGeneralTextHandler.h"
VCMI_LIB_NAMESPACE_BEGIN
namespace {
MetaString loadMessage(const JsonNode & value)
{
MetaString ret;
if (value.isNumber())
ret.addTxt(MetaString::ADVOB_TXT, static_cast<ui32>(value.Float()));
else
ret << value.String();
return ret;
}
bool testForKey(const JsonNode & value, const std::string & key)
{
for(const auto & reward : value["rewards"].Vector())
{
if (!reward[key].isNull())
return true;
}
return false;
}
}
void CRandomRewardObjectInfo::init(const JsonNode & objectConfig)
{
parameters = objectConfig;
}
TRewardLimitersList CRandomRewardObjectInfo::configureSublimiters(Rewardable::Configuration & object, CRandomGenerator & rng, const JsonNode & source) const
{
TRewardLimitersList result;
for (const auto & input : source.Vector())
{
auto newLimiter = std::make_shared<CRewardLimiter>();
configureLimiter(object, rng, *newLimiter, input);
result.push_back(newLimiter);
}
return result;
}
void CRandomRewardObjectInfo::configureLimiter(Rewardable::Configuration & object, CRandomGenerator & rng, CRewardLimiter & limiter, const JsonNode & source) const
{
std::vector<SpellID> spells;
for (size_t i=0; i<6; i++)
IObjectInterface::cb->getAllowedSpells(spells, static_cast<ui16>(i));
limiter.dayOfWeek = JsonRandom::loadValue(source["dayOfWeek"], rng);
limiter.daysPassed = JsonRandom::loadValue(source["daysPassed"], rng);
limiter.heroExperience = JsonRandom::loadValue(source["heroExperience"], rng);
limiter.heroLevel = JsonRandom::loadValue(source["heroLevel"], rng)
+ JsonRandom::loadValue(source["minLevel"], rng); // VCMI 1.1 compatibilty
limiter.manaPercentage = JsonRandom::loadValue(source["manaPercentage"], rng);
limiter.manaPoints = JsonRandom::loadValue(source["manaPoints"], rng);
limiter.resources = JsonRandom::loadResources(source["resources"], rng);
limiter.primary = JsonRandom::loadPrimary(source["primary"], rng);
limiter.secondary = JsonRandom::loadSecondary(source["secondary"], rng);
limiter.artifacts = JsonRandom::loadArtifacts(source["artifacts"], rng);
limiter.spells = JsonRandom::loadSpells(source["spells"], rng, spells);
limiter.creatures = JsonRandom::loadCreatures(source["creatures"], rng);
limiter.allOf = configureSublimiters(object, rng, source["allOf"] );
limiter.anyOf = configureSublimiters(object, rng, source["anyOf"] );
limiter.noneOf = configureSublimiters(object, rng, source["noneOf"] );
}
void CRandomRewardObjectInfo::configureReward(Rewardable::Configuration & object, CRandomGenerator & rng, CRewardInfo & reward, const JsonNode & source) const
{
reward.resources = JsonRandom::loadResources(source["resources"], rng);
reward.heroExperience = JsonRandom::loadValue(source["heroExperience"], rng)
+ JsonRandom::loadValue(source["gainedExp"], rng); // VCMI 1.1 compatibilty
reward.heroLevel = JsonRandom::loadValue(source["heroLevel"], rng)
+ JsonRandom::loadValue(source["gainedLevels"], rng); // VCMI 1.1 compatibilty
reward.manaDiff = JsonRandom::loadValue(source["manaPoints"], rng);
reward.manaOverflowFactor = JsonRandom::loadValue(source["manaOverflowFactor"], rng);
reward.manaPercentage = JsonRandom::loadValue(source["manaPercentage"], rng, -1);
reward.movePoints = JsonRandom::loadValue(source["movePoints"], rng);
reward.movePercentage = JsonRandom::loadValue(source["movePercentage"], rng, -1);
reward.removeObject = source["removeObject"].Bool();
reward.bonuses = JsonRandom::loadBonuses(source["bonuses"]);
reward.primary = JsonRandom::loadPrimary(source["primary"], rng);
reward.secondary = JsonRandom::loadSecondary(source["secondary"], rng);
std::vector<SpellID> spells;
for (size_t i=0; i<6; i++)
IObjectInterface::cb->getAllowedSpells(spells, static_cast<ui16>(i));
reward.artifacts = JsonRandom::loadArtifacts(source["artifacts"], rng);
reward.spells = JsonRandom::loadSpells(source["spells"], rng, spells);
reward.creatures = JsonRandom::loadCreatures(source["creatures"], rng);
if(!source["spellCast"].isNull() && source["spellCast"].isStruct())
{
reward.spellCast.first = JsonRandom::loadSpell(source["spellCast"]["spell"], rng);
reward.spellCast.second = source["spellCast"]["schoolLevel"].Integer();
}
for ( auto node : source["changeCreatures"].Struct() )
{
CreatureID from(VLC->modh->identifiers.getIdentifier(node.second.meta, "creature", node.first).value());
CreatureID dest(VLC->modh->identifiers.getIdentifier(node.second.meta, "creature", node.second.String()).value());
reward.extraComponents.emplace_back(Component::EComponentType::CREATURE, dest.getNum(), 0, 0);
reward.creaturesChange[from] = dest;
}
}
void CRandomRewardObjectInfo::configureResetInfo(Rewardable::Configuration & object, CRandomGenerator & rng, CRewardResetInfo & resetParameters, const JsonNode & source) const
{
resetParameters.period = static_cast<ui32>(source["period"].Float());
resetParameters.visitors = source["visitors"].Bool();
resetParameters.rewards = source["rewards"].Bool();
}
void CRandomRewardObjectInfo::configureRewards(
Rewardable::Configuration & object,
CRandomGenerator & rng, const
JsonNode & source,
std::map<si32, si32> & thrownDice,
CRewardVisitInfo::ERewardEventType event ) const
{
for (const JsonNode & reward : source.Vector())
{
if (!reward["appearChance"].isNull())
{
JsonNode chance = reward["appearChance"];
si32 diceID = static_cast<si32>(chance["dice"].Float());
if (thrownDice.count(diceID) == 0)
thrownDice[diceID] = rng.getIntRange(0, 99)();
if (!chance["min"].isNull())
{
int min = static_cast<int>(chance["min"].Float());
if (min > thrownDice[diceID])
continue;
}
if (!chance["max"].isNull())
{
int max = static_cast<int>(chance["max"].Float());
if (max <= thrownDice[diceID])
continue;
}
}
CRewardVisitInfo info;
configureLimiter(object, rng, info.limiter, reward["limiter"]);
configureReward(object, rng, info.reward, reward);
info.visitType = event;
info.message = loadMessage(reward["message"]);
for (const auto & artifact : info.reward.artifacts )
info.message.addReplacement(MetaString::ART_NAMES, artifact.getNum());
for (const auto & artifact : info.reward.spells )
info.message.addReplacement(MetaString::SPELL_NAME, artifact.getNum());
object.info.push_back(info);
}
}
void CRandomRewardObjectInfo::configureObject(Rewardable::Configuration & object, CRandomGenerator & rng) const
{
object.info.clear();
std::map<si32, si32> thrownDice;
configureRewards(object, rng, parameters["rewards"], thrownDice, CRewardVisitInfo::EVENT_FIRST_VISIT);
configureRewards(object, rng, parameters["onVisited"], thrownDice, CRewardVisitInfo::EVENT_ALREADY_VISITED);
configureRewards(object, rng, parameters["onEmpty"], thrownDice, CRewardVisitInfo::EVENT_NOT_AVAILABLE);
object.onSelect = loadMessage(parameters["onSelectMessage"]);
if (!parameters["onVisitedMessage"].isNull())
{
CRewardVisitInfo onVisited;
onVisited.visitType = CRewardVisitInfo::EVENT_ALREADY_VISITED;
onVisited.message = loadMessage(parameters["onVisitedMessage"]);
object.info.push_back(onVisited);
}
if (!parameters["onEmptyMessage"].isNull())
{
CRewardVisitInfo onEmpty;
onEmpty.visitType = CRewardVisitInfo::EVENT_NOT_AVAILABLE;
onEmpty.message = loadMessage(parameters["onEmptyMessage"]);
object.info.push_back(onEmpty);
}
configureResetInfo(object, rng, object.resetParameters, parameters["resetParameters"]);
object.canRefuse = parameters["canRefuse"].Bool();
if(parameters["showInInfobox"].isNull())
object.infoWindowType = EInfoWindowMode::AUTO;
else
object.infoWindowType = parameters["showInInfobox"].Bool() ? EInfoWindowMode::INFO : EInfoWindowMode::MODAL;
auto visitMode = parameters["visitMode"].String();
for(int i = 0; i < Rewardable::VisitModeString.size(); ++i)
{
if(Rewardable::VisitModeString[i] == visitMode)
{
object.visitMode = i;
break;
}
}
auto selectMode = parameters["selectMode"].String();
for(int i = 0; i < Rewardable::SelectModeString.size(); ++i)
{
if(Rewardable::SelectModeString[i] == selectMode)
{
object.selectMode = i;
break;
}
}
}
bool CRandomRewardObjectInfo::givesResources() const
{
return testForKey(parameters, "resources");
}
bool CRandomRewardObjectInfo::givesExperience() const
{
return testForKey(parameters, "gainedExp") || testForKey(parameters, "gainedLevels");
}
bool CRandomRewardObjectInfo::givesMana() const
{
return testForKey(parameters, "manaPoints") || testForKey(parameters, "manaPercentage");
}
bool CRandomRewardObjectInfo::givesMovement() const
{
return testForKey(parameters, "movePoints") || testForKey(parameters, "movePercentage");
}
bool CRandomRewardObjectInfo::givesPrimarySkills() const
{
return testForKey(parameters, "primary");
}
bool CRandomRewardObjectInfo::givesSecondarySkills() const
{
return testForKey(parameters, "secondary");
}
bool CRandomRewardObjectInfo::givesArtifacts() const
{
return testForKey(parameters, "artifacts");
}
bool CRandomRewardObjectInfo::givesCreatures() const
{
return testForKey(parameters, "spells");
}
bool CRandomRewardObjectInfo::givesSpells() const
{
return testForKey(parameters, "creatures");
}
bool CRandomRewardObjectInfo::givesBonuses() const
{
return testForKey(parameters, "bonuses");
}
const JsonNode & CRandomRewardObjectInfo::getParameters() const
{
return parameters;
}
VCMI_LIB_NAMESPACE_END

View File

@ -0,0 +1,60 @@
/*
* CRandomRewardObjectInfo.h, part of VCMI engine
*
* Authors: listed in file AUTHORS in main folder
*
* License: GNU General Public License v2.0 or later
* Full text of license available in license.txt file, in main folder
*
*/
#pragma once
#include "../JsonNode.h"
#include "CObjectClassesHandler.h"
#include "Rewardable.h"
VCMI_LIB_NAMESPACE_BEGIN
class CRandomGenerator;
class DLL_LINKAGE CRandomRewardObjectInfo : public IObjectInfo
{
JsonNode parameters;
void configureRewards(Rewardable::Configuration & object, CRandomGenerator & rng, const JsonNode & source, std::map<si32, si32> & thrownDice, CRewardVisitInfo::ERewardEventType mode) const;
void configureLimiter(Rewardable::Configuration & object, CRandomGenerator & rng, CRewardLimiter & limiter, const JsonNode & source) const;
TRewardLimitersList configureSublimiters(Rewardable::Configuration & object, CRandomGenerator & rng, const JsonNode & source) const;
void configureReward(Rewardable::Configuration & object, CRandomGenerator & rng, CRewardInfo & info, const JsonNode & source) const;
void configureResetInfo(Rewardable::Configuration & object, CRandomGenerator & rng, CRewardResetInfo & info, const JsonNode & source) const;
public:
const JsonNode & getParameters() const;
bool givesResources() const override;
bool givesExperience() const override;
bool givesMana() const override;
bool givesMovement() const override;
bool givesPrimarySkills() const override;
bool givesSecondarySkills() const override;
bool givesArtifacts() const override;
bool givesCreatures() const override;
bool givesSpells() const override;
bool givesBonuses() const override;
void configureObject(Rewardable::Configuration & object, CRandomGenerator & rng) const;
void init(const JsonNode & objectConfig);
template <typename Handler> void serialize(Handler &h, const int version)
{
h & parameters;
}
};
VCMI_LIB_NAMESPACE_END

View File

@ -9,303 +9,12 @@
*/
#include "StdInc.h"
#include "CRewardableConstructor.h"
#include "../CRandomGenerator.h"
#include "../StringConstants.h"
#include "../CCreatureHandler.h"
#include "../CModHandler.h"
#include "JsonRandom.h"
#include "../IGameCallback.h"
#include "CRewardableObject.h"
#include "../CGeneralTextHandler.h"
#include "../IGameCallback.h"
VCMI_LIB_NAMESPACE_BEGIN
namespace {
MetaString loadMessage(const JsonNode & value)
{
MetaString ret;
if (value.isNumber())
ret.addTxt(MetaString::ADVOB_TXT, static_cast<ui32>(value.Float()));
else
ret << value.String();
return ret;
}
bool testForKey(const JsonNode & value, const std::string & key)
{
for(const auto & reward : value["rewards"].Vector())
{
if (!reward[key].isNull())
return true;
}
return false;
}
}
void CRandomRewardObjectInfo::init(const JsonNode & objectConfig)
{
parameters = objectConfig;
}
TRewardLimitersList CRandomRewardObjectInfo::configureSublimiters(Rewardable::Configuration & object, CRandomGenerator & rng, const JsonNode & source) const
{
TRewardLimitersList result;
for (const auto & input : source.Vector())
{
auto newLimiter = std::make_shared<CRewardLimiter>();
configureLimiter(object, rng, *newLimiter, input);
result.push_back(newLimiter);
}
return result;
}
void CRandomRewardObjectInfo::configureLimiter(Rewardable::Configuration & object, CRandomGenerator & rng, CRewardLimiter & limiter, const JsonNode & source) const
{
std::vector<SpellID> spells;
for (size_t i=0; i<6; i++)
IObjectInterface::cb->getAllowedSpells(spells, static_cast<ui16>(i));
limiter.dayOfWeek = JsonRandom::loadValue(source["dayOfWeek"], rng);
limiter.daysPassed = JsonRandom::loadValue(source["daysPassed"], rng);
limiter.heroExperience = JsonRandom::loadValue(source["heroExperience"], rng);
limiter.heroLevel = JsonRandom::loadValue(source["heroLevel"], rng)
+ JsonRandom::loadValue(source["minLevel"], rng); // VCMI 1.1 compatibilty
limiter.manaPercentage = JsonRandom::loadValue(source["manaPercentage"], rng);
limiter.manaPoints = JsonRandom::loadValue(source["manaPoints"], rng);
limiter.resources = JsonRandom::loadResources(source["resources"], rng);
limiter.primary = JsonRandom::loadPrimary(source["primary"], rng);
limiter.secondary = JsonRandom::loadSecondary(source["secondary"], rng);
limiter.artifacts = JsonRandom::loadArtifacts(source["artifacts"], rng);
limiter.spells = JsonRandom::loadSpells(source["spells"], rng, spells);
limiter.creatures = JsonRandom::loadCreatures(source["creatures"], rng);
limiter.allOf = configureSublimiters(object, rng, source["allOf"] );
limiter.anyOf = configureSublimiters(object, rng, source["anyOf"] );
limiter.noneOf = configureSublimiters(object, rng, source["noneOf"] );
}
void CRandomRewardObjectInfo::configureReward(Rewardable::Configuration & object, CRandomGenerator & rng, CRewardInfo & reward, const JsonNode & source) const
{
reward.resources = JsonRandom::loadResources(source["resources"], rng);
reward.heroExperience = JsonRandom::loadValue(source["heroExperience"], rng)
+ JsonRandom::loadValue(source["gainedExp"], rng); // VCMI 1.1 compatibilty
reward.heroLevel = JsonRandom::loadValue(source["heroLevel"], rng)
+ JsonRandom::loadValue(source["gainedLevels"], rng); // VCMI 1.1 compatibilty
reward.manaDiff = JsonRandom::loadValue(source["manaPoints"], rng);
reward.manaOverflowFactor = JsonRandom::loadValue(source["manaOverflowFactor"], rng);
reward.manaPercentage = JsonRandom::loadValue(source["manaPercentage"], rng, -1);
reward.movePoints = JsonRandom::loadValue(source["movePoints"], rng);
reward.movePercentage = JsonRandom::loadValue(source["movePercentage"], rng, -1);
reward.removeObject = source["removeObject"].Bool();
reward.bonuses = JsonRandom::loadBonuses(source["bonuses"]);
reward.primary = JsonRandom::loadPrimary(source["primary"], rng);
reward.secondary = JsonRandom::loadSecondary(source["secondary"], rng);
std::vector<SpellID> spells;
for (size_t i=0; i<6; i++)
IObjectInterface::cb->getAllowedSpells(spells, static_cast<ui16>(i));
reward.artifacts = JsonRandom::loadArtifacts(source["artifacts"], rng);
reward.spells = JsonRandom::loadSpells(source["spells"], rng, spells);
reward.creatures = JsonRandom::loadCreatures(source["creatures"], rng);
if(!source["spellCast"].isNull() && source["spellCast"].isStruct())
{
reward.spellCast.first = JsonRandom::loadSpell(source["spellCast"]["spell"], rng);
reward.spellCast.second = source["spellCast"]["schoolLevel"].Integer();
}
for ( auto node : source["changeCreatures"].Struct() )
{
CreatureID from(VLC->modh->identifiers.getIdentifier(node.second.meta, "creature", node.first).value());
CreatureID dest(VLC->modh->identifiers.getIdentifier(node.second.meta, "creature", node.second.String()).value());
reward.extraComponents.emplace_back(Component::EComponentType::CREATURE, dest.getNum(), 0, 0);
reward.creaturesChange[from] = dest;
}
}
void CRandomRewardObjectInfo::configureResetInfo(Rewardable::Configuration & object, CRandomGenerator & rng, CRewardResetInfo & resetParameters, const JsonNode & source) const
{
resetParameters.period = static_cast<ui32>(source["period"].Float());
resetParameters.visitors = source["visitors"].Bool();
resetParameters.rewards = source["rewards"].Bool();
}
void CRandomRewardObjectInfo::configureRewards(
Rewardable::Configuration & object,
CRandomGenerator & rng, const
JsonNode & source,
std::map<si32, si32> & thrownDice,
CRewardVisitInfo::ERewardEventType event ) const
{
for (const JsonNode & reward : source.Vector())
{
if (!reward["appearChance"].isNull())
{
JsonNode chance = reward["appearChance"];
si32 diceID = static_cast<si32>(chance["dice"].Float());
if (thrownDice.count(diceID) == 0)
thrownDice[diceID] = rng.getIntRange(0, 99)();
if (!chance["min"].isNull())
{
int min = static_cast<int>(chance["min"].Float());
if (min > thrownDice[diceID])
continue;
}
if (!chance["max"].isNull())
{
int max = static_cast<int>(chance["max"].Float());
if (max <= thrownDice[diceID])
continue;
}
}
CRewardVisitInfo info;
configureLimiter(object, rng, info.limiter, reward["limiter"]);
configureReward(object, rng, info.reward, reward);
info.visitType = event;
info.message = loadMessage(reward["message"]);
for (const auto & artifact : info.reward.artifacts )
info.message.addReplacement(MetaString::ART_NAMES, artifact.getNum());
for (const auto & artifact : info.reward.spells )
info.message.addReplacement(MetaString::SPELL_NAME, artifact.getNum());
object.info.push_back(info);
}
}
void CRandomRewardObjectInfo::configureObject(Rewardable::Configuration & object, CRandomGenerator & rng) const
{
object.info.clear();
std::map<si32, si32> thrownDice;
configureRewards(object, rng, parameters["rewards"], thrownDice, CRewardVisitInfo::EVENT_FIRST_VISIT);
configureRewards(object, rng, parameters["onVisited"], thrownDice, CRewardVisitInfo::EVENT_ALREADY_VISITED);
configureRewards(object, rng, parameters["onEmpty"], thrownDice, CRewardVisitInfo::EVENT_NOT_AVAILABLE);
object.onSelect = loadMessage(parameters["onSelectMessage"]);
if (!parameters["onVisitedMessage"].isNull())
{
CRewardVisitInfo onVisited;
onVisited.visitType = CRewardVisitInfo::EVENT_ALREADY_VISITED;
onVisited.message = loadMessage(parameters["onVisitedMessage"]);
object.info.push_back(onVisited);
}
if (!parameters["onEmptyMessage"].isNull())
{
CRewardVisitInfo onEmpty;
onEmpty.visitType = CRewardVisitInfo::EVENT_NOT_AVAILABLE;
onEmpty.message = loadMessage(parameters["onEmptyMessage"]);
object.info.push_back(onEmpty);
}
configureResetInfo(object, rng, object.resetParameters, parameters["resetParameters"]);
object.canRefuse = parameters["canRefuse"].Bool();
if(parameters["showInInfobox"].isNull())
object.infoWindowType = EInfoWindowMode::AUTO;
else
object.infoWindowType = parameters["showInInfobox"].Bool() ? EInfoWindowMode::INFO : EInfoWindowMode::MODAL;
auto visitMode = parameters["visitMode"].String();
for(int i = 0; i < Rewardable::VisitModeString.size(); ++i)
{
if(Rewardable::VisitModeString[i] == visitMode)
{
object.visitMode = i;
break;
}
}
auto selectMode = parameters["selectMode"].String();
for(int i = 0; i < Rewardable::SelectModeString.size(); ++i)
{
if(Rewardable::SelectModeString[i] == selectMode)
{
object.selectMode = i;
break;
}
}
}
bool CRandomRewardObjectInfo::givesResources() const
{
return testForKey(parameters, "resources");
}
bool CRandomRewardObjectInfo::givesExperience() const
{
return testForKey(parameters, "gainedExp") || testForKey(parameters, "gainedLevels");
}
bool CRandomRewardObjectInfo::givesMana() const
{
return testForKey(parameters, "manaPoints") || testForKey(parameters, "manaPercentage");
}
bool CRandomRewardObjectInfo::givesMovement() const
{
return testForKey(parameters, "movePoints") || testForKey(parameters, "movePercentage");
}
bool CRandomRewardObjectInfo::givesPrimarySkills() const
{
return testForKey(parameters, "primary");
}
bool CRandomRewardObjectInfo::givesSecondarySkills() const
{
return testForKey(parameters, "secondary");
}
bool CRandomRewardObjectInfo::givesArtifacts() const
{
return testForKey(parameters, "artifacts");
}
bool CRandomRewardObjectInfo::givesCreatures() const
{
return testForKey(parameters, "spells");
}
bool CRandomRewardObjectInfo::givesSpells() const
{
return testForKey(parameters, "creatures");
}
bool CRandomRewardObjectInfo::givesBonuses() const
{
return testForKey(parameters, "bonuses");
}
const JsonNode & CRandomRewardObjectInfo::getParameters() const
{
return parameters;
}
void CRewardableConstructor::initTypeData(const JsonNode & config)
{
objectInfo.init(config);

View File

@ -9,52 +9,11 @@
*/
#pragma once
#include "CRewardableObject.h"
#include "CObjectClassesHandler.h"
#include "../JsonNode.h"
#include "CRandomRewardObjectInfo.h"
VCMI_LIB_NAMESPACE_BEGIN
class DLL_LINKAGE CRandomRewardObjectInfo : public IObjectInfo
{
JsonNode parameters;
void configureRewards(Rewardable::Configuration & object, CRandomGenerator & rng, const JsonNode & source, std::map<si32, si32> & thrownDice, CRewardVisitInfo::ERewardEventType mode) const;
void configureLimiter(Rewardable::Configuration & object, CRandomGenerator & rng, CRewardLimiter & limiter, const JsonNode & source) const;
TRewardLimitersList configureSublimiters(Rewardable::Configuration & object, CRandomGenerator & rng, const JsonNode & source) const;
void configureReward(Rewardable::Configuration & object, CRandomGenerator & rng, CRewardInfo & info, const JsonNode & source) const;
void configureResetInfo(Rewardable::Configuration & object, CRandomGenerator & rng, CRewardResetInfo & info, const JsonNode & source) const;
public:
const JsonNode & getParameters() const;
bool givesResources() const override;
bool givesExperience() const override;
bool givesMana() const override;
bool givesMovement() const override;
bool givesPrimarySkills() const override;
bool givesSecondarySkills() const override;
bool givesArtifacts() const override;
bool givesCreatures() const override;
bool givesSpells() const override;
bool givesBonuses() const override;
void configureObject(Rewardable::Configuration & object, CRandomGenerator & rng) const;
void init(const JsonNode & objectConfig);
template <typename Handler> void serialize(Handler &h, const int version)
{
h & parameters;
}
};
class DLL_LINKAGE CRewardableConstructor : public AObjectTypeHandler
{
CRandomRewardObjectInfo objectInfo;

View File

@ -10,174 +10,16 @@
#include "StdInc.h"
#include "CRewardableObject.h"
#include "../CHeroHandler.h"
#include "../CGeneralTextHandler.h"
#include "../CSoundBase.h"
#include "../NetPacks.h"
#include "../IGameCallback.h"
#include "../CGameState.h"
#include "../CPlayerState.h"
#include "../spells/CSpellHandler.h"
#include "../spells/ISpellMechanics.h"
#include "../mapObjects/MiscObjects.h"
#include "CObjectClassesHandler.h"
#include "Rewardable.h"
#include "../CGameState.h"
#include "../CGeneralTextHandler.h"
#include "../CPlayerState.h"
#include "../IGameCallback.h"
#include "../NetPacks.h"
VCMI_LIB_NAMESPACE_BEGIN
bool CRewardLimiter::heroAllowed(const CGHeroInstance * hero) const
{
if(dayOfWeek != 0)
{
if (IObjectInterface::cb->getDate(Date::DAY_OF_WEEK) != dayOfWeek)
return false;
}
if(daysPassed != 0)
{
if (IObjectInterface::cb->getDate(Date::DAY) < daysPassed)
return false;
}
for(const auto & reqStack : creatures)
{
size_t count = 0;
for(const auto & slot : hero->Slots())
{
const CStackInstance * heroStack = slot.second;
if (heroStack->type == reqStack.type)
count += heroStack->count;
}
if (count < reqStack.count) //not enough creatures of this kind
return false;
}
if(!IObjectInterface::cb->getPlayerState(hero->tempOwner)->resources.canAfford(resources))
return false;
if(heroLevel > static_cast<si32>(hero->level))
return false;
if(static_cast<TExpType>(heroExperience) > hero->exp)
return false;
if(manaPoints > hero->mana)
return false;
if(manaPercentage > 100 * hero->mana / hero->manaLimit())
return false;
for(size_t i=0; i<primary.size(); i++)
{
if(primary[i] > hero->getPrimSkillLevel(static_cast<PrimarySkill::PrimarySkill>(i)))
return false;
}
for(const auto & skill : secondary)
{
if (skill.second > hero->getSecSkillLevel(skill.first))
return false;
}
for(const auto & spell : spells)
{
if (!hero->spellbookContainsSpell(spell))
return false;
}
for(const auto & art : artifacts)
{
if (!hero->hasArt(art))
return false;
}
for(const auto & sublimiter : noneOf)
{
if (sublimiter->heroAllowed(hero))
return false;
}
for(const auto & sublimiter : allOf)
{
if (!sublimiter->heroAllowed(hero))
return false;
}
if(anyOf.empty())
return true;
for(const auto & sublimiter : anyOf)
{
if (sublimiter->heroAllowed(hero))
return true;
}
return false;
}
si32 CRewardInfo::calculateManaPoints(const CGHeroInstance * hero) const
{
si32 manaScaled = hero->mana;
if (manaPercentage >= 0)
manaScaled = hero->manaLimit() * manaPercentage / 100;
si32 manaMissing = std::max(0, hero->manaLimit() - manaScaled);
si32 manaGranted = std::min(manaMissing, manaDiff);
si32 manaOverflow = manaDiff - manaGranted;
si32 manaOverLimit = manaOverflow * manaOverflowFactor / 100;
si32 manaOutput = manaScaled + manaGranted + manaOverLimit;
return manaOutput;
}
Component CRewardInfo::getDisplayedComponent(const CGHeroInstance * h) const
{
std::vector<Component> comps;
loadComponents(comps, h);
assert(!comps.empty());
return comps.front();
}
void CRewardInfo::loadComponents(std::vector<Component> & comps,
const CGHeroInstance * h) const
{
for (auto comp : extraComponents)
comps.push_back(comp);
if (heroExperience)
{
comps.emplace_back(Component::EComponentType::EXPERIENCE, 0, static_cast<si32>(h->calculateXp(heroExperience)), 0);
}
if (heroLevel)
comps.emplace_back(Component::EComponentType::EXPERIENCE, 1, heroLevel, 0);
if (manaDiff || manaPercentage >= 0)
comps.emplace_back(Component::EComponentType::PRIM_SKILL, 5, calculateManaPoints(h) - h->mana, 0);
for (size_t i=0; i<primary.size(); i++)
{
if (primary[i] != 0)
comps.emplace_back(Component::EComponentType::PRIM_SKILL, static_cast<ui16>(i), primary[i], 0);
}
for(const auto & entry : secondary)
comps.emplace_back(Component::EComponentType::SEC_SKILL, entry.first, entry.second, 0);
for(const auto & entry : artifacts)
comps.emplace_back(Component::EComponentType::ARTIFACT, entry, 1, 0);
for(const auto & entry : spells)
comps.emplace_back(Component::EComponentType::SPELL, entry, 1, 0);
for(const auto & entry : creatures)
comps.emplace_back(Component::EComponentType::CREATURE, entry.type->getId(), entry.count, 0);
for (size_t i=0; i<resources.size(); i++)
{
if (resources[i] !=0)
comps.emplace_back(Component::EComponentType::RESOURCE, static_cast<ui16>(i), resources[i], 0);
}
}
// FIXME: copy-pasted from CObjectHandler
static std::string visitedTxt(const bool visited)
{
@ -185,157 +27,6 @@ static std::string visitedTxt(const bool visited)
return VLC->generaltexth->allTexts[id];
}
std::vector<ui32> Rewardable::Interface::getAvailableRewards(const CGHeroInstance * hero, CRewardVisitInfo::ERewardEventType event) const
{
std::vector<ui32> ret;
for(size_t i = 0; i < _configuration.info.size(); i++)
{
const CRewardVisitInfo & visit = _configuration.info[i];
if(event == visit.visitType && visit.limiter.heroAllowed(hero))
{
logGlobal->trace("Reward %d is allowed", i);
ret.push_back(static_cast<ui32>(i));
}
}
return ret;
}
Rewardable::EVisitMode Rewardable::Configuration::getVisitMode() const
{
return static_cast<EVisitMode>(visitMode);
}
ui16 Rewardable::Configuration::getResetDuration() const
{
return resetParameters.period;
}
const Rewardable::Configuration & Rewardable::Interface::getConfiguration() const
{
return _configuration;
}
Rewardable::Configuration & Rewardable::Interface::configuration()
{
return _configuration;
}
void Rewardable::Interface::grantRewardBeforeLevelup(IGameCallback * cb, const CRewardVisitInfo & info, const CGHeroInstance * hero) const
{
assert(hero);
assert(hero->tempOwner.isValidPlayer());
assert(info.reward.creatures.size() <= GameConstants::ARMY_SIZE);
cb->giveResources(hero->tempOwner, info.reward.resources);
for(const auto & entry : info.reward.secondary)
{
int current = hero->getSecSkillLevel(entry.first);
if( (current != 0 && current < entry.second) ||
(hero->canLearnSkill() ))
{
cb->changeSecSkill(hero, entry.first, entry.second);
}
}
for(int i=0; i< info.reward.primary.size(); i++)
cb->changePrimSkill(hero, static_cast<PrimarySkill::PrimarySkill>(i), info.reward.primary[i], false);
si64 expToGive = 0;
if (info.reward.heroLevel > 0)
expToGive += VLC->heroh->reqExp(hero->level+info.reward.heroLevel) - VLC->heroh->reqExp(hero->level);
if (info.reward.heroExperience > 0)
expToGive += hero->calculateXp(info.reward.heroExperience);
if(expToGive)
cb->changePrimSkill(hero, PrimarySkill::EXPERIENCE, expToGive);
}
void Rewardable::Interface::grantRewardAfterLevelup(IGameCallback * cb, const CRewardVisitInfo & info, const CGHeroInstance * hero) const
{
if(info.reward.manaDiff || info.reward.manaPercentage >= 0)
cb->setManaPoints(hero->id, info.reward.calculateManaPoints(hero));
if(info.reward.movePoints || info.reward.movePercentage >= 0)
{
SetMovePoints smp;
smp.hid = hero->id;
smp.val = hero->movement;
if (info.reward.movePercentage >= 0) // percent from max
smp.val = hero->maxMovePoints(hero->boat && hero->boat->layer == EPathfindingLayer::SAIL) * info.reward.movePercentage / 100;
smp.val = std::max<si32>(0, smp.val + info.reward.movePoints);
cb->setMovePoints(&smp);
}
for(const Bonus & bonus : info.reward.bonuses)
{
assert(bonus.source == Bonus::OBJECT);
GiveBonus gb;
gb.who = GiveBonus::ETarget::HERO;
gb.bonus = bonus;
gb.id = hero->id.getNum();
cb->giveHeroBonus(&gb);
}
for(const ArtifactID & art : info.reward.artifacts)
cb->giveHeroNewArtifact(hero, VLC->arth->objects[art],ArtifactPosition::FIRST_AVAILABLE);
if(!info.reward.spells.empty())
{
std::set<SpellID> spellsToGive(info.reward.spells.begin(), info.reward.spells.end());
cb->changeSpells(hero, true, spellsToGive);
}
if(!info.reward.creaturesChange.empty())
{
for(const auto & slot : hero->Slots())
{
const CStackInstance * heroStack = slot.second;
for(const auto & change : info.reward.creaturesChange)
{
if (heroStack->type->getId() == change.first)
{
StackLocation location(hero, slot.first);
cb->changeStackType(location, change.second.toCreature());
break;
}
}
}
}
if(!info.reward.creatures.empty())
{
CCreatureSet creatures;
for(const auto & crea : info.reward.creatures)
creatures.addToSlot(creatures.getFreeSlot(), new CStackInstance(crea.type, crea.count));
if(auto * army = dynamic_cast<const CArmedInstance*>(this)) //TODO: to fix that, CArmedInstance must be splitted on map instance part and interface part
cb->giveCreatures(army, hero, creatures, false);
}
if(info.reward.spellCast.first != SpellID::NONE)
{
caster.setActualCaster(hero);
caster.setSpellSchoolLevel(info.reward.spellCast.second);
cb->castSpell(&caster, info.reward.spellCast.first, int3{-1, -1, -1});
if(info.reward.removeObject)
logMod->warn("Removal of object with spell casts is not supported!");
}
else if(info.reward.removeObject) //FIXME: object can't track spell cancel or finish, so removeObject leads to crash
if(auto * instance = dynamic_cast<const CGObjectInstance*>(this))
cb->removeObject(instance);
}
void CRewardableObject::onHeroVisit(const CGHeroInstance *h) const
{
auto grantRewardWithMessage = [&](int index, bool markAsVisit) -> void
@ -441,7 +132,7 @@ void CRewardableObject::onHeroVisit(const CGHeroInstance *h) const
void CRewardableObject::heroLevelUpDone(const CGHeroInstance *hero) const
{
grantRewardAfterLevelup(cb, getConfiguration().info.at(selectedReward), hero);
grantRewardAfterLevelup(cb, getConfiguration().info.at(selectedReward), this, hero);
}
void CRewardableObject::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
@ -477,7 +168,7 @@ void CRewardableObject::grantReward(ui32 rewardID, const CGHeroInstance * hero)
// hero is not blocked by levelup dialog - grant remainer immediately
if(!cb->isVisitCoveredByAnotherQuery(this, hero))
{
grantRewardAfterLevelup(cb, getConfiguration().info.at(rewardID), hero);
grantRewardAfterLevelup(cb, getConfiguration().info.at(rewardID), this, hero);
}
}

View File

@ -9,345 +9,11 @@
*/
#pragma once
#include "CObjectHandler.h"
#include "CArmedInstance.h"
#include "../NetPacksBase.h"
#include "../ResourceSet.h"
#include "../spells/ExternalCaster.h"
#include "Rewardable.h"
VCMI_LIB_NAMESPACE_BEGIN
class CRandomRewardObjectInfo;
class CRewardLimiter;
using TRewardLimitersList = std::vector<std::shared_ptr<CRewardLimiter>>;
/// Limiters of rewards. Rewards will be granted to hero only if he satisfies requirements
/// Note: for this is only a test - it won't remove anything from hero (e.g. artifacts or creatures)
/// NOTE: in future should (partially) replace seer hut/quest guard quests checks
class DLL_LINKAGE CRewardLimiter
{
public:
/// day of week, unused if 0, 1-7 will test for current day of week
si32 dayOfWeek;
si32 daysPassed;
/// total experience that hero needs to have
si32 heroExperience;
/// level that hero needs to have
si32 heroLevel;
/// mana points that hero needs to have
si32 manaPoints;
/// percentage of mana points that hero needs to have
si32 manaPercentage;
/// resources player needs to have in order to trigger reward
TResources resources;
/// skills hero needs to have
std::vector<si32> primary;
std::map<SecondarySkill, si32> secondary;
/// artifacts that hero needs to have (equipped or in backpack) to trigger this
/// Note: does not checks for multiple copies of the same arts
std::vector<ArtifactID> artifacts;
/// Spells that hero must have in the spellbook
std::vector<SpellID> spells;
/// creatures that hero needs to have
std::vector<CStackBasicDescriptor> creatures;
/// sub-limiters, all must pass for this limiter to pass
TRewardLimitersList allOf;
/// sub-limiters, at least one should pass for this limiter to pass
TRewardLimitersList anyOf;
/// sub-limiters, none should pass for this limiter to pass
TRewardLimitersList noneOf;
CRewardLimiter():
dayOfWeek(0),
daysPassed(0),
heroExperience(0),
heroLevel(0),
manaPercentage(0),
manaPoints(0),
primary(GameConstants::PRIMARY_SKILLS, 0)
{}
bool heroAllowed(const CGHeroInstance * hero) const;
template <typename Handler> void serialize(Handler &h, const int version)
{
h & dayOfWeek;
h & daysPassed;
h & heroExperience;
h & heroLevel;
h & manaPoints;
h & manaPercentage;
h & resources;
h & primary;
h & secondary;
h & artifacts;
h & creatures;
h & allOf;
h & anyOf;
h & noneOf;
}
};
class DLL_LINKAGE CRewardResetInfo
{
public:
CRewardResetInfo()
: period(0)
, visitors(false)
, rewards(false)
{}
/// if above zero, object state will be reset each resetDuration days
ui32 period;
/// if true - reset list of visitors (heroes & players) on reset
bool visitors;
/// if true - re-randomize rewards on a new week
bool rewards;
template <typename Handler> void serialize(Handler &h, const int version)
{
h & period;
h & visitors;
h & rewards;
}
};
/// Reward that can be granted to a hero
/// NOTE: eventually should replace seer hut rewards and events/pandoras
class DLL_LINKAGE CRewardInfo
{
public:
/// resources that will be given to player
TResources resources;
/// received experience
si32 heroExperience;
/// received levels (converted into XP during grant)
si32 heroLevel;
/// mana given to/taken from hero, fixed value
si32 manaDiff;
/// if giving mana points puts hero above mana pool, any overflow will be multiplied by specified percentage
si32 manaOverflowFactor;
/// fixed value, in form of percentage from max
si32 manaPercentage;
/// movement points, only for current day. Bonuses should be used to grant MP on any other day
si32 movePoints;
/// fixed value, in form of percentage from max
si32 movePercentage;
/// list of bonuses, e.g. morale/luck
std::vector<Bonus> bonuses;
/// skills that hero may receive or lose
std::vector<si32> primary;
std::map<SecondarySkill, si32> secondary;
/// creatures that will be changed in hero's army
std::map<CreatureID, CreatureID> creaturesChange;
/// objects that hero may receive
std::vector<ArtifactID> artifacts;
std::vector<SpellID> spells;
std::vector<CStackBasicDescriptor> creatures;
/// actions that hero may execute and object caster. Pair of spellID and school level
std::pair<SpellID, int> spellCast;
/// list of components that will be added to reward description. First entry in list will override displayed component
std::vector<Component> extraComponents;
/// if set to true, object will be removed after granting reward
bool removeObject;
/// Generates list of components that describes reward for a specific hero
virtual void loadComponents(std::vector<Component> & comps,
const CGHeroInstance * h) const;
Component getDisplayedComponent(const CGHeroInstance * h) const;
si32 calculateManaPoints(const CGHeroInstance * h) const;
CRewardInfo() :
heroExperience(0),
heroLevel(0),
manaDiff(0),
manaPercentage(-1),
movePoints(0),
movePercentage(-1),
primary(4, 0),
removeObject(false),
spellCast(SpellID::NONE, SecSkillLevel::NONE)
{}
template <typename Handler> void serialize(Handler &h, const int version)
{
h & resources;
h & extraComponents;
h & removeObject;
h & manaPercentage;
h & movePercentage;
h & heroExperience;
h & heroLevel;
h & manaDiff;
h & manaOverflowFactor;
h & movePoints;
h & primary;
h & secondary;
h & bonuses;
h & artifacts;
h & spells;
h & creatures;
h & creaturesChange;
if(version >= 821)
h & spellCast;
}
};
class DLL_LINKAGE CRewardVisitInfo
{
public:
enum ERewardEventType
{
EVENT_INVALID,
EVENT_FIRST_VISIT,
EVENT_ALREADY_VISITED,
EVENT_NOT_AVAILABLE
};
CRewardLimiter limiter;
CRewardInfo reward;
/// Message that will be displayed on granting of this reward, if not empty
MetaString message;
/// Event to which this reward is assigned
ERewardEventType visitType;
CRewardVisitInfo() = default;
template <typename Handler> void serialize(Handler &h, const int version)
{
h & limiter;
h & reward;
h & message;
h & visitType;
}
};
namespace Rewardable
{
enum EVisitMode
{
VISIT_UNLIMITED, // any number of times. Side effect - object hover text won't contain visited/not visited text
VISIT_ONCE, // only once, first to visit get all the rewards
VISIT_HERO, // every hero can visit object once
VISIT_BONUS, // can be visited by any hero that don't have bonus from this object
VISIT_PLAYER // every player can visit object once
};
/// controls selection of reward granted to player
enum ESelectMode
{
SELECT_FIRST, // first reward that matches limiters
SELECT_PLAYER, // player can select from all allowed rewards
SELECT_RANDOM, // one random reward from all mathing limiters
};
const std::array<std::string, 3> SelectModeString{"selectFirst", "selectPlayer", "selectRandom"};
const std::array<std::string, 5> VisitModeString{"unlimited", "once", "hero", "bonus", "player"};
/// Base class that can handle granting rewards to visiting heroes.
struct DLL_LINKAGE Configuration
{
/// Message that will be shown if player needs to select one of multiple rewards
MetaString onSelect;
/// Rewards that can be applied by an object
std::vector<CRewardVisitInfo> info;
/// how reward will be selected, uses ESelectMode enum
ui8 selectMode = Rewardable::SELECT_FIRST;
/// contols who can visit an object, uses EVisitMode enum
ui8 visitMode = Rewardable::VISIT_UNLIMITED;
/// how and when should the object be reset
CRewardResetInfo resetParameters;
/// if true - player can refuse visiting an object (e.g. Tomb)
bool canRefuse = false;
/// if true - object info will shown in infobox (like resource pickup)
EInfoWindowMode infoWindowType = EInfoWindowMode::AUTO;
EVisitMode getVisitMode() const;
ui16 getResetDuration() const;
template <typename Handler> void serialize(Handler &h, const int version)
{
h & info;
h & canRefuse;
h & resetParameters;
h & onSelect;
h & visitMode;
h & selectMode;
h & infoWindowType;
}
};
class DLL_LINKAGE Interface
{
private:
Rewardable::Configuration _configuration;
/// caster to cast adveture spells, no serialize
mutable spells::ExternalCaster caster;
protected:
/// filters list of visit info and returns rewards that can be granted to current hero
std::vector<ui32> getAvailableRewards(const CGHeroInstance * hero, CRewardVisitInfo::ERewardEventType event) const;
/// function that must be called if hero got level-up during grantReward call
virtual void grantRewardAfterLevelup(IGameCallback * cb, const CRewardVisitInfo & reward, const CGHeroInstance * hero) const;
/// grants reward to hero
virtual void grantRewardBeforeLevelup(IGameCallback * cb, const CRewardVisitInfo & reward, const CGHeroInstance * hero) const;
public:
const Rewardable::Configuration & getConfiguration() const;
Rewardable::Configuration & configuration();
template <typename Handler> void serialize(Handler &h, const int version)
{
h & _configuration;
}
};
}
/// Base class that can handle granting rewards to visiting heroes.
/// Inherits from CArmedInstance for proper trasfer of armies
class DLL_LINKAGE CRewardableObject : public CArmedInstance, public Rewardable::Interface

View File

@ -0,0 +1,327 @@
/*
* Rewardable.cpp, part of VCMI engine
*
* Authors: listed in file AUTHORS in main folder
*
* License: GNU General Public License v2.0 or later
* Full text of license available in license.txt file, in main folder
*
*/
#include "StdInc.h"
#include "Rewardable.h"
#include "../CHeroHandler.h"
#include "../CSoundBase.h"
#include "../NetPacks.h"
#include "../IGameCallback.h"
#include "../CPlayerState.h"
#include "../spells/CSpellHandler.h"
#include "../spells/ISpellMechanics.h"
#include "../mapObjects/MiscObjects.h"
VCMI_LIB_NAMESPACE_BEGIN
bool CRewardLimiter::heroAllowed(const CGHeroInstance * hero) const
{
if(dayOfWeek != 0)
{
if (IObjectInterface::cb->getDate(Date::DAY_OF_WEEK) != dayOfWeek)
return false;
}
if(daysPassed != 0)
{
if (IObjectInterface::cb->getDate(Date::DAY) < daysPassed)
return false;
}
for(const auto & reqStack : creatures)
{
size_t count = 0;
for(const auto & slot : hero->Slots())
{
const CStackInstance * heroStack = slot.second;
if (heroStack->type == reqStack.type)
count += heroStack->count;
}
if (count < reqStack.count) //not enough creatures of this kind
return false;
}
if(!IObjectInterface::cb->getPlayerState(hero->tempOwner)->resources.canAfford(resources))
return false;
if(heroLevel > static_cast<si32>(hero->level))
return false;
if(static_cast<TExpType>(heroExperience) > hero->exp)
return false;
if(manaPoints > hero->mana)
return false;
if(manaPercentage > 100 * hero->mana / hero->manaLimit())
return false;
for(size_t i=0; i<primary.size(); i++)
{
if(primary[i] > hero->getPrimSkillLevel(static_cast<PrimarySkill::PrimarySkill>(i)))
return false;
}
for(const auto & skill : secondary)
{
if (skill.second > hero->getSecSkillLevel(skill.first))
return false;
}
for(const auto & spell : spells)
{
if (!hero->spellbookContainsSpell(spell))
return false;
}
for(const auto & art : artifacts)
{
if (!hero->hasArt(art))
return false;
}
for(const auto & sublimiter : noneOf)
{
if (sublimiter->heroAllowed(hero))
return false;
}
for(const auto & sublimiter : allOf)
{
if (!sublimiter->heroAllowed(hero))
return false;
}
if(anyOf.empty())
return true;
for(const auto & sublimiter : anyOf)
{
if (sublimiter->heroAllowed(hero))
return true;
}
return false;
}
si32 CRewardInfo::calculateManaPoints(const CGHeroInstance * hero) const
{
si32 manaScaled = hero->mana;
if (manaPercentage >= 0)
manaScaled = hero->manaLimit() * manaPercentage / 100;
si32 manaMissing = std::max(0, hero->manaLimit() - manaScaled);
si32 manaGranted = std::min(manaMissing, manaDiff);
si32 manaOverflow = manaDiff - manaGranted;
si32 manaOverLimit = manaOverflow * manaOverflowFactor / 100;
si32 manaOutput = manaScaled + manaGranted + manaOverLimit;
return manaOutput;
}
Component CRewardInfo::getDisplayedComponent(const CGHeroInstance * h) const
{
std::vector<Component> comps;
loadComponents(comps, h);
assert(!comps.empty());
return comps.front();
}
void CRewardInfo::loadComponents(std::vector<Component> & comps,
const CGHeroInstance * h) const
{
for (auto comp : extraComponents)
comps.push_back(comp);
if (heroExperience)
{
comps.emplace_back(Component::EComponentType::EXPERIENCE, 0, static_cast<si32>(h->calculateXp(heroExperience)), 0);
}
if (heroLevel)
comps.emplace_back(Component::EComponentType::EXPERIENCE, 1, heroLevel, 0);
if (manaDiff || manaPercentage >= 0)
comps.emplace_back(Component::EComponentType::PRIM_SKILL, 5, calculateManaPoints(h) - h->mana, 0);
for (size_t i=0; i<primary.size(); i++)
{
if (primary[i] != 0)
comps.emplace_back(Component::EComponentType::PRIM_SKILL, static_cast<ui16>(i), primary[i], 0);
}
for(const auto & entry : secondary)
comps.emplace_back(Component::EComponentType::SEC_SKILL, entry.first, entry.second, 0);
for(const auto & entry : artifacts)
comps.emplace_back(Component::EComponentType::ARTIFACT, entry, 1, 0);
for(const auto & entry : spells)
comps.emplace_back(Component::EComponentType::SPELL, entry, 1, 0);
for(const auto & entry : creatures)
comps.emplace_back(Component::EComponentType::CREATURE, entry.type->getId(), entry.count, 0);
for (size_t i=0; i<resources.size(); i++)
{
if (resources[i] !=0)
comps.emplace_back(Component::EComponentType::RESOURCE, static_cast<ui16>(i), resources[i], 0);
}
}
std::vector<ui32> Rewardable::Interface::getAvailableRewards(const CGHeroInstance * hero, CRewardVisitInfo::ERewardEventType event) const
{
std::vector<ui32> ret;
for(size_t i = 0; i < _configuration.info.size(); i++)
{
const CRewardVisitInfo & visit = _configuration.info[i];
if(event == visit.visitType && visit.limiter.heroAllowed(hero))
{
logGlobal->trace("Reward %d is allowed", i);
ret.push_back(static_cast<ui32>(i));
}
}
return ret;
}
Rewardable::EVisitMode Rewardable::Configuration::getVisitMode() const
{
return static_cast<EVisitMode>(visitMode);
}
ui16 Rewardable::Configuration::getResetDuration() const
{
return resetParameters.period;
}
const Rewardable::Configuration & Rewardable::Interface::getConfiguration() const
{
return _configuration;
}
Rewardable::Configuration & Rewardable::Interface::configuration()
{
return _configuration;
}
void Rewardable::Interface::grantRewardBeforeLevelup(IGameCallback * cb, const CRewardVisitInfo & info, const CGHeroInstance * hero) const
{
assert(hero);
assert(hero->tempOwner.isValidPlayer());
assert(info.reward.creatures.size() <= GameConstants::ARMY_SIZE);
cb->giveResources(hero->tempOwner, info.reward.resources);
for(const auto & entry : info.reward.secondary)
{
int current = hero->getSecSkillLevel(entry.first);
if( (current != 0 && current < entry.second) ||
(hero->canLearnSkill() ))
{
cb->changeSecSkill(hero, entry.first, entry.second);
}
}
for(int i=0; i< info.reward.primary.size(); i++)
cb->changePrimSkill(hero, static_cast<PrimarySkill::PrimarySkill>(i), info.reward.primary[i], false);
si64 expToGive = 0;
if (info.reward.heroLevel > 0)
expToGive += VLC->heroh->reqExp(hero->level+info.reward.heroLevel) - VLC->heroh->reqExp(hero->level);
if (info.reward.heroExperience > 0)
expToGive += hero->calculateXp(info.reward.heroExperience);
if(expToGive)
cb->changePrimSkill(hero, PrimarySkill::EXPERIENCE, expToGive);
}
void Rewardable::Interface::grantRewardAfterLevelup(IGameCallback * cb, const CRewardVisitInfo & info, const CArmedInstance * army, const CGHeroInstance * hero) const
{
if(info.reward.manaDiff || info.reward.manaPercentage >= 0)
cb->setManaPoints(hero->id, info.reward.calculateManaPoints(hero));
if(info.reward.movePoints || info.reward.movePercentage >= 0)
{
SetMovePoints smp;
smp.hid = hero->id;
smp.val = hero->movement;
if (info.reward.movePercentage >= 0) // percent from max
smp.val = hero->maxMovePoints(hero->boat && hero->boat->layer == EPathfindingLayer::SAIL) * info.reward.movePercentage / 100;
smp.val = std::max<si32>(0, smp.val + info.reward.movePoints);
cb->setMovePoints(&smp);
}
for(const Bonus & bonus : info.reward.bonuses)
{
assert(bonus.source == Bonus::OBJECT);
GiveBonus gb;
gb.who = GiveBonus::ETarget::HERO;
gb.bonus = bonus;
gb.id = hero->id.getNum();
cb->giveHeroBonus(&gb);
}
for(const ArtifactID & art : info.reward.artifacts)
cb->giveHeroNewArtifact(hero, VLC->arth->objects[art],ArtifactPosition::FIRST_AVAILABLE);
if(!info.reward.spells.empty())
{
std::set<SpellID> spellsToGive(info.reward.spells.begin(), info.reward.spells.end());
cb->changeSpells(hero, true, spellsToGive);
}
if(!info.reward.creaturesChange.empty())
{
for(const auto & slot : hero->Slots())
{
const CStackInstance * heroStack = slot.second;
for(const auto & change : info.reward.creaturesChange)
{
if (heroStack->type->getId() == change.first)
{
StackLocation location(hero, slot.first);
cb->changeStackType(location, change.second.toCreature());
break;
}
}
}
}
if(!info.reward.creatures.empty())
{
CCreatureSet creatures;
for(const auto & crea : info.reward.creatures)
creatures.addToSlot(creatures.getFreeSlot(), new CStackInstance(crea.type, crea.count));
if(auto * army = dynamic_cast<const CArmedInstance*>(this)) //TODO: to fix that, CArmedInstance must be splitted on map instance part and interface part
cb->giveCreatures(army, hero, creatures, false);
}
if(info.reward.spellCast.first != SpellID::NONE)
{
caster.setActualCaster(hero);
caster.setSpellSchoolLevel(info.reward.spellCast.second);
cb->castSpell(&caster, info.reward.spellCast.first, int3{-1, -1, -1});
if(info.reward.removeObject)
logMod->warn("Removal of object with spell casts is not supported!");
}
else if(info.reward.removeObject) //FIXME: object can't track spell cancel or finish, so removeObject leads to crash
if(auto * instance = dynamic_cast<const CGObjectInstance*>(this))
cb->removeObject(instance);
}
VCMI_LIB_NAMESPACE_END

350
lib/mapObjects/Rewardable.h Normal file
View File

@ -0,0 +1,350 @@
/*
* Rewardable.h, part of VCMI engine
*
* Authors: listed in file AUTHORS in main folder
*
* License: GNU General Public License v2.0 or later
* Full text of license available in license.txt file, in main folder
*
*/
#pragma once
#include "CObjectHandler.h"
#include "../CCreatureSet.h"
#include "../ResourceSet.h"
#include "../spells/ExternalCaster.h"
VCMI_LIB_NAMESPACE_BEGIN
class CRandomRewardObjectInfo;
class CRewardLimiter;
using TRewardLimitersList = std::vector<std::shared_ptr<CRewardLimiter>>;
/// Limiters of rewards. Rewards will be granted to hero only if he satisfies requirements
/// Note: for this is only a test - it won't remove anything from hero (e.g. artifacts or creatures)
/// NOTE: in future should (partially) replace seer hut/quest guard quests checks
class DLL_LINKAGE CRewardLimiter
{
public:
/// day of week, unused if 0, 1-7 will test for current day of week
si32 dayOfWeek;
si32 daysPassed;
/// total experience that hero needs to have
si32 heroExperience;
/// level that hero needs to have
si32 heroLevel;
/// mana points that hero needs to have
si32 manaPoints;
/// percentage of mana points that hero needs to have
si32 manaPercentage;
/// resources player needs to have in order to trigger reward
TResources resources;
/// skills hero needs to have
std::vector<si32> primary;
std::map<SecondarySkill, si32> secondary;
/// artifacts that hero needs to have (equipped or in backpack) to trigger this
/// Note: does not checks for multiple copies of the same arts
std::vector<ArtifactID> artifacts;
/// Spells that hero must have in the spellbook
std::vector<SpellID> spells;
/// creatures that hero needs to have
std::vector<CStackBasicDescriptor> creatures;
/// sub-limiters, all must pass for this limiter to pass
TRewardLimitersList allOf;
/// sub-limiters, at least one should pass for this limiter to pass
TRewardLimitersList anyOf;
/// sub-limiters, none should pass for this limiter to pass
TRewardLimitersList noneOf;
CRewardLimiter():
dayOfWeek(0),
daysPassed(0),
heroExperience(0),
heroLevel(0),
manaPercentage(0),
manaPoints(0),
primary(GameConstants::PRIMARY_SKILLS, 0)
{}
bool heroAllowed(const CGHeroInstance * hero) const;
template <typename Handler> void serialize(Handler &h, const int version)
{
h & dayOfWeek;
h & daysPassed;
h & heroExperience;
h & heroLevel;
h & manaPoints;
h & manaPercentage;
h & resources;
h & primary;
h & secondary;
h & artifacts;
h & creatures;
h & allOf;
h & anyOf;
h & noneOf;
}
};
class DLL_LINKAGE CRewardResetInfo
{
public:
CRewardResetInfo()
: period(0)
, visitors(false)
, rewards(false)
{}
/// if above zero, object state will be reset each resetDuration days
ui32 period;
/// if true - reset list of visitors (heroes & players) on reset
bool visitors;
/// if true - re-randomize rewards on a new week
bool rewards;
template <typename Handler> void serialize(Handler &h, const int version)
{
h & period;
h & visitors;
h & rewards;
}
};
/// Reward that can be granted to a hero
/// NOTE: eventually should replace seer hut rewards and events/pandoras
class DLL_LINKAGE CRewardInfo
{
public:
/// resources that will be given to player
TResources resources;
/// received experience
si32 heroExperience;
/// received levels (converted into XP during grant)
si32 heroLevel;
/// mana given to/taken from hero, fixed value
si32 manaDiff;
/// if giving mana points puts hero above mana pool, any overflow will be multiplied by specified percentage
si32 manaOverflowFactor;
/// fixed value, in form of percentage from max
si32 manaPercentage;
/// movement points, only for current day. Bonuses should be used to grant MP on any other day
si32 movePoints;
/// fixed value, in form of percentage from max
si32 movePercentage;
/// list of bonuses, e.g. morale/luck
std::vector<Bonus> bonuses;
/// skills that hero may receive or lose
std::vector<si32> primary;
std::map<SecondarySkill, si32> secondary;
/// creatures that will be changed in hero's army
std::map<CreatureID, CreatureID> creaturesChange;
/// objects that hero may receive
std::vector<ArtifactID> artifacts;
std::vector<SpellID> spells;
std::vector<CStackBasicDescriptor> creatures;
/// actions that hero may execute and object caster. Pair of spellID and school level
std::pair<SpellID, int> spellCast;
/// list of components that will be added to reward description. First entry in list will override displayed component
std::vector<Component> extraComponents;
/// if set to true, object will be removed after granting reward
bool removeObject;
/// Generates list of components that describes reward for a specific hero
virtual void loadComponents(std::vector<Component> & comps,
const CGHeroInstance * h) const;
Component getDisplayedComponent(const CGHeroInstance * h) const;
si32 calculateManaPoints(const CGHeroInstance * h) const;
CRewardInfo() :
heroExperience(0),
heroLevel(0),
manaDiff(0),
manaPercentage(-1),
movePoints(0),
movePercentage(-1),
primary(4, 0),
removeObject(false),
spellCast(SpellID::NONE, SecSkillLevel::NONE)
{}
template <typename Handler> void serialize(Handler &h, const int version)
{
h & resources;
h & extraComponents;
h & removeObject;
h & manaPercentage;
h & movePercentage;
h & heroExperience;
h & heroLevel;
h & manaDiff;
h & manaOverflowFactor;
h & movePoints;
h & primary;
h & secondary;
h & bonuses;
h & artifacts;
h & spells;
h & creatures;
h & creaturesChange;
if(version >= 821)
h & spellCast;
}
};
class DLL_LINKAGE CRewardVisitInfo
{
public:
enum ERewardEventType
{
EVENT_INVALID,
EVENT_FIRST_VISIT,
EVENT_ALREADY_VISITED,
EVENT_NOT_AVAILABLE
};
CRewardLimiter limiter;
CRewardInfo reward;
/// Message that will be displayed on granting of this reward, if not empty
MetaString message;
/// Event to which this reward is assigned
ERewardEventType visitType;
CRewardVisitInfo() = default;
template <typename Handler> void serialize(Handler &h, const int version)
{
h & limiter;
h & reward;
h & message;
h & visitType;
}
};
namespace Rewardable
{
enum EVisitMode
{
VISIT_UNLIMITED, // any number of times. Side effect - object hover text won't contain visited/not visited text
VISIT_ONCE, // only once, first to visit get all the rewards
VISIT_HERO, // every hero can visit object once
VISIT_BONUS, // can be visited by any hero that don't have bonus from this object
VISIT_PLAYER // every player can visit object once
};
/// controls selection of reward granted to player
enum ESelectMode
{
SELECT_FIRST, // first reward that matches limiters
SELECT_PLAYER, // player can select from all allowed rewards
SELECT_RANDOM, // one random reward from all mathing limiters
};
const std::array<std::string, 3> SelectModeString{"selectFirst", "selectPlayer", "selectRandom"};
const std::array<std::string, 5> VisitModeString{"unlimited", "once", "hero", "bonus", "player"};
/// Base class that can handle granting rewards to visiting heroes.
struct DLL_LINKAGE Configuration
{
/// Message that will be shown if player needs to select one of multiple rewards
MetaString onSelect;
/// Rewards that can be applied by an object
std::vector<CRewardVisitInfo> info;
/// how reward will be selected, uses ESelectMode enum
ui8 selectMode = Rewardable::SELECT_FIRST;
/// contols who can visit an object, uses EVisitMode enum
ui8 visitMode = Rewardable::VISIT_UNLIMITED;
/// how and when should the object be reset
CRewardResetInfo resetParameters;
/// if true - player can refuse visiting an object (e.g. Tomb)
bool canRefuse = false;
/// if true - object info will shown in infobox (like resource pickup)
EInfoWindowMode infoWindowType = EInfoWindowMode::AUTO;
EVisitMode getVisitMode() const;
ui16 getResetDuration() const;
template <typename Handler> void serialize(Handler &h, const int version)
{
h & info;
h & canRefuse;
h & resetParameters;
h & onSelect;
h & visitMode;
h & selectMode;
h & infoWindowType;
}
};
class DLL_LINKAGE Interface
{
private:
Rewardable::Configuration _configuration;
/// caster to cast adveture spells, no serialize
mutable spells::ExternalCaster caster;
protected:
/// filters list of visit info and returns rewards that can be granted to current hero
std::vector<ui32> getAvailableRewards(const CGHeroInstance * hero, CRewardVisitInfo::ERewardEventType event) const;
/// function that must be called if hero got level-up during grantReward call
virtual void grantRewardAfterLevelup(IGameCallback * cb, const CRewardVisitInfo & reward, const CArmedInstance * army, const CGHeroInstance * hero) const;
/// grants reward to hero
virtual void grantRewardBeforeLevelup(IGameCallback * cb, const CRewardVisitInfo & reward, const CGHeroInstance * hero) const;
public:
const Rewardable::Configuration & getConfiguration() const;
Rewardable::Configuration & configuration();
template <typename Handler> void serialize(Handler &h, const int version)
{
h & _configuration;
}
};
}
VCMI_LIB_NAMESPACE_END