1
0
mirror of https://github.com/vcmi/vcmi.git synced 2024-12-24 22:14:36 +02:00

Merge pull request #2101 from Nordsoft91/rewardable-expand

Part 2: refactoring for rewardable object
This commit is contained in:
Nordsoft91 2023-05-02 01:19:57 +04:00 committed by GitHub
commit c9b59735cf
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
20 changed files with 1323 additions and 1083 deletions

View File

@ -319,7 +319,7 @@ bool isWeeklyRevisitable(const CGObjectInstance * obj)
//TODO: allow polling of remaining creatures in dwelling
if(const auto * rewardable = dynamic_cast<const CRewardableObject *>(obj))
return rewardable->getResetDuration() == 7;
return rewardable->configuration.getResetDuration() == 7;
if(dynamic_cast<const CGDwelling *>(obj))
return true;

View File

@ -72,10 +72,10 @@ void AIMemory::markObjectVisited(const CGObjectInstance * obj)
// TODO: maybe this logic belongs to CaptureObjects::shouldVisit
if(const auto * rewardable = dynamic_cast<const CRewardableObject *>(obj))
{
if (rewardable->getVisitMode() == CRewardableObject::VISIT_HERO) //we may want to visit it with another hero
if (rewardable->configuration.getVisitMode() == Rewardable::VISIT_HERO) //we may want to visit it with another hero
return;
if (rewardable->getVisitMode() == CRewardableObject::VISIT_BONUS) //or another time
if (rewardable->configuration.getVisitMode() == Rewardable::VISIT_BONUS) //or another time
return;
}

View File

