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

Fixed lots of warnings.

Disabled the following (for MSVC only) that couldn't (or shouldn't) be fixed.

4003: not enough actual parameters for macro 'identifier'
4250: 'class1' : inherits 'class2::member' via dominance
4251: 'type' : class 'type1' needs to have dll-interface to be used by clients of class 'type2'
4275: non dll-interface class 'type1' used as base for dll-interface class 'type2'
This commit is contained in:
John Bolton 2020-10-01 01:38:06 -07:00
parent ff471af3de
commit a05ae78e67
142 changed files with 854 additions and 839 deletions

View File

@ -25,12 +25,12 @@ void CEmptyAI::yourTurn()
void CEmptyAI::heroGotLevel(const CGHeroInstance *hero, PrimarySkill::PrimarySkill pskill, std::vector<SecondarySkill> &skills, QueryID queryID)
{
cb->selectionMade(CRandomGenerator::getDefault().nextInt(skills.size() - 1), queryID);
cb->selectionMade(CRandomGenerator::getDefault().nextInt((int)skills.size() - 1), queryID);
}
void CEmptyAI::commanderGotLevel(const CCommanderInstance * commander, std::vector<ui32> skills, QueryID queryID)
{
cb->selectionMade(CRandomGenerator::getDefault().nextInt(skills.size() - 1), queryID);
cb->selectionMade(CRandomGenerator::getDefault().nextInt((int)skills.size() - 1), queryID);
}
void CEmptyAI::showBlockingDialog(const std::string &text, const std::vector<Component> &components, QueryID askID, const int soundID, bool selection, bool cancel)

View File

@ -54,8 +54,8 @@ struct EnemyInfo
void calcDmg(const CStack * ourStack)
{
TDmgRange retal, dmg = cbc->battleEstimateDamage(ourStack, s, &retal);
adi = (dmg.first + dmg.second) / 2;
adr = (retal.first + retal.second) / 2;
adi = static_cast<int>((dmg.first + dmg.second) / 2);
adr = static_cast<int>((retal.first + retal.second) / 2);
}
bool operator==(const EnemyInfo& ei) const

View File

@ -46,10 +46,10 @@ struct armyStructure
armyStructure evaluateArmyStructure(const CArmedInstance * army)
{
ui64 totalStrenght = army->getArmyStrength();
double walkersStrenght = 0;
double flyersStrenght = 0;
double shootersStrenght = 0;
ui64 totalStrength = army->getArmyStrength();
double walkersStrength = 0;
double flyersStrength = 0;
double shootersStrength = 0;
ui32 maxSpeed = 0;
static const CSelector selectorSHOOTER = Selector::type(Bonus::SHOOTER);
@ -67,23 +67,23 @@ armyStructure evaluateArmyStructure(const CArmedInstance * army)
const CCreature * creature = s.second->type;
if(creature->hasBonus(selectorSHOOTER, keySHOOTER))
{
shootersStrenght += s.second->getPower();
shootersStrength += s.second->getPower();
walker = false;
}
if(creature->hasBonus(selectorFLYING, keyFLYING))
{
flyersStrenght += s.second->getPower();
flyersStrength += s.second->getPower();
walker = false;
}
if(walker)
walkersStrenght += s.second->getPower();
walkersStrength += s.second->getPower();
vstd::amax(maxSpeed, creature->valOfBonuses(selectorSTACKS_SPEED, keySTACKS_SPEED));
}
armyStructure as;
as.walkers = walkersStrenght / totalStrenght;
as.shooters = shootersStrenght / totalStrenght;
as.flyers = flyersStrenght / totalStrenght;
as.walkers = static_cast<float>(walkersStrength / totalStrength);
as.shooters = static_cast<float>(shootersStrength / totalStrength);
as.flyers = static_cast<float>(flyersStrength / totalStrength);
as.maxSpeed = maxSpeed;
assert(as.walkers || as.flyers || as.shooters);
return as;
@ -346,7 +346,7 @@ void HeroMovementGoalEngineBase::setSharedFuzzyVariables(Goals::AbstractGoal & g
float strengthRatioData = 10.0f; //we are much stronger than enemy
ui64 danger = fh->evaluateDanger(goal.tile, goal.hero.h);
if(danger)
strengthRatioData = (fl::scalar)goal.hero.h->getTotalStrength() / danger;
strengthRatioData = static_cast<float>((fl::scalar)goal.hero.h->getTotalStrength() / danger);
try
{
@ -419,7 +419,7 @@ float VisitObjEngine::evaluate(Goals::VisitObj & goal)
{
objectValue->setValue(objValue);
engine.process();
output = value->getValue();
output = static_cast<float>(value->getValue());
}
catch(fl::Exception & fe)
{
@ -448,7 +448,7 @@ float VisitTileEngine::evaluate(Goals::VisitTile & goal)
{
engine.process();
goal.priority = value->getValue();
goal.priority = static_cast<float>(value->getValue());
}
catch(fl::Exception & fe)
{

View File

@ -115,7 +115,7 @@ float FuzzyHelper::evaluate(Goals::AdventureSpellCast & g)
float FuzzyHelper::evaluate(Goals::CompleteQuest & g)
{
// TODO: How to evaluate quest complexity?
const float questPenalty = 0.2;
const float questPenalty = 0.2f;
if(!g.parent)
{
@ -150,7 +150,7 @@ float FuzzyHelper::evaluate(Goals::GatherArmy & g)
{
//the more army we need, the more important goal
//the more army we lack, the less important goal
float army = g.hero->getArmyStrength();
float army = static_cast<float>(g.hero->getArmyStrength());
float ratio = g.value / std::max(g.value - army, 2000.0f); //2000 is about the value of hero recruited from tavern
return 5 * (ratio / (ratio + 2)); //so 50% army gives 2.5, asymptotic 5
}
@ -240,7 +240,7 @@ ui64 FuzzyHelper::evaluateDanger(crint3 tile, const CGHeroInstance * visitor, co
if(armedObj)
{
float tacticalAdvantage = tacticalAdvantageEngine.getTacticalAdvantage(visitor, armedObj);
objectDanger *= tacticalAdvantage; //this line tends to go infinite for allied towns (?)
objectDanger = static_cast<ui64>(objectDanger * tacticalAdvantage); //this line tends to go infinite for allied towns (?)
}
}
if(dangerousObject->ID == Obj::SUBTERRANEAN_GATE)

View File

@ -35,7 +35,7 @@ TSubgoal BuyArmy::whatToDoToAchieve()
{
//TODO: calculate the actual cost of units instead
TResources price;
price[Res::GOLD] = value * 0.4f; //some approximate value
price[Res::GOLD] = static_cast<int>(value * 0.4f); //some approximate value
return ai->ah->whatToDo(price, iAmElementar()); //buy right now or gather resources
}

View File

@ -414,7 +414,7 @@ TSubgoal Explore::exploreNearestNeighbour(HeroPtr h) const
//look for nearby objs -> visit them if they're close enough
const int DIST_LIMIT = 3;
const float COST_LIMIT = .2; //todo: fine tune
const float COST_LIMIT = .2f; //todo: fine tune
std::vector<const CGObjectInstance *> nearbyVisitableObjs;
for(int x = hpos.x - DIST_LIMIT; x <= hpos.x + DIST_LIMIT; ++x) //get only local objects instead of all possible objects on the map

View File

@ -148,7 +148,7 @@ TGoalVec GatherArmy::getAllPossibleSubgoals()
{
auto dwelling = dynamic_cast<const CGDwelling *>(obj);
ui32 val = std::min<ui32>(value, ai->ah->howManyReinforcementsCanBuy(hero.get(), dwelling));
ui32 val = std::min((ui32)value, (ui32)ai->ah->howManyReinforcementsCanBuy(hero.get(), dwelling));
if(val)
{

View File

@ -53,7 +53,7 @@ TGoalVec VisitObj::getAllPossibleSubgoals()
if(isSafeToVisit(hero, pos))
goalList.push_back(sptr(VisitObj(obj->id.getNum()).sethero(hero)));
else
goalList.push_back(sptr(GatherArmy(fh->evaluateDanger(pos, hero.h) * SAFE_ATTACK_CONSTANT).sethero(hero).setisAbstract(true)));
goalList.push_back(sptr(GatherArmy((int)(fh->evaluateDanger(pos, hero.h) * SAFE_ATTACK_CONSTANT)).sethero(hero).setisAbstract(true)));
return goalList;
}
@ -67,7 +67,7 @@ TGoalVec VisitObj::getAllPossibleSubgoals()
if(isSafeToVisit(potentialVisitor, pos))
goalList.push_back(sptr(VisitObj(obj->id.getNum()).sethero(potentialVisitor)));
else
goalList.push_back(sptr(GatherArmy(fh->evaluateDanger(pos, potentialVisitor) * SAFE_ATTACK_CONSTANT).sethero(potentialVisitor).setisAbstract(true)));
goalList.push_back(sptr(GatherArmy((int)(fh->evaluateDanger(pos, potentialVisitor) * SAFE_ATTACK_CONSTANT)).sethero(potentialVisitor).setisAbstract(true)));
}
}
if(!goalList.empty())

View File

@ -49,7 +49,7 @@ TSubgoal VisitTile::whatToDoToAchieve()
}
else
{
return sptr(GatherArmy(fh->evaluateDanger(tile, *ret->hero) * SAFE_ATTACK_CONSTANT)
return sptr(GatherArmy((int)(fh->evaluateDanger(tile, *ret->hero) * SAFE_ATTACK_CONSTANT))
.sethero(ret->hero).setisAbstract(true));
}
}

View File

@ -17,8 +17,6 @@
#include "../Goals/AbstractGoal.h"
#include "Actions/ISpecialAction.h"
struct AIPathNode;
struct AIPathNode : public CGPathNode
{
uint32_t chainMask;

View File

@ -49,7 +49,7 @@ namespace AIPathfinding
source->manaCost);
#endif
return hero->mana >= source->manaCost + getManaCost(hero);
return hero->mana >= (si32)(source->manaCost + getManaCost(hero));
}
uint32_t SummonBoatAction::getManaCost(const CGHeroInstance * hero) const

View File

@ -13,7 +13,7 @@
#include "../../AIUtility.h"
#include "../../Goals/AbstractGoal.h"
class AIPathNode;
struct AIPathNode;
class ISpecialAction
{

View File

@ -178,7 +178,7 @@ Goals::TGoalVec PathfindingManager::findPath(
#ifdef VCMI_TRACE_PATHFINDER
logAi->trace("Gather army for %s, value=%s", hero->name, std::to_string(danger));
#endif
result.push_back(sptr(Goals::GatherArmy(danger * SAFE_ATTACK_CONSTANT).sethero(hero).setisAbstract(true)));
result.push_back(sptr(Goals::GatherArmy((int)(danger * SAFE_ATTACK_CONSTANT)).sethero(hero).setisAbstract(true)));
}
return result;

View File

@ -116,7 +116,7 @@ namespace AIPathfinding
auto boatNodeOptional = nodeStorage->getOrCreateNode(
node->coord,
node->layer,
node->chainMask | virtualBoat->getSpecialChain());
(int)(node->chainMask | virtualBoat->getSpecialChain()));
if(boatNodeOptional)
{

View File

@ -631,7 +631,7 @@ void VCAI::showBlockingDialog(const std::string & text, const std::vector<Compon
% components.size() % text));
if(selection) //select from multiple components -> take the last one (they're indexed [1-size])
sel = components.size();
sel = static_cast<int>(components.size());
if(!selection && cancel) //yes&no -> always answer yes, we are a brave AI :)
sel = 1;
@ -812,6 +812,7 @@ void VCAI::makeTurn()
}
catch (boost::thread_interrupted & e)
{
(void)e;
logAi->debug("Making turn thread has been interrupted. We'll end without calling endTurn.");
return;
}
@ -968,6 +969,7 @@ void VCAI::mainLoop()
}
catch (boost::thread_interrupted & e)
{
(void)e;
logAi->debug("Player %d: Making turn thread received an interruption!", playerID);
throw; //rethrow, we want to truly end this thread
}
@ -1820,7 +1822,7 @@ bool VCAI::moveHeroToTile(int3 dst, HeroPtr h)
logAi->error("Hero %s cannot reach %s.", h->name, dst.toString());
throw goalFulfilledException(sptr(Goals::VisitTile(dst).sethero(h)));
}
int i = path.nodes.size() - 1;
int i = (int)path.nodes.size() - 1;
auto getObj = [&](int3 coord, bool ignoreHero)
{
@ -2112,12 +2114,12 @@ void VCAI::tryRealize(Goals::Trade & g) //trade
int toGive, toGet;
m->getOffer(res, g.resID, toGive, toGet, EMarketMode::RESOURCE_RESOURCE);
toGive = toGive * (it->resVal / toGive); //round down
toGive = static_cast<int>(toGive * (it->resVal / toGive)); //round down
//TODO trade only as much as needed
if (toGive) //don't try to sell 0 resources
{
cb->trade(obj, EMarketMode::RESOURCE_RESOURCE, res, g.resID, toGive);
accquiredResources = toGet * (it->resVal / toGive);
accquiredResources = static_cast<int>(toGet * (it->resVal / toGive));
logAi->debug("Traded %d of %s for %d of %s at %s", toGive, res, accquiredResources, g.resID, obj->getObjectName());
}
if (ah->freeResources()[g.resID] >= g.value)
@ -2330,6 +2332,7 @@ void VCAI::striveToGoal(Goals::TSubgoal basicGoal)
}
catch (boost::thread_interrupted & e)
{
(void)e;
logAi->debug("Player %d: Making turn thread received an interruption!", playerID);
throw; //rethrow, we want to truly end this thread
}
@ -2625,7 +2628,7 @@ void AIStatus::removeQuery(QueryID ID)
int AIStatus::getQueriesCount()
{
boost::unique_lock<boost::mutex> lock(mx);
return remainingQueries.size();
return static_cast<int>(remainingQueries.size());
}
void AIStatus::startedTurn()

View File

@ -143,7 +143,11 @@ if(WIN32)
# Suppress warnings
add_definitions(-D_CRT_SECURE_NO_WARNINGS)
add_definitions(-D_SCL_SECURE_NO_WARNINGS)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /bigobj /wd4251")
# 4003: not enough actual parameters for macro 'identifier'
# 4250: 'class1' : inherits 'class2::member' via dominance
# 4251: 'type' : class 'type1' needs to have dll-interface to be used by clients of class 'type2'
# 4275: non dll-interface class 'type1' used as base for dll-interface class 'type2'
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /bigobj /wd4003 /wd4250 /wd4251 /wd4275")
if(ENABLE_MULTI_PROCESS_BUILDS)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /MP")

View File

