diff --git a/AI/EmptyAI/CEmptyAI.cpp b/AI/EmptyAI/CEmptyAI.cpp index 27638a378..f7b29f3fe 100644 --- a/AI/EmptyAI/CEmptyAI.cpp +++ b/AI/EmptyAI/CEmptyAI.cpp @@ -25,12 +25,12 @@ void CEmptyAI::yourTurn() void CEmptyAI::heroGotLevel(const CGHeroInstance *hero, PrimarySkill::PrimarySkill pskill, std::vector &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 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 &components, QueryID askID, const int soundID, bool selection, bool cancel) diff --git a/AI/StupidAI/StupidAI.cpp b/AI/StupidAI/StupidAI.cpp index 62affac5b..0a7b66c8e 100644 --- a/AI/StupidAI/StupidAI.cpp +++ b/AI/StupidAI/StupidAI.cpp @@ -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((dmg.first + dmg.second) / 2); + adr = static_cast((retal.first + retal.second) / 2); } bool operator==(const EnemyInfo& ei) const diff --git a/AI/VCAI/FuzzyEngines.cpp b/AI/VCAI/FuzzyEngines.cpp index 10c4e6c94..b5f0bb36a 100644 --- a/AI/VCAI/FuzzyEngines.cpp +++ b/AI/VCAI/FuzzyEngines.cpp @@ -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(walkersStrength / totalStrength); + as.shooters = static_cast(shootersStrength / totalStrength); + as.flyers = static_cast(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((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(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(value->getValue()); } catch(fl::Exception & fe) { diff --git a/AI/VCAI/FuzzyHelper.cpp b/AI/VCAI/FuzzyHelper.cpp index b4457fd98..252d05c5c 100644 --- a/AI/VCAI/FuzzyHelper.cpp +++ b/AI/VCAI/FuzzyHelper.cpp @@ -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(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(objectDanger * tacticalAdvantage); //this line tends to go infinite for allied towns (?) } } if(dangerousObject->ID == Obj::SUBTERRANEAN_GATE) diff --git a/AI/VCAI/Goals/BuyArmy.cpp b/AI/VCAI/Goals/BuyArmy.cpp index e986d7a88..cf5f1bb39 100644 --- a/AI/VCAI/Goals/BuyArmy.cpp +++ b/AI/VCAI/Goals/BuyArmy.cpp @@ -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(value * 0.4f); //some approximate value return ai->ah->whatToDo(price, iAmElementar()); //buy right now or gather resources } diff --git a/AI/VCAI/Goals/Explore.cpp b/AI/VCAI/Goals/Explore.cpp index b25beb9be..4a3a59359 100644 --- a/AI/VCAI/Goals/Explore.cpp +++ b/AI/VCAI/Goals/Explore.cpp @@ -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 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 diff --git a/AI/VCAI/Goals/GatherArmy.cpp b/AI/VCAI/Goals/GatherArmy.cpp index 826037689..df6620a81 100644 --- a/AI/VCAI/Goals/GatherArmy.cpp +++ b/AI/VCAI/Goals/GatherArmy.cpp @@ -148,7 +148,7 @@ TGoalVec GatherArmy::getAllPossibleSubgoals() { auto dwelling = dynamic_cast(obj); - ui32 val = std::min(value, ai->ah->howManyReinforcementsCanBuy(hero.get(), dwelling)); + ui32 val = std::min((ui32)value, (ui32)ai->ah->howManyReinforcementsCanBuy(hero.get(), dwelling)); if(val) { diff --git a/AI/VCAI/Goals/VisitObj.cpp b/AI/VCAI/Goals/VisitObj.cpp index 18bac7401..4cbfd1465 100644 --- a/AI/VCAI/Goals/VisitObj.cpp +++ b/AI/VCAI/Goals/VisitObj.cpp @@ -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()) diff --git a/AI/VCAI/Goals/VisitTile.cpp b/AI/VCAI/Goals/VisitTile.cpp index f6bbc3e76..30c2429d0 100644 --- a/AI/VCAI/Goals/VisitTile.cpp +++ b/AI/VCAI/Goals/VisitTile.cpp @@ -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)); } } diff --git a/AI/VCAI/Pathfinding/AINodeStorage.h b/AI/VCAI/Pathfinding/AINodeStorage.h index 6130e4e10..31c1c8c3a 100644 --- a/AI/VCAI/Pathfinding/AINodeStorage.h +++ b/AI/VCAI/Pathfinding/AINodeStorage.h @@ -17,8 +17,6 @@ #include "../Goals/AbstractGoal.h" #include "Actions/ISpecialAction.h" -struct AIPathNode; - struct AIPathNode : public CGPathNode { uint32_t chainMask; diff --git a/AI/VCAI/Pathfinding/Actions/BoatActions.cpp b/AI/VCAI/Pathfinding/Actions/BoatActions.cpp index ce598ce10..f6077d3f0 100644 --- a/AI/VCAI/Pathfinding/Actions/BoatActions.cpp +++ b/AI/VCAI/Pathfinding/Actions/BoatActions.cpp @@ -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 diff --git a/AI/VCAI/Pathfinding/Actions/ISpecialAction.h b/AI/VCAI/Pathfinding/Actions/ISpecialAction.h index 52c8d0725..c8943aaa5 100644 --- a/AI/VCAI/Pathfinding/Actions/ISpecialAction.h +++ b/AI/VCAI/Pathfinding/Actions/ISpecialAction.h @@ -13,7 +13,7 @@ #include "../../AIUtility.h" #include "../../Goals/AbstractGoal.h" -class AIPathNode; +struct AIPathNode; class ISpecialAction { diff --git a/AI/VCAI/Pathfinding/PathfindingManager.cpp b/AI/VCAI/Pathfinding/PathfindingManager.cpp index 61e010d50..d0b19519b 100644 --- a/AI/VCAI/Pathfinding/PathfindingManager.cpp +++ b/AI/VCAI/Pathfinding/PathfindingManager.cpp @@ -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; diff --git a/AI/VCAI/Pathfinding/Rules/AILayerTransitionRule.cpp b/AI/VCAI/Pathfinding/Rules/AILayerTransitionRule.cpp index 7a1fae0dc..fe9878a22 100644 --- a/AI/VCAI/Pathfinding/Rules/AILayerTransitionRule.cpp +++ b/AI/VCAI/Pathfinding/Rules/AILayerTransitionRule.cpp @@ -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) { diff --git a/AI/VCAI/VCAI.cpp b/AI/VCAI/VCAI.cpp index 9f54af911..6a0e0f6f2 100644 --- a/AI/VCAI/VCAI.cpp +++ b/AI/VCAI/VCAI.cpp @@ -631,7 +631,7 @@ void VCAI::showBlockingDialog(const std::string & text, const std::vector take the last one (they're indexed [1-size]) - sel = components.size(); + sel = static_cast(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(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(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 lock(mx); - return remainingQueries.size(); + return static_cast(remainingQueries.size()); } void AIStatus::startedTurn() diff --git a/CMakeLists.txt b/CMakeLists.txt index 5925051cb..858510dc2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -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") diff --git a/Global.h b/Global.h index a1f62ae3a..ed0bc63dd 100644 --- a/Global.h +++ b/Global.h @@ -342,7 +342,7 @@ namespace vstd template 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 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 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 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 bool iswithin(const t1 &value, const t2 &min, const t3 &max) { - return value >= min && value <= max; + return value >= (t1)min && value <= (t1)max; } template diff --git a/client/CBitmapHandler.cpp b/client/CBitmapHandler.cpp index b92a97c39..563e20ac9 100644 --- a/client/CBitmapHandler.cpp +++ b/client/CBitmapHandler.cpp @@ -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; ipixels + 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; ipixels + 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) { diff --git a/client/CMT.cpp b/client/CMT.cpp index f21de7d5b..4c0a76e90 100644 --- a/client/CMT.cpp +++ b/client/CMT.cpp @@ -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__ diff --git a/client/CMessage.cpp b/client/CMessage.cpp index 71f1df693..f9ec7fa02 100644 --- a/client/CMessage.cpp +++ b/client/CMessage.cpp @@ -144,8 +144,8 @@ std::vector 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 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> & SComps, int maxw, bool blitOr) { - int orWidth = graphics->fonts[FONT_MEDIUM]->getStringWidth(CGI->generaltexth->allTexts[4]); + int orWidth = static_cast(graphics->fonts[FONT_MEDIUM]->getStringWidth(CGI->generaltexth->allTexts[4])); w = h = 0; if(SComps.empty()) @@ -440,7 +440,7 @@ ComponentsToBlit::ComponentsToBlit(std::vector> & 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(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; } diff --git a/client/CMusicHandler.cpp b/client/CMusicHandler.cpp index b22f543c1..3c12e3ebe 100644 --- a/client/CMusicHandler.cpp +++ b/client/CMusicHandler.cpp @@ -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(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(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(): diff --git a/client/CPlayerInterface.cpp b/client/CPlayerInterface.cpp index defe847c5..8c071b801 100644 --- a/client/CPlayerInterface.cpp +++ b/client/CPlayerInterface.cpp @@ -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(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(settings["session"]["spectate-hero-speed"].Integer()); } else if (makingTurn) // our turn, our hero moves - speed = settings["adventure"]["heroSpeed"].Float(); + speed = static_cast(settings["adventure"]["heroSpeed"].Float()); else - speed = settings["adventure"]["enemySpeed"].Float(); + speed = static_cast(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; diff --git a/client/CServerHandler.cpp b/client/CServerHandler.cpp index 262aec497..9761ad124 100644 --- a/client/CServerHandler.cpp +++ b/client/CServerHandler.cpp @@ -288,9 +288,9 @@ bool CServerHandler::isGuest() const ui16 CServerHandler::getDefaultPort() { if(settings["session"]["serverport"].Integer()) - return settings["session"]["serverport"].Integer(); + return static_cast(settings["session"]["serverport"].Integer()); else - return settings["server"]["port"].Integer(); + return static_cast(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(connectedId); auto color = PlayerColor(boost::lexical_cast(playerColorId)); diff --git a/client/CVideoHandler.cpp b/client/CVideoHandler.cpp index 6f3fa8351..e60e10d38 100644 --- a/client/CVideoHandler.cpp +++ b/client/CVideoHandler.cpp @@ -43,7 +43,7 @@ static int lodRead(void* opaque, uint8_t* buf, int size) { auto video = reinterpret_cast(opaque); - return video->data->read(buf, size); + return static_cast(video->data->read(buf, size)); } static si64 lodSeek(void * opaque, si64 pos, int whence) diff --git a/client/Client.cpp b/client/Client.cpp index a5b166817..4839b5122 100644 --- a/client/Client.cpp +++ b/client/Client.cpp @@ -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(playerint.size()); h & players; for(auto i = playerint.begin(); i != playerint.end(); i++) diff --git a/client/Client.h b/client/Client.h index ccd822009..68e3843b7 100644 --- a/client/Client.h +++ b/client/Client.h @@ -26,7 +26,7 @@ class CBattleGameInterface; class CGameState; class CGameInterface; class CCallback; -struct BattleAction; +class BattleAction; class CClient; class CScriptingModule; struct CPathsInfo; diff --git a/client/CreatureCostBox.cpp b/client/CreatureCostBox.cpp index ca1e070f9..a6acb8bc7 100644 --- a/client/CreatureCostBox.cpp +++ b/client/CreatureCostBox.cpp @@ -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)) { diff --git a/client/Graphics.cpp b/client/Graphics.cpp index db17d6a51..236e5c52c 100644 --- a/client/Graphics.cpp +++ b/client/Graphics.cpp @@ -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(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(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(index); entry["file"].String() = imageName; imageLists["SPRITES/" + listName]["images"].Vector().push_back(entry); diff --git a/client/battle/CBattleAnimations.cpp b/client/battle/CBattleAnimations.cpp index b91535596..cdedab652 100644 --- a/client/battle/CBattleAnimations.cpp +++ b/client/battle/CBattleAnimations.cpp @@ -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(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(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(bestID); // Set projectile animation start delay which is specified in frames spi.animStartDelay = shooterInfo->animation.attackClimaxFrame; diff --git a/client/battle/CBattleInterface.cpp b/client/battle/CBattleInterface.cpp index a56b353c2..e76eece9f 100644 --- a/client/battle/CBattleInterface.cpp +++ b/client/battle/CBattleInterface.cpp @@ -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; gformat->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((colorsToChange+g)->r) *rCor; - (colorsToChange+g)->g = static_cast((colorsToChange+g)->g) *gCor; - (colorsToChange+g)->b = static_cast((colorsToChange+g)->b) *bCor; + color->r = static_cast(color->r * rCor); + color->g = static_cast(color->g * gCor); + color->b = static_cast(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(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(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 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(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(vstd::round(settings["session"]["spectate-battle-speed"].Float() *100)); - return vstd::round(settings["battle"]["animationSpeed"].Float() *100); + return static_cast(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(it->x - dst.w / 2); + dst.y = static_cast(it->y - dst.h / 2); image->draw(to, &dst, nullptr); } @@ -3426,7 +3429,7 @@ void CBattleInterface::showBattleEffects(SDL_Surface *to, const std::vectorcurrentFrame); + int currentFrame = static_cast(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(pendingAnims.size()); for (auto it = pendingAnims.begin(); it != pendingAnims.end(); ++it) { if (it->first == nullptr) diff --git a/client/battle/CBattleInterfaceClasses.cpp b/client/battle/CBattleInterfaceClasses.cpp index 428c38b67..02689ecdb 100644 --- a/client/battle/CBattleInterfaceClasses.cpp +++ b/client/battle/CBattleInterfaceClasses.cpp @@ -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(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; diff --git a/client/battle/CCreatureAnimation.cpp b/client/battle/CCreatureAnimation.cpp index 50b28988c..6f72451b3 100644 --- a/client/battle/CCreatureAnimation.cpp +++ b/client/battle/CCreatureAnimation.cpp @@ -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(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(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(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(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(settings["battle"]["animationSpeed"].Float() * 100); } float AnimationControls::getSpellEffectSpeed() { - return settings["battle"]["animationSpeed"].Float() * 30; + return static_cast(settings["battle"]["animationSpeed"].Float() * 30); } float AnimationControls::getMovementDuration(const CCreature * creature) { - return settings["battle"]["animationSpeed"].Float() * 4 / creature->animation.walkAnimationTime; + return static_cast(settings["battle"]["animationSpeed"].Float() * 4 / creature->animation.walkAnimationTime); } float AnimationControls::getFlightDistance(const CCreature * creature) { - return creature->animation.flightAnimationDistance * 200; + return static_cast(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(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(floor(currentFrame)); std::shared_ptr 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(forward->size(group)); } bool CCreatureAnimation::isDead() const diff --git a/client/gui/CAnimation.cpp b/client/gui/CAnimation.cpp index 4335257d2..035a978ac 100644 --- a/client/gui/CAnimation.cpp +++ b/client/gui/CAnimation.cpp @@ -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(jsonMargins["left"].Integer()); + margins.y = static_cast(jsonMargins["top"].Integer()); - fullSize.x = conf["width"].Integer(); - fullSize.y = conf["height"].Integer(); + fullSize.x = static_cast(conf["width"].Integer()); + fullSize.y = static_cast(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 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(sourceRect), targetSurface, destRect); //FIXME CSDL_Ext::setAlpha(fadingSurface, 255); } diff --git a/client/gui/CCursorHandler.cpp b/client/gui/CCursorHandler.cpp index e5b97de87..43e5999ad 100644 --- a/client/gui/CCursorHandler.cpp +++ b/client/gui/CCursorHandler.cpp @@ -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((screen->w / 2.) - (currentCursor->pos.w / 2.)); + this->ypos = static_cast((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); diff --git a/client/gui/CGuiHandler.cpp b/client/gui/CGuiHandler.cpp index b915f0cab..6fc54ba70 100644 --- a/client/gui/CGuiHandler.cpp +++ b/client/gui/CGuiHandler.cpp @@ -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(ceil(1000.0 / (accumulatedTime/accumulatedFrames))); accumulatedTime = 0; accumulatedFrames = 0; } diff --git a/client/gui/Fonts.cpp b/client/gui/Fonts.cpp index 9b8c0f648..3d0654150 100644 --- a/client/gui/Fonts.cpp +++ b/client/gui/Fonts.cpp @@ -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 & 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 & 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, ui64> CTrueTypeFont::loadData(const JsonNode & TTF_Font * CTrueTypeFont::loadFont(const JsonNode &config) { - int pointSize = config["size"].Float(); + int pointSize = static_cast(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(0, clipRect.y - posY); - int lineEnd = std::min(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(0, clipRect.x - posX); - int rowEnd = std::min(size, clipRect.x + clipRect.w - posX); + int rowEnd = std::min((int)size, clipRect.x + clipRect.w - posX); //for each line in symbol for(int dy = lineBegin; dy 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. diff --git a/client/gui/SDL_Extensions.cpp b/client/gui/SDL_Extensions.cpp index 711bc71fd..da9b4b165 100644 --- a/client/gui/SDL_Extensions.cpp +++ b/client/gui/SDL_Extensions.cpp @@ -538,7 +538,7 @@ void CSDL_Ext::applyEffectBpp( SDL_Surface * surf, const SDL_Rect * rect, int mo int r = Channels::px::r.get(pixel); int g = Channels::px::g.get(pixel); int b = Channels::px::b.get(pixel); - int gray = 0.299 * r + 0.587 * g + 0.114 *b; + int gray = static_cast(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::g.get(pixel); int b = Channels::px::b.get(pixel); - int gray = 0.299 * r + 0.587 * g + 0.114 *b; + int gray = static_cast(0.299 * r + 0.587 * g + 0.114 *b); vstd::amax(gray, 255); Channels::px::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(floor(factorX * x)), + origY = static_cast(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::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(PX(r, p11) * w11 + PX(r, p12) * w12 + PX(r, p21) * w21 + PX(r, p22) * w22); + int resG = static_cast(PX(g, p11) * w11 + PX(g, p12) * w12 + PX(g, p21) * w21 + PX(g, p22) * w22); + int resB = static_cast(PX(b, p11) * w11 + PX(b, p12) * w12 + PX(b, p21) * w21 + PX(b, p22) * w22); + int resA = static_cast(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; diff --git a/client/lobby/CBonusSelection.cpp b/client/lobby/CBonusSelection.cpp index f585b8af4..02d712521 100644 --- a/client/lobby/CBonusSelection.cpp +++ b/client/lobby/CBonusSelection.cpp @@ -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(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(desc["x"].Float()); + rd.ypos = static_cast(desc["y"].Float()); sc.regions.push_back(rd); } diff --git a/client/lobby/CBonusSelection.h b/client/lobby/CBonusSelection.h index 948727a07..9cc819748 100644 --- a/client/lobby/CBonusSelection.h +++ b/client/lobby/CBonusSelection.h @@ -10,7 +10,7 @@ #pragma once #include "../windows/CWindowObject.h" -class SDL_Surface; +struct SDL_Surface; class CCampaignState; class CButton; class CTextBox; diff --git a/client/lobby/CLobbyScreen.cpp b/client/lobby/CLobbyScreen.cpp index 4406f2865..dc99e6c2e 100644 --- a/client/lobby/CLobbyScreen.cpp +++ b/client/lobby/CLobbyScreen.cpp @@ -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(...) diff --git a/client/lobby/CSelectionBase.cpp b/client/lobby/CSelectionBase.cpp index 9afb617b5..8c45e8c15 100644 --- a/client/lobby/CSelectionBase.cpp +++ b/client/lobby/CSelectionBase.cpp @@ -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(graphics->fonts[FONT_SMALL]->getLineHeight()); inputBox = std::make_shared(Rect(0, rect.h - height, rect.w, height)); inputBox->removeUsedEvents(KEYBOARD); chatHistory = std::make_shared("", 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(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 ico } } - int curx = 128 - 9 * flags.size(); + int curx = 128 - 9 * (int)flags.size(); for(auto & flag : flags) { iconsFlags.push_back(std::make_shared(icons, flag, 0, curx, 75 + 50 * i)); diff --git a/client/lobby/OptionsTab.cpp b/client/lobby/OptionsTab.cpp index aacf2419a..be402a217 100644 --- a/client/lobby/OptionsTab.cpp +++ b/client/lobby/OptionsTab.cpp @@ -40,15 +40,15 @@ OptionsTab::OptionsTab() background = std::make_shared("ADVOPTBK", 0, 6); pos = background->pos; labelTitle = std::make_shared(222, 30, FONT_BIG, CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[515]); - labelSubTitle = std::make_shared(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(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(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(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(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(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(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(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(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(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(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(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(222, 538, FONT_SMALL, EAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[521]); labelTurnDurationValue = std::make_shared(319, 559, FONT_SMALL, EAlignment::CENTER, Colors::WHITE); } @@ -466,7 +466,7 @@ OptionsTab::PlayerOptionsEntry::PlayerOptionsEntry(const PlayerSettings & S) background = std::make_shared(BitmapHandler::loadBitmap(bgs[s.color.getNum()]), 0, 0, true); labelPlayerName = std::make_shared(55, 10, EFonts::FONT_SMALL, EAlignment::CENTER, Colors::WHITE, s.name); - labelWhoCanPlay = std::make_shared(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(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) { diff --git a/client/lobby/SelectionTab.cpp b/client/lobby/SelectionTab.cpp index 6d85bcc2d..d92abf5a1 100644 --- a/client/lobby/SelectionTab.cpp +++ b/client/lobby/SelectionTab.cpp @@ -185,7 +185,7 @@ SelectionTab::SelectionTab(ESelectionScreen Type) listItems.push_back(std::make_shared(Point(30, 129 + i * 25), iconsMapFormats, iconsVictoryCondition, iconsLossCondition)); labelTabTitle = std::make_shared(205, 28, FONT_MEDIUM, EAlignment::CENTER, Colors::YELLOW, tabTitle); - slider = std::make_shared(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(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) { diff --git a/client/mainmenu/CCampaignScreen.cpp b/client/mainmenu/CCampaignScreen.cpp index 670f2a49c..ea79cd775 100644 --- a/client/mainmenu/CCampaignScreen.cpp +++ b/client/mainmenu/CCampaignScreen.cpp @@ -77,17 +77,17 @@ std::shared_ptr CCampaignScreen::createExitButton(const JsonNode & butt { std::pair 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(Point(button["x"].Float(), button["y"].Float()), button["name"].String(), help, [=](){ close();}, button["hotkey"].Float()); + return std::make_shared(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(config["x"].Float()); + pos.y += static_cast(config["y"].Float()); pos.w = 200; pos.h = 116; diff --git a/client/mainmenu/CCampaignScreen.h b/client/mainmenu/CCampaignScreen.h index 159d26f52..d990f51bd 100644 --- a/client/mainmenu/CCampaignScreen.h +++ b/client/mainmenu/CCampaignScreen.h @@ -12,7 +12,7 @@ class CLabel; class CPicture; class CButton; -class SDL_Surface; +struct SDL_Surface; class JsonNode; class CCampaignScreen : public CWindowObject diff --git a/client/mainmenu/CMainMenu.cpp b/client/mainmenu/CMainMenu.cpp index 692402598..0ec51b780 100644 --- a/client/mainmenu/CMainMenu.cpp +++ b/client/mainmenu/CMainMenu.cpp @@ -109,7 +109,7 @@ std::shared_ptr 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 CMenuEntry::createButton(CMenuScreen * parent, const Js std::pair 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(button["x"].Float()); if(posx < 0) posx = pos.w + posx; - int posy = button["y"].Float(); + int posy = static_cast(button["y"].Float()); if(posy < 0) posy = pos.h + posy; - return std::make_shared(Point(posx, posy), button["name"].String(), help, command, button["hotkey"].Float()); + return std::make_shared(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::create() std::shared_ptr CMainMenu::createPicture(const JsonNode & config) { - return std::make_shared(config["name"].String(), config["x"].Float(), config["y"].Float()); + return std::make_shared(config["name"].String(), (int)config["x"].Float(), (int)config["y"].Float()); } CMultiMode::CMultiMode(ESelectionScreen ScreenType) diff --git a/client/mainmenu/CPrologEpilogVideo.h b/client/mainmenu/CPrologEpilogVideo.h index 1f6417d0d..b0a095da5 100644 --- a/client/mainmenu/CPrologEpilogVideo.h +++ b/client/mainmenu/CPrologEpilogVideo.h @@ -12,7 +12,7 @@ #include "../../lib/mapping/CCampaignHandler.h" class CMultiLineLabel; -class SDL_Surface; +struct SDL_Surface; class CPrologEpilogVideo : public CWindowObject { diff --git a/client/mainmenu/CreditsScreen.h b/client/mainmenu/CreditsScreen.h index cb06407bc..b91e3e2d8 100644 --- a/client/mainmenu/CreditsScreen.h +++ b/client/mainmenu/CreditsScreen.h @@ -12,7 +12,7 @@ #include "../windows/CWindowObject.h" class CMultiLineLabel; -class SDL_Surface; +struct SDL_Surface; class CreditsScreen : public CIntObject { diff --git a/client/mapHandler.cpp b/client/mapHandler.cpp index fc9a66106..c90772443 100644 --- a/client/mapHandler.cpp +++ b/client/mapHandler.cpp @@ -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); diff --git a/client/mapHandler.h b/client/mapHandler.h index 9321ef311..72f094904 100644 --- a/client/mapHandler.h +++ b/client/mapHandler.h @@ -150,7 +150,7 @@ public: } int size() const { - return inver.size(); + return static_cast(inver.size()); } private: diff --git a/client/widgets/AdventureMapClasses.cpp b/client/widgets/AdventureMapClasses.cpp index 39766e2ed..5113df340 100644 --- a/client/widgets/AdventureMapClasses.cpp +++ b/client/widgets/AdventureMapClasses.cpp @@ -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(Point(0, 0), btnUp, CGI->generaltexth->zelp[helpUp]); - scrollDown = std::make_shared(Point(0, scrollUp->pos.h + 32*size), btnDown, CGI->generaltexth->zelp[helpDown]); + scrollDown = std::make_shared(Point(0, scrollUp->pos.h + 32*(int)size), btnDown, CGI->generaltexth->zelp[helpDown]); listBox = std::make_shared(create, Point(1,scrollUp->pos.h), Point(0, 32), size, listAmount); @@ -150,7 +150,7 @@ void CList::select(std::shared_ptr which) int CList::getSelectedIndex() { - return listBox->getIndexOf(selected); + return static_cast(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(toX + stepX * tile.x); + y = static_cast(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(currX); + int yBegin = static_cast(currY); + int xEnd = static_cast(currX + stepX); + int yEnd = static_cast(currY + stepY); for (int y=yBegin; y > 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(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("itmtl", i, 0, 6 + 42 * i , 11)); + hallIcons.push_back(std::make_shared("itmtl", i, 0, 6 + 42 * (int)i , 11)); if(halls[i]) - hallLabels.push_back(std::make_shared( 26 + 42 * i, 64, FONT_SMALL, CENTER, Colors::WHITE, boost::lexical_cast(halls[i]))); + hallLabels.push_back(std::make_shared( 26 + 42 * (int)i, 64, FONT_SMALL, CENTER, Colors::WHITE, boost::lexical_cast(halls[i]))); } } @@ -980,7 +980,7 @@ void CInGameConsole::show(SDL_Surface * to) { int number = 0; - std::vector >::iterator> toDel; + std::vector >::iterator> toDel; boost::unique_lock 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(previouslyEntered.size() - 1); enteredText = previouslyEntered[prevEntDisp] + "_"; refreshEnteredText(); } diff --git a/client/widgets/AdventureMapClasses.h b/client/widgets/AdventureMapClasses.h index 2fe8ede48..d87c58a81 100644 --- a/client/widgets/AdventureMapClasses.h +++ b/client/widgets/AdventureMapClasses.h @@ -400,7 +400,7 @@ public: class CInGameConsole : public CIntObject { private: - std::list< std::pair< std::string, int > > texts; //list + std::list< std::pair< std::string, Uint32 > > texts; //list 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 diff --git a/client/widgets/Buttons.cpp b/client/widgets/Buttons.cpp index d50e3cf0a..fd9ca05d0 100644 --- a/client/widgets/Buttons.cpp +++ b/client/widgets/Buttons.cpp @@ -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(std::make_shared(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(animImage->size()) / 100.0); + moveTo((int)(value * static_cast(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(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(pos.w) * animImage->size(); + int index = static_cast(px / static_cast(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(value) / positions; part*=(pos.w-48); - int newPos = part + pos.x + 16 - slider->pos.x; + int newPos = static_cast(part + pos.x + 16 - slider->pos.x); slider->moveBy(Point(newPos, 0)); } else @@ -627,7 +627,7 @@ void CSlider::updateSliderPos() { double part = static_cast(value) / positions; part*=(pos.h-48); - int newPos = part + pos.y + 16 - slider->pos.y; + int newPos = static_cast(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) diff --git a/client/widgets/CArtifactHolder.cpp b/client/widgets/CArtifactHolder.cpp index 822455eca..ad79022ef 100644 --- a/client/widgets/CArtifactHolder.cpp +++ b/client/widgets/CArtifactHolder.cpp @@ -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(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 for(size_t s=0; sourOwner = 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(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(Point(403 + 46 * s, 365)); diff --git a/client/widgets/CComponent.cpp b/client/widgets/CComponent.cpp index 6620fe4ed..6f6a49598 100644 --- a/client/widgets/CComponent.cpp +++ b/client/widgets/CComponent.cpp @@ -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 textLines = CMessage::breakText(getSubtitle(), std::max(80, pos.w), font); for(auto & line : textLines) { - int height = graphics->fonts[font]->getLineHeight(); + int height = static_cast(graphics->fonts[font]->getLineHeight()); auto label = std::make_shared(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 newSe int CComponentBox::selectedIndex() { if (selected) - return std::find(components.begin(), components.end(), selected) - components.begin(); + return static_cast(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; diff --git a/client/widgets/Images.cpp b/client/widgets/Images.cpp index 5577ba886..cab929bc8 100644 --- a/client/widgets/Images.cpp +++ b/client/widgets/Images.cpp @@ -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()) { diff --git a/client/widgets/MiscWidgets.cpp b/client/widgets/MiscWidgets.cpp index c7880daef..4aae4578a 100644 --- a/client/widgets/MiscWidgets.cpp +++ b/client/widgets/MiscWidgets.cpp @@ -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(75 + 28 * i, 58, FONT_SMALL, CENTER, Colors::WHITE, + labels.push_back(std::make_shared(75 + 28 * (int)i, 58, FONT_SMALL, CENTER, Colors::WHITE, boost::lexical_cast(hero.details->primskills[i]))); labels.push_back(std::make_shared(158, 98, FONT_TINY, CENTER, Colors::WHITE, boost::lexical_cast(hero.details->mana))); diff --git a/client/widgets/ObjectLists.cpp b/client/widgets/ObjectLists.cpp index 91300898b..0a2da112c 100644 --- a/client/widgets/ObjectLists.cpp +++ b/client/widgets/ObjectLists.cpp @@ -87,7 +87,7 @@ CListBox::CListBox(CreateFunc create, Point Pos, Point ItemOffset, size_t Visibl { OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE); slider = std::make_shared(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(); } diff --git a/client/widgets/TextControls.cpp b/client/widgets/TextControls.cpp index 9e095005c..00b7a4354 100644 --- a/client/widgets/TextControls.cpp +++ b/client/widgets/TextControls.cpp @@ -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(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(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(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(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); diff --git a/client/windows/CAdvmapInterface.cpp b/client/windows/CAdvmapInterface.cpp index ffde55028..4372266f4 100644 --- a/client/windows/CAdvmapInterface.cpp +++ b/client/windows/CAdvmapInterface.cpp @@ -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(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(CGI->mh->tilesW / 2 / worldViewScale); + on.y -= static_cast(CGI->mh->tilesH / 2 / worldViewScale); break; } diff --git a/client/windows/CCastleInterface.cpp b/client/windows/CCastleInterface.cpp index bb4ebfd87..883b524ae 100644 --- a/client/windows/CCastleInterface.cpp +++ b/client/windows/CCastleInterface.cpp @@ -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(a.r * f + b.r * (1 - f)); + ret.g = static_cast(a.g * f + b.g * (1 - f)); + ret.b = static_cast(a.b * f + b.b * (1 - f)); + ret.a = static_cast(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; imoveBy(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(Point(14+55*i, 459), town, i)); + creainfo.push_back(std::make_shared(Point(14+55*(int)i, 459), town, (int)i)); for(size_t i=0; i<4; i++) - creainfo.push_back(std::make_shared(Point(14+55*i, 507), town, i+4)); + creainfo.push_back(std::make_shared(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(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(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(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; itown->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; jtown->mageGuildLevel() && owner->town->spells[i].size()>j) diff --git a/client/windows/CCreatureWindow.cpp b/client/windows/CCreatureWindow.cpp index 51786cde1..27572922f 100644 --- a/client/windows/CCreatureWindow.cpp +++ b/client/windows/CCreatureWindow.cpp @@ -255,7 +255,7 @@ CStackWindow::BonusesSection::BonusesSection(CStackWindow * owner, int yOffset, size_t visibleSize = preferredSize ? preferredSize.get() : std::min(3, totalSize); pos.w = owner->pos.w; - pos.h = itemHeight * visibleSize; + pos.h = itemHeight * (int)visibleSize; auto onCreate = [=](size_t index) -> std::shared_ptr { @@ -306,7 +306,7 @@ CStackWindow::ButtonsSection::ButtonsSection(CStackWindow * owner, int yOffset) std::vector> resComps; for(TResources::nziterator i(totalCost); i.valid(); i++) { - resComps.push_back(std::make_shared(CComponent::resource, i->resType, i->resVal)); + resComps.push_back(std::make_shared(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(Point(221 + buttonIndex * 40, 5), "stackWindow/upgradeButton", CGI->generaltexth->zelp[446], onClick, SDLK_1); + auto upgradeBtn = std::make_shared(Point(221 + (int)buttonIndex * 40, 5), "stackWindow/upgradeButton", CGI->generaltexth->zelp[446], onClick, SDLK_1); upgradeBtn->addOverlay(std::make_shared("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(Point(302 + buttonIndex*40, 5), "stackWindow/upgradeButton", CButton::tooltip(text), onSwitch); + parent->switchButtons[buttonIndex] = std::make_shared(Point(302 + (int)buttonIndex*40, 5), "stackWindow/upgradeButton", CButton::tooltip(text), onSwitch); parent->switchButtons[buttonIndex]->addOverlay(std::make_shared("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 + auto onCreate = [=](size_t index)->std::shared_ptr { 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(rank)); boost::replace_first(expText, "%i", boost::lexical_cast(stack->experience)); - number = CGI->creh->expRanks[tier][rank] - stack->experience; + number = static_cast(CGI->creh->expRanks[tier][rank] - stack->experience); boost::replace_first(expText, "%i", boost::lexical_cast(number)); number = CGI->creh->maxExpPerBattle[tier]; //percent @@ -878,7 +878,7 @@ std::string CStackWindow::generateStackExpDescription() boost::replace_first(expText, "%i", boost::lexical_cast(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((stack->count * (stack->experience - expmin)) / expmin); //Maximum New Recruits without losing current Rank boost::replace_first(expText, "%i", boost::lexical_cast(number)); //TODO boost::replace_first(expText, "%.2f", boost::lexical_cast(1)); //TODO Experience Multiplier diff --git a/client/windows/CCreatureWindow.h b/client/windows/CCreatureWindow.h index f19f32689..14fcec428 100644 --- a/client/windows/CCreatureWindow.h +++ b/client/windows/CCreatureWindow.h @@ -49,6 +49,7 @@ class CStackWindow : public CWindowObject class CWindowSection : public CIntObject { + std::shared_ptr onCreate(int index); private: std::shared_ptr background; protected: diff --git a/client/windows/CKingdomInterface.cpp b/client/windows/CKingdomInterface.cpp index 3073b041a..e5e845714 100644 --- a/client/windows/CKingdomInterface.cpp +++ b/client/windows/CKingdomInterface.cpp @@ -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::primskill, getSubID(), getValue()); + comp = std::make_shared(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::secskill, subID, value); + text = CGI->skillh->skillInfo(subID, (int)value); + comp = std::make_shared(CComponent::secskill, subID, (int)value); } break; } @@ -704,7 +704,7 @@ std::shared_ptr CKingdHeroList::createHeroItem(size_t index) if(index < heroesCount) { - auto hero = std::make_shared(LOCPLINT->cb->getHeroBySerial(index, false)); + auto hero = std::make_shared(LOCPLINT->cb->getHeroBySerial((int)index, false)); addSet(hero->heroArts); return hero; } @@ -754,7 +754,7 @@ std::shared_ptr CKingdTownList::createTownItem(size_t index) size_t townsCount = LOCPLINT->cb->howManyTowns(); if(index < townsCount) - return std::make_shared(LOCPLINT->cb->getTownBySerial(index)); + return std::make_shared(LOCPLINT->cb->getTownBySerial((int)index)); else return std::make_shared("OVSLOT", (index-2) % picCount ); } @@ -780,8 +780,8 @@ CTownItem::CTownItem(const CGTownInstance * Town) for(size_t i=0; icreatures.size(); i++) { - growth.push_back(std::make_shared(Point(401+37*i, 78), town, i, true, true)); - available.push_back(std::make_shared(Point(48+37*i, 78), town, i, true, false)); + growth.push_back(std::make_shared(Point(401+37*(int)i, 78), town, (int)i, true, true)); + available.push_back(std::make_shared(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("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(Point(270+i*48, 65))); } }; @@ -839,7 +839,7 @@ public: pos = background->pos; btnLeft = std::make_shared(Point(269, 66), "HSBTNS3", CButton::tooltip(), 0); btnRight = std::make_shared(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(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(Point(364+it*112, 46), "OVBUTN3", CButton::tooltip(hover, overlay), 0); + auto button = std::make_shared(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(IInfoBoxData::HERO_PRIMARY_SKILL, hero, i); - heroInfo.push_back(std::make_shared(Point(78+i*36, 26), InfoBox::POS_DOWN, InfoBox::SIZE_SMALL, data)); + auto data = std::make_shared(IInfoBoxData::HERO_PRIMARY_SKILL, hero, (int)i); + heroInfo.push_back(std::make_shared(Point(78+(int)i*36, 26), InfoBox::POS_DOWN, InfoBox::SIZE_SMALL, data)); } for(size_t i=0; i(IInfoBoxData::HERO_SECONDARY_SKILL, hero, i); - heroInfo.push_back(std::make_shared(Point(410+i*36, 5), InfoBox::POS_NONE, InfoBox::SIZE_SMALL, data)); + auto data = std::make_shared(IInfoBoxData::HERO_SECONDARY_SKILL, hero, (int)i); + heroInfo.push_back(std::make_shared(Point(410+(int)i*36, 5), InfoBox::POS_NONE, InfoBox::SIZE_SMALL, data)); } { diff --git a/client/windows/CQuestLog.cpp b/client/windows/CQuestLog.cpp index 3a8ae9811..85c1a2a5d 100644 --- a/client/windows/CQuestLog.cpp +++ b/client/windows/CQuestLog.cpp @@ -181,7 +181,7 @@ void CQuestLog::recreateLabelList() if (quests[i].quest->progress != CQuest::COMPLETE) selectQuest(i, currentLabel); - currentLabel = labels.size(); + currentLabel = static_cast(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(components.size()); int descriptionHeight = DESCRIPTION_HEIGHT_MAX; if(componentsSize) { diff --git a/client/windows/CTradeWindow.cpp b/client/windows/CTradeWindow.cpp index a8027fc9e..7f92f936b 100644 --- a/client/windows/CTradeWindow.cpp +++ b/client/windows/CTradeWindow.cpp @@ -408,7 +408,7 @@ void CTradeWindow::initItems(bool Left) if(Left || !ids) amount = 7; else - amount = ids->size(); + amount = static_cast(ids->size()); if(ids) vstd::amin(amount, ids->size()); @@ -486,8 +486,8 @@ void CTradeWindow::getPositionsFor(std::vector &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(hero->calculateXp(val)); expOnAltar->setText(boost::lexical_cast(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(hero->calculateXp(val)); printAtMiddleLoc(boost::lexical_cast(val), 304, 498, FONT_SMALL, Colors::WHITE, to); } } @@ -1493,7 +1493,7 @@ bool CAltarWindow::putOnAltar(std::shared_ptr altarSlot, const C int dmp, val; market->getOffer(art->artType->id, 0, dmp, val, EMarketMode::ARTIFACT_EXP); - val = hero->calculateXp(val); + val = static_cast(hero->calculateXp(val)); arts->artifactsOnAltar.insert(art); altarSlot->setArtInstance(art); @@ -1505,7 +1505,7 @@ bool CAltarWindow::putOnAltar(std::shared_ptr altarSlot, const C void CAltarWindow::moveFromSlotToAltar(ArtifactPosition slotID, std::shared_ptr 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; diff --git a/client/windows/GUIClasses.cpp b/client/windows/GUIClasses.cpp index 0e59e6c54..bf43055cf 100644 --- a/client/windows/GUIClasses.cpp +++ b/client/windows/GUIClasses.cpp @@ -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(Point( 76, 77), "sysopb2.def", CGI->generaltexth->zelp[350])); heroMoveSpeed->addToggle(4, std::make_shared(Point(124, 77), "sysopb3.def", CGI->generaltexth->zelp[351])); heroMoveSpeed->addToggle(8, std::make_shared(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(Point( 28, 144), "sysopb5.def", CGI->generaltexth->zelp[353])); enemyMoveSpeed->addToggle(4, std::make_shared(Point( 76, 144), "sysopb6.def", CGI->generaltexth->zelp[354])); enemyMoveSpeed->addToggle(8, std::make_shared(Point(124, 144), "sysopb7.def", CGI->generaltexth->zelp[355])); enemyMoveSpeed->addToggle(0, std::make_shared(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(Point( 28, 210), "sysopb9.def", CGI->generaltexth->zelp[357])); mapScrollSpeed->addToggle(2, std::make_shared(Point( 92, 210), "sysob10.def", CGI->generaltexth->zelp[358])); mapScrollSpeed->addToggle(4, std::make_shared(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(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(itgflags, players[i + j*4].getNum(), 0, rowStartX + i*12, rowStartY)); + cells.push_back(std::make_shared(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(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(items.size()); break; default: return; diff --git a/launcher/modManager/cmodlistmodel_moc.cpp b/launcher/modManager/cmodlistmodel_moc.cpp index 86057dd39..ac5fd08aa 100644 --- a/launcher/modManager/cmodlistmodel_moc.cpp +++ b/launcher/modManager/cmodlistmodel_moc.cpp @@ -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; } diff --git a/launcher/settingsView/csettingsview_moc.cpp b/launcher/settingsView/csettingsview_moc.cpp index 7ddd34719..29b167a1b 100644 --- a/launcher/settingsView/csettingsview_moc.cpp +++ b/launcher/settingsView/csettingsview_moc.cpp @@ -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); } diff --git a/lib/CArtHandler.cpp b/lib/CArtHandler.cpp index f6417131c..a1f1d339c 100644 --- a/lib/CArtHandler.cpp +++ b/lib/CArtHandler.cpp @@ -232,7 +232,7 @@ std::vector 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(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 (b["level"].Float(), Bonus())); + art->bonusesPerLevel.push_back(std::pair ((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 (b["level"].Float(), Bonus())); + art->thresholdBonuses.push_back(std::pair ((ui16)b["level"].Float(), Bonus())); JsonUtils::parseBonus(b["bonus"], &art->thresholdBonuses.back().second); } } @@ -647,7 +647,7 @@ void CArtHandler::initAllowedArtifactsList(const std::vector &allowed) if (allowed[i] && legalArtifact(i)) allowedArtifacts.push_back(artifacts[i]); } - for (ArtifactID i = ArtifactID::ART_SELECTION; iisBig()) //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); } diff --git a/lib/CBuildingHandler.cpp b/lib/CBuildingHandler.cpp index 15d9395f3..5543d9805 100644 --- a/lib/CBuildingHandler.cpp +++ b/lib/CBuildingHandler.cpp @@ -33,7 +33,7 @@ BuildingID CBuildingHandler::campToERMU( int camp, int townType, std::set(campToERMU.size()); for (int i=0; i(g["x"].Float()); + button.y = static_cast(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(g["x"].Float()); + ac.gemY[gem] = static_cast(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 curRes(g["resolution"]["x"].Float(), g["resolution"]["y"].Float()); + std::pair 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(g["InGameConsole"]["maxInputPerLine"].Float()); + current->ac.outputLineLength = static_cast(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(g["AdvMap"]["x"].Float()); + current->ac.advmapY = static_cast(g["AdvMap"]["y"].Float()); + current->ac.advmapW = static_cast(g["AdvMap"]["width"].Float()); + current->ac.advmapH = static_cast(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(g["InfoBox"]["x"].Float()); + current->ac.infoboxY = static_cast(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(g["HeroList"]["x"].Float()); + current->ac.hlistY = static_cast(g["HeroList"]["y"].Float()); + current->ac.hlistSize = static_cast(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(g["TownList"]["x"].Float()); + current->ac.tlistY = static_cast(g["TownList"]["y"].Float()); + current->ac.tlistSize = static_cast(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(g["Minimap"]["width"].Float()); + current->ac.minimapH = static_cast(g["Minimap"]["height"].Float()); + current->ac.minimapX = static_cast(g["Minimap"]["x"].Float()); + current->ac.minimapY = static_cast(g["Minimap"]["y"].Float()); - current->ac.overviewPics = g["Overview"]["pics"].Float(); - current->ac.overviewSize = g["Overview"]["size"].Float(); + current->ac.overviewPics = static_cast(g["Overview"]["pics"].Float()); + current->ac.overviewSize = static_cast(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(g["Statusbar"]["x"].Float()); + current->ac.statusbarY = static_cast(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(g["ResDataBar"]["x"].Float()); + current->ac.resdatabarY = static_cast(g["ResDataBar"]["y"].Float()); + current->ac.resOffsetX = static_cast(g["ResDataBar"]["offsetX"].Float()); + current->ac.resOffsetY = static_cast(g["ResDataBar"]["offsetY"].Float()); + current->ac.resDist = static_cast(g["ResDataBar"]["resSpace"].Float()); + current->ac.resDateDist = static_cast(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. diff --git a/lib/CCreatureHandler.cpp b/lib/CCreatureHandler.cpp index b9a0d0363..643150c88 100644 --- a/lib/CCreatureHandler.cpp +++ b/lib/CCreatureHandler.cpp @@ -95,7 +95,7 @@ bool CCreature::isEvil () const si32 CCreature::maxAmount(const std::vector &res) const //how many creatures can be bought { int ret = 2147483645; - int resAmnt = std::min(res.size(),cost.size()); + int resAmnt = static_cast(std::min(res.size(),cost.size())); for(int i=0;i()); 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::pair > 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(ability["skills"].Vector()[0].Float()); + a.second.second = static_cast(ability["skills"].Vector()[1].Float()); skillRequirements.push_back (a); } } @@ -398,7 +398,7 @@ std::vector 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(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(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(node["fightValue"].Float()); + cre->AIValue = static_cast(node["aiValue"].Float()); + cre->growth = static_cast(node["growth"].Float()); + cre->hordeGrowth = static_cast(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(node["advMapAmount"]["min"].Float()); + cre->ammMax = static_cast(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(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(offsets["upperX"].Float()); + cre->animation.upperRightMissleOffsetY = static_cast(offsets["upperY"].Float()); + cre->animation.rightMissleOffsetX = static_cast(offsets["middleX"].Float()); + cre->animation.rightMissleOffsetY = static_cast(offsets["middleY"].Float()); + cre->animation.lowerRightMissleOffsetX = static_cast(offsets["lowerX"].Float()); + cre->animation.lowerRightMissleOffsetY = static_cast(offsets["lowerY"].Float()); - cre->animation.attackClimaxFrame = missile["attackClimaxFrame"].Float(); + cre->animation.attackClimaxFrame = static_cast(missile["attackClimaxFrame"].Float()); cre->animation.missleFrameAngles = missile["frameAngles"].convertTo >(); 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(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)); } - lastVal = val.Float(); + lastVal = static_cast(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(parser.readNumber());// 0 level is never active for (int i = 1; i < 11; ++i) { - curVal = parser.readNumber(); + curVal = static_cast(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(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(parser.readNumber()); if (b.type == Bonus::HATE) curVal *= 10; //odd fix if (curVal > lastVal) //threshold, add new bonus diff --git a/lib/CCreatureSet.cpp b/lib/CCreatureSet.cpp index d1450d571..545353ce5 100644 --- a/lib/CCreatureSet.cpp +++ b/lib/CCreatureSet.cpp @@ -261,7 +261,7 @@ std::string CCreatureSet::getArmyDescription() const int CCreatureSet::stacksCount() const { - return stacks.size(); + return static_cast(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(stacks[slot]->count)); + stacks[slot]->experience = static_cast(stacks[slot]->experience * (count / static_cast(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(type)); if (type->isMyUpgrade(c) && VLC->modh->modules.STACK_EXP) - experience *= VLC->creh->expAfterUpgrade / 100.0; + experience = static_cast(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() diff --git a/lib/CGameInfoCallback.cpp b/lib/CGameInfoCallback.cpp index 42e7f9518..d274b383e 100644 --- a/lib/CGameInfoCallback.cpp +++ b/lib/CGameInfoCallback.cpp @@ -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(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> 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(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(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++; } diff --git a/lib/CGameState.cpp b/lib/CGameState.cpp index 4451557e1..0260b09f9 100644 --- a/lib/CGameState.cpp +++ b/lib/CGameState.cpp @@ -484,7 +484,7 @@ std::pair 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 CGameState::pickObject (CGObjectInstance *obj) //if castle alignment available if (auto info = dynamic_cast(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::vectorartifactsInBackpack.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::vectorartType = 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(ret); } TeamState::TeamState() diff --git a/lib/CGeneralTextHandler.h b/lib/CGeneralTextHandler.h index f69d90dd8..4c325e940 100644 --- a/lib/CGeneralTextHandler.h +++ b/lib/CGeneralTextHandler.h @@ -75,7 +75,7 @@ public: std::vector ret; ret.reserve(size); while (size--) - ret.push_back(readNumber()); + ret.push_back((numeric)readNumber()); return ret; } diff --git a/lib/CHeroHandler.cpp b/lib/CHeroHandler.cpp index 33a52cf03..d05c4d6d6 100644 --- a/lib/CHeroHandler.cpp +++ b/lib/CHeroHandler.cpp @@ -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(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(node["defaultTavern"].Float()); for(auto & tavern : node["tavern"].Struct()) { - int value = tavern.second.Float(); + int value = static_cast(tavern.second.Float()); VLC->modh->identifiers.requestIdentifier(tavern.second.meta, "faction", tavern.first, [=](si32 factionID) @@ -199,7 +199,7 @@ std::vector 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(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(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(heroClass->defaultTavernChance * faction->town->defaultTavernChance); heroClass->selectionProbability[faction->index] = static_cast(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(source["min"].Float()); + hero->initialArmy[i].maxAmount = static_cast(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(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(specialty["type"].Integer()); + spec.val = static_cast(specialty["val"].Integer()); + spec.subtype = static_cast(specialty["subtype"].Integer()); + spec.additionalinfo = static_cast(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(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(obs["width"].Float()); + obi.height = static_cast(obs["height"].Float()); obi.allowedTerrains = obs["allowedTerrain"].convertTo >(); obi.allowedSpecialBfields = obs["specialBattlefields"].convertTo >(); obi.blockedTiles = obs["blockedTiles"].convertTo >(); @@ -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(ballParser.readNumber()); + bli.tower = static_cast(ballParser.readNumber()); + bli.gate = static_cast(ballParser.readNumber()); + bli.wall = static_cast(ballParser.readNumber()); + bli.shots = static_cast(ballParser.readNumber()); + bli.noDmg = static_cast(ballParser.readNumber()); + bli.oneDmg = static_cast(ballParser.readNumber()); + bli.twoDmg = static_cast(ballParser.readNumber()); + bli.sum = static_cast(ballParser.readNumber()); ballistics.push_back(bli); assert(bli.noDmg + bli.oneDmg + bli.twoDmg == 100 && bli.sum == 100); @@ -837,8 +837,8 @@ std::vector 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(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(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 CHeroHandler::getDefaultAllowed() const diff --git a/lib/CModHandler.cpp b/lib/CModHandler.cpp index 2c9c79096..9eeb15785 100644 --- a/lib/CModHandler.cpp +++ b/lib/CModHandler.cpp @@ -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(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(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(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(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(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(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(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(settings.DWELLINGS_ACCUMULATE_CREATURES)); diff --git a/lib/CPathfinder.cpp b/lib/CPathfinder.cpp index 4342f9671..9a3fc60e8 100644 --- a/lib/CPathfinder.cpp +++ b/lib/CPathfinder.cpp @@ -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(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(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(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) { diff --git a/lib/CRandomGenerator.cpp b/lib/CRandomGenerator.cpp index 88fb9b422..c05b126b3 100644 --- a/lib/CRandomGenerator.cpp +++ b/lib/CRandomGenerator.cpp @@ -27,7 +27,7 @@ void CRandomGenerator::resetSeed() { boost::hash stringHash; auto threadIdHash = stringHash(boost::lexical_cast(boost::this_thread::get_id())); - setSeed(threadIdHash * std::time(nullptr)); + setSeed((int)(threadIdHash * std::time(nullptr))); } TRandI CRandomGenerator::getIntRange(int lower, int upper) diff --git a/lib/CSkillHandler.cpp b/lib/CSkillHandler.cpp index abcadc5d7..12f10d8d4 100644 --- a/lib/CSkillHandler.cpp +++ b/lib/CSkillHandler.cpp @@ -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(json["gainChance"].Integer()); + skill->gainChance[1] = static_cast(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(json["gainChance"]["might"].Integer()); + skill->gainChance[1] = static_cast(json["gainChance"]["magic"].Integer()); break; default: break; diff --git a/lib/CStack.cpp b/lib/CStack.cpp index 37df8f7de..bdf01abd7 100644 --- a/lib/CStack.cpp +++ b/lib/CStack.cpp @@ -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); } diff --git a/lib/CThreadHelper.cpp b/lib/CThreadHelper.cpp index 9dfffadcc..6e0c32e82 100644 --- a/lib/CThreadHelper.cpp +++ b/lib/CThreadHelper.cpp @@ -18,7 +18,7 @@ CThreadHelper::CThreadHelper(std::vector > *Tasks, int Threads) { - currentTask = 0; amount = Tasks->size(); + currentTask = 0; amount = (int)Tasks->size(); tasks = Tasks; threads = Threads; } diff --git a/lib/CTownHandler.cpp b/lib/CTownHandler.cpp index e974f1995..ffee9e0c5 100644 --- a/lib/CTownHandler.cpp +++ b/lib/CTownHandler.cpp @@ -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(source["x"].Float()); + ret->pos.y = static_cast(source["y"].Float()); + ret->pos.z = static_cast(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(node["x"].Float()); + ret.y = static_cast(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(resIter - std::begin(GameConstants::RESOURCE_NAMES)); warMachinesToLoad[town] = source["warMachine"]; - town->moatDamage = source["moatDamage"].Float(); + town->moatDamage = static_cast(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 >(); - town->mageLevel = source["mageGuild"].Float(); + town->mageLevel = static_cast(source["mageGuild"].Float()); town->names = source["names"].convertTo >(); // 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(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(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(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(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(piece["x"].Float()); + spi.y = static_cast(piece["y"].Float()); + spi.whenUncovered = static_cast(piece["index"].Float()); + spi.number = static_cast(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(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(index); if (factions.size() > index) assert(factions[index] == nullptr); // ensure that this id was not loaded before else @@ -917,7 +917,7 @@ std::set CTownHandler::getAllowedFactions(bool withTown) const for (size_t i=0; i& b) + const int notIndepBonuses = (int)boost::count_if(bonuses, [](const std::shared_ptr& 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(undecided.size()); for(int i = 0; i < undecided.size(); i++) { auto b = undecided[i]; diff --git a/lib/JsonDetail.cpp b/lib/JsonDetail.cpp index 1505bbe51..7456a1e26 100644 --- a/lib/JsonDetail.cpp +++ b/lib/JsonDetail.cpp @@ -512,7 +512,7 @@ bool JsonParser::extractFloat(JsonNode &node) pos++; } - result = integerPart; + result = static_cast(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(index); auto onExit = vstd::makeScopeGuard([&]() { validator.currentPath.pop_back(); diff --git a/lib/JsonNode.cpp b/lib/JsonNode.cpp index fee986eed..48fc01c5f 100644 --- a/lib/JsonNode.cpp +++ b/lib/JsonNode.cpp @@ -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(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(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(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(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 dest) { - dest->val = source[1].Float(); + dest->val = static_cast(source[1].Float()); resolveIdentifier(source[2],dest->subtype); - dest->additionalInfo = source[3].Float(); + dest->additionalInfo = static_cast(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(value.Integer()); break; case JsonNode::JsonType::DATA_FLOAT: - var = value.Float(); + var = static_cast(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(value.Integer()); break; case JsonNode::JsonType::DATA_FLOAT: - var = value.Float(); + var = static_cast(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(vec[i].Integer()); break; case JsonNode::JsonType::DATA_FLOAT: - var[i] = vec[i].Float(); + var[i] = static_cast(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(node.Integer()); break; case JsonNode::JsonType::DATA_FLOAT: - var = node.Float(); + var = static_cast(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(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(ability["turns"].Float()); - b->sid = ability["sourceID"].Float(); + b->sid = static_cast(ability["sourceID"].Float()); b->description = ability["description"].String(); @@ -781,9 +781,9 @@ bool JsonUtils::parseBonus(const JsonNode &ability, Bonus *b) { std::shared_ptr updater = std::make_shared(); const JsonVector param = updaterJson["parameters"].Vector(); - updater->valPer20 = param[0].Integer(); + updater->valPer20 = static_cast(param[0].Integer()); if(param.size() > 1) - updater->stepSize = param[1].Integer(); + updater->stepSize = static_cast(param[1].Integer()); b->addUpdater(updater); } else diff --git a/lib/JsonNode.h b/lib/JsonNode.h index 24cf4413a..10912baa8 100644 --- a/lib/JsonNode.h +++ b/lib/JsonNode.h @@ -278,7 +278,7 @@ namespace JsonDetail { static T convertImpl(const JsonNode & node) { - return node.Float(); + return T(node.Float()); } }; diff --git a/lib/NetPacksLib.cpp b/lib/NetPacksLib.cpp index 95426b76f..d02a1bbd6 100644 --- a/lib/NetPacksLib.cpp +++ b/lib/NetPacksLib.cpp @@ -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(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); diff --git a/lib/ResourceSet.cpp b/lib/ResourceSet.cpp index 0a4e5ddf9..3d922c6f2 100644 --- a/lib/ResourceSet.cpp +++ b/lib/ResourceSet.cpp @@ -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, diff --git a/lib/StartInfo.h b/lib/StartInfo.h index bcbe1151c..913161220 100644 --- a/lib/StartInfo.h +++ b/lib/StartInfo.h @@ -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 diff --git a/lib/battle/BattleHex.cpp b/lib/battle/BattleHex.cpp index 54c05b23e..db83f9c4f 100644 --- a/lib/battle/BattleHex.cpp +++ b/lib/battle/BattleHex.cpp @@ -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; diff --git a/lib/battle/BattleInfo.cpp b/lib/battle/BattleInfo.cpp index 1e63fda03..65278f443 100644 --- a/lib/battle/BattleInfo.cpp +++ b/lib/battle/BattleInfo.cpp @@ -94,7 +94,7 @@ namespace CGH std::vector 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(); obstPtr->obstacleType = CObstacleInstance::ABSOLUTE_OBSTACLE; obstPtr->ID = obidgen.getSuchNumber(appropriateAbsoluteObstacle); - obstPtr->uniqueID = curB->obstacles.size(); + obstPtr->uniqueID = static_cast(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(); obstPtr->ID = obid; obstPtr->pos = posgenerator.getSuchNumber(validPosition); - obstPtr->uniqueID = curB->obstacles.size(); + obstPtr->uniqueID = static_cast(curB->obstacles.size()); curB->obstacles.push_back(obstPtr); for(BattleHex blocked : obstPtr->getBlockedTiles()) blockedTiles.push_back(blocked); - tilesToBlock -= obi.blockedTiles.size(); + tilesToBlock -= static_cast(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(); moat->ID = curB->town->subID; moat->obstacleType = CObstacleInstance::MOAT; - moat->uniqueID = curB->obstacles.size(); + moat->uniqueID = static_cast(curB->obstacles.size()); curB->obstacles.push_back(moat); } @@ -980,7 +980,7 @@ void BattleInfo::removeUnitBonus(uint32_t id, const std::vector & bonus) uint32_t BattleInfo::nextUnitId() const { - return stacks.size(); + return static_cast(stacks.size()); } void BattleInfo::addOrUpdateUnitBonus(CStack * sta, const Bonus & value, bool forceAdd) diff --git a/lib/battle/CBattleInfoCallback.cpp b/lib/battle/CBattleInfoCallback.cpp index 6bc263008..e20dc7270 100644 --- a/lib/battle/CBattleInfoCallback.cpp +++ b/lib/battle/CBattleInfoCallback.cpp @@ -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 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(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; } diff --git a/lib/battle/CUnitState.cpp b/lib/battle/CUnitState.cpp index 640ec2762..727e27bd3 100644 --- a/lib/battle/CUnitState.cpp +++ b/lib/battle/CUnitState.cpp @@ -270,7 +270,7 @@ void CHealth::damage(int64_t & amount) } else { - firstHPleft -= amount; + firstHPleft -= static_cast(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(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(frenzyPower); } vstd::amax(ret, 0); diff --git a/lib/filesystem/CArchiveLoader.cpp b/lib/filesystem/CArchiveLoader.cpp index 9f3ba9b5e..294f4db2d 100644 --- a/lib/filesystem/CArchiveLoader.cpp +++ b/lib/filesystem/CArchiveLoader.cpp @@ -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) diff --git a/lib/filesystem/CBinaryReader.cpp b/lib/filesystem/CBinaryReader.cpp index 5e960d91d..643dcdd71 100644 --- a/lib/filesystem/CBinaryReader.cpp +++ b/lib/filesystem/CBinaryReader.cpp @@ -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; } diff --git a/lib/filesystem/CCompressedStream.cpp b/lib/filesystem/CCompressedStream.cpp index b5a6515e4..7fa23529f 100644 --- a/lib/filesystem/CCompressedStream.cpp +++ b/lib/filesystem/CCompressedStream.cpp @@ -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(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(); } diff --git a/lib/filesystem/CZipLoader.cpp b/lib/filesystem/CZipLoader.cpp index 673eee275..35e4cdcd8 100644 --- a/lib/filesystem/CZipLoader.cpp +++ b/lib/filesystem/CZipLoader.cpp @@ -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 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 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())); } diff --git a/lib/filesystem/FileStream.cpp b/lib/filesystem/FileStream.cpp index 11edd9e3f..d3d4796f8 100644 --- a/lib/filesystem/FileStream.cpp +++ b/lib/filesystem/FileStream.cpp @@ -317,7 +317,7 @@ std::streamoff FileBuf::seek(std::streamoff off, std::ios_base::seekdir way) throw std::ios_base::failure("bad seek direction"); } }(); - if(std::fseek(GETFILE, off, src)) + if(std::fseek(GETFILE, (long)off, src)) throw std::ios_base::failure("bad seek offset"); return static_cast(std::ftell(GETFILE)); diff --git a/lib/filesystem/MinizipExtensions.cpp b/lib/filesystem/MinizipExtensions.cpp index 3435a43d9..23edf26d4 100644 --- a/lib/filesystem/MinizipExtensions.cpp +++ b/lib/filesystem/MinizipExtensions.cpp @@ -20,7 +20,7 @@ template inline uLong streamRead(voidpf opaque, voidpf stream, v _Stream * actualStream = static_cast<_Stream *>(stream); - return actualStream->read((ui8 *)buf, size); + return (uLong)actualStream->read((ui8 *)buf, (uLong)size); } template inline ZPOS64_T streamTell(voidpf opaque, voidpf stream) diff --git a/lib/mapObjects/CArmedInstance.cpp b/lib/mapObjects/CArmedInstance.cpp index b743d19a3..625f6ffba 100644 --- a/lib/mapObjects/CArmedInstance.cpp +++ b/lib/mapObjects/CArmedInstance.cpp @@ -97,7 +97,7 @@ void CArmedInstance::updateMoraleBonusFromArmy() } else if (!factions.empty()) // no bonus from empty garrison { - b->val = 2 - factionsInArmy; + b->val = 2 - (si32)factionsInArmy; b->description = boost::str(boost::format(VLC->generaltexth->arraytxt[114]) % factionsInArmy % b->val); //Troops of %d alignments %d b->description = b->description.substr(0, b->description.size()-2);//trim value } diff --git a/lib/mapObjects/CGHeroInstance.cpp b/lib/mapObjects/CGHeroInstance.cpp index 39ec42f0f..2fa0125dc 100644 --- a/lib/mapObjects/CGHeroInstance.cpp +++ b/lib/mapObjects/CGHeroInstance.cpp @@ -602,7 +602,7 @@ ui64 CGHeroInstance::getTotalStrength() const TExpType CGHeroInstance::calculateXp(TExpType exp) const { - return exp * (100 + valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::LEARNING))/100.0; + return (TExpType)(exp * (100 + valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::LEARNING))/100.0); } int32_t CGHeroInstance::getCasterUnitId() const @@ -632,15 +632,15 @@ ui8 CGHeroInstance::getSpellSchoolLevel(const spells::Spell * spell, int * outSe vstd::amax(skill, 0); //in case we don't know any school vstd::amin(skill, 3); - return skill; + return (ui8)skill; } int64_t CGHeroInstance::getSpellBonus(const spells::Spell * spell, int64_t base, const battle::Unit * affectedStack) const { //applying sorcery secondary skill - base *= (100.0 + valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::SORCERY)) / 100.0; - base *= (100.0 + valOfBonuses(Bonus::SPELL_DAMAGE) + valOfBonuses(Bonus::SPECIFIC_SPELL_DAMAGE, spell->getIndex())) / 100.0; + base = (int64_t)(base * (100 + valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::SORCERY)) / 100.0); + base = (int64_t)(base * (100 + valOfBonuses(Bonus::SPELL_DAMAGE) + valOfBonuses(Bonus::SPECIFIC_SPELL_DAMAGE, spell->getIndex())) / 100.0); int maxSchoolBonus = 0; @@ -649,17 +649,17 @@ int64_t CGHeroInstance::getSpellBonus(const spells::Spell * spell, int64_t base, vstd::amax(maxSchoolBonus, valOfBonuses(cnf.damagePremyBonus)); }); - base *= (100.0 + maxSchoolBonus) / 100.0; + base = (int64_t)(base * (100 + maxSchoolBonus) / 100.0); if(affectedStack && affectedStack->creatureLevel() > 0) //Hero specials like Solmyr, Deemer - base *= (100. + valOfBonuses(Bonus::SPECIAL_SPELL_LEV, spell->getIndex()) / affectedStack->creatureLevel()) / 100.0; + base = (int64_t)(base * double(100 + valOfBonuses(Bonus::SPECIAL_SPELL_LEV, spell->getIndex()) / affectedStack->creatureLevel()) / 100.0); return base; } int64_t CGHeroInstance::getSpecificSpellBonus(const spells::Spell * spell, int64_t base) const { - base *= (100.0 + valOfBonuses(Bonus::SPECIFIC_SPELL_DAMAGE, spell->getIndex())) / 100.0; + base = (int64_t)(base * (100 + valOfBonuses(Bonus::SPECIFIC_SPELL_DAMAGE, spell->getIndex())) / 100.0); return base; } @@ -1089,7 +1089,7 @@ int CGHeroInstance::movementPointsAfterEmbark(int MPsBefore, int basicCost, bool int mp1 = ti->getMaxMovePoints(disembark ? EPathfindingLayer::LAND : EPathfindingLayer::SAIL); int mp2 = ti->getMaxMovePoints(disembark ? EPathfindingLayer::SAIL : EPathfindingLayer::LAND); if(ti->hasBonusOfType(Bonus::FREE_SHIP_BOARDING)) - ret = (MPsBefore - basicCost) * static_cast(mp1) / mp2; + ret = static_cast((MPsBefore - basicCost) * static_cast(mp1) / mp2); if(localTi) delete ti; @@ -1099,7 +1099,7 @@ int CGHeroInstance::movementPointsAfterEmbark(int MPsBefore, int basicCost, bool EDiggingStatus CGHeroInstance::diggingStatus() const { - if(movement < maxMovePoints(true)) + if((int)movement < maxMovePoints(true)) return EDiggingStatus::LACK_OF_MOVEMENT; return cb->getTile(getPosition(false))->getDiggingStatus(); @@ -1264,11 +1264,11 @@ void CGHeroInstance::setPrimarySkill(PrimarySkill::PrimarySkill primarySkill, si if(abs) { - skill->val = value; + skill->val = static_cast(value); } else { - skill->val += value; + skill->val += static_cast(value); } CBonusSystemNode::treeHasChanged(); } @@ -1287,7 +1287,7 @@ void CGHeroInstance::setPrimarySkill(PrimarySkill::PrimarySkill primarySkill, si bool CGHeroInstance::gainsLevel() const { - return exp >= VLC->heroh->reqExp(level+1); + return exp >= static_cast(VLC->heroh->reqExp(level+1)); } void CGHeroInstance::levelUp(std::vector skills) @@ -1350,7 +1350,7 @@ bool CGHeroInstance::hasVisions(const CGObjectInstance * target, const int subty if (visionsMultiplier > 0) vstd::amax(visionsRange, 3); //minimum range is 3 tiles, but only if VISIONS bonus present - const int distance = target->pos.dist2d(getPosition(false)); + const int distance = static_cast(target->pos.dist2d(getPosition(false))); //logGlobal->debug(boost::to_string(boost::format("Visions: dist %d, mult %d, range %d") % distance % visionsMultiplier % visionsRange)); @@ -1400,7 +1400,7 @@ void CGHeroInstance::serializeCommonOptions(JsonSerializeFormat & handler) handler.serializeBool("female", sex, 1, 0, 0xFF); { - const int legacyHeroes = VLC->modh->settings.data["textData"]["hero"].Integer(); + const int legacyHeroes = static_cast(VLC->modh->settings.data["textData"]["hero"].Integer()); const int moddedStart = legacyHeroes + GameConstants::HERO_PORTRAIT_SHIFT; if(handler.saving) diff --git a/lib/mapObjects/CGMarket.cpp b/lib/mapObjects/CGMarket.cpp index 462037785..e6b75dbdb 100644 --- a/lib/mapObjects/CGMarket.cpp +++ b/lib/mapObjects/CGMarket.cpp @@ -43,12 +43,12 @@ bool IMarket::getOffer(int id1, int id2, int &val1, int &val2, EMarketMode::EMar if(r>g) //if given resource is more expensive than wanted { - val2 = ceil(r / g); + val2 = (int)ceil(r / g); val1 = 1; } else //if wanted resource is more expensive { - val1 = (g / r) + 0.5; + val1 = (int)((g / r) + 0.5); val2 = 1; } } @@ -63,12 +63,12 @@ bool IMarket::getOffer(int id1, int id2, int &val1, int &val2, EMarketMode::EMar if(r>g) //if given resource is more expensive than wanted { - val2 = ceil(r / g); + val2 = (int)ceil(r / g); val1 = 1; } else //if wanted resource is more expensive { - val1 = (g / r) + 0.5; + val1 = (int)((g / r) + 0.5); val2 = 1; } } diff --git a/lib/mapObjects/CGPandoraBox.cpp b/lib/mapObjects/CGPandoraBox.cpp index 4e978375d..9f11932d2 100644 --- a/lib/mapObjects/CGPandoraBox.cpp +++ b/lib/mapObjects/CGPandoraBox.cpp @@ -101,7 +101,7 @@ void CGPandoraBox::giveContentsUpToExp(const CGHeroInstance *h) const iw.text.addReplacement(h->name); if(expVal) - iw.components.push_back(Component(Component::EXPERIENCE,0,expVal,0)); + iw.components.push_back(Component(Component::EXPERIENCE,0,static_cast(expVal),0)); for(int i=0; i(stacks.size()); for(int i = 0; i < count; i++) { auto pair = *vstd::maxElementByFun(stacks, [&](std::pair elem) @@ -926,7 +926,7 @@ void CGTownInstance::mergeGarrisonOnSiege() const cb->moveStack(StackLocation(this, pair.first), StackLocation(visitingHero, dst), -1); else { - dst = getWeakestStackSlot(pair.second->getPower()); + dst = getWeakestStackSlot(static_cast(pair.second->getPower())); if(dst.validSlot()) cb->swapStacks(StackLocation(this, pair.first), StackLocation(visitingHero, dst)); } @@ -1248,7 +1248,7 @@ const CTown * CGTownInstance::getTown() const int CGTownInstance::getTownLevel() const { // count all buildings that are not upgrades - return boost::range::count_if(builtBuildings, [&](const BuildingID & build) + return (int)boost::range::count_if(builtBuildings, [&](const BuildingID & build) { return town->buildings.at(build) && town->buildings.at(build)->upgrade == -1; }); @@ -1502,7 +1502,7 @@ COPWBonus::COPWBonus (BuildingID index, CGTownInstance *TOWN) { ID = index; town = TOWN; - id = town->bonusingBuildings.size(); + id = static_cast(town->bonusingBuildings.size()); } void COPWBonus::setProperty(ui8 what, ui32 val) { @@ -1563,7 +1563,7 @@ CTownBonus::CTownBonus (BuildingID index, CGTownInstance *TOWN) { ID = index; town = TOWN; - id = town->bonusingBuildings.size(); + id = static_cast(town->bonusingBuildings.size()); } void CTownBonus::setProperty (ui8 what, ui32 val) { @@ -1603,7 +1603,7 @@ void CTownBonus::onHeroVisit (const CGHeroInstance * h) const break; case ETownType::DUNGEON://academy of battle scholars what = PrimarySkill::EXPERIENCE; - val = h->calculateXp(1000); + val = static_cast(h->calculateXp(1000)); mid = 583; iw.components.push_back (Component(Component::EXPERIENCE, 0, val, 0)); break; diff --git a/lib/mapObjects/CObjectClassesHandler.cpp b/lib/mapObjects/CObjectClassesHandler.cpp index fce778e8a..418aedaa0 100644 --- a/lib/mapObjects/CObjectClassesHandler.cpp +++ b/lib/mapObjects/CObjectClassesHandler.cpp @@ -111,7 +111,7 @@ CObjectClassesHandler::~CObjectClassesHandler() std::vector CObjectClassesHandler::loadLegacyData(size_t dataSize) { CLegacyConfigParser parser("Data/Objects.txt"); - size_t totalNumber = parser.readNumber(); // first line contains number of objects to read and nothing else + size_t totalNumber = static_cast(parser.readNumber()); // first line contains number of objects to read and nothing else parser.endLine(); for (size_t i=0; i CObjectClassesHandler::loadLegacyData(size_t dataSize) template si32 selectNextID(const JsonNode & fixedID, const Map & map, si32 defaultID) { - if (!fixedID.isNull() && fixedID.Float() < defaultID) - return fixedID.Float(); // H3M object with fixed ID + if (!fixedID.isNull() && (si32)fixedID.Float() < defaultID) + return static_cast(fixedID.Float()); // H3M object with fixed ID if (map.empty()) return defaultID; // no objects loaded, keep gap for H3M objects @@ -209,7 +209,7 @@ CObjectClassesHandler::ObjectContainter * CObjectClassesHandler::loadFromJson(co if(json["defaultAiValue"].isNull()) obj->groupDefaultAiValue = boost::none; else - obj->groupDefaultAiValue = json["defaultAiValue"].Integer(); + obj->groupDefaultAiValue = static_cast(json["defaultAiValue"].Integer()); for (auto entry : json["types"].Struct()) { @@ -229,8 +229,8 @@ void CObjectClassesHandler::loadObject(std::string scope, std::string name, cons void CObjectClassesHandler::loadObject(std::string scope, std::string name, const JsonNode & data, size_t index) { auto object = loadFromJson(data, normalizeIdentifier(scope, "core", name)); - assert(objects[index] == nullptr); // ensure that this id was not loaded before - objects[index] = object; + assert(objects[(si32)index] == nullptr); // ensure that this id was not loaded before + objects[(si32)index] = object; VLC->modh->identifiers.registerObject(scope, "object", name, object->id); } @@ -347,7 +347,7 @@ void CObjectClassesHandler::afterLoadFinalization() size_t currentIndex = portalCount; while(portalVec.size() < 100) { - portalVec[currentIndex] = portalVec[currentIndex % portalCount]; + portalVec[(si32)currentIndex] = portalVec[static_cast(currentIndex % portalCount)]; currentIndex++; } } @@ -425,7 +425,7 @@ static ui32 loadJsonOrMax(const JsonNode & input) if (input.isNull()) return std::numeric_limits::max(); else - return input.Float(); + return static_cast(input.Float()); } void AObjectTypeHandler::init(const JsonNode & input, boost::optional name) @@ -434,10 +434,10 @@ void AObjectTypeHandler::init(const JsonNode & input, boost::optional(input["rmg"]["value"].Float()); rmgInfo.mapLimit = loadJsonOrMax(input["rmg"]["mapLimit"]); rmgInfo.zoneLimit = loadJsonOrMax(input["rmg"]["zoneLimit"]); - rmgInfo.rarity = input["rmg"]["rarity"].Float(); + rmgInfo.rarity = static_cast(input["rmg"]["rarity"].Float()); } // else block is not needed - set in constructor for (auto entry : input["templates"].Struct()) @@ -470,7 +470,7 @@ void AObjectTypeHandler::init(const JsonNode & input, boost::optional(input["aiValue"].Integer()); initTypeData(input); } diff --git a/lib/mapObjects/CObjectHandler.cpp b/lib/mapObjects/CObjectHandler.cpp index 1d6040352..e76321790 100644 --- a/lib/mapObjects/CObjectHandler.cpp +++ b/lib/mapObjects/CObjectHandler.cpp @@ -114,7 +114,7 @@ CObjectHandler::CObjectHandler() const JsonNode config2(ResourceID("config/resources.json")); for(const JsonNode &price : config2["resources_prices"].Vector()) { - resVals.push_back(price.Float()); + resVals.push_back(static_cast(price.Float())); } logGlobal->trace("\t\tDone loading resource prices!"); } diff --git a/lib/mapObjects/CQuest.cpp b/lib/mapObjects/CQuest.cpp index 45ecd7491..765e06e50 100644 --- a/lib/mapObjects/CQuest.cpp +++ b/lib/mapObjects/CQuest.cpp @@ -72,7 +72,7 @@ bool CQuest::checkQuest(const CGHeroInstance * h) const case MISSION_PRIMARY_STAT: for(int i = 0; i < GameConstants::PRIMARY_SKILLS; ++i) { - if(h->getPrimSkillLevel(static_cast(i)) < m2stats[i]) + if(h->getPrimSkillLevel(static_cast(i)) < (int)m2stats[i]) return false; } return true; @@ -106,17 +106,17 @@ bool CQuest::checkQuest(const CGHeroInstance * h) const slotsCount++; } } - if(count < cre->count) //not enough creatures of this kind + if((TQuantity)count < cre->count) //not enough creatures of this kind return false; - hasExtraCreatures |= count > cre->count; + hasExtraCreatures |= (TQuantity)count > cre->count; } return hasExtraCreatures || slotsCount < h->Slots().size(); } case MISSION_RESOURCES: for(Res::ERes i = Res::WOOD; i <= Res::GOLD; vstd::advance(i, +1)) //including Mithril ? { //Quest has no direct access to callback - if(h->cb->getResource (h->tempOwner, i) < m7resources[i]) + if(h->cb->getResource (h->tempOwner, i) < (int)m7resources[i]) return false; } return true; @@ -617,7 +617,7 @@ void CGSeerHut::getCompletionText(MetaString &text, std::vector &comp quest->getCompletionText (text, components, isCustom, h); switch(rewardType) { - case EXPERIENCE: components.push_back(Component (Component::EXPERIENCE, 0, h->calculateXp(rVal), 0)); + case EXPERIENCE: components.push_back(Component (Component::EXPERIENCE, 0, (si32)h->calculateXp(rVal), 0)); break; case MANA_POINTS: components.push_back(Component (Component::PRIM_SKILL, 5, rVal, 0)); break; @@ -771,7 +771,7 @@ void CGSeerHut::finishQuest(const CGHeroInstance * h, ui32 accept) const case CQuest::MISSION_RESOURCES: for (int i = 0; i < 7; ++i) { - cb->giveResource(h->getOwner(), static_cast(i), -quest->m7resources[i]); + cb->giveResource(h->getOwner(), static_cast(i), -(int)quest->m7resources[i]); } break; default: diff --git a/lib/mapObjects/CRewardableConstructor.cpp b/lib/mapObjects/CRewardableConstructor.cpp index 8fbd53d80..971913571 100644 --- a/lib/mapObjects/CRewardableConstructor.cpp +++ b/lib/mapObjects/CRewardableConstructor.cpp @@ -21,7 +21,7 @@ namespace { { MetaString ret; if (value.isNumber()) - ret.addTxt(MetaString::ADVOB_TXT, value.Float()); + ret.addTxt(MetaString::ADVOB_TXT, static_cast(value.Float())); else ret << value.String(); return ret; @@ -52,20 +52,20 @@ void CRandomRewardObjectInfo::configureObject(CRewardableObject * object, CRando if (!reward["appearChance"].isNull()) { JsonNode chance = reward["appearChance"]; - si32 diceID = chance["dice"].Float(); + si32 diceID = static_cast(chance["dice"].Float()); if (thrownDice.count(diceID) == 0) thrownDice[diceID] = rng.getIntRange(1, 100)(); if (!chance["min"].isNull()) { - int min = chance["min"].Float(); + int min = static_cast(chance["min"].Float()); if (min > thrownDice[diceID]) continue; } if (!chance["max"].isNull()) { - int max = chance["max"].Float(); + int max = static_cast(chance["max"].Float()); if (max < thrownDice[diceID]) continue; } @@ -103,7 +103,7 @@ void CRandomRewardObjectInfo::configureObject(CRewardableObject * object, CRando std::vector spells; for (size_t i=0; i<6; i++) - IObjectInterface::cb->getAllowedSpells(spells, i); + IObjectInterface::cb->getAllowedSpells(spells, static_cast(i)); info.reward.artifacts = JsonRandom::loadArtifacts(reward["artifacts"], rng); info.reward.spells = JsonRandom::loadSpells(reward["spells"], rng, spells); @@ -119,8 +119,8 @@ void CRandomRewardObjectInfo::configureObject(CRewardableObject * object, CRando //TODO: visitMode and selectMode - object->resetDuration = parameters["resetDuration"].Float(); - object->canRefuse =parameters["canRefuse"].Bool(); + object->resetDuration = static_cast(parameters["resetDuration"].Float()); + object->canRefuse = parameters["canRefuse"].Bool(); } bool CRandomRewardObjectInfo::givesResources() const diff --git a/lib/mapObjects/CRewardableObject.cpp b/lib/mapObjects/CRewardableObject.cpp index 72b21247e..4f4116494 100644 --- a/lib/mapObjects/CRewardableObject.cpp +++ b/lib/mapObjects/CRewardableObject.cpp @@ -44,7 +44,7 @@ bool CRewardLimiter::heroAllowed(const CGHeroInstance * hero) const if(!IObjectInterface::cb->getPlayer(hero->tempOwner)->resources.canAfford(resources)) return false; - if(minLevel > hero->level) + if(minLevel > (si32)hero->level) return false; for(size_t i=0; i CRewardableObject::getAvailableRewards(const CGHeroInstance * && visit.limiter.heroAllowed(hero)) { logGlobal->trace("Reward %d is allowed", i); - ret.push_back(i); + ret.push_back(static_cast(i)); } } return ret; @@ -161,7 +161,7 @@ void CRewardableObject::onHeroVisit(const CGHeroInstance *h) const grantRewardWithMessage(rewards[0]); break; case SELECT_RANDOM: // select one randomly //TODO: use weights - grantRewardWithMessage(rewards[CRandomGenerator::getDefault().nextInt(rewards.size()-1)]); + grantRewardWithMessage(rewards[CRandomGenerator::getDefault().nextInt((int)rewards.size()-1)]); break; } break; @@ -360,7 +360,7 @@ void CRewardInfo::loadComponents(std::vector & comps, if (gainedExp) { comps.push_back(Component( - Component::EXPERIENCE, 0, h->calculateXp(gainedExp), 0)); + Component::EXPERIENCE, 0, (si32)h->calculateXp(gainedExp), 0)); } if (gainedLevels) comps.push_back(Component(Component::EXPERIENCE, 0, gainedLevels, 0)); @@ -369,7 +369,7 @@ void CRewardInfo::loadComponents(std::vector & comps, for (size_t i=0; i & comps, for (size_t i=0; i CGMagicSpring::getAvailableRewards(const CGHeroInstance * hero { if (pos - tiles[i] == hero->getPosition() && info[i].numOfGrants == 0) { - return std::vector(1, i); + return std::vector(1, (ui32)i); } } // hero is either not on visitable tile (should not happen) or tile is already used diff --git a/lib/mapObjects/CommonConstructors.cpp b/lib/mapObjects/CommonConstructors.cpp index 381fc28e7..c4350247a 100644 --- a/lib/mapObjects/CommonConstructors.cpp +++ b/lib/mapObjects/CommonConstructors.cpp @@ -264,7 +264,7 @@ void CBankInstanceConstructor::initTypeData(const JsonNode & input) { //TODO: name = input["name"].String(); levels = input["levels"].Vector(); - bankResetDuration = input["resetDuration"].Float(); + bankResetDuration = static_cast(input["resetDuration"].Float()); } CGObjectInstance *CBankInstanceConstructor::create(const ObjectTemplate & tmpl) const @@ -276,22 +276,22 @@ BankConfig CBankInstanceConstructor::generateConfig(const JsonNode & level, CRan { BankConfig bc; - bc.chance = level["chance"].Float(); + bc.chance = static_cast(level["chance"].Float()); bc.guards = JsonRandom::loadCreatures(level["guards"], rng); - bc.upgradeChance = level["upgrade_chance"].Float(); - bc.combatValue = level["combat_value"].Float(); + bc.upgradeChance = static_cast(level["upgrade_chance"].Float()); + bc.combatValue = static_cast(level["combat_value"].Float()); std::vector spells; for (size_t i=0; i<6; i++) - IObjectInterface::cb->getAllowedSpells(spells, i); + IObjectInterface::cb->getAllowedSpells(spells, static_cast(i)); bc.resources = Res::ResourceSet(level["reward"]["resources"]); bc.creatures = JsonRandom::loadCreatures(level["reward"]["creatures"], rng); bc.artifacts = JsonRandom::loadArtifacts(level["reward"]["artifacts"], rng); bc.spells = JsonRandom::loadSpells(level["reward"]["spells"], rng, spells); - bc.value = level["value"].Float(); + bc.value = static_cast(level["value"].Float()); return bc; } @@ -304,7 +304,7 @@ void CBankInstanceConstructor::configureObject(CGObjectInstance * object, CRando si32 totalChance = 0; for (auto & node : levels) - totalChance += node["chance"].Float(); + totalChance += static_cast(node["chance"].Float()); assert(totalChance != 0); @@ -313,7 +313,7 @@ void CBankInstanceConstructor::configureObject(CGObjectInstance * object, CRando int cumulativeChance = 0; for (auto & node : levels) { - cumulativeChance += node["chance"].Float(); + cumulativeChance += static_cast(node["chance"].Float()); if (selectedChance < cumulativeChance) { bank->setConfig(generateConfig(node, rng)); @@ -406,7 +406,7 @@ TPossibleGuards CBankInfo::getPossibleGuards() const //TODO: add fields for flyers, walkers etc... } - ui8 chance = configEntry["chance"].Float(); + ui8 chance = static_cast(configEntry["chance"].Float()); out.push_back(std::make_pair(chance, army)); } return out; diff --git a/lib/mapObjects/JsonRandom.cpp b/lib/mapObjects/JsonRandom.cpp index f7a934850..1d5c370ea 100644 --- a/lib/mapObjects/JsonRandom.cpp +++ b/lib/mapObjects/JsonRandom.cpp @@ -28,11 +28,11 @@ namespace JsonRandom if (value.isNull()) return defaultValue; if (value.isNumber()) - return value.Float(); + return static_cast(value.Float()); if (!value["amount"].isNull()) - return value["amount"].Float(); - si32 min = value["min"].Float(); - si32 max = value["max"].Float(); + return static_cast(value["amount"].Float()); + si32 min = static_cast(value["min"].Float()); + si32 max = static_cast(value["max"].Float()); return rng.getIntRange(min, max)(); } @@ -89,8 +89,8 @@ namespace JsonRandom for (auto & entry : value["slot"].Vector()) allowedPositions.insert(VLC->arth->stringToSlot(entry.String())); - if (!value["minValue"].isNull()) minValue = value["minValue"].Float(); - if (!value["maxValue"].isNull()) maxValue = value["maxValue"].Float(); + if (!value["minValue"].isNull()) minValue = static_cast(value["minValue"].Float()); + if (!value["maxValue"].isNull()) maxValue = static_cast(value["maxValue"].Float()); return VLC->arth->pickRandomArtifact(rng, [=](ArtifactID artID) -> bool { @@ -188,11 +188,11 @@ namespace JsonRandom RandomStackInfo info; if (!node["amount"].isNull()) - info.minAmount = info.maxAmount = node["amount"].Float(); + info.minAmount = info.maxAmount = static_cast(node["amount"].Float()); else { - info.minAmount = node["min"].Float(); - info.maxAmount = node["max"].Float(); + info.minAmount = static_cast(node["min"].Float()); + info.maxAmount = static_cast(node["max"].Float()); } const CCreature * crea = VLC->creh->creatures[VLC->modh->identifiers.getIdentifier("creature", node["type"]).get()]; info.allowedCreatures.push_back(crea); diff --git a/lib/mapObjects/MiscObjects.cpp b/lib/mapObjects/MiscObjects.cpp index 7a93a4c8b..0436a8e3b 100644 --- a/lib/mapObjects/MiscObjects.cpp +++ b/lib/mapObjects/MiscObjects.cpp @@ -248,7 +248,7 @@ void CGCreature::newTurn(CRandomGenerator & rand) const { if (stacks.begin()->second->count < VLC->modh->settings.CREEP_SIZE && cb->getDate(Date::DAY_OF_WEEK) == 1 && cb->getDate(Date::DAY) > 1) { - ui32 power = temppower * (100 + VLC->modh->settings.WEEKLY_GROWTH) / 100; + ui32 power = static_cast(temppower * (100 + VLC->modh->settings.WEEKLY_GROWTH) / 100); cb->setObjProperty(id, ObjProperty::MONSTER_COUNT, std::min(power / 1000, (ui32)VLC->modh->settings.CREEP_SIZE)); //set new amount cb->setObjProperty(id, ObjProperty::MONSTER_POWER, power); //increase temppower } @@ -432,7 +432,7 @@ void CGCreature::fight( const CGHeroInstance *h ) const { if (containsUpgradedStack()) //upgrade { - SlotID slotID = SlotID(std::floor((float)stacks.size() / 2)); + SlotID slotID = SlotID((si32)(std::floor((float)stacks.size() / 2.0f))); const auto & upgrades = getStack(slotID).type->upgrades; if(!upgrades.empty()) { @@ -515,12 +515,12 @@ bool CGCreature::containsUpgradedStack() const { //source http://heroescommunity.com/viewthread.php3?TID=27539&PID=830557#focus - float a = 2992.911117; - float b = 14174.264968; - float c = 5325.181015; - float d = 32788.727920; + float a = 2992.911117f; + float b = 14174.264968f; + float c = 5325.181015f; + float d = 32788.727920f; - int val = std::floor (a*pos.x + b*pos.y + c*pos.z + d); + int val = (int)std::floor (a*pos.x + b*pos.y + c*pos.z + d); return ((val % 32768) % 100) < 50; } @@ -1126,7 +1126,7 @@ void CGMonolith::initObj(CRandomGenerator & rand) channel = findMeChannel(IDs, subID); if(channel == TeleportChannelID()) - channel = TeleportChannelID(cb->gameState()->map->teleportChannels.size()); + channel = TeleportChannelID((si32)cb->gameState()->map->teleportChannels.size()); addToChannel(cb->gameState()->map->teleportChannels, this); } @@ -1178,7 +1178,7 @@ void CGSubterraneanGate::postInit() //matches subterranean gates into pairs { if(obj->channel == TeleportChannelID()) { // if object not linked to channel then create new channel - obj->channel = TeleportChannelID(cb->gameState()->map->teleportChannels.size()); + obj->channel = TeleportChannelID((si32)cb->gameState()->map->teleportChannels.size()); addToChannel(cb->gameState()->map->teleportChannels, obj); } }; @@ -1235,7 +1235,7 @@ void CGWhirlpool::onHeroVisit( const CGHeroInstance * h ) const targetstack = (i->first); } - TQuantity countToTake = h->getStackCount(targetstack) * 0.5; + TQuantity countToTake = static_cast(h->getStackCount(targetstack) * 0.5); vstd::amax(countToTake, 1); InfoWindow iw; @@ -1741,7 +1741,7 @@ void CGScholar::initObj(CRandomGenerator & rand) bonusID = rand.nextInt(GameConstants::PRIMARY_SKILLS -1); break; case SECONDARY_SKILL: - bonusID = rand.nextInt(VLC->skillh->size() - 1); + bonusID = rand.nextInt((int)VLC->skillh->size() - 1); break; case SPELL: std::vector possibilities; @@ -1935,7 +1935,7 @@ void CGSirens::onHeroVisit( const CGHeroInstance * h ) const for (auto i = h->Slots().begin(); i != h->Slots().end(); i++) { - TQuantity drown = i->second->count * 0.3; + TQuantity drown = static_cast(i->second->count * 0.3); if(drown) { cb->changeStackCount(StackLocation(h, i->first), -drown); @@ -1945,9 +1945,9 @@ void CGSirens::onHeroVisit( const CGHeroInstance * h ) const if(xp) { - xp = h->calculateXp(xp); + xp = h->calculateXp((int)xp); iw.text.addTxt(MetaString::ADVOB_TXT,132); - iw.text.addReplacement(xp); + iw.text.addReplacement((int)xp); cb->changePrimSkill(h, PrimarySkill::EXPERIENCE, xp, false); } else diff --git a/lib/mapObjects/ObjectTemplate.cpp b/lib/mapObjects/ObjectTemplate.cpp index 5cc2ccf98..f8763d2a3 100644 --- a/lib/mapObjects/ObjectTemplate.cpp +++ b/lib/mapObjects/ObjectTemplate.cpp @@ -143,7 +143,7 @@ void ObjectTemplate::readTxt(CLegacyConfigParser & parser) for (size_t i=0; i<9; i++) { if (terrStr[8-i] == '1') - allowedTerrains.insert(ETerrainType(i)); + allowedTerrains.insert(ETerrainType((si32)i)); } id = Obj(boost::lexical_cast(strings[5])); @@ -205,7 +205,7 @@ void ObjectTemplate::readMap(CBinaryReader & reader) for (size_t i=0; i<9; i++) { if (((terrMask >> i) & 1 ) != 0) - allowedTerrains.insert(ETerrainType(i)); + allowedTerrains.insert(ETerrainType((si32)i)); } id = Obj(reader.readUInt32()); @@ -252,7 +252,7 @@ void ObjectTemplate::readJson(const JsonNode &node, const bool withTerrain) else { for (size_t i=0; i< GameConstants::TERRAIN_TYPES; i++) - allowedTerrains.insert(ETerrainType(i)); + allowedTerrains.insert(ETerrainType((si32)i)); allowedTerrains.erase(ETerrainType::ROCK); } @@ -285,7 +285,7 @@ void ObjectTemplate::readJson(const JsonNode &node, const bool withTerrain) for (auto & line : mask) vstd::amax(width, line.String().size()); - setSize(width, height); + setSize((ui32)width, (ui32)height); for (size_t i=0; i(node["zIndex"].Float()); afterLoadFixup(); } @@ -397,7 +397,7 @@ ui32 ObjectTemplate::getWidth() const ui32 ret = 0; for (const auto &row : usedTiles) //copy is expensive { - ret = std::max(ret, row.size()); + ret = std::max(ret, (ui32)row.size()); } return ret; } @@ -405,7 +405,7 @@ ui32 ObjectTemplate::getWidth() const ui32 ObjectTemplate::getHeight() const { //TODO: Use 2D array - return usedTiles.size(); + return static_cast(usedTiles.size()); } void ObjectTemplate::setSize(ui32 width, ui32 height) @@ -428,7 +428,7 @@ bool ObjectTemplate::isWithin(si32 X, si32 Y) const { if (X < 0 || Y < 0) return false; - return !(X >= getWidth() || Y >= getHeight()); + return !(X >= (si32)getWidth() || Y >= (si32)getHeight()); } bool ObjectTemplate::isVisitableAt(si32 X, si32 Y) const @@ -449,9 +449,9 @@ bool ObjectTemplate::isBlockedAt(si32 X, si32 Y) const std::set ObjectTemplate::getBlockedOffsets() const { std::set ret; - for(int w = 0; w < getWidth(); ++w) + for(int w = 0; w < (int)getWidth(); ++w) { - for(int h = 0; h < getHeight(); ++h) + for(int h = 0; h < (int)getHeight(); ++h) { if (isBlockedAt(w, h)) ret.insert(int3(-w, -h, 0)); @@ -462,9 +462,9 @@ std::set ObjectTemplate::getBlockedOffsets() const int3 ObjectTemplate::getBlockMapOffset() const { - for(int w = 0; w < getWidth(); ++w) + for(int w = 0; w < (int)getWidth(); ++w) { - for(int h = 0; h < getHeight(); ++h) + for(int h = 0; h < (int)getHeight(); ++h) { if (isBlockedAt(w, h)) return int3(w, h, 0); @@ -494,8 +494,8 @@ bool ObjectTemplate::isVisitableFrom(si8 X, si8 Y) const int3 ObjectTemplate::getVisitableOffset() const { - for(int y = 0; y < getHeight(); y++) - for (int x = 0; x < getWidth(); x++) + for(int y = 0; y < (int)getHeight(); y++) + for (int x = 0; x < (int)getWidth(); x++) if (isVisitableAt(x, y)) return int3(x,y,0); diff --git a/lib/mapping/CCampaignHandler.cpp b/lib/mapping/CCampaignHandler.cpp index af41c1951..b86e5052d 100644 --- a/lib/mapping/CCampaignHandler.cpp +++ b/lib/mapping/CCampaignHandler.cpp @@ -77,7 +77,7 @@ std::unique_ptr CCampaignHandler::getCampaign( const std::string & na ret->header = readHeaderFromMemory(reader); ret->header.filename = name; - int howManyScenarios = VLC->generaltexth->campaignRegionNames[ret->header.mapVersion].size(); + int howManyScenarios = static_cast(VLC->generaltexth->campaignRegionNames[ret->header.mapVersion].size()); for(int g=0; gheader.version, ret->header.mapVersion); @@ -101,7 +101,7 @@ std::unique_ptr CCampaignHandler::getCampaign( const std::string & na //set map piece appropriately, convert vector to string ret->mapPieces[scenarioID].assign(reinterpret_cast< const char* >(file[g].data()), file[g].size()); CMapService mapService; - ret->scenarios[scenarioID].scenarioName = mapService.loadMapHeader((const ui8*)ret->mapPieces[scenarioID].c_str(), ret->mapPieces[scenarioID].size(), scenarioName)->name; + ret->scenarios[scenarioID].scenarioName = mapService.loadMapHeader((const ui8*)ret->mapPieces[scenarioID].c_str(), (int)ret->mapPieces[scenarioID].size(), scenarioName)->name; scenarioID++; } @@ -497,7 +497,7 @@ CMap * CCampaignState::getMap(int scenarioId) const std::string & mapContent = camp->mapPieces.find(scenarioId)->second; auto buffer = reinterpret_cast(mapContent.data()); CMapService mapService; - return mapService.loadMap(buffer, mapContent.size(), scenarioName).release(); + return mapService.loadMap(buffer, (int)mapContent.size(), scenarioName).release(); } std::unique_ptr CCampaignState::getHeader(int scenarioId) const @@ -511,7 +511,7 @@ std::unique_ptr CCampaignState::getHeader(int scenarioId) const std::string & mapContent = camp->mapPieces.find(scenarioId)->second; auto buffer = reinterpret_cast(mapContent.data()); CMapService mapService; - return mapService.loadMapHeader(buffer, mapContent.size(), scenarioName); + return mapService.loadMapHeader(buffer, (int)mapContent.size(), scenarioName); } std::shared_ptr CCampaignState::getMapInfo(int scenarioId) const diff --git a/lib/mapping/CMap.cpp b/lib/mapping/CMap.cpp index 9e52d460a..5eff238e9 100644 --- a/lib/mapping/CMap.cpp +++ b/lib/mapping/CMap.cpp @@ -587,7 +587,7 @@ void CMap::checkForObjectives() void CMap::addNewArtifactInstance(CArtifactInstance * art) { - art->id = ArtifactInstanceID(artInstances.size()); + art->id = ArtifactInstanceID((si32)artInstances.size()); artInstances.push_back(art); } @@ -599,13 +599,13 @@ void CMap::eraseArtifactInstance(CArtifactInstance * art) void CMap::addNewQuestInstance(CQuest* quest) { - quest->qid = quests.size(); + quest->qid = static_cast(quests.size()); quests.push_back(quest); } void CMap::addNewObject(CGObjectInstance * obj) { - if(obj->id != ObjectInstanceID(objects.size())) + if(obj->id != ObjectInstanceID((si32)objects.size())) throw std::runtime_error("Invalid object instance id"); if(obj->instanceName == "") diff --git a/lib/mapping/CMapEditManager.cpp b/lib/mapping/CMapEditManager.cpp index e9246ba9a..fd632fb87 100644 --- a/lib/mapping/CMapEditManager.cpp +++ b/lib/mapping/CMapEditManager.cpp @@ -608,7 +608,7 @@ void CDrawTerrainOperation::updateTerrainTypes() terrainTile.terType = centerTile.terType; auto testTile = getInvalidTiles(posToTest); - int nativeTilesCntNorm = testTile.nativeTiles.empty() ? std::numeric_limits::max() : testTile.nativeTiles.size(); + int nativeTilesCntNorm = testTile.nativeTiles.empty() ? std::numeric_limits::max() : (int)testTile.nativeTiles.size(); bool putSuitableTile = false; bool addToSuitableTiles = false; @@ -652,7 +652,7 @@ void CDrawTerrainOperation::updateTerrainTypes() //} invalidNativeTilesCnt = nativeTilesCntNorm; - invalidForeignTilesCnt = testTile.foreignTiles.size(); + invalidForeignTilesCnt = static_cast(testTile.foreignTiles.size()); suitableTiles.clear(); addToSuitableTiles = true; } @@ -1081,7 +1081,7 @@ CInsertObjectOperation::CInsertObjectOperation(CMap * map, CGObjectInstance * ob void CInsertObjectOperation::execute() { - obj->id = ObjectInstanceID(map->objects.size()); + obj->id = ObjectInstanceID((si32)map->objects.size()); boost::format fmt("%s_%d"); fmt % obj->typeName % obj->id.getNum(); diff --git a/lib/mapping/MapFormatH3M.cpp b/lib/mapping/MapFormatH3M.cpp index 69441f087..0ddf09038 100644 --- a/lib/mapping/MapFormatH3M.cpp +++ b/lib/mapping/MapFormatH3M.cpp @@ -851,7 +851,7 @@ void CMapLoaderH3M::loadArtifactsOfHero(CGHeroInstance * hero) int amount = reader.readUInt16(); for(int ss = 0; ss < amount; ++ss) { - loadArtifactToSlot(hero, GameConstants::BACKPACK_START + hero->artifactsInBackpack.size()); + loadArtifactToSlot(hero, GameConstants::BACKPACK_START + (int)hero->artifactsInBackpack.size()); } } } @@ -966,7 +966,7 @@ void CMapLoaderH3M::readObjects() int3 objPos = readInt3(); int defnum = reader.readUInt32(); - ObjectInstanceID idToBeGiven = ObjectInstanceID(map->objects.size()); + ObjectInstanceID idToBeGiven = ObjectInstanceID((si32)map->objects.size()); ObjectTemplate & objTempl = templates.at(defnum); reader.skip(5); @@ -1482,7 +1482,7 @@ void CMapLoaderH3M::readObjects() nobj->subID = objTempl.subid; } nobj->appearance = objTempl; - assert(idToBeGiven == ObjectInstanceID(map->objects.size())); + assert(idToBeGiven == ObjectInstanceID((si32)map->objects.size())); { //TODO: define valid typeName and subtypeName fro H3M maps @@ -2072,11 +2072,11 @@ std::set CMapLoaderH3M::convertBuildings(const std::set for(const JsonNode & entry : config["table"].Vector()) { - int town = entry["town"].Float(); + int town = static_cast(entry["town"].Float()); if (town == castleID || town == -1) { - mapa[entry["h3"].Float()] = BuildingID((si32)entry["vcmi"].Float()); + mapa[(int)entry["h3"].Float()] = BuildingID((si32)entry["vcmi"].Float()); } } diff --git a/lib/mapping/MapFormatJson.cpp b/lib/mapping/MapFormatJson.cpp index c1f95a270..97d69927f 100644 --- a/lib/mapping/MapFormatJson.cpp +++ b/lib/mapping/MapFormatJson.cpp @@ -219,7 +219,7 @@ namespace TriggeredEventsDetail event.objectType = type.get(); event.objectInstanceName = data["object"].String(); if(data["value"].isNumber()) - event.value = data["value"].Integer(); + event.value = static_cast(data["value"].Integer()); } break; case EventCondition::HAVE_BUILDING_0: @@ -240,10 +240,10 @@ namespace TriggeredEventsDetail } if (data["type"].isNumber()) - event.objectType = data["type"].Float(); + event.objectType = static_cast(data["type"].Float()); if (!data["value"].isNull()) - event.value = data["value"].Float(); + event.value = static_cast(data["value"].Float()); } break; } @@ -251,9 +251,9 @@ namespace TriggeredEventsDetail if (!data["position"].isNull()) { auto & position = data["position"].Vector(); - event.position.x = position.at(0).Float(); - event.position.y = position.at(1).Float(); - event.position.z = position.at(2).Float(); + event.position.x = static_cast(position.at(0).Float()); + event.position.y = static_cast(position.at(1).Float()); + event.position.z = static_cast(position.at(2).Float()); } } return event; @@ -380,7 +380,7 @@ void CMapFormatJson::serializeAllowedFactions(JsonSerializeFormat & handler, std value.clear(); for (std::size_t i=0; ihowManyTeams = srcVector.size(); + mapHeader->howManyTeams = static_cast(srcVector.size()); for(int team = 0; team < mapHeader->howManyTeams; team++) for(const JsonNode & playerData : srcVector[team].Vector()) @@ -911,7 +911,7 @@ void CMapLoaderJson::readHeader(const bool complete) //do not use map field here, use only mapHeader JsonNode header = getFromArchive(HEADER_FILE_NAME); - fileVersionMajor = header["versionMajor"].Integer(); + fileVersionMajor = static_cast(header["versionMajor"].Integer()); if(fileVersionMajor != VERSION_MAJOR) { @@ -919,7 +919,7 @@ void CMapLoaderJson::readHeader(const bool complete) throw std::runtime_error("Unsupported map format version"); } - fileVersionMinor = header["versionMinor"].Integer(); + fileVersionMinor = static_cast(header["versionMinor"].Integer()); if(fileVersionMinor > VERSION_MINOR) { @@ -1114,16 +1114,16 @@ void CMapLoaderJson::MapObjectLoader::construct() } int3 pos; - pos.x = configuration["x"].Float(); - pos.y = configuration["y"].Float(); - pos.z = configuration["l"].Float(); + pos.x = static_cast(configuration["x"].Float()); + pos.y = static_cast(configuration["y"].Float()); + pos.z = static_cast(configuration["l"].Float()); //special case for grail if(typeName == "grail") { owner->map->grailPos = pos; - owner->map->grailRadius = configuration["options"]["grailRadius"].Float(); + owner->map->grailRadius = static_cast(configuration["options"]["grailRadius"].Float()); return; } else if(subtypeName.empty()) @@ -1143,7 +1143,7 @@ void CMapLoaderJson::MapObjectLoader::construct() instance = handler->create(appearance); - instance->id = ObjectInstanceID(owner->map->objects.size()); + instance->id = ObjectInstanceID((si32)owner->map->objects.size()); instance->instanceName = jsonKey; instance->pos = pos; owner->map->addNewObject(instance); diff --git a/lib/rmg/CMapGenOptions.cpp b/lib/rmg/CMapGenOptions.cpp index cb1c9d875..321bf1331 100644 --- a/lib/rmg/CMapGenOptions.cpp +++ b/lib/rmg/CMapGenOptions.cpp @@ -331,7 +331,7 @@ void CMapGenOptions::updateCompOnlyPlayers() } // Add some comp only players if necessary - int compOnlyPlayersToAdd = getPlayerCount() - players.size(); + int compOnlyPlayersToAdd = static_cast(getPlayerCount() - players.size()); if (compOnlyPlayersToAdd < 0) { diff --git a/lib/rmg/CMapGenerator.cpp b/lib/rmg/CMapGenerator.cpp index e14d76ea1..994c043cd 100644 --- a/lib/rmg/CMapGenerator.cpp +++ b/lib/rmg/CMapGenerator.cpp @@ -532,9 +532,9 @@ void CMapGenerator::createDirectConnections() //find tiles with minimum manhattan distance from center of the mass of zone border size_t tilesCount = middleTiles.size() ? middleTiles.size() : 1; int3 middleTile = std::accumulate(middleTiles.begin(), middleTiles.end(), int3(0, 0, 0)); - middleTile.x /= tilesCount; - middleTile.y /= tilesCount; - middleTile.z /= tilesCount; //TODO: implement division operator for int3? + middleTile.x /= (si32)tilesCount; + middleTile.y /= (si32)tilesCount; + middleTile.z /= (si32)tilesCount; //TODO: implement division operator for int3? boost::sort(middleTiles, [middleTile](const int3 &lhs, const int3 &rhs) -> bool { //choose tiles with both corrdinates in the middle @@ -640,8 +640,8 @@ void CMapGenerator::createConnections2() int3 otherTile = tile; otherTile.z = posB.z; - float distanceFromA = posA.dist2d(tile); - float distanceFromB = posB.dist2d(otherTile); + float distanceFromA = static_cast(posA.dist2d(tile)); + float distanceFromB = static_cast(posB.dist2d(otherTile)); if (distanceFromA > 5 && distanceFromB > 5) { diff --git a/lib/rmg/CRmgTemplateZone.cpp b/lib/rmg/CRmgTemplateZone.cpp index fb3f61ff5..82544b23f 100644 --- a/lib/rmg/CRmgTemplateZone.cpp +++ b/lib/rmg/CRmgTemplateZone.cpp @@ -36,7 +36,7 @@ void CRmgTemplateZone::addRoadNode(const int3& node) roadNodes.insert(node); } -CTileInfo::CTileInfo():nearestObjectDistance(INT_MAX), terrain(ETerrainType::WRONG),roadType(ERoadType::NO_ROAD) +CTileInfo::CTileInfo():nearestObjectDistance(float(INT_MAX)), terrain(ETerrainType::WRONG),roadType(ERoadType::NO_ROAD) { occupied = ETileType::POSSIBLE; //all tiles are initially possible to place objects or passages } @@ -145,8 +145,8 @@ void CRmgTemplateZone::setCenter(const float3 &f) //alternate solution - wrap zone around unitary square. If it doesn't fit on one side, will come out on the opposite side center = f; - center.x = std::fmod(center.x, 1); - center.y = std::fmod(center.y, 1); + center.x = static_cast(std::fmod(center.x, 1)); + center.y = static_cast(std::fmod(center.y, 1)); if (center.x < 0) //fmod seems to work only for positive numbers? we want to stay positive center.x = 1 - std::abs(center.x); @@ -291,7 +291,7 @@ void CRmgTemplateZone::fractalize() for (auto clearTile : clearedTiles) { - float distance = tileToMakePath.dist2dSQ(clearTile); + float distance = static_cast(tileToMakePath.dist2dSQ(clearTile)); if (distance < currentDistance) { @@ -369,7 +369,7 @@ void CRmgTemplateZone::fractalize() for (auto clearTile : freePaths) { - float distance = tile.dist2dSQ(clearTile); + float distance = static_cast(tile.dist2dSQ(clearTile)); if (distance < blockDistance) { @@ -436,7 +436,7 @@ do not leave zone border bool end = false; int3 currentPos = src; - float distance = currentPos.dist2dSQ (dst); + float distance = static_cast(currentPos.dist2dSQ (dst)); while (!end) { @@ -469,7 +469,7 @@ do not leave zone border if (clearedTiles) clearedTiles->insert(pos); currentPos = pos; - distance = currentPos.dist2dSQ (dst); + distance = static_cast(currentPos.dist2dSQ (dst)); } else if (gen->isFree(pos)) { @@ -505,7 +505,7 @@ do not leave zone border if (clearedTiles) clearedTiles->insert(pos); anotherPos = pos; - lastDistance = currentPos.dist2dSQ(dst); + lastDistance = static_cast(currentPos.dist2dSQ(dst)); } } } @@ -534,7 +534,7 @@ do not leave zone border return result; } -boost::heap::priority_queue> CRmgTemplateZone::createPiorityQueue() +boost::heap::priority_queue> CRmgTemplateZone::createPriorityQueue() { return boost::heap::priority_queue>(); } @@ -544,7 +544,7 @@ bool CRmgTemplateZone::createRoad(const int3& src, const int3& dst) //A* algorithm taken from Wiki http://en.wikipedia.org/wiki/A*_search_algorithm std::set closed; // The set of nodes already evaluated. - auto pq = createPiorityQueue(); // The set of tentative nodes to be evaluated, initially containing the start node + auto pq = createPriorityQueue(); // The set of tentative nodes to be evaluated, initially containing the start node std::map cameFrom; // The map of navigated nodes. std::map distances; @@ -634,7 +634,7 @@ bool CRmgTemplateZone::connectPath(const int3& src, bool onlyStraight) //A* algorithm taken from Wiki http://en.wikipedia.org/wiki/A*_search_algorithm std::set closed; // The set of nodes already evaluated. - auto open = createPiorityQueue(); // The set of tentative nodes to be evaluated, initially containing the start node + auto open = createPriorityQueue(); // The set of tentative nodes to be evaluated, initially containing the start node std::map cameFrom; // The map of navigated nodes. std::map distances; @@ -676,17 +676,17 @@ bool CRmgTemplateZone::connectPath(const int3& src, bool onlyStraight) if (gen->isBlocked(pos) || gen->getZoneID(pos) != id) return; - int distance = distances[currentNode] + 1; + int distance = static_cast(distances[currentNode]) + 1; int bestDistanceSoFar = std::numeric_limits::max(); auto it = distances.find(pos); if (it != distances.end()) - bestDistanceSoFar = it->second; + bestDistanceSoFar = static_cast(it->second); if (distance < bestDistanceSoFar) { cameFrom[pos] = currentNode; - open.push(std::make_pair(pos, distance)); - distances[pos] = distance; + open.push(std::make_pair(pos, (float)distance)); + distances[pos] = static_cast(distance); } }; @@ -711,7 +711,7 @@ bool CRmgTemplateZone::connectWithCenter(const int3& src, bool onlyStraight) //A* algorithm taken from Wiki http://en.wikipedia.org/wiki/A*_search_algorithm std::set closed; // The set of nodes already evaluated. - auto open = createPiorityQueue(); // The set of tentative nodes to be evaluated, initially containing the start node + auto open = createPriorityQueue(); // The set of tentative nodes to be evaluated, initially containing the start node std::map cameFrom; // The map of navigated nodes. std::map distances; @@ -761,7 +761,7 @@ bool CRmgTemplateZone::connectWithCenter(const int3& src, bool onlyStraight) int bestDistanceSoFar = std::numeric_limits::max(); //FIXME: boost::limits auto it = distances.find(pos); if (it != distances.end()) - bestDistanceSoFar = it->second; + bestDistanceSoFar = static_cast(it->second); if (distance < bestDistanceSoFar) { @@ -808,8 +808,8 @@ bool CRmgTemplateZone::addMonster(int3 &pos, si32 strength, bool clearSurroundin static const float multiplier1[] = {0.5, 0.75, 1.0, 1.5, 1.5}; static const float multiplier2[] = {0.5, 0.75, 1.0, 1.0, 1.5}; - int strength1 = std::max(0.f, (strength - value1[monsterStrength]) * multiplier1[monsterStrength]); - int strength2 = std::max(0.f, (strength - value2[monsterStrength]) * multiplier2[monsterStrength]); + int strength1 = static_cast(std::max(0.f, (strength - value1[monsterStrength]) * multiplier1[monsterStrength])); + int strength2 = static_cast(std::max(0.f, (strength - value2[monsterStrength]) * multiplier2[monsterStrength])); strength = strength1 + strength2; if (strength < 2000) @@ -826,7 +826,7 @@ bool CRmgTemplateZone::addMonster(int3 &pos, si32 strength, bool clearSurroundin continue; if (!vstd::contains(monsterTypes, cre->faction)) continue; - if ((cre->AIValue * (cre->ammMin + cre->ammMax) / 2 < strength) && (strength < cre->AIValue * 100)) //at least one full monster. size between average size of given stack and 100 + if (((si32)(cre->AIValue * (cre->ammMin + cre->ammMax) / 2) < strength) && (strength < (si32)cre->AIValue * 100)) //at least one full monster. size between average size of given stack and 100 { possibleCreatures.push_back(cre->idNumber); } @@ -836,7 +836,7 @@ bool CRmgTemplateZone::addMonster(int3 &pos, si32 strength, bool clearSurroundin creId = *RandomGeneratorUtil::nextItem(possibleCreatures, gen->rand); amount = strength / VLC->creh->creatures[creId]->AIValue; if (amount >= 4) - amount *= gen->rand.nextDouble(0.75, 1.25); + amount = static_cast(amount * gen->rand.nextDouble(0.75, 1.25)); } else //just pick any available creature { @@ -883,7 +883,7 @@ bool CRmgTemplateZone::createTreasurePile(int3 &pos, float minDistance, const CT int currentValue = 0; CGObjectInstance * object = nullptr; - while (currentValue <= desiredValue - 100) //no objects with value below 100 are avaiable + while (currentValue <= (int)desiredValue - 100) //no objects with value below 100 are available { treasures[info.nextTreasurePos] = nullptr; @@ -993,7 +993,7 @@ bool CRmgTemplateZone::createTreasurePile(int3 &pos, float minDistance, const CT if (closestFreeTile.dist2d(visitablePos) < minTreasureDistance) { closestTile = visitablePos + int3 (0, 1, 0); //start below object (y+1), possibly even outside the map, to not make path up through it - minTreasureDistance = closestFreeTile.dist2d(visitablePos); + minTreasureDistance = static_cast(closestFreeTile.dist2d(visitablePos)); } } for (auto visitablePos : info.visitableFromTopPositions) //all objects are accessible from any direction @@ -1002,7 +1002,7 @@ bool CRmgTemplateZone::createTreasurePile(int3 &pos, float minDistance, const CT if (closestFreeTile.dist2d(visitablePos) < minTreasureDistance) { closestTile = visitablePos; - minTreasureDistance = closestFreeTile.dist2d(visitablePos); + minTreasureDistance = static_cast(closestFreeTile.dist2d(visitablePos)); } } assert (closestTile.valid()); @@ -1415,8 +1415,8 @@ bool CRmgTemplateZone::createRequiredObjects() // smallest distance to zone center, greatest distance to nearest object auto isCloser = [this](const int3 & lhs, const int3 & rhs) -> bool { - float lDist = this->pos.dist2d(lhs); - float rDist = this->pos.dist2d(rhs); + float lDist = static_cast(this->pos.dist2d(lhs)); + float rDist = static_cast(this->pos.dist2d(rhs)); lDist *= (lDist > 12) ? 10 : 1; //objects within 12 tile radius are preferred (smaller distance rating) rDist *= (rDist > 12) ? 10 : 1; @@ -1499,7 +1499,7 @@ void CRmgTemplateZone::createTreasures() //also, normalize it to zone count - higher count means relatively smaller zones //this is squared distance for optimization purposes - const double minDistance = std::max((125.f / totalDensity), 2); + const float minDistance = std::max((125.f / totalDensity), 2.0f); //distance lower than 2 causes objects to overlap and crash bool stop = false; @@ -1567,7 +1567,7 @@ void CRmgTemplateZone::createObstacles2() for (auto temp : handler->getTemplates()) { if (temp.canBePlacedAt(terrainType) && temp.getBlockMapOffset().valid()) - obstaclesBySize[temp.getBlockedOffsets().size()].push_back(temp); + obstaclesBySize[(ui8)temp.getBlockedOffsets().size()].push_back(temp); } } } @@ -1837,7 +1837,7 @@ bool CRmgTemplateZone::findPlaceForObject(CGObjectInstance* obj, si32 min_dist, { if (areAllTilesAvailable(obj, tile, tilesBlockedByObject)) { - best_distance = dist; + best_distance = static_cast(dist); pos = tile; result = true; } @@ -1918,7 +1918,7 @@ void CRmgTemplateZone::updateDistances(const int3 & pos) for (auto tile : possibleTiles) //don't need to mark distance for not possible tiles { ui32 d = pos.dist2dSQ(tile); //optimization, only relative distance is interesting - gen->setNearestObjectDistance(tile, std::min(d, gen->getNearestObjectDistance(tile))); + gen->setNearestObjectDistance(tile, std::min((float)d, gen->getNearestObjectDistance(tile))); } } @@ -2015,7 +2015,7 @@ ObjectInfo CRmgTemplateZone::getRandomObject(CTreasurePileInfo &info, ui32 desir //calculate actual treasure value range based on remaining value ui32 maxVal = desiredValue - currentValue; - ui32 minValue = 0.25f * (desiredValue - currentValue); + ui32 minValue = static_cast(0.25f * (desiredValue - currentValue)); //roulette wheel for (ObjectInfo &oi : possibleObjects) //copy constructor turned out to be costly @@ -2153,7 +2153,7 @@ ObjectInfo CRmgTemplateZone::getRandomObject(CTreasurePileInfo &info, ui32 desir auto it = std::lower_bound(thresholds.begin(), thresholds.end(), r, [](const std::pair &rhs, const int lhs)->bool { - return rhs.first < lhs; + return (int)rhs.first < lhs; }); return *(it->second); } @@ -2163,7 +2163,7 @@ void CRmgTemplateZone::addAllPossibleObjects() { ObjectInfo oi; - int numZones = gen->getZones().size(); + int numZones = static_cast(gen->getZones().size()); std::vector creatures; //native creatures for this zone for (auto cre : VLC->creh->creatures) @@ -2261,8 +2261,8 @@ void CRmgTemplateZone::addAllPossibleObjects() auto cre = creatures.front(); if (cre->faction == townType) { - float nativeZonesCount = gen->getZoneCount(cre->faction); - oi.value = cre->AIValue * cre->growth * (1 + (nativeZonesCount / gen->getTotalZoneCount()) + (nativeZonesCount / 2)); + float nativeZonesCount = static_cast(gen->getZoneCount(cre->faction)); + oi.value = static_cast(cre->AIValue * cre->growth * (1 + (nativeZonesCount / gen->getTotalZoneCount()) + (nativeZonesCount / 2))); oi.probability = 40; for (auto temp : dwellingHandler->getTemplates()) @@ -2370,7 +2370,7 @@ void CRmgTemplateZone::addAllPossibleObjects() { creaturesAmount = boost::math::round(creaturesAmount / 10) * 10; } - return creaturesAmount; + return static_cast(creaturesAmount); }; for (auto creature : creatures) @@ -2388,7 +2388,7 @@ void CRmgTemplateZone::addAllPossibleObjects() return obj; }; oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType); - oi.value = (2 * (creature->AIValue) * creaturesAmount * (1 + (float)(gen->getZoneCount(creature->faction)) / gen->getTotalZoneCount())) / 3; + oi.value = static_cast((2 * (creature->AIValue) * creaturesAmount * (1 + (float)(gen->getZoneCount(creature->faction)) / gen->getTotalZoneCount())) / 3); oi.probability = 3; possibleObjects.push_back(oi); } @@ -2409,7 +2409,7 @@ void CRmgTemplateZone::addAllPossibleObjects() } RandomGeneratorUtil::randomShuffle(spells, gen->rand); - for (int j = 0; j < std::min(12, spells.size()); j++) + for (int j = 0; j < std::min(12, (int)spells.size()); j++) { obj->spells.push_back(spells[j]->id); } @@ -2439,7 +2439,7 @@ void CRmgTemplateZone::addAllPossibleObjects() } RandomGeneratorUtil::randomShuffle(spells, gen->rand); - for (int j = 0; j < std::min(15, spells.size()); j++) + for (int j = 0; j < std::min(15, (int)spells.size()); j++) { obj->spells.push_back(spells[j]->id); } @@ -2467,7 +2467,7 @@ void CRmgTemplateZone::addAllPossibleObjects() } RandomGeneratorUtil::randomShuffle(spells, gen->rand); - for (int j = 0; j < std::min(60, spells.size()); j++) + for (int j = 0; j < std::min(60, (int)spells.size()); j++) { obj->spells.push_back(spells[j]->id); } @@ -2485,13 +2485,13 @@ void CRmgTemplateZone::addAllPossibleObjects() { static const int genericSeerHuts = 8; int seerHutsPerType = 0; - const int questArtsRemaining = gen->getQuestArtsRemaning().size(); + const int questArtsRemaining = static_cast(gen->getQuestArtsRemaning().size()); //general issue is that not many artifact types are available for quests - if (questArtsRemaining >= genericSeerHuts + creatures.size()) + if (questArtsRemaining >= genericSeerHuts + (int)creatures.size()) { - seerHutsPerType = questArtsRemaining / (genericSeerHuts + creatures.size()); + seerHutsPerType = questArtsRemaining / (genericSeerHuts + (int)creatures.size()); } else if (questArtsRemaining >= genericSeerHuts) { @@ -2516,7 +2516,7 @@ void CRmgTemplateZone::addAllPossibleObjects() return artInfo; }; - for (int i = 0; i < std::min(creatures.size(), questArtsRemaining - genericSeerHuts); i++) + for (int i = 0; i < std::min((int)creatures.size(), questArtsRemaining - genericSeerHuts); i++) { auto creature = creatures[i]; int creaturesAmount = creatureToCount(creature); @@ -2547,7 +2547,7 @@ void CRmgTemplateZone::addAllPossibleObjects() return obj; }; oi.setTemplate(Obj::SEER_HUT, randomAppearance, terrainType); - oi.value = ((2 * (creature->AIValue) * creaturesAmount * (1 + (float)(gen->getZoneCount(creature->faction)) / gen->getTotalZoneCount())) - 4000) / 3; + oi.value = static_cast(((2 * (creature->AIValue) * creaturesAmount * (1 + (float)(gen->getZoneCount(creature->faction)) / gen->getTotalZoneCount())) - 4000) / 3); oi.probability = 3; possibleObjects.push_back(oi); } diff --git a/lib/rmg/CRmgTemplateZone.h b/lib/rmg/CRmgTemplateZone.h index c1d19eeb3..2656f4699 100644 --- a/lib/rmg/CRmgTemplateZone.h +++ b/lib/rmg/CRmgTemplateZone.h @@ -157,7 +157,7 @@ public: return (rhs.second < lhs.second); } }; - boost::heap::priority_queue> createPiorityQueue(); + boost::heap::priority_queue> createPriorityQueue(); private: CMapGenerator * gen; diff --git a/lib/rmg/CZonePlacer.cpp b/lib/rmg/CZonePlacer.cpp index 8a86aa9ad..9cb59eb4b 100644 --- a/lib/rmg/CZonePlacer.cpp +++ b/lib/rmg/CZonePlacer.cpp @@ -32,12 +32,12 @@ CZonePlacer::~CZonePlacer() int3 CZonePlacer::cords (const float3 f) const { - return int3(std::max(0.f, (f.x * gen->map->width)-1), std::max(0.f, (f.y * gen->map->height-1)), f.z); + return int3((si32)std::max(0.f, (f.x * gen->map->width)-1), (si32)std::max(0.f, (f.y * gen->map->height-1)), f.z); } float CZonePlacer::getDistance (float distance) const { - return (distance ? distance * distance : 1e-6); + return (distance ? distance * distance : 1e-6f); } void CZonePlacer::placeZones(const CMapGenOptions * mapGenOptions, CRandomGenerator * rand) @@ -56,8 +56,8 @@ void CZonePlacer::placeZones(const CMapGenOptions * mapGenOptions, CRandomGenera let's assume we try to fit N circular zones with radius = size on a map */ - gravityConstant = 4e-3; - stiffnessConstant = 4e-3; + gravityConstant = 4e-3f; + stiffnessConstant = 4e-3f; TZoneVector zonesVector(zones.begin(), zones.end()); assert (zonesVector.size()); @@ -67,7 +67,7 @@ void CZonePlacer::placeZones(const CMapGenOptions * mapGenOptions, CRandomGenera //0. set zone sizes and surface / underground level prepareZones(zones, zonesVector, underground, rand); - //gravity-based algorithm. connected zones attract, intersceting zones and map boundaries push back + //gravity-based algorithm. connected zones attract, intersecting zones and map boundaries push back //remember best solution float bestTotalDistance = 1e10; @@ -236,7 +236,7 @@ void CZonePlacer::prepareZones(TZoneMap &zones, TZoneVector &zonesVector, const { int level = levels[zone.first]; totalSize[level] += (zone.second->getSize() * zone.second->getSize()); - float randomAngle = rand->nextDouble(0, pi2); + float randomAngle = static_cast(rand->nextDouble(0, pi2)); zone.second->setCenter(float3(0.5f + std::sin(randomAngle) * radius, 0.5f + std::cos(randomAngle) * radius, level)); //place zones around circle } @@ -251,10 +251,10 @@ void CZonePlacer::prepareZones(TZoneMap &zones, TZoneVector &zonesVector, const std::vector prescaler = { 0, 0 }; for (int i = 0; i < 2; i++) prescaler[i] = sqrt((width * height) / (totalSize[i] * 3.14f)); - mapSize = sqrt(width * height); + mapSize = static_cast(sqrt(width * height)); for (auto zone : zones) { - zone.second->setSize(zone.second->getSize() * prescaler[zone.second->getCenter().z]); + zone.second->setSize((int)(zone.second->getSize() * prescaler[zone.second->getCenter().z])); } } @@ -270,7 +270,7 @@ void CZonePlacer::attractConnectedZones(TZoneMap &zones, TForceVector &forces, T { auto otherZone = zones[con]; float3 otherZoneCenter = otherZone->getCenter(); - float distance = pos.dist2d(otherZoneCenter); + float distance = static_cast(pos.dist2d(otherZoneCenter)); float minDistance = 0; if (pos.z != otherZoneCenter.z) @@ -300,7 +300,7 @@ void CZonePlacer::separateOverlappingZones(TZoneMap &zones, TForceVector &forces float3 pos = zone.second->getCenter(); float overlap = 0; - //separate overlaping zones + //separate overlapping zones for (auto otherZone : zones) { float3 otherZoneCenter = otherZone.second->getCenter(); @@ -308,11 +308,11 @@ void CZonePlacer::separateOverlappingZones(TZoneMap &zones, TForceVector &forces if (zone == otherZone || pos.z != otherZoneCenter.z) continue; - float distance = pos.dist2d(otherZoneCenter); + float distance = static_cast(pos.dist2d(otherZoneCenter)); float minDistance = (zone.second->getSize() + otherZone.second->getSize()) / mapSize; if (distance < minDistance) { - forceVector -= (((otherZoneCenter - pos)*(minDistance / (distance ? distance : 1e-3))) / getDistance(distance)) * stiffnessConstant; //negative value + forceVector -= (((otherZoneCenter - pos)*(minDistance / (distance ? distance : 1e-3f))) / getDistance(distance)) * stiffnessConstant; //negative value overlap += (minDistance - distance); //overlapping of small zones hurts us more } } @@ -324,7 +324,7 @@ void CZonePlacer::separateOverlappingZones(TZoneMap &zones, TForceVector &forces auto pushAwayFromBoundary = [&forceVector, pos, size, &overlap, this](float x, float y) { float3 boundary = float3(x, y, pos.z); - float distance = pos.dist2d(boundary); + float distance = static_cast(pos.dist2d(boundary)); overlap += std::max(0, distance - size); //check if we're closer to map boundary than value of zone size forceVector -= (boundary - pos) * (size - distance) / this->getDistance(distance) * this->stiffnessConstant; //negative value }; @@ -353,7 +353,7 @@ void CZonePlacer::separateOverlappingZones(TZoneMap &zones, TForceVector &forces void CZonePlacer::moveOneZone(TZoneMap &zones, TForceVector &totalForces, TDistanceVector &distances, TDistanceVector &overlaps) { float maxRatio = 0; - const int maxDistanceMovementRatio = zones.size() * zones.size(); //experimental - the more zones, the greater total distance expected + const int maxDistanceMovementRatio = static_cast(zones.size() * zones.size()); //experimental - the more zones, the greater total distance expected std::shared_ptr misplacedZone; float totalDistance = 0; @@ -363,7 +363,7 @@ void CZonePlacer::moveOneZone(TZoneMap &zones, TForceVector &totalForces, TDista totalDistance += zone.second; float overlap = overlaps[zone.first]; totalOverlap += overlap; - float ratio = (zone.second + overlap) / totalForces[zone.first].mag(); //if distance to actual movement is long, the zone is misplaced + float ratio = (zone.second + overlap) / (float)totalForces[zone.first].mag(); //if distance to actual movement is long, the zone is misplaced if (ratio > maxRatio) { maxRatio = ratio; @@ -384,7 +384,7 @@ void CZonePlacer::moveOneZone(TZoneMap &zones, TForceVector &totalForces, TDista for (auto con : misplacedZone->getConnections()) { auto otherZone = zones[con]; - float distance = otherZone->getCenter().dist2dSQ(ourCenter); + float distance = static_cast(otherZone->getCenter().dist2dSQ(ourCenter)); if (distance > maxDistance) { maxDistance = distance; @@ -412,7 +412,7 @@ void CZonePlacer::moveOneZone(TZoneMap &zones, TForceVector &totalForces, TDista if (otherZone.second == misplacedZone || otherZoneCenter.z != ourCenter.z) continue; - float distance = otherZoneCenter.dist2dSQ(ourCenter); + float distance = static_cast(otherZoneCenter.dist2dSQ(ourCenter)); if (distance > maxOverlap) { maxOverlap = distance; @@ -450,7 +450,7 @@ d = 0.01 * dx^3 - 0.1618 * dx^2 + 1 * dx + ... float dy = abs(A.y - B.y) * scaleY; //Horner scheme - return dx * (1 + dx * (0.1 + dx * 0.01)) + dy * (1.618 + dy * (-0.1618 + dy * 0.01618)); + return dx * (1.0f + dx * (0.1f + dx * 0.01f)) + dy * (1.618f + dy * (-0.1618f + dy * 0.01618f)); } void CZonePlacer::assignZones(const CMapGenOptions * mapGenOptions) @@ -486,7 +486,7 @@ void CZonePlacer::assignZones(const CMapGenOptions * mapGenOptions) { total += tile; } - int size = tiles.size(); + int size = static_cast(tiles.size()); assert(size); zone->setPos(int3(total.x / size, total.y / size, total.z / size)); }; @@ -509,7 +509,7 @@ void CZonePlacer::assignZones(const CMapGenOptions * mapGenOptions) for (auto zone : zones) { if (zone.second->getPos().z == k) - distances.push_back(std::make_pair(zone.second, pos.dist2dSQ(zone.second->getPos()))); + distances.push_back(std::make_pair(zone.second, (float)pos.dist2dSQ(zone.second->getPos()))); else distances.push_back(std::make_pair(zone.second, std::numeric_limits::max())); } @@ -557,7 +557,7 @@ void CZonePlacer::assignZones(const CMapGenOptions * mapGenOptions) if (zone.second->getPos().z) { if (!CREATE_FULL_UNDERGROUND) - zone.second->discardDistantTiles(zone.second->getSize() + 1); + zone.second->discardDistantTiles((float)(zone.second->getSize() + 1)); //make sure that terrain inside zone is not a rock //FIXME: reorder actions? diff --git a/lib/rmg/float3.h b/lib/rmg/float3.h index e3068d610..13942d6fb 100644 --- a/lib/rmg/float3.h +++ b/lib/rmg/float3.h @@ -52,7 +52,7 @@ public: } float3 unitVector() const { - return float3(x, y, z) / mag(); + return float3(x, y, z) / (float)mag(); } // returns distance on Oxy plane (z coord is not used) double dist2d(const float3 &other) const { return std::sqrt(dist2dSQ(other)); } diff --git a/lib/serializer/BinaryDeserializer.cpp b/lib/serializer/BinaryDeserializer.cpp index eb825c399..d48587c42 100644 --- a/lib/serializer/BinaryDeserializer.cpp +++ b/lib/serializer/BinaryDeserializer.cpp @@ -97,7 +97,7 @@ void CLoadFile::clear() void CLoadFile::checkMagicBytes(const std::string &text) { std::string loaded = text; - read((void*)loaded.data(), text.length()); + read((void*)loaded.data(), (unsigned int)text.length()); if(loaded != text) throw std::runtime_error("Magic bytes doesn't match!"); } diff --git a/lib/serializer/BinarySerializer.cpp b/lib/serializer/BinarySerializer.cpp index 2f95d337a..229860012 100644 --- a/lib/serializer/BinarySerializer.cpp +++ b/lib/serializer/BinarySerializer.cpp @@ -71,5 +71,5 @@ void CSaveFile::clear() void CSaveFile::putMagicBytes(const std::string &text) { - write(text.c_str(), text.length()); + write(text.c_str(), (unsigned int)text.length()); } diff --git a/lib/serializer/BinarySerializer.h b/lib/serializer/BinarySerializer.h index c2b815ee9..f8272855a 100644 --- a/lib/serializer/BinarySerializer.h +++ b/lib/serializer/BinarySerializer.h @@ -253,7 +253,7 @@ public: template ::value, int >::type = 0> void save(const std::vector &data) { - ui32 length = data.size(); + ui32 length = (ui32)data.size(); *this & length; for(ui32 i=0;i &data) { std::set &d = const_cast &>(data); - ui32 length = d.size(); + ui32 length = (ui32)d.size(); save(length); for(typename std::set::iterator i=d.begin();i!=d.end();i++) save(*i); @@ -277,7 +277,7 @@ public: void save(const std::unordered_set &data) { std::unordered_set &d = const_cast &>(data); - ui32 length = d.size(); + ui32 length = (ui32)d.size(); *this & length; for(typename std::unordered_set::iterator i=d.begin();i!=d.end();i++) save(*i); @@ -286,7 +286,7 @@ public: void save(const std::list &data) { std::list &d = const_cast &>(data); - ui32 length = d.size(); + ui32 length = (ui32)d.size(); *this & length; for(typename std::list::iterator i=d.begin();i!=d.end();i++) save(*i); @@ -294,7 +294,7 @@ public: void save(const std::string &data) { save(ui32(data.length())); - this->write(data.c_str(),data.size()); + this->write(data.c_str(),(unsigned int)data.size()); } template void save(const std::pair &data) diff --git a/lib/serializer/CTypeList.cpp b/lib/serializer/CTypeList.cpp index c50eaa7e5..37740bfe5 100644 --- a/lib/serializer/CTypeList.cpp +++ b/lib/serializer/CTypeList.cpp @@ -28,7 +28,7 @@ CTypeList::TypeInfoPtr CTypeList::registerType(const std::type_info *type) //type not found - add it to the list and return given ID auto newType = std::make_shared(); - newType->typeID = typeInfos.size() + 1; + newType->typeID = static_cast(typeInfos.size() + 1); newType->name = type->name(); typeInfos[type] = newType; diff --git a/lib/serializer/Connection.cpp b/lib/serializer/Connection.cpp index defbd81d6..5d799d666 100644 --- a/lib/serializer/Connection.cpp +++ b/lib/serializer/Connection.cpp @@ -134,7 +134,7 @@ int CConnection::write(const void * data, unsigned size) try { int ret; - ret = asio::write(*socket,asio::const_buffers_1(asio::const_buffer(data,size))); + ret = static_cast(asio::write(*socket,asio::const_buffers_1(asio::const_buffer(data,size)))); return ret; } catch(...) @@ -148,7 +148,7 @@ int CConnection::read(void * data, unsigned size) { try { - int ret = asio::read(*socket,asio::mutable_buffers_1(asio::mutable_buffer(data,size))); + int ret = static_cast(asio::read(*socket,asio::mutable_buffers_1(asio::mutable_buffer(data,size)))); return ret; } catch(...) diff --git a/lib/serializer/JsonSerializeFormat.h b/lib/serializer/JsonSerializeFormat.h index 551dcb699..61edca347 100644 --- a/lib/serializer/JsonSerializeFormat.h +++ b/lib/serializer/JsonSerializeFormat.h @@ -519,6 +519,6 @@ void JsonArraySerializer::serializeInt(const size_t index, T & value) serializeInt64(index, temp); - if(!owner->saving) + if (!owner->saving) value = static_cast(temp); }; diff --git a/lib/spells/AdventureSpellMechanics.cpp b/lib/spells/AdventureSpellMechanics.cpp index 780c8e69f..1ea510c79 100644 --- a/lib/spells/AdventureSpellMechanics.cpp +++ b/lib/spells/AdventureSpellMechanics.cpp @@ -324,7 +324,7 @@ ESpellCastResult DimensionDoorMechanics::applyAdventureEffects(const SpellCastEn { SetMovePoints smp; smp.hid = parameters.caster->id; - if(movementCost < parameters.caster->movement) + if(movementCost < (int)parameters.caster->movement) smp.val = parameters.caster->movement - movementCost; else smp.val = 0; @@ -352,7 +352,7 @@ ESpellCastResult TownPortalMechanics::applyAdventureEffects(const SpellCastEnvir if(nullptr == destination) return ESpellCastResult::ERROR; - if(parameters.caster->movement < moveCost) + if((int)parameters.caster->movement < moveCost) return ESpellCastResult::ERROR; if(destination->visitingHero) @@ -402,7 +402,7 @@ ESpellCastResult TownPortalMechanics::applyAdventureEffects(const SpellCastEnvir return ESpellCastResult::ERROR; } - if(parameters.caster->movement < moveCost) + if((int)parameters.caster->movement < moveCost) { env->complain("This hero has not enough movement points!"); return ESpellCastResult::ERROR; @@ -445,7 +445,7 @@ ESpellCastResult TownPortalMechanics::beginCast(const SpellCastEnvironment * env const int moveCost = movementCost(parameters); - if(parameters.caster->movement < moveCost) + if((int)parameters.caster->movement < moveCost) { InfoWindow iw; iw.player = parameters.caster->tempOwner; @@ -460,7 +460,7 @@ ESpellCastResult TownPortalMechanics::beginCast(const SpellCastEnvironment * env { if(reply.getType() == JsonNode::JsonType::DATA_INTEGER) { - ObjectInstanceID townId(reply.Integer()); + ObjectInstanceID townId((si32)reply.Integer()); const CGObjectInstance * o = env->getCb()->getObj(townId, true); if(o == nullptr) diff --git a/lib/spells/CSpellHandler.cpp b/lib/spells/CSpellHandler.cpp index 4f34564fb..2fe0c8d44 100644 --- a/lib/spells/CSpellHandler.cpp +++ b/lib/spells/CSpellHandler.cpp @@ -183,7 +183,7 @@ bool CSpell::canBeCast(spells::Problem & problem, const CBattleInfoCallback * cb genProblem = ESpellCastProblem::NO_SPELLBOOK; else if(!castingHero->canCastThisSpell(this)) genProblem = ESpellCastProblem::HERO_DOESNT_KNOW_SPELL; - else if(castingHero->mana < cb->battleGetSpellCost(this, castingHero)) //not enough mana + else if(castingHero->mana < (si32)cb->battleGetSpellCost(this, castingHero)) //not enough mana genProblem = ESpellCastProblem::NOT_ENOUGH_MANA; } break; @@ -631,7 +631,7 @@ std::vector CSpellHandler::loadLegacyData(size_t dataSize) lineNode["name"].String() = parser.readString(); parser.readString(); //ignored unused abbreviated name - lineNode["level"].Integer() = parser.readNumber(); + lineNode["level"].Integer() = static_cast(parser.readNumber()); auto& schools = lineNode["school"].Struct(); @@ -649,13 +649,13 @@ std::vector CSpellHandler::loadLegacyData(size_t dataSize) }; auto costs = parser.readNumArray(GameConstants::SPELL_SCHOOL_LEVELS); - lineNode["power"].Integer() = parser.readNumber(); + lineNode["power"].Integer() = static_cast(parser.readNumber()); auto powers = parser.readNumArray(GameConstants::SPELL_SCHOOL_LEVELS); auto & chances = lineNode["gainChance"].Struct(); for(size_t i = 0; i < GameConstants::F_NUMBER; i++) - chances[ETownType::names[i]].Integer() = parser.readNumber(); + chances[ETownType::names[i]].Integer() = static_cast(parser.readNumber()); auto AIVals = parser.readNumArray(GameConstants::SPELL_SCHOOL_LEVELS); @@ -744,14 +744,14 @@ CSpell * CSpellHandler::loadFromJson(const JsonNode & json, const std::string & spell->school[info.id] = schoolNames[info.jsonName].Bool(); } - spell->level = json["level"].Integer(); - spell->power = json["power"].Integer(); + spell->level = static_cast(json["level"].Integer()); + spell->power = static_cast(json["power"].Integer()); - spell->defaultProbability = json["defaultGainChance"].Integer(); + spell->defaultProbability = static_cast(json["defaultGainChance"].Integer()); for(const auto & node : json["gainChance"].Struct()) { - const int chance = node.second.Integer(); + const int chance = static_cast(node.second.Integer()); VLC->modh->identifiers.requestIdentifier(node.second.meta, "faction",node.first, [=](si32 factionID) { @@ -910,7 +910,7 @@ CSpell * CSpellHandler::loadFromJson(const JsonNode & json, const std::string & } else if(item.isNumber()) { - newItem.pause = item.Float(); + newItem.pause = static_cast(item.Float()); } q.push_back(newItem); @@ -944,11 +944,11 @@ CSpell * CSpellHandler::loadFromJson(const JsonNode & json, const std::string & CSpell::LevelInfo & levelObject = spell->levels[levelIndex]; - const si32 levelPower = levelObject.power = levelNode["power"].Integer(); + const si32 levelPower = levelObject.power = static_cast(levelNode["power"].Integer()); levelObject.description = levelNode["description"].String(); - levelObject.cost = levelNode["cost"].Integer(); - levelObject.AIValue = levelNode["aiValue"].Integer(); + levelObject.cost = static_cast(levelNode["cost"].Integer()); + levelObject.AIValue = static_cast(levelNode["aiValue"].Integer()); levelObject.smartTarget = levelNode["targetModifier"]["smart"].Bool(); levelObject.clearTarget = levelNode["targetModifier"]["clearTarget"].Bool(); levelObject.clearAffected = levelNode["targetModifier"]["clearAffected"].Bool(); diff --git a/lib/spells/effects/Damage.cpp b/lib/spells/effects/Damage.cpp index 7c44b2852..15c9a1c15 100644 --- a/lib/spells/effects/Damage.cpp +++ b/lib/spells/effects/Damage.cpp @@ -132,7 +132,7 @@ void Damage::describeEffect(std::vector & log, const Mechanics * m, std::string text = VLC->generaltexth->allTexts.at(343); //Does %d points of damage. boost::algorithm::trim(text); line << text; - line.addReplacement(damage); //no more text afterwards + line.addReplacement((int)damage); //no more text afterwards log.push_back(line); } } @@ -142,7 +142,7 @@ void Damage::describeEffect(std::vector & log, const Mechanics * m, MetaString line; line.addTxt(MetaString::GENERAL_TXT, 376); line.addReplacement(MetaString::SPELL_NAME, m->getSpellIndex()); - line.addReplacement(damage); + line.addReplacement((int)damage); log.push_back(line); } diff --git a/lib/spells/effects/Obstacle.cpp b/lib/spells/effects/Obstacle.cpp index fd8a7e99d..d848a4567 100644 --- a/lib/spells/effects/Obstacle.cpp +++ b/lib/spells/effects/Obstacle.cpp @@ -201,7 +201,7 @@ void Obstacle::apply(BattleStateProxy * battleState, RNG & rng, const Mechanics } RandomGeneratorUtil::randomShuffle(availableTiles, rng); - const int patchesToPut = std::min(patchCount, availableTiles.size()); + const int patchesToPut = std::min(patchCount, (int)availableTiles.size()); EffectTarget randomTarget; randomTarget.reserve(patchesToPut); diff --git a/lib/spells/effects/Summon.cpp b/lib/spells/effects/Summon.cpp index 889e5876b..4382c4d2b 100644 --- a/lib/spells/effects/Summon.cpp +++ b/lib/spells/effects/Summon.cpp @@ -122,7 +122,7 @@ void Summon::apply(BattleStateProxy * battleState, RNG & rng, const Mechanics * { auto creatureType = creature.toCreature(); auto creatureMaxHealth = creatureType->MaxHealth(); - amount = valueWithBonus / creatureMaxHealth; + amount = static_cast(valueWithBonus / creatureMaxHealth); } else { diff --git a/server/CGameHandler.cpp b/server/CGameHandler.cpp index d5624994a..1ce17e4ba 100644 --- a/server/CGameHandler.cpp +++ b/server/CGameHandler.cpp @@ -196,6 +196,7 @@ public: } catch(ExceptionNotAllowedAction & e) { + (void)e; return false; } catch(...) @@ -536,7 +537,7 @@ void CGameHandler::levelUpCommander(const CCommanderInstance * c) clu.skills.push_back (i); ++i; } - int skillAmount = clu.skills.size(); + int skillAmount = static_cast(clu.skills.size()); if (!skillAmount) { @@ -685,7 +686,7 @@ void CGameHandler::endBattle(int3 tile, const CGHeroInstance *hero1, const CGHer battleQuery->result = boost::make_optional(*battleResult.data); //Check how many battle queries were created (number of players blocked by battle) - const int queriedPlayers = battleQuery ? boost::count(queries.allQueries(), battleQuery) : 0; + const int queriedPlayers = battleQuery ? (int)boost::count(queries.allQueries(), battleQuery) : 0; finishingBattle = make_unique(battleQuery, queriedPlayers); @@ -1148,7 +1149,7 @@ void CGameHandler::applyBattleEffects(BattleAttack & bat, std::shared_ptraddText(text, MetaString::GENERAL_TXT, 361); attackerState->addNameReplacement(text, false); - text.addReplacement(toHeal); + text.addReplacement((int)toHeal); def->addNameReplacement(text, true); bat.battleLog.push_back(text); } @@ -1355,14 +1356,14 @@ int CGameHandler::moveStack(int stack, BattleHex dest) { std::vector tiles; const int tilesToMove = std::max((int)(path.first.size() - creSpeed), 0); - int v = path.first.size()-1; + int v = (int)path.first.size()-1; path.first.push_back(start); // check if gate need to be open or closed at some point BattleHex openGateAtHex, gateMayCloseAtHex; if (canUseGate) { - for (int i = path.first.size()-1; i >= 0; i--) + for (int i = (int)path.first.size()-1; i >= 0; i--) { auto needOpenGates = [&](BattleHex hex) -> bool { @@ -1536,7 +1537,7 @@ void CGameHandler::init(StartInfo *si) { if (si->seedToBeUsed == 0) { - si->seedToBeUsed = std::time(nullptr); + si->seedToBeUsed = static_cast(std::time(nullptr)); } CMapService mapService; gs = new CGameState(); @@ -1871,7 +1872,7 @@ void CGameHandler::newTurn() for (size_t j=0; jinTownGarrison) && complain("Can not move garrisoned hero!")) - || ((h->movement < cost && dst != h->pos && !teleporting) + || (((int)h->movement < cost && dst != h->pos && !teleporting) && complain("Hero doesn't have any movement points left!")) || ((transit && !canFly && !CGTeleport::isTeleport(t.topVisitableObj())) && complain("Hero cannot transit over this tile!")) @@ -2324,7 +2325,7 @@ bool CGameHandler::moveHero(ObjectInstanceID hid, int3 dst, ui8 teleporting, boo //still here? it is standard movement! { - tmh.movePoints = h->movement >= cost + tmh.movePoints = (int)h->movement >= cost ? h->movement - cost : 0; @@ -2671,7 +2672,7 @@ void CGameHandler::useScholarSkill(ObjectInstanceID fromHero, ObjectInstanceID t if (!cs2.spells.empty())//if found new spell - apply { iw.text.addTxt(MetaString::GENERAL_TXT, 140);//learns - int size = cs2.spells.size(); + int size = static_cast(cs2.spells.size()); for (auto it : cs2.spells) { iw.components.push_back(Component(Component::SPELL, it, 1, 0)); @@ -2696,7 +2697,7 @@ void CGameHandler::useScholarSkill(ObjectInstanceID fromHero, ObjectInstanceID t if (!cs1.spells.empty()) { iw.text.addTxt(MetaString::GENERAL_TXT, 147);//teaches - int size = cs1.spells.size(); + int size = static_cast(cs1.spells.size()); for (auto it : cs1.spells) { iw.components.push_back(Component(Component::SPELL, it, 1, 0)); @@ -3235,7 +3236,7 @@ bool CGameHandler::recruitCreatures(ObjectInstanceID objid, ObjectInstanceID dst SlotID slot = dst->getSlotFor(crid); if ((!found && complain("Cannot recruit: no such creatures!")) - || (cram > VLC->creh->creatures.at(crid)->maxAmount(getPlayer(dst->tempOwner)->resources) && complain("Cannot recruit: lack of resources!")) + || ((si32)cram > VLC->creh->creatures.at(crid)->maxAmount(getPlayer(dst->tempOwner)->resources) && complain("Cannot recruit: lack of resources!")) || (cram<=0 && complain("Cannot recruit: cram <= 0!")) || (!slot.validSlot() && !warMachine && complain("Cannot recruit: no available slot!"))) { @@ -3443,7 +3444,7 @@ bool CGameHandler::moveArtifact(const ArtifactLocation &al1, const ArtifactLocat COMPLAIN_RET("Cannot move catapult!"); if (dst.slot >= GameConstants::BACKPACK_START) - vstd::amin(dst.slot, ArtifactPosition(GameConstants::BACKPACK_START + dst.getHolderArtSet()->artifactsInBackpack.size())); + vstd::amin(dst.slot, ArtifactPosition(GameConstants::BACKPACK_START + (si32)dst.getHolderArtSet()->artifactsInBackpack.size())); if (src.slot == dst.slot && src.artHolder == dst.artHolder) COMPLAIN_RET("Won't move artifact: Dest same as source!"); @@ -3452,7 +3453,7 @@ bool CGameHandler::moveArtifact(const ArtifactLocation &al1, const ArtifactLocat { //old artifact must be removed first moveArtifact(dst, ArtifactLocation(dst.artHolder, ArtifactPosition( - dst.getHolderArtSet()->artifactsInBackpack.size() + GameConstants::BACKPACK_START))); + (si32)dst.getHolderArtSet()->artifactsInBackpack.size() + GameConstants::BACKPACK_START))); } MoveArtifact ma; @@ -3666,7 +3667,7 @@ bool CGameHandler::sellCreatures(ui32 count, const IMarket *market, const CGHero const CStackInstance &s = hero->getStack(slot); - if (s.count < count //can't sell more creatures than have + if (s.count < (TQuantity)count //can't sell more creatures than have || (hero->stacksCount() == 1 && hero->needsLastStack() && s.count == count)) //can't sell last stack { COMPLAIN_RET("Not enough creatures in army!"); @@ -3682,7 +3683,7 @@ bool CGameHandler::sellCreatures(ui32 count, const IMarket *market, const CGHero assert(0); } - changeStackCount(StackLocation(hero, slot), -count); + changeStackCount(StackLocation(hero, slot), -(TQuantity)count); giveResource(hero->tempOwner, resourceID, b2 * units); @@ -3730,7 +3731,7 @@ bool CGameHandler::sendResources(ui32 val, PlayerColor player, Res::ERes r1, Pla vstd::amin(val, curRes1); - giveResource(player, r1, -val); + giveResource(player, r1, -(int)val); giveResource(r2, r1, val); return true; @@ -4421,7 +4422,7 @@ bool CGameHandler::makeBattleAction(BattleAction &ba) text.addTxt(MetaString::GENERAL_TXT, 414); healer->addNameReplacement(text, false); destStack->addNameReplacement(text, false); - text.addReplacement(toHeal); + text.addReplacement((int)toHeal); pack.battleLog.push_back(text); UnitChanges info(state->unitId(), UnitChanges::EOperation::RESET_STATE); @@ -4453,7 +4454,7 @@ bool CGameHandler::makeBattleAction(BattleAction &ba) ui64 targetHealth = destStack->getCreature()->MaxHealth() * destStack->baseAmount; ui64 canRiseHp = std::min(targetHealth, risedHp); - ui32 canRiseAmount = canRiseHp / summonedType.toCreature()->MaxHealth(); + ui32 canRiseAmount = static_cast(canRiseHp / summonedType.toCreature()->MaxHealth()); battle::UnitInfo info; info.id = gs->curB->battleNextUnitId(); @@ -5500,7 +5501,7 @@ void CGameHandler::handleAfterAttackCasting(bool ranged, const CStack * attacker int staredCreatures = distribution(getRandomGenerator().getStdGenerator()); double cap = 1 / std::max(chanceToKill, (double)(0.01));//don't divide by 0 - int maxToKill = (attacker->getCount() + cap - 1) / cap; //not much more than chance * count + int maxToKill = static_cast((attacker->getCount() + cap - 1) / cap); //not much more than chance * count vstd::amin(staredCreatures, maxToKill); staredCreatures += (attacker->level() * attacker->valOfBonuses(Bonus::DEATH_STARE, 1)) / defender->level(); @@ -5596,7 +5597,7 @@ void CGameHandler::handleAfterAttackCasting(bool ranged, const CStack * attacker { chanceToTrigger = attacker->valOfBonuses(Bonus::DESTRUCTION, 0) / 100.0f; int percentageToDie = attacker->getBonus(Selector::type(Bonus::DESTRUCTION).And(Selector::subtype(0)))->additionalInfo[0]; - amountToDie = defender->getCount() * percentageToDie * 0.01f; + amountToDie = static_cast(defender->getCount() * percentageToDie * 0.01f); } else if(attacker->hasBonusOfType(Bonus::DESTRUCTION, 1)) //killing by count { @@ -5651,7 +5652,7 @@ bool CGameHandler::sacrificeCreatures(const IMarket * market, const CGHeroInstan { int oldCount = hero->getStackCount(slot[i]); - if(oldCount < count[i]) + if(oldCount < (int)count[i]) { finish(); COMPLAIN_RET("Not enough creatures to sacrifice!") @@ -5664,7 +5665,7 @@ bool CGameHandler::sacrificeCreatures(const IMarket * market, const CGHeroInstan int crid = hero->getStack(slot[i]).type->idNumber; - changeStackCount(StackLocation(hero, slot[i]), -count[i]); + changeStackCount(StackLocation(hero, slot[i]), -(TQuantity)count[i]); int dump, exp; market->getOffer(crid, 0, dump, exp, EMarketMode::CREATURE_EXP); @@ -6372,12 +6373,12 @@ void CGameHandler::spawnWanderingMonsters(CreatureID creatureID) std::vector::iterator tile; std::vector tiles; getFreeTiles(tiles); - ui32 amount = tiles.size() / 200; //Chance is 0.5% for each tile + ui32 amount = (ui32)tiles.size() / 200; //Chance is 0.5% for each tile RandomGeneratorUtil::randomShuffle(tiles, getRandomGenerator()); logGlobal->trace("Spawning wandering monsters. Found %d free tiles. Creature type: %d", tiles.size(), creatureID.num); const CCreature *cre = VLC->creh->creatures.at(creatureID); - for (int i = 0; i < amount; ++i) + for (int i = 0; i < (int)amount; ++i) { tile = tiles.begin(); logGlobal->trace("\tSpawning monster at %s", tile->toString()); diff --git a/server/CVCMIServer.cpp b/server/CVCMIServer.cpp index f392a6118..b469585fe 100644 --- a/server/CVCMIServer.cpp +++ b/server/CVCMIServer.cpp @@ -299,6 +299,7 @@ void CVCMIServer::connectionAccepted(const boost::system::error_code & ec) } catch(std::exception & e) { + (void)e; upcomingConnection.reset(); logNetwork->info("I guess it was just my imagination!"); } @@ -328,11 +329,13 @@ void CVCMIServer::threadHandleClient(std::shared_ptr c) } catch(boost::system::system_error & e) { + (void)e; if(state != EServerState::LOBBY) gh->handleClientDisconnection(c); } catch(const std::exception & e) { + (void)e; boost::unique_lock queueLock(mx); logNetwork->error("%s dies... \nWhat happened: %s", c->toString(), e.what()); } @@ -682,7 +685,7 @@ void CVCMIServer::optionNextCastle(PlayerColor player, int dir) else { assert(dir >= -1 && dir <= 1); //othervice std::advance may go out of range - auto iter = allowed.find(cur); + auto iter = allowed.find((ui8)cur); std::advance(iter, dir); cur = *iter; } @@ -730,14 +733,14 @@ void CVCMIServer::optionNextHero(PlayerColor player, int dir) if(s.hero == PlayerSettings::RANDOM) // first/last available { - int max = VLC->heroh->heroes.size(), + int max = static_cast(VLC->heroh->heroes.size()), min = 0; s.hero = nextAllowedHero(player, min, max, 0, dir); } else { if(dir > 0) - s.hero = nextAllowedHero(player, s.hero, VLC->heroh->heroes.size(), 1, dir); + s.hero = nextAllowedHero(player, s.hero, (int)VLC->heroh->heroes.size(), 1, dir); else s.hero = nextAllowedHero(player, -1, s.hero, 1, dir); // min needs to be -1 -- hero at index 0 would be skipped otherwise } diff --git a/server/CVCMIServer.h b/server/CVCMIServer.h index 38c2e8f40..111ded751 100644 --- a/server/CVCMIServer.h +++ b/server/CVCMIServer.h @@ -22,7 +22,7 @@ struct SharedMemory; struct StartInfo; struct LobbyInfo; -class PlayerSettings; +struct PlayerSettings; class PlayerColor; template class CApplier; diff --git a/test/vcai/mock_ResourceManager.h b/test/vcai/mock_ResourceManager.h index 40c7851c7..f1027345f 100644 --- a/test/vcai/mock_ResourceManager.h +++ b/test/vcai/mock_ResourceManager.h @@ -9,7 +9,7 @@ class VCAI; class ResourceManagerMock : public ResourceManager { - friend class ResourceManagerTest; //everything is public + friend struct ResourceManagerTest; //everything is public public: using ResourceManager::ResourceManager; //access protected members, TODO: consider other architecture?