@ -1605,10 +1605,10 @@ void VCAI::markObjectVisited(const CGObjectInstance * obj)
if(const auto * rewardable = dynamic_cast<const CRewardableObject *>(obj)) //we may want to visit it with another hero
{
if (rewardable->getVisitMode() == CRewardableObject::VISIT_HERO) //we may want to visit it with another hero
if (rewardable->configuration.getVisitMode() == Rewardable::VISIT_HERO) //we may want to visit it with another hero
return;
if (rewardable->getVisitMode() == CRewardableObject::VISIT_BONUS) //or another time
if (rewardable->configuration.getVisitMode() == Rewardable::VISIT_BONUS) //or another time
return;
}
@ -2746,7 +2746,7 @@ bool isWeeklyRevisitable(const CGObjectInstance * obj)
{
//TODO: allow polling of remaining creatures in dwelling
if(const auto * rewardable = dynamic_cast<const CRewardableObject *>(obj))
return rewardable->getResetDuration() == 7;
return rewardable->configuration.getResetDuration() == 7;
if(dynamic_cast<const CGDwelling *>(obj))
return true;

View File

@ -67,7 +67,6 @@ macro(add_main_lib TARGET_NAME LIBRARY_TYPE)
${MAIN_LIB_DIR}/mapObjects/CQuest.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
@ -93,6 +92,12 @@ macro(add_main_lib TARGET_NAME LIBRARY_TYPE)
${MAIN_LIB_DIR}/registerTypes/TypesLobbyPacks.cpp
${MAIN_LIB_DIR}/registerTypes/TypesServerPacks.cpp
${MAIN_LIB_DIR}/rewardable/Configuration.cpp
${MAIN_LIB_DIR}/rewardable/Info.cpp
${MAIN_LIB_DIR}/rewardable/Interface.cpp
${MAIN_LIB_DIR}/rewardable/Limiter.cpp
${MAIN_LIB_DIR}/rewardable/Reward.cpp
${MAIN_LIB_DIR}/rmg/RmgArea.cpp
${MAIN_LIB_DIR}/rmg/RmgObject.cpp
${MAIN_LIB_DIR}/rmg/RmgPath.cpp
@ -198,6 +203,7 @@ macro(add_main_lib TARGET_NAME LIBRARY_TYPE)
${MAIN_LIB_DIR}/IHandlerBase.cpp
${MAIN_LIB_DIR}/JsonDetail.cpp
${MAIN_LIB_DIR}/JsonNode.cpp
${MAIN_LIB_DIR}/JsonRandom.cpp
${MAIN_LIB_DIR}/LoadProgress.cpp
${MAIN_LIB_DIR}/LogicalExpression.cpp
${MAIN_LIB_DIR}/NetPacksLib.cpp
@ -339,7 +345,6 @@ macro(add_main_lib TARGET_NAME LIBRARY_TYPE)
${MAIN_LIB_DIR}/mapObjects/CQuest.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
@ -360,6 +365,12 @@ macro(add_main_lib TARGET_NAME LIBRARY_TYPE)
${MAIN_LIB_DIR}/registerTypes/RegisterTypes.h
${MAIN_LIB_DIR}/rewardable/Configuration.h
${MAIN_LIB_DIR}/rewardable/Info.h
${MAIN_LIB_DIR}/rewardable/Interface.h
${MAIN_LIB_DIR}/rewardable/Limiter.h
${MAIN_LIB_DIR}/rewardable/Reward.h
${MAIN_LIB_DIR}/rmg/RmgArea.h
${MAIN_LIB_DIR}/rmg/RmgObject.h
${MAIN_LIB_DIR}/rmg/RmgPath.h
@ -476,6 +487,7 @@ macro(add_main_lib TARGET_NAME LIBRARY_TYPE)
${MAIN_LIB_DIR}/Interprocess.h
${MAIN_LIB_DIR}/JsonDetail.h
${MAIN_LIB_DIR}/JsonNode.h
${MAIN_LIB_DIR}/JsonRandom.h
${MAIN_LIB_DIR}/Languages.h
${MAIN_LIB_DIR}/LoadProgress.h
${MAIN_LIB_DIR}/LogicalExpression.h

View File

@ -13,18 +13,18 @@
#include <vstd/StringUtils.h>
#include "../JsonNode.h"
#include "../CRandomGenerator.h"
#include "../StringConstants.h"
#include "../VCMI_Lib.h"
#include "../CModHandler.h"
#include "../CArtHandler.h"
#include "../CCreatureHandler.h"
#include "../CCreatureSet.h"
#include "../spells/CSpellHandler.h"
#include "../CSkillHandler.h"
#include "../mapObjects/CObjectHandler.h"
#include "../IGameCallback.h"
#include "JsonNode.h"
#include "CRandomGenerator.h"
#include "StringConstants.h"
#include "VCMI_Lib.h"
#include "CModHandler.h"
#include "CArtHandler.h"
#include "CCreatureHandler.h"
#include "CCreatureSet.h"
#include "spells/CSpellHandler.h"
#include "CSkillHandler.h"
#include "mapObjects/CObjectHandler.h"
#include "IGameCallback.h"
VCMI_LIB_NAMESPACE_BEGIN

View File

@ -9,8 +9,8 @@
*/
#pragma once
#include "../GameConstants.h"
#include "../ResourceSet.h"
#include "GameConstants.h"
#include "ResourceSet.h"
VCMI_LIB_NAMESPACE_BEGIN

View File

@ -9,321 +9,20 @@
*/
#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(CRewardableObject * 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(CRewardableObject * 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(CRewardableObject * 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"]);
for (auto & bonus : reward.bonuses)
{
bonus.source = Bonus::OBJECT;
bonus.sid = object->ID;
//TODO: bonus.description = object->getObjectName();
if (bonus.type == Bonus::MORALE)
reward.extraComponents.emplace_back(Component::EComponentType::MORALE, 0, bonus.val, 0);
if (bonus.type == Bonus::LUCK)
reward.extraComponents.emplace_back(Component::EComponentType::LUCK, 0, bonus.val, 0);
}
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(CRewardableObject * 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(
CRewardableObject * 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(CRewardableObject * 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->blockVisit= parameters["blockedVisitable"].Bool();
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);
blockVisit = config["blockedVisitable"].Bool();
if (!config["name"].isNull())
VLC->generaltexth->registerString( config.meta, getNameTextID(), config["name"].String());
}
bool CRewardableConstructor::hasNameTextID() const
@ -336,17 +35,34 @@ CGObjectInstance * CRewardableConstructor::create(std::shared_ptr<const ObjectTe
auto * ret = new CRewardableObject();
preInitObject(ret);
ret->appearance = tmpl;
ret->blockVisit = blockVisit;
return ret;
}
void CRewardableConstructor::configureObject(CGObjectInstance * object, CRandomGenerator & rng) const
{
objectInfo.configureObject(dynamic_cast<CRewardableObject*>(object), rng);
if(auto * rewardableObject = dynamic_cast<CRewardableObject*>(object))
{
objectInfo.configureObject(rewardableObject->configuration, rng);
for(auto & rewardInfo : rewardableObject->configuration.info)
{
for (auto & bonus : rewardInfo.reward.bonuses)
{
bonus.source = Bonus::OBJECT;
bonus.sid = rewardableObject->ID;
//TODO: bonus.description = object->getObjectName();
if (bonus.type == Bonus::MORALE)
rewardInfo.reward.extraComponents.emplace_back(Component::EComponentType::MORALE, 0, bonus.val, 0);
if (bonus.type == Bonus::LUCK)
rewardInfo.reward.extraComponents.emplace_back(Component::EComponentType::LUCK, 0, bonus.val, 0);
}
}
}
}
std::unique_ptr<IObjectInfo> CRewardableConstructor::getObjectInfo(std::shared_ptr<const ObjectTemplate> tmpl) const
{
return std::unique_ptr<IObjectInfo>(new CRandomRewardObjectInfo(objectInfo));
return std::unique_ptr<IObjectInfo>(new Rewardable::Info(objectInfo));
}
VCMI_LIB_NAMESPACE_END

View File

@ -9,57 +9,18 @@
*/
#pragma once
#include "CRewardableObject.h"
#include "CObjectClassesHandler.h"
#include "../JsonNode.h"
#include "../mapObjects/CObjectClassesHandler.h"
#include "../rewardable/Info.h"
VCMI_LIB_NAMESPACE_BEGIN
class DLL_LINKAGE CRandomRewardObjectInfo : public IObjectInfo
{
JsonNode parameters;
void configureRewards(CRewardableObject * object, CRandomGenerator & rng, const JsonNode & source, std::map<si32, si32> & thrownDice, CRewardVisitInfo::ERewardEventType mode) const;
void configureLimiter(CRewardableObject * object, CRandomGenerator & rng, CRewardLimiter & limiter, const JsonNode & source) const;
TRewardLimitersList configureSublimiters(CRewardableObject * object, CRandomGenerator & rng, const JsonNode & source) const;
void configureReward(CRewardableObject * object, CRandomGenerator & rng, CRewardInfo & info, const JsonNode & source) const;
void configureResetInfo(CRewardableObject * 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(CRewardableObject * 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;
Rewardable::Info objectInfo;
void initTypeData(const JsonNode & config) override;
bool blockVisit = false;
public:
bool hasNameTextID() const override;

View File

@ -10,170 +10,67 @@
#include "StdInc.h"
#include "CRewardableObject.h"
#include "../CHeroHandler.h"
#include "../CGeneralTextHandler.h"
#include "../CSoundBase.h"
#include "../NetPacks.h"
#include "../IGameCallback.h"
#include "../mapObjects/CObjectClassesHandler.h"
#include "../CGameState.h"
#include "../CGeneralTextHandler.h"
#include "../CPlayerState.h"
#include "../spells/CSpellHandler.h"
#include "../spells/ISpellMechanics.h"
#include "../mapObjects/MiscObjects.h"
#include "CObjectClassesHandler.h"
#include "../IGameCallback.h"
#include "../NetPacks.h"
VCMI_LIB_NAMESPACE_BEGIN
bool CRewardLimiter::heroAllowed(const CGHeroInstance * hero) const
// FIXME: copy-pasted from CObjectHandler
static std::string visitedTxt(const bool visited)
{
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;
}
std::vector<ui32> CRewardableObject::getAvailableRewards(const CGHeroInstance * hero, CRewardVisitInfo::ERewardEventType event) const
{
std::vector<ui32> ret;
for(size_t i=0; i<info.size(); i++)
{
const CRewardVisitInfo & visit = 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;
int id = visited ? 352 : 353;
return VLC->generaltexth->allTexts[id];
}
void CRewardableObject::onHeroVisit(const CGHeroInstance *h) const
{
auto grantRewardWithMessage = [&](int index, bool markAsVisit) -> void
{
auto vi = info[index];
auto vi = configuration.info.at(index);
logGlobal->debug("Granting reward %d. Message says: %s", index, vi.message.toString());
// show message only if it is not empty or in infobox
if (infoWindowType != EInfoWindowMode::MODAL || !vi.message.toString().empty())
if (configuration.infoWindowType != EInfoWindowMode::MODAL || !vi.message.toString().empty())
{
InfoWindow iw;
iw.player = h->tempOwner;
iw.text = vi.message;
vi.reward.loadComponents(iw.components, h);
iw.type = infoWindowType;
iw.type = configuration.infoWindowType;
if(!iw.components.empty() || !iw.text.toString().empty())
cb->showInfoDialog(&iw);
}
// grant reward afterwards. Note that it may remove object
grantReward(index, h, markAsVisit);
if(markAsVisit)
markAsVisited(h);
grantReward(index, h);
};
auto selectRewardsMessage = [&](const std::vector<ui32> & rewards, const MetaString & dialog) -> void
{
BlockingDialog sd(canRefuse, rewards.size() > 1);
BlockingDialog sd(configuration.canRefuse, rewards.size() > 1);
sd.player = h->tempOwner;
sd.text = dialog;
if (rewards.size() > 1)
for (auto index : rewards)
sd.components.push_back(info[index].reward.getDisplayedComponent(h));
sd.components.push_back(configuration.info.at(index).reward.getDisplayedComponent(h));
if (rewards.size() == 1)
info[rewards[0]].reward.loadComponents(sd.components, h);
configuration.info.at(rewards.front()).reward.loadComponents(sd.components, h);
cb->showBlockingDialog(&sd);
};
if(!wasVisitedBefore(h))
{
auto rewards = getAvailableRewards(h, CRewardVisitInfo::EVENT_FIRST_VISIT);
auto rewards = getAvailableRewards(h, Rewardable::EEventType::EVENT_FIRST_VISIT);
bool objectRemovalPossible = false;
for(auto index : rewards)
{
if(info[index].reward.removeObject)
if(configuration.info.at(index).reward.removeObject)
objectRemovalPossible = true;
}
@ -182,7 +79,7 @@ void CRewardableObject::onHeroVisit(const CGHeroInstance *h) const
{
case 0: // no available rewards, e.g. visiting School of War without gold
{
auto emptyRewards = getAvailableRewards(h, CRewardVisitInfo::EVENT_NOT_AVAILABLE);
auto emptyRewards = getAvailableRewards(h, Rewardable::EEventType::EVENT_NOT_AVAILABLE);
if (!emptyRewards.empty())
grantRewardWithMessage(emptyRewards[0], false);
else
@ -191,27 +88,30 @@ void CRewardableObject::onHeroVisit(const CGHeroInstance *h) const
}
case 1: // one reward. Just give it with message
{
if (canRefuse)
selectRewardsMessage(rewards, info[rewards[0]].message);
if (configuration.canRefuse)
selectRewardsMessage(rewards, configuration.info.at(rewards.front()).message);
else
grantRewardWithMessage(rewards[0], true);
grantRewardWithMessage(rewards.front(), true);
break;
}
default: // multiple rewards. Act according to select mode
{
switch (selectMode) {
case SELECT_PLAYER: // player must select
selectRewardsMessage(rewards, onSelect);
switch (configuration.selectMode) {
case Rewardable::SELECT_PLAYER: // player must select
selectRewardsMessage(rewards, configuration.onSelect);
break;
case SELECT_FIRST: // give first available
grantRewardWithMessage(rewards[0], true);
case Rewardable::SELECT_FIRST: // give first available
grantRewardWithMessage(rewards.front(), true);
break;
case Rewardable::SELECT_RANDOM: // give random
grantRewardWithMessage(*RandomGeneratorUtil::nextItem(rewards, cb->gameState()->getRandomGenerator()), true);
break;
}
break;
}
}
if(!objectRemovalPossible && getAvailableRewards(h, CRewardVisitInfo::EVENT_FIRST_VISIT).empty())
if(!objectRemovalPossible && getAvailableRewards(h, Rewardable::EEventType::EVENT_FIRST_VISIT).empty())
{
ChangeObjectVisitors cov(ChangeObjectVisitors::VISITOR_ADD_TEAM, id, h->id);
cb->sendAndApply(&cov);
@ -221,7 +121,7 @@ void CRewardableObject::onHeroVisit(const CGHeroInstance *h) const
{
logGlobal->debug("Revisiting already visited object");
auto visitedRewards = getAvailableRewards(h, CRewardVisitInfo::EVENT_ALREADY_VISITED);
auto visitedRewards = getAvailableRewards(h, Rewardable::EEventType::EVENT_ALREADY_VISITED);
if (!visitedRewards.empty())
grantRewardWithMessage(visitedRewards[0], false);
else
@ -231,7 +131,7 @@ void CRewardableObject::onHeroVisit(const CGHeroInstance *h) const
void CRewardableObject::heroLevelUpDone(const CGHeroInstance *hero) const
{
grantRewardAfterLevelup(info[selectedReward], hero);
grantRewardAfterLevelup(cb, configuration.info.at(selectedReward), this, hero);
}
void CRewardableObject::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
@ -239,10 +139,11 @@ void CRewardableObject::blockingDialogAnswered(const CGHeroInstance *hero, ui32
if(answer == 0)
return; // player refused
if(answer > 0 && answer-1 < info.size())
if(answer > 0 && answer-1 < configuration.info.size())
{
auto list = getAvailableRewards(hero, CRewardVisitInfo::EVENT_FIRST_VISIT);
grantReward(list[answer - 1], hero, true);
auto list = getAvailableRewards(hero, Rewardable::EEventType::EVENT_FIRST_VISIT);
markAsVisited(hero);
grantReward(list[answer - 1], hero);
}
else
{
@ -250,169 +151,55 @@ void CRewardableObject::blockingDialogAnswered(const CGHeroInstance *hero, ui32
}
}
void CRewardableObject::grantReward(ui32 rewardID, const CGHeroInstance * hero, bool markVisited) const
void CRewardableObject::markAsVisited(const CGHeroInstance * hero) const
{
if (markVisited)
{
cb->setObjProperty(id, ObjProperty::REWARD_CLEARED, true);
cb->setObjProperty(id, ObjProperty::REWARD_CLEARED, true);
ChangeObjectVisitors cov(ChangeObjectVisitors::VISITOR_ADD, id, hero->id);
cb->sendAndApply(&cov);
}
cb->setObjProperty(id, ObjProperty::REWARD_SELECT, rewardID);
grantRewardBeforeLevelup(info[rewardID], hero);
ChangeObjectVisitors cov(ChangeObjectVisitors::VISITOR_ADD, id, hero->id);
cb->sendAndApply(&cov);
}
void CRewardableObject::grantRewardBeforeLevelup(const CRewardVisitInfo & info, const CGHeroInstance * hero) const
void CRewardableObject::grantReward(ui32 rewardID, const CGHeroInstance * hero) const
{
assert(hero);
assert(hero->tempOwner.isValidPlayer());
assert(stacks.empty());
assert(info.reward.creatures.size() <= GameConstants::ARMY_SIZE);
assert(!cb->isVisitCoveredByAnotherQuery(this, hero));
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);
cb->setObjProperty(id, ObjProperty::REWARD_SELECT, rewardID);
grantRewardBeforeLevelup(cb, configuration.info.at(rewardID), hero);
// hero is not blocked by levelup dialog - grant remainer immediately
if(!cb->isVisitCoveredByAnotherQuery(this, hero))
{
grantRewardAfterLevelup(info, hero);
grantRewardAfterLevelup(cb, configuration.info.at(rewardID), this, hero);
}
}
void CRewardableObject::grantRewardAfterLevelup(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);
assert(bonus.sid == ID);
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));
cb->giveCreatures(this, 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
cb->removeObject(this);
}
bool CRewardableObject::wasVisitedBefore(const CGHeroInstance * contextHero) const
{
switch (visitMode)
switch (configuration.visitMode)
{
case VISIT_UNLIMITED:
case Rewardable::VISIT_UNLIMITED:
return false;
case VISIT_ONCE:
case Rewardable::VISIT_ONCE:
return onceVisitableObjectCleared;
case VISIT_PLAYER:
case Rewardable::VISIT_PLAYER:
return vstd::contains(cb->getPlayerState(contextHero->getOwner())->visitedObjects, ObjectInstanceID(id));
case VISIT_BONUS:
case Rewardable::VISIT_BONUS:
return contextHero->hasBonusFrom(Bonus::OBJECT, ID);
case VISIT_HERO:
case Rewardable::VISIT_HERO:
return contextHero->visitedObjects.count(ObjectInstanceID(id));
default:
return false;
}
}
bool CRewardableObject::wasVisited(PlayerColor player) const
{
switch (visitMode)
switch (configuration.visitMode)
{
case VISIT_UNLIMITED:
case VISIT_BONUS:
case VISIT_HERO:
case Rewardable::VISIT_UNLIMITED:
case Rewardable::VISIT_BONUS:
case Rewardable::VISIT_HERO:
return false;
case VISIT_ONCE:
case VISIT_PLAYER:
case Rewardable::VISIT_ONCE:
case Rewardable::VISIT_PLAYER:
return vstd::contains(cb->getPlayerState(player)->visitedObjects, ObjectInstanceID(id));
default:
return false;
@ -421,108 +208,27 @@ bool CRewardableObject::wasVisited(PlayerColor player) const
bool CRewardableObject::wasVisited(const CGHeroInstance * h) const
{
switch (visitMode)
switch (configuration.visitMode)
{
case VISIT_BONUS:
case Rewardable::VISIT_BONUS:
return h->hasBonusFrom(Bonus::OBJECT, ID);
case VISIT_HERO:
case Rewardable::VISIT_HERO:
return h->visitedObjects.count(ObjectInstanceID(id));
default:
return wasVisited(h->tempOwner);
}
}
CRewardableObject::EVisitMode CRewardableObject::getVisitMode() const
{
return static_cast<EVisitMode>(visitMode);
}
ui16 CRewardableObject::getResetDuration() const
{
return resetParameters.period;
}
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);
}
}
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();
}
// FIXME: copy-pasted from CObjectHandler
static std::string visitedTxt(const bool visited)
{
int id = visited ? 352 : 353;
return VLC->generaltexth->allTexts[id];
}
std::string CRewardableObject::getHoverText(PlayerColor player) const
{
if(visitMode == VISIT_PLAYER || visitMode == VISIT_ONCE)
if(configuration.visitMode == Rewardable::VISIT_PLAYER || configuration.visitMode == Rewardable::VISIT_ONCE)
return getObjectName() + " " + visitedTxt(wasVisited(player));
return getObjectName();
}
std::string CRewardableObject::getHoverText(const CGHeroInstance * hero) const
{
if(visitMode != VISIT_UNLIMITED)
if(configuration.visitMode != Rewardable::VISIT_UNLIMITED)
return getObjectName() + " " + visitedTxt(wasVisited(hero));
return getObjectName();
}
@ -543,39 +249,30 @@ void CRewardableObject::setPropertyDer(ui8 what, ui32 val)
}
}
void CRewardableObject::triggerReset() const
{
if (resetParameters.rewards)
{
cb->setObjProperty(id, ObjProperty::REWARD_RANDOMIZE, 0);
}
if (resetParameters.visitors)
{
cb->setObjProperty(id, ObjProperty::REWARD_CLEARED, false);
ChangeObjectVisitors cov(ChangeObjectVisitors::VISITOR_CLEAR, id);
cb->sendAndApply(&cov);
}
}
void CRewardableObject::newTurn(CRandomGenerator & rand) const
{
if (resetParameters.period != 0 && cb->getDate(Date::DAY) > 1 && ((cb->getDate(Date::DAY)-1) % resetParameters.period) == 0)
triggerReset();
if (configuration.resetParameters.period != 0 && cb->getDate(Date::DAY) > 1 && ((cb->getDate(Date::DAY)-1) % configuration.resetParameters.period) == 0)
{
if (configuration.resetParameters.rewards)
{
cb->setObjProperty(id, ObjProperty::REWARD_RANDOMIZE, 0);
}
if (configuration.resetParameters.visitors)
{
cb->setObjProperty(id, ObjProperty::REWARD_CLEARED, false);
ChangeObjectVisitors cov(ChangeObjectVisitors::VISITOR_CLEAR, id);
cb->sendAndApply(&cov);
}
}
}
void CRewardableObject::initObj(CRandomGenerator & rand)
{
VLC->objtypeh->getHandlerFor(ID, subID)->configureObject(this, rand);
assert(!info.empty());
assert(!configuration.info.empty());
}
CRewardableObject::CRewardableObject():
selectMode(0),
visitMode(0),
selectedReward(0),
onceVisitableObjectCleared(false),
canRefuse(false)
CRewardableObject::CRewardableObject()
{}
VCMI_LIB_NAMESPACE_END

View File

@ -9,337 +9,34 @@
*/
#pragma once
#include "CObjectHandler.h"
#include "CArmedInstance.h"
#include "../NetPacksBase.h"
#include "../ResourceSet.h"
#include "../spells/ExternalCaster.h"
#include "../mapObjects/CArmedInstance.h"
#include "../rewardable/Interface.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
{
const std::array<std::string, 3> SelectModeString{"selectFirst", "selectPlayer"};
const std::array<std::string, 5> VisitModeString{"unlimited", "once", "hero", "bonus", "player"};
}
/// Base class that can handle granting rewards to visiting heroes.
/// Inherits from CArmedInstance for proper trasfer of armies
class DLL_LINKAGE CRewardableObject : public CArmedInstance
class DLL_LINKAGE CRewardableObject : public CArmedInstance, public Rewardable::Interface
{
/// function that must be called if hero got level-up during grantReward call
void grantRewardAfterLevelup(const CRewardVisitInfo & reward, const CGHeroInstance * hero) const;
/// grants reward to hero
void grantRewardBeforeLevelup(const CRewardVisitInfo & reward, const CGHeroInstance * hero) const;
public:
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
};
protected:
/// 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
};
/// filters list of visit info and returns rewards that can be granted to current hero
virtual std::vector<ui32> getAvailableRewards(const CGHeroInstance * hero, CRewardVisitInfo::ERewardEventType event ) const;
virtual void grantReward(ui32 rewardID, const CGHeroInstance * hero, bool markVisited) const;
virtual void triggerReset() const;
/// 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;
/// contols who can visit an object, uses EVisitMode enum
ui8 visitMode;
/// reward selected by player
ui16 selectedReward;
/// how and when should the object be reset
CRewardResetInfo resetParameters;
/// if true - player can refuse visiting an object (e.g. Tomb)
bool canRefuse;
/// if true - object info will shown in infobox (like resource pickup)
EInfoWindowMode infoWindowType = EInfoWindowMode::AUTO;
bool onceVisitableObjectCleared = false;
/// reward selected by player, no serialize
ui16 selectedReward = 0;
void grantReward(ui32 rewardID, const CGHeroInstance * hero) const;
void markAsVisited(const CGHeroInstance * hero) const;
/// return true if this object was "cleared" before and no longer has rewards applicable to selected hero
/// unlike wasVisited, this method uses information not available to player owner, for example, if object was cleared by another player before
bool wasVisitedBefore(const CGHeroInstance * contextHero) const;
bool onceVisitableObjectCleared;
/// caster to cast adveture spells
mutable spells::ExternalCaster caster;
public:
EVisitMode getVisitMode() const;
ui16 getResetDuration() const;
void setPropertyDer(ui8 what, ui32 val) override;
std::string getHoverText(PlayerColor player) const override;
std::string getHoverText(const CGHeroInstance * hero) const override;
/// Visitability checks. Note that hero check includes check for hero owner (returns true if object was visited by player)
bool wasVisited(PlayerColor player) const override;
bool wasVisited(const CGHeroInstance * h) const override;
/// gives reward to player or ask for choice in case of multiple rewards
void onHeroVisit(const CGHeroInstance *h) const override;
@ -353,26 +50,20 @@ public:
void blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const override;
void initObj(CRandomGenerator & rand) override;
void setPropertyDer(ui8 what, ui32 val) override;
CRewardableObject();
std::string getHoverText(PlayerColor player) const override;
std::string getHoverText(const CGHeroInstance * hero) const override;
template <typename Handler> void serialize(Handler &h, const int version)
{
h & static_cast<CArmedInstance&>(*this);
h & info;
h & canRefuse;
h & resetParameters;
h & onSelect;
h & visitMode;
h & selectMode;
h & selectedReward;
h & static_cast<Rewardable::Interface&>(*this);
h & onceVisitableObjectCleared;
if (version >= 817)
h & infoWindowType;
}
// for configuration/object setup
friend class CRandomRewardObjectInfo;
};
//TODO:

View File

@ -0,0 +1,26 @@
/*
* Configuration.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 "Configuration.h"
VCMI_LIB_NAMESPACE_BEGIN
Rewardable::EVisitMode Rewardable::Configuration::getVisitMode() const
{
return static_cast<EVisitMode>(visitMode);
}
ui16 Rewardable::Configuration::getResetDuration() const
{
return resetParameters.period;
}
VCMI_LIB_NAMESPACE_END

View File

@ -0,0 +1,136 @@
/*
* Configuration.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 "Limiter.h"
#include "Reward.h"
VCMI_LIB_NAMESPACE_BEGIN
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
};
enum class EEventType
{
EVENT_INVALID = 0,
EVENT_FIRST_VISIT,
EVENT_ALREADY_VISITED,
EVENT_NOT_AVAILABLE
};
const std::array<std::string, 3> SelectModeString{"selectFirst", "selectPlayer", "selectRandom"};
const std::array<std::string, 5> VisitModeString{"unlimited", "once", "hero", "bonus", "player"};
struct DLL_LINKAGE ResetInfo
{
ResetInfo()
: 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;
}
};
struct DLL_LINKAGE VisitInfo
{
Limiter limiter;
Reward reward;
/// Message that will be displayed on granting of this reward, if not empty
MetaString message;
/// Event to which this reward is assigned
EEventType visitType;
template <typename Handler> void serialize(Handler &h, const int version)
{
h & limiter;
h & reward;
h & message;
h & visitType;
}
};
/// 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<Rewardable::VisitInfo> 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
Rewardable::ResetInfo 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;
}
};
}
VCMI_LIB_NAMESPACE_END

315
lib/rewardable/Info.cpp Normal file
View File

@ -0,0 +1,315 @@
/*
* Info.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 "Info.h"
#include "Limiter.h"
#include "Reward.h"
#include "Configuration.h"
#include "../CRandomGenerator.h"
#include "../StringConstants.h"
#include "../CCreatureHandler.h"
#include "../CModHandler.h"
#include "../JsonRandom.h"
#include "../IGameCallback.h"
#include "../CGeneralTextHandler.h"
#include "../JsonNode.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 Rewardable::Info::init(const JsonNode & objectConfig)
{
parameters = objectConfig;
}
Rewardable::LimitersList Rewardable::Info::configureSublimiters(Rewardable::Configuration & object, CRandomGenerator & rng, const JsonNode & source) const
{
Rewardable::LimitersList result;
for (const auto & input : source.Vector())
{
auto newLimiter = std::make_shared<Rewardable::Limiter>();
configureLimiter(object, rng, *newLimiter, input);
result.push_back(newLimiter);
}
return result;
}
void Rewardable::Info::configureLimiter(Rewardable::Configuration & object, CRandomGenerator & rng, Rewardable::Limiter & 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 Rewardable::Info::configureReward(Rewardable::Configuration & object, CRandomGenerator & rng, Rewardable::Reward & 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 Rewardable::Info::configureResetInfo(Rewardable::Configuration & object, CRandomGenerator & rng, Rewardable::ResetInfo & resetParameters, const JsonNode & source) const
{
resetParameters.period = static_cast<ui32>(source["period"].Float());
resetParameters.visitors = source["visitors"].Bool();
resetParameters.rewards = source["rewards"].Bool();
}
void Rewardable::Info::configureRewards(
Rewardable::Configuration & object,
CRandomGenerator & rng, const
JsonNode & source,
std::map<si32, si32> & thrownDice,
Rewardable::EEventType 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;
}
}
Rewardable::VisitInfo 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 Rewardable::Info::configureObject(Rewardable::Configuration & object, CRandomGenerator & rng) const
{
object.info.clear();
std::map<si32, si32> thrownDice;
configureRewards(object, rng, parameters["rewards"], thrownDice, Rewardable::EEventType::EVENT_FIRST_VISIT);
configureRewards(object, rng, parameters["onVisited"], thrownDice, Rewardable::EEventType::EVENT_ALREADY_VISITED);
configureRewards(object, rng, parameters["onEmpty"], thrownDice, Rewardable::EEventType::EVENT_NOT_AVAILABLE);
object.onSelect = loadMessage(parameters["onSelectMessage"]);
if (!parameters["onVisitedMessage"].isNull())
{
Rewardable::VisitInfo onVisited;
onVisited.visitType = Rewardable::EEventType::EVENT_ALREADY_VISITED;
onVisited.message = loadMessage(parameters["onVisitedMessage"]);
object.info.push_back(onVisited);
}
if (!parameters["onEmptyMessage"].isNull())
{
Rewardable::VisitInfo onEmpty;
onEmpty.visitType = Rewardable::EEventType::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 Rewardable::Info::givesResources() const
{
return testForKey(parameters, "resources");
}
bool Rewardable::Info::givesExperience() const
{
return testForKey(parameters, "gainedExp") || testForKey(parameters, "gainedLevels");
}
bool Rewardable::Info::givesMana() const
{
return testForKey(parameters, "manaPoints") || testForKey(parameters, "manaPercentage");
}
bool Rewardable::Info::givesMovement() const
{
return testForKey(parameters, "movePoints") || testForKey(parameters, "movePercentage");
}
bool Rewardable::Info::givesPrimarySkills() const
{
return testForKey(parameters, "primary");
}
bool Rewardable::Info::givesSecondarySkills() const
{
return testForKey(parameters, "secondary");
}
bool Rewardable::Info::givesArtifacts() const
{
return testForKey(parameters, "artifacts");
}
bool Rewardable::Info::givesCreatures() const
{
return testForKey(parameters, "spells");
}
bool Rewardable::Info::givesSpells() const
{
return testForKey(parameters, "creatures");
}
bool Rewardable::Info::givesBonuses() const
{
return testForKey(parameters, "bonuses");
}
const JsonNode & Rewardable::Info::getParameters() const
{
return parameters;
}
VCMI_LIB_NAMESPACE_END

71
lib/rewardable/Info.h Normal file
View File

@ -0,0 +1,71 @@
/*
* Info.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 "../mapObjects/CObjectClassesHandler.h"
VCMI_LIB_NAMESPACE_BEGIN
class CRandomGenerator;
namespace Rewardable
{
struct Limiter;
using LimitersList = std::vector<std::shared_ptr<Rewardable::Limiter>>;
struct Reward;
struct Configuration;
struct ResetInfo;
enum class EEventType;
class DLL_LINKAGE Info : public IObjectInfo
{
JsonNode parameters;
void configureRewards(Rewardable::Configuration & object, CRandomGenerator & rng, const JsonNode & source, std::map<si32, si32> & thrownDice, Rewardable::EEventType mode) const;
void configureLimiter(Rewardable::Configuration & object, CRandomGenerator & rng, Rewardable::Limiter & limiter, const JsonNode & source) const;
Rewardable::LimitersList configureSublimiters(Rewardable::Configuration & object, CRandomGenerator & rng, const JsonNode & source) const;
void configureReward(Rewardable::Configuration & object, CRandomGenerator & rng, Rewardable::Reward & info, const JsonNode & source) const;
void configureResetInfo(Rewardable::Configuration & object, CRandomGenerator & rng, Rewardable::ResetInfo & 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

@ -0,0 +1,153 @@
/*
* Interface.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 "Interface.h"
#include "../CHeroHandler.h"
#include "../CSoundBase.h"
#include "../NetPacks.h"
#include "../spells/CSpellHandler.h"
#include "../spells/ISpellMechanics.h"
#include "../mapObjects/MiscObjects.h"
#include "../IGameCallback.h"
VCMI_LIB_NAMESPACE_BEGIN
std::vector<ui32> Rewardable::Interface::getAvailableRewards(const CGHeroInstance * hero, Rewardable::EEventType event) const
{
std::vector<ui32> ret;
for(size_t i = 0; i < configuration.info.size(); i++)
{
const Rewardable::VisitInfo & 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;
}
void Rewardable::Interface::grantRewardBeforeLevelup(IGameCallback * cb, const Rewardable::VisitInfo & 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 Rewardable::VisitInfo & 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

View File

@ -0,0 +1,54 @@
/*
* Interface.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 "../mapObjects/CObjectHandler.h"
#include "../CCreatureSet.h"
#include "../ResourceSet.h"
#include "../spells/ExternalCaster.h"
#include "Configuration.h"
VCMI_LIB_NAMESPACE_BEGIN
namespace Rewardable
{
class DLL_LINKAGE Interface
{
private:
/// 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, Rewardable::EEventType event) const;
/// function that must be called if hero got level-up during grantReward call
virtual void grantRewardAfterLevelup(IGameCallback * cb, const Rewardable::VisitInfo & reward, const CArmedInstance * army, const CGHeroInstance * hero) const;
/// grants reward to hero
virtual void grantRewardBeforeLevelup(IGameCallback * cb, const Rewardable::VisitInfo & reward, const CGHeroInstance * hero) const;
public:
Rewardable::Configuration configuration;
template <typename Handler> void serialize(Handler &h, const int version)
{
h & configuration;
}
};
}
VCMI_LIB_NAMESPACE_END

108
lib/rewardable/Limiter.cpp Normal file
View File

@ -0,0 +1,108 @@
/*
* Limiter.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 "Limiter.h"
#include "../IGameCallback.h"
#include "../CGameStateFwd.h"
#include "../CPlayerState.h"
VCMI_LIB_NAMESPACE_BEGIN
bool Rewardable::Limiter::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;
}
VCMI_LIB_NAMESPACE_END

102
lib/rewardable/Limiter.h Normal file
View File

@ -0,0 +1,102 @@
/*
* Limiter.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 "../mapObjects/CGHeroInstance.h"
VCMI_LIB_NAMESPACE_BEGIN
namespace Rewardable {
struct Limiter;
using LimitersList = std::vector<std::shared_ptr<Rewardable::Limiter>>;
/// 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
struct DLL_LINKAGE Limiter
{
/// 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
LimitersList allOf;
/// sub-limiters, at least one should pass for this limiter to pass
LimitersList anyOf;
/// sub-limiters, none should pass for this limiter to pass
LimitersList noneOf;
Limiter():
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;
}
};
}
VCMI_LIB_NAMESPACE_END

80
lib/rewardable/Reward.cpp Normal file
View File

@ -0,0 +1,80 @@
/*
* Reward.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 "Reward.h"
VCMI_LIB_NAMESPACE_BEGIN
si32 Rewardable::Reward::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 Rewardable::Reward::getDisplayedComponent(const CGHeroInstance * h) const
{
std::vector<Component> comps;
loadComponents(comps, h);
assert(!comps.empty());
return comps.front();
}
void Rewardable::Reward::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);
}
}
VCMI_LIB_NAMESPACE_END

118
lib/rewardable/Reward.h Normal file
View File

@ -0,0 +1,118 @@
/*
* Reward.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 "../mapObjects/CGHeroInstance.h"
VCMI_LIB_NAMESPACE_BEGIN
namespace Rewardable
{
struct Reward;
using RewardsList = std::vector<std::shared_ptr<Rewardable::Reward>>;
/// Reward that can be granted to a hero
/// NOTE: eventually should replace seer hut rewards and events/pandoras
struct DLL_LINKAGE Reward
{
/// 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;
Reward() :
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;
}
};
}
VCMI_LIB_NAMESPACE_END