@ -342,7 +342,7 @@ namespace vstd
template <typename Container, typename T2>
int find_pos(const Container & c, const T2 &s)
{
size_t i=0;
int i=0;
for (auto iter = std::begin(c); iter != std::end(c); iter++, i++)
if(*iter == s)
return i;
@ -407,11 +407,11 @@ namespace vstd
template <typename t1, typename t2>
t1 &amax(t1 &a, const t2 &b)
{
if(a >= b)
if(a >= (t1)b)
return a;
else
{
a = b;
a = t1(b);
return a;
}
}
@ -420,11 +420,11 @@ namespace vstd
template <typename t1, typename t2>
t1 &amin(t1 &a, const t2 &b)
{
if(a <= b)
if(a <= (t1)b)
return a;
else
{
a = b;
a = t1(b);
return a;
}
}
@ -442,14 +442,14 @@ namespace vstd
template <typename t1, typename t2, typename t3>
bool isbetween(const t1 &value, const t2 &min, const t3 &max)
{
return value > min && value < max;
return value > (t1)min && value < (t1)max;
}
//checks if a is within b and c
template <typename t1, typename t2, typename t3>
bool iswithin(const t1 &value, const t2 &min, const t3 &max)
{
return value >= min && value <= max;
return value >= (t1)min && value <= (t1)max;
}
template <typename t1, typename t2>

View File

@ -60,14 +60,14 @@ SDL_Surface * BitmapHandler::loadH3PCX(ui8 * pcx, size_t size)
ret = SDL_CreateRGBSurface(0, width, height, 8, 0, 0, 0, 0);
it = 0xC;
for (int i=0; i<height; i++)
for (int i=0; i<(int)height; i++)
{
memcpy((char*)ret->pixels + ret->pitch * i, pcx + it, width);
it+= width;
}
//palette - last 256*3 bytes
it = size-256*3;
it = (int)size-256*3;
for (int i=0;i<256;i++)
{
SDL_Color tp;
@ -92,7 +92,7 @@ SDL_Surface * BitmapHandler::loadH3PCX(ui8 * pcx, size_t size)
ret = SDL_CreateRGBSurface(0, width, height, 24, rmask, gmask, bmask, 0);
//it == 0xC;
for (int i=0; i<height; i++)
for (int i=0; i<(int)height; i++)
{
memcpy((char*)ret->pixels + ret->pitch * i, pcx + it, width*3);
it+= width*3;
@ -138,7 +138,7 @@ SDL_Surface * BitmapHandler::loadBitmapFromDir(std::string path, std::string fna
{ //loading via SDL_Image
ret = IMG_Load_RW(
//create SDL_RW with our data (will be deleted by SDL)
SDL_RWFromConstMem((void*)readFile.first.get(), readFile.second),
SDL_RWFromConstMem((void*)readFile.first.get(), (int)readFile.second),
1); // mark it for auto-deleting
if (ret)
{

View File

@ -320,7 +320,7 @@ int main(int argc, char * argv[])
conf.init();
logGlobal->info("Loading settings: %d ms", pomtime.getDiff());
srand ( time(nullptr) );
srand ( (unsigned int)time(nullptr) );
const JsonNode& video = settings["video"];
@ -379,7 +379,7 @@ int main(int argc, char * argv[])
logGlobal->info("\t%s", driverName);
}
config::CConfigHandler::GuiOptionsMap::key_type resPair(res["width"].Float(), res["height"].Float());
config::CConfigHandler::GuiOptionsMap::key_type resPair((int)res["width"].Float(), (int)res["height"].Float());
if (conf.guiOptions.count(resPair) == 0)
{
// selected resolution was not found - complain & fallback to something that we do have.
@ -394,13 +394,13 @@ int main(int argc, char * argv[])
Settings newRes = settings.write["video"]["screenRes"];
newRes["width"].Float() = conf.guiOptions.begin()->first.first;
newRes["height"].Float() = conf.guiOptions.begin()->first.second;
conf.SetResolution(newRes["width"].Float(), newRes["height"].Float());
conf.SetResolution((int)newRes["width"].Float(), (int)newRes["height"].Float());
logGlobal->error("Falling back to %dx%d", newRes["width"].Integer(), newRes["height"].Integer());
}
}
setScreenRes(res["width"].Float(), res["height"].Float(), video["bitsPerPixel"].Float(), video["fullscreen"].Bool(), video["displayIndex"].Float());
setScreenRes((int)res["width"].Float(), (int)res["height"].Float(), (int)video["bitsPerPixel"].Float(), video["fullscreen"].Bool(), (int)video["displayIndex"].Float());
logGlobal->info("\tInitializing screen: %d ms", pomtime.getDiff());
}
@ -424,10 +424,10 @@ int main(int argc, char * argv[])
//initializing audio
CCS->soundh = new CSoundHandler();
CCS->soundh->init();
CCS->soundh->setVolume(settings["general"]["sound"].Float());
CCS->soundh->setVolume((ui32)settings["general"]["sound"].Float());
CCS->musich = new CMusicHandler();
CCS->musich->init();
CCS->musich->setVolume(settings["general"]["music"].Float());
CCS->musich->setVolume((ui32)settings["general"]["music"].Float());
logGlobal->info("Initializing screen and sound handling: %d ms", pomtime.getDiff());
}
#ifdef __APPLE__

View File

@ -144,8 +144,8 @@ std::vector<std::string> CMessage::breakText( std::string text, size_t maxLineWi
else if (text[currPos]=='}')
opened=false;
else
lineWidth += glyphWidth;
currPos += symbolSize;
lineWidth += (ui32)glyphWidth;
currPos += (ui32)symbolSize;
}
// long line, create line break
@ -154,7 +154,7 @@ std::vector<std::string> CMessage::breakText( std::string text, size_t maxLineWi
if (wordBreak != ui32(-1))
currPos = wordBreak;
else
currPos -= symbolSize;
currPos -= (ui32)symbolSize;
}
//non-blank line
@ -238,7 +238,7 @@ void CMessage::drawIWindow(CInfoWindow * ret, std::string text, PlayerColor play
{
int bh = 0;
// Compute total width of buttons
bw = 20*(ret->buttons.size()-1); // space between all buttons
bw = 20*((int)ret->buttons.size()-1); // space between all buttons
for(auto & elem : ret->buttons) //and add buttons width
{
bw+=elem->pos.w;
@ -397,7 +397,7 @@ ComponentsToBlit::~ComponentsToBlit() = default;
ComponentsToBlit::ComponentsToBlit(std::vector<std::shared_ptr<CComponent>> & SComps, int maxw, bool blitOr)
{
int orWidth = graphics->fonts[FONT_MEDIUM]->getStringWidth(CGI->generaltexth->allTexts[4]);
int orWidth = static_cast<int>(graphics->fonts[FONT_MEDIUM]->getStringWidth(CGI->generaltexth->allTexts[4]));
w = h = 0;
if(SComps.empty())
@ -440,7 +440,7 @@ ComponentsToBlit::ComponentsToBlit(std::vector<std::shared_ptr<CComponent>> & SC
void ComponentsToBlit::blitCompsOnSur( bool blitOr, int inter, int &curh, SDL_Surface *ret )
{
int orWidth = graphics->fonts[FONT_MEDIUM]->getStringWidth(CGI->generaltexth->allTexts[4]);
int orWidth = static_cast<int>(graphics->fonts[FONT_MEDIUM]->getStringWidth(CGI->generaltexth->allTexts[4]));
for (auto & elem : comps)//for each row
{
@ -454,9 +454,9 @@ void ComponentsToBlit::blitCompsOnSur( bool blitOr, int inter, int &curh, SDL_Su
//add space between comps in this row
if(blitOr)
totalw += (inter*2+orWidth) * (elem.size() - 1);
totalw += (inter*2+orWidth) * ((int)elem.size() - 1);
else
totalw += (inter) * (elem.size() - 1);
totalw += (inter) * ((int)elem.size() - 1);
int middleh = curh + maxHeight/2;//axis for image aligment
int curw = ret->w/2 - totalw/2;
@ -478,7 +478,7 @@ void ComponentsToBlit::blitCompsOnSur( bool blitOr, int inter, int &curh, SDL_Su
curw+=inter;
graphics->fonts[FONT_MEDIUM]->renderTextLeft(ret, CGI->generaltexth->allTexts[4], Colors::WHITE,
Point(curw,middleh-(graphics->fonts[FONT_MEDIUM]->getLineHeight()/2)));
Point(curw,middleh-((int)graphics->fonts[FONT_MEDIUM]->getLineHeight()/2)));
curw+=orWidth;
}

View File

@ -77,7 +77,7 @@ void CAudioBase::setVolume(ui32 percent)
void CSoundHandler::onVolumeChange(const JsonNode &volumeNode)
{
setVolume(volumeNode.Float());
setVolume((ui32)volumeNode.Float());
}
CSoundHandler::CSoundHandler():
@ -114,7 +114,7 @@ void CSoundHandler::init()
{
CAudioBase::init();
if(ambientConfig["allocateChannels"].isNumber())
Mix_AllocateChannels(ambientConfig["allocateChannels"].Integer());
Mix_AllocateChannels((int)ambientConfig["allocateChannels"].Integer());
if (initialized)
{
@ -148,7 +148,7 @@ Mix_Chunk *CSoundHandler::GetSoundChunk(std::string &sound, bool cache)
return soundChunks[sound].first;
auto data = CResourceHandler::get()->load(ResourceID(std::string("SOUNDS/") + sound, EResType::SOUND))->readAll();
SDL_RWops *ops = SDL_RWFromMem(data.first.get(), data.second);
SDL_RWops *ops = SDL_RWFromMem(data.first.get(), (int)data.second);
Mix_Chunk *chunk = Mix_LoadWAV_RW(ops, 1); // will free ops
if (cache)
@ -168,8 +168,8 @@ int CSoundHandler::ambientDistToVolume(int distance) const
if(distance >= ambientConfig["distances"].Vector().size())
return 0;
int volume = ambientConfig["distances"].Vector()[distance].Integer();
return volume * ambientConfig["volume"].Integer() * getVolume() / 10000;
int volume = static_cast<int>(ambientConfig["distances"].Vector()[distance].Integer());
return volume * (int)ambientConfig["volume"].Integer() * getVolume() / 10000;
}
void CSoundHandler::ambientStopSound(std::string soundId)
@ -270,7 +270,7 @@ void CSoundHandler::soundFinishedCallback(int channel)
int CSoundHandler::ambientGetRange() const
{
return ambientConfig["range"].Integer();
return static_cast<int>(ambientConfig["range"].Integer());
}
bool CSoundHandler::ambientCheckVisitable() const
@ -322,7 +322,7 @@ void CSoundHandler::ambientStopAllChannels()
void CMusicHandler::onVolumeChange(const JsonNode &volumeNode)
{
setVolume(volumeNode.Float());
setVolume((ui32)volumeNode.Float());
}
CMusicHandler::CMusicHandler():

View File

@ -163,7 +163,7 @@ void CPlayerInterface::yourTurn()
adventureInt->selection = nullptr;
std::string prefix = settings["session"]["saveprefix"].String();
int frequency = settings["general"]["saveFrequency"].Integer();
int frequency = static_cast<int>(settings["general"]["saveFrequency"].Integer());
if (firstCall)
{
if(CSH->howManyPlayerInterfaces() == 1)
@ -320,12 +320,12 @@ void CPlayerInterface::heroMoved(const TryMoveHero & details)
if(settings["session"]["spectate"].Bool())
{
if(!settings["session"]["spectate-hero-speed"].isNull())
speed = settings["session"]["spectate-hero-speed"].Integer();
speed = static_cast<ui32>(settings["session"]["spectate-hero-speed"].Integer());
}
else if (makingTurn) // our turn, our hero moves
speed = settings["adventure"]["heroSpeed"].Float();
speed = static_cast<ui32>(settings["adventure"]["heroSpeed"].Float());
else
speed = settings["adventure"]["enemySpeed"].Float();
speed = static_cast<ui32>(settings["adventure"]["enemySpeed"].Float());
if (speed == 0)
{
@ -2592,7 +2592,7 @@ void CPlayerInterface::playerStartsTurn(PlayerColor player)
EVENT_HANDLER_CALLED_BY_CLIENT;
if (!vstd::contains (GH.listInt, adventureInt))
{
GH.popInts (GH.listInt.size()); //after map load - remove everything else
GH.popInts ((int)GH.listInt.size()); //after map load - remove everything else
GH.pushInt (adventureInt);
}
else
@ -2729,7 +2729,7 @@ void CPlayerInterface::doMoveHero(const CGHeroInstance * h, CGPath path)
return false;
};
for (i=path.nodes.size()-1; i>0 && (stillMoveHero.data == CONTINUE_MOVE || !canStop(&path.nodes[i])); i--)
for (i=(int)path.nodes.size()-1; i>0 && (stillMoveHero.data == CONTINUE_MOVE || !canStop(&path.nodes[i])); i--)
{
int3 currentCoord = path.nodes[i].coord;
int3 nextCoord = path.nodes[i-1].coord;

View File

@ -288,9 +288,9 @@ bool CServerHandler::isGuest() const
ui16 CServerHandler::getDefaultPort()
{
if(settings["session"]["serverport"].Integer())
return settings["session"]["serverport"].Integer();
return static_cast<ui16>(settings["session"]["serverport"].Integer());
else
return settings["server"]["port"].Integer();
return static_cast<ui16>(settings["server"]["port"].Integer());
}
std::string CServerHandler::getDefaultPortStr()
@ -418,7 +418,7 @@ void CServerHandler::sendMessage(const std::string & txt) const
std::string connectedId, playerColorId;
readed >> connectedId;
readed >> playerColorId;
if(connectedId.length(), playerColorId.length())
if(connectedId.length(), playerColorId.length()) // BUG https://bugs.vcmi.eu/view.php?id=3144
{
ui8 connected = boost::lexical_cast<int>(connectedId);
auto color = PlayerColor(boost::lexical_cast<int>(playerColorId));

View File

@ -43,7 +43,7 @@ static int lodRead(void* opaque, uint8_t* buf, int size)
{
auto video = reinterpret_cast<CVideoPlayer *>(opaque);
return video->data->read(buf, size);
return static_cast<int>(video->data->read(buf, size));
}
static si64 lodSeek(void * opaque, si64 pos, int whence)

View File

@ -178,7 +178,7 @@ void CClient::loadGame()
void CClient::serialize(BinarySerializer & h, const int version)
{
assert(h.saving);
ui8 players = playerint.size();
ui8 players = static_cast<ui8>(playerint.size());
h & players;
for(auto i = playerint.begin(); i != playerint.end(); i++)

View File

@ -26,7 +26,7 @@ class CBattleGameInterface;
class CGameState;
class CGameInterface;
class CCallback;
struct BattleAction;
class BattleAction;
class CClient;
class CScriptingModule;
struct CPathsInfo;

View File

@ -47,7 +47,7 @@ void CreatureCostBox::createItems(TResources res)
if(!resources.empty())
{
int curx = pos.w / 2 - (16 * resources.size()) - (8 * (resources.size() - 1));
int curx = pos.w / 2 - (16 * (int)resources.size()) - (8 * ((int)resources.size() - 1));
//reverse to display gold as first resource
for(auto & currentRes : boost::adaptors::reverse(resources))
{

View File

@ -98,7 +98,7 @@ void Graphics::initializeBattleGraphics()
const JsonNode config(ResourceID("config/battles_graphics.json"));
// Reserve enough space for the terrains
int idx = config["backgrounds"].Vector().size();
int idx = static_cast<int>(config["backgrounds"].Vector().size());
battleBacks.resize(idx+1); // 1 to idx, 0 is unused
idx = 1;
@ -109,7 +109,7 @@ void Graphics::initializeBattleGraphics()
//initialization of AC->def name mapping
for(const JsonNode &ac : config["ac_mapping"].Vector()) {
int ACid = ac["id"].Float();
int ACid = static_cast<int>(ac["id"].Float());
std::vector< std::string > toAdd;
for(const JsonNode &defname : ac["defnames"].Vector()) {
@ -428,7 +428,7 @@ void Graphics::addImageListEntry(size_t index, std::string listName, std::string
if (!imageName.empty())
{
JsonNode entry;
entry["frame"].Float() = index;
entry["frame"].Float() = static_cast<double>(index);
entry["file"].String() = imageName;
imageLists["SPRITES/" + listName]["images"].Vector().push_back(entry);

View File

@ -495,7 +495,7 @@ bool CMovementAnimation::init()
if (stack->hasBonus(Selector::type(Bonus::FLYING)))
{
float distance = sqrt(distanceX * distanceX + distanceY * distanceY);
float distance = static_cast<float>(sqrt(distanceX * distanceX + distanceY * distanceY));
timeToMove *= AnimationControls::getFlightDistance(stack->getCreature()) / distance;
}
@ -829,10 +829,10 @@ bool CShootingAnimation::init()
else
{
// Catapult attack
spi.catapultInfo.reset(new CatapultProjectileInfo(Point(spi.x, spi.y), destPos));
spi.catapultInfo.reset(new CatapultProjectileInfo(Point((int)spi.x, (int)spi.y), destPos));
double animSpeed = AnimationControls::getProjectileSpeed() / 10;
spi.lastStep = std::abs((destPos.x - spi.x) / animSpeed);
spi.lastStep = static_cast<int>(std::abs((destPos.x - spi.x) / animSpeed));
spi.dx = animSpeed;
spi.dy = 0;
@ -871,7 +871,7 @@ bool CShootingAnimation::init()
}
}
spi.frameNum = bestID;
spi.frameNum = static_cast<int>(bestID);
// Set projectile animation start delay which is specified in frames
spi.animStartDelay = shooterInfo->animation.attackClimaxFrame;

View File

@ -78,13 +78,14 @@ static void transformPalette(SDL_Surface *surf, double rCor, double gCor, double
SDL_Color *colorsToChange = surf->format->palette->colors;
for (int g=0; g<surf->format->palette->ncolors; ++g)
{
if ((colorsToChange+g)->b != 132 &&
(colorsToChange+g)->g != 231 &&
(colorsToChange+g)->r != 255) //it's not yellow border
SDL_Color *color = &colorsToChange[g];
if (color->b != 132 &&
color->g != 231 &&
color->r != 255) //it's not yellow border
{
(colorsToChange+g)->r = static_cast<double>((colorsToChange+g)->r) *rCor;
(colorsToChange+g)->g = static_cast<double>((colorsToChange+g)->g) *gCor;
(colorsToChange+g)->b = static_cast<double>((colorsToChange+g)->b) *bCor;
color->r = static_cast<Uint8>(color->r * rCor);
color->g = static_cast<Uint8>(color->g * gCor);
color->b = static_cast<Uint8>(color->b * bCor);
}
}
}
@ -708,7 +709,7 @@ void CBattleInterface::setBattleCursor(const int myNumber)
sectorCursor.insert(sectorCursor.begin() + 2, aboveAttackable ? 14 : -1);
if (sector < 1.5)
cursorIndex = sector;
cursorIndex = static_cast<int>(sector);
else if (sector >= 1.5 && sector < 2.5)
cursorIndex = 2;
else if (sector >= 2.5 && sector < 4.5)
@ -720,7 +721,7 @@ void CBattleInterface::setBattleCursor(const int myNumber)
}
else
{
cursorIndex = sector;
cursorIndex = static_cast<int>(sector);
}
// Generally should NEVER happen, but to avoid the possibility of having endless loop below... [#1016]
@ -1082,7 +1083,7 @@ void CBattleInterface::stacksAreAttacked(std::vector<StackAttackedInfo> attacked
for(const StackAttackedInfo & attackedInfo : attackedInfos)
{
++targets;
damage += attackedInfo.dmg;
damage += (int)attackedInfo.dmg;
ui8 side = attackedInfo.defender->side;
killedBySide.at(side) += attackedInfo.amountKilled;
@ -1348,7 +1349,7 @@ void CBattleInterface::spellCast(const BattleSpellCast * sc)
double diffY = (destcoord.y - srccoord.y)*(destcoord.y - srccoord.y);
double distance = sqrt(diffX + diffY);
int steps = distance / AnimationControls::getSpellEffectSpeed() + 1;
int steps = static_cast<int>(distance / AnimationControls::getSpellEffectSpeed() + 1);
int dx = (destcoord.x - srccoord.x - first->width())/steps;
int dy = (destcoord.y - srccoord.y - first->height())/steps;
@ -1576,9 +1577,9 @@ void CBattleInterface::setAnimSpeed(int set)
int CBattleInterface::getAnimSpeed() const
{
if(settings["session"]["spectate"].Bool() && !settings["session"]["spectate-battle-speed"].isNull())
return vstd::round(settings["session"]["spectate-battle-speed"].Float() *100);
return static_cast<int>(vstd::round(settings["session"]["spectate-battle-speed"].Float() *100));
return vstd::round(settings["battle"]["animationSpeed"].Float() *100);
return static_cast<int>(vstd::round(settings["battle"]["animationSpeed"].Float() *100));
}
CPlayerInterface *CBattleInterface::getCurrentPlayerInterface() const
@ -2333,7 +2334,8 @@ void CBattleInterface::handleHex(BattleHex myNumber, int eventType)
}
};
std::string estDmgText = formatDmgRange(curInt->cb->battleEstimateDamage(activeStack, shere)); //calculating estimated dmg
TDmgRange damage = curInt->cb->battleEstimateDamage(activeStack, shere);
std::string estDmgText = formatDmgRange(std::make_pair((ui32)damage.first, (ui32)damage.second)); //calculating estimated dmg
consoleMsg = (boost::format(CGI->generaltexth->allTexts[36]) % shere->getName() % estDmgText).str(); //Attack %s (%s damage)
}
break;
@ -2345,7 +2347,8 @@ void CBattleInterface::handleHex(BattleHex myNumber, int eventType)
cursorFrame = ECursor::COMBAT_SHOOT;
realizeAction = [=](){giveCommand(EActionType::SHOOT, myNumber);};
std::string estDmgText = formatDmgRange(curInt->cb->battleEstimateDamage(activeStack, shere)); //calculating estimated dmg
TDmgRange damage = curInt->cb->battleEstimateDamage(activeStack, shere);
std::string estDmgText = formatDmgRange(std::make_pair((ui32)damage.first, (ui32)damage.second)); //calculating estimated dmg
//printing - Shoot %s (%d shots left, %s damage)
consoleMsg = (boost::format(CGI->generaltexth->allTexts[296]) % shere->getName() % activeStack->shots.available() % estDmgText).str();
}
@ -3227,8 +3230,8 @@ void CBattleInterface::showProjectiles(SDL_Surface *to)
SDL_Rect dst;
dst.h = image->height();
dst.w = image->width();
dst.x = it->x - dst.w / 2;
dst.y = it->y - dst.h / 2;
dst.x = static_cast<int>(it->x - dst.w / 2);
dst.y = static_cast<int>(it->y - dst.h / 2);
image->draw(to, &dst, nullptr);
}
@ -3426,7 +3429,7 @@ void CBattleInterface::showBattleEffects(SDL_Surface *to, const std::vector<cons
{
for (auto & elem : battleEffects)
{
int currentFrame = floor(elem->currentFrame);
int currentFrame = static_cast<int>(floor(elem->currentFrame));
currentFrame %= elem->animation->size();
auto img = elem->animation->getImage(currentFrame);
@ -3611,7 +3614,7 @@ void CBattleInterface::updateBattleAnimations()
}
//delete anims
int preSize = pendingAnims.size();
int preSize = static_cast<int>(pendingAnims.size());
for (auto it = pendingAnims.begin(); it != pendingAnims.end(); ++it)
{
if (it->first == nullptr)

View File

@ -78,12 +78,12 @@ bool CBattleConsole::addText(const std::string & text)
if(text[i] == 10)
{
texts.push_back( text.substr(firstInToken, i-firstInToken) );
firstInToken = i+1;
firstInToken = (int)i+1;
}
}
texts.push_back( text.substr(firstInToken, text.size()) );
lastShown = texts.size()-1;
lastShown = (int)texts.size()-1;
return true;
}
@ -242,7 +242,7 @@ void CBattleHero::switchToNextPhase()
firstFrame = 0;
lastFrame = animation->size(phase);
lastFrame = static_cast<int>(animation->size(phase));
}
currentFrame = firstFrame;
@ -467,7 +467,7 @@ CBattleResultWindow::CBattleResultWindow(const BattleResult & br, CPlayerInterfa
}
else
{
int xPos = 235 - (br.casualties[step].size()*32 + (br.casualties[step].size() - 1)*10)/2; //increment by 42 with each picture
int xPos = 235 - ((int)br.casualties[step].size()*32 + ((int)br.casualties[step].size() - 1)*10)/2; //increment by 42 with each picture
int yPos = 344 + step * 97;
for(auto & elem : br.casualties[step])
{
@ -793,12 +793,12 @@ void CStackQueue::StackBox::setUnit(const battle::Unit * unit, size_t turn)
if(stateIcon)
{
if(unit->defended(turn) || (turn > 0 && unit->defended(turn - 1)))
if(unit->defended((int)turn) || (turn > 0 && unit->defended((int)turn - 1)))
{
stateIcon->setFrame(0, 0);
stateIcon->visible = true;
}
else if(unit->waited(turn))
else if(unit->waited((int)turn))
{
stateIcon->setFrame(1, 0);
stateIcon->visible = true;

View File

@ -52,19 +52,19 @@ float AnimationControls::getCreatureAnimationSpeed(const CCreature * creature, c
//split "Attack time" into "Shoot Time" and "Cast Time"
// a lot of arbitrary multipliers, mostly to make animation speed closer to H3
const float baseSpeed = 0.1;
const float speedMult = settings["battle"]["animationSpeed"].Float();
const float baseSpeed = 0.1f;
const float speedMult = static_cast<float>(settings["battle"]["animationSpeed"].Float());
const float speed = baseSpeed / speedMult;
switch (type)
{
case CCreatureAnim::MOVING:
return speed * 2 * creature->animation.walkAnimationTime / anim->framesInGroup(type);
return static_cast<float>(speed * 2 * creature->animation.walkAnimationTime / anim->framesInGroup(type));
case CCreatureAnim::MOUSEON:
return baseSpeed;
case CCreatureAnim::HOLDING:
return baseSpeed * creature->animation.idleAnimationTime / anim->framesInGroup(type);
return static_cast<float>(baseSpeed * creature->animation.idleAnimationTime / anim->framesInGroup(type));
case CCreatureAnim::SHOOT_UP:
case CCreatureAnim::SHOOT_FRONT:
@ -75,7 +75,7 @@ float AnimationControls::getCreatureAnimationSpeed(const CCreature * creature, c
case CCreatureAnim::VCMI_CAST_DOWN:
case CCreatureAnim::VCMI_CAST_FRONT:
case CCreatureAnim::VCMI_CAST_UP:
return speed * 4 * creature->animation.attackAnimationTime / anim->framesInGroup(type);
return static_cast<float>(speed * 4 * creature->animation.attackAnimationTime / anim->framesInGroup(type));
// as strange as it looks like "attackAnimationTime" does not affects melee attacks
// necessary because length of these animations must be same for all creatures for synchronization
@ -110,22 +110,22 @@ float AnimationControls::getCreatureAnimationSpeed(const CCreature * creature, c
float AnimationControls::getProjectileSpeed()
{
return settings["battle"]["animationSpeed"].Float() * 100;
return static_cast<float>(settings["battle"]["animationSpeed"].Float() * 100);
}
float AnimationControls::getSpellEffectSpeed()
{
return settings["battle"]["animationSpeed"].Float() * 30;
return static_cast<float>(settings["battle"]["animationSpeed"].Float() * 30);
}
float AnimationControls::getMovementDuration(const CCreature * creature)
{
return settings["battle"]["animationSpeed"].Float() * 4 / creature->animation.walkAnimationTime;
return static_cast<float>(settings["battle"]["animationSpeed"].Float() * 4 / creature->animation.walkAnimationTime);
}
float AnimationControls::getFlightDistance(const CCreature * creature)
{
return creature->animation.flightAnimationDistance * 200;
return static_cast<float>(creature->animation.flightAnimationDistance * 200);
}
CCreatureAnim::EAnimType CCreatureAnimation::getType() const
@ -153,7 +153,7 @@ void CCreatureAnimation::shiftColor(const ColorShifter* shifter)
CCreatureAnimation::CCreatureAnimation(const std::string & name_, TSpeedController controller)
: name(name_),
speed(0.1),
speed(0.1f),
currentFrame(0),
elapsedTime(0),
type(CCreatureAnim::HOLDING),
@ -256,7 +256,7 @@ inline int getBorderStrength(float time)
{
float borderStrength = fabs(vstd::round(time) - time) * 2; // generate value in range 0-1
return borderStrength * 155 + 100; // scale to 0-255
return static_cast<int>(borderStrength * 155 + 100); // scale to 0-255
}
static SDL_Color genShadow(ui8 alpha)
@ -293,7 +293,7 @@ void CCreatureAnimation::genBorderPalette(IImage::BorderPallete & target)
void CCreatureAnimation::nextFrame(SDL_Surface * dest, bool attacker)
{
size_t frame = floor(currentFrame);
size_t frame = static_cast<size_t>(floor(currentFrame));
std::shared_ptr<IImage> image;
@ -315,7 +315,7 @@ void CCreatureAnimation::nextFrame(SDL_Surface * dest, bool attacker)
int CCreatureAnimation::framesInGroup(CCreatureAnim::EAnimType group) const
{
return forward->size(group);
return static_cast<int>(forward->size(group));
}
bool CCreatureAnimation::isDead() const

View File

@ -318,7 +318,7 @@ CDefFile::CDefFile(std::string Name):
//8 unknown bytes - skipping
//13 bytes for name of every frame in this block - not used, skipping
it+= 13 * totalEntries;
it+= 13 * (int)totalEntries;
for (ui32 j=0; j<totalEntries; j++)
{
@ -603,20 +603,20 @@ SDLImage::SDLImage(const JsonNode & conf)
const JsonNode & jsonMargins = conf["margins"];
margins.x = jsonMargins["left"].Integer();
margins.y = jsonMargins["top"].Integer();
margins.x = static_cast<int>(jsonMargins["left"].Integer());
margins.y = static_cast<int>(jsonMargins["top"].Integer());
fullSize.x = conf["width"].Integer();
fullSize.y = conf["height"].Integer();
fullSize.x = static_cast<int>(conf["width"].Integer());
fullSize.y = static_cast<int>(conf["height"].Integer());
if(fullSize.x == 0)
{
fullSize.x = margins.x + surf->w + jsonMargins["right"].Integer();
fullSize.x = margins.x + surf->w + (int)jsonMargins["right"].Integer();
}
if(fullSize.y == 0)
{
fullSize.y = margins.y + surf->h + jsonMargins["bottom"].Integer();
fullSize.y = margins.y + surf->h + (int)jsonMargins["bottom"].Integer();
}
}
@ -695,7 +695,7 @@ void SDLImage::draw(SDL_Surface* where, SDL_Rect* dest, SDL_Rect* src, ui8 alpha
std::shared_ptr<IImage> SDLImage::scaleFast(float scale) const
{
auto scaled = CSDL_Ext::scaleSurfaceFast(surf, surf->w * scale, surf->h * scale);
auto scaled = CSDL_Ext::scaleSurfaceFast(surf, (int)(surf->w * scale), (int)(surf->h * scale));
if (scaled->format && scaled->format->palette) // fix color keying, because SDL loses it at this point
CSDL_Ext::setColorKey(scaled, scaled->format->palette->colors[0]);
@ -1284,7 +1284,7 @@ void CFadeAnimation::draw(SDL_Surface * targetSurface, const SDL_Rect * sourceRe
return;
}
CSDL_Ext::setAlpha(fadingSurface, fadingCounter * 255);
CSDL_Ext::setAlpha(fadingSurface, (int)(fadingCounter * 255));
SDL_BlitSurface(fadingSurface, const_cast<SDL_Rect *>(sourceRect), targetSurface, destRect); //FIXME
CSDL_Ext::setAlpha(fadingSurface, 255);
}

View File

@ -207,8 +207,8 @@ void CCursorHandler::shiftPos( int &x, int &y )
void CCursorHandler::centerCursor()
{
this->xpos = (screen->w / 2.) - (currentCursor->pos.w / 2.);
this->ypos = (screen->h / 2.) - (currentCursor->pos.h / 2.);
this->xpos = static_cast<int>((screen->w / 2.) - (currentCursor->pos.w / 2.));
this->ypos = static_cast<int>((screen->h / 2.) - (currentCursor->pos.h / 2.));
SDL_EventState(SDL_MOUSEMOTION, SDL_IGNORE);
SDL_WarpMouse(this->xpos, this->ypos);
SDL_EventState(SDL_MOUSEMOTION, SDL_ENABLE);

View File

@ -615,7 +615,7 @@ void CFramerateManager::framerateDelay()
// FPS is higher than it should be, then wait some time
if (timeElapsed < rateticks)
{
SDL_Delay(ceil(this->rateticks) - timeElapsed);
SDL_Delay((Uint32)ceil(this->rateticks) - timeElapsed);
}
accumulatedTime += timeElapsed;
@ -624,7 +624,7 @@ void CFramerateManager::framerateDelay()
if(accumulatedFrames >= 100)
{
//about 2 second should be passed
fps = ceil(1000.0 / (accumulatedTime/accumulatedFrames));
fps = static_cast<int>(ceil(1000.0 / (accumulatedTime/accumulatedFrames)));
accumulatedTime = 0;
accumulatedFrames = 0;
}

View File

@ -36,13 +36,13 @@ void IFont::renderTextLeft(SDL_Surface * surface, const std::string & data, cons
void IFont::renderTextRight(SDL_Surface * surface, const std::string & data, const SDL_Color & color, const Point & pos) const
{
Point size(getStringWidth(data), getLineHeight());
Point size((int)getStringWidth(data), (int)getLineHeight());
renderText(surface, data, color, pos - size);
}
void IFont::renderTextCenter(SDL_Surface * surface, const std::string & data, const SDL_Color & color, const Point & pos) const
{
Point size(getStringWidth(data), getLineHeight());
Point size((int)getStringWidth(data), (int)getLineHeight());
renderText(surface, data, color, pos - size / 2);
}
@ -53,31 +53,31 @@ void IFont::renderTextLinesLeft(SDL_Surface * surface, const std::vector<std::st
for(const std::string & line : data)
{
renderTextLeft(surface, line, color, currPos);
currPos.y += getLineHeight();
currPos.y += (int)getLineHeight();
}
}
void IFont::renderTextLinesRight(SDL_Surface * surface, const std::vector<std::string> & data, const SDL_Color & color, const Point & pos) const
{
Point currPos = pos;
currPos.y -= data.size() * getLineHeight();
currPos.y -= (int)data.size() * (int)getLineHeight();
for(const std::string & line : data)
{
renderTextRight(surface, line, color, currPos);
currPos.y += getLineHeight();
currPos.y += (int)getLineHeight();
}
}
void IFont::renderTextLinesCenter(SDL_Surface * surface, const std::vector<std::string> & data, const SDL_Color & color, const Point & pos) const
{
Point currPos = pos;
currPos.y -= data.size() * getLineHeight()/2;
currPos.y -= (int)data.size() * (int)getLineHeight() / 2;
for(const std::string & line : data)
{
renderTextCenter(surface, line, color, currPos);
currPos.y += getLineHeight();
currPos.y += (int)getLineHeight();
}
}
@ -211,12 +211,12 @@ std::pair<std::unique_ptr<ui8[]>, ui64> CTrueTypeFont::loadData(const JsonNode &
TTF_Font * CTrueTypeFont::loadFont(const JsonNode &config)
{
int pointSize = config["size"].Float();
int pointSize = static_cast<int>(config["size"].Float());
if(!TTF_WasInit() && TTF_Init()==-1)
throw std::runtime_error(std::string("Failed to initialize true type support: ") + TTF_GetError() + "\n");
return TTF_OpenFontRW(SDL_RWFromConstMem(data.first.get(), data.second), 1, pointSize);
return TTF_OpenFontRW(SDL_RWFromConstMem(data.first.get(), (int)data.second), 1, pointSize);
}
int CTrueTypeFont::getFontStyle(const JsonNode &config)
@ -315,11 +315,11 @@ void CBitmapHanFont::renderCharacter(SDL_Surface * surface, int characterIndex,
// start of line, may differ from 0 due to end of surface or clipped surface
int lineBegin = std::max<int>(0, clipRect.y - posY);
int lineEnd = std::min<int>(size, clipRect.y + clipRect.h - posY);
int lineEnd = std::min((int)size, clipRect.y + clipRect.h - posY);
// start end end of each row, may differ from 0
int rowBegin = std::max<int>(0, clipRect.x - posX);
int rowEnd = std::min<int>(size, clipRect.x + clipRect.w - posX);
int rowEnd = std::min<int>((int)size, clipRect.x + clipRect.w - posX);
//for each line in symbol
for(int dy = lineBegin; dy <lineEnd; dy++)
@ -342,7 +342,7 @@ void CBitmapHanFont::renderCharacter(SDL_Surface * surface, int characterIndex,
colorPutter(dstPixel, color.r, color.g, color.b);
}
}
posX += size + 1;
posX += (int)size + 1;
}
void CBitmapHanFont::renderText(SDL_Surface * surface, const std::string & data, const SDL_Color & color, const Point & pos) const
@ -360,7 +360,7 @@ void CBitmapHanFont::renderText(SDL_Surface * surface, const std::string & data,
fallback->renderCharacter(surface, fallback->chars[ui8(localChar[0])], color, posX, posY);
if (localChar.size() == 2)
renderCharacter(surface, getCharacterIndex(localChar[0], localChar[1]), color, posX, posY);
renderCharacter(surface, (int)getCharacterIndex(localChar[0], localChar[1]), color, posX, posY);
}
SDL_UnlockSurface(surface);
}
@ -368,7 +368,7 @@ void CBitmapHanFont::renderText(SDL_Surface * surface, const std::string & data,
CBitmapHanFont::CBitmapHanFont(const JsonNode &config):
fallback(new CBitmapFont(config["fallback"].String())),
data(CResourceHandler::get()->load(ResourceID("data/" + config["name"].String(), EResType::OTHER))->readAll()),
size(config["size"].Float())
size((size_t)config["size"].Float())
{
// basic tests to make sure that fonts are OK
// 1) fonts must contain 190 "sections", 126 symbols each.

View File

@ -538,7 +538,7 @@ void CSDL_Ext::applyEffectBpp( SDL_Surface * surf, const SDL_Rect * rect, int mo
int r = Channels::px<bpp>::r.get(pixel);
int g = Channels::px<bpp>::g.get(pixel);
int b = Channels::px<bpp>::b.get(pixel);
int gray = 0.299 * r + 0.587 * g + 0.114 *b;
int gray = static_cast<int>(0.299 * r + 0.587 * g + 0.114 * b);
r = g = b = gray;
r = r + (sepiaDepth * 2);
@ -573,7 +573,7 @@ void CSDL_Ext::applyEffectBpp( SDL_Surface * surf, const SDL_Rect * rect, int mo
int g = Channels::px<bpp>::g.get(pixel);
int b = Channels::px<bpp>::b.get(pixel);
int gray = 0.299 * r + 0.587 * g + 0.114 *b;
int gray = static_cast<int>(0.299 * r + 0.587 * g + 0.114 *b);
vstd::amax(gray, 255);
Channels::px<bpp>::r.set(pixel, gray);
@ -609,8 +609,8 @@ void scaleSurfaceFastInternal(SDL_Surface *surf, SDL_Surface *ret)
for(int x = 0; x < ret->w; x++)
{
//coordinates we want to calculate
int origX = floor(factorX * x),
origY = floor(factorY * y);
int origX = static_cast<int>(floor(factorX * x)),
origY = static_cast<int>(floor(factorY * y));
// Get pointers to source pixels
Uint8 *srcPtr = (Uint8*)surf->pixels + origY * surf->pitch + origX * bpp;
@ -674,10 +674,10 @@ void scaleSurfaceInternal(SDL_Surface *surf, SDL_Surface *ret)
Uint8 *p22 = p21 + bpp;
// Calculate resulting channels
#define PX(X, PTR) Channels::px<bpp>::X.get(PTR)
int resR = PX(r, p11) * w11 + PX(r, p12) * w12 + PX(r, p21) * w21 + PX(r, p22) * w22;
int resG = PX(g, p11) * w11 + PX(g, p12) * w12 + PX(g, p21) * w21 + PX(g, p22) * w22;
int resB = PX(b, p11) * w11 + PX(b, p12) * w12 + PX(b, p21) * w21 + PX(b, p22) * w22;
int resA = PX(a, p11) * w11 + PX(a, p12) * w12 + PX(a, p21) * w21 + PX(a, p22) * w22;
int resR = static_cast<int>(PX(r, p11) * w11 + PX(r, p12) * w12 + PX(r, p21) * w21 + PX(r, p22) * w22);
int resG = static_cast<int>(PX(g, p11) * w11 + PX(g, p12) * w12 + PX(g, p21) * w21 + PX(g, p22) * w22);
int resB = static_cast<int>(PX(b, p11) * w11 + PX(b, p12) * w12 + PX(b, p21) * w21 + PX(b, p22) * w22);
int resA = static_cast<int>(PX(a, p11) * w11 + PX(a, p12) * w12 + PX(a, p21) * w21 + PX(a, p22) * w22);
//assert(resR < 256 && resG < 256 && resB < 256 && resA < 256);
#undef PX
Uint8 *dest = (Uint8*)ret->pixels + y * ret->pitch + x * bpp;

View File

@ -124,15 +124,15 @@ void CBonusSelection::loadPositionsOfGraphics()
SCampPositions sc;
sc.campPrefix = campaign["prefix"].String();
sc.colorSuffixLength = campaign["color_suffix_length"].Float();
sc.colorSuffixLength = static_cast<int>(campaign["color_suffix_length"].Float());
for(const JsonNode & desc : campaign["desc"].Vector())
{
SCampPositions::SRegionDesc rd;
rd.infix = desc["infix"].String();
rd.xpos = desc["x"].Float();
rd.ypos = desc["y"].Float();
rd.xpos = static_cast<int>(desc["x"].Float());
rd.ypos = static_cast<int>(desc["y"].Float());
sc.regions.push_back(rd);
}

View File

@ -10,7 +10,7 @@
#pragma once
#include "../windows/CWindowObject.h"
class SDL_Surface;
struct SDL_Surface;
class CCampaignState;
class CButton;
class CTextBox;

View File

@ -133,15 +133,17 @@ void CLobbyScreen::startScenario(bool allowOnlyAI)
}
catch(ExceptionMapMissing & e)
{
(void)e;
}
catch(ExceptionNoHuman & e)
{
(void)e;
// You must position yourself prior to starting the game.
CInfoWindow::showYesNoDialog(std::ref(CGI->generaltexth->allTexts[530]), CInfoWindow::TCompsInfo(), 0, std::bind(&CLobbyScreen::startScenario, this, true), PlayerColor(1));
}
catch(ExceptionNoTemplate & e)
{
(void)e;
CInfoWindow::showInfoDialog(std::ref(CGI->generaltexth->allTexts[751]), CInfoWindow::TCompsInfo(), PlayerColor(1));
}
catch(...)

View File

@ -234,12 +234,12 @@ void InfoCard::changeSelection()
if(pset)
{
auto name = boost::str(boost::format("%s (%d-%d %s)") % p.second.name % p.second.connection % pid % pset->color.getStr());
labelGroupPlayersAssigned->add(24, 285 + labelGroupPlayersAssigned->currentSize()*graphics->fonts[FONT_SMALL]->getLineHeight(), name);
labelGroupPlayersAssigned->add(24, 285 + (int)labelGroupPlayersAssigned->currentSize()*(int)graphics->fonts[FONT_SMALL]->getLineHeight(), name);
}
else
{
auto name = boost::str(boost::format("%s (%d-%d)") % p.second.name % p.second.connection % pid);
labelGroupPlayersUnassigned->add(193, 285 + labelGroupPlayersUnassigned->currentSize()*graphics->fonts[FONT_SMALL]->getLineHeight(), name);
labelGroupPlayersUnassigned->add(193, 285 + (int)labelGroupPlayersUnassigned->currentSize()*(int)graphics->fonts[FONT_SMALL]->getLineHeight(), name);
}
}
}
@ -312,7 +312,7 @@ CChatBox::CChatBox(const Rect & rect)
captureAllKeys = true;
type |= REDRAW_PARENT;
const int height = graphics->fonts[FONT_SMALL]->getLineHeight();
const int height = static_cast<int>(graphics->fonts[FONT_SMALL]->getLineHeight());
inputBox = std::make_shared<CTextInput>(Rect(0, rect.h - height, rect.w, height));
inputBox->removeUsedEvents(KEYBOARD);
chatHistory = std::make_shared<CTextBox>("", Rect(0, 0, rect.w, rect.h - height), 1);
@ -359,19 +359,19 @@ void CFlagBox::recreate()
flagsAllies.clear();
flagsEnemies.clear();
OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
const int alliesX = 5 + labelAllies->getWidth();
const int enemiesX = 5 + 133 + labelEnemies->getWidth();
const int alliesX = 5 + (int)labelAllies->getWidth();
const int enemiesX = 5 + 133 + (int)labelEnemies->getWidth();
for(auto i = CSH->si->playerInfos.cbegin(); i != CSH->si->playerInfos.cend(); i++)
{
auto flag = std::make_shared<CAnimImage>(iconsTeamFlags, i->first.getNum(), 0);
if(i->first == CSH->myFirstColor() || CSH->getPlayerTeamId(i->first) == CSH->getPlayerTeamId(CSH->myFirstColor()))
{
flag->moveTo(Point(pos.x + alliesX + flagsAllies.size()*flag->pos.w, pos.y));
flag->moveTo(Point(pos.x + alliesX + (int)flagsAllies.size()*flag->pos.w, pos.y));
flagsAllies.push_back(flag);
}
else
{
flag->moveTo(Point(pos.x + enemiesX + flagsEnemies.size()*flag->pos.w, pos.y));
flag->moveTo(Point(pos.x + enemiesX + (int)flagsEnemies.size()*flag->pos.w, pos.y));
flagsEnemies.push_back(flag);
}
}
@ -406,7 +406,7 @@ CFlagBox::CFlagBoxTooltipBox::CFlagBoxTooltipBox(std::shared_ptr<CAnimation> ico
}
}
int curx = 128 - 9 * flags.size();
int curx = 128 - 9 * (int)flags.size();
for(auto & flag : flags)
{
iconsFlags.push_back(std::make_shared<CAnimImage>(icons, flag, 0, curx, 75 + 50 * i));

View File

@ -40,15 +40,15 @@ OptionsTab::OptionsTab()
background = std::make_shared<CPicture>("ADVOPTBK", 0, 6);
pos = background->pos;
labelTitle = std::make_shared<CLabel>(222, 30, FONT_BIG, CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[515]);
labelSubTitle = std::make_shared<CMultiLineLabel>(Rect(60, 44, 320, graphics->fonts[EFonts::FONT_SMALL]->getLineHeight()*2), EFonts::FONT_SMALL, EAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[516]);
labelSubTitle = std::make_shared<CMultiLineLabel>(Rect(60, 44, 320, (int)graphics->fonts[EFonts::FONT_SMALL]->getLineHeight()*2), EFonts::FONT_SMALL, EAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[516]);
labelPlayerNameAndHandicap = std::make_shared<CMultiLineLabel>(Rect(58, 86, 100, graphics->fonts[EFonts::FONT_SMALL]->getLineHeight()*2), EFonts::FONT_SMALL, EAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[517]);
labelStartingTown = std::make_shared<CMultiLineLabel>(Rect(163, 86, 70, graphics->fonts[EFonts::FONT_SMALL]->getLineHeight()*2), EFonts::FONT_SMALL, EAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[518]);
labelStartingHero = std::make_shared<CMultiLineLabel>(Rect(239, 86, 70, graphics->fonts[EFonts::FONT_SMALL]->getLineHeight()*2), EFonts::FONT_SMALL, EAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[519]);
labelStartingBonus = std::make_shared<CMultiLineLabel>(Rect(315, 86, 70, graphics->fonts[EFonts::FONT_SMALL]->getLineHeight()*2), EFonts::FONT_SMALL, EAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[520]);
labelPlayerNameAndHandicap = std::make_shared<CMultiLineLabel>(Rect(58, 86, 100, (int)graphics->fonts[EFonts::FONT_SMALL]->getLineHeight()*2), EFonts::FONT_SMALL, EAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[517]);
labelStartingTown = std::make_shared<CMultiLineLabel>(Rect(163, 86, 70, (int)graphics->fonts[EFonts::FONT_SMALL]->getLineHeight()*2), EFonts::FONT_SMALL, EAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[518]);
labelStartingHero = std::make_shared<CMultiLineLabel>(Rect(239, 86, 70, (int)graphics->fonts[EFonts::FONT_SMALL]->getLineHeight()*2), EFonts::FONT_SMALL, EAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[519]);
labelStartingBonus = std::make_shared<CMultiLineLabel>(Rect(315, 86, 70, (int)graphics->fonts[EFonts::FONT_SMALL]->getLineHeight()*2), EFonts::FONT_SMALL, EAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[520]);
if(SEL->screenType == ESelectionScreen::newGame || SEL->screenType == ESelectionScreen::loadGame || SEL->screenType == ESelectionScreen::scenarioInfo)
{
sliderTurnDuration = std::make_shared<CSlider>(Point(55, 551), 194, std::bind(&IServerAPI::setTurnLength, CSH, _1), 1, GameConstants::POSSIBLE_TURNTIME.size(), GameConstants::POSSIBLE_TURNTIME.size(), true, CSlider::BLUE);
sliderTurnDuration = std::make_shared<CSlider>(Point(55, 551), 194, std::bind(&IServerAPI::setTurnLength, CSH, _1), 1, (int)GameConstants::POSSIBLE_TURNTIME.size(), (int)GameConstants::POSSIBLE_TURNTIME.size(), true, CSlider::BLUE);
labelPlayerTurnDuration = std::make_shared<CLabel>(222, 538, FONT_SMALL, EAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[521]);
labelTurnDurationValue = std::make_shared<CLabel>(319, 559, FONT_SMALL, EAlignment::CENTER, Colors::WHITE);
}
@ -466,7 +466,7 @@ OptionsTab::PlayerOptionsEntry::PlayerOptionsEntry(const PlayerSettings & S)
background = std::make_shared<CPicture>(BitmapHandler::loadBitmap(bgs[s.color.getNum()]), 0, 0, true);
labelPlayerName = std::make_shared<CLabel>(55, 10, EFonts::FONT_SMALL, EAlignment::CENTER, Colors::WHITE, s.name);
labelWhoCanPlay = std::make_shared<CMultiLineLabel>(Rect(6, 23, 45, graphics->fonts[EFonts::FONT_TINY]->getLineHeight()*2), EFonts::FONT_TINY, EAlignment::CENTER, Colors::WHITE, CGI->generaltexth->arraytxt[206 + whoCanPlay]);
labelWhoCanPlay = std::make_shared<CMultiLineLabel>(Rect(6, 23, 45, (int)graphics->fonts[EFonts::FONT_TINY]->getLineHeight()*2), EFonts::FONT_TINY, EAlignment::CENTER, Colors::WHITE, CGI->generaltexth->arraytxt[206 + whoCanPlay]);
if(SEL->screenType == ESelectionScreen::newGame)
{

View File

@ -185,7 +185,7 @@ SelectionTab::SelectionTab(ESelectionScreen Type)
listItems.push_back(std::make_shared<ListItem>(Point(30, 129 + i * 25), iconsMapFormats, iconsVictoryCondition, iconsLossCondition));
labelTabTitle = std::make_shared<CLabel>(205, 28, FONT_MEDIUM, EAlignment::CENTER, Colors::YELLOW, tabTitle);
slider = std::make_shared<CSlider>(Point(372, 86), tabType != ESelectionScreen::saveGame ? 480 : 430, std::bind(&SelectionTab::sliderMove, this, _1), positionsToShow, curItems.size(), 0, false, CSlider::BLUE);
slider = std::make_shared<CSlider>(Point(372, 86), tabType != ESelectionScreen::saveGame ? 480 : 430, std::bind(&SelectionTab::sliderMove, this, _1), positionsToShow, (int)curItems.size(), 0, false, CSlider::BLUE);
filter(0);
}
@ -242,7 +242,7 @@ void SelectionTab::toggleMode()
restoreLastSelection();
}
}
slider->setAmount(curItems.size());
slider->setAmount((int)curItems.size());
updateListItems();
redraw();
}
@ -271,21 +271,21 @@ void SelectionTab::keyPressed(const SDL_KeyboardEvent & key)
moveBy = +1;
break;
case SDLK_PAGEUP:
moveBy = -listItems.size() + 1;
moveBy = -(int)listItems.size() + 1;
break;
case SDLK_PAGEDOWN:
moveBy = +listItems.size() - 1;
moveBy = +(int)listItems.size() - 1;
break;
case SDLK_HOME:
select(-slider->getValue());
return;
case SDLK_END:
select(curItems.size() - slider->getValue());
select((int)curItems.size() - slider->getValue());
return;
default:
return;
}
select(selectionPos - slider->getValue() + moveBy);
select((int)selectionPos - slider->getValue() + moveBy);
}
void SelectionTab::onDoubleClick()
@ -319,7 +319,7 @@ void SelectionTab::filter(int size, bool selectFirst)
if(curItems.size())
{
slider->block(false);
slider->setAmount(curItems.size());
slider->setAmount((int)curItems.size());
sort();
if(selectFirst)
{
@ -380,7 +380,7 @@ void SelectionTab::select(int position)
if(position < 0)
slider->moveBy(position);
else if(position >= listItems.size())
slider->moveBy(position - listItems.size() + 1);
slider->moveBy(position - (int)listItems.size() + 1);
rememberCurrentSelection();
@ -451,7 +451,7 @@ int SelectionTab::getLine()
void SelectionTab::selectFileName(std::string fname)
{
boost::to_upper(fname);
for(int i = curItems.size() - 1; i >= 0; i--)
for(int i = (int)curItems.size() - 1; i >= 0; i--)
{
if(curItems[i]->fileURI == fname)
{

View File

@ -77,17 +77,17 @@ std::shared_ptr<CButton> CCampaignScreen::createExitButton(const JsonNode & butt
{
std::pair<std::string, std::string> help;
if(!button["help"].isNull() && button["help"].Float() > 0)
help = CGI->generaltexth->zelp[button["help"].Float()];
help = CGI->generaltexth->zelp[(size_t)button["help"].Float()];
return std::make_shared<CButton>(Point(button["x"].Float(), button["y"].Float()), button["name"].String(), help, [=](){ close();}, button["hotkey"].Float());
return std::make_shared<CButton>(Point((int)button["x"].Float(), (int)button["y"].Float()), button["name"].String(), help, [=](){ close();}, (int)button["hotkey"].Float());
}
CCampaignScreen::CCampaignButton::CCampaignButton(const JsonNode & config)
{
OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
pos.x += config["x"].Float();
pos.y += config["y"].Float();
pos.x += static_cast<int>(config["x"].Float());
pos.y += static_cast<int>(config["y"].Float());
pos.w = 200;
pos.h = 116;

View File

@ -12,7 +12,7 @@
class CLabel;
class CPicture;
class CButton;
class SDL_Surface;
struct SDL_Surface;
class JsonNode;
class CCampaignScreen : public CWindowObject

View File

@ -109,7 +109,7 @@ std::shared_ptr<CIntObject> CMenuScreen::createTab(size_t index)
void CMenuScreen::show(SDL_Surface * to)
{
if(!config["video"].isNull())
CCS->videoh->update(config["video"]["x"].Float() + pos.x, config["video"]["y"].Float() + pos.y, to, true, false);
CCS->videoh->update((int)config["video"]["x"].Float() + pos.x, (int)config["video"]["y"].Float() + pos.y, to, true, false);
CIntObject::show(to);
}
@ -221,17 +221,17 @@ std::shared_ptr<CButton> CMenuEntry::createButton(CMenuScreen * parent, const Js
std::pair<std::string, std::string> help;
if(!button["help"].isNull() && button["help"].Float() > 0)
help = CGI->generaltexth->zelp[button["help"].Float()];
help = CGI->generaltexth->zelp[(size_t)button["help"].Float()];
int posx = button["x"].Float();
int posx = static_cast<int>(button["x"].Float());
if(posx < 0)
posx = pos.w + posx;
int posy = button["y"].Float();
int posy = static_cast<int>(button["y"].Float());
if(posy < 0)
posy = pos.h + posy;
return std::make_shared<CButton>(Point(posx, posy), button["name"].String(), help, command, button["hotkey"].Float());
return std::make_shared<CButton>(Point(posx, posy), button["name"].String(), help, command, (int)button["hotkey"].Float());
}
CMenuEntry::CMenuEntry(CMenuScreen * parent, const JsonNode & config)
@ -358,7 +358,7 @@ std::shared_ptr<CMainMenu> CMainMenu::create()
std::shared_ptr<CPicture> CMainMenu::createPicture(const JsonNode & config)
{
return std::make_shared<CPicture>(config["name"].String(), config["x"].Float(), config["y"].Float());
return std::make_shared<CPicture>(config["name"].String(), (int)config["x"].Float(), (int)config["y"].Float());
}
CMultiMode::CMultiMode(ESelectionScreen ScreenType)

View File

@ -12,7 +12,7 @@
#include "../../lib/mapping/CCampaignHandler.h"
class CMultiLineLabel;
class SDL_Surface;
struct SDL_Surface;
class CPrologEpilogVideo : public CWindowObject
{

View File

@ -12,7 +12,7 @@
#include "../windows/CWindowObject.h"
class CMultiLineLabel;
class SDL_Surface;
struct SDL_Surface;
class CreditsScreen : public CIntObject
{

View File

@ -121,7 +121,7 @@ void CMapHandler::prepareFOWDefs()
elem[j].resize(sizes.z);
for(int k = 0; k < sizes.z; ++k)
{
elem[j][k] = CRandomGenerator::getDefault().nextInt(size - 1);
elem[j][k] = CRandomGenerator::getDefault().nextInt((int)size - 1);
}
}
}
@ -617,7 +617,7 @@ void CMapHandler::CMapWorldViewBlitter::drawObject(SDL_Surface * targetSurf, std
if (moving)
return;
Rect scaledSourceRect(sourceRect->x * info->scale, sourceRect->y * info->scale, sourceRect->w, sourceRect->h);
Rect scaledSourceRect((int)(sourceRect->x * info->scale), (int)(sourceRect->y * info->scale), sourceRect->w, sourceRect->h);
CMapBlitter::drawObject(targetSurf, source, &scaledSourceRect, false);
}
@ -1295,14 +1295,14 @@ bool CMapHandler::hideObject(const CGObjectInstance * obj, bool fadeout)
{
for (size_t k = 0; k<(map->twoLevel ? 2 : 1); k++)
{
auto &objs = ttiles[i][j][k].objects;
auto &objs = ttiles[(int)i][(int)j][(int)k].objects;
for (size_t x = 0; x < objs.size(); x++)
{
if (objs[x].obj && objs[x].obj->id == obj->id)
{
if (fadeout && ADVOPT.objectFading) // object should be faded == erase is delayed until the end of fadeout
{
if (startObjectFade(objs[x], false, int3(i, j, k)))
if (startObjectFade(objs[x], false, int3((si32)i, (si32)j, (si32)k)))
objs[x].obj = nullptr;
else
objs.erase(objs.begin() + x);

View File

@ -150,7 +150,7 @@ public:
}
int size() const
{
return inver.size();
return static_cast<int>(inver.size());
}
private:

View File

@ -109,7 +109,7 @@ CList::CList(int Size, Point position, std::string btnUp, std::string btnDown, s
{
OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
scrollUp = std::make_shared<CButton>(Point(0, 0), btnUp, CGI->generaltexth->zelp[helpUp]);
scrollDown = std::make_shared<CButton>(Point(0, scrollUp->pos.h + 32*size), btnDown, CGI->generaltexth->zelp[helpDown]);
scrollDown = std::make_shared<CButton>(Point(0, scrollUp->pos.h + 32*(int)size), btnDown, CGI->generaltexth->zelp[helpDown]);
listBox = std::make_shared<CListBox>(create, Point(1,scrollUp->pos.h), Point(0, 32), size, listAmount);
@ -150,7 +150,7 @@ void CList::select(std::shared_ptr<CListItem> which)
int CList::getSelectedIndex()
{
return listBox->getIndexOf(selected);
return static_cast<int>(listBox->getIndexOf(selected));
}
void CList::selectIndex(int which)
@ -402,8 +402,8 @@ void CMinimapInstance::tileToPixels (const int3 &tile, int &x, int &y, int toX,
double stepX = double(pos.w) / mapSizes.x;
double stepY = double(pos.h) / mapSizes.y;
x = toX + stepX * tile.x;
y = toY + stepY * tile.y;
x = static_cast<int>(toX + stepX * tile.x);
y = static_cast<int>(toY + stepY * tile.y);
}
void CMinimapInstance::blitTileWithColor(const SDL_Color &color, const int3 &tile, SDL_Surface *to, int toX, int toY)
@ -446,10 +446,10 @@ void CMinimapInstance::drawScaled(int level)
//coordinates of rectangle on minimap representing this tile
// begin - first to blit, end - first NOT to blit
int xBegin = currX;
int yBegin = currY;
int xEnd = currX + stepX;
int yEnd = currY + stepY;
int xBegin = static_cast<int>(currX);
int yBegin = static_cast<int>(currY);
int xEnd = static_cast<int>(currX + stepX);
int yEnd = static_cast<int>(currY + stepY);
for (int y=yBegin; y<yEnd; y++)
{
@ -508,7 +508,7 @@ std::map<int, std::pair<SDL_Color, SDL_Color> > CMinimap::loadColors(std::string
logGlobal->error("Error: unknown terrain in terrains.json: %s", m.first);
continue;
}
int terrainID = index - std::begin(GameConstants::TERRAIN_NAMES);
int terrainID = static_cast<int>(index - std::begin(GameConstants::TERRAIN_NAMES));
const JsonVector &unblockedVec = m.second["minimapUnblocked"].Vector();
SDL_Color normal =
@ -554,7 +554,7 @@ int3 CMinimap::translateMousePosition()
int3 mapSizes = LOCPLINT->cb->getMapSize();
int3 tile (mapSizes.x * dx, mapSizes.y * dy, level);
int3 tile ((si32)(mapSizes.x * dx), (si32)(mapSizes.y * dy), level);
return tile;
}
@ -803,9 +803,9 @@ CInfoBar::VisibleGameStatusInfo::VisibleGameStatusInfo()
for(size_t i=0; i<halls.size(); i++)
{
hallIcons.push_back(std::make_shared<CAnimImage>("itmtl", i, 0, 6 + 42 * i , 11));
hallIcons.push_back(std::make_shared<CAnimImage>("itmtl", i, 0, 6 + 42 * (int)i , 11));
if(halls[i])
hallLabels.push_back(std::make_shared<CLabel>( 26 + 42 * i, 64, FONT_SMALL, CENTER, Colors::WHITE, boost::lexical_cast<std::string>(halls[i])));
hallLabels.push_back(std::make_shared<CLabel>( 26 + 42 * (int)i, 64, FONT_SMALL, CENTER, Colors::WHITE, boost::lexical_cast<std::string>(halls[i])));
}
}
@ -980,7 +980,7 @@ void CInGameConsole::show(SDL_Surface * to)
{
int number = 0;
std::vector<std::list< std::pair< std::string, int > >::iterator> toDel;
std::vector<std::list< std::pair< std::string, Uint32 > >::iterator> toDel;
boost::unique_lock<boost::mutex> lock(texts_mx);
for(auto it = texts.begin(); it != texts.end(); ++it, ++number)
@ -991,9 +991,9 @@ void CInGameConsole::show(SDL_Surface * to)
leftBottomCorner = LOCPLINT->battleInt->pos.bottomLeft();
}
graphics->fonts[FONT_MEDIUM]->renderTextLeft(to, it->first, Colors::GREEN,
Point(leftBottomCorner.x + 50, leftBottomCorner.y - texts.size() * 20 - 80 + number*20));
Point(leftBottomCorner.x + 50, leftBottomCorner.y - (int)texts.size() * 20 - 80 + number*20));
if(SDL_GetTicks() - it->second > defaultTimeout)
if((int)(SDL_GetTicks() - it->second) > defaultTimeout)
{
toDel.push_back(it);
}
@ -1086,7 +1086,7 @@ void CInGameConsole::keyPressed (const SDL_KeyboardEvent & key)
if(prevEntDisp == -1)
{
prevEntDisp = previouslyEntered.size() - 1;
prevEntDisp = static_cast<int>(previouslyEntered.size() - 1);
enteredText = previouslyEntered[prevEntDisp] + "_";
refreshEnteredText();
}

View File

@ -400,7 +400,7 @@ public:
class CInGameConsole : public CIntObject
{
private:
std::list< std::pair< std::string, int > > texts; //list<text to show, time of add>
std::list< std::pair< std::string, Uint32 > > texts; //list<text to show, time of add>
boost::mutex texts_mx; // protects texts
std::vector< std::string > previouslyEntered; //previously entered texts, for up/down arrows to work
int prevEntDisp; //displayed entry from previouslyEntered - if none it's -1

View File

@ -45,7 +45,7 @@ void CButton::update()
newPos = 0;
if (state == HIGHLIGHTED && image->size() < 4)
newPos = image->size()-1;
newPos = (int)image->size()-1;
image->setFrame(newPos);
if (active)
@ -474,7 +474,7 @@ CVolumeSlider::CVolumeSlider(const Point & position, const std::string & defName
animImage = std::make_shared<CAnimImage>(std::make_shared<CAnimation>(defName), 0, 0, position.x, position.y),
pos.x += position.x;
pos.y += position.y;
pos.w = (animImage->pos.w + 1) * animImage->size();
pos.w = (animImage->pos.w + 1) * (int)animImage->size();
pos.h = animImage->pos.h;
type |= REDRAW_PARENT;
setVolume(value);
@ -483,7 +483,7 @@ CVolumeSlider::CVolumeSlider(const Point & position, const std::string & defName
void CVolumeSlider::setVolume(int value_)
{
value = value_;
moveTo(value * static_cast<double>(animImage->size()) / 100.0);
moveTo((int)(value * static_cast<double>(animImage->size()) / 100.0));
}
void CVolumeSlider::moveTo(int id)
@ -507,7 +507,7 @@ void CVolumeSlider::clickLeft(tribool down, bool previousState)
double px = GH.current->motion.x - pos.x;
double rx = px / static_cast<double>(pos.w);
// setVolume is out of 100
setVolume(rx * 100);
setVolume((int)(rx * 100));
// Volume config is out of 100, set to increments of 5ish roughly based on the half point of the indicator
// 0.0 -> 0, 0.05 -> 5, 0.09 -> 5,...,
// 0.1 -> 10, ..., 0.19 -> 15, 0.2 -> 20, ...,
@ -524,7 +524,7 @@ void CVolumeSlider::clickRight(tribool down, bool previousState)
if (down)
{
double px = GH.current->motion.x - pos.x;
int index = px / static_cast<double>(pos.w) * animImage->size();
int index = static_cast<int>(px / static_cast<double>(pos.w) * animImage->size());
std::string hoverText = helpHandlers[index].first;
std::string helpBox = helpHandlers[index].second;
if(!helpBox.empty())
@ -573,7 +573,7 @@ void CSlider::mouseMoved (const SDL_MouseMotionEvent & sEvent)
v += 0.5;
if(v!=value)
{
moveTo(v);
moveTo((int)v);
}
}
@ -615,7 +615,7 @@ void CSlider::updateSliderPos()
{
double part = static_cast<double>(value) / positions;
part*=(pos.w-48);
int newPos = part + pos.x + 16 - slider->pos.x;
int newPos = static_cast<int>(part + pos.x + 16 - slider->pos.x);
slider->moveBy(Point(newPos, 0));
}
else
@ -627,7 +627,7 @@ void CSlider::updateSliderPos()
{
double part = static_cast<double>(value) / positions;
part*=(pos.h-48);
int newPos = part + pos.y + 16 - slider->pos.y;
int newPos = static_cast<int>(part + pos.y + 16 - slider->pos.y);
slider->moveBy(Point(0, newPos));
}
else
@ -671,7 +671,7 @@ void CSlider::clickLeft(tribool down, bool previousState)
// if (rw>1) return;
// if (rw<0) return;
slider->clickLeft(true, slider->mouseState(EIntObjMouseBtnType::LEFT));
moveTo(rw * positions + 0.5);
moveTo((int)(rw * positions + 0.5));
return;
}
if(active & MOVE)

View File

@ -178,7 +178,7 @@ void CHeroArtPlace::clickLeft(tribool down, bool previousState)
{
setMeAsDest();
vstd::amin(ourOwner->commonInfo->dst.slotID, ArtifactPosition(
ourOwner->curHero->artifactsInBackpack.size() + GameConstants::BACKPACK_START));
(si32)ourOwner->curHero->artifactsInBackpack.size() + GameConstants::BACKPACK_START));
if(srcInBackpack && srcInSameHero)
{
if(!ourArt //cannot move from backpack to AFTER backpack -> combined with vstd::amin above it will guarantee that dest is at most the last artifact
@ -449,7 +449,7 @@ void CArtifactsOfHero::dispose()
void CArtifactsOfHero::scrollBackpack(int dir)
{
int artsInBackpack = curHero->artifactsInBackpack.size();
int artsInBackpack = static_cast<int>(curHero->artifactsInBackpack.size());
backpackPos += dir;
if(backpackPos < 0)// No guarantee of modulus behavior with negative operands -> we keep it positive
backpackPos += artsInBackpack;
@ -487,7 +487,7 @@ void CArtifactsOfHero::scrollBackpack(int dir)
}
}
for( ; s - omitedSoFar < backpack.size(); s++)
eraseSlotData(backpack[s-omitedSoFar], ArtifactPosition(GameConstants::BACKPACK_START + s));
eraseSlotData(backpack[s-omitedSoFar], ArtifactPosition(GameConstants::BACKPACK_START + (si32)s));
//in artifact merchant selling artifacts we may have highlight on one of backpack artifacts -> market needs update, cause artifact under highlight changed
if(highlightModeCallback)
@ -613,7 +613,7 @@ CArtifactsOfHero::CArtifactsOfHero(ArtPlaceMap ArtWorn, std::vector<ArtPlacePtr>
for(size_t s=0; s<backpack.size(); ++s)
{
backpack[s]->ourOwner = this;
eraseSlotData(backpack[s], ArtifactPosition(GameConstants::BACKPACK_START + s));
eraseSlotData(backpack[s], ArtifactPosition(GameConstants::BACKPACK_START + (si32)s));
}
leftArtRoll->addCallback(std::bind(&CArtifactsOfHero::scrollBackpack, this,-1));
@ -649,7 +649,7 @@ CArtifactsOfHero::CArtifactsOfHero(const Point & position, bool createCommonPart
};
// Create slots for worn artifacts.
for(size_t g = 0; g < GameConstants::BACKPACK_START; g++)
for(si32 g = 0; g < GameConstants::BACKPACK_START; g++)
{
artWorn[ArtifactPosition(g)] = std::make_shared<CHeroArtPlace>(slotPos[g]);
artWorn[ArtifactPosition(g)]->ourOwner = this;
@ -657,7 +657,7 @@ CArtifactsOfHero::CArtifactsOfHero(const Point & position, bool createCommonPart
}
// Create slots for the backpack.
for(size_t s=0; s<5; ++s)
for(int s=0; s<5; ++s)
{
auto add = std::make_shared<CHeroArtPlace>(Point(403 + 46 * s, 365));

View File

@ -56,7 +56,7 @@ void CComponent::init(Etype Type, int Subtype, int Val, ESize imageSize)
assert(compType < typeInvalid);
assert(size < sizeInvalid);
setSurface(getFileName()[size], getIndex());
setSurface(getFileName()[size], (int)getIndex());
pos.w = image->pos.w;
pos.h = image->pos.h;
@ -70,7 +70,7 @@ void CComponent::init(Etype Type, int Subtype, int Val, ESize imageSize)
std::vector<std::string> textLines = CMessage::breakText(getSubtitle(), std::max<int>(80, pos.w), font);
for(auto & line : textLines)
{
int height = graphics->fonts[font]->getLineHeight();
int height = static_cast<int>(graphics->fonts[font]->getLineHeight());
auto label = std::make_shared<CLabel>(pos.w/2, pos.h + height/2, font, CENTER, Colors::WHITE, line);
pos.h += height;
@ -307,7 +307,7 @@ void CComponentBox::selectionChanged(std::shared_ptr<CSelectableComponent> newSe
int CComponentBox::selectedIndex()
{
if (selected)
return std::find(components.begin(), components.end(), selected) - components.begin();
return static_cast<int>(std::find(components.begin(), components.end(), selected) - components.begin());
return -1;
}
@ -392,7 +392,7 @@ void CComponentBox::placeComponents(bool selectable)
vstd::amax(pos.w, row.width);
}
int height = (rows.size() - 1) * betweenRows;
int height = ((int)rows.size() - 1) * betweenRows;
for(auto & row : rows)
height += row.height;
@ -407,7 +407,7 @@ void CComponentBox::placeComponents(bool selectable)
for (auto & rows_row : rows)
{
// amount of free space we may add on each side of every component
int freeSpace = (pos.w - rows_row.width) / (rows_row.comps * 2);
int freeSpace = (pos.w - rows_row.width) / ((int)rows_row.comps * 2);
prevComp = nullptr;
int currentX = 0;

View File

@ -441,7 +441,7 @@ void CCreatureAnim::loopPreview(bool warMachine)
if (anim->size(elem))
available.push_back(elem);
size_t rnd = CRandomGenerator::getDefault().nextInt(available.size() * 2 - 1);
size_t rnd = CRandomGenerator::getDefault().nextInt((int)available.size() * 2 - 1);
if (rnd >= available.size())
{

View File

@ -282,7 +282,7 @@ void CHeroTooltip::init(const InfoAboutHero & hero)
if(hero.details)
{
for(size_t i = 0; i < hero.details->primskills.size(); i++)
labels.push_back(std::make_shared<CLabel>(75 + 28 * i, 58, FONT_SMALL, CENTER, Colors::WHITE,
labels.push_back(std::make_shared<CLabel>(75 + 28 * (int)i, 58, FONT_SMALL, CENTER, Colors::WHITE,
boost::lexical_cast<std::string>(hero.details->primskills[i])));
labels.push_back(std::make_shared<CLabel>(158, 98, FONT_TINY, CENTER, Colors::WHITE, boost::lexical_cast<std::string>(hero.details->mana)));

View File

@ -87,7 +87,7 @@ CListBox::CListBox(CreateFunc create, Point Pos, Point ItemOffset, size_t Visibl
{
OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
slider = std::make_shared<CSlider>(SliderPos.topLeft(), SliderPos.w, std::bind(&CListBox::moveToPos, this, _1),
VisibleSize, TotalSize, InitialPos, Slider & 2, Slider & 4 ? CSlider::BLUE : CSlider::BROWN);
(int)VisibleSize, (int)TotalSize, (int)InitialPos, Slider & 2, Slider & 4 ? CSlider::BLUE : CSlider::BROWN);
}
reset();
}
@ -105,7 +105,7 @@ void CListBox::updatePositions()
{
redraw();
if (slider)
slider->moveTo(first);
slider->moveTo((int)first);
}
}
@ -124,7 +124,7 @@ void CListBox::resize(size_t newSize)
{
totalSize = newSize;
if (slider)
slider->setAmount(totalSize);
slider->setAmount((int)totalSize);
reset();
}

View File

@ -47,8 +47,8 @@ CLabel::CLabel(int x, int y, EFonts Font, EAlignment Align, const SDL_Color & Co
if(alignment == TOPLEFT) // causes issues for MIDDLE
{
pos.w = graphics->fonts[font]->getStringWidth(visibleText().c_str());
pos.h = graphics->fonts[font]->getLineHeight();
pos.w = (int)graphics->fonts[font]->getStringWidth(visibleText().c_str());
pos.h = (int)graphics->fonts[font]->getLineHeight();
}
}
@ -151,8 +151,8 @@ void CTextContainer::blitLine(SDL_Surface *to, Rect destRect, std::string what)
if (alignment == BOTTOMRIGHT)
{
where.x += getBorderSize().x + destRect.w - f->getStringWidth(what);
where.y += getBorderSize().y + destRect.h - f->getLineHeight();
where.x += getBorderSize().x + destRect.w - (int)f->getStringWidth(what);
where.y += getBorderSize().y + destRect.h - (int)f->getLineHeight();
}
size_t begin = 0;
@ -172,7 +172,7 @@ void CTextContainer::blitLine(SDL_Surface *to, Rect destRect, std::string what)
f->renderTextLeft(to, toPrint, color, where);
begin = end;
where.x += f->getStringWidth(toPrint);
where.x += (int)f->getStringWidth(toPrint);
}
currDelimeter++;
}
@ -192,24 +192,24 @@ void CMultiLineLabel::showAll(SDL_Surface * to)
const auto f = graphics->fonts[font];
// calculate which lines should be visible
int totalLines = lines.size();
int totalLines = static_cast<int>(lines.size());
int beginLine = visibleSize.y;
int endLine = getTextLocation().h + visibleSize.y;
if (beginLine < 0)
beginLine = 0;
else
beginLine /= f->getLineHeight();
beginLine /= (int)f->getLineHeight();
if (endLine < 0)
endLine = 0;
else
endLine /= f->getLineHeight();
endLine /= (int)f->getLineHeight();
endLine++;
// and where they should be displayed
Point lineStart = getTextLocation().topLeft() - visibleSize + Point(0, beginLine * f->getLineHeight());
Point lineSize = Point(getTextLocation().w, f->getLineHeight());
Point lineStart = getTextLocation().topLeft() - visibleSize + Point(0, beginLine * (int)f->getLineHeight());
Point lineSize = Point(getTextLocation().w, (int)f->getLineHeight());
CSDL_Ext::CClipRectGuard guard(to, getTextLocation()); // to properly trim text that is too big to fit
@ -218,7 +218,7 @@ void CMultiLineLabel::showAll(SDL_Surface * to)
if (!lines[i].empty()) //non-empty line
blitLine(to, Rect(lineStart, lineSize), lines[i]);
lineStart.y += f->getLineHeight();
lineStart.y += (int)f->getLineHeight();
}
}
@ -227,11 +227,11 @@ void CMultiLineLabel::splitText(const std::string &Txt, bool redrawAfter)
lines.clear();
const auto f = graphics->fonts[font];
int lineHeight = f->getLineHeight();
int lineHeight = static_cast<int>(f->getLineHeight());
lines = CMessage::breakText(Txt, pos.w, font);
textSize.y = lineHeight * lines.size();
textSize.y = lineHeight * (int)lines.size();
textSize.x = 0;
for(const std::string &line : lines)
vstd::amax( textSize.x, f->getStringWidth(line.c_str()));
@ -247,7 +247,7 @@ Rect CMultiLineLabel::getTextLocation()
if (pos.h <= textSize.y)
return pos;
Point textSize(pos.w, graphics->fonts[font]->getLineHeight() * lines.size());
Point textSize(pos.w, (int)graphics->fonts[font]->getLineHeight() * (int)lines.size());
Point textOffset(pos.w - textSize.x, pos.h - textSize.y);
switch(alignment)
@ -335,7 +335,7 @@ void CTextBox::setText(const std::string &text)
OBJECT_CONSTRUCTION_CUSTOM_CAPTURING(255-DISPOSE);
slider = std::make_shared<CSlider>(Point(pos.w - 32, 0), pos.h, std::bind(&CTextBox::sliderMoved, this, _1),
label->pos.h, label->textSize.y, 0, false, CSlider::EStyle(sliderStyle));
slider->setScrollStep(graphics->fonts[label->font]->getLineHeight());
slider->setScrollStep((int)graphics->fonts[label->font]->getLineHeight());
}
}
@ -367,7 +367,7 @@ CGStatusBar::CGStatusBar(int x, int y, std::string name, int maxw)
OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
background = std::make_shared<CPicture>(name);
pos = background->pos;
if((unsigned int)maxw < pos.w)
if(maxw < pos.w)
{
vstd::amin(pos.w, maxw);
background->srcRect = new Rect(0, 0, maxw, pos.h);

View File

@ -448,7 +448,7 @@ int3 CTerrainRect::tileCountOnScreen()
case EAdvMapMode::NORMAL:
return int3(tilesw, tilesh, 1);
case EAdvMapMode::WORLD_VIEW:
return int3(tilesw / adventureInt->worldViewScale, tilesh / adventureInt->worldViewScale, 1);
return int3((si32)(tilesw / adventureInt->worldViewScale), (si32)(tilesh / adventureInt->worldViewScale), 1);
}
}
@ -1089,7 +1089,7 @@ void CAdvMapInt::show(SDL_Surface * to)
void CAdvMapInt::handleMapScrollingUpdate()
{
int scrollSpeed = settings["adventure"]["scrollSpeed"].Float();
int scrollSpeed = static_cast<int>(settings["adventure"]["scrollSpeed"].Float());
//if advmap needs updating AND (no dialog is shown OR ctrl is pressed)
if((animValHitCount % (4 / scrollSpeed)) == 0
&& ((GH.topInt().get() == this) || isCtrlKeyDown()))
@ -1161,8 +1161,8 @@ void CAdvMapInt::centerOn(int3 on, bool fade)
on.y -= CGI->mh->frameH;
break;
case EAdvMapMode::WORLD_VIEW:
on.x -= CGI->mh->tilesW / 2 / worldViewScale;
on.y -= CGI->mh->tilesH / 2 / worldViewScale;
on.x -= static_cast<si32>(CGI->mh->tilesW / 2 / worldViewScale);
on.y -= static_cast<si32>(CGI->mh->tilesH / 2 / worldViewScale);
break;
}

View File

@ -140,10 +140,10 @@ void CBuildingRect::clickRight(tribool down, bool previousState)
SDL_Color multiplyColors(const SDL_Color & b, const SDL_Color & a, double f)
{
SDL_Color ret;
ret.r = a.r*f + b.r*(1-f);
ret.g = a.g*f + b.g*(1-f);
ret.b = a.b*f + b.b*(1-f);
ret.a = a.a*f + b.b*(1-f);
ret.r = static_cast<Uint8>(a.r * f + b.r * (1 - f));
ret.g = static_cast<Uint8>(a.g * f + b.g * (1 - f));
ret.b = static_cast<Uint8>(a.b * f + b.b * (1 - f));
ret.a = static_cast<Uint8>(a.a * f + b.b * (1 - f));
return ret;
}
@ -287,7 +287,7 @@ CDwellingInfoBox::CDwellingInfoBox(int centerX, int centerY, const CGTownInstanc
}
int posY = 238;
int posX = pos.w/2 - resAmount.size() * 25 + 5;
int posX = pos.w/2 - (int)resAmount.size() * 25 + 5;
for (size_t i=0; i<resAmount.size(); i++)
{
resPicture[i]->moveBy(Point(posX, posY));
@ -1223,10 +1223,10 @@ void CCastleInterface::recreateIcons()
creainfo.clear();
for(size_t i=0; i<4; i++)
creainfo.push_back(std::make_shared<CCreaInfo>(Point(14+55*i, 459), town, i));
creainfo.push_back(std::make_shared<CCreaInfo>(Point(14+55*(int)i, 459), town, (int)i));
for(size_t i=0; i<4; i++)
creainfo.push_back(std::make_shared<CCreaInfo>(Point(14+55*i, 507), town, i+4));
creainfo.push_back(std::make_shared<CCreaInfo>(Point(14+55*(int)i, 507), town, (int)i+4));
}
void CCastleInterface::keyPressed(const SDL_KeyboardEvent & key)
@ -1358,8 +1358,8 @@ CHallInterface::CHallInterface(const CGTownInstance * Town):
}
}
}
int posX = pos.w/2 - boxList[row].size()*154/2 - (boxList[row].size()-1)*20 + 194*col,
posY = 35 + 104*row;
int posX = pos.w/2 - (int)boxList[row].size()*154/2 - ((int)boxList[row].size()-1)*20 + 194*(int)col,
posY = 35 + 104*(int)row;
if(building)
boxes[row].push_back(std::make_shared<CBuildingBox>(posX, posY, town, building));
@ -1500,7 +1500,7 @@ CFortScreen::CFortScreen(const CGTownInstance * town):
CStatusbarWindow(PLAYER_COLORED | BORDERED, getBgName(town))
{
OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
ui32 fortSize = town->creatures.size();
ui32 fortSize = static_cast<ui32>(town->creatures.size());
if(fortSize > GameConstants::CREATURES_PER_TOWN && town->creatures.back().second.empty())
fortSize--;
@ -1557,7 +1557,7 @@ CFortScreen::CFortScreen(const CGTownInstance * town):
std::string CFortScreen::getBgName(const CGTownInstance * town)
{
ui32 fortSize = town->creatures.size();
ui32 fortSize = static_cast<ui32>(town->creatures.size());
if(fortSize > GameConstants::CREATURES_PER_TOWN && town->creatures.back().second.empty())
fortSize--;
@ -1709,7 +1709,7 @@ CMageGuildScreen::CMageGuildScreen(CCastleInterface * owner,std::string imagem)
for(size_t i=0; i<owner->town->town->mageLevel; i++)
{
size_t spellCount = owner->town->spellsAtLevel(i+1,false); //spell at level with -1 hmmm?
size_t spellCount = owner->town->spellsAtLevel((int)i+1,false); //spell at level with -1 hmmm?
for(size_t j=0; j<spellCount; j++)
{
if(i<owner->town->mageGuildLevel() && owner->town->spells[i].size()>j)

View File

@ -255,7 +255,7 @@ CStackWindow::BonusesSection::BonusesSection(CStackWindow * owner, int yOffset,
size_t visibleSize = preferredSize ? preferredSize.get() : std::min<size_t>(3, totalSize);
pos.w = owner->pos.w;
pos.h = itemHeight * visibleSize;
pos.h = itemHeight * (int)visibleSize;
auto onCreate = [=](size_t index) -> std::shared_ptr<CIntObject>
{
@ -306,7 +306,7 @@ CStackWindow::ButtonsSection::ButtonsSection(CStackWindow * owner, int yOffset)
std::vector<std::shared_ptr<CComponent>> resComps;
for(TResources::nziterator i(totalCost); i.valid(); i++)
{
resComps.push_back(std::make_shared<CComponent>(CComponent::resource, i->resType, i->resVal));
resComps.push_back(std::make_shared<CComponent>(CComponent::resource, i->resType, (int)i->resVal));
}
if(LOCPLINT->cb->getResourceAmount().canAfford(totalCost))
@ -318,7 +318,7 @@ CStackWindow::ButtonsSection::ButtonsSection(CStackWindow * owner, int yOffset)
LOCPLINT->showInfoDialog(CGI->generaltexth->allTexts[314], resComps);
}
};
auto upgradeBtn = std::make_shared<CButton>(Point(221 + buttonIndex * 40, 5), "stackWindow/upgradeButton", CGI->generaltexth->zelp[446], onClick, SDLK_1);
auto upgradeBtn = std::make_shared<CButton>(Point(221 + (int)buttonIndex * 40, 5), "stackWindow/upgradeButton", CGI->generaltexth->zelp[446], onClick, SDLK_1);
upgradeBtn->addOverlay(std::make_shared<CAnimImage>("CPRSMALL", VLC->creh->creatures[upgradeInfo.info.newID[buttonIndex]]->iconIndex));
@ -342,7 +342,7 @@ CStackWindow::ButtonsSection::ButtonsSection(CStackWindow * owner, int yOffset)
};
const JsonNode & text = VLC->generaltexth->localizedTexts["creatureWindow"][btnIDs[buttonIndex]];
parent->switchButtons[buttonIndex] = std::make_shared<CButton>(Point(302 + buttonIndex*40, 5), "stackWindow/upgradeButton", CButton::tooltip(text), onSwitch);
parent->switchButtons[buttonIndex] = std::make_shared<CButton>(Point(302 + (int)buttonIndex*40, 5), "stackWindow/upgradeButton", CButton::tooltip(text), onSwitch);
parent->switchButtons[buttonIndex]->addOverlay(std::make_shared<CAnimImage>("stackWindow/switchModeIcons", buttonIndex));
}
parent->switchButtons[parent->activeTab]->disable();
@ -426,7 +426,7 @@ CStackWindow::CommanderMainSection::CommanderMainSection(CStackWindow * owner, i
return skillID >= 100;
});
auto onCreate = [=](int index)->std::shared_ptr<CIntObject>
auto onCreate = [=](size_t index)->std::shared_ptr<CIntObject>
{
for(auto skillID : parent->info->levelupInfo->skills)
{
@ -867,7 +867,7 @@ std::string CStackWindow::generateStackExpDescription()
boost::replace_first(expText, "%s", CGI->generaltexth->zcrexp[rank]);
boost::replace_first(expText, "%i", boost::lexical_cast<std::string>(rank));
boost::replace_first(expText, "%i", boost::lexical_cast<std::string>(stack->experience));
number = CGI->creh->expRanks[tier][rank] - stack->experience;
number = static_cast<int>(CGI->creh->expRanks[tier][rank] - stack->experience);
boost::replace_first(expText, "%i", boost::lexical_cast<std::string>(number));
number = CGI->creh->maxExpPerBattle[tier]; //percent
@ -878,7 +878,7 @@ std::string CStackWindow::generateStackExpDescription()
boost::replace_first(expText, "%i", boost::lexical_cast<std::string>(stack->count)); //Number of Creatures in stack
int expmin = std::max(CGI->creh->expRanks[tier][std::max(rank-1, 0)], (ui32)1);
number = (stack->count * (stack->experience - expmin)) / expmin; //Maximum New Recruits without losing current Rank
number = static_cast<int>((stack->count * (stack->experience - expmin)) / expmin); //Maximum New Recruits without losing current Rank
boost::replace_first(expText, "%i", boost::lexical_cast<std::string>(number)); //TODO
boost::replace_first(expText, "%.2f", boost::lexical_cast<std::string>(1)); //TODO Experience Multiplier

View File

@ -49,6 +49,7 @@ class CStackWindow : public CWindowObject
class CWindowSection : public CIntObject
{
std::shared_ptr<CIntObject> onCreate(int index);
private:
std::shared_ptr<CPicture> background;
protected:

View File

@ -260,7 +260,7 @@ void InfoBoxAbstractHeroData::prepareMessage(std::string & text, std::shared_ptr
break;
case HERO_PRIMARY_SKILL:
text = CGI->generaltexth->arraytxt[2+getSubID()];
comp = std::make_shared<CComponent>(CComponent::primskill, getSubID(), getValue());
comp = std::make_shared<CComponent>(CComponent::primskill, getSubID(), (int)getValue());
break;
case HERO_MANA:
text = CGI->generaltexth->allTexts[149];
@ -274,8 +274,8 @@ void InfoBoxAbstractHeroData::prepareMessage(std::string & text, std::shared_ptr
int subID = getSubID();
if(value)
{
text = CGI->skillh->skillInfo(subID, value);
comp = std::make_shared<CComponent>(CComponent::secskill, subID, value);
text = CGI->skillh->skillInfo(subID, (int)value);
comp = std::make_shared<CComponent>(CComponent::secskill, subID, (int)value);
}
break;
}
@ -704,7 +704,7 @@ std::shared_ptr<CIntObject> CKingdHeroList::createHeroItem(size_t index)
if(index < heroesCount)
{
auto hero = std::make_shared<CHeroItem>(LOCPLINT->cb->getHeroBySerial(index, false));
auto hero = std::make_shared<CHeroItem>(LOCPLINT->cb->getHeroBySerial((int)index, false));
addSet(hero->heroArts);
return hero;
}
@ -754,7 +754,7 @@ std::shared_ptr<CIntObject> CKingdTownList::createTownItem(size_t index)
size_t townsCount = LOCPLINT->cb->howManyTowns();
if(index < townsCount)
return std::make_shared<CTownItem>(LOCPLINT->cb->getTownBySerial(index));
return std::make_shared<CTownItem>(LOCPLINT->cb->getTownBySerial((int)index));
else
return std::make_shared<CAnimImage>("OVSLOT", (index-2) % picCount );
}
@ -780,8 +780,8 @@ CTownItem::CTownItem(const CGTownInstance * Town)
for(size_t i=0; i<town->creatures.size(); i++)
{
growth.push_back(std::make_shared<CCreaInfo>(Point(401+37*i, 78), town, i, true, true));
available.push_back(std::make_shared<CCreaInfo>(Point(48+37*i, 78), town, i, true, false));
growth.push_back(std::make_shared<CCreaInfo>(Point(401+37*(int)i, 78), town, (int)i, true, true));
available.push_back(std::make_shared<CCreaInfo>(Point(48+37*(int)i, 78), town, (int)i, true, false));
}
}
@ -819,7 +819,7 @@ public:
OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
background = std::make_shared<CAnimImage>("OVSLOT", 4);
pos = background->pos;
for(size_t i=0; i<9; i++)
for(int i=0; i<9; i++)
arts.push_back(std::make_shared<CHeroArtPlace>(Point(270+i*48, 65)));
}
};
@ -839,7 +839,7 @@ public:
pos = background->pos;
btnLeft = std::make_shared<CButton>(Point(269, 66), "HSBTNS3", CButton::tooltip(), 0);
btnRight = std::make_shared<CButton>(Point(675, 66), "HSBTNS5", CButton::tooltip(), 0);
for(size_t i=0; i<8; i++)
for(int i=0; i<8; i++)
arts.push_back(std::make_shared<CHeroArtPlace>(Point(295+i*48, 65)));
}
};
@ -903,9 +903,9 @@ CHeroItem::CHeroItem(const CGHeroInstance * Hero)
std::string hover = CGI->generaltexth->overview[13+it];
std::string overlay = CGI->generaltexth->overview[8+it];
auto button = std::make_shared<CToggleButton>(Point(364+it*112, 46), "OVBUTN3", CButton::tooltip(hover, overlay), 0);
auto button = std::make_shared<CToggleButton>(Point(364+(int)it*112, 46), "OVBUTN3", CButton::tooltip(hover, overlay), 0);
button->addTextOverlay(CGI->generaltexth->allTexts[stringID[it]], FONT_SMALL, Colors::YELLOW);
artButtons->addToggle(it, button);
artButtons->addToggle((int)it, button);
}
artButtons->addCallback(std::bind(&CTabbedInt::setActive, artsTabs, _1));
artButtons->addCallback(std::bind(&CHeroItem::onArtChange, this, _1));
@ -921,14 +921,14 @@ CHeroItem::CHeroItem(const CGHeroInstance * Hero)
for(size_t i=0; i<GameConstants::PRIMARY_SKILLS; i++)
{
auto data = std::make_shared<InfoBoxHeroData>(IInfoBoxData::HERO_PRIMARY_SKILL, hero, i);
heroInfo.push_back(std::make_shared<InfoBox>(Point(78+i*36, 26), InfoBox::POS_DOWN, InfoBox::SIZE_SMALL, data));
auto data = std::make_shared<InfoBoxHeroData>(IInfoBoxData::HERO_PRIMARY_SKILL, hero, (int)i);
heroInfo.push_back(std::make_shared<InfoBox>(Point(78+(int)i*36, 26), InfoBox::POS_DOWN, InfoBox::SIZE_SMALL, data));
}
for(size_t i=0; i<GameConstants::SKILL_PER_HERO; i++)
{
auto data = std::make_shared<InfoBoxHeroData>(IInfoBoxData::HERO_SECONDARY_SKILL, hero, i);
heroInfo.push_back(std::make_shared<InfoBox>(Point(410+i*36, 5), InfoBox::POS_NONE, InfoBox::SIZE_SMALL, data));
auto data = std::make_shared<InfoBoxHeroData>(IInfoBoxData::HERO_SECONDARY_SKILL, hero, (int)i);
heroInfo.push_back(std::make_shared<InfoBox>(Point(410+(int)i*36, 5), InfoBox::POS_NONE, InfoBox::SIZE_SMALL, data));
}
{

View File

@ -181,7 +181,7 @@ void CQuestLog::recreateLabelList()
if (quests[i].quest->progress != CQuest::COMPLETE)
selectQuest(i, currentLabel);
currentLabel = labels.size();
currentLabel = static_cast<int>(labels.size());
}
if (completeMissing) // We can't use block(completeMissing) because if false button state reset to NORMAL
@ -241,7 +241,7 @@ void CQuestLog::selectQuest(int which, int labelId)
componentsBox.reset();
int componentsSize = components.size();
int componentsSize = static_cast<int>(components.size());
int descriptionHeight = DESCRIPTION_HEIGHT_MAX;
if(componentsSize)
{

View File

@ -408,7 +408,7 @@ void CTradeWindow::initItems(bool Left)
if(Left || !ids)
amount = 7;
else
amount = ids->size();
amount = static_cast<int>(ids->size());
if(ids)
vstd::amin(amount, ids->size());
@ -486,8 +486,8 @@ void CTradeWindow::getPositionsFor(std::vector<Rect> &poss, bool Left, EType typ
for (int j = 0; j < 5 ; j++)
poss.push_back(Rect(x + dx*j, y + dy*i, w, h));
poss.push_back(Rect(x + dx*1.5, y + dy*4, w, h));
poss.push_back(Rect(x + dx*2.5, y + dy*4, w, h));
poss.push_back(Rect((int)(x + dx * 1.5), (y + dy * 4), w, h));
poss.push_back(Rect((int)(x + dx * 2.5), (y + dy * 4), w, h));
}
else
{
@ -1397,7 +1397,7 @@ void CAltarWindow::calcTotalExp()
val += valOfArt; //WAS val += valOfArt * arts->artifactsOnAltar.count(*i);
}
}
val = hero->calculateXp(val);
val = static_cast<int>(hero->calculateXp(val));
expOnAltar->setText(boost::lexical_cast<std::string>(val));
}
@ -1467,7 +1467,7 @@ void CAltarWindow::showAll(SDL_Surface * to)
int dmp, val;
market->getOffer(arts->commonInfo->src.art->artType->id, 0, dmp, val, EMarketMode::ARTIFACT_EXP);
val = hero->calculateXp(val);
val = static_cast<int>(hero->calculateXp(val));
printAtMiddleLoc(boost::lexical_cast<std::string>(val), 304, 498, FONT_SMALL, Colors::WHITE, to);
}
}
@ -1493,7 +1493,7 @@ bool CAltarWindow::putOnAltar(std::shared_ptr<CTradeableItem> altarSlot, const C
int dmp, val;
market->getOffer(art->artType->id, 0, dmp, val, EMarketMode::ARTIFACT_EXP);
val = hero->calculateXp(val);
val = static_cast<int>(hero->calculateXp(val));
arts->artifactsOnAltar.insert(art);
altarSlot->setArtInstance(art);
@ -1505,7 +1505,7 @@ bool CAltarWindow::putOnAltar(std::shared_ptr<CTradeableItem> altarSlot, const C
void CAltarWindow::moveFromSlotToAltar(ArtifactPosition slotID, std::shared_ptr<CTradeableItem> altarSlot, const CArtifactInstance *art)
{
auto freeBackpackSlot = ArtifactPosition(hero->artifactsInBackpack.size() + GameConstants::BACKPACK_START);
auto freeBackpackSlot = ArtifactPosition((si32)hero->artifactsInBackpack.size() + GameConstants::BACKPACK_START);
if(arts->commonInfo->src.art)
{
arts->commonInfo->dst.slotID = freeBackpackSlot;

View File

@ -257,10 +257,10 @@ void CRecruitmentWindow::availableCreaturesChanged()
//normal distance between cards - 18px
int requiredSpace = 18;
//maximum distance we can use without reaching window borders
int availableSpace = pos.w - 50 - creatureWidth * cards.size();
int availableSpace = pos.w - 50 - creatureWidth * (int)cards.size();
if (cards.size() > 1) // avoid division by zero
availableSpace /= cards.size() - 1;
availableSpace /= (int)cards.size() - 1;
else
availableSpace = 0;
@ -270,7 +270,7 @@ void CRecruitmentWindow::availableCreaturesChanged()
const int totalCreatureWidth = spaceBetween + creatureWidth;
//now we know total amount of cards and can move them to correct position
int curx = pos.w / 2 - (creatureWidth*cards.size()/2) - (spaceBetween*(cards.size()-1)/2);
int curx = pos.w / 2 - (creatureWidth*(int)cards.size()/2) - (spaceBetween*((int)cards.size()-1)/2);
for(auto & card : cards)
{
card->moveBy(Point(curx, 64));
@ -500,20 +500,20 @@ CSystemOptionsWindow::CSystemOptionsWindow()
heroMoveSpeed->addToggle(2, std::make_shared<CToggleButton>(Point( 76, 77), "sysopb2.def", CGI->generaltexth->zelp[350]));
heroMoveSpeed->addToggle(4, std::make_shared<CToggleButton>(Point(124, 77), "sysopb3.def", CGI->generaltexth->zelp[351]));
heroMoveSpeed->addToggle(8, std::make_shared<CToggleButton>(Point(172, 77), "sysopb4.def", CGI->generaltexth->zelp[352]));
heroMoveSpeed->setSelected(settings["adventure"]["heroSpeed"].Float());
heroMoveSpeed->setSelected((int)settings["adventure"]["heroSpeed"].Float());
heroMoveSpeed->addCallback(std::bind(&setIntSetting, "adventure", "heroSpeed", _1));
enemyMoveSpeed->addToggle(2, std::make_shared<CToggleButton>(Point( 28, 144), "sysopb5.def", CGI->generaltexth->zelp[353]));
enemyMoveSpeed->addToggle(4, std::make_shared<CToggleButton>(Point( 76, 144), "sysopb6.def", CGI->generaltexth->zelp[354]));
enemyMoveSpeed->addToggle(8, std::make_shared<CToggleButton>(Point(124, 144), "sysopb7.def", CGI->generaltexth->zelp[355]));
enemyMoveSpeed->addToggle(0, std::make_shared<CToggleButton>(Point(172, 144), "sysopb8.def", CGI->generaltexth->zelp[356]));
enemyMoveSpeed->setSelected(settings["adventure"]["enemySpeed"].Float());
enemyMoveSpeed->setSelected((int)settings["adventure"]["enemySpeed"].Float());
enemyMoveSpeed->addCallback(std::bind(&setIntSetting, "adventure", "enemySpeed", _1));
mapScrollSpeed->addToggle(1, std::make_shared<CToggleButton>(Point( 28, 210), "sysopb9.def", CGI->generaltexth->zelp[357]));
mapScrollSpeed->addToggle(2, std::make_shared<CToggleButton>(Point( 92, 210), "sysob10.def", CGI->generaltexth->zelp[358]));
mapScrollSpeed->addToggle(4, std::make_shared<CToggleButton>(Point(156, 210), "sysob11.def", CGI->generaltexth->zelp[359]));
mapScrollSpeed->setSelected(settings["adventure"]["scrollSpeed"].Float());
mapScrollSpeed->setSelected((int)settings["adventure"]["scrollSpeed"].Float());
mapScrollSpeed->addCallback(std::bind(&setIntSetting, "adventure", "scrollSpeed", _1));
musicVolume = std::make_shared<CVolumeSlider>(Point(29, 359), "syslb.def", CCS->musich->getVolume(), &CGI->generaltexth->zelp[326]);
@ -763,7 +763,7 @@ CTavernWindow::HeroPortrait::HeroPortrait(int & sel, int id, int x, int y, const
hoverName = CGI->generaltexth->tavernInfo[4];
boost::algorithm::replace_first(hoverName,"%s",H->name);
int artifs = h->artifactsWorn.size() + h->artifactsInBackpack.size();
int artifs = (int)h->artifactsWorn.size() + (int)h->artifactsInBackpack.size();
for(int i=13; i<=17; i++) //war machines and spellbook don't count
if(vstd::contains(h->artifactsWorn, ArtifactPosition(i)))
artifs--;
@ -1484,7 +1484,7 @@ void CHillFortWindow::updateGarrisons()
{
//reverse iterator is used to display gold as first element
int j = 0;
for(int res = costs[i].size()-1; (res >= 0) && (j < 2); res--)
for(int res = (int)costs[i].size()-1; (res >= 0) && (j < 2); res--)
{
int val = costs[i][res];
if(!val)
@ -1649,11 +1649,11 @@ CThievesGuildWindow::CThievesGuildWindow(const CGObjectInstance * _owner):
{
// origin of this row | offset for 2nd row| shift right for short rows
//if we have 2 rows, start either from mid or beginning (depending on count), otherwise center the flags
int rowStartX = xpos + (j ? 6 + (rowLength[j] < 3 ? 12 : 0) : 24 - 6 * rowLength[j]);
int rowStartX = xpos + (j ? 6 + ((int)rowLength[j] < 3 ? 12 : 0) : 24 - 6 * (int)rowLength[j]);
int rowStartY = ypos + (j ? 4 : 0);
for(size_t i=0; i < rowLength[j]; i++)
cells.push_back(std::make_shared<CAnimImage>(itgflags, players[i + j*4].getNum(), 0, rowStartX + i*12, rowStartY));
cells.push_back(std::make_shared<CAnimImage>(itgflags, players[i + j*4].getNum(), 0, rowStartX + (int)i*12, rowStartY));
}
}
}
@ -1847,7 +1847,7 @@ void CObjectListWindow::keyPressed (const SDL_KeyboardEvent & key)
if(key.state != SDL_PRESSED)
return;
int sel = selected;
int sel = static_cast<int>(selected);
switch(key.keysym.sym)
{
@ -1867,7 +1867,7 @@ void CObjectListWindow::keyPressed (const SDL_KeyboardEvent & key)
sel = 0;
break; case SDLK_END:
sel = items.size();
sel = static_cast<int>(items.size());
break; default:
return;

View File

@ -253,7 +253,7 @@ bool CModFilterModel::filterAcceptsRow(int source_row, const QModelIndex & sourc
for(size_t i = 0; i < base->rowCount(index); i++)
{
if(filterMatchesThis(index.child(i, 0)))
if(filterMatchesThis(index.child((int)i, 0)))
return true;
}

View File

@ -95,7 +95,7 @@ void CSettingsView::loadSettings()
std::string encoding = settings["general"]["encoding"].String();
size_t encodingIndex = boost::range::find(knownEncodingsList, encoding) - knownEncodingsList;
if(encodingIndex < ui->comboBoxEncoding->count())
ui->comboBoxEncoding->setCurrentIndex(encodingIndex);
ui->comboBoxEncoding->setCurrentIndex((int)encodingIndex);
ui->comboBoxAutoSave->setCurrentIndex(settings["general"]["saveFrequency"].Integer() > 0 ? 1 : 0);
}

View File

@ -232,7 +232,7 @@ std::vector<JsonNode> CArtHandler::loadLegacyData(size_t dataSize)
void CArtHandler::loadObject(std::string scope, std::string name, const JsonNode & data)
{
auto object = loadFromJson(data, normalizeIdentifier(scope, "core", name));
object->id = ArtifactID(artifacts.size());
object->id = ArtifactID((si32)artifacts.size());
object->iconIndex = object->id + 5;
artifacts.push_back(object);
@ -265,7 +265,7 @@ void CArtHandler::loadObject(std::string scope, std::string name, const JsonNode
void CArtHandler::loadObject(std::string scope, std::string name, const JsonNode & data, size_t index)
{
auto object = loadFromJson(data, normalizeIdentifier(scope, "core", name));
object->id = ArtifactID(index);
object->id = ArtifactID((si32)index);
object->iconIndex = object->id;
assert(artifacts[index] == nullptr); // ensure that this id was not loaded before
@ -323,7 +323,7 @@ CArtifact * CArtHandler::loadFromJson(const JsonNode & node, const std::string &
art->advMapDef = graphics["map"].String();
art->price = node["value"].Float();
art->price = static_cast<ui32>(node["value"].Float());
loadSlots(art, node);
loadClass(art, node);
@ -481,12 +481,12 @@ void CArtHandler::loadGrowingArt(CGrowingArtifact * art, const JsonNode & node)
{
for (auto b : node["growing"]["bonusesPerLevel"].Vector())
{
art->bonusesPerLevel.push_back(std::pair <ui16, Bonus>(b["level"].Float(), Bonus()));
art->bonusesPerLevel.push_back(std::pair <ui16, Bonus>((ui16)b["level"].Float(), Bonus()));
JsonUtils::parseBonus(b["bonus"], &art->bonusesPerLevel.back().second);
}
for (auto b : node["growing"]["thresholdBonuses"].Vector())
{
art->thresholdBonuses.push_back(std::pair <ui16, Bonus>(b["level"].Float(), Bonus()));
art->thresholdBonuses.push_back(std::pair <ui16, Bonus>((ui16)b["level"].Float(), Bonus()));
JsonUtils::parseBonus(b["bonus"], &art->thresholdBonuses.back().second);
}
}
@ -647,7 +647,7 @@ void CArtHandler::initAllowedArtifactsList(const std::vector<bool> &allowed)
if (allowed[i] && legalArtifact(i))
allowedArtifacts.push_back(artifacts[i]);
}
for (ArtifactID i = ArtifactID::ART_SELECTION; i<ArtifactID(artifacts.size()); i.advance(1)) //try to allow all artifacts added by mods
for (ArtifactID i = ArtifactID::ART_SELECTION; i<ArtifactID((si32)artifacts.size()); i.advance(1)) //try to allow all artifacts added by mods
{
if (legalArtifact(ArtifactID(i)))
allowedArtifacts.push_back(artifacts[i]);
@ -831,7 +831,7 @@ ArtifactPosition CArtifactInstance::firstBackpackSlot(const CArtifactSet *h) con
{
if(!artType->isBig()) //discard big artifact
return ArtifactPosition(
GameConstants::BACKPACK_START + h->artifactsInBackpack.size());
GameConstants::BACKPACK_START + (si32)h->artifactsInBackpack.size());
return ArtifactPosition::PRE_FIRST;
}
@ -1399,7 +1399,7 @@ void CArtifactSet::serializeJsonHero(JsonSerializeFormat & handler, CMap * map)
for(const ArtifactID & artifactID : backpackTemp)
{
auto artifact = CArtifactInstance::createArtifact(map, artifactID.toEnum());
auto slot = ArtifactPosition(GameConstants::BACKPACK_START + artifactsInBackpack.size());
auto slot = ArtifactPosition(GameConstants::BACKPACK_START + (si32)artifactsInBackpack.size());
if(artifact->canBePutAt(this, slot))
putArtifact(slot, artifact);
}

View File

@ -33,7 +33,7 @@ BuildingID CBuildingHandler::campToERMU( int camp, int townType, std::set<Buildi
{2}, {1}, {1,4}, {0,2}, {0}, {0}, {0}, {0}, {0}
};
int curPos = campToERMU.size();
int curPos = static_cast<int>(campToERMU.size());
for (int i=0; i<GameConstants::CREATURES_PER_TOWN; ++i)
{
if(camp == curPos) //non-upgraded

View File

@ -182,8 +182,8 @@ JsonNode& Settings::operator [](std::string value)
static void setButton(ButtonInfo &button, const JsonNode &g)
{
button.x = g["x"].Float();
button.y = g["y"].Float();
button.x = static_cast<int>(g["x"].Float());
button.y = static_cast<int>(g["y"].Float());
button.playerColoured = g["playerColoured"].Float();
button.defName = g["graphic"].String();
@ -198,8 +198,8 @@ static void setButton(ButtonInfo &button, const JsonNode &g)
static void setGem(AdventureMapConfig &ac, const int gem, const JsonNode &g)
{
ac.gemX[gem] = g["x"].Float();
ac.gemY[gem] = g["y"].Float();
ac.gemX[gem] = static_cast<int>(g["x"].Float());
ac.gemY[gem] = static_cast<int>(g["y"].Float());
ac.gemG.push_back(g["graphic"].String());
}
@ -220,23 +220,23 @@ void config::CConfigHandler::init()
for(const JsonNode &g : guisettings_vec)
{
std::pair<int,int> curRes(g["resolution"]["x"].Float(), g["resolution"]["y"].Float());
std::pair<int,int> curRes((int)g["resolution"]["x"].Float(), (int)g["resolution"]["y"].Float());
GUIOptions *current = &conf.guiOptions[curRes];
current->ac.inputLineLength = g["InGameConsole"]["maxInputPerLine"].Float();
current->ac.outputLineLength = g["InGameConsole"]["maxOutputPerLine"].Float();
current->ac.inputLineLength = static_cast<int>(g["InGameConsole"]["maxInputPerLine"].Float());
current->ac.outputLineLength = static_cast<int>(g["InGameConsole"]["maxOutputPerLine"].Float());
current->ac.advmapX = g["AdvMap"]["x"].Float();
current->ac.advmapY = g["AdvMap"]["y"].Float();
current->ac.advmapW = g["AdvMap"]["width"].Float();
current->ac.advmapH = g["AdvMap"]["height"].Float();
current->ac.advmapX = static_cast<int>(g["AdvMap"]["x"].Float());
current->ac.advmapY = static_cast<int>(g["AdvMap"]["y"].Float());
current->ac.advmapW = static_cast<int>(g["AdvMap"]["width"].Float());
current->ac.advmapH = static_cast<int>(g["AdvMap"]["height"].Float());
current->ac.smoothMove = g["AdvMap"]["smoothMove"].Float();
current->ac.puzzleSepia = g["AdvMap"]["puzzleSepia"].Float();
current->ac.screenFading = g["AdvMap"]["screenFading"].isNull() ? true : g["AdvMap"]["screenFading"].Float(); // enabled by default
current->ac.objectFading = g["AdvMap"]["objectFading"].isNull() ? true : g["AdvMap"]["objectFading"].Float();
current->ac.infoboxX = g["InfoBox"]["x"].Float();
current->ac.infoboxY = g["InfoBox"]["y"].Float();
current->ac.infoboxX = static_cast<int>(g["InfoBox"]["x"].Float());
current->ac.infoboxY = static_cast<int>(g["InfoBox"]["y"].Float());
setGem(current->ac, 0, g["gem0"]);
setGem(current->ac, 1, g["gem1"]);
@ -246,39 +246,39 @@ void config::CConfigHandler::init()
current->ac.mainGraphic = g["background"].String();
current->ac.worldViewGraphic = g["backgroundWorldView"].String();
current->ac.hlistX = g["HeroList"]["x"].Float();
current->ac.hlistY = g["HeroList"]["y"].Float();
current->ac.hlistSize = g["HeroList"]["size"].Float();
current->ac.hlistX = static_cast<int>(g["HeroList"]["x"].Float());
current->ac.hlistY = static_cast<int>(g["HeroList"]["y"].Float());
current->ac.hlistSize = static_cast<int>(g["HeroList"]["size"].Float());
current->ac.hlistMB = g["HeroList"]["movePoints"].String();
current->ac.hlistMN = g["HeroList"]["manaPoints"].String();
current->ac.hlistAU = g["HeroList"]["arrowUp"].String();
current->ac.hlistAD = g["HeroList"]["arrowDown"].String();
current->ac.tlistX = g["TownList"]["x"].Float();
current->ac.tlistY = g["TownList"]["y"].Float();
current->ac.tlistSize = g["TownList"]["size"].Float();
current->ac.tlistX = static_cast<int>(g["TownList"]["x"].Float());
current->ac.tlistY = static_cast<int>(g["TownList"]["y"].Float());
current->ac.tlistSize = static_cast<int>(g["TownList"]["size"].Float());
current->ac.tlistAU = g["TownList"]["arrowUp"].String();
current->ac.tlistAD = g["TownList"]["arrowDown"].String();
current->ac.minimapW = g["Minimap"]["width"].Float();
current->ac.minimapH = g["Minimap"]["height"].Float();
current->ac.minimapX = g["Minimap"]["x"].Float();
current->ac.minimapY = g["Minimap"]["y"].Float();
current->ac.minimapW = static_cast<int>(g["Minimap"]["width"].Float());
current->ac.minimapH = static_cast<int>(g["Minimap"]["height"].Float());
current->ac.minimapX = static_cast<int>(g["Minimap"]["x"].Float());
current->ac.minimapY = static_cast<int>(g["Minimap"]["y"].Float());
current->ac.overviewPics = g["Overview"]["pics"].Float();
current->ac.overviewSize = g["Overview"]["size"].Float();
current->ac.overviewPics = static_cast<int>(g["Overview"]["pics"].Float());
current->ac.overviewSize = static_cast<int>(g["Overview"]["size"].Float());
current->ac.overviewBg = g["Overview"]["graphic"].String();
current->ac.statusbarX = g["Statusbar"]["x"].Float();
current->ac.statusbarY = g["Statusbar"]["y"].Float();
current->ac.statusbarX = static_cast<int>(g["Statusbar"]["x"].Float());
current->ac.statusbarY = static_cast<int>(g["Statusbar"]["y"].Float());
current->ac.statusbarG = g["Statusbar"]["graphic"].String();
current->ac.resdatabarX = g["ResDataBar"]["x"].Float();
current->ac.resdatabarY = g["ResDataBar"]["y"].Float();
current->ac.resOffsetX = g["ResDataBar"]["offsetX"].Float();
current->ac.resOffsetY = g["ResDataBar"]["offsetY"].Float();
current->ac.resDist = g["ResDataBar"]["resSpace"].Float();
current->ac.resDateDist = g["ResDataBar"]["resDateSpace"].Float();
current->ac.resdatabarX = static_cast<int>(g["ResDataBar"]["x"].Float());
current->ac.resdatabarY = static_cast<int>(g["ResDataBar"]["y"].Float());
current->ac.resOffsetX = static_cast<int>(g["ResDataBar"]["offsetX"].Float());
current->ac.resOffsetY = static_cast<int>(g["ResDataBar"]["offsetY"].Float());
current->ac.resDist = static_cast<int>(g["ResDataBar"]["resSpace"].Float());
current->ac.resDateDist = static_cast<int>(g["ResDataBar"]["resDateSpace"].Float());
current->ac.resdatabarG = g["ResDataBar"]["graphic"].String();
setButton(current->ac.kingOverview, g["ButtonKingdomOv"]);
@ -295,7 +295,7 @@ void config::CConfigHandler::init()
const JsonNode& screenRes = settings["video"]["screenRes"];
SetResolution(screenRes["width"].Float(), screenRes["height"].Float());
SetResolution((int)screenRes["width"].Float(), (int)screenRes["height"].Float());
}
// Force instantiation of the SettingsStorage::NodeAccessor class template.

View File

@ -95,7 +95,7 @@ bool CCreature::isEvil () const
si32 CCreature::maxAmount(const std::vector<si32> &res) const //how many creatures can be bought
{
int ret = 2147483645;
int resAmnt = std::min(res.size(),cost.size());
int resAmnt = static_cast<int>(std::min(res.size(),cost.size()));
for(int i=0;i<resAmnt;i++)
if(cost[i])
ret = std::min(ret,(int)(res[i]/cost[i]));
@ -245,7 +245,7 @@ void CCreatureHandler::loadCommanders()
skillLevels.push_back (std::vector<ui8>());
for (auto skillLevel : skill["levels"].Vector())
{
skillLevels[i].push_back (skillLevel.Float());
skillLevels[i].push_back ((ui8)skillLevel.Float());
}
++i;
}
@ -254,8 +254,8 @@ void CCreatureHandler::loadCommanders()
{
std::pair <std::shared_ptr<Bonus>, std::pair <ui8, ui8> > a;
a.first = JsonUtils::parseBonus (ability["ability"].Vector());
a.second.first = ability["skills"].Vector()[0].Float();
a.second.second = ability["skills"].Vector()[1].Float();
a.second.first = static_cast<ui8>(ability["skills"].Vector()[0].Float());
a.second.second = static_cast<ui8>(ability["skills"].Vector()[1].Float());
skillRequirements.push_back (a);
}
}
@ -398,7 +398,7 @@ std::vector<JsonNode> CCreatureHandler::loadLegacyData(size_t dataSize)
void CCreatureHandler::loadObject(std::string scope, std::string name, const JsonNode & data)
{
auto object = loadFromJson(data, normalizeIdentifier(scope, "core", name));
object->setId(CreatureID(creatures.size()));
object->setId(CreatureID((si32)creatures.size()));
object->iconIndex = object->idNumber + 2;
creatures.push_back(object);
@ -432,7 +432,7 @@ void CCreatureHandler::loadObject(std::string scope, std::string name, const Jso
void CCreatureHandler::loadObject(std::string scope, std::string name, const JsonNode & data, size_t index)
{
auto object = loadFromJson(data, normalizeIdentifier(scope, "core", name));
object->setId(CreatureID(index));
object->setId(CreatureID((si32)index));
object->iconIndex = object->idNumber + 2;
if(data["hasDoubleWeek"].Bool()) //
@ -528,7 +528,7 @@ void CCreatureHandler::loadCrExpBon()
}
do //parse everything that's left
{
auto sid = parser.readNumber(); //id = this particular creature ID
ui32 sid = static_cast<ui32>(parser.readNumber()); //id = this particular creature ID
b.sid = sid;
bl.clear();
loadStackExp(b, bl, parser);
@ -573,8 +573,8 @@ void CCreatureHandler::loadCrExpBon()
expBonParser.readString(); //ignore upgrade mod? ->hardcoded
expBonParser.readString(); //already calculated
maxExpPerBattle[i] = expBonParser.readNumber();
expRanks[i].push_back(expRanks[i].back() + expBonParser.readNumber());
maxExpPerBattle[i] = static_cast<ui32>(expBonParser.readNumber());
expRanks[i].push_back(expRanks[i].back() + (ui32)expBonParser.readNumber());
expBonParser.endLine();
}
@ -654,30 +654,30 @@ CCreature * CCreatureHandler::loadFromJson(const JsonNode & node, const std::str
cre->cost = Res::ResourceSet(node["cost"]);
cre->fightValue = node["fightValue"].Float();
cre->AIValue = node["aiValue"].Float();
cre->growth = node["growth"].Float();
cre->hordeGrowth = node["horde"].Float(); // Needed at least until configurable buildings
cre->fightValue = static_cast<ui32>(node["fightValue"].Float());
cre->AIValue = static_cast<ui32>(node["aiValue"].Float());
cre->growth = static_cast<ui32>(node["growth"].Float());
cre->hordeGrowth = static_cast<ui32>(node["horde"].Float()); // Needed at least until configurable buildings
cre->addBonus(node["hitPoints"].Float(), Bonus::STACK_HEALTH);
cre->addBonus(node["speed"].Float(), Bonus::STACKS_SPEED);
cre->addBonus(node["attack"].Float(), Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK);
cre->addBonus(node["defense"].Float(), Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE);
cre->addBonus((int)node["hitPoints"].Float(), Bonus::STACK_HEALTH);
cre->addBonus((int)node["speed"].Float(), Bonus::STACKS_SPEED);
cre->addBonus((int)node["attack"].Float(), Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK);
cre->addBonus((int)node["defense"].Float(), Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE);
cre->addBonus(node["damage"]["min"].Float(), Bonus::CREATURE_DAMAGE, 1);
cre->addBonus(node["damage"]["max"].Float(), Bonus::CREATURE_DAMAGE, 2);
cre->addBonus((int)node["damage"]["min"].Float(), Bonus::CREATURE_DAMAGE, 1);
cre->addBonus((int)node["damage"]["max"].Float(), Bonus::CREATURE_DAMAGE, 2);
assert(node["damage"]["min"].Float() <= node["damage"]["max"].Float());
cre->ammMin = node["advMapAmount"]["min"].Float();
cre->ammMax = node["advMapAmount"]["max"].Float();
cre->ammMin = static_cast<ui32>(node["advMapAmount"]["min"].Float());
cre->ammMax = static_cast<ui32>(node["advMapAmount"]["max"].Float());
assert(cre->ammMin <= cre->ammMax);
if (!node["shots"].isNull())
cre->addBonus(node["shots"].Float(), Bonus::SHOTS);
cre->addBonus((int)node["shots"].Float(), Bonus::SHOTS);
if (node["spellPoints"].isNull())
cre->addBonus(node["spellPoints"].Float(), Bonus::CASTS);
cre->addBonus((int)node["spellPoints"].Float(), Bonus::CASTS);
cre->doubleWide = node["doubleWide"].Bool();
@ -690,7 +690,7 @@ CCreature * CCreatureHandler::loadFromJson(const JsonNode & node, const std::str
void CCreatureHandler::loadJsonAnimation(CCreature * cre, const JsonNode & graphics)
{
cre->animation.timeBetweenFidgets = graphics["timeBetweenFidgets"].Float();
cre->animation.troopCountLocationOffset = graphics["troopCountLocationOffset"].Float();
cre->animation.troopCountLocationOffset = static_cast<int>(graphics["troopCountLocationOffset"].Float());
const JsonNode & animationTime = graphics["animationTime"];
cre->animation.walkAnimationTime = animationTime["walk"].Float();
@ -700,14 +700,14 @@ void CCreatureHandler::loadJsonAnimation(CCreature * cre, const JsonNode & graph
const JsonNode & missile = graphics["missile"];
const JsonNode & offsets = missile["offset"];
cre->animation.upperRightMissleOffsetX = offsets["upperX"].Float();
cre->animation.upperRightMissleOffsetY = offsets["upperY"].Float();
cre->animation.rightMissleOffsetX = offsets["middleX"].Float();
cre->animation.rightMissleOffsetY = offsets["middleY"].Float();
cre->animation.lowerRightMissleOffsetX = offsets["lowerX"].Float();
cre->animation.lowerRightMissleOffsetY = offsets["lowerY"].Float();
cre->animation.upperRightMissleOffsetX = static_cast<int>(offsets["upperX"].Float());
cre->animation.upperRightMissleOffsetY = static_cast<int>(offsets["upperY"].Float());
cre->animation.rightMissleOffsetX = static_cast<int>(offsets["middleX"].Float());
cre->animation.rightMissleOffsetY = static_cast<int>(offsets["middleY"].Float());
cre->animation.lowerRightMissleOffsetX = static_cast<int>(offsets["lowerX"].Float());
cre->animation.lowerRightMissleOffsetY = static_cast<int>(offsets["lowerY"].Float());
cre->animation.attackClimaxFrame = missile["attackClimaxFrame"].Float();
cre->animation.attackClimaxFrame = static_cast<int>(missile["attackClimaxFrame"].Float());
cre->animation.missleFrameAngles = missile["frameAngles"].convertTo<std::vector<double> >();
cre->advMapDef = graphics["map"].String();
@ -717,7 +717,7 @@ void CCreatureHandler::loadJsonAnimation(CCreature * cre, const JsonNode & graph
void CCreatureHandler::loadCreatureJson(CCreature * creature, const JsonNode & config)
{
creature->level = config["level"].Float();
creature->level = static_cast<ui8>(config["level"].Float());
creature->animDefName = config["graphics"]["animation"].String();
//FIXME: MOD COMPATIBILITY
@ -813,11 +813,11 @@ void CCreatureHandler::loadStackExperience(CCreature * creature, const JsonNode
{
if (val.Float() != lastVal)
{
bonus->val = val.Float() - lastVal;
bonus->val = (int)val.Float() - lastVal;
bonus->limiter.reset (new RankRangeLimiter(lowerLimit));
creature->addNewBonus (std::make_shared<Bonus>(*bonus));
}
lastVal = val.Float();
lastVal = static_cast<int>(val.Float());
++lowerLimit;
}
}
@ -1093,10 +1093,10 @@ void CCreatureHandler::loadStackExp(Bonus & b, BonusList & bl, CLegacyConfigPars
{
if (b.type != Bonus::REBIRTH)
b.val = 0; //on-off ability, no value specified
curVal = parser.readNumber();// 0 level is never active
curVal = static_cast<si32>(parser.readNumber());// 0 level is never active
for (int i = 1; i < 11; ++i)
{
curVal = parser.readNumber();
curVal = static_cast<si32>(parser.readNumber());
if (curVal == 1)
{
b.limiter.reset (new RankRangeLimiter(i));
@ -1107,13 +1107,13 @@ void CCreatureHandler::loadStackExp(Bonus & b, BonusList & bl, CLegacyConfigPars
}
else
{
lastVal = parser.readNumber();
lastVal = static_cast<si32>(parser.readNumber());
if (b.type == Bonus::HATE)
lastVal *= 10; //odd fix
//FIXME: value for zero level should be stored in our config files (independent of stack exp)
for (int i = 1; i < 11; ++i)
{
curVal = parser.readNumber();
curVal = static_cast<si32>(parser.readNumber());
if (b.type == Bonus::HATE)
curVal *= 10; //odd fix
if (curVal > lastVal) //threshold, add new bonus

View File

@ -261,7 +261,7 @@ std::string CCreatureSet::getArmyDescription() const
int CCreatureSet::stacksCount() const
{
return stacks.size();
return static_cast<int>(stacks.size());
}
void CCreatureSet::setFormation(bool tight)
@ -274,7 +274,7 @@ void CCreatureSet::setStackCount(SlotID slot, TQuantity count)
assert(hasStackAtSlot(slot));
assert(stacks[slot]->count + count > 0);
if (VLC->modh->modules.STACK_EXP && count > stacks[slot]->count)
stacks[slot]->experience *= (count / static_cast<double>(stacks[slot]->count));
stacks[slot]->experience = static_cast<TExpType>(stacks[slot]->experience * (count / static_cast<double>(stacks[slot]->count)));
stacks[slot]->count = count;
armyChanged();
}
@ -520,7 +520,7 @@ void CCreatureSet::serializeJson(JsonSerializeFormat & handler, const std::strin
{
CStackInstance * new_stack = new CStackInstance();
new_stack->serializeJson(handler);
putStack(SlotID(idx), new_stack);
putStack(SlotID((si32)idx), new_stack);
}
}
}
@ -570,7 +570,7 @@ int CStackInstance::getExpRank() const
int tier = type->level;
if (vstd::iswithin(tier, 1, 7))
{
for (int i = VLC->creh->expRanks[tier].size()-2; i >-1; --i)//sic!
for (int i = (int)VLC->creh->expRanks[tier].size()-2; i >-1; --i)//sic!
{ //exp values vary from 1st level to max exp at 11th level
if (experience >= VLC->creh->expRanks[tier][i])
return ++i; //faster, but confusing - 0 index mean 1st level of experience
@ -579,7 +579,7 @@ int CStackInstance::getExpRank() const
}
else //higher tier
{
for (int i = VLC->creh->expRanks[0].size()-2; i >-1; --i)
for (int i = (int)VLC->creh->expRanks[0].size()-2; i >-1; --i)
{
if (experience >= VLC->creh->expRanks[0][i])
return ++i;
@ -633,7 +633,7 @@ void CStackInstance::setType(const CCreature *c)
{
detachFrom(const_cast<CCreature*>(type));
if (type->isMyUpgrade(c) && VLC->modh->modules.STACK_EXP)
experience *= VLC->creh->expAfterUpgrade / 100.0;
experience = static_cast<TExpType>(experience * VLC->creh->expAfterUpgrade / 100.0);
}
CStackBasicDescriptor::setType(c);
@ -858,7 +858,7 @@ ArtBearer::ArtBearer CCommanderInstance::bearerType() const
bool CCommanderInstance::gainsLevel() const
{
return experience >= VLC->heroh->reqExp(level+1);
return experience >= (TExpType)VLC->heroh->reqExp(level+1);
}
CStackBasicDescriptor::CStackBasicDescriptor()

View File

@ -228,7 +228,7 @@ void CGameInfoCallback::getThievesGuildInfo(SThievesGuildInfo & thi, const CGObj
int CGameInfoCallback::howManyTowns(PlayerColor Player) const
{
ERROR_RET_VAL_IF(!hasAccess(Player), "Access forbidden!", -1);
return gs->players[Player].towns.size();
return static_cast<int>(gs->players[Player].towns.size());
}
bool CGameInfoCallback::getTownInfo(const CGObjectInstance * town, InfoAboutTown & dest, const CGObjectInstance * selectedObject) const
@ -314,7 +314,7 @@ bool CGameInfoCallback::getHeroInfo(const CGObjectInstance * hero, InfoAboutHero
for(auto & elem : info.army)
{
if(elem.second.type->AIValue > maxAIValue)
if((int)elem.second.type->AIValue > maxAIValue)
{
maxAIValue = elem.second.type->AIValue;
mostStrong = elem.second.type;
@ -350,7 +350,7 @@ bool CGameInfoCallback::getHeroInfo(const CGObjectInstance * hero, InfoAboutHero
for(auto creature : VLC->creh->creatures)
{
if(creature->faction == factionIndex && creature->AIValue > maxAIValue)
if((si16)creature->faction == factionIndex && (int)creature->AIValue > maxAIValue)
{
maxAIValue = creature->AIValue;
mostStrong = creature;
@ -512,7 +512,7 @@ std::shared_ptr<boost::multi_array<TerrainTile*, 3>> CGameInfoCallback::getAllVi
for (size_t z = 0; z < levels; z++)
{
if (team->fogOfWarMap[x][y][z])
tileArray[x][y][z] = &gs->map->getTile(int3(x, y, z));
tileArray[x][y][z] = &gs->map->getTile(int3((si32)x, (si32)y, (si32)z));
else
tileArray[x][y][z] = nullptr;
}
@ -654,7 +654,7 @@ int CGameInfoCallback::getHeroCount( PlayerColor player, bool includeGarrisoned
ERROR_RET_VAL_IF(!p, "No such player!", -1);
if(includeGarrisoned)
return p->heroes.size();
return static_cast<int>(p->heroes.size());
else
for(auto & elem : p->heroes)
if(!elem->inTownGarrison)
@ -751,7 +751,7 @@ int CPlayerSpecificInfoCallback::getHeroSerial(const CGHeroInstance * hero, bool
index++;
if (heroe == hero)
return index;
return static_cast<int>(index);
}
return -1;
}
@ -821,7 +821,7 @@ const CGHeroInstance* CPlayerSpecificInfoCallback::getHeroBySerial(int serialId,
if (!includeGarrisoned)
{
for(ui32 i = 0; i < p->heroes.size() && i<=serialId; i++)
for(ui32 i = 0; i < p->heroes.size() && (int)i<=serialId; i++)
if(p->heroes[i]->inTownGarrison)
serialId++;
}

View File

@ -484,7 +484,7 @@ std::pair<Obj,int> CGameState::pickObject (CGObjectInstance *obj)
{
do
{
f = getRandomGenerator().nextInt(VLC->townh->factions.size() - 1);
f = getRandomGenerator().nextInt((int)VLC->townh->factions.size() - 1);
}
while (VLC->townh->factions[f]->town == nullptr); // find playable faction
}
@ -506,7 +506,7 @@ std::pair<Obj,int> CGameState::pickObject (CGObjectInstance *obj)
//if castle alignment available
if (auto info = dynamic_cast<CCreGenAsCastleInfo*>(dwl->info))
{
faction = getRandomGenerator().nextInt(VLC->townh->factions.size() - 1);
faction = getRandomGenerator().nextInt((int)VLC->townh->factions.size() - 1);
if(info->asCastle && info->instanceId != "")
{
auto iter = map->instanceNames.find(info->instanceId);
@ -886,7 +886,7 @@ void CGameState::initGrailPosition()
&& !t.visitable
&& t.terType != ETerrainType::WATER
&& t.terType != ETerrainType::ROCK
&& map->grailPos.dist2dSQ(int3(i, j, k)) <= (map->grailRadius * map->grailRadius))
&& (int)map->grailPos.dist2dSQ(int3(i, j, k)) <= (map->grailRadius * map->grailRadius))
allowedPos.push_back(int3(i,j,k));
}
}
@ -915,7 +915,7 @@ void CGameState::initRandomFactionsForPlayers()
{
if(elem.second.castle==-1)
{
auto randomID = getRandomGenerator().nextInt(map->players[elem.first.getNum()].allowedFactions.size() - 1);
auto randomID = getRandomGenerator().nextInt((int)map->players[elem.first.getNum()].allowedFactions.size() - 1);
auto iter = map->players[elem.first.getNum()].allowedFactions.begin();
std::advance(iter, randomID);
@ -1207,7 +1207,7 @@ void CGameState::prepareCrossoverHeroes(std::vector<CGameState::CampaignHeroRepl
size_t totalArts = GameConstants::BACKPACK_START + hero->artifactsInBackpack.size();
for (size_t i = 0; i < totalArts; i++ )
{
auto artifactPosition = ArtifactPosition(i);
auto artifactPosition = ArtifactPosition((si32)i);
if(artifactPosition == ArtifactPosition::SPELLBOOK) continue; // do not handle spellbook this way
const ArtSlotInfo *info = hero->getSlot(artifactPosition);
@ -2094,7 +2094,7 @@ void CGameState::updateRumor()
// Makes sure that map rumors only used if there enough rumors too choose from
if(map->rumors.size() && (map->rumors.size() > 1 || !rumor.last.count(RumorState::TYPE_MAP)))
{
rumorId = rand.nextInt(map->rumors.size() - 1);
rumorId = rand.nextInt((int)map->rumors.size() - 1);
break;
}
else
@ -2104,7 +2104,7 @@ void CGameState::updateRumor()
case RumorState::TYPE_RAND:
do
{
rumorId = rand.nextInt(VLC->generaltexth->tavernRumors.size() - 1);
rumorId = rand.nextInt((int)VLC->generaltexth->tavernRumors.size() - 1);
}
while(!VLC->generaltexth->tavernRumors[rumorId].length());
@ -2304,7 +2304,7 @@ bool CGameState::checkForVictory(PlayerColor player, const EventCondition & cond
}
case EventCondition::DAYS_PASSED:
{
return gs->day > condition.value;
return (si32)gs->day > condition.value;
}
case EventCondition::IS_HUMAN:
{
@ -2440,7 +2440,7 @@ struct statsHLP
int ret = 0;
for(auto h : ps->heroes)
{
ret += h->artifactsInBackpack.size() + h->artifactsWorn.size();
ret += (int)h->artifactsInBackpack.size() + (int)h->artifactsWorn.size();
}
return ret;
}
@ -2816,7 +2816,7 @@ void CGameState::replaceHeroesPlaceholders(const std::vector<CGameState::Campaig
{
art->artType = VLC->arth->artifacts[art->artType->id];
gs->map->artInstances.push_back(art);
art->id = ArtifactInstanceID(gs->map->artInstances.size() - 1);
art->id = ArtifactInstanceID((si32)gs->map->artInstances.size() - 1);
};
for(auto &&i : heroToPlace->artifactsWorn)
@ -3079,7 +3079,7 @@ int ArmyDescriptor::getStrength() const
for(auto & elem : *this)
ret += elem.second.type->AIValue * CCreature::estimateCreatureCount(elem.second.count);
}
return ret;
return static_cast<int>(ret);
}
TeamState::TeamState()

View File

@ -75,7 +75,7 @@ public:
std::vector<numeric> ret;
ret.reserve(size);
while (size--)
ret.push_back(readNumber());
ret.push_back((numeric)readNumber());
return ret;
}

View File

@ -113,14 +113,14 @@ CHeroClass * CHeroClassHandler::loadFromJson(const JsonNode & node, const std::s
for(const std::string & pSkill : PrimarySkill::names)
{
heroClass->primarySkillInitial.push_back(node["primarySkills"][pSkill].Float());
heroClass->primarySkillLowLevel.push_back(node["lowLevelChance"][pSkill].Float());
heroClass->primarySkillHighLevel.push_back(node["highLevelChance"][pSkill].Float());
heroClass->primarySkillInitial.push_back((int)node["primarySkills"][pSkill].Float());
heroClass->primarySkillLowLevel.push_back((int)node["lowLevelChance"][pSkill].Float());
heroClass->primarySkillHighLevel.push_back((int)node["highLevelChance"][pSkill].Float());
}
for(auto skillPair : node["secondarySkills"].Struct())
{
int probability = skillPair.second.Integer();
int probability = static_cast<int>(skillPair.second.Integer());
VLC->modh->identifiers.requestIdentifier(skillPair.second.meta, "skill", skillPair.first, [heroClass, probability](si32 skillID)
{
if(heroClass->secSkillProbability.size() <= skillID)
@ -135,10 +135,10 @@ CHeroClass * CHeroClassHandler::loadFromJson(const JsonNode & node, const std::s
heroClass->commander = VLC->creh->creatures[commanderID];
});
heroClass->defaultTavernChance = node["defaultTavern"].Float();
heroClass->defaultTavernChance = static_cast<ui32>(node["defaultTavern"].Float());
for(auto & tavern : node["tavern"].Struct())
{
int value = tavern.second.Float();
int value = static_cast<int>(tavern.second.Float());
VLC->modh->identifiers.requestIdentifier(tavern.second.meta, "faction", tavern.first,
[=](si32 factionID)
@ -199,7 +199,7 @@ std::vector<JsonNode> CHeroClassHandler::loadLegacyData(size_t dataSize)
void CHeroClassHandler::loadObject(std::string scope, std::string name, const JsonNode & data)
{
auto object = loadFromJson(data, normalizeIdentifier(scope, "core", name));
object->id = heroClasses.size();
object->id = static_cast<ui8>(heroClasses.size());
heroClasses.push_back(object);
@ -217,7 +217,7 @@ void CHeroClassHandler::loadObject(std::string scope, std::string name, const Js
void CHeroClassHandler::loadObject(std::string scope, std::string name, const JsonNode & data, size_t index)
{
auto object = loadFromJson(data, normalizeIdentifier(scope, "core", name));
object->id = index;
object->id = static_cast<ui8>(index);
assert(heroClasses[index] == nullptr); // ensure that this id was not loaded before
heroClasses[index] = object;
@ -245,7 +245,7 @@ void CHeroClassHandler::afterLoadFinalization()
if (heroClass->selectionProbability.count(faction->index))
continue;
float chance = heroClass->defaultTavernChance * faction->town->defaultTavernChance;
float chance = static_cast<float>(heroClass->defaultTavernChance * faction->town->defaultTavernChance);
heroClass->selectionProbability[faction->index] = static_cast<int>(sqrt(chance) + 0.5); //FIXME: replace with std::round once MVS supports it
}
// set default probabilities for gaining secondary skills where not loaded previously
@ -347,8 +347,8 @@ void CHeroHandler::loadHeroArmy(CHero * hero, const JsonNode & node)
{
const JsonNode & source = node["army"].Vector()[i];
hero->initialArmy[i].minAmount = source["min"].Float();
hero->initialArmy[i].maxAmount = source["max"].Float();
hero->initialArmy[i].minAmount = static_cast<ui32>(source["min"].Float());
hero->initialArmy[i].maxAmount = static_cast<ui32>(source["max"].Float());
assert(hero->initialArmy[i].minAmount <= hero->initialArmy[i].maxAmount);
@ -363,7 +363,7 @@ void CHeroHandler::loadHeroSkills(CHero * hero, const JsonNode & node)
{
for(const JsonNode &set : node["skills"].Vector())
{
int skillLevel = boost::range::find(NSecondarySkill::levels, set["level"].String()) - std::begin(NSecondarySkill::levels);
int skillLevel = static_cast<int>(boost::range::find(NSecondarySkill::levels, set["level"].String()) - std::begin(NSecondarySkill::levels));
if (skillLevel < SecSkillLevel::LEVELS_SIZE)
{
size_t currentIndex = hero->secSkillsInit.size();
@ -657,10 +657,10 @@ void CHeroHandler::loadHeroSpecialty(CHero * hero, const JsonNode & node)
for(const JsonNode &specialty : specialtiesNode.Vector())
{
SSpecialtyInfo spec;
spec.type = specialty["type"].Integer();
spec.val = specialty["val"].Integer();
spec.subtype = specialty["subtype"].Integer();
spec.additionalinfo = specialty["info"].Integer();
spec.type = static_cast<si32>(specialty["type"].Integer());
spec.val = static_cast<si32>(specialty["val"].Integer());
spec.subtype = static_cast<si32>(specialty["subtype"].Integer());
spec.additionalinfo = static_cast<si32>(specialty["info"].Integer());
//we convert after loading completes, to have all identifiers for json logging
hero->specDeprecated.push_back(spec);
}
@ -734,12 +734,12 @@ void CHeroHandler::loadObstacles()
{
for(const JsonNode &obs : node.Vector())
{
int ID = obs["id"].Float();
int ID = static_cast<int>(obs["id"].Float());
CObstacleInfo & obi = out[ID];
obi.ID = ID;
obi.defName = obs["defname"].String();
obi.width = obs["width"].Float();
obi.height = obs["height"].Float();
obi.width = static_cast<si32>(obs["width"].Float());
obi.height = static_cast<si32>(obs["height"].Float());
obi.allowedTerrains = obs["allowedTerrain"].convertTo<std::vector<ETerrainType> >();
obi.allowedSpecialBfields = obs["specialBattlefields"].convertTo<std::vector<BFieldType> >();
obi.blockedTiles = obs["blockedTiles"].convertTo<std::vector<si16> >();
@ -774,15 +774,15 @@ void CHeroHandler::loadBallistics()
ballParser.readString();
CHeroHandler::SBallisticsLevelInfo bli;
bli.keep = ballParser.readNumber();
bli.tower = ballParser.readNumber();
bli.gate = ballParser.readNumber();
bli.wall = ballParser.readNumber();
bli.shots = ballParser.readNumber();
bli.noDmg = ballParser.readNumber();
bli.oneDmg = ballParser.readNumber();
bli.twoDmg = ballParser.readNumber();
bli.sum = ballParser.readNumber();
bli.keep = static_cast<ui8>(ballParser.readNumber());
bli.tower = static_cast<ui8>(ballParser.readNumber());
bli.gate = static_cast<ui8>(ballParser.readNumber());
bli.wall = static_cast<ui8>(ballParser.readNumber());
bli.shots = static_cast<ui8>(ballParser.readNumber());
bli.noDmg = static_cast<ui8>(ballParser.readNumber());
bli.oneDmg = static_cast<ui8>(ballParser.readNumber());
bli.twoDmg = static_cast<ui8>(ballParser.readNumber());
bli.sum = static_cast<ui8>(ballParser.readNumber());
ballistics.push_back(bli);
assert(bli.noDmg + bli.oneDmg + bli.twoDmg == 100 && bli.sum == 100);
@ -837,8 +837,8 @@ std::vector<JsonNode> CHeroHandler::loadLegacyData(size_t dataSize)
void CHeroHandler::loadObject(std::string scope, std::string name, const JsonNode & data)
{
auto object = loadFromJson(data, normalizeIdentifier(scope, "core", name));
object->ID = HeroTypeID(heroes.size());
object->imageIndex = heroes.size() + GameConstants::HERO_PORTRAIT_SHIFT; // 2 special frames + some extra portraits
object->ID = HeroTypeID((si32)heroes.size());
object->imageIndex = (si32)heroes.size() + GameConstants::HERO_PORTRAIT_SHIFT; // 2 special frames + some extra portraits
heroes.push_back(object);
@ -848,8 +848,8 @@ void CHeroHandler::loadObject(std::string scope, std::string name, const JsonNod
void CHeroHandler::loadObject(std::string scope, std::string name, const JsonNode & data, size_t index)
{
auto object = loadFromJson(data, normalizeIdentifier(scope, "core", name));
object->ID = HeroTypeID(index);
object->imageIndex = index;
object->ID = HeroTypeID((si32)index);
object->imageIndex = static_cast<si32>(index);
assert(heroes[index] == nullptr); // ensure that this id was not loaded before
heroes[index] = object;
@ -923,7 +923,7 @@ void CHeroHandler::afterLoadFinalization()
ui32 CHeroHandler::level (ui64 experience) const
{
return boost::range::upper_bound(expPerLevel, experience) - std::begin(expPerLevel);
return static_cast<ui32>(boost::range::upper_bound(expPerLevel, experience) - std::begin(expPerLevel));
}
ui64 CHeroHandler::reqExp (ui32 level) const
@ -948,7 +948,7 @@ void CHeroHandler::loadTerrains()
terrCosts.reserve(GameConstants::TERRAIN_TYPES);
for(const std::string & name : GameConstants::TERRAIN_NAMES)
terrCosts.push_back(config[name]["moveCost"].Float());
terrCosts.push_back((int)config[name]["moveCost"].Float());
}
std::vector<bool> CHeroHandler::getDefaultAllowed() const

View File

@ -319,7 +319,7 @@ void CIdentifierStorage::finalize()
ContentTypeHandler::ContentTypeHandler(IHandlerBase * handler, std::string objectName):
handler(handler),
objectName(objectName),
originalData(handler->loadLegacyData(VLC->modh->settings.data["textData"][objectName].Float()))
originalData(handler->loadLegacyData((size_t)VLC->modh->settings.data["textData"][objectName].Float()))
{
for(auto & node : originalData)
{
@ -385,7 +385,7 @@ bool ContentTypeHandler::loadMod(std::string modName, bool validate)
if (vstd::contains(data.Struct(), "index") && !data["index"].isNull())
{
// try to add H3 object data
size_t index = data["index"].Float();
size_t index = static_cast<size_t>(data["index"].Float());
if(originalData.size() > index)
{
@ -643,17 +643,17 @@ void CModHandler::loadConfigFromFile (std::string name)
logMod->debug("Loading hardcoded features settings from [%s], result:", paths);
settings.data = JsonUtils::assembleFromFiles("config/" + name);
const JsonNode & hardcodedFeatures = settings.data["hardcodedFeatures"];
settings.MAX_HEROES_AVAILABLE_PER_PLAYER = hardcodedFeatures["MAX_HEROES_AVAILABLE_PER_PLAYER"].Integer();
settings.MAX_HEROES_AVAILABLE_PER_PLAYER = static_cast<int>(hardcodedFeatures["MAX_HEROES_AVAILABLE_PER_PLAYER"].Integer());
logMod->debug("\tMAX_HEROES_AVAILABLE_PER_PLAYER\t%d", settings.MAX_HEROES_AVAILABLE_PER_PLAYER);
settings.MAX_HEROES_ON_MAP_PER_PLAYER = hardcodedFeatures["MAX_HEROES_ON_MAP_PER_PLAYER"].Integer();
settings.MAX_HEROES_ON_MAP_PER_PLAYER = static_cast<int>(hardcodedFeatures["MAX_HEROES_ON_MAP_PER_PLAYER"].Integer());
logMod->debug("\tMAX_HEROES_ON_MAP_PER_PLAYER\t%d", settings.MAX_HEROES_ON_MAP_PER_PLAYER);
settings.CREEP_SIZE = hardcodedFeatures["CREEP_SIZE"].Integer();
settings.CREEP_SIZE = static_cast<int>(hardcodedFeatures["CREEP_SIZE"].Integer());
logMod->debug("\tCREEP_SIZE\t%d", settings.CREEP_SIZE);
settings.WEEKLY_GROWTH = hardcodedFeatures["WEEKLY_GROWTH_PERCENT"].Integer();
settings.WEEKLY_GROWTH = static_cast<int>(hardcodedFeatures["WEEKLY_GROWTH_PERCENT"].Integer());
logMod->debug("\tWEEKLY_GROWTH\t%d", settings.WEEKLY_GROWTH);
settings.NEUTRAL_STACK_EXP = hardcodedFeatures["NEUTRAL_STACK_EXP_DAILY"].Integer();
settings.NEUTRAL_STACK_EXP = static_cast<int>(hardcodedFeatures["NEUTRAL_STACK_EXP_DAILY"].Integer());
logMod->debug("\tNEUTRAL_STACK_EXP\t%d", settings.NEUTRAL_STACK_EXP);
settings.MAX_BUILDING_PER_TURN = hardcodedFeatures["MAX_BUILDING_PER_TURN"].Integer();
settings.MAX_BUILDING_PER_TURN = static_cast<int>(hardcodedFeatures["MAX_BUILDING_PER_TURN"].Integer());
logMod->debug("\tMAX_BUILDING_PER_TURN\t%d", settings.MAX_BUILDING_PER_TURN);
settings.DWELLINGS_ACCUMULATE_CREATURES = hardcodedFeatures["DWELLINGS_ACCUMULATE_CREATURES"].Bool();
logMod->debug("\tDWELLINGS_ACCUMULATE_CREATURES\t%d", static_cast<int>(settings.DWELLINGS_ACCUMULATE_CREATURES));

View File

@ -1240,22 +1240,22 @@ int CPathfinderHelper::getMovementCost(
if(dt->blocked && ti->hasBonusOfType(Bonus::FLYING_MOVEMENT))
{
ret *= (100.0 + ti->valOfBonuses(Bonus::FLYING_MOVEMENT)) / 100.0;
ret = static_cast<int>(ret * (100.0 + ti->valOfBonuses(Bonus::FLYING_MOVEMENT)) / 100.0);
}
else if(dt->terType == ETerrainType::WATER)
{
if(hero->boat && ct->hasFavorableWinds() && dt->hasFavorableWinds())
ret *= 0.666;
ret = static_cast<int>(ret * 0.666);
else if(!hero->boat && ti->hasBonusOfType(Bonus::WATER_WALKING))
{
ret *= (100.0 + ti->valOfBonuses(Bonus::WATER_WALKING)) / 100.0;
ret = static_cast<int>(ret * (100.0 + ti->valOfBonuses(Bonus::WATER_WALKING)) / 100.0);
}
}
if(src.x != dst.x && src.y != dst.y) //it's diagonal move
{
int old = ret;
ret *= 1.414213;
ret = static_cast < int>(ret * 1.414213);
//diagonal move costs too much but normal move is possible - allow diagonal move for remaining move points
if(ret > remainingMovePoints && remainingMovePoints >= old)
{

View File

@ -27,7 +27,7 @@ void CRandomGenerator::resetSeed()
{
boost::hash<std::string> stringHash;
auto threadIdHash = stringHash(boost::lexical_cast<std::string>(boost::this_thread::get_id()));
setSeed(threadIdHash * std::time(nullptr));
setSeed((int)(threadIdHash * std::time(nullptr)));
}
TRandI CRandomGenerator::getIntRange(int lower, int upper)

View File

@ -148,18 +148,18 @@ const std::string & CSkillHandler::skillName(int skill) const
CSkill * CSkillHandler::loadFromJson(const JsonNode & json, const std::string & identifier, size_t index)
{
CSkill * skill = new CSkill(SecondarySkill(index), identifier);
CSkill * skill = new CSkill(SecondarySkill((si32)index), identifier);
skill->name = json["name"].String();
switch(json["gainChance"].getType())
{
case JsonNode::JsonType::DATA_INTEGER:
skill->gainChance[0] = json["gainChance"].Integer();
skill->gainChance[1] = json["gainChance"].Integer();
skill->gainChance[0] = static_cast<si32>(json["gainChance"].Integer());
skill->gainChance[1] = static_cast<si32>(json["gainChance"].Integer());
break;
case JsonNode::JsonType::DATA_STRUCT:
skill->gainChance[0] = json["gainChance"]["might"].Integer();
skill->gainChance[1] = json["gainChance"]["magic"].Integer();
skill->gainChance[0] = static_cast<si32>(json["gainChance"]["might"].Integer());
skill->gainChance[1] = static_cast<si32>(json["gainChance"]["magic"].Integer());
break;
default:
break;

View File

@ -316,7 +316,7 @@ std::string CStack::getName() const
bool CStack::canBeHealed() const
{
return getFirstHPleft() < MaxHealth()
return getFirstHPleft() < (int32_t)MaxHealth()
&& isValidTarget()
&& !hasBonusOfType(Bonus::SIEGE_WEAPON);
}

View File

@ -18,7 +18,7 @@
CThreadHelper::CThreadHelper(std::vector<std::function<void()> > *Tasks, int Threads)
{
currentTask = 0; amount = Tasks->size();
currentTask = 0; amount = (int)Tasks->size();
tasks = Tasks;
threads = Threads;
}

View File

@ -364,7 +364,7 @@ void CTownHandler::loadBuilding(CTown * town, const std::string & stringID, cons
ret->identifier = stringID;
ret->town = town;
ret->bid = BuildingID(source["id"].Float());
ret->bid = BuildingID((BuildingID::EBuildingID)source["id"].Float());
ret->name = source["name"].String();
ret->description = source["description"].String();
ret->resources = TResources(source["cost"]);
@ -461,9 +461,9 @@ void CTownHandler::loadStructure(CTown &town, const std::string & stringID, cons
}
ret->identifier = stringID;
ret->pos.x = source["x"].Float();
ret->pos.y = source["y"].Float();
ret->pos.z = source["z"].Float();
ret->pos.x = static_cast<si32>(source["x"].Float());
ret->pos.y = static_cast<si32>(source["y"].Float());
ret->pos.z = static_cast<si32>(source["z"].Float());
ret->hiddenUpgrade = source["hidden"].Bool();
ret->defName = source["animation"].String();
@ -517,8 +517,8 @@ void CTownHandler::loadTownHall(CTown &town, const JsonNode & source)
CTown::ClientInfo::Point JsonToPoint(const JsonNode & node)
{
CTown::ClientInfo::Point ret;
ret.x = node["x"].Float();
ret.y = node["y"].Float();
ret.x = static_cast<si32>(node["x"].Float());
ret.y = static_cast<si32>(node["y"].Float());
return ret;
}
@ -607,29 +607,29 @@ void CTownHandler::loadTown(CTown * town, const JsonNode & source)
if(resIter == std::end(GameConstants::RESOURCE_NAMES))
town->primaryRes = Res::WOOD_AND_ORE; //Wood + Ore
else
town->primaryRes = resIter - std::begin(GameConstants::RESOURCE_NAMES);
town->primaryRes = static_cast<ui16>(resIter - std::begin(GameConstants::RESOURCE_NAMES));
warMachinesToLoad[town] = source["warMachine"];
town->moatDamage = source["moatDamage"].Float();
town->moatDamage = static_cast<si32>(source["moatDamage"].Float());
// Compatability for <= 0.98f mods
// Compatibility for <= 0.98f mods
if(source["moatHexes"].isNull())
town->moatHexes = CTown::defaultMoatHexes();
else
town->moatHexes = source["moatHexes"].convertTo<std::vector<BattleHex> >();
town->mageLevel = source["mageGuild"].Float();
town->mageLevel = static_cast<ui32>(source["mageGuild"].Float());
town->names = source["names"].convertTo<std::vector<std::string> >();
// Horde building creature level
for(const JsonNode &node : source["horde"].Vector())
town->hordeLvl[town->hordeLvl.size()] = node.Float();
town->hordeLvl[(int)town->hordeLvl.size()] = static_cast<int>(node.Float());
// town needs to have exactly 2 horde entries. Validation will take care of 2+ entries
// but anything below 2 must be handled here
for (size_t i=source["horde"].Vector().size(); i<2; i++)
town->hordeLvl[i] = -1;
town->hordeLvl[(int)i] = -1;
const JsonVector & creatures = source["creatures"].Vector();
@ -650,11 +650,11 @@ void CTownHandler::loadTown(CTown * town, const JsonNode & source)
}
}
town->defaultTavernChance = source["defaultTavern"].Float();
town->defaultTavernChance = static_cast<ui32>(source["defaultTavern"].Float());
/// set chance of specific hero class to appear in this town
for(auto &node : source["tavern"].Struct())
{
int chance = node.second.Float();
int chance = static_cast<int>(node.second.Float());
VLC->modh->identifiers.requestIdentifier(node.second.meta, "heroClass",node.first, [=](si32 classID)
{
@ -664,7 +664,7 @@ void CTownHandler::loadTown(CTown * town, const JsonNode & source)
for(auto &node : source["guildSpells"].Struct())
{
int chance = node.second.Float();
int chance = static_cast<int>(node.second.Float());
VLC->modh->identifiers.requestIdentifier(node.second.meta, "spell", node.first, [=](si32 spellID)
{
@ -692,10 +692,10 @@ void CTownHandler::loadPuzzle(CFaction &faction, const JsonNode &source)
size_t index = faction.puzzleMap.size();
SPuzzleInfo spi;
spi.x = piece["x"].Float();
spi.y = piece["y"].Float();
spi.whenUncovered = piece["index"].Float();
spi.number = index;
spi.x = static_cast<si16>(piece["x"].Float());
spi.y = static_cast<si16>(piece["y"].Float());
spi.whenUncovered = static_cast<ui16>(piece["index"].Float());
spi.number = static_cast<ui16>(index);
// filename calculation
std::ostringstream suffix;
@ -769,7 +769,7 @@ void CTownHandler::loadObject(std::string scope, std::string name, const JsonNod
{
auto object = loadFromJson(data, normalizeIdentifier(scope, "core", name));
object->index = factions.size();
object->index = static_cast<TFaction>(factions.size());
factions.push_back(object);
if (object->town)
@ -808,7 +808,7 @@ void CTownHandler::loadObject(std::string scope, std::string name, const JsonNod
void CTownHandler::loadObject(std::string scope, std::string name, const JsonNode & data, size_t index)
{
auto object = loadFromJson(data, normalizeIdentifier(scope, "core", name));
object->index = index;
object->index = static_cast<TFaction>(index);
if (factions.size() > index)
assert(factions[index] == nullptr); // ensure that this id was not loaded before
else
@ -917,7 +917,7 @@ std::set<TFaction> CTownHandler::getAllowedFactions(bool withTown) const
for (size_t i=0; i<allowed.size(); i++)
if (allowed[i])
allowedFactions.insert(i);
allowedFactions.insert((TFaction)i);
return allowedFactions;
}

View File

@ -461,7 +461,7 @@ int BonusList::totalValue() const
if(hasIndepMin && hasIndepMax)
assert(indepMin < indepMax);
const int notIndepBonuses = boost::count_if(bonuses, [](const std::shared_ptr<Bonus>& b)
const int notIndepBonuses = (int)boost::count_if(bonuses, [](const std::shared_ptr<Bonus>& b)
{
return b->valType != Bonus::INDEPENDENT_MAX && b->valType != Bonus::INDEPENDENT_MIN;
});
@ -1307,7 +1307,7 @@ void CBonusSystemNode::limitBonuses(const BonusList &allBonuses, BonusList &out)
while(true)
{
int undecidedCount = undecided.size();
int undecidedCount = static_cast<int>(undecided.size());
for(int i = 0; i < undecided.size(); i++)
{
auto b = undecided[i];

View File

@ -512,7 +512,7 @@ bool JsonParser::extractFloat(JsonNode &node)
pos++;
}
result = integerPart;
result = static_cast<double>(integerPart);
if (input[pos] == '.')
{
@ -802,7 +802,7 @@ namespace
std::string itemEntryCheck(Validation::ValidationData & validator, const JsonVector items, const JsonNode & schema, size_t index)
{
validator.currentPath.push_back(JsonNode());
validator.currentPath.back().Float() = index;
validator.currentPath.back().Float() = static_cast<double>(index);
auto onExit = vstd::makeScopeGuard([&]()
{
validator.currentPath.pop_back();

View File

@ -168,14 +168,14 @@ void JsonNode::setType(JsonType Type)
//float<->int conversion
if(type == JsonType::DATA_FLOAT && Type == JsonType::DATA_INTEGER)
{
si64 converted = data.Float;
si64 converted = static_cast<si64>(data.Float);
type = Type;
data.Integer = converted;
return;
}
else if(type == JsonType::DATA_INTEGER && Type == JsonType::DATA_FLOAT)
{
double converted = data.Integer;
double converted = static_cast<double>(data.Integer);
type = Type;
data.Float = converted;
return;
@ -249,7 +249,7 @@ bool JsonNode::isCompact() const
return true;
case JsonType::DATA_STRUCT:
{
int propertyCount = data.Struct->size();
auto propertyCount = data.Struct->size();
if(propertyCount == 0)
return true;
else if(propertyCount == 1)
@ -317,7 +317,7 @@ double JsonNode::Float() const
if(type == JsonType::DATA_NULL)
return floatDefault;
else if(type == JsonType::DATA_INTEGER)
return data.Integer;
return static_cast<double>(data.Integer);
assert(type == JsonType::DATA_FLOAT);
return data.Float;
@ -329,7 +329,7 @@ si64 JsonNode::Integer() const
if(type == JsonType::DATA_NULL)
return integetDefault;
else if(type == JsonType::DATA_FLOAT)
return data.Float;
return static_cast<si64>(data.Float);
assert(type == JsonType::DATA_INTEGER);
return data.Integer;
@ -426,9 +426,9 @@ std::string JsonNode::toJson(bool compact) const
void JsonUtils::parseTypedBonusShort(const JsonVector& source, std::shared_ptr<Bonus> dest)
{
dest->val = source[1].Float();
dest->val = static_cast<si32>(source[1].Float());
resolveIdentifier(source[2],dest->subtype);
dest->additionalInfo = source[3].Float();
dest->additionalInfo = static_cast<si32>(source[3].Float());
dest->duration = Bonus::PERMANENT; //TODO: handle flags (as integer)
dest->turnsRemain = 0;
}
@ -479,10 +479,10 @@ void JsonUtils::resolveIdentifier(si32 &var, const JsonNode &node, std::string n
switch (value.getType())
{
case JsonNode::JsonType::DATA_INTEGER:
var = value.Integer();
var = static_cast<si32>(value.Integer());
break;
case JsonNode::JsonType::DATA_FLOAT:
var = value.Float();
var = static_cast<si32>(value.Float());
break;
case JsonNode::JsonType::DATA_STRING:
VLC->modh->identifiers.requestIdentifier(value, [&](si32 identifier)
@ -504,10 +504,10 @@ void JsonUtils::resolveAddInfo(CAddInfo & var, const JsonNode & node)
switch (value.getType())
{
case JsonNode::JsonType::DATA_INTEGER:
var = value.Integer();
var = static_cast<si32>(value.Integer());
break;
case JsonNode::JsonType::DATA_FLOAT:
var = value.Float();
var = static_cast<si32>(value.Float());
break;
case JsonNode::JsonType::DATA_STRING:
VLC->modh->identifiers.requestIdentifier(value, [&](si32 identifier)
@ -524,10 +524,10 @@ void JsonUtils::resolveAddInfo(CAddInfo & var, const JsonNode & node)
switch(vec[i].getType())
{
case JsonNode::JsonType::DATA_INTEGER:
var[i] = vec[i].Integer();
var[i] = static_cast<si32>(vec[i].Integer());
break;
case JsonNode::JsonType::DATA_FLOAT:
var[i] = vec[i].Float();
var[i] = static_cast<si32>(vec[i].Float());
break;
case JsonNode::JsonType::DATA_STRING:
VLC->modh->identifiers.requestIdentifier(vec[i], [&var,i](si32 identifier)
@ -552,10 +552,10 @@ void JsonUtils::resolveIdentifier(const JsonNode &node, si32 &var)
switch (node.getType())
{
case JsonNode::JsonType::DATA_INTEGER:
var = node.Integer();
var = static_cast<si32>(node.Integer());
break;
case JsonNode::JsonType::DATA_FLOAT:
var = node.Float();
var = static_cast<si32>(node.Float());
break;
case JsonNode::JsonType::DATA_STRING:
VLC->modh->identifiers.requestIdentifier(node, [&](si32 identifier)
@ -712,7 +712,7 @@ bool JsonUtils::parseBonus(const JsonNode &ability, Bonus *b)
resolveIdentifier(b->subtype, ability, "subtype");
b->val = ability["val"].Float();
b->val = static_cast<si32>(ability["val"].Float());
value = &ability["valueType"];
if (!value->isNull())
@ -722,9 +722,9 @@ bool JsonUtils::parseBonus(const JsonNode &ability, Bonus *b)
resolveAddInfo(b->additionalInfo, ability);
b->turnsRemain = ability["turns"].Float();
b->turnsRemain = static_cast<si32>(ability["turns"].Float());
b->sid = ability["sourceID"].Float();
b->sid = static_cast<si32>(ability["sourceID"].Float());
b->description = ability["description"].String();
@ -781,9 +781,9 @@ bool JsonUtils::parseBonus(const JsonNode &ability, Bonus *b)
{
std::shared_ptr<GrowsWithLevelUpdater> updater = std::make_shared<GrowsWithLevelUpdater>();
const JsonVector param = updaterJson["parameters"].Vector();
updater->valPer20 = param[0].Integer();
updater->valPer20 = static_cast<int>(param[0].Integer());
if(param.size() > 1)
updater->stepSize = param[1].Integer();
updater->stepSize = static_cast<int>(param[1].Integer());
b->addUpdater(updater);
}
else

View File

@ -278,7 +278,7 @@ namespace JsonDetail
{
static T convertImpl(const JsonNode & node)
{
return node.Float();
return T(node.Float());
}
};

View File

@ -71,7 +71,7 @@ DLL_LINKAGE void SetCommanderProperty::applyGs(CGameState *gs)
commander->specialSKills.insert (additionalInfo);
break;
case SECONDARY_SKILL:
commander->secondarySkills[additionalInfo] = amount;
commander->secondarySkills[additionalInfo] = static_cast<ui8>(amount);
break;
case ALIVE:
if (amount)
@ -635,7 +635,7 @@ DLL_LINKAGE void HeroRecruited::applyGs(CGameState *gs)
gs->hpool.heroesPool.erase(hid);
if(h->id == ObjectInstanceID())
{
h->id = ObjectInstanceID(gs->map->objects.size());
h->id = ObjectInstanceID((si32)gs->map->objects.size());
gs->map->objects.push_back(h);
}
else
@ -721,7 +721,7 @@ DLL_LINKAGE void NewObject::applyGs(CGameState *gs)
o->subID = subID;
o->pos = pos;
o->appearance = VLC->objtypeh->getHandlerFor(o->ID, o->subID)->getTemplates(terrainType).front();
id = o->id = ObjectInstanceID(gs->map->objects.size());
id = o->id = ObjectInstanceID((si32)gs->map->objects.size());
gs->map->objects.push_back(o);
gs->map->addBlockVisTiles(o);

View File

@ -25,7 +25,7 @@ Res::ResourceSet::ResourceSet(const JsonNode & node)
{
reserve(GameConstants::RESOURCE_QUANTITY);
for(std::string name : GameConstants::RESOURCE_NAMES)
push_back(node[name].Float());
push_back((int)node[name].Float());
}
Res::ResourceSet::ResourceSet(TResource wood, TResource mercury, TResource ore, TResource sulfur, TResource crystal,

View File

@ -16,7 +16,7 @@ class CCampaignState;
class CMapInfo;
struct PlayerInfo;
class PlayerColor;
class SharedMemory;
struct SharedMemory;
/// Struct which describes the name, the color, the starting bonus of a player
struct DLL_LINKAGE PlayerSettings

View File

@ -151,7 +151,7 @@ char BattleHex::getDistance(BattleHex hex1, BattleHex hex2)
int y1 = hex1.getY(), y2 = hex2.getY();
// FIXME: Omit floating point arithmetics
int x1 = (hex1.getX() + y1 * 0.5), x2 = (hex2.getX() + y2 * 0.5);
int x1 = (int)(hex1.getX() + y1 * 0.5), x2 = (int)(hex2.getX() + y2 * 0.5);
int xDst = x2 - x1, yDst = y2 - y1;

View File

@ -94,7 +94,7 @@ namespace CGH
std::vector<int> pom;
for(const JsonNode &value : level.Vector())
{
pom.push_back(value.Float());
pom.push_back((int)value.Float());
}
dest.push_back(pom);
@ -264,12 +264,12 @@ BattleInfo * BattleInfo::setupBattle(int3 tile, ETerrainType terrain, BFieldType
auto obstPtr = std::make_shared<CObstacleInstance>();
obstPtr->obstacleType = CObstacleInstance::ABSOLUTE_OBSTACLE;
obstPtr->ID = obidgen.getSuchNumber(appropriateAbsoluteObstacle);
obstPtr->uniqueID = curB->obstacles.size();
obstPtr->uniqueID = static_cast<si32>(curB->obstacles.size());
curB->obstacles.push_back(obstPtr);
for(BattleHex blocked : obstPtr->getBlockedTiles())
blockedTiles.push_back(blocked);
tilesToBlock -= VLC->heroh->absoluteObstacles[obstPtr->ID].blockedTiles.size() / 2;
tilesToBlock -= (int)VLC->heroh->absoluteObstacles[obstPtr->ID].blockedTiles.size() / 2;
}
catch(RangeGenerator::ExhaustedPossibilities &)
{
@ -317,12 +317,12 @@ BattleInfo * BattleInfo::setupBattle(int3 tile, ETerrainType terrain, BFieldType
auto obstPtr = std::make_shared<CObstacleInstance>();
obstPtr->ID = obid;
obstPtr->pos = posgenerator.getSuchNumber(validPosition);
obstPtr->uniqueID = curB->obstacles.size();
obstPtr->uniqueID = static_cast<si32>(curB->obstacles.size());
curB->obstacles.push_back(obstPtr);
for(BattleHex blocked : obstPtr->getBlockedTiles())
blockedTiles.push_back(blocked);
tilesToBlock -= obi.blockedTiles.size();
tilesToBlock -= static_cast<int>(obi.blockedTiles.size());
}
}
catch(RangeGenerator::ExhaustedPossibilities &)
@ -347,11 +347,11 @@ BattleInfo * BattleInfo::setupBattle(int3 tile, ETerrainType terrain, BFieldType
for (auto position : config["commanderPositions"]["field"].Vector())
{
commanderField.push_back (position.Float());
commanderField.push_back ((int)position.Float());
}
for (auto position : config["commanderPositions"]["creBank"].Vector())
{
commanderBank.push_back (position.Float());
commanderBank.push_back ((int)position.Float());
}
@ -444,7 +444,7 @@ BattleInfo * BattleInfo::setupBattle(int3 tile, ETerrainType terrain, BFieldType
auto moat = std::make_shared<MoatObstacle>();
moat->ID = curB->town->subID;
moat->obstacleType = CObstacleInstance::MOAT;
moat->uniqueID = curB->obstacles.size();
moat->uniqueID = static_cast<si32>(curB->obstacles.size());
curB->obstacles.push_back(moat);
}
@ -980,7 +980,7 @@ void BattleInfo::removeUnitBonus(uint32_t id, const std::vector<Bonus> & bonus)
uint32_t BattleInfo::nextUnitId() const
{
return stacks.size();
return static_cast<uint32_t>(stacks.size());
}
void BattleInfo::addOrUpdateUnitBonus(CStack * sta, const Bonus & value, bool forceAdd)

View File

@ -40,7 +40,7 @@ static void retrieveTurretDamageRange(const CGTownInstance * town, const battle:
assert(town);
assert(turret->getPosition() >= -4 && turret->getPosition() <= -2);
const float multiplier = (turret->getPosition() == -2) ? 1 : 0.5;
const float multiplier = (turret->getPosition() == -2) ? 1.0f : 0.5f;
//Revised - Where do below values come from?
/*int baseMin = 6;
@ -579,7 +579,7 @@ std::vector<BattleHex> CBattleInfoCallback::battleGetAvailableHexes(const Reacha
else
{
//Not tactics phase -> destination must be reachable and within unit range.
if(cache.distances[i] > unitSpeed)
if(cache.distances[i] > (int)unitSpeed)
continue;
}
@ -1901,7 +1901,7 @@ int CBattleInfoCallback::battleGetSurrenderCost(PlayerColor Player) const
if(const CGHeroInstance * h = battleGetFightingHero(side))
discount += h->valOfBonuses(Bonus::SURRENDER_DISCOUNT);
ret *= (100.0 - discount) / 100.0;
ret = static_cast<int>(ret * (100.0 - discount) / 100.0);
vstd::amax(ret, 0); //no negative costs for >100% discounts (impossible in original H3 mechanics, but some day...)
return ret;
}

View File

@ -270,7 +270,7 @@ void CHealth::damage(int64_t & amount)
}
else
{
firstHPleft -= amount;
firstHPleft -= static_cast<int32_t>(amount);
}
addResurrected(getCount() - oldCount);
@ -317,7 +317,7 @@ void CHealth::setFromTotal(const int64_t totalHealth)
{
const int32_t unitHealth = owner->MaxHealth();
firstHPleft = totalHealth % unitHealth;
fullUnits = totalHealth / unitHealth;
fullUnits = static_cast<int32_t>(totalHealth / unitHealth);
if(firstHPleft == 0 && fullUnits >= 1)
{
@ -696,7 +696,7 @@ int CUnitState::getAttack(bool ranged) const
{
double frenzyPower = (double)inFrenzy->totalValue() / 100;
frenzyPower *= (double) (ranged ? defence.getRangedValue() : defence.getMeleeValue());
ret += frenzyPower;
ret += static_cast<int>(frenzyPower);
}
vstd::amax(ret, 0);

View File

@ -102,7 +102,7 @@ void CArchiveLoader::initVIDArchive(const std::string &mountPoint, CFileInputStr
offsets.insert(entry.offset);
entries[ResourceID(mountPoint + entry.name)] = entry;
}
offsets.insert(fileStream.getSize());
offsets.insert((int)fileStream.getSize());
// now when we know position of all files their sizes can be set correctly
for (auto & entry : entries)

View File

@ -53,7 +53,7 @@ si64 CBinaryReader::read(ui8 * data, si64 size)
si64 bytesRead = stream->read(data, size);
if(bytesRead != size)
{
throw std::runtime_error(getEndOfStreamExceptionMsg(size));
throw std::runtime_error(getEndOfStreamExceptionMsg((long)size));
}
return bytesRead;
}

View File

@ -60,7 +60,7 @@ si64 CBufferedStream::getSize()
void CBufferedStream::ensureSize(si64 size)
{
while (buffer.size() < size && !endOfFileReached)
while ((si64)buffer.size() < size && !endOfFileReached)
{
si64 initialSize = buffer.size();
si64 currentStep = std::min<si64>(size, buffer.size());
@ -125,7 +125,7 @@ si64 CCompressedStream::readMore(ui8 *data, si64 size)
int decompressed = inflateState->total_out;
inflateState->avail_out = size;
inflateState->avail_out = (uInt)size;
inflateState->next_out = data;
do
@ -138,7 +138,7 @@ si64 CCompressedStream::readMore(ui8 *data, si64 size)
if (availSize != compressedBuffer.size())
gzipStream.reset();
inflateState->avail_in = availSize;
inflateState->avail_in = (uInt)availSize;
inflateState->next_in = compressedBuffer.data();
}

View File

@ -32,7 +32,7 @@ CZipStream::~CZipStream()
si64 CZipStream::readMore(ui8 * data, si64 size)
{
return unzReadCurrentFile(file, data, size);
return unzReadCurrentFile(file, data, (unsigned int)size);
}
si64 CZipStream::getSize()
@ -80,7 +80,7 @@ std::unordered_map<ResourceID, unz64_file_pos> CZipLoader::listFiles(const std::
filename.resize(info.size_filename);
// Get name of current file. Contrary to docs "info" parameter can't be null
unzGetCurrentFileInfo64 (file, &info, filename.data(), filename.size(), nullptr, 0, nullptr, 0);
unzGetCurrentFileInfo64 (file, &info, filename.data(), (uLong)filename.size(), nullptr, 0, nullptr, 0);
std::string filenameString(filename.data(), filename.size());
unzGetFilePos64(file, &ret[ResourceID(mountPoint + filenameString)]);
@ -128,7 +128,7 @@ static bool extractCurrent(unzFile file, std::ostream & where)
while (1)
{
int readSize = unzReadCurrentFile(file, buffer.data(), buffer.size());
int readSize = unzReadCurrentFile(file, buffer.data(), (unsigned int)buffer.size());
if (readSize < 0) // error
break;
@ -166,7 +166,7 @@ std::vector<std::string> ZipArchive::listFiles(boost::filesystem::path filename)
zipFilename.resize(info.size_filename);
// Get name of current file. Contrary to docs "info" parameter can't be null
unzGetCurrentFileInfo64 (file, &info, zipFilename.data(), zipFilename.size(), nullptr, 0, nullptr, 0);
unzGetCurrentFileInfo64 (file, &info, zipFilename.data(), (uLong)zipFilename.size(), nullptr, 0, nullptr, 0);
ret.push_back(std::string(zipFilename.data(), zipFilename.size()));
}

Some files were not shown because too many files have changed in this diff Show More