Browse Source

Code style: uncrustify formatting preview

Arseniy Shestakov 8 years ago
parent
commit
58f32f6dc2
100 changed files with 6950 additions and 6569 deletions
  1. 6 6
      AI/BattleAI/AttackPossibility.cpp
  2. 3 3
      AI/BattleAI/AttackPossibility.h
  3. 88 89
      AI/BattleAI/BattleAI.cpp
  4. 28 28
      AI/BattleAI/BattleAI.h
  5. 3 2
      AI/BattleAI/EnemyInfo.h
  6. 14 14
      AI/BattleAI/PotentialTargets.cpp
  7. 1 1
      AI/BattleAI/PotentialTargets.h
  8. 3 4
      AI/BattleAI/StackWithBonuses.cpp
  9. 2 3
      AI/BattleAI/StackWithBonuses.h
  10. 47 47
      AI/BattleAI/ThreatMap.cpp
  11. 5 5
      AI/BattleAI/ThreatMap.h
  12. 1 1
      AI/BattleAI/common.h
  13. 3 3
      AI/BattleAI/main.cpp
  14. 4 4
      AI/EmptyAI/CEmptyAI.cpp
  15. 4 4
      AI/EmptyAI/CEmptyAI.h
  16. 1 1
      AI/EmptyAI/StdInc.cpp
  17. 1 1
      AI/EmptyAI/StdInc.h
  18. 4 4
      AI/EmptyAI/exp_funcs.cpp
  19. 1 1
      AI/StupidAI/StdInc.cpp
  20. 1 1
      AI/StupidAI/StdInc.h
  21. 36 34
      AI/StupidAI/StupidAI.cpp
  22. 11 11
      AI/StupidAI/StupidAI.h
  23. 3 3
      AI/StupidAI/main.cpp
  24. 107 104
      AI/VCAI/AIUtility.cpp
  25. 40 36
      AI/VCAI/AIUtility.h
  26. 77 77
      AI/VCAI/Fuzzy.cpp
  27. 25 22
      AI/VCAI/Fuzzy.h
  28. 315 315
      AI/VCAI/Goals.cpp
  29. 174 98
      AI/VCAI/Goals.h
  30. 224 225
      AI/VCAI/VCAI.cpp
  31. 94 85
      AI/VCAI/VCAI.h
  32. 3 3
      AI/VCAI/main.cpp
  33. 57 55
      CCallback.cpp
  34. 59 59
      CCallback.h
  35. 359 356
      Global.h
  36. 47 44
      client/CBitmapHandler.cpp
  37. 2 2
      client/CBitmapHandler.h
  38. 104 102
      client/CDefHandler.cpp
  39. 9 7
      client/CDefHandler.h
  40. 5 1
      client/CGameInfo.h
  41. 202 203
      client/CMT.cpp
  42. 3 3
      client/CMT.h
  43. 105 101
      client/CMessage.cpp
  44. 2 2
      client/CMessage.h
  45. 81 83
      client/CMusicHandler.cpp
  46. 23 20
      client/CMusicHandler.h
  47. 198 185
      client/CPlayerInterface.cpp
  48. 75 73
      client/CPlayerInterface.h
  49. 217 201
      client/CPreGame.cpp
  50. 184 125
      client/CPreGame.h
  51. 82 68
      client/CVideoHandler.cpp
  52. 31 32
      client/CVideoHandler.h
  53. 129 122
      client/Client.cpp
  54. 64 59
      client/Client.h
  55. 70 63
      client/Graphics.cpp
  56. 19 11
      client/Graphics.h
  57. 282 284
      client/NetPacksClient.cpp
  58. 25 25
      client/SDLRWwrapper.cpp
  59. 1 1
      client/SDLRWwrapper.h
  60. 1 1
      client/StdInc.cpp
  61. 133 140
      client/battle/CBattleAnimations.cpp
  62. 15 8
      client/battle/CBattleAnimations.h
  63. 219 227
      client/battle/CBattleInterface.cpp
  64. 102 84
      client/battle/CBattleInterface.h
  65. 139 134
      client/battle/CBattleInterfaceClasses.cpp
  66. 23 18
      client/battle/CBattleInterfaceClasses.h
  67. 48 52
      client/battle/CCreatureAnimation.cpp
  68. 20 19
      client/battle/CCreatureAnimation.h
  69. 240 249
      client/gui/CAnimation.cpp
  70. 20 15
      client/gui/CAnimation.h
  71. 22 20
      client/gui/CCursorHandler.cpp
  72. 31 14
      client/gui/CCursorHandler.h
  73. 62 55
      client/gui/CGuiHandler.cpp
  74. 28 26
      client/gui/CGuiHandler.h
  75. 41 44
      client/gui/CIntObject.cpp
  76. 65 28
      client/gui/CIntObject.h
  77. 58 60
      client/gui/Fonts.cpp
  78. 7 4
      client/gui/Fonts.h
  79. 6 6
      client/gui/Geometries.cpp
  80. 52 52
      client/gui/Geometries.h
  81. 1 3
      client/gui/SDL_Compat.h
  82. 235 203
      client/gui/SDL_Extensions.cpp
  83. 109 108
      client/gui/SDL_Extensions.h
  84. 134 134
      client/gui/SDL_Pixels.h
  85. 234 233
      client/mapHandler.cpp
  86. 56 56
      client/mapHandler.h
  87. 1 1
      client/resource.h
  88. 209 221
      client/widgets/AdventureMapClasses.cpp
  89. 54 40
      client/widgets/AdventureMapClasses.h
  90. 96 105
      client/widgets/Buttons.cpp
  91. 33 31
      client/widgets/Buttons.h
  92. 142 146
      client/widgets/CArtifactHolder.cpp
  93. 36 36
      client/widgets/CArtifactHolder.h
  94. 169 130
      client/widgets/CComponent.cpp
  95. 29 12
      client/widgets/CComponent.h
  96. 84 90
      client/widgets/CGarrisonInt.cpp
  97. 28 32
      client/widgets/CGarrisonInt.h
  98. 81 98
      client/widgets/Images.cpp
  99. 44 34
      client/widgets/Images.h
  100. 79 78
      client/widgets/MiscWidgets.cpp

+ 6 - 6
AI/BattleAI/AttackPossibility.cpp

@@ -12,7 +12,7 @@
 
 int AttackPossibility::damageDiff() const
 {
-	if (!priorities)
+	if(!priorities)
 		priorities = new Priorities();
 	const auto dealtDmgValue = priorities->stackEvaluator(enemy) * damageDealt;
 	const auto receivedDmgValue = priorities->stackEvaluator(attack.attacker) * damageReceived;
@@ -24,21 +24,21 @@ int AttackPossibility::attackValue() const
 	return damageDiff() + tacticImpact;
 }
 
-AttackPossibility AttackPossibility::evaluate(const BattleAttackInfo &AttackInfo, const HypotheticChangesToBattleState &state, BattleHex hex)
+AttackPossibility AttackPossibility::evaluate(const BattleAttackInfo & AttackInfo, const HypotheticChangesToBattleState & state, BattleHex hex)
 {
 	auto attacker = AttackInfo.attacker;
 	auto enemy = AttackInfo.defender;
 
 	const int remainingCounterAttacks = getValOr(state.counterAttacksLeft, enemy, enemy->counterAttacks.available());
 	const bool counterAttacksBlocked = attacker->hasBonusOfType(Bonus::BLOCKS_RETALIATION) || enemy->hasBonusOfType(Bonus::NO_RETALIATION);
-	const int totalAttacks = 1 + AttackInfo.attackerBonuses->getBonuses(Selector::type(Bonus::ADDITIONAL_ATTACK), (Selector::effectRange (Bonus::NO_LIMIT).Or(Selector::effectRange(Bonus::ONLY_MELEE_FIGHT))))->totalValue();
+	const int totalAttacks = 1 + AttackInfo.attackerBonuses->getBonuses(Selector::type(Bonus::ADDITIONAL_ATTACK), (Selector::effectRange(Bonus::NO_LIMIT).Or(Selector::effectRange(Bonus::ONLY_MELEE_FIGHT))))->totalValue();
 
 	AttackPossibility ap = {enemy, hex, AttackInfo, 0, 0, 0};
 
 	auto curBai = AttackInfo; //we'll modify here the stack counts
-	for(int i  = 0; i < totalAttacks; i++)
+	for(int i = 0; i < totalAttacks; i++)
 	{
-		std::pair<ui32, ui32> retaliation(0,0);
+		std::pair<ui32, ui32> retaliation(0, 0);
 		auto attackDmg = getCbc()->battleEstimateDamage(CRandomGenerator::getDefault(), curBai, &retaliation);
 		ap.damageDealt = (attackDmg.first + attackDmg.second) / 2;
 		ap.damageReceived = (retaliation.first + retaliation.second) / 2;
@@ -59,4 +59,4 @@ AttackPossibility AttackPossibility::evaluate(const BattleAttackInfo &AttackInfo
 }
 
 
-Priorities* AttackPossibility::priorities = nullptr;
+Priorities * AttackPossibility::priorities = nullptr;

+ 3 - 3
AI/BattleAI/AttackPossibility.h

@@ -27,14 +27,14 @@ public:
 	Priorities()
 	{
 		//        range::copy(VLC->objh->resVals, std::back_inserter(resourceTypeBaseValues));
-		stackEvaluator = [](const CStack*){ return 1.0; };
+		stackEvaluator = [](const CStack *){ return 1.0; };
 	}
 };
 
 class AttackPossibility
 {
 public:
-	const CStack *enemy; //redundant (to attack.defender) but looks nice
+	const CStack * enemy; //redundant (to attack.defender) but looks nice
 	BattleHex tile; //tile from which we attack
 	BattleAttackInfo attack;
 
@@ -45,6 +45,6 @@ public:
 	int damageDiff() const;
 	int attackValue() const;
 
-	static AttackPossibility evaluate(const BattleAttackInfo &AttackInfo, const HypotheticChangesToBattleState &state, BattleHex hex);
+	static AttackPossibility evaluate(const BattleAttackInfo & AttackInfo, const HypotheticChangesToBattleState & state, BattleHex hex);
 	static Priorities * priorities;
 };

+ 88 - 89
AI/BattleAI/BattleAI.cpp

@@ -42,9 +42,9 @@ void CBattleAI::init(std::shared_ptr<CBattleCallback> CB)
 	CB->unlockGsWhenWaiting = false;
 }
 
-BattleAction CBattleAI::activeStack( const CStack * stack )
+BattleAction CBattleAI::activeStack(const CStack * stack)
 {
-	LOG_TRACE_PARAMS(logAi, "stack: %s", stack->nodeName())	;
+	LOG_TRACE_PARAMS(logAi, "stack: %s", stack->nodeName());
 	setCbc(cb); //TODO: make solid sure that AIs always use their callbacks (need to take care of event handlers too)
 	try
 	{
@@ -53,7 +53,7 @@ BattleAction CBattleAI::activeStack( const CStack * stack )
 		if(stack->hasBonusOfType(Bonus::SIEGE_WEAPON) && stack->hasBonusOfType(Bonus::HEALER))
 		{
 			auto healingTargets = cb->battleGetStacks(CBattleInfoEssentials::ONLY_MINE);
-			std::map<int, const CStack*> woundHpToStack;
+			std::map<int, const CStack *> woundHpToStack;
 			for(auto stack : healingTargets)
 				if(auto woundHp = stack->MaxHealth() - stack->getFirstHPleft())
 					woundHpToStack[woundHp] = stack;
@@ -91,7 +91,7 @@ BattleAction CBattleAI::activeStack( const CStack * stack )
 			{
 				//ThreatMap threatsToUs(stack); // These lines may be usefull but they are't used in the code.
 				auto dists = getCbc()->battleGetDistances(stack);
-				const EnemyInfo &ei= *range::min_element(targets.unreachableEnemies, std::bind(isCloser, _1, _2, std::ref(dists)));
+				const EnemyInfo & ei = *range::min_element(targets.unreachableEnemies, std::bind(isCloser, _1, _2, std::ref(dists)));
 				if(distToNearestNeighbour(ei.s->position, dists) < GameConstants::BFIELD_SIZE)
 				{
 					return goTowards(stack, ei.s->position);
@@ -103,9 +103,9 @@ BattleAction CBattleAI::activeStack( const CStack * stack )
 			}
 		}
 	}
-	catch(std::exception &e)
+	catch(std::exception & e)
 	{
-		logAi->error("Exception occurred in %s %s",__FUNCTION__, e.what());
+		logAi->error("Exception occurred in %s %s", __FUNCTION__, e.what());
 	}
 	return BattleAction::makeDefend(stack);
 }
@@ -134,11 +134,11 @@ BattleAction CBattleAI::goTowards(const CStack * stack, BattleHex destination)
 		// Flying stack doesn't go hex by hex, so we can't backtrack using predecessors.
 		// We just check all available hexes and pick the one closest to the target.
 		auto distToDestNeighbour = [&](BattleHex hex) -> int
-		{
-			auto nearestNeighbourToHex = vstd::minElementByFun(destNeighbours, [&](BattleHex a)
-			{return BattleHex::getDistance(a, hex);});
-			return BattleHex::getDistance(*nearestNeighbourToHex, hex);
-		};
+			{
+				auto nearestNeighbourToHex = vstd::minElementByFun(destNeighbours, [&](BattleHex a)
+										   {return BattleHex::getDistance(a, hex);});
+				return BattleHex::getDistance(*nearestNeighbourToHex, hex);
+			};
 		auto nearestAvailableHex = vstd::minElementByFun(avHexes, distToDestNeighbour);
 		return BattleAction::makeMove(stack, *nearestAvailableHex);
 	}
@@ -168,14 +168,16 @@ BattleAction CBattleAI::useCatapult(const CStack * stack)
 
 enum SpellTypes
 {
-	OFFENSIVE_SPELL, TIMED_EFFECT, OTHER
+	OFFENSIVE_SPELL,
+	TIMED_EFFECT,
+	OTHER
 };
 
-SpellTypes spellType(const CSpell *spell)
+SpellTypes spellType(const CSpell * spell)
 {
-	if (spell->isOffensiveSpell())
+	if(spell->isOffensiveSpell())
 		return OFFENSIVE_SPELL;
-	if (spell->hasEffects())
+	if(spell->hasEffects())
 		return TIMED_EFFECT;
 	return OTHER;
 }
@@ -191,15 +193,15 @@ void CBattleAI::attemptCastingSpell()
 
 	LOGL("Casting spells sounds like fun. Let's see...");
 	//Get all spells we can cast
-	std::vector<const CSpell*> possibleSpells;
-	vstd::copy_if(VLC->spellh->objects, std::back_inserter(possibleSpells), [this, hero] (const CSpell *s) -> bool
+	std::vector<const CSpell *> possibleSpells;
+	vstd::copy_if(VLC->spellh->objects, std::back_inserter(possibleSpells), [this, hero](const CSpell * s) -> bool
 	{
 		return s->canBeCast(getCbc().get(), ECastingMode::HERO_CASTING, hero) == ESpellCastProblem::OK;
 	});
 	LOGFL("I can cast %d spells.", possibleSpells.size());
 
-	vstd::erase_if(possibleSpells, [](const CSpell *s)
-	{return spellType(s) == OTHER; });
+	vstd::erase_if(possibleSpells, [](const CSpell * s)
+		       {return spellType(s) == OTHER; });
 	LOGFL("I know about workings of %d of them.", possibleSpells.size());
 
 	//Get possible spell-target pairs
@@ -216,80 +218,80 @@ void CBattleAI::attemptCastingSpell()
 	if(possibleCasts.empty())
 		return;
 
-	std::map<const CStack*, int> valueOfStack;
+	std::map<const CStack *, int> valueOfStack;
 	for(auto stack : cb->battleGetStacks())
 	{
 		PotentialTargets pt(stack);
 		valueOfStack[stack] = pt.bestActionValue();
 	}
 
-	auto evaluateSpellcast = [&] (const PossibleSpellcast &ps) -> int
-	{
-		const int skillLevel = hero->getSpellSchoolLevel(ps.spell);
-		const int spellPower = hero->getPrimSkillLevel(PrimarySkill::SPELL_POWER);
-		switch(spellType(ps.spell))
+	auto evaluateSpellcast = [&](const PossibleSpellcast & ps) -> int
 		{
-		case OFFENSIVE_SPELL:
-		{
-			int damageDealt = 0, damageReceived = 0;
-			auto stacksSuffering = ps.spell->getAffectedStacks(cb.get(), ECastingMode::HERO_CASTING, hero, skillLevel, ps.dest);
-			if(stacksSuffering.empty())
-				return -1;
-			for(auto stack : stacksSuffering)
+			const int skillLevel = hero->getSpellSchoolLevel(ps.spell);
+			const int spellPower = hero->getPrimSkillLevel(PrimarySkill::SPELL_POWER);
+			switch(spellType(ps.spell))
 			{
-				const int dmg = ps.spell->calculateDamage(hero, stack, skillLevel, spellPower);
-				if(stack->owner == playerID)
-					damageReceived += dmg;
-				else
-					damageDealt += dmg;
-			}
-			const int damageDiff = damageDealt - damageReceived * 10;
-			LOGFL("Casting %s on hex %d would deal { %d %d } damage points among %d stacks.",
-				  ps.spell->name % ps.dest % damageDealt % damageReceived % stacksSuffering.size());
-			//TODO tactic effect too
-			return damageDiff;
-		}
-		case TIMED_EFFECT:
-		{
-			auto stacksAffected = ps.spell->getAffectedStacks(cb.get(), ECastingMode::HERO_CASTING, hero, skillLevel, ps.dest);
-			if(stacksAffected.empty())
-				return -1;
-			int totalGain = 0;
-			for(const CStack * sta : stacksAffected)
+			case OFFENSIVE_SPELL:
 			{
-				StackWithBonuses swb;
-				swb.stack = sta;
-				//todo: handle effect actualization in HypotheticChangesToBattleState
-				ps.spell->getEffects(swb.bonusesToAdd, skillLevel, false, hero->getEnchantPower(ps.spell));
-				ps.spell->getEffects(swb.bonusesToAdd, skillLevel, true, hero->getEnchantPower(ps.spell));
-				HypotheticChangesToBattleState state;
-				state.bonusesOfStacks[swb.stack] = &swb;
-				PotentialTargets pt(swb.stack, state);
-				auto newValue = pt.bestActionValue();
-				auto oldValue = valueOfStack[swb.stack];
-				auto gain = newValue - oldValue;
-				if(swb.stack->owner != playerID) //enemy
-					gain = -gain;
-				LOGFL("Casting %s on %s would improve the stack by %d points (from %d to %d)",
-					  ps.spell->name % sta->nodeName() % (gain) % (oldValue) % (newValue));
-				totalGain += gain;
+				int damageDealt = 0, damageReceived = 0;
+				auto stacksSuffering = ps.spell->getAffectedStacks(cb.get(), ECastingMode::HERO_CASTING, hero, skillLevel, ps.dest);
+				if(stacksSuffering.empty())
+					return -1;
+				for(auto stack : stacksSuffering)
+				{
+					const int dmg = ps.spell->calculateDamage(hero, stack, skillLevel, spellPower);
+					if(stack->owner == playerID)
+						damageReceived += dmg;
+					else
+						damageDealt += dmg;
+				}
+				const int damageDiff = damageDealt - damageReceived * 10;
+				LOGFL("Casting %s on hex %d would deal { %d %d } damage points among %d stacks.",
+				      ps.spell->name % ps.dest % damageDealt % damageReceived % stacksSuffering.size());
+				//TODO tactic effect too
+				return damageDiff;
 			}
+			case TIMED_EFFECT:
+			{
+				auto stacksAffected = ps.spell->getAffectedStacks(cb.get(), ECastingMode::HERO_CASTING, hero, skillLevel, ps.dest);
+				if(stacksAffected.empty())
+					return -1;
+				int totalGain = 0;
+				for(const CStack * sta : stacksAffected)
+				{
+					StackWithBonuses swb;
+					swb.stack = sta;
+					//todo: handle effect actualization in HypotheticChangesToBattleState
+					ps.spell->getEffects(swb.bonusesToAdd, skillLevel, false, hero->getEnchantPower(ps.spell));
+					ps.spell->getEffects(swb.bonusesToAdd, skillLevel, true, hero->getEnchantPower(ps.spell));
+					HypotheticChangesToBattleState state;
+					state.bonusesOfStacks[swb.stack] = &swb;
+					PotentialTargets pt(swb.stack, state);
+					auto newValue = pt.bestActionValue();
+					auto oldValue = valueOfStack[swb.stack];
+					auto gain = newValue - oldValue;
+					if(swb.stack->owner != playerID) //enemy
+						gain = -gain;
+					LOGFL("Casting %s on %s would improve the stack by %d points (from %d to %d)",
+					      ps.spell->name % sta->nodeName() % (gain) % (oldValue) % (newValue));
+					totalGain += gain;
+				}
 
-			LOGFL("Total gain of cast %s at hex %d is %d", ps.spell->name % (ps.dest.hex) % (totalGain));
-			return totalGain;
-		}
-		default:
-			assert(0);
-			return 0;
-		}
-	};
+				LOGFL("Total gain of cast %s at hex %d is %d", ps.spell->name % (ps.dest.hex) % (totalGain));
+				return totalGain;
+			}
+			default:
+				assert(0);
+				return 0;
+			}
+		};
 
 	for(PossibleSpellcast & psc : possibleCasts)
 		psc.value = evaluateSpellcast(psc);
-	auto pscValue = [] (const PossibleSpellcast &ps) -> int
-	{
-		return ps.value;
-	};
+	auto pscValue = [](const PossibleSpellcast & ps) -> int
+		{
+			return ps.value;
+		};
 	auto castToPerform = *vstd::maxElementByFun(possibleCasts, pscValue);
 	LOGFL("Best spell is %s. Will cast.", castToPerform.spell->name);
 	BattleAction spellcast;
@@ -321,7 +323,7 @@ std::vector<BattleHex> CBattleAI::getTargetsToConsider(const CSpell * spell, con
 				bool casterStack = stack->owner == caster->getOwner();
 
 				if(!immune)
-					switch (spell->positiveness)
+					switch(spell->positiveness)
 					{
 					case CSpell::POSITIVE:
 						if(casterStack || targetInfo.smart)
@@ -337,14 +339,14 @@ std::vector<BattleHex> CBattleAI::getTargetsToConsider(const CSpell * spell, con
 					}
 			}
 		}
-			break;
+		break;
 		case CSpell::LOCATION:
 		{
 			for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
 				if(BattleHex(i).isAvailable())
 					ret.push_back(i);
 		}
-			break;
+		break;
 
 		default:
 			break;
@@ -353,7 +355,7 @@ std::vector<BattleHex> CBattleAI::getTargetsToConsider(const CSpell * spell, con
 	return ret;
 }
 
-int CBattleAI::distToNearestNeighbour(BattleHex hex, const ReachabilityInfo::TDistances &dists, BattleHex *chosenHex)
+int CBattleAI::distToNearestNeighbour(BattleHex hex, const ReachabilityInfo::TDistances & dists, BattleHex * chosenHex)
 {
 	int ret = 1000000;
 	for(BattleHex n : hex.neighbouringTiles())
@@ -368,18 +370,18 @@ int CBattleAI::distToNearestNeighbour(BattleHex hex, const ReachabilityInfo::TDi
 	return ret;
 }
 
-void CBattleAI::battleStart(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool Side)
+void CBattleAI::battleStart(const CCreatureSet * army1, const CCreatureSet * army2, int3 tile, const CGHeroInstance * hero1, const CGHeroInstance * hero2, bool Side)
 {
 	print("battleStart called");
 	side = Side;
 }
 
-bool CBattleAI::isCloser(const EnemyInfo &ei1, const EnemyInfo &ei2, const ReachabilityInfo::TDistances &dists)
+bool CBattleAI::isCloser(const EnemyInfo & ei1, const EnemyInfo & ei2, const ReachabilityInfo::TDistances & dists)
 {
 	return distToNearestNeighbour(ei1.s->position, dists) < distToNearestNeighbour(ei2.s->position, dists);
 }
 
-void CBattleAI::print(const std::string &text) const
+void CBattleAI::print(const std::string & text) const
 {
 	logAi->trace("CBattleAI [%p]: %s", this, text);
 }
@@ -394,6 +396,3 @@ boost::optional<BattleAction> CBattleAI::considerFleeingOrSurrendering()
 	}
 	return boost::none;
 }
-
-
-

+ 28 - 28
AI/BattleAI/BattleAI.h

@@ -17,37 +17,37 @@ class EnemyInfo;
 /*
 struct CurrentOffensivePotential
 {
-	std::map<const CStack *, PotentialTargets> ourAttacks;
-	std::map<const CStack *, PotentialTargets> enemyAttacks;
+        std::map<const CStack *, PotentialTargets> ourAttacks;
+        std::map<const CStack *, PotentialTargets> enemyAttacks;
 
-	CurrentOffensivePotential(ui8 side)
-	{
-		for(auto stack : cbc->battleGetStacks())
-		{
-			if(stack->side == side)
-				ourAttacks[stack] = PotentialTargets(stack);
-			else
-				enemyAttacks[stack] = PotentialTargets(stack);
-		}
-	}
+        CurrentOffensivePotential(ui8 side)
+        {
+                for(auto stack : cbc->battleGetStacks())
+                {
+                        if(stack->side == side)
+                                ourAttacks[stack] = PotentialTargets(stack);
+                        else
+                                enemyAttacks[stack] = PotentialTargets(stack);
+                }
+        }
 
-	int potentialValue()
-	{
-		int ourPotential = 0, enemyPotential = 0;
-		for(auto &p : ourAttacks)
-			ourPotential += p.second.bestAction().attackValue();
+        int potentialValue()
+        {
+                int ourPotential = 0, enemyPotential = 0;
+                for(auto &p : ourAttacks)
+                        ourPotential += p.second.bestAction().attackValue();
 
-		for(auto &p : enemyAttacks)
-			enemyPotential += p.second.bestAction().attackValue();
+                for(auto &p : enemyAttacks)
+                        enemyPotential += p.second.bestAction().attackValue();
 
-		return ourPotential - enemyPotential;
-	}
+                return ourPotential - enemyPotential;
+        }
 };
-*/ // These lines may be usefull but they are't used in the code.
+*/// These lines may be usefull but they are't used in the code.
 
 struct PossibleSpellcast
 {
-	const CSpell *spell;
+	const CSpell * spell;
 	BattleHex dest;
 	si32 value;
 };
@@ -68,16 +68,16 @@ public:
 	void attemptCastingSpell();
 
 	BattleAction activeStack(const CStack * stack) override; //called when it's turn of that stack
-	BattleAction goTowards(const CStack * stack, BattleHex hex );
+	BattleAction goTowards(const CStack * stack, BattleHex hex);
 
 	boost::optional<BattleAction> considerFleeingOrSurrendering();
 
-	std::vector<BattleHex> getTargetsToConsider(const CSpell *spell, const ISpellCaster * caster) const;
-	static int distToNearestNeighbour(BattleHex hex, const ReachabilityInfo::TDistances& dists, BattleHex *chosenHex = nullptr);
+	std::vector<BattleHex> getTargetsToConsider(const CSpell * spell, const ISpellCaster * caster) const;
+	static int distToNearestNeighbour(BattleHex hex, const ReachabilityInfo::TDistances & dists, BattleHex * chosenHex = nullptr);
 	static bool isCloser(const EnemyInfo & ei1, const EnemyInfo & ei2, const ReachabilityInfo::TDistances & dists);
 
-	void print(const std::string &text) const;
-	BattleAction useCatapult(const CStack *stack);
+	void print(const std::string & text) const;
+	BattleAction useCatapult(const CStack * stack);
 	void battleStart(const CCreatureSet * army1, const CCreatureSet * army2, int3 tile, const CGHeroInstance * hero1, const CGHeroInstance * hero2, bool Side) override;
 	//void actionFinished(const BattleAction &action) override;//occurs AFTER every action taken by any stack or by the hero
 	//void actionStarted(const BattleAction &action) override;//occurs BEFORE every action taken by any stack or by the hero

+ 3 - 2
AI/BattleAI/EnemyInfo.h

@@ -19,10 +19,11 @@ public:
 	const CStack * s;
 	int adi, adr;
 	std::vector<BattleHex> attackFrom; //for melee fight
-	EnemyInfo(const CStack * _s) : s(_s)
+	EnemyInfo(const CStack * _s)
+		: s(_s)
 	{}
 	void calcDmg(const CStack * ourStack);
-	bool operator==(const EnemyInfo& ei) const
+	bool operator==(const EnemyInfo & ei) const
 	{
 		return s == ei.s;
 	}

+ 14 - 14
AI/BattleAI/PotentialTargets.cpp

@@ -15,26 +15,26 @@ PotentialTargets::PotentialTargets(const CStack * attacker, const HypotheticChan
 	auto dists = getCbc()->battleGetDistances(attacker);
 	auto avHexes = getCbc()->battleGetAvailableHexes(attacker, false);
 
-	for(const CStack *enemy : getCbc()->battleGetStacks())
+	for(const CStack * enemy : getCbc()->battleGetStacks())
 	{
 		//Consider only stacks of different owner
 		if(enemy->side == attacker->side)
 			continue;
 
 		auto GenerateAttackInfo = [&](bool shooting, BattleHex hex) -> AttackPossibility
-		{
-			auto bai = BattleAttackInfo(attacker, enemy, shooting);
-			bai.attackerBonuses = getValOr(state.bonusesOfStacks, bai.attacker, bai.attacker);
-			bai.defenderBonuses = getValOr(state.bonusesOfStacks, bai.defender, bai.defender);
-
-			if(hex.isValid())
 			{
-				assert(dists[hex] <= attacker->Speed());
-				bai.chargedFields = dists[hex];
-			}
+				auto bai = BattleAttackInfo(attacker, enemy, shooting);
+				bai.attackerBonuses = getValOr(state.bonusesOfStacks, bai.attacker, bai.attacker);
+				bai.defenderBonuses = getValOr(state.bonusesOfStacks, bai.defender, bai.defender);
+
+				if(hex.isValid())
+				{
+					assert(dists[hex] <= attacker->Speed());
+					bai.chargedFields = dists[hex];
+				}
 
-			return AttackPossibility::evaluate(bai, state, hex);
-		};
+				return AttackPossibility::evaluate(bai, state, hex);
+			};
 
 		if(getCbc()->battleCanShoot(attacker, enemy->position))
 		{
@@ -46,7 +46,7 @@ PotentialTargets::PotentialTargets(const CStack * attacker, const HypotheticChan
 				if(CStack::isMeleeAttackPossible(attacker, enemy, hex))
 					possibleAttacks.push_back(GenerateAttackInfo(false, hex));
 
-			if(!vstd::contains_if(possibleAttacks, [=](const AttackPossibility &pa) { return pa.enemy == enemy; }))
+			if(!vstd::contains_if(possibleAttacks, [=](const AttackPossibility & pa) { return pa.enemy == enemy; }))
 				unreachableEnemies.push_back(enemy);
 		}
 	}
@@ -67,5 +67,5 @@ AttackPossibility PotentialTargets::bestAction() const
 	if(possibleAttacks.empty())
 		throw std::runtime_error("No best action, since we don't have any actions");
 
-	return *vstd::maxElementByFun(possibleAttacks, [](const AttackPossibility &ap) { return ap.attackValue(); } );
+	return *vstd::maxElementByFun(possibleAttacks, [](const AttackPossibility & ap) { return ap.attackValue(); });
 }

+ 1 - 1
AI/BattleAI/PotentialTargets.h

@@ -19,7 +19,7 @@ public:
 	//std::function<AttackPossibility(bool,BattleHex)>  GenerateAttackInfo; //args: shooting, destHex
 
 	PotentialTargets(){};
-	PotentialTargets(const CStack *attacker, const HypotheticChangesToBattleState &state = HypotheticChangesToBattleState());
+	PotentialTargets(const CStack * attacker, const HypotheticChangesToBattleState & state = HypotheticChangesToBattleState());
 
 	AttackPossibility bestAction() const;
 	int bestActionValue() const;

+ 3 - 4
AI/BattleAI/StackWithBonuses.cpp

@@ -12,16 +12,15 @@
 #include "../../lib/CStack.h"
 
 
-const TBonusListPtr StackWithBonuses::getAllBonuses(const CSelector &selector, const CSelector &limit,
-							const CBonusSystemNode * root, const std::string & cachingStr) const
+const TBonusListPtr StackWithBonuses::getAllBonuses(const CSelector & selector, const CSelector & limit, const CBonusSystemNode * root, const std::string & cachingStr) const
 {
 	TBonusListPtr ret = std::make_shared<BonusList>();
 	const TBonusListPtr originalList = stack->getAllBonuses(selector, limit, root, cachingStr);
 	range::copy(*originalList, std::back_inserter(*ret));
-	for(auto &bonus : bonusesToAdd)
+	for(auto & bonus : bonusesToAdd)
 	{
 		auto b = std::make_shared<Bonus>(bonus);
-		if(selector(b.get())  &&  (!limit || !limit(b.get())))
+		if(selector(b.get()) && (!limit || !limit(b.get())))
 			ret->push_back(b);
 	}
 	//TODO limiters?

+ 2 - 3
AI/BattleAI/StackWithBonuses.h

@@ -15,9 +15,8 @@ class CStack;
 class StackWithBonuses : public IBonusBearer
 {
 public:
-	const CStack *stack;
+	const CStack * stack;
 	mutable std::vector<Bonus> bonusesToAdd;
 
-	virtual const TBonusListPtr getAllBonuses(const CSelector &selector, const CSelector &limit,
-						  const CBonusSystemNode *root = nullptr, const std::string &cachingStr = "") const override;
+	virtual const TBonusListPtr getAllBonuses(const CSelector & selector, const CSelector & limit, const CBonusSystemNode * root = nullptr, const std::string & cachingStr = "") const override;
 };

+ 47 - 47
AI/BattleAI/ThreatMap.cpp

@@ -15,59 +15,59 @@
 template <typename Container, typename Pred>
 auto sum(const Container & c, Pred p) -> decltype(p(*std::begin(c)))
 {
-	double ret = 0;
-	for(const auto &element : c)
-	{
-		ret += p(element);
-	}
+        double ret = 0;
+        for(const auto &element : c)
+        {
+                ret += p(element);
+        }
 
-	return ret;
+        return ret;
 }
 ThreatMap::ThreatMap(const CStack *Endangered) : endangered(Endangered)
 {
-	sufferedDamage.fill(0);
+        sufferedDamage.fill(0);
 
-	for(const CStack *enemy : getCbc()->battleGetStacks())
-	{
-		//Consider only stacks of different owner
-		if(enemy->side == endangered->side)
-			continue;
+        for(const CStack *enemy : getCbc()->battleGetStacks())
+        {
+                //Consider only stacks of different owner
+                if(enemy->side == endangered->side)
+                        continue;
 
-		//Look-up which tiles can be melee-attacked
-		std::array<bool, GameConstants::BFIELD_SIZE> meleeAttackable;
-		meleeAttackable.fill(false);
-		auto enemyReachability = getCbc()->getReachability(enemy);
-		for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
-		{
-			if(enemyReachability.isReachable(i))
-			{
-				meleeAttackable[i] = true;
-				for(auto n : BattleHex(i).neighbouringTiles())
-					meleeAttackable[n] = true;
-			}
-		}
+                //Look-up which tiles can be melee-attacked
+                std::array<bool, GameConstants::BFIELD_SIZE> meleeAttackable;
+                meleeAttackable.fill(false);
+                auto enemyReachability = getCbc()->getReachability(enemy);
+                for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
+                {
+                        if(enemyReachability.isReachable(i))
+                        {
+                                meleeAttackable[i] = true;
+                                for(auto n : BattleHex(i).neighbouringTiles())
+                                        meleeAttackable[n] = true;
+                        }
+                }
 
-		//Gather possible assaults
-		for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
-		{
-			if(getCbc()->battleCanShoot(enemy, i))
-				threatMap[i].push_back(BattleAttackInfo(enemy, endangered, true));
-			else if(meleeAttackable[i])
-			{
-				BattleAttackInfo bai(enemy, endangered, false);
-				bai.chargedFields = std::max(BattleHex::getDistance(enemy->position, i) - 1, 0); //TODO check real distance (BFS), not just metric
-				threatMap[i].push_back(BattleAttackInfo(bai));
-			}
-		}
-	}
+                //Gather possible assaults
+                for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
+                {
+                        if(getCbc()->battleCanShoot(enemy, i))
+                                threatMap[i].push_back(BattleAttackInfo(enemy, endangered, true));
+                        else if(meleeAttackable[i])
+                        {
+                                BattleAttackInfo bai(enemy, endangered, false);
+                                bai.chargedFields = std::max(BattleHex::getDistance(enemy->position, i) - 1, 0); //TODO check real distance (BFS), not just metric
+                                threatMap[i].push_back(BattleAttackInfo(bai));
+                        }
+                }
+        }
 
-	for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
-	{
-		sufferedDamage[i] = sum(threatMap[i], [](const BattleAttackInfo &bai) -> int
-		{
-			auto dmg = getCbc()->calculateDmgRange(bai);
-			return (dmg.first + dmg.second)/2;
-		});
-	}
+        for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
+        {
+                sufferedDamage[i] = sum(threatMap[i], [](const BattleAttackInfo &bai) -> int
+                {
+                        auto dmg = getCbc()->calculateDmgRange(bai);
+                        return (dmg.first + dmg.second)/2;
+                });
+        }
 }
-*/ // These lines may be usefull but they are't used in the code.
+*/// These lines may be usefull but they are't used in the code.

+ 5 - 5
AI/BattleAI/ThreatMap.h

@@ -16,10 +16,10 @@
 class ThreatMap
 {
 public:
-	std::array<std::vector<BattleAttackInfo>, GameConstants::BFIELD_SIZE> threatMap; // [hexNr] -> enemies able to strike
+        std::array<std::vector<BattleAttackInfo>, GameConstants::BFIELD_SIZE> threatMap; // [hexNr] -> enemies able to strike
 
-	const CStack *endangered;
-	std::array<int, GameConstants::BFIELD_SIZE> sufferedDamage;
+        const CStack *endangered;
+        std::array<int, GameConstants::BFIELD_SIZE> sufferedDamage;
 
-	ThreatMap(const CStack *Endangered);
-};*/ // These lines may be usefull but they are't used in the code.
+        ThreatMap(const CStack *Endangered);
+};*/// These lines may be usefull but they are't used in the code.

+ 1 - 1
AI/BattleAI/common.h

@@ -12,7 +12,7 @@
 class CBattleCallback;
 
 template<typename Key, typename Val, typename Val2>
-const Val getValOr(const std::map<Key, Val> &Map, const Key &key, const Val2 defaultValue)
+const Val getValOr(const std::map<Key, Val> & Map, const Key & key, const Val2 defaultValue)
 {
 	//returning references here won't work: defaultValue must be converted into Val, creating temporary
 	auto i = Map.find(key);

+ 3 - 3
AI/BattleAI/main.cpp

@@ -15,19 +15,19 @@
 #define strcpy_s(a, b, c) strncpy(a, c, b)
 #endif
 
-static const char *g_cszAiName = "Battle AI";
+static const char * g_cszAiName = "Battle AI";
 
 extern "C" DLL_EXPORT int GetGlobalAiVersion()
 {
 	return AI_INTERFACE_VER;
 }
 
-extern "C" DLL_EXPORT void GetAiName(char* name)
+extern "C" DLL_EXPORT void GetAiName(char * name)
 {
 	strcpy_s(name, strlen(g_cszAiName) + 1, g_cszAiName);
 }
 
-extern "C" DLL_EXPORT void GetNewBattleAI(std::shared_ptr<CBattleGameInterface> &out)
+extern "C" DLL_EXPORT void GetNewBattleAI(std::shared_ptr<CBattleGameInterface> & out)
 {
 	out = std::make_shared<CBattleAI>();
 }

+ 4 - 4
AI/EmptyAI/CEmptyAI.cpp

@@ -15,7 +15,7 @@
 void CEmptyAI::init(std::shared_ptr<CCallback> CB)
 {
 	cb = CB;
-	human=false;
+	human = false;
 	playerID = *cb->getMyColor();
 }
 void CEmptyAI::yourTurn()
@@ -23,7 +23,7 @@ void CEmptyAI::yourTurn()
 	cb->endTurn();
 }
 
-void CEmptyAI::heroGotLevel(const CGHeroInstance *hero, PrimarySkill::PrimarySkill pskill, std::vector<SecondarySkill> &skills, QueryID queryID)
+void CEmptyAI::heroGotLevel(const CGHeroInstance * hero, PrimarySkill::PrimarySkill pskill, std::vector<SecondarySkill> & skills, QueryID queryID)
 {
 	cb->selectionMade(CRandomGenerator::getDefault().nextInt(skills.size() - 1), queryID);
 }
@@ -33,7 +33,7 @@ void CEmptyAI::commanderGotLevel(const CCommanderInstance * commander, std::vect
 	cb->selectionMade(CRandomGenerator::getDefault().nextInt(skills.size() - 1), queryID);
 }
 
-void CEmptyAI::showBlockingDialog(const std::string &text, const std::vector<Component> &components, QueryID askID, const int soundID, bool selection, bool cancel)
+void CEmptyAI::showBlockingDialog(const std::string & text, const std::vector<Component> & components, QueryID askID, const int soundID, bool selection, bool cancel)
 {
 	cb->selectionMade(0, askID);
 }
@@ -43,7 +43,7 @@ void CEmptyAI::showTeleportDialog(TeleportChannelID channel, TTeleportExitsList
 	cb->selectionMade(0, askID);
 }
 
-void CEmptyAI::showGarrisonDialog(const CArmedInstance *up, const CGHeroInstance *down, bool removableUnits, QueryID queryID)
+void CEmptyAI::showGarrisonDialog(const CArmedInstance * up, const CGHeroInstance * down, bool removableUnits, QueryID queryID)
 {
 	cb->selectionMade(0, queryID);
 }

+ 4 - 4
AI/EmptyAI/CEmptyAI.h

@@ -21,11 +21,11 @@ class CEmptyAI : public CGlobalAI
 public:
 	void init(std::shared_ptr<CCallback> CB) override;
 	void yourTurn() override;
-	void heroGotLevel(const CGHeroInstance *hero, PrimarySkill::PrimarySkill pskill, std::vector<SecondarySkill> &skills, QueryID queryID) override;
-	void commanderGotLevel (const CCommanderInstance * commander, std::vector<ui32> skills, QueryID queryID) override;
-	void showBlockingDialog(const std::string &text, const std::vector<Component> &components, QueryID askID, const int soundID, bool selection, bool cancel) override;
+	void heroGotLevel(const CGHeroInstance * hero, PrimarySkill::PrimarySkill pskill, std::vector<SecondarySkill> & skills, QueryID queryID) override;
+	void commanderGotLevel(const CCommanderInstance * commander, std::vector<ui32> skills, QueryID queryID) override;
+	void showBlockingDialog(const std::string & text, const std::vector<Component> & components, QueryID askID, const int soundID, bool selection, bool cancel) override;
 	void showTeleportDialog(TeleportChannelID channel, TTeleportExitsList exits, bool impassable, QueryID askID) override;
-	void showGarrisonDialog(const CArmedInstance *up, const CGHeroInstance *down, bool removableUnits, QueryID queryID) override;
+	void showGarrisonDialog(const CArmedInstance * up, const CGHeroInstance * down, bool removableUnits, QueryID queryID) override;
 	void showMapObjectSelectDialog(QueryID askID, const Component & icon, const MetaString & title, const MetaString & description, const std::vector<ObjectInstanceID> & objects) override;
 };
 

+ 1 - 1
AI/EmptyAI/StdInc.cpp

@@ -1,2 +1,2 @@
-// Creates the precompiled header
+// Creates the precompiled header
 #include "StdInc.h"

+ 1 - 1
AI/EmptyAI/StdInc.h

@@ -4,4 +4,4 @@
 
 // This header should be treated as a pre compiled header file(PCH) in the compiler building settings.
 
-// Here you can add specific libraries and macros which are specific to this project.
+// Here you can add specific libraries and macros which are specific to this project.

+ 4 - 4
AI/EmptyAI/exp_funcs.cpp

@@ -11,18 +11,18 @@
 
 #include "CEmptyAI.h"
 
-std::set<CGlobalAI*> ais;
+std::set<CGlobalAI *> ais;
 extern "C" DLL_EXPORT int GetGlobalAiVersion()
 {
 	return AI_INTERFACE_VER;
 }
 
-extern "C" DLL_EXPORT void GetAiName(char* name)
+extern "C" DLL_EXPORT void GetAiName(char * name)
 {
-	strcpy(name,NAME);
+	strcpy(name, NAME);
 }
 
-extern "C" DLL_EXPORT void GetNewAI(std::shared_ptr<CGlobalAI> &out)
+extern "C" DLL_EXPORT void GetNewAI(std::shared_ptr<CGlobalAI> & out)
 {
 	out = std::make_shared<CEmptyAI>();
 }

+ 1 - 1
AI/StupidAI/StdInc.cpp

@@ -1,2 +1,2 @@
-// Creates the precompiled header
+// Creates the precompiled header
 #include "StdInc.h"

+ 1 - 1
AI/StupidAI/StdInc.h

@@ -4,4 +4,4 @@
 
 // This header should be treated as a pre compiled header file(PCH) in the compiler building settings.
 
-// Here you can add specific libraries and macros which are specific to this project.
+// Here you can add specific libraries and macros which are specific to this project.

+ 36 - 34
AI/StupidAI/StupidAI.cpp

@@ -34,12 +34,12 @@ void CStupidAI::init(std::shared_ptr<CBattleCallback> CB)
 	cbc = cb = CB;
 }
 
-void CStupidAI::actionFinished(const BattleAction &action)
+void CStupidAI::actionFinished(const BattleAction & action)
 {
 	print("actionFinished called");
 }
 
-void CStupidAI::actionStarted(const BattleAction &action)
+void CStupidAI::actionStarted(const BattleAction & action)
 {
 	print("actionStarted called");
 }
@@ -49,7 +49,8 @@ struct EnemyInfo
 	const CStack * s;
 	int adi, adr;
 	std::vector<BattleHex> attackFrom; //for melee fight
-	EnemyInfo(const CStack * _s) : s(_s), adi(0), adr(0)
+	EnemyInfo(const CStack * _s)
+		: s(_s), adi(0), adr(0)
 	{}
 	void calcDmg(const CStack * ourStack)
 	{
@@ -58,23 +59,24 @@ struct EnemyInfo
 		adr = (retal.first + retal.second) / 2;
 	}
 
-	bool operator==(const EnemyInfo& ei) const
+	bool operator==(const EnemyInfo & ei) const
 	{
 		return s == ei.s;
 	}
 };
 
-bool isMoreProfitable(const EnemyInfo &ei1, const EnemyInfo& ei2)
+bool isMoreProfitable(const EnemyInfo & ei1, const EnemyInfo & ei2)
 {
-	return (ei1.adi-ei1.adr) < (ei2.adi - ei2.adr);
+	return (ei1.adi - ei1.adr) < (ei2.adi - ei2.adr);
 }
 
-namespace {
+namespace
+{
 
-int distToNearestNeighbour(BattleHex hex, const ReachabilityInfo::TDistances& dists, BattleHex *chosenHex = nullptr)
+int distToNearestNeighbour(BattleHex hex, const ReachabilityInfo::TDistances & dists, BattleHex * chosenHex = nullptr)
 {
 	int ret = 1000000;
-	for(auto & n: hex.neighbouringTiles())
+	for(auto & n : hex.neighbouringTiles())
 	{
 		if(dists[n] >= 0 && dists[n] < ret)
 		{
@@ -94,20 +96,20 @@ bool isCloser(const EnemyInfo & ei1, const EnemyInfo & ei2, const ReachabilityIn
 
 }
 
-static bool willSecondHexBlockMoreEnemyShooters(const BattleHex &h1, const BattleHex &h2)
+static bool willSecondHexBlockMoreEnemyShooters(const BattleHex & h1, const BattleHex & h2)
 {
 	int shooters[2] = {0}; //count of shooters on hexes
 
 	for(int i = 0; i < 2; i++)
-		for (auto & neighbour : (i ? h2 : h1).neighbouringTiles())
-			if(const CStack *s = cbc->battleGetStackByPos(neighbour))
+		for(auto & neighbour : (i ? h2 : h1).neighbouringTiles())
+			if(const CStack * s = cbc->battleGetStackByPos(neighbour))
 				if(s->getCreature()->isShooting())
-						shooters[i]++;
+					shooters[i]++;
 
 	return shooters[0] < shooters[1];
 }
 
-BattleAction CStupidAI::activeStack( const CStack * stack )
+BattleAction CStupidAI::activeStack(const CStack * stack)
 {
 	//boost::this_thread::sleep(boost::posix_time::seconds(2));
 	print("activeStack called for " + stack->nodeName());
@@ -132,7 +134,7 @@ BattleAction CStupidAI::activeStack( const CStack * stack )
 		return BattleAction::makeDefend(stack);
 	}
 
-	for (const CStack *s : cb->battleGetStacks(CBattleCallback::ONLY_ENEMY))
+	for(const CStack * s : cb->battleGetStacks(CBattleCallback::ONLY_ENEMY))
 	{
 		if(cb->battleCanShoot(stack, s->position))
 		{
@@ -142,7 +144,7 @@ BattleAction CStupidAI::activeStack( const CStack * stack )
 		{
 			std::vector<BattleHex> avHexes = cb->battleGetAvailableHexes(stack, false);
 
-			for (BattleHex hex : avHexes)
+			for(BattleHex hex : avHexes)
 			{
 				if(CStack::isMeleeAttackPossible(stack, s, hex))
 				{
@@ -162,26 +164,26 @@ BattleAction CStupidAI::activeStack( const CStack * stack )
 		}
 	}
 
-	for ( auto & enemy : enemiesReachable )
-		enemy.calcDmg( stack );
+	for(auto & enemy : enemiesReachable)
+		enemy.calcDmg(stack);
 
-	for ( auto & enemy : enemiesShootable )
-		enemy.calcDmg( stack );
+	for(auto & enemy : enemiesShootable)
+		enemy.calcDmg(stack);
 
 	if(enemiesShootable.size())
 	{
-		const EnemyInfo &ei= *std::max_element(enemiesShootable.begin(), enemiesShootable.end(), isMoreProfitable);
+		const EnemyInfo & ei = *std::max_element(enemiesShootable.begin(), enemiesShootable.end(), isMoreProfitable);
 		return BattleAction::makeShotAttack(stack, ei.s);
 	}
 	else if(enemiesReachable.size())
 	{
-		const EnemyInfo &ei= *std::max_element(enemiesReachable.begin(), enemiesReachable.end(), &isMoreProfitable);
+		const EnemyInfo & ei = *std::max_element(enemiesReachable.begin(), enemiesReachable.end(), &isMoreProfitable);
 		return BattleAction::makeMeleeAttack(stack, ei.s, *std::max_element(ei.attackFrom.begin(), ei.attackFrom.end(), &willSecondHexBlockMoreEnemyShooters));
 	}
 	else if(enemiesUnreachable.size()) //due to #955 - a buggy battle may occur when there are no enemies
 	{
 		assert(enemiesUnreachable.size());
-		const EnemyInfo &ei= *std::min_element(enemiesUnreachable.begin(), enemiesUnreachable.end(), std::bind(isCloser, _1, _2, std::ref(dists)));
+		const EnemyInfo & ei = *std::min_element(enemiesUnreachable.begin(), enemiesUnreachable.end(), std::bind(isCloser, _1, _2, std::ref(dists)));
 		assert(ei.s);
 		if(distToNearestNeighbour(ei.s->position, dists) < GameConstants::BFIELD_SIZE)
 		{
@@ -192,7 +194,7 @@ BattleAction CStupidAI::activeStack( const CStack * stack )
 	return BattleAction::makeDefend(stack);
 }
 
-void CStupidAI::battleAttack(const BattleAttack *ba)
+void CStupidAI::battleAttack(const BattleAttack * ba)
 {
 	print("battleAttack called");
 }
@@ -202,14 +204,14 @@ void CStupidAI::battleStacksAttacked(const std::vector<BattleStackAttacked> & bs
 	print("battleStacksAttacked called");
 }
 
-void CStupidAI::battleEnd(const BattleResult *br)
+void CStupidAI::battleEnd(const BattleResult * br)
 {
 	print("battleEnd called");
 }
 
 // void CStupidAI::battleResultsApplied()
 // {
-// 	print("battleResultsApplied called");
+//      print("battleResultsApplied called");
 // }
 
 void CStupidAI::battleNewRoundFirst(int round)
@@ -227,7 +229,7 @@ void CStupidAI::battleStackMoved(const CStack * stack, std::vector<BattleHex> de
 	print("battleStackMoved called");
 }
 
-void CStupidAI::battleSpellCast(const BattleSpellCast *sc)
+void CStupidAI::battleSpellCast(const BattleSpellCast * sc)
 {
 	print("battleSpellCast called");
 }
@@ -237,13 +239,13 @@ void CStupidAI::battleStacksEffectsSet(const SetStackEffect & sse)
 	print("battleStacksEffectsSet called");
 }
 
-void CStupidAI::battleStart(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool Side)
+void CStupidAI::battleStart(const CCreatureSet * army1, const CCreatureSet * army2, int3 tile, const CGHeroInstance * hero1, const CGHeroInstance * hero2, bool Side)
 {
 	print("battleStart called");
 	side = Side;
 }
 
-void CStupidAI::battleStacksHealedRes(const std::vector<std::pair<ui32, ui32> > & healedStacks, bool lifeDrain, bool tentHeal, si32 lifeDrainFrom)
+void CStupidAI::battleStacksHealedRes(const std::vector<std::pair<ui32, ui32>> & healedStacks, bool lifeDrain, bool tentHeal, si32 lifeDrainFrom)
 {
 	print("battleStacksHealedRes called");
 }
@@ -268,7 +270,7 @@ void CStupidAI::battleStacksRemoved(const BattleStacksRemoved & bsr)
 	print("battleStacksRemoved called");
 }
 
-void CStupidAI::print(const std::string &text) const
+void CStupidAI::print(const std::string & text) const
 {
 	logAi->trace("CStupidAI  [%p]: %s", this, text);
 }
@@ -303,14 +305,14 @@ BattleAction CStupidAI::goTowards(const CStack * stack, BattleHex destination)
 		// Flying stack doesn't go hex by hex, so we can't backtrack using predecessors.
 		// We just check all available hexes and pick the one closest to the target.
 		auto distToDestNeighbour = [&](BattleHex hex) -> int
-		{
-			auto nearestNeighbourToHex = vstd::minElementByFun(destNeighbours, [&](BattleHex a)
+			{
+				auto nearestNeighbourToHex = vstd::minElementByFun(destNeighbours, [&](BattleHex a)
 			{
 				return BattleHex::getDistance(a, hex);
 			});
 
-			return BattleHex::getDistance(*nearestNeighbourToHex, hex);
-		};
+				return BattleHex::getDistance(*nearestNeighbourToHex, hex);
+			};
 
 		auto nearestAvailableHex = vstd::minElementByFun(avHexes, distToDestNeighbour);
 		return BattleAction::makeMove(stack, *nearestAvailableHex);

+ 11 - 11
AI/StupidAI/StupidAI.h

@@ -16,37 +16,37 @@ class CStupidAI : public CBattleGameInterface
 	int side;
 	std::shared_ptr<CBattleCallback> cb;
 
-	void print(const std::string &text) const;
+	void print(const std::string & text) const;
+
 public:
 	CStupidAI(void);
 	~CStupidAI(void);
 
 	void init(std::shared_ptr<CBattleCallback> CB) override;
-	void actionFinished(const BattleAction &action) override;//occurs AFTER every action taken by any stack or by the hero
-	void actionStarted(const BattleAction &action) override;//occurs BEFORE every action taken by any stack or by the hero
+	void actionFinished(const BattleAction & action) override; //occurs AFTER every action taken by any stack or by the hero
+	void actionStarted(const BattleAction & action) override; //occurs BEFORE every action taken by any stack or by the hero
 	BattleAction activeStack(const CStack * stack) override; //called when it's turn of that stack
 
-	void battleAttack(const BattleAttack *ba) override; //called when stack is performing attack
+	void battleAttack(const BattleAttack * ba) override; //called when stack is performing attack
 	void battleStacksAttacked(const std::vector<BattleStackAttacked> & bsa) override; //called when stack receives damage (after battleAttack())
-	void battleEnd(const BattleResult *br) override;
+	void battleEnd(const BattleResult * br) override;
 	//void battleResultsApplied() override; //called when all effects of last battle are applied
 	void battleNewRoundFirst(int round) override; //called at the beginning of each turn before changes are applied;
 	void battleNewRound(int round) override; //called at the beginning of each turn, round=-1 is the tactic phase, round=0 is the first "normal" turn
 	void battleStackMoved(const CStack * stack, std::vector<BattleHex> dest, int distance) override;
-	void battleSpellCast(const BattleSpellCast *sc) override;
-	void battleStacksEffectsSet(const SetStackEffect & sse) override;//called when a specific effect is set to stacks
+	void battleSpellCast(const BattleSpellCast * sc) override;
+	void battleStacksEffectsSet(const SetStackEffect & sse) override; //called when a specific effect is set to stacks
 	//void battleTriggerEffect(const BattleTriggerEffect & bte) override;
-	void battleStart(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool side) override; //called by engine when battle starts; side=0 - left, side=1 - right
-	void battleStacksHealedRes(const std::vector<std::pair<ui32, ui32> > & healedStacks, bool lifeDrain, bool tentHeal, si32 lifeDrainFrom) override; //called when stacks are healed / resurrected first element of pair - stack id, second - healed hp
+	void battleStart(const CCreatureSet * army1, const CCreatureSet * army2, int3 tile, const CGHeroInstance * hero1, const CGHeroInstance * hero2, bool side) override; //called by engine when battle starts; side=0 - left, side=1 - right
+	void battleStacksHealedRes(const std::vector<std::pair<ui32, ui32>> & healedStacks, bool lifeDrain, bool tentHeal, si32 lifeDrainFrom) override; //called when stacks are healed / resurrected first element of pair - stack id, second - healed hp
 	void battleNewStackAppeared(const CStack * stack) override; //not called at the beginning of a battle or by resurrection; called eg. when elemental is summoned
 	void battleObstaclesRemoved(const std::set<si32> & removedObstacles) override; //called when a certain set  of obstacles is removed from batlefield; IDs of them are given
 	void battleCatapultAttacked(const CatapultAttack & ca) override; //called when catapult makes an attack
 	void battleStacksRemoved(const BattleStacksRemoved & bsr) override; //called when certain stack is completely removed from battlefield
 
-	BattleAction goTowards(const CStack * stack, BattleHex hex );
+	BattleAction goTowards(const CStack * stack, BattleHex hex);
 
 	virtual void saveGame(BinarySerializer & h, const int version) override;
 	virtual void loadGame(BinaryDeserializer & h, const int version) override;
 
 };
-

+ 3 - 3
AI/StupidAI/main.cpp

@@ -16,19 +16,19 @@
 #define strcpy_s(a, b, c) strncpy(a, c, b)
 #endif
 
-static const char *g_cszAiName = "Stupid AI 0.1";
+static const char * g_cszAiName = "Stupid AI 0.1";
 
 extern "C" DLL_EXPORT int GetGlobalAiVersion()
 {
 	return AI_INTERFACE_VER;
 }
 
-extern "C" DLL_EXPORT void GetAiName(char* name)
+extern "C" DLL_EXPORT void GetAiName(char * name)
 {
 	strcpy_s(name, strlen(g_cszAiName) + 1, g_cszAiName);
 }
 
-extern "C" DLL_EXPORT void GetNewBattleAI(std::shared_ptr<CBattleGameInterface> &out)
+extern "C" DLL_EXPORT void GetNewBattleAI(std::shared_ptr<CBattleGameInterface> & out)
 {
 	out = std::make_shared<CStupidAI>();
 }

+ 107 - 104
AI/VCAI/AIUtility.cpp

@@ -23,7 +23,7 @@
 
 extern boost::thread_specific_ptr<CCallback> cb;
 extern boost::thread_specific_ptr<VCAI> ai;
-extern FuzzyHelper *fh;
+extern FuzzyHelper * fh;
 
 //extern static const int3 dirs[8];
 
@@ -32,27 +32,29 @@ const CGObjectInstance * ObjectIdRef::operator->() const
 	return cb->getObj(id, false);
 }
 
-ObjectIdRef::operator const CGObjectInstance*() const
+ObjectIdRef::operator const CGObjectInstance *() const
 {
 	return cb->getObj(id, false);
 }
 
-ObjectIdRef::ObjectIdRef(ObjectInstanceID _id) : id(_id)
+ObjectIdRef::ObjectIdRef(ObjectInstanceID _id)
+	: id(_id)
 {
 
 }
 
-ObjectIdRef::ObjectIdRef(const CGObjectInstance *obj) : id(obj->id)
+ObjectIdRef::ObjectIdRef(const CGObjectInstance * obj)
+	: id(obj->id)
 {
 
 }
 
-bool ObjectIdRef::operator<(const ObjectIdRef &rhs) const
+bool ObjectIdRef::operator<(const ObjectIdRef & rhs) const
 {
 	return id < rhs.id;
 }
 
-HeroPtr::HeroPtr(const CGHeroInstance *H)
+HeroPtr::HeroPtr(const CGHeroInstance * H)
 {
 	if(!H)
 	{
@@ -76,11 +78,11 @@ HeroPtr::HeroPtr()
 
 HeroPtr::~HeroPtr()
 {
-// 	if(hid >= 0)
-// 		infosCount[ai->playerID][hid]--;
+//      if(hid >= 0)
+//              infosCount[ai->playerID][hid]--;
 }
 
-bool HeroPtr::operator<(const HeroPtr &rhs) const
+bool HeroPtr::operator<(const HeroPtr & rhs) const
 {
 	return hid < rhs.hid;
 }
@@ -126,7 +128,7 @@ const CGHeroInstance * HeroPtr::operator*() const
 	return get();
 }
 
-void foreach_tile_pos(std::function<void(const int3& pos)> foo)
+void foreach_tile_pos(std::function<void(const int3 &pos)> foo)
 {
 	// some micro-optimizations since this function gets called a LOT
 	// callback pointer is thread-specific and slow to retrieve -> read map size only once
@@ -135,39 +137,39 @@ void foreach_tile_pos(std::function<void(const int3& pos)> foo)
 	for(int i = 0; i < mapSize.x; i++)
 		for(int j = 0; j < mapSize.y; j++)
 			for(int k = 0; k < mapSize.z; k++)
-				foo(int3(i,j,k));
+				foo(int3(i, j, k));
 
 }
 
-void foreach_tile_pos(CCallback * cbp, std::function<void(CCallback * cbp, const int3& pos)> foo)
+void foreach_tile_pos(CCallback * cbp, std::function<void(CCallback * cbp, const int3 &pos)> foo)
 {
 	int3 mapSize = cbp->getMapSize();
 
 	for(int i = 0; i < mapSize.x; i++)
 		for(int j = 0; j < mapSize.y; j++)
 			for(int k = 0; k < mapSize.z; k++)
-				foo(cbp, int3(i,j,k));
+				foo(cbp, int3(i, j, k));
 }
 
-void foreach_neighbour(const int3 &pos, std::function<void(const int3& pos)> foo)
+void foreach_neighbour(const int3 & pos, std::function<void(const int3 &pos)> foo)
 {
 	CCallback * cbp = cb.get(); // avoid costly retrieval of thread-specific pointer
 
-	for(const int3 &dir : int3::getDirs())
+	for(const int3 & dir : int3::getDirs())
 	{
 		const int3 n = pos + dir;
 		if(cbp->isInTheMap(n))
-			foo(pos+dir);
+			foo(pos + dir);
 	}
 }
 
-void foreach_neighbour(CCallback * cbp, const int3 &pos, std::function<void(CCallback * cbp, const int3& pos)> foo)
+void foreach_neighbour(CCallback * cbp, const int3 & pos, std::function<void(CCallback * cbp, const int3 &pos)> foo)
 {
-	for(const int3 &dir : int3::getDirs())
+	for(const int3 & dir : int3::getDirs())
 	{
 		const int3 n = pos + dir;
 		if(cbp->isInTheMap(n))
-			foo(cbp, pos+dir);
+			foo(cbp, pos + dir);
 	}
 }
 
@@ -178,10 +180,10 @@ std::string strFromInt3(int3 pos)
 	return oss.str();
 }
 
-bool CDistanceSorter::operator ()(const CGObjectInstance *lhs, const CGObjectInstance *rhs)
+bool CDistanceSorter::operator()(const CGObjectInstance * lhs, const CGObjectInstance * rhs)
 {
-	const CGPathNode *ln = ai->myCb->getPathsInfo(hero)->getPathInfo(lhs->visitablePos()),
-	                 *rn = ai->myCb->getPathsInfo(hero)->getPathInfo(rhs->visitablePos());
+	const CGPathNode * ln = ai->myCb->getPathsInfo(hero)->getPathInfo(lhs->visitablePos()),
+			 * rn = ai->myCb->getPathsInfo(hero)->getPathInfo(rhs->visitablePos());
 
 	if(ln->turns != rn->turns)
 		return ln->turns < rn->turns;
@@ -196,7 +198,7 @@ bool compareMovement(HeroPtr lhs, HeroPtr rhs)
 
 ui64 evaluateDanger(crint3 tile)
 {
-	const TerrainTile *t = cb->getTile(tile, false);
+	const TerrainTile * t = cb->getTile(tile, false);
 	if(!t) //we can know about guard but can't check its tile (the edge of fow)
 		return 190000000; //MUCH
 
@@ -214,9 +216,9 @@ ui64 evaluateDanger(crint3 tile)
 	return std::max(objectDanger, guardDanger);
 }
 
-ui64 evaluateDanger(crint3 tile, const CGHeroInstance *visitor)
+ui64 evaluateDanger(crint3 tile, const CGHeroInstance * visitor)
 {
-	const TerrainTile *t = cb->getTile(tile, false);
+	const TerrainTile * t = cb->getTile(tile, false);
 	if(!t) //we can know about guard but can't check its tile (the edge of fow)
 		return 190000000; //MUCH
 
@@ -233,35 +235,35 @@ ui64 evaluateDanger(crint3 tile, const CGHeroInstance *visitor)
 	if(const CGObjectInstance * dangerousObject = vstd::backOrNull(visitableObjects))
 	{
 		objectDanger = evaluateDanger(dangerousObject); //unguarded objects can also be dangerous or unhandled
-		if (objectDanger)
+		if(objectDanger)
 		{
 			//TODO: don't downcast objects AI shouldn't know about!
-			auto armedObj = dynamic_cast<const CArmedInstance*>(dangerousObject);
-			if (armedObj)
+			auto armedObj = dynamic_cast<const CArmedInstance *>(dangerousObject);
+			if(armedObj)
 			{
 				float tacticalAdvantage = fh->getTacticalAdvantage(visitor, armedObj);
 				objectDanger *= tacticalAdvantage; //this line tends to go infinite for allied towns (?)
 			}
 		}
-		if (dangerousObject->ID == Obj::SUBTERRANEAN_GATE)
+		if(dangerousObject->ID == Obj::SUBTERRANEAN_GATE)
 		{ //check guard on the other side of the gate
 			auto it = ai->knownSubterraneanGates.find(dangerousObject);
-			if (it != ai->knownSubterraneanGates.end())
+			if(it != ai->knownSubterraneanGates.end())
 			{
 				auto guards = cb->getGuardingCreatures(it->second->visitablePos());
-				for (auto cre : guards)
+				for(auto cre : guards)
 				{
-					vstd::amax (guardDanger, evaluateDanger(cre) *
-						fh->getTacticalAdvantage(visitor, dynamic_cast<const CArmedInstance*>(cre)));
+					vstd::amax(guardDanger, evaluateDanger(cre) *
+						   fh->getTacticalAdvantage(visitor, dynamic_cast<const CArmedInstance *>(cre)));
 				}
 			}
 		}
 	}
 
 	auto guards = cb->getGuardingCreatures(tile);
-	for (auto cre : guards)
+	for(auto cre : guards)
 	{
-		vstd::amax (guardDanger, evaluateDanger(cre) * fh->getTacticalAdvantage(visitor, dynamic_cast<const CArmedInstance*>(cre))); //we are interested in strongest monster around
+		vstd::amax(guardDanger, evaluateDanger(cre) * fh->getTacticalAdvantage(visitor, dynamic_cast<const CArmedInstance *>(cre))); //we are interested in strongest monster around
 	}
 
 
@@ -269,7 +271,7 @@ ui64 evaluateDanger(crint3 tile, const CGHeroInstance *visitor)
 	return std::max(objectDanger, guardDanger);
 }
 
-ui64 evaluateDanger(const CGObjectInstance *obj)
+ui64 evaluateDanger(const CGObjectInstance * obj)
 {
 	if(obj->tempOwner < PlayerColor::PLAYER_LIMIT && cb->getPlayerRelations(obj->tempOwner, ai->playerID) != PlayerRelations::ENEMIES) //owned or allied objects don't pose any threat
 		return 0;
@@ -277,56 +279,57 @@ ui64 evaluateDanger(const CGObjectInstance *obj)
 	switch(obj->ID)
 	{
 	case Obj::HERO:
-		{
-			InfoAboutHero iah;
-			cb->getHeroInfo(obj, iah);
-			return iah.army.getStrength();
-		}
+	{
+		InfoAboutHero iah;
+		cb->getHeroInfo(obj, iah);
+		return iah.army.getStrength();
+	}
 	case Obj::TOWN:
-	case Obj::GARRISON: case Obj::GARRISON2: //garrison
-		{
-			InfoAboutTown iat;
-			cb->getTownInfo(obj, iat);
-			return iat.army.getStrength();
-		}
+	case Obj::GARRISON:
+	case Obj::GARRISON2: //garrison
+	{
+		InfoAboutTown iat;
+		cb->getTownInfo(obj, iat);
+		return iat.army.getStrength();
+	}
 	case Obj::MONSTER:
-		{
-			//TODO!!!!!!!!
-			const CGCreature *cre = dynamic_cast<const CGCreature*>(obj);
-			return cre->getArmyStrength();
-		}
+	{
+		//TODO!!!!!!!!
+		const CGCreature * cre = dynamic_cast<const CGCreature *>(obj);
+		return cre->getArmyStrength();
+	}
 	case Obj::CREATURE_GENERATOR1:
 	case Obj::CREATURE_GENERATOR4:
-		{
-			const CGDwelling *d = dynamic_cast<const CGDwelling*>(obj);
-			return d->getArmyStrength();
-		}
+	{
+		const CGDwelling * d = dynamic_cast<const CGDwelling *>(obj);
+		return d->getArmyStrength();
+	}
 	case Obj::MINE:
 	case Obj::ABANDONED_MINE:
-		{
-			const CArmedInstance * a = dynamic_cast<const CArmedInstance*>(obj);
-			return a->getArmyStrength();
-		}
+	{
+		const CArmedInstance * a = dynamic_cast<const CArmedInstance *>(obj);
+		return a->getArmyStrength();
+	}
 	case Obj::CRYPT: //crypt
 	case Obj::CREATURE_BANK: //crebank
 	case Obj::DRAGON_UTOPIA:
 	case Obj::SHIPWRECK: //shipwreck
 	case Obj::DERELICT_SHIP: //derelict ship
 //	case Obj::PYRAMID:
-		return fh->estimateBankDanger (dynamic_cast<const CBank *>(obj));
+		return fh->estimateBankDanger(dynamic_cast<const CBank *>(obj));
 	case Obj::PYRAMID:
-		{
-		    if(obj->subID == 0)
-				return fh->estimateBankDanger (dynamic_cast<const CBank *>(obj));
-			else
-				return 0;
-		}
+	{
+		if(obj->subID == 0)
+			return fh->estimateBankDanger(dynamic_cast<const CBank *>(obj));
+		else
+			return 0;
+	}
 	default:
 		return 0;
 	}
 }
 
-bool compareDanger(const CGObjectInstance *lhs, const CGObjectInstance *rhs)
+bool compareDanger(const CGObjectInstance * lhs, const CGObjectInstance * rhs)
 {
 	return evaluateDanger(lhs) < evaluateDanger(rhs);
 }
@@ -334,7 +337,7 @@ bool compareDanger(const CGObjectInstance *lhs, const CGObjectInstance *rhs)
 bool isSafeToVisit(HeroPtr h, crint3 tile)
 {
 	const ui64 heroStrength = h->getTotalStrength(),
-				dangerStrength = evaluateDanger(tile, *h);
+		   dangerStrength = evaluateDanger(tile, *h);
 	if(dangerStrength)
 	{
 		if(heroStrength / SAFE_ATTACK_CONSTANT > dangerStrength)
@@ -349,17 +352,17 @@ bool isSafeToVisit(HeroPtr h, crint3 tile)
 	return true; //there's no danger
 }
 
-bool canBeEmbarkmentPoint(const TerrainTile *t, bool fromWater)
+bool canBeEmbarkmentPoint(const TerrainTile * t, bool fromWater)
 {
 	//tile must be free of with unoccupied boat
 	return !t->blocked
-        || (!fromWater && t->visitableObjects.size() == 1 && t->topVisitableId() == Obj::BOAT);
+	       || (!fromWater && t->visitableObjects.size() == 1 && t->topVisitableId() == Obj::BOAT);
 	//do not try to board when in water sector
 }
 
 int3 whereToExplore(HeroPtr h)
 {
-	TimeCheck tc ("where to explore");
+	TimeCheck tc("where to explore");
 	int radius = h->getSightRadius();
 	int3 hpos = h->visitablePos();
 
@@ -368,22 +371,22 @@ int3 whereToExplore(HeroPtr h)
 	//look for nearby objs -> visit them if they're close enouh
 	const int DIST_LIMIT = 3;
 	std::vector<const CGObjectInstance *> nearbyVisitableObjs;
-	for (int x = hpos.x - DIST_LIMIT; x <= hpos.x + DIST_LIMIT; ++x) //get only local objects instead of all possible objects on the map
+	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
 	{
-		for (int y = hpos.y - DIST_LIMIT; y <= hpos.y + DIST_LIMIT; ++y)
+		for(int y = hpos.y - DIST_LIMIT; y <= hpos.y + DIST_LIMIT; ++y)
 		{
-			for (auto obj : cb->getVisitableObjs (int3(x,y,hpos.z), false))
+			for(auto obj : cb->getVisitableObjs(int3(x, y, hpos.z), false))
 			{
 				int3 op = obj->visitablePos();
 				CGPath p;
 				ai->myCb->getPathsInfo(h.get())->getPath(p, op);
-				if (p.nodes.size() && p.endPos() == op && p.nodes.size() <= DIST_LIMIT)
-					if (ai->isGoodForVisit(obj, h, *sm))
+				if(p.nodes.size() && p.endPos() == op && p.nodes.size() <= DIST_LIMIT)
+					if(ai->isGoodForVisit(obj, h, *sm))
 						nearbyVisitableObjs.push_back(obj);
 			}
 		}
 	}
-	vstd::removeDuplicates (nearbyVisitableObjs); //one object may occupy multiple tiles
+	vstd::removeDuplicates(nearbyVisitableObjs); //one object may occupy multiple tiles
 	boost::sort(nearbyVisitableObjs, CDistanceSorter(h.get()));
 	if(nearbyVisitableObjs.size())
 		return nearbyVisitableObjs.back()->visitablePos();
@@ -392,7 +395,7 @@ int3 whereToExplore(HeroPtr h)
 	{
 		return ai->explorationBestNeighbour(hpos, radius, h);
 	}
-	catch(cannotFulfillGoalException &e)
+	catch(cannotFulfillGoalException & e)
 	{
 		//perform exhaustive search
 		return ai->explorationNewPoint(h);
@@ -401,29 +404,29 @@ int3 whereToExplore(HeroPtr h)
 
 bool isBlockedBorderGate(int3 tileToHit) //TODO: is that function needed? should be handled by pathfinder
 {
-    return cb->getTile(tileToHit)->topVisitableId() == Obj::BORDER_GATE &&
-	       (dynamic_cast <const CGKeys *>(cb->getTile(tileToHit)->visitableObjects.back()))->wasMyColorVisited (ai->playerID);
+	return cb->getTile(tileToHit)->topVisitableId() == Obj::BORDER_GATE &&
+	       (dynamic_cast<const CGKeys *>(cb->getTile(tileToHit)->visitableObjects.back()))->wasMyColorVisited(ai->playerID);
 }
-bool isBlockVisitObj(const int3 &pos)
+bool isBlockVisitObj(const int3 & pos)
 {
-	if (auto obj = cb->getTopObj(pos))
-		if (obj->blockVisit) //we can't stand on that object
+	if(auto obj = cb->getTopObj(pos))
+		if(obj->blockVisit) //we can't stand on that object
 			return true;
 
 	return false;
 }
 
-int howManyTilesWillBeDiscovered(const int3 &pos, int radious, CCallback * cbp)
+int howManyTilesWillBeDiscovered(const int3 & pos, int radious, CCallback * cbp)
 { //TODO: do not explore dead-end boundaries
 	int ret = 0;
 	for(int x = pos.x - radious; x <= pos.x + radious; x++)
 	{
 		for(int y = pos.y - radious; y <= pos.y + radious; y++)
 		{
-			int3 npos = int3(x,y,pos.z);
-			if(cbp->isInTheMap(npos) && pos.dist2d(npos) - 0.5 < radious  && !cbp->isVisible(npos))
+			int3 npos = int3(x, y, pos.z);
+			if(cbp->isInTheMap(npos) && pos.dist2d(npos) - 0.5 < radious && !cbp->isVisible(npos))
 			{
-				if (!boundaryBetweenTwoPoints (pos, npos, cbp))
+				if(!boundaryBetweenTwoPoints(pos, npos, cbp))
 					ret++;
 			}
 		}
@@ -432,21 +435,21 @@ int howManyTilesWillBeDiscovered(const int3 &pos, int radious, CCallback * cbp)
 	return ret;
 }
 
-bool boundaryBetweenTwoPoints (int3 pos1, int3 pos2, CCallback * cbp) //determines if two points are separated by known barrier
+bool boundaryBetweenTwoPoints(int3 pos1, int3 pos2, CCallback * cbp) //determines if two points are separated by known barrier
 {
-	int xMin = std::min (pos1.x, pos2.x);
-	int xMax = std::max (pos1.x, pos2.x);
-	int yMin = std::min (pos1.y, pos2.y);
-	int yMax = std::max (pos1.y, pos2.y);
+	int xMin = std::min(pos1.x, pos2.x);
+	int xMax = std::max(pos1.x, pos2.x);
+	int yMin = std::min(pos1.y, pos2.y);
+	int yMax = std::max(pos1.y, pos2.y);
 
-	for (int x = xMin; x <= xMax; ++x)
+	for(int x = xMin; x <= xMax; ++x)
 	{
-		for (int y = yMin; y <= yMax; ++y)
+		for(int y = yMin; y <= yMax; ++y)
 		{
 			int3 tile = int3(x, y, pos1.z); //use only on same level, ofc
-			if (std::abs(pos1.dist2d(tile) - pos2.dist2d(tile)) < 1.5)
+			if(std::abs(pos1.dist2d(tile) - pos2.dist2d(tile)) < 1.5)
 			{
-				if (!(cbp->isVisible(tile) && cbp->getTile(tile)->blocked)) //if there's invisible or unblocked tile between, it's good
+				if(!(cbp->isVisible(tile) && cbp->getTile(tile)->blocked)) //if there's invisible or unblocked tile between, it's good
 					return false;
 			}
 		}
@@ -459,9 +462,9 @@ int howManyTilesWillBeDiscovered(int radious, int3 pos, crint3 dir)
 	return howManyTilesWillBeDiscovered(pos + dir, radious, cb.get());
 }
 
-void getVisibleNeighbours(const std::vector<int3> &tiles, std::vector<int3> &out)
+void getVisibleNeighbours(const std::vector<int3> & tiles, std::vector<int3> & out)
 {
-	for(const int3 &tile : tiles)
+	for(const int3 & tile : tiles)
 	{
 		foreach_neighbour(tile, [&](int3 neighbour)
 		{
@@ -471,7 +474,7 @@ void getVisibleNeighbours(const std::vector<int3> &tiles, std::vector<int3> &out
 	}
 }
 
-ui64 howManyReinforcementsCanGet(HeroPtr h, const CGTownInstance *t)
+ui64 howManyReinforcementsCanGet(HeroPtr h, const CGTownInstance * t)
 {
 	ui64 ret = 0;
 	int freeHeroSlots = GameConstants::ARMY_SIZE - h->stacksCount();
@@ -485,11 +488,11 @@ ui64 howManyReinforcementsCanGet(HeroPtr h, const CGTownInstance *t)
 		else
 			toMove.push_back(slot.second);
 	}
-	boost::sort(toMove, [](const CStackInstance *lhs, const CStackInstance *rhs)
+	boost::sort(toMove, [](const CStackInstance * lhs, const CStackInstance * rhs)
 	{
 		return lhs->getPower() < rhs->getPower();
 	});
-	for (auto & stack : boost::adaptors::reverse(toMove))
+	for(auto & stack : boost::adaptors::reverse(toMove))
 	{
 		if(freeHeroSlots)
 		{
@@ -507,12 +510,12 @@ bool compareHeroStrength(HeroPtr h1, HeroPtr h2)
 	return h1->getTotalStrength() < h2->getTotalStrength();
 }
 
-bool compareArmyStrength(const CArmedInstance *a1, const CArmedInstance *a2)
+bool compareArmyStrength(const CArmedInstance * a1, const CArmedInstance * a2)
 {
 	return a1->getArmyStrength() < a2->getArmyStrength();
 }
 
-bool compareArtifacts(const CArtifactInstance *a1, const CArtifactInstance *a2)
+bool compareArtifacts(const CArtifactInstance * a1, const CArtifactInstance * a2)
 {
 	auto art1 = a1->artType;
 	auto art2 = a2->artType;

+ 40 - 36
AI/VCAI/AIUtility.h

@@ -20,8 +20,8 @@
 
 class CCallback;
 
-typedef const int3& crint3;
-typedef const std::string& crstring;
+typedef const int3 & crint3;
+typedef const std::string & crstring;
 
 const int GOLD_MINE_PRODUCTION = 1000, WOOD_ORE_MINE_PRODUCTION = 2, RESOURCE_MINE_PRODUCTION = 1;
 const int ACTUAL_RESOURCE_COUNT = 7;
@@ -36,7 +36,7 @@ extern const int GOLD_RESERVE;
 
 struct HeroPtr
 {
-	const CGHeroInstance *h;
+	const CGHeroInstance * h;
 	ObjectInstanceID hid;
 
 public:
@@ -44,7 +44,7 @@ public:
 
 
 	HeroPtr();
-	HeroPtr(const CGHeroInstance *H);
+	HeroPtr(const CGHeroInstance * H);
 	~HeroPtr();
 
 	operator bool() const
@@ -52,15 +52,15 @@ public:
 		return validAndSet();
 	}
 
-	bool operator<(const HeroPtr &rhs) const;
-	const CGHeroInstance *operator->() const;
-	const CGHeroInstance *operator*() const; //not that consistent with -> but all interfaces use CGHeroInstance*, so it's convenient
+	bool operator<(const HeroPtr & rhs) const;
+	const CGHeroInstance * operator->() const;
+	const CGHeroInstance * operator*() const; //not that consistent with -> but all interfaces use CGHeroInstance*, so it's convenient
 
-	const CGHeroInstance *get(bool doWeExpectNull = false) const;
+	const CGHeroInstance * get(bool doWeExpectNull = false) const;
 	bool validAndSet() const;
 
 
-	template <typename Handler> void serialize(Handler &h, const int version)
+	template<typename Handler> void serialize(Handler & h, const int version)
 	{
 		h & this->h & hid & name;
 	}
@@ -80,16 +80,16 @@ struct ObjectIdRef
 {
 	ObjectInstanceID id;
 
-	const CGObjectInstance *operator->() const;
+	const CGObjectInstance * operator->() const;
 	operator const CGObjectInstance *() const;
 
 	ObjectIdRef(ObjectInstanceID _id);
-	ObjectIdRef(const CGObjectInstance *obj);
+	ObjectIdRef(const CGObjectInstance * obj);
 
-	bool operator<(const ObjectIdRef &rhs) const;
+	bool operator<(const ObjectIdRef & rhs) const;
 
 
-	template <typename Handler> void serialize(Handler &h, const int version)
+	template<typename Handler> void serialize(Handler & h, const int version)
 	{
 		h & id;
 	}
@@ -99,13 +99,14 @@ struct TimeCheck
 {
 	CStopWatch time;
 	std::string txt;
-	TimeCheck(crstring TXT) : txt(TXT)
+	TimeCheck(crstring TXT)
+		: txt(TXT)
 	{
 	}
 
 	~TimeCheck()
 	{
-		logAi->trace("Time of %s was %d ms.",txt,time.getDiff());
+		logAi->trace("Time of %s was %d ms.", txt, time.getDiff());
 	}
 };
 
@@ -113,7 +114,8 @@ struct TimeCheck
 struct AtScopeExit
 {
 	std::function<void()> foo;
-	AtScopeExit(const std::function<void()> &FOO) : foo(FOO)
+	AtScopeExit(const std::function<void()> & FOO)
+		: foo(FOO)
 	{}
 	~AtScopeExit()
 	{
@@ -128,45 +130,47 @@ private:
 };
 
 template<int id>
-bool objWithID(const CGObjectInstance *obj)
+bool objWithID(const CGObjectInstance * obj)
 {
 	return obj->ID == id;
 }
 
-std::string strFromInt3(int3 pos);//todo: remove
-void foreach_tile_pos(std::function<void(const int3& pos)> foo);
-void foreach_tile_pos(CCallback * cbp, std::function<void(CCallback * cbp, const int3& pos)> foo); // avoid costly retrieval of thread-specific pointer
-void foreach_neighbour(const int3 &pos, std::function<void(const int3& pos)> foo);
-void foreach_neighbour(CCallback * cbp, const int3 &pos, std::function<void(CCallback * cbp, const int3& pos)> foo); // avoid costly retrieval of thread-specific pointer
+std::string strFromInt3(int3 pos); //todo: remove
+void foreach_tile_pos(std::function<void(const int3 &pos)> foo);
+void foreach_tile_pos(CCallback * cbp, std::function<void(CCallback * cbp, const int3 &pos)> foo); // avoid costly retrieval of thread-specific pointer
+void foreach_neighbour(const int3 & pos, std::function<void(const int3 &pos)> foo);
+void foreach_neighbour(CCallback * cbp, const int3 & pos, std::function<void(CCallback * cbp, const int3 &pos)> foo); // avoid costly retrieval of thread-specific pointer
 
-int howManyTilesWillBeDiscovered(const int3 &pos, int radious, CCallback * cbp);
+int howManyTilesWillBeDiscovered(const int3 & pos, int radious, CCallback * cbp);
 int howManyTilesWillBeDiscovered(int radious, int3 pos, crint3 dir);
-void getVisibleNeighbours(const std::vector<int3> &tiles, std::vector<int3> &out);
+void getVisibleNeighbours(const std::vector<int3> & tiles, std::vector<int3> & out);
 
-bool canBeEmbarkmentPoint(const TerrainTile *t, bool fromWater);
+bool canBeEmbarkmentPoint(const TerrainTile * t, bool fromWater);
 bool isBlockedBorderGate(int3 tileToHit);
-bool isBlockVisitObj(const int3 &pos);
+bool isBlockVisitObj(const int3 & pos);
 
-bool isWeeklyRevisitable (const CGObjectInstance * obj);
-bool shouldVisit (HeroPtr h, const CGObjectInstance * obj);
+bool isWeeklyRevisitable(const CGObjectInstance * obj);
+bool shouldVisit(HeroPtr h, const CGObjectInstance * obj);
 
-ui64 evaluateDanger(const CGObjectInstance *obj);
-ui64 evaluateDanger(crint3 tile, const CGHeroInstance *visitor);
+ui64 evaluateDanger(const CGObjectInstance * obj);
+ui64 evaluateDanger(crint3 tile, const CGHeroInstance * visitor);
 bool isSafeToVisit(HeroPtr h, crint3 tile);
-bool boundaryBetweenTwoPoints (int3 pos1, int3 pos2, CCallback * cbp);
+bool boundaryBetweenTwoPoints(int3 pos1, int3 pos2, CCallback * cbp);
 
 bool compareMovement(HeroPtr lhs, HeroPtr rhs);
 bool compareHeroStrength(HeroPtr h1, HeroPtr h2);
-bool compareArmyStrength(const CArmedInstance *a1, const CArmedInstance *a2);
-bool compareArtifacts(const CArtifactInstance *a1, const CArtifactInstance *a2);
-ui64 howManyReinforcementsCanGet(HeroPtr h, const CGTownInstance *t);
+bool compareArmyStrength(const CArmedInstance * a1, const CArmedInstance * a2);
+bool compareArtifacts(const CArtifactInstance * a1, const CArtifactInstance * a2);
+ui64 howManyReinforcementsCanGet(HeroPtr h, const CGTownInstance * t);
 int3 whereToExplore(HeroPtr h);
 
 class CDistanceSorter
 {
 	const CGHeroInstance * hero;
+
 public:
-	CDistanceSorter(const CGHeroInstance * hero): hero(hero) {}
+	CDistanceSorter(const CGHeroInstance * hero)
+		: hero(hero) {}
 
-	bool operator ()(const CGObjectInstance *lhs, const CGObjectInstance *rhs);
+	bool operator()(const CGObjectInstance * lhs, const CGObjectInstance * rhs);
 };

+ 77 - 77
AI/VCAI/Fuzzy.cpp

@@ -31,7 +31,7 @@ class CGTownInstance;
 
 //using namespace Goals;
 
-FuzzyHelper *fh;
+FuzzyHelper * fh;
 
 extern boost::thread_specific_ptr<CCallback> cb;
 extern boost::thread_specific_ptr<VCAI> ai;
@@ -47,7 +47,7 @@ void engineBase::configure()
 	logAi->info(engine.toString());
 }
 
-void engineBase::addRule(const std::string &txt)
+void engineBase::addRule(const std::string & txt)
 {
 	rules.addRule(fl::Rule::parse(txt, &engine));
 }
@@ -58,7 +58,7 @@ struct armyStructure
 	ui32 maxSpeed;
 };
 
-armyStructure evaluateArmyStructure (const CArmedInstance * army)
+armyStructure evaluateArmyStructure(const CArmedInstance * army)
 {
 	ui64 totalStrenght = army->getArmyStrength();
 	double walkersStrenght = 0;
@@ -69,17 +69,17 @@ armyStructure evaluateArmyStructure (const CArmedInstance * army)
 	for(auto s : army->Slots())
 	{
 		bool walker = true;
-		if (s.second->type->hasBonusOfType(Bonus::SHOOTER))
+		if(s.second->type->hasBonusOfType(Bonus::SHOOTER))
 		{
 			shootersStrenght += s.second->getPower();
 			walker = false;
 		}
-		if (s.second->type->hasBonusOfType(Bonus::FLYING))
+		if(s.second->type->hasBonusOfType(Bonus::FLYING))
 		{
 			flyersStrenght += s.second->getPower();
 			walker = false;
 		}
-		if (walker)
+		if(walker)
 			walkersStrenght += s.second->getPower();
 
 		vstd::amax(maxSpeed, s.second->type->valOfBonuses(Bonus::STACKS_SPEED));
@@ -115,12 +115,12 @@ void FuzzyHelper::initTacticalAdvantage()
 		ta.enemyFlyers = new fl::InputVariable("EnemyFlyers");
 
 		//Tactical advantage calculation
-		std::vector<fl::InputVariable*> helper =
+		std::vector<fl::InputVariable *> helper =
 		{
 			ta.ourShooters, ta.ourWalkers, ta.ourFlyers, ta.enemyShooters, ta.enemyWalkers, ta.enemyFlyers
 		};
 
-		for (auto val : helper)
+		for(auto val : helper)
 		{
 			ta.engine.addInputVariable(val);
 			val->addTerm(new fl::Ramp("FEW", 0.6, 0.0));
@@ -133,7 +133,7 @@ void FuzzyHelper::initTacticalAdvantage()
 
 		helper = {ta.ourSpeed, ta.enemySpeed};
 
-		for (auto val : helper)
+		for(auto val : helper)
 		{
 			ta.engine.addInputVariable(val);
 			val->addTerm(new fl::Ramp("LOW", 6.5, 3));
@@ -145,14 +145,14 @@ void FuzzyHelper::initTacticalAdvantage()
 		ta.castleWalls = new fl::InputVariable("CastleWalls");
 		ta.engine.addInputVariable(ta.castleWalls);
 		{
-			fl::Rectangle* none = new fl::Rectangle("NONE", CGTownInstance::NONE, CGTownInstance::NONE + (CGTownInstance::FORT - CGTownInstance::NONE) * 0.5f);
+			fl::Rectangle * none = new fl::Rectangle("NONE", CGTownInstance::NONE, CGTownInstance::NONE + (CGTownInstance::FORT - CGTownInstance::NONE) * 0.5f);
 			ta.castleWalls->addTerm(none);
 
-			fl::Trapezoid* medium = new fl::Trapezoid("MEDIUM", (CGTownInstance::FORT - CGTownInstance::NONE) * 0.5f, CGTownInstance::FORT,
-				CGTownInstance::CITADEL, CGTownInstance::CITADEL + (CGTownInstance::CASTLE - CGTownInstance::CITADEL) * 0.5f);
+			fl::Trapezoid * medium = new fl::Trapezoid("MEDIUM", (CGTownInstance::FORT - CGTownInstance::NONE) * 0.5f, CGTownInstance::FORT,
+								   CGTownInstance::CITADEL, CGTownInstance::CITADEL + (CGTownInstance::CASTLE - CGTownInstance::CITADEL) * 0.5f);
 			ta.castleWalls->addTerm(medium);
 
-			fl::Ramp* high = new fl::Ramp("HIGH", CGTownInstance::CITADEL - 0.1, CGTownInstance::CASTLE);
+			fl::Ramp * high = new fl::Ramp("HIGH", CGTownInstance::CITADEL - 0.1, CGTownInstance::CASTLE);
 			ta.castleWalls->addTerm(high);
 
 			ta.castleWalls->setRange(CGTownInstance::NONE, CGTownInstance::CASTLE);
@@ -163,9 +163,9 @@ void FuzzyHelper::initTacticalAdvantage()
 		ta.bankPresent = new fl::InputVariable("Bank");
 		ta.engine.addInputVariable(ta.bankPresent);
 		{
-			fl::Rectangle* termFalse = new fl::Rectangle("FALSE", 0.0, 0.5f);
+			fl::Rectangle * termFalse = new fl::Rectangle("FALSE", 0.0, 0.5f);
 			ta.bankPresent->addTerm(termFalse);
-			fl::Rectangle* termTrue = new fl::Rectangle("TRUE", 0.5f, 1);
+			fl::Rectangle * termTrue = new fl::Rectangle("TRUE", 0.5f, 1);
 			ta.bankPresent->addTerm(termTrue);
 			ta.bankPresent->setRange(0, 1);
 		}
@@ -197,23 +197,23 @@ void FuzzyHelper::initTacticalAdvantage()
 		ta.addRule("if CastleWalls is MEDIUM and OurShooters is MANY and EnemyWalkers is MANY then Threat is LOW");
 
 	}
-	catch (fl::Exception & pe)
+	catch(fl::Exception & pe)
 	{
 		logAi->error("initTacticalAdvantage: %s", pe.getWhat());
 	}
 }
 
-ui64 FuzzyHelper::estimateBankDanger (const CBank * bank)
+ui64 FuzzyHelper::estimateBankDanger(const CBank * bank)
 {
 	//this one is not fuzzy anymore, just calculate weighted average
 
 	auto objectInfo = VLC->objtypeh->getHandlerFor(bank->ID, bank->subID)->getObjectInfo(bank->appearance);
 
-	CBankInfo * bankInfo = dynamic_cast<CBankInfo *> (objectInfo.get());
+	CBankInfo * bankInfo = dynamic_cast<CBankInfo *>(objectInfo.get());
 
 	ui64 totalStrength = 0;
 	ui8 totalChance = 0;
-	for (auto config : bankInfo->getPossibleGuards())
+	for(auto config : bankInfo->getPossibleGuards())
 	{
 		totalStrength += config.second.totalStrength * config.first;
 		totalChance += config.first;
@@ -222,7 +222,7 @@ ui64 FuzzyHelper::estimateBankDanger (const CBank * bank)
 
 }
 
-float FuzzyHelper::getTacticalAdvantage (const CArmedInstance *we, const CArmedInstance *enemy)
+float FuzzyHelper::getTacticalAdvantage(const CArmedInstance * we, const CArmedInstance * enemy)
 {
 	float output = 1;
 	try
@@ -240,14 +240,14 @@ float FuzzyHelper::getTacticalAdvantage (const CArmedInstance *we, const CArmedI
 		ta.enemyFlyers->setInputValue(enemyStructure.flyers);
 		ta.enemySpeed->setInputValue(enemyStructure.maxSpeed);
 
-		bool bank = dynamic_cast<const CBank*> (enemy);
-		if (bank)
+		bool bank = dynamic_cast<const CBank *>(enemy);
+		if(bank)
 			ta.bankPresent->setInputValue(1);
 		else
 			ta.bankPresent->setInputValue(0);
 
-		const CGTownInstance * fort = dynamic_cast<const CGTownInstance*> (enemy);
-		if (fort)
+		const CGTownInstance * fort = dynamic_cast<const CGTownInstance *>(enemy);
+		if(fort)
 		{
 			ta.castleWalls->setInputValue(fort->fortLevel());
 		}
@@ -258,18 +258,18 @@ float FuzzyHelper::getTacticalAdvantage (const CArmedInstance *we, const CArmedI
 		ta.engine.process();
 		output = ta.threat->getOutputValue();
 	}
-	catch (fl::Exception & fe)
+	catch(fl::Exception & fe)
 	{
-		logAi->error("getTacticalAdvantage: %s ",fe.getWhat());
+		logAi->error("getTacticalAdvantage: %s ", fe.getWhat());
 	}
 
-	if (output < 0 || (output != output))
+	if(output < 0 || (output != output))
 	{
-		fl::InputVariable* tab[] = {ta.bankPresent, ta.castleWalls, ta.ourWalkers, ta.ourShooters, ta.ourFlyers, ta.ourSpeed, ta.enemyWalkers, ta.enemyShooters, ta.enemyFlyers, ta.enemySpeed};
+		fl::InputVariable * tab[] = {ta.bankPresent, ta.castleWalls, ta.ourWalkers, ta.ourShooters, ta.ourFlyers, ta.ourSpeed, ta.enemyWalkers, ta.enemyShooters, ta.enemyFlyers, ta.enemySpeed};
 		std::string names[] = {"bankPresent", "castleWalls", "ourWalkers", "ourShooters", "ourFlyers", "ourSpeed", "enemyWalkers", "enemyShooters", "enemyFlyers", "enemySpeed" };
 		std::stringstream log("Warning! Fuzzy engine doesn't cover this set of parameters: ");
 
-		for (int i = 0; i < boost::size(tab); i++)
+		for(int i = 0; i < boost::size(tab); i++)
 			log << names[i] << ": " << tab[i]->getInputValue() << " ";
 		logAi->error(log.str());
 		assert(false);
@@ -296,39 +296,39 @@ FuzzyHelper::TacticalAdvantage::~TacticalAdvantage()
 
 //std::shared_ptr<AbstractGoal> chooseSolution (std::vector<std::shared_ptr<AbstractGoal>> & vec)
 
-Goals::TSubgoal FuzzyHelper::chooseSolution (Goals::TGoalVec vec)
+Goals::TSubgoal FuzzyHelper::chooseSolution(Goals::TGoalVec vec)
 {
-	if (vec.empty()) //no possibilities found
+	if(vec.empty()) //no possibilities found
 		return sptr(Goals::Invalid());
 
 	ai->cachedSectorMaps.clear();
 
 	//a trick to switch between heroes less often - calculatePaths is costly
 	auto sortByHeroes = [](const Goals::TSubgoal & lhs, const Goals::TSubgoal & rhs) -> bool
-	{
-		return lhs->hero.h < rhs->hero.h;
-	};
-	boost::sort (vec, sortByHeroes);
+		{
+			return lhs->hero.h < rhs->hero.h;
+		};
+	boost::sort(vec, sortByHeroes);
 
-	for (auto g : vec)
+	for(auto g : vec)
 	{
 		setPriority(g);
 	}
 
 	auto compareGoals = [](const Goals::TSubgoal & lhs, const Goals::TSubgoal & rhs) -> bool
-	{
-		return lhs->priority < rhs->priority;
-	};
-	boost::sort (vec, compareGoals);
+		{
+			return lhs->priority < rhs->priority;
+		};
+	boost::sort(vec, compareGoals);
 
 	return vec.back();
 }
 
-float FuzzyHelper::evaluate (Goals::Explore & g)
+float FuzzyHelper::evaluate(Goals::Explore & g)
 {
 	return 1;
 }
-float FuzzyHelper::evaluate (Goals::RecruitHero & g)
+float FuzzyHelper::evaluate(Goals::RecruitHero & g)
 {
 	return 1; //just try to recruit hero as one of options
 }
@@ -354,8 +354,8 @@ void FuzzyHelper::initVisitTile()
 		vt.value->setMinimum(0);
 		vt.value->setMaximum(5);
 
-		std::vector<fl::InputVariable*> helper = {vt.strengthRatio, vt.heroStrength, vt.turnDistance, vt.missionImportance, vt.estimatedReward};
-		for (auto val : helper)
+		std::vector<fl::InputVariable *> helper = {vt.strengthRatio, vt.heroStrength, vt.turnDistance, vt.missionImportance, vt.estimatedReward};
+		for(auto val : helper)
 		{
 			vt.engine.addInputVariable(val);
 		}
@@ -363,7 +363,7 @@ void FuzzyHelper::initVisitTile()
 
 		vt.strengthRatio->addTerm(new fl::Ramp("LOW", SAFE_ATTACK_CONSTANT, 0));
 		vt.strengthRatio->addTerm(new fl::Ramp("HIGH", SAFE_ATTACK_CONSTANT, SAFE_ATTACK_CONSTANT * 3));
-		vt.strengthRatio->setRange(0, SAFE_ATTACK_CONSTANT * 3 );
+		vt.strengthRatio->setRange(0, SAFE_ATTACK_CONSTANT * 3);
 
 		//strength compared to our main hero
 		vt.heroStrength->addTerm(new fl::Ramp("LOW", 0.2, 0));
@@ -386,11 +386,11 @@ void FuzzyHelper::initVisitTile()
 		vt.estimatedReward->setRange(0.0, 5.0);
 
 		//an issue: in 99% cases this outputs center of mass (2.5) regardless of actual input :/
-		 //should be same as "mission Importance" to keep consistency
+		//should be same as "mission Importance" to keep consistency
 		vt.value->addTerm(new fl::Ramp("LOW", 2.5, 0));
 		vt.value->addTerm(new fl::Triangle("MEDIUM", 2, 3)); //can't be center of mass :/
 		vt.value->addTerm(new fl::Ramp("HIGH", 2.5, 5));
-		vt.value->setRange(0.0,5.0);
+		vt.value->setRange(0.0, 5.0);
 
 		//use unarmed scouts if possible
 		vt.addRule("if strengthRatio is HIGH and heroStrength is LOW then Value is very HIGH");
@@ -415,38 +415,38 @@ void FuzzyHelper::initVisitTile()
 		vt.addRule("if estimatedReward is HIGH then Value is very HIGH");
 		vt.addRule("if estimatedReward is LOW then Value is somewhat LOW");
 	}
-	catch (fl::Exception & fe)
+	catch(fl::Exception & fe)
 	{
-		logAi->error("visitTile: %s",fe.getWhat());
+		logAi->error("visitTile: %s", fe.getWhat());
 	}
 }
 
-float FuzzyHelper::evaluate (Goals::VisitTile & g)
+float FuzzyHelper::evaluate(Goals::VisitTile & g)
 {
 	//we assume that hero is already set and we want to choose most suitable one for the mission
-	if (!g.hero)
+	if(!g.hero)
 		return 0;
 
 	//assert(cb->isInTheMap(g.tile));
 	float turns = 0;
 	float distance = CPathfinderHelper::getMovementCost(g.hero.h, g.tile);
-	if (!distance) //we stand on that tile
+	if(!distance) //we stand on that tile
 		turns = 0;
 	else
 	{
-		if (distance < g.hero->movement) //we can move there within one turn
+		if(distance < g.hero->movement) //we can move there within one turn
 			turns = (fl::scalar)distance / g.hero->movement;
 		else
 			turns = 1 + (fl::scalar)(distance - g.hero->movement) / g.hero->maxMovePoints(true); //bool on land?
 	}
 
 	float missionImportance = 0;
-	if (vstd::contains(ai->lockedHeroes, g.hero))
+	if(vstd::contains(ai->lockedHeroes, g.hero))
 		missionImportance = ai->lockedHeroes[g.hero]->priority;
 
 	float strengthRatio = 10.0f; //we are much stronger than enemy
-	ui64 danger = evaluateDanger (g.tile, g.hero.h);
-	if (danger)
+	ui64 danger = evaluateDanger(g.tile, g.hero.h);
+	if(danger)
 		strengthRatio = (fl::scalar)g.hero.h->getTotalStrength() / danger;
 
 	float tilePriority = 0;
@@ -457,7 +457,7 @@ float FuzzyHelper::evaluate (Goals::VisitTile & g)
 		vt.estimatedReward->setEnabled(true);
 		tilePriority = 5;
 	}
-		
+
 	try
 	{
 		vt.strengthRatio->setInputValue(strengthRatio);
@@ -470,48 +470,48 @@ float FuzzyHelper::evaluate (Goals::VisitTile & g)
 		//engine.process(VISIT_TILE); //TODO: Process only Visit_Tile
 		g.priority = vt.value->getOutputValue();
 	}
-	catch (fl::Exception & fe)
+	catch(fl::Exception & fe)
 	{
-		logAi->error("evaluate VisitTile: %s",fe.getWhat());
+		logAi->error("evaluate VisitTile: %s", fe.getWhat());
 	}
-	assert (g.priority >= 0);
+	assert(g.priority >= 0);
 	return g.priority;
 }
-float FuzzyHelper::evaluate (Goals::VisitHero & g)
+float FuzzyHelper::evaluate(Goals::VisitHero & g)
 {
 	auto obj = cb->getObj(ObjectInstanceID(g.objid)); //we assume for now that these goals are similar
-	if (!obj)
+	if(!obj)
 		return -100; //hero died in the meantime
 	//TODO: consider direct copy (constructor?)
 	g.setpriority(Goals::VisitTile(obj->visitablePos()).sethero(g.hero).setisAbstract(g.isAbstract).accept(this));
 	return g.priority;
 }
-float FuzzyHelper::evaluate (Goals::GatherArmy & g)
+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 ratio =  g.value / std::max(g.value - army, 2000.0f); //2000 is about the value of hero recruited from tavern
+	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
 }
 
-float FuzzyHelper::evaluate (Goals::ClearWayTo & g)
+float FuzzyHelper::evaluate(Goals::ClearWayTo & g)
 {
-	if (!g.hero.h)
+	if(!g.hero.h)
 		throw cannotFulfillGoalException("ClearWayTo called without hero!");
 
 	int3 t = ai->getCachedSectorMap(g.hero)->firstTileToGet(g.hero, g.tile);
 
-	if (t.valid())
+	if(t.valid())
 	{
-		if (isSafeToVisit(g.hero, t))
+		if(isSafeToVisit(g.hero, t))
 		{
 			g.setpriority(Goals::VisitTile(g.tile).sethero(g.hero).setisAbstract(g.isAbstract).accept(this));
 		}
 		else
 		{
-			g.setpriority (Goals::GatherArmy(evaluateDanger(t, g.hero.h)*SAFE_ATTACK_CONSTANT).
-				sethero(g.hero).setisAbstract(true).accept(this));
+			g.setpriority(Goals::GatherArmy(evaluateDanger(t, g.hero.h) * SAFE_ATTACK_CONSTANT).
+				      sethero(g.hero).setisAbstract(true).accept(this));
 		}
 		return g.priority;
 	}
@@ -520,32 +520,32 @@ float FuzzyHelper::evaluate (Goals::ClearWayTo & g)
 
 }
 
-float FuzzyHelper::evaluate (Goals::BuildThis & g)
+float FuzzyHelper::evaluate(Goals::BuildThis & g)
 {
 	return 1;
 }
-float FuzzyHelper::evaluate (Goals::DigAtTile & g)
+float FuzzyHelper::evaluate(Goals::DigAtTile & g)
 {
 	return 0;
 }
-float FuzzyHelper::evaluate (Goals::CollectRes & g)
+float FuzzyHelper::evaluate(Goals::CollectRes & g)
 {
 	return 0;
 }
-float FuzzyHelper::evaluate (Goals::Build & g)
+float FuzzyHelper::evaluate(Goals::Build & g)
 {
 	return 0;
 }
-float FuzzyHelper::evaluate (Goals::Invalid & g)
+float FuzzyHelper::evaluate(Goals::Invalid & g)
 {
 	return -1e10;
 }
-float FuzzyHelper::evaluate (Goals::AbstractGoal & g)
+float FuzzyHelper::evaluate(Goals::AbstractGoal & g)
 {
 	logAi->warn("Cannot evaluate goal %s", g.name());
 	return g.priority;
 }
-void FuzzyHelper::setPriority (Goals::TSubgoal & g)
+void FuzzyHelper::setPriority(Goals::TSubgoal & g)
 {
 	g->setpriority(g->accept(this)); //this enforces returned value is set
 }

+ 25 - 22
AI/VCAI/Fuzzy.h

@@ -24,7 +24,7 @@ public:
 
 	engineBase();
 	void configure();
-	void addRule(const std::string &txt);
+	void addRule(const std::string & txt);
 };
 
 class FuzzyHelper
@@ -33,7 +33,7 @@ class FuzzyHelper
 
 	class TacticalAdvantage : public engineBase
 	{
-	public:
+public:
 		fl::InputVariable * ourWalkers, * ourShooters, * ourFlyers, * enemyWalkers, * enemyShooters, * enemyFlyers;
 		fl::InputVariable * ourSpeed, * enemySpeed;
 		fl::InputVariable * bankPresent;
@@ -44,7 +44,7 @@ class FuzzyHelper
 
 	class EvalVisitTile : public engineBase
 	{
-	public:
+public:
 		fl::InputVariable * strengthRatio;
 		fl::InputVariable * heroStrength;
 		fl::InputVariable * turnDistance;
@@ -55,33 +55,36 @@ class FuzzyHelper
 		~EvalVisitTile();
 	} vt;
 
-	
-
 public:
-	enum RuleBlocks {BANK_DANGER, TACTICAL_ADVANTAGE, VISIT_TILE};
+	enum RuleBlocks
+	{
+		BANK_DANGER,
+		TACTICAL_ADVANTAGE,
+		VISIT_TILE
+	};
 	//blocks should be initialized in this order, which may be confusing :/
 
 	FuzzyHelper();
 	void initTacticalAdvantage();
 	void initVisitTile();
 
-	float evaluate (Goals::Explore & g);
-	float evaluate (Goals::RecruitHero & g);
-	float evaluate (Goals::VisitTile & g);
-	float evaluate (Goals::VisitHero & g);
-	float evaluate (Goals::BuildThis & g);
-	float evaluate (Goals::DigAtTile & g);
-	float evaluate (Goals::CollectRes & g);
-	float evaluate (Goals::Build & g);
-	float evaluate (Goals::GatherArmy & g);
-	float evaluate (Goals::ClearWayTo & g);
-	float evaluate (Goals::Invalid & g);
-	float evaluate (Goals::AbstractGoal & g);
-	void setPriority (Goals::TSubgoal & g);
+	float evaluate(Goals::Explore & g);
+	float evaluate(Goals::RecruitHero & g);
+	float evaluate(Goals::VisitTile & g);
+	float evaluate(Goals::VisitHero & g);
+	float evaluate(Goals::BuildThis & g);
+	float evaluate(Goals::DigAtTile & g);
+	float evaluate(Goals::CollectRes & g);
+	float evaluate(Goals::Build & g);
+	float evaluate(Goals::GatherArmy & g);
+	float evaluate(Goals::ClearWayTo & g);
+	float evaluate(Goals::Invalid & g);
+	float evaluate(Goals::AbstractGoal & g);
+	void setPriority(Goals::TSubgoal & g);
 
-	ui64 estimateBankDanger (const CBank * bank);
-	float getTacticalAdvantage (const CArmedInstance *we, const CArmedInstance *enemy); //returns factor how many times enemy is stronger than us
+	ui64 estimateBankDanger(const CBank * bank);
+	float getTacticalAdvantage(const CArmedInstance * we, const CArmedInstance * enemy); //returns factor how many times enemy is stronger than us
 
-	Goals::TSubgoal chooseSolution (Goals::TGoalVec vec);
+	Goals::TSubgoal chooseSolution(Goals::TGoalVec vec);
 	//std::shared_ptr<AbstractGoal> chooseSolution (std::vector<std::shared_ptr<AbstractGoal>> & vec);
 };

File diff suppressed because it is too large
+ 315 - 315
AI/VCAI/Goals.cpp


+ 174 - 98
AI/VCAI/Goals.h

@@ -21,64 +21,89 @@ class FuzzyHelper;
 
 namespace Goals
 {
-	class AbstractGoal;
-	class VisitTile;
-	typedef std::shared_ptr<Goals::AbstractGoal> TSubgoal;
-	typedef std::vector<TSubgoal> TGoalVec;
+class AbstractGoal;
+class VisitTile;
+typedef std::shared_ptr<Goals::AbstractGoal> TSubgoal;
+typedef std::vector<TSubgoal> TGoalVec;
 
-	enum EGoals
+enum EGoals
 {
 	INVALID = -1,
-	WIN, DO_NOT_LOSE, CONQUER, BUILD, //build needs to get a real reasoning
-	EXPLORE, GATHER_ARMY, BOOST_HERO,
+	WIN,
+	DO_NOT_LOSE,
+	CONQUER,
+	BUILD,
+	//build needs to get a real reasoning
+	EXPLORE,
+	GATHER_ARMY,
+	BOOST_HERO,
 	RECRUIT_HERO,
-	BUILD_STRUCTURE, //if hero set, then in visited town
+	BUILD_STRUCTURE,
+	//if hero set, then in visited town
 	COLLECT_RES,
-	GATHER_TROOPS, // val of creatures with objid
+	GATHER_TROOPS,
+	// val of creatures with objid
 
 	OBJECT_GOALS_BEGIN,
-	GET_OBJ, //visit or defeat or collect the object
-	FIND_OBJ, //find and visit any obj with objid + resid //TODO: consider universal subid for various types (aid, bid)
-	VISIT_HERO, //heroes can move around - set goal abstract and track hero every turn
+	GET_OBJ,
+	//visit or defeat or collect the object
+	FIND_OBJ,
+	//find and visit any obj with objid + resid //TODO: consider universal subid for various types (aid, bid)
+	VISIT_HERO,
+	//heroes can move around - set goal abstract and track hero every turn
 
 	GET_ART_TYPE,
-
 	//BUILD_STRUCTURE,
 	ISSUE_COMMAND,
-
-	VISIT_TILE, //tile, in conjunction with hero elementar; assumes tile is reachable
+	VISIT_TILE,
+	//tile, in conjunction with hero elementar; assumes tile is reachable
 	CLEAR_WAY_TO,
 	DIG_AT_TILE //elementar with hero on tile
 };
 
-	//method chaining + clone pattern
-#define VSETTER(type, field) virtual AbstractGoal & set ## field(const type &rhs) {field = rhs; return *this;};
-#define OSETTER(type, field) CGoal<T> & set ## field(const type &rhs) override { field = rhs; return *this; };
+//method chaining + clone pattern
+#define VSETTER(type, field) virtual AbstractGoal &set ## field(const type &rhs) {field = rhs; return *this;};
+#define OSETTER(type, field) CGoal<T>&set ## field(const type &rhs) override { field = rhs; return *this; };
 
 #if 0
 	#define SETTER
 #endif // _DEBUG
 
-enum {LOW_PR = -1};
+enum
+{
+	LOW_PR = -1
+};
 
 TSubgoal sptr(const AbstractGoal & tmp);
 
 class AbstractGoal
 {
 public:
-	bool isElementar; VSETTER(bool, isElementar)
-	bool isAbstract; VSETTER(bool, isAbstract)
-	float priority; VSETTER(float, priority)
-	int value; VSETTER(int, value)
-	int resID; VSETTER(int, resID)
-	int objid; VSETTER(int, objid)
-	int aid; VSETTER(int, aid)
-	int3 tile; VSETTER(int3, tile)
-	HeroPtr hero; VSETTER(HeroPtr, hero)
-	const CGTownInstance *town; VSETTER(CGTownInstance *, town)
-	int bid; VSETTER(int, bid)
-
-	AbstractGoal (EGoals goal = INVALID) : goalType (goal)
+	bool isElementar;
+	VSETTER(bool, isElementar)
+	bool isAbstract;
+	VSETTER(bool, isAbstract)
+	float priority;
+	VSETTER(float, priority)
+	int value;
+	VSETTER(int, value)
+	int resID;
+	VSETTER(int, resID)
+	int objid;
+	VSETTER(int, objid)
+	int aid;
+	VSETTER(int, aid)
+	int3 tile;
+	VSETTER(int3, tile)
+	HeroPtr hero;
+	VSETTER(HeroPtr, hero)
+	const CGTownInstance * town;
+	VSETTER(CGTownInstance *, town)
+	int bid;
+	VSETTER(int, bid)
+
+	AbstractGoal(EGoals goal = INVALID)
+		: goalType(goal)
 	{
 		priority = 0;
 		isElementar = false;
@@ -93,7 +118,7 @@ public:
 	}
 	virtual ~AbstractGoal(){};
 	//FIXME: abstract goal should be abstract, but serializer fails to instantiate subgoals in such case
-	virtual AbstractGoal * clone() const {return const_cast<AbstractGoal*>(this);};
+	virtual AbstractGoal * clone() const {return const_cast<AbstractGoal *>(this);};
 	virtual TGoalVec getAllPossibleSubgoals() {TGoalVec vec; return vec;};
 	virtual TSubgoal whatToDoToAchieve() {return sptr(AbstractGoal());};
 
@@ -104,32 +129,32 @@ public:
 
 	bool invalid() const;
 
-	static TSubgoal goVisitOrLookFor(const CGObjectInstance *obj); //if obj is nullptr, then we'll explore
+	static TSubgoal goVisitOrLookFor(const CGObjectInstance * obj); //if obj is nullptr, then we'll explore
 	static TSubgoal lookForArtSmart(int aid); //checks non-standard ways of obtaining art (merchants, quests, etc.)
 	static TSubgoal tryRecruitHero();
 
 	///Visitor pattern
 	//TODO: make accept work for std::shared_ptr... somehow
-	virtual void accept (VCAI * ai); //unhandled goal will report standard error
-	virtual float accept (FuzzyHelper * f);
+	virtual void accept(VCAI * ai); //unhandled goal will report standard error
+	virtual float accept(FuzzyHelper * f);
 
-	virtual bool operator== (AbstractGoal &g);
-	virtual bool fulfillsMe (Goals::TSubgoal goal) //TODO: multimethod instead of type check
+	virtual bool operator==(AbstractGoal & g);
+	virtual bool fulfillsMe(Goals::TSubgoal goal) //TODO: multimethod instead of type check
 	{
 		return false;
 	}
 
-	template <typename Handler> void serialize(Handler &h, const int version)
+	template<typename Handler> void serialize(Handler & h, const int version)
 	{
 		h & goalType & isElementar & isAbstract & priority;
 		h & value & resID & objid & aid & tile & hero & town & bid;
 	}
 };
 
-template <typename T> class CGoal : public AbstractGoal
+template<typename T> class CGoal : public AbstractGoal
 {
 public:
-	CGoal<T> (EGoals goal = INVALID) : AbstractGoal (goal)
+	CGoal<T>(EGoals goal = INVALID) : AbstractGoal(goal)
 	{
 		priority = 0;
 		isElementar = false;
@@ -154,12 +179,12 @@ public:
 	OSETTER(CGTownInstance *, town)
 	OSETTER(int, bid)
 
-	void accept (VCAI * ai) override;
-	float accept (FuzzyHelper * f) override;
+	void accept(VCAI * ai) override;
+	float accept(FuzzyHelper * f) override;
 
 	CGoal<T> * clone() const override
 	{
-		return new T(static_cast<T const&>(*this)); //casting enforces template instantiation
+		return new T(static_cast<T const &>(*this)); //casting enforces template instantiation
 	}
 	TSubgoal iAmElementar()
 	{
@@ -168,9 +193,9 @@ public:
 		ptr.reset(clone());
 		return ptr;
 	}
-	template <typename Handler> void serialize(Handler &h, const int version)
+	template<typename Handler> void serialize(Handler & h, const int version)
 	{
-		h & static_cast<AbstractGoal&> (*this);
+		h & static_cast<AbstractGoal &>(*this);
 		//h & goalType & isElementar & isAbstract & priority;
 		//h & value & resID & objid & aid & tile & hero & town & bid;
 	}
@@ -178,187 +203,238 @@ public:
 
 class Invalid : public CGoal<Invalid>
 {
-	public:
-	Invalid() : CGoal (Goals::INVALID) {priority = -1e10;};
+public:
+	Invalid()
+		: CGoal(Goals::INVALID) {priority = -1e10;};
 	TGoalVec getAllPossibleSubgoals() override {return TGoalVec();};
 	TSubgoal whatToDoToAchieve() override;
 };
+
 class Win : public CGoal<Win>
 {
-	public:
-	Win() : CGoal (Goals::WIN) {priority = 100;};
+public:
+	Win()
+		: CGoal(Goals::WIN) {priority = 100;};
 	TGoalVec getAllPossibleSubgoals() override {return TGoalVec();};
 	TSubgoal whatToDoToAchieve() override;
 };
+
 class NotLose : public CGoal<NotLose>
 {
-	public:
-	NotLose() : CGoal (Goals::DO_NOT_LOSE) {priority = 100;};
+public:
+	NotLose()
+		: CGoal(Goals::DO_NOT_LOSE) {priority = 100;};
 	TGoalVec getAllPossibleSubgoals() override {return TGoalVec();};
 	//TSubgoal whatToDoToAchieve() override;
 };
+
 class Conquer : public CGoal<Conquer>
 {
-	public:
-	Conquer() : CGoal (Goals::CONQUER) {priority = 10;};
+public:
+	Conquer()
+		: CGoal(Goals::CONQUER) {priority = 10;};
 	TGoalVec getAllPossibleSubgoals() override;
 	TSubgoal whatToDoToAchieve() override;
 };
+
 class Build : public CGoal<Build>
 {
-	public:
-	Build() : CGoal (Goals::BUILD) {priority = 1;};
+public:
+	Build()
+		: CGoal(Goals::BUILD) {priority = 1;};
 	TGoalVec getAllPossibleSubgoals() override {return TGoalVec();};
 	TSubgoal whatToDoToAchieve() override;
 };
+
 class Explore : public CGoal<Explore>
 {
-	public:
-	Explore() : CGoal (Goals::EXPLORE){priority = 1;};
-	Explore(HeroPtr h) : CGoal (Goals::EXPLORE){hero = h; priority = 1;};
+public:
+	Explore()
+		: CGoal(Goals::EXPLORE){priority = 1;};
+	Explore(HeroPtr h)
+		: CGoal(Goals::EXPLORE){hero = h; priority = 1;};
 	TGoalVec getAllPossibleSubgoals() override;
 	TSubgoal whatToDoToAchieve() override;
 	std::string completeMessage() const override;
-	bool fulfillsMe (TSubgoal goal) override;
+	bool fulfillsMe(TSubgoal goal) override;
 };
+
 class GatherArmy : public CGoal<GatherArmy>
 {
 public:
-	GatherArmy() : CGoal (Goals::GATHER_ARMY){};
+	GatherArmy()
+		: CGoal(Goals::GATHER_ARMY){};
 
-	GatherArmy(int val) : CGoal (Goals::GATHER_ARMY){value = val; priority = 2.5;};
+	GatherArmy(int val)
+		: CGoal(Goals::GATHER_ARMY){value = val; priority = 2.5;};
 	TGoalVec getAllPossibleSubgoals() override;
 	TSubgoal whatToDoToAchieve() override;
 	std::string completeMessage() const override;
 };
+
 class BoostHero : public CGoal<BoostHero>
 {
-	public:
-	BoostHero() : CGoal (Goals::INVALID){priority = -1e10;}; //TODO
+public:
+	BoostHero()
+		: CGoal(Goals::INVALID){priority = -1e10;}; //TODO
 	TGoalVec getAllPossibleSubgoals() override {return TGoalVec();};
 	//TSubgoal whatToDoToAchieve() override {return sptr(Invalid());};
 };
+
 class RecruitHero : public CGoal<RecruitHero>
 {
-	public:
-	RecruitHero() : CGoal (Goals::RECRUIT_HERO){priority = 1;};
+public:
+	RecruitHero()
+		: CGoal(Goals::RECRUIT_HERO){priority = 1;};
 	TGoalVec getAllPossibleSubgoals() override {return TGoalVec();};
 	TSubgoal whatToDoToAchieve() override;
 };
+
 class BuildThis : public CGoal<BuildThis>
 {
 public:
-	BuildThis() : CGoal (Goals::BUILD_STRUCTURE){}; //FIXME: should be not allowed (private)
+	BuildThis()
+		: CGoal(Goals::BUILD_STRUCTURE){}; //FIXME: should be not allowed (private)
 
-	BuildThis(BuildingID Bid, const CGTownInstance *tid) : CGoal (Goals::BUILD_STRUCTURE) {bid = Bid; town = tid; priority =  5;};
-	BuildThis(BuildingID Bid) : CGoal (Goals::BUILD_STRUCTURE) {bid = Bid; priority = 5;};
+	BuildThis(BuildingID Bid, const CGTownInstance * tid)
+		: CGoal(Goals::BUILD_STRUCTURE) {bid = Bid; town = tid; priority = 5;};
+	BuildThis(BuildingID Bid)
+		: CGoal(Goals::BUILD_STRUCTURE) {bid = Bid; priority = 5;};
 	TGoalVec getAllPossibleSubgoals() override {return TGoalVec();};
 	TSubgoal whatToDoToAchieve() override;
 };
+
 class CollectRes : public CGoal<CollectRes>
 {
-public:	
-	CollectRes() : CGoal (Goals::COLLECT_RES){};
+public:
+	CollectRes()
+		: CGoal(Goals::COLLECT_RES){};
 
-	CollectRes(int rid, int val) : CGoal (Goals::COLLECT_RES) {resID = rid; value = val; priority = 2;};
+	CollectRes(int rid, int val)
+		: CGoal(Goals::COLLECT_RES) {resID = rid; value = val; priority = 2;};
 	TGoalVec getAllPossibleSubgoals() override {return TGoalVec();};
 	TSubgoal whatToDoToAchieve() override;
 };
+
 class GatherTroops : public CGoal<GatherTroops>
 {
 public:
-	GatherTroops() : CGoal (Goals::GATHER_TROOPS){priority = 2;};
+	GatherTroops()
+		: CGoal(Goals::GATHER_TROOPS){priority = 2;};
 
-	GatherTroops(int type, int val) : CGoal (Goals::GATHER_TROOPS){objid = type; value = val; priority = 2;};
+	GatherTroops(int type, int val)
+		: CGoal(Goals::GATHER_TROOPS){objid = type; value = val; priority = 2;};
 	TGoalVec getAllPossibleSubgoals() override {return TGoalVec();};
 	TSubgoal whatToDoToAchieve() override;
 };
+
 class GetObj : public CGoal<GetObj>
 {
 public:
 	GetObj() {}; // empty constructor not allowed
 
-	GetObj(int Objid) : CGoal(Goals::GET_OBJ) {objid = Objid; priority = 3;};
+	GetObj(int Objid)
+		: CGoal(Goals::GET_OBJ) {objid = Objid; priority = 3;};
 	TGoalVec getAllPossibleSubgoals() override {return TGoalVec();};
 	TSubgoal whatToDoToAchieve() override;
-	bool operator== (GetObj &g) {return g.objid ==  objid;}
-	bool fulfillsMe (TSubgoal goal) override;
+	bool operator==(GetObj & g) {return g.objid == objid;}
+	bool fulfillsMe(TSubgoal goal) override;
 	std::string completeMessage() const override;
 };
+
 class FindObj : public CGoal<FindObj>
 {
 public:
 	FindObj() {}; // empty constructor not allowed
 
-	FindObj(int ID) : CGoal(Goals::FIND_OBJ) {objid = ID; priority = 1;};
-	FindObj(int ID, int subID) : CGoal(Goals::FIND_OBJ) {objid = ID; resID = subID; priority = 1;};
+	FindObj(int ID)
+		: CGoal(Goals::FIND_OBJ) {objid = ID; priority = 1;};
+	FindObj(int ID, int subID)
+		: CGoal(Goals::FIND_OBJ) {objid = ID; resID = subID; priority = 1;};
 	TGoalVec getAllPossibleSubgoals() override {return TGoalVec();};
 	TSubgoal whatToDoToAchieve() override;
 };
+
 class VisitHero : public CGoal<VisitHero>
 {
 public:
-	VisitHero() : CGoal (Goals::VISIT_HERO){};
+	VisitHero()
+		: CGoal(Goals::VISIT_HERO){};
 
-	VisitHero(int hid) : CGoal (Goals::VISIT_HERO){objid = hid; priority = 4;};
+	VisitHero(int hid)
+		: CGoal(Goals::VISIT_HERO){objid = hid; priority = 4;};
 	TGoalVec getAllPossibleSubgoals() override {return TGoalVec();};
 	TSubgoal whatToDoToAchieve() override;
-	bool operator== (VisitHero &g) { return g.goalType == goalType && g.objid == objid; }
-	bool fulfillsMe (TSubgoal goal) override;
+	bool operator==(VisitHero & g) { return g.goalType == goalType && g.objid == objid; }
+	bool fulfillsMe(TSubgoal goal) override;
 	std::string completeMessage() const override;
 };
+
 class GetArtOfType : public CGoal<GetArtOfType>
 {
 public:
-	GetArtOfType() : CGoal (Goals::GET_ART_TYPE){};
+	GetArtOfType()
+		: CGoal(Goals::GET_ART_TYPE){};
 
-	GetArtOfType(int type) : CGoal (Goals::GET_ART_TYPE){aid = type; priority = 2;};
+	GetArtOfType(int type)
+		: CGoal(Goals::GET_ART_TYPE){aid = type; priority = 2;};
 	TGoalVec getAllPossibleSubgoals() override {return TGoalVec();};
 	TSubgoal whatToDoToAchieve() override;
 };
+
 class VisitTile : public CGoal<VisitTile>
 	//tile, in conjunction with hero elementar; assumes tile is reachable
 {
 public:
 	VisitTile() {}; // empty constructor not allowed
 
-	VisitTile(int3 Tile) : CGoal (Goals::VISIT_TILE) {tile = Tile; priority = 5;};
+	VisitTile(int3 Tile)
+		: CGoal(Goals::VISIT_TILE) {tile = Tile; priority = 5;};
 	TGoalVec getAllPossibleSubgoals() override;
 	TSubgoal whatToDoToAchieve() override;
-	bool operator== (VisitTile &g) { return g.goalType == goalType && g.tile == tile; }
+	bool operator==(VisitTile & g) { return g.goalType == goalType && g.tile == tile; }
 	std::string completeMessage() const override;
-}; 
+};
+
 class ClearWayTo : public CGoal<ClearWayTo>
 {
 public:
-	ClearWayTo() : CGoal (Goals::CLEAR_WAY_TO){};
+	ClearWayTo()
+		: CGoal(Goals::CLEAR_WAY_TO){};
 
-	ClearWayTo(int3 Tile) : CGoal (Goals::CLEAR_WAY_TO) {tile = Tile; priority = 5;};
-	ClearWayTo(int3 Tile, HeroPtr h) : CGoal (Goals::CLEAR_WAY_TO) {tile = Tile; hero = h; priority = 5;};
+	ClearWayTo(int3 Tile)
+		: CGoal(Goals::CLEAR_WAY_TO) {tile = Tile; priority = 5;};
+	ClearWayTo(int3 Tile, HeroPtr h)
+		: CGoal(Goals::CLEAR_WAY_TO) {tile = Tile; hero = h; priority = 5;};
 	TGoalVec getAllPossibleSubgoals() override;
 	TSubgoal whatToDoToAchieve() override;
-	bool operator== (ClearWayTo &g) { return g.goalType == goalType && g.tile == tile; }
+	bool operator==(ClearWayTo & g) { return g.goalType == goalType && g.tile == tile; }
 };
+
 class DigAtTile : public CGoal<DigAtTile>
 	//elementar with hero on tile
 {
 public:
-	DigAtTile() : CGoal (Goals::DIG_AT_TILE){};
+	DigAtTile()
+		: CGoal(Goals::DIG_AT_TILE){};
 
-	DigAtTile(int3 Tile) : CGoal (Goals::DIG_AT_TILE) {tile = Tile; priority = 20;};
+	DigAtTile(int3 Tile)
+		: CGoal(Goals::DIG_AT_TILE) {tile = Tile; priority = 20;};
 	TGoalVec getAllPossibleSubgoals() override {return TGoalVec();};
 	TSubgoal whatToDoToAchieve() override;
-	bool operator== (DigAtTile &g) { return g.goalType == goalType && g.tile == tile; }
+	bool operator==(DigAtTile & g) { return g.goalType == goalType && g.tile == tile; }
 };
 
 class CIssueCommand : public CGoal<CIssueCommand>
 {
 	std::function<bool()> command;
 
-	public:
-	CIssueCommand(): CGoal(ISSUE_COMMAND){};
+public:
+	CIssueCommand()
+		: CGoal(ISSUE_COMMAND){};
 
-	CIssueCommand(std::function<bool()> _command): CGoal(ISSUE_COMMAND), command(_command) {priority = 1e10;};
+	CIssueCommand(std::function<bool()> _command)
+		: CGoal(ISSUE_COMMAND), command(_command) {priority = 1e10;};
 	TGoalVec getAllPossibleSubgoals() override {return TGoalVec();};
 	//TSubgoal whatToDoToAchieve() override {return sptr(Invalid());};
 };

File diff suppressed because it is too large
+ 224 - 225
AI/VCAI/VCAI.cpp


+ 94 - 85
AI/VCAI/VCAI.h

@@ -35,7 +35,7 @@ class AIStatus
 	BattleState battle;
 	std::map<QueryID, std::string> remainingQueries;
 	std::map<int, QueryID> requestToQueryID; //IDs of answer-requests sent to server => query ids (so we can match answer confirmation from server to the query)
-	std::vector<const CGObjectInstance*> objectsBeingVisited;
+	std::vector<const CGObjectInstance *> objectsBeingVisited;
 	bool ongoingHeroMovement;
 	bool ongoingChannelProbing; // true if AI currently explore bidirectional teleport channel exits
 
@@ -58,16 +58,21 @@ public:
 	bool haveTurn();
 	void attemptedAnsweringQuery(QueryID queryID, int answerRequestID);
 	void receivedAnswerConfirmation(int answerRequestID, int result);
-	void heroVisit(const CGObjectInstance *obj, bool started);
+	void heroVisit(const CGObjectInstance * obj, bool started);
 
 
-	template <typename Handler> void serialize(Handler &h, const int version)
+	template<typename Handler> void serialize(Handler & h, const int version)
 	{
 		h & battle & remainingQueries & requestToQueryID & havingTurn;
 	}
 };
 
-enum {NOT_VISIBLE = 0, NOT_CHECKED = 1, NOT_AVAILABLE};
+enum
+{
+	NOT_VISIBLE = 0,
+	NOT_CHECKED = 1,
+	NOT_AVAILABLE
+};
 
 struct SectorMap
 {
@@ -95,7 +100,7 @@ struct SectorMap
 	//std::vector<std::vector<std::vector<unsigned char>>> pathfinderSector;
 
 	std::map<int, Sector> infoOnSectors;
-	std::shared_ptr<boost::multi_array<TerrainTile*, 3>> visibleTiles;
+	std::shared_ptr<boost::multi_array<TerrainTile *, 3>> visibleTiles;
 
 	SectorMap();
 	SectorMap(HeroPtr h);
@@ -104,12 +109,12 @@ struct SectorMap
 	void exploreNewSector(crint3 pos, int num, CCallback * cbp);
 	void write(crstring fname);
 
-	bool markIfBlocked(TSectorID &sec, crint3 pos, const TerrainTile *t);
-	bool markIfBlocked(TSectorID &sec, crint3 pos);
+	bool markIfBlocked(TSectorID & sec, crint3 pos, const TerrainTile * t);
+	bool markIfBlocked(TSectorID & sec, crint3 pos);
 	TSectorID & retreiveTile(crint3 pos);
-	TSectorID & retreiveTileN(TSectorArray &vectors, const int3 &pos);
-	const TSectorID & retreiveTileN(const TSectorArray &vectors, const int3 &pos);
-	TerrainTile* getTile(crint3 pos) const;
+	TSectorID & retreiveTileN(TSectorArray & vectors, const int3 & pos);
+	const TSectorID & retreiveTileN(const TSectorArray & vectors, const int3 & pos);
+	TerrainTile * getTile(crint3 pos) const;
 	std::vector<const CGObjectInstance *> getNearbyObjs(HeroPtr h, bool sectorsAround);
 
 	void makeParentBFS(crint3 source);
@@ -125,25 +130,25 @@ public:
 
 	//try build an unbuilt structure in maxDays at most (0 = indefinite)
 	/*bool canBuildStructure(const CGTownInstance * t, BuildingID building, unsigned int maxDays=7);*/
-	bool tryBuildStructure(const CGTownInstance * t, BuildingID building, unsigned int maxDays=7);
+	bool tryBuildStructure(const CGTownInstance * t, BuildingID building, unsigned int maxDays = 7);
 	//try build ANY unbuilt structure
-	BuildingID canBuildAnyStructure(const CGTownInstance * t, std::vector<BuildingID> buildList, unsigned int maxDays=7);
-	bool tryBuildAnyStructure(const CGTownInstance * t, std::vector<BuildingID> buildList, unsigned int maxDays=7);
+	BuildingID canBuildAnyStructure(const CGTownInstance * t, std::vector<BuildingID> buildList, unsigned int maxDays = 7);
+	bool tryBuildAnyStructure(const CGTownInstance * t, std::vector<BuildingID> buildList, unsigned int maxDays = 7);
 	//try build first unbuilt structure
-	bool tryBuildNextStructure(const CGTownInstance * t, std::vector<BuildingID> buildList, unsigned int maxDays=7);
+	bool tryBuildNextStructure(const CGTownInstance * t, std::vector<BuildingID> buildList, unsigned int maxDays = 7);
 
 	friend class FuzzyHelper;
 
-	std::map<TeleportChannelID, std::shared_ptr<TeleportChannel> > knownTeleportChannels;
+	std::map<TeleportChannelID, std::shared_ptr<TeleportChannel>> knownTeleportChannels;
 	std::map<const CGObjectInstance *, const CGObjectInstance *> knownSubterraneanGates;
 	ObjectInstanceID destinationTeleport;
 	int3 destinationTeleportPos;
 	std::vector<ObjectInstanceID> teleportChannelProbingList; //list of teleport channel exits that not visible and need to be (re-)explored
 	//std::vector<const CGObjectInstance *> visitedThisWeek; //only OPWs
-	std::map<HeroPtr, std::set<const CGTownInstance *> > townVisitsThisWeek;
+	std::map<HeroPtr, std::set<const CGTownInstance *>> townVisitsThisWeek;
 
 	std::map<HeroPtr, Goals::TSubgoal> lockedHeroes; //TODO: allow non-elementar objectives
-	std::map<HeroPtr, std::set<const CGObjectInstance *> > reservedHeroesMap; //objects reserved by specific heroes
+	std::map<HeroPtr, std::set<const CGObjectInstance *>> reservedHeroesMap; //objects reserved by specific heroes
 	std::set<HeroPtr> heroesUnableToExplore; //these heroes will not be polled for exploration in current state of game
 
 	//sets are faster to search, also do not contain duplicates
@@ -151,7 +156,7 @@ public:
 	std::set<const CGObjectInstance *> alreadyVisited;
 	std::set<const CGObjectInstance *> reservedObjs; //to be visited by specific hero
 
-	std::map <HeroPtr, std::shared_ptr<SectorMap>> cachedSectorMaps; //TODO: serialize? not necessary
+	std::map<HeroPtr, std::shared_ptr<SectorMap>> cachedSectorMaps; //TODO: serialize? not necessary
 
 	TResources saving;
 
@@ -188,67 +193,67 @@ public:
 	virtual void init(std::shared_ptr<CCallback> CB) override;
 	virtual void yourTurn() override;
 
-	virtual void heroGotLevel(const CGHeroInstance *hero, PrimarySkill::PrimarySkill pskill, std::vector<SecondarySkill> &skills, QueryID queryID) override; //pskill is gained primary skill, interface has to choose one of given skills and call callback with selection id
-	virtual void commanderGotLevel (const CCommanderInstance * commander, std::vector<ui32> skills, QueryID queryID) override; //TODO
-	virtual void showBlockingDialog(const std::string &text, const std::vector<Component> &components, QueryID askID, const int soundID, bool selection, bool cancel) override; //Show a dialog, player must take decision. If selection then he has to choose between one of given components, if cancel he is allowed to not choose. After making choice, CCallback::selectionMade should be called with number of selected component (1 - n) or 0 for cancel (if allowed) and askID.
-	virtual void showGarrisonDialog(const CArmedInstance *up, const CGHeroInstance *down, bool removableUnits, QueryID queryID) override; //all stacks operations between these objects become allowed, interface has to call onEnd when done
+	virtual void heroGotLevel(const CGHeroInstance * hero, PrimarySkill::PrimarySkill pskill, std::vector<SecondarySkill> & skills, QueryID queryID) override; //pskill is gained primary skill, interface has to choose one of given skills and call callback with selection id
+	virtual void commanderGotLevel(const CCommanderInstance * commander, std::vector<ui32> skills, QueryID queryID) override; //TODO
+	virtual void showBlockingDialog(const std::string & text, const std::vector<Component> & components, QueryID askID, const int soundID, bool selection, bool cancel) override; //Show a dialog, player must take decision. If selection then he has to choose between one of given components, if cancel he is allowed to not choose. After making choice, CCallback::selectionMade should be called with number of selected component (1 - n) or 0 for cancel (if allowed) and askID.
+	virtual void showGarrisonDialog(const CArmedInstance * up, const CGHeroInstance * down, bool removableUnits, QueryID queryID) override; //all stacks operations between these objects become allowed, interface has to call onEnd when done
 	virtual void showTeleportDialog(TeleportChannelID channel, TTeleportExitsList exits, bool impassable, QueryID askID) override;
 	void showMapObjectSelectDialog(QueryID askID, const Component & icon, const MetaString & title, const MetaString & description, const std::vector<ObjectInstanceID> & objects) override;
 	virtual void saveGame(BinarySerializer & h, const int version) override; //saving
 	virtual void loadGame(BinaryDeserializer & h, const int version) override; //loading
 	virtual void finish() override;
 
-	virtual void availableCreaturesChanged(const CGDwelling *town) override;
+	virtual void availableCreaturesChanged(const CGDwelling * town) override;
 	virtual void heroMoved(const TryMoveHero & details) override;
-	virtual void stackChagedCount(const StackLocation &location, const TQuantity &change, bool isAbsolute) override;
-	virtual void heroInGarrisonChange(const CGTownInstance *town) override;
+	virtual void stackChagedCount(const StackLocation & location, const TQuantity & change, bool isAbsolute) override;
+	virtual void heroInGarrisonChange(const CGTownInstance * town) override;
 	virtual void centerView(int3 pos, int focusTime) override;
-	virtual void tileHidden(const std::unordered_set<int3, ShashInt3> &pos) override;
-	virtual void artifactMoved(const ArtifactLocation &src, const ArtifactLocation &dst) override;
-	virtual void artifactAssembled(const ArtifactLocation &al) override;
-	virtual void showTavernWindow(const CGObjectInstance *townOrTavern) override;
-	virtual void showThievesGuildWindow (const CGObjectInstance * obj) override;
+	virtual void tileHidden(const std::unordered_set<int3, ShashInt3> & pos) override;
+	virtual void artifactMoved(const ArtifactLocation & src, const ArtifactLocation & dst) override;
+	virtual void artifactAssembled(const ArtifactLocation & al) override;
+	virtual void showTavernWindow(const CGObjectInstance * townOrTavern) override;
+	virtual void showThievesGuildWindow(const CGObjectInstance * obj) override;
 	virtual void playerBlocked(int reason, bool start) override;
 	virtual void showPuzzleMap() override;
-	virtual void showShipyardDialog(const IShipyard *obj) override;
+	virtual void showShipyardDialog(const IShipyard * obj) override;
 	virtual void gameOver(PlayerColor player, const EVictoryLossCheckResult & victoryLossCheckResult) override;
-	virtual void artifactPut(const ArtifactLocation &al) override;
-	virtual void artifactRemoved(const ArtifactLocation &al) override;
-	virtual void stacksErased(const StackLocation &location) override;
-	virtual void artifactDisassembled(const ArtifactLocation &al) override;
-	virtual void heroVisit(const CGHeroInstance *visitor, const CGObjectInstance *visitedObj, bool start) override;
-	virtual void availableArtifactsChanged(const CGBlackMarket *bm = nullptr) override;
-	virtual void heroVisitsTown(const CGHeroInstance* hero, const CGTownInstance * town) override;
-	virtual void tileRevealed(const std::unordered_set<int3, ShashInt3> &pos) override;
+	virtual void artifactPut(const ArtifactLocation & al) override;
+	virtual void artifactRemoved(const ArtifactLocation & al) override;
+	virtual void stacksErased(const StackLocation & location) override;
+	virtual void artifactDisassembled(const ArtifactLocation & al) override;
+	virtual void heroVisit(const CGHeroInstance * visitor, const CGObjectInstance * visitedObj, bool start) override;
+	virtual void availableArtifactsChanged(const CGBlackMarket * bm = nullptr) override;
+	virtual void heroVisitsTown(const CGHeroInstance * hero, const CGTownInstance * town) override;
+	virtual void tileRevealed(const std::unordered_set<int3, ShashInt3> & pos) override;
 	virtual void heroExchangeStarted(ObjectInstanceID hero1, ObjectInstanceID hero2, QueryID query) override;
 	virtual void heroPrimarySkillChanged(const CGHeroInstance * hero, int which, si64 val) override;
-	virtual void showRecruitmentDialog(const CGDwelling *dwelling, const CArmedInstance *dst, int level) override;
+	virtual void showRecruitmentDialog(const CGDwelling * dwelling, const CArmedInstance * dst, int level) override;
 	virtual void heroMovePointsChanged(const CGHeroInstance * hero) override;
-	virtual void stackChangedType(const StackLocation &location, const CCreature &newType) override;
-	virtual void stacksRebalanced(const StackLocation &src, const StackLocation &dst, TQuantity count) override;
+	virtual void stackChangedType(const StackLocation & location, const CCreature & newType) override;
+	virtual void stacksRebalanced(const StackLocation & src, const StackLocation & dst, TQuantity count) override;
 	virtual void newObject(const CGObjectInstance * obj) override;
-	virtual void showHillFortWindow(const CGObjectInstance *object, const CGHeroInstance *visitor) override;
-	virtual void playerBonusChanged(const Bonus &bonus, bool gain) override;
-	virtual void newStackInserted(const StackLocation &location, const CStackInstance &stack) override;
-	virtual void heroCreated(const CGHeroInstance*) override;
+	virtual void showHillFortWindow(const CGObjectInstance * object, const CGHeroInstance * visitor) override;
+	virtual void playerBonusChanged(const Bonus & bonus, bool gain) override;
+	virtual void newStackInserted(const StackLocation & location, const CStackInstance & stack) override;
+	virtual void heroCreated(const CGHeroInstance *) override;
 	virtual void advmapSpellCast(const CGHeroInstance * caster, int spellID) override;
-	virtual void showInfoDialog(const std::string &text, const std::vector<Component*> &components, int soundID) override;
-	virtual void requestRealized(PackageApplied *pa) override;
+	virtual void showInfoDialog(const std::string & text, const std::vector<Component *> & components, int soundID) override;
+	virtual void requestRealized(PackageApplied * pa) override;
 	virtual void receivedResource() override;
-	virtual void stacksSwapped(const StackLocation &loc1, const StackLocation &loc2) override;
-	virtual void objectRemoved(const CGObjectInstance *obj) override;
-	virtual void showUniversityWindow(const IMarket *market, const CGHeroInstance *visitor) override;
+	virtual void stacksSwapped(const StackLocation & loc1, const StackLocation & loc2) override;
+	virtual void objectRemoved(const CGObjectInstance * obj) override;
+	virtual void showUniversityWindow(const IMarket * market, const CGHeroInstance * visitor) override;
 	virtual void heroManaPointsChanged(const CGHeroInstance * hero) override;
 	virtual void heroSecondarySkillChanged(const CGHeroInstance * hero, int which, int val) override;
 	virtual void battleResultsApplied() override;
 	virtual void objectPropertyChanged(const SetObjectProperty * sop) override;
-	virtual void buildChanged(const CGTownInstance *town, BuildingID buildingID, int what) override;
-	virtual void heroBonusChanged(const CGHeroInstance *hero, const Bonus &bonus, bool gain) override;
-	virtual void showMarketWindow(const IMarket *market, const CGHeroInstance *visitor) override;
+	virtual void buildChanged(const CGTownInstance * town, BuildingID buildingID, int what) override;
+	virtual void heroBonusChanged(const CGHeroInstance * hero, const Bonus & bonus, bool gain) override;
+	virtual void showMarketWindow(const IMarket * market, const CGHeroInstance * visitor) override;
 	void showWorldViewEx(const std::vector<ObjectPosInfo> & objectPositions) override;
 
-	virtual void battleStart(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool side) override;
-	virtual void battleEnd(const BattleResult *br) override;
+	virtual void battleStart(const CCreatureSet * army1, const CCreatureSet * army2, int3 tile, const CGHeroInstance * hero1, const CGHeroInstance * hero2, bool side) override;
+	virtual void battleEnd(const BattleResult * br) override;
 	void makeTurn();
 
 	void makeTurnInternal();
@@ -261,15 +266,15 @@ public:
 	void wander(HeroPtr h);
 	void setGoal(HeroPtr h, Goals::TSubgoal goal);
 	void evaluateGoal(HeroPtr h); //evaluates goal assigned to hero, if any
-	void completeGoal (Goals::TSubgoal goal); //safely removes goal from reserved hero
-	void striveToQuest (const QuestInfo &q);
+	void completeGoal(Goals::TSubgoal goal); //safely removes goal from reserved hero
+	void striveToQuest(const QuestInfo & q);
 
 	void recruitHero(const CGTownInstance * t, bool throwing = false);
-	bool isGoodForVisit(const CGObjectInstance *obj, HeroPtr h, SectorMap &sm);
+	bool isGoodForVisit(const CGObjectInstance * obj, HeroPtr h, SectorMap & sm);
 	void buildStructure(const CGTownInstance * t);
 	//void recruitCreatures(const CGTownInstance * t);
 	void recruitCreatures(const CGDwelling * d, const CArmedInstance * recruiter);
-	bool canGetArmy (const CGHeroInstance * h, const CGHeroInstance * source); //can we get any better stacks from other hero?
+	bool canGetArmy(const CGHeroInstance * h, const CGHeroInstance * source); //can we get any better stacks from other hero?
 	void pickBestCreatures(const CArmedInstance * army, const CArmedInstance * source); //called when we can't find a slot for new stack
 	void pickBestArtifacts(const CGHeroInstance * h, const CGHeroInstance * other = nullptr);
 	void moveCreaturesToHero(const CGTownInstance * t);
@@ -281,50 +286,50 @@ public:
 	void lostHero(HeroPtr h); //should remove all references to hero (assigned tasks and so on)
 	void waitTillFree();
 
-	void addVisitableObj(const CGObjectInstance *obj);
-	void markObjectVisited (const CGObjectInstance *obj);
-	void reserveObject (HeroPtr h, const CGObjectInstance *obj); //TODO: reserve all objects that heroes attempt to visit
-	void unreserveObject (HeroPtr h, const CGObjectInstance *obj);
+	void addVisitableObj(const CGObjectInstance * obj);
+	void markObjectVisited(const CGObjectInstance * obj);
+	void reserveObject(HeroPtr h, const CGObjectInstance * obj); //TODO: reserve all objects that heroes attempt to visit
+	void unreserveObject(HeroPtr h, const CGObjectInstance * obj);
 
-	void markHeroUnableToExplore (HeroPtr h);
-	void markHeroAbleToExplore (HeroPtr h);
-	bool isAbleToExplore (HeroPtr h);
+	void markHeroUnableToExplore(HeroPtr h);
+	void markHeroAbleToExplore(HeroPtr h);
+	bool isAbleToExplore(HeroPtr h);
 	void clearPathsInfo();
 
-	void validateObject(const CGObjectInstance *obj); //checks if object is still visible and if not, removes references to it
+	void validateObject(const CGObjectInstance * obj); //checks if object is still visible and if not, removes references to it
 	void validateObject(ObjectIdRef obj); //checks if object is still visible and if not, removes references to it
 	void validateVisitableObjs();
-	void retreiveVisitableObjs(std::vector<const CGObjectInstance *> &out, bool includeOwned = false) const;
+	void retreiveVisitableObjs(std::vector<const CGObjectInstance *> & out, bool includeOwned = false) const;
 	void retreiveVisitableObjs();
 	std::vector<const CGObjectInstance *> getFlaggedObjects() const;
 
-	const CGObjectInstance *lookForArt(int aid) const;
-	bool isAccessible(const int3 &pos);
+	const CGObjectInstance * lookForArt(int aid) const;
+	bool isAccessible(const int3 & pos);
 	HeroPtr getHeroWithGrail() const;
 
-	const CGObjectInstance *getUnvisitedObj(const std::function<bool(const CGObjectInstance *)> &predicate);
+	const CGObjectInstance * getUnvisitedObj(const std::function<bool(const CGObjectInstance *)> & predicate);
 	bool isAccessibleForHero(const int3 & pos, HeroPtr h, bool includeAllies = false) const;
 	//optimization - use one SM for every hero call
 	std::shared_ptr<SectorMap> getCachedSectorMap(HeroPtr h);
 
-	const CGTownInstance *findTownWithTavern() const;
+	const CGTownInstance * findTownWithTavern() const;
 	bool canRecruitAnyHero(const CGTownInstance * t = NULL) const;
 
-	Goals::TSubgoal getGoal (HeroPtr h) const;
+	Goals::TSubgoal getGoal(HeroPtr h) const;
 	bool canAct(HeroPtr h) const;
 	std::vector<HeroPtr> getUnblockedHeroes() const;
 	HeroPtr primaryHero() const;
 	TResources freeResources() const; //owned resources minus gold reserve
 	TResources estimateIncome() const;
-	bool containsSavedRes(const TResources &cost) const;
-	void checkHeroArmy (HeroPtr h);
+	bool containsSavedRes(const TResources & cost) const;
+	void checkHeroArmy(HeroPtr h);
 
-	void requestSent(const CPackForServer *pack, int requestID) override;
+	void requestSent(const CPackForServer * pack, int requestID) override;
 	void answerQuery(QueryID queryID, int selection);
 	//special function that can be called ONLY from game events handling thread and will send request ASAP
 	void requestActionASAP(std::function<void()> whatToDo);
 
-	template <typename Handler> void registerGoals(Handler &h)
+	template<typename Handler> void registerGoals(Handler & h)
 	{
 		//h.template registerType<Goals::AbstractGoal, Goals::BoostHero>();
 		h.template registerType<Goals::AbstractGoal, Goals::Build>();
@@ -348,7 +353,7 @@ public:
 		h.template registerType<Goals::AbstractGoal, Goals::Win>();
 	}
 
-	template <typename Handler> void serializeInternal(Handler &h, const int version)
+	template<typename Handler> void serializeInternal(Handler & h, const int version)
 	{
 		h & knownTeleportChannels & knownSubterraneanGates & destinationTeleport;
 		h & townVisitsThisWeek & lockedHeroes & reservedHeroesMap; //FIXME: cannot instantiate abstract class
@@ -363,8 +368,10 @@ public:
 class cannotFulfillGoalException : public std::exception
 {
 	std::string msg;
+
 public:
-	explicit cannotFulfillGoalException(crstring _Message) : msg(_Message)
+	explicit cannotFulfillGoalException(crstring _Message)
+		: msg(_Message)
 	{
 	}
 
@@ -372,18 +379,21 @@ public:
 	{
 	};
 
-	const char *what() const throw () override
+	const char * what() const throw ()override
 	{
 		return msg.c_str();
 	}
 };
+
 class goalFulfilledException : public std::exception
 {
 	std::string msg;
+
 public:
 	Goals::TSubgoal goal;
 
-	explicit goalFulfilledException(Goals::TSubgoal Goal) : goal(Goal)
+	explicit goalFulfilledException(Goals::TSubgoal Goal)
+		: goal(Goal)
 	{
 		msg = goal->name();
 	}
@@ -392,11 +402,10 @@ public:
 	{
 	};
 
-	const char *what() const throw () override
+	const char * what() const throw ()override
 	{
 		return msg.c_str();
 	}
 };
 
-void makePossibleUpgrades(const CArmedInstance *obj);
-
+void makePossibleUpgrades(const CArmedInstance * obj);

+ 3 - 3
AI/VCAI/main.cpp

@@ -14,19 +14,19 @@
 #define strcpy_s(a, b, c) strncpy(a, c, b)
 #endif
 
-static const char *g_cszAiName = "VCAI";
+static const char * g_cszAiName = "VCAI";
 
 extern "C" DLL_EXPORT int GetGlobalAiVersion()
 {
 	return AI_INTERFACE_VER;
 }
 
-extern "C" DLL_EXPORT void GetAiName(char* name)
+extern "C" DLL_EXPORT void GetAiName(char * name)
 {
 	strcpy_s(name, strlen(g_cszAiName) + 1, g_cszAiName);
 }
 
-extern "C" DLL_EXPORT void GetNewAI(std::shared_ptr<CGlobalAI> &out)
+extern "C" DLL_EXPORT void GetNewAI(std::shared_ptr<CGlobalAI> & out)
 {
 	out = std::make_shared<VCAI>();
 }

+ 57 - 55
CCallback.cpp

@@ -29,16 +29,16 @@
 #include "lib/UnlockGuard.h"
 #include "lib/battle/BattleInfo.h"
 
-bool CCallback::teleportHero(const CGHeroInstance *who, const CGTownInstance *where)
+bool CCallback::teleportHero(const CGHeroInstance * who, const CGTownInstance * where)
 {
 	CastleTeleportHero pack(who->id, where->id, 1);
 	sendRequest(&pack);
 	return true;
 }
 
-bool CCallback::moveHero(const CGHeroInstance *h, int3 dst, bool transit)
+bool CCallback::moveHero(const CGHeroInstance * h, int3 dst, bool transit)
 {
-	MoveHero pack(dst,h->id,transit);
+	MoveHero pack(dst, h->id, transit);
 	sendRequest(&pack);
 	return true;
 }
@@ -74,52 +74,53 @@ void CCallback::recruitCreatures(const CGDwelling * obj, const CArmedInstance *
 	sendRequest(&pack);
 }
 
-bool CCallback::dismissCreature(const CArmedInstance *obj, SlotID stackPos)
+bool CCallback::dismissCreature(const CArmedInstance * obj, SlotID stackPos)
 {
-	if((player && obj->tempOwner != player) || (obj->stacksCount()<2  && obj->needsLastStack()))
+	if((player && obj->tempOwner != player) || (obj->stacksCount() < 2 && obj->needsLastStack()))
 		return false;
 
-	DisbandCreature pack(stackPos,obj->id);
+	DisbandCreature pack(stackPos, obj->id);
 	sendRequest(&pack);
 	return true;
 }
 
-bool CCallback::upgradeCreature(const CArmedInstance *obj, SlotID stackPos, CreatureID newID)
+bool CCallback::upgradeCreature(const CArmedInstance * obj, SlotID stackPos, CreatureID newID)
 {
-	UpgradeCreature pack(stackPos,obj->id,newID);
+	UpgradeCreature pack(stackPos, obj->id, newID);
 	sendRequest(&pack);
 	return false;
 }
 
 void CCallback::endTurn()
 {
-	logGlobal->traceStream() << "Player " << *player << " ended his turn.";
+	logGlobal->traceStream() << "Player " << * player << " ended his turn.";
 	EndTurn pack;
 	sendRequest(&pack); //report that we ended turn
 }
-int CCallback::swapCreatures(const CArmedInstance *s1, const CArmedInstance *s2, SlotID p1, SlotID p2)
+int CCallback::swapCreatures(const CArmedInstance * s1, const CArmedInstance * s2, SlotID p1, SlotID p2)
 {
-	ArrangeStacks pack(1,p1,p2,s1->id,s2->id,0);
+	ArrangeStacks pack(1, p1, p2, s1->id, s2->id, 0);
 	sendRequest(&pack);
 	return 0;
 }
 
-int CCallback::mergeStacks(const CArmedInstance *s1, const CArmedInstance *s2, SlotID p1, SlotID p2)
+int CCallback::mergeStacks(const CArmedInstance * s1, const CArmedInstance * s2, SlotID p1, SlotID p2)
 {
-	ArrangeStacks pack(2,p1,p2,s1->id,s2->id,0);
+	ArrangeStacks pack(2, p1, p2, s1->id, s2->id, 0);
 	sendRequest(&pack);
 	return 0;
 }
-int CCallback::splitStack(const CArmedInstance *s1, const CArmedInstance *s2, SlotID p1, SlotID p2, int val)
+int CCallback::splitStack(const CArmedInstance * s1, const CArmedInstance * s2, SlotID p1, SlotID p2, int val)
 {
-	ArrangeStacks pack(3,p1,p2,s1->id,s2->id,val);
+	ArrangeStacks pack(3, p1, p2, s1->id, s2->id, val);
 	sendRequest(&pack);
 	return 0;
 }
 
-bool CCallback::dismissHero(const CGHeroInstance *hero)
+bool CCallback::dismissHero(const CGHeroInstance * hero)
 {
-	if(player!=hero->tempOwner) return false;
+	if(player != hero->tempOwner)
+		return false;
 
 	DismissHero pack(hero->id);
 	sendRequest(&pack);
@@ -128,11 +129,11 @@ bool CCallback::dismissHero(const CGHeroInstance *hero)
 
 // int CCallback::getMySerial() const
 // {
-// 	boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
-// 	return gs->players[player].serial;
+//      boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
+//      return gs->players[player].serial;
 // }
 
-bool CCallback::swapArtifacts(const ArtifactLocation &l1, const ArtifactLocation &l2)
+bool CCallback::swapArtifacts(const ArtifactLocation & l1, const ArtifactLocation & l2)
 {
 	ExchangeArtifacts ea;
 	ea.src = l1;
@@ -149,9 +150,9 @@ bool CCallback::swapArtifacts(const ArtifactLocation &l1, const ArtifactLocation
  * @param assembleTo If assemble is true, this represents the artifact ID of the combination
  * artifact to assemble to. Otherwise it's not used.
  */
-bool CCallback::assembleArtifacts (const CGHeroInstance * hero, ArtifactPosition artifactSlot, bool assemble, ArtifactID assembleTo)
+bool CCallback::assembleArtifacts(const CGHeroInstance * hero, ArtifactPosition artifactSlot, bool assemble, ArtifactID assembleTo)
 {
-	if (player != hero->tempOwner)
+	if(player != hero->tempOwner)
 		return false;
 
 	AssembleArtifacts aa(hero->id, artifactSlot, assemble, assembleTo);
@@ -159,20 +160,20 @@ bool CCallback::assembleArtifacts (const CGHeroInstance * hero, ArtifactPosition
 	return true;
 }
 
-bool CCallback::buildBuilding(const CGTownInstance *town, BuildingID buildingID)
+bool CCallback::buildBuilding(const CGTownInstance * town, BuildingID buildingID)
 {
-	if(town->tempOwner!=player)
+	if(town->tempOwner != player)
 		return false;
 
 	if(!canBuildStructure(town, buildingID))
 		return false;
 
-	BuildStructure pack(town->id,buildingID);
+	BuildStructure pack(town->id, buildingID);
 	sendRequest(&pack);
 	return true;
 }
 
-int CBattleCallback::battleMakeAction(BattleAction* action)
+int CBattleCallback::battleMakeAction(BattleAction * action)
 {
 	assert(action->actionType == Battle::HERO_SPELL);
 	MakeCustomAction mca(*action);
@@ -180,7 +181,7 @@ int CBattleCallback::battleMakeAction(BattleAction* action)
 	return 0;
 }
 
-int CBattleCallback::sendRequest(const CPack *request)
+int CBattleCallback::sendRequest(const CPack * request)
 {
 	int requestID = cl->sendRequest(request, *player);
 	if(waitTillRealize)
@@ -194,25 +195,26 @@ int CBattleCallback::sendRequest(const CPack *request)
 	return requestID;
 }
 
-void CCallback::swapGarrisonHero( const CGTownInstance *town )
+void CCallback::swapGarrisonHero(const CGTownInstance * town)
 {
 	if(town->tempOwner == *player
-	   || (town->garrisonHero && town->garrisonHero->tempOwner == *player ))
+	   || (town->garrisonHero && town->garrisonHero->tempOwner == *player))
 	{
 		GarrisonHeroSwap pack(town->id);
 		sendRequest(&pack);
 	}
 }
 
-void CCallback::buyArtifact(const CGHeroInstance *hero, ArtifactID aid)
+void CCallback::buyArtifact(const CGHeroInstance * hero, ArtifactID aid)
 {
-	if(hero->tempOwner != player) return;
+	if(hero->tempOwner != player)
+		return;
 
-	BuyArtifact pack(hero->id,aid);
+	BuyArtifact pack(hero->id, aid);
 	sendRequest(&pack);
 }
 
-void CCallback::trade(const CGObjectInstance *market, EMarketMode::EMarketMode mode, int id1, int id2, int val1, const CGHeroInstance *hero)
+void CCallback::trade(const CGObjectInstance * market, EMarketMode::EMarketMode mode, int id1, int id2, int val1, const CGHeroInstance * hero)
 {
 	TradeOnMarketplace pack;
 	pack.market = market;
@@ -226,16 +228,16 @@ void CCallback::trade(const CGObjectInstance *market, EMarketMode::EMarketMode m
 
 void CCallback::setFormation(const CGHeroInstance * hero, bool tight)
 {
-	SetFormation pack(hero->id,tight);
+	SetFormation pack(hero->id, tight);
 	sendRequest(&pack);
 }
 
-void CCallback::recruitHero(const CGObjectInstance *townOrTavern, const CGHeroInstance *hero)
+void CCallback::recruitHero(const CGObjectInstance * townOrTavern, const CGHeroInstance * hero)
 {
 	assert(townOrTavern);
 	assert(hero);
-	ui8 i=0;
-	for(; i<gs->players[*player].availableHeroes.size(); i++)
+	ui8 i = 0;
+	for(; i < gs->players[*player].availableHeroes.size(); i++)
 	{
 		if(gs->players[*player].availableHeroes[i] == hero)
 		{
@@ -247,28 +249,28 @@ void CCallback::recruitHero(const CGObjectInstance *townOrTavern, const CGHeroIn
 	}
 }
 
-void CCallback::save( const std::string &fname )
+void CCallback::save(const std::string & fname)
 {
 	cl->save(fname);
 }
 
 
-void CCallback::sendMessage(const std::string &mess, const CGObjectInstance * currentObject)
+void CCallback::sendMessage(const std::string & mess, const CGObjectInstance * currentObject)
 {
 	ASSERT_IF_CALLED_WITH_PLAYER
-	PlayerMessage pm(*player, mess, currentObject? currentObject->id : ObjectInstanceID(-1));
-	sendRequest(&(CPackForClient&)pm);
+	PlayerMessage pm(*player, mess, currentObject ? currentObject->id : ObjectInstanceID(-1));
+	sendRequest(&(CPackForClient &)pm);
 }
 
-void CCallback::buildBoat( const IShipyard *obj )
+void CCallback::buildBoat(const IShipyard * obj)
 {
 	BuildBoat bb;
 	bb.objid = obj->o->id;
 	sendRequest(&bb);
 }
 
-CCallback::CCallback( CGameState * GS, boost::optional<PlayerColor> Player, CClient *C )
-	:CBattleCallback(GS, Player, C)
+CCallback::CCallback(CGameState * GS, boost::optional<PlayerColor> Player, CClient * C)
+	: CBattleCallback(GS, Player, C)
 {
 	waitTillRealize = false;
 	unlockGsWhenWaiting = false;
@@ -279,38 +281,38 @@ CCallback::~CCallback()
 //trivial, but required. Don`t remove.
 }
 
-bool CCallback::canMoveBetween(const int3 &a, const int3 &b)
+bool CCallback::canMoveBetween(const int3 & a, const int3 & b)
 {
 	//bidirectional
 	return gs->map->canMoveBetween(a, b);
 }
 
-const CPathsInfo * CCallback::getPathsInfo(const CGHeroInstance *h)
+const CPathsInfo * CCallback::getPathsInfo(const CGHeroInstance * h)
 {
 	return cl->getPathsInfo(h);
 }
 
 int3 CCallback::getGuardingCreaturePosition(int3 tile)
 {
-	if (!gs->map->isInTheMap(tile))
-		return int3(-1,-1,-1);
+	if(!gs->map->isInTheMap(tile))
+		return int3(-1, -1, -1);
 
 	return gs->map->guardingCreaturePositions[tile.x][tile.y][tile.z];
 }
 
-void CCallback::calculatePaths( const CGHeroInstance *hero, CPathsInfo &out)
+void CCallback::calculatePaths(const CGHeroInstance * hero, CPathsInfo & out)
 {
 	gs->calculatePaths(hero, out);
 }
 
-void CCallback::dig( const CGObjectInstance *hero )
+void CCallback::dig(const CGObjectInstance * hero)
 {
 	DigWithHero dwh;
 	dwh.id = hero->id;
 	sendRequest(&dwh);
 }
 
-void CCallback::castSpell(const CGHeroInstance *hero, SpellID spellID, const int3 &pos)
+void CCallback::castSpell(const CGHeroInstance * hero, SpellID spellID, const int3 & pos)
 {
 	CastAdvSpell cas;
 	cas.hid = hero->id;
@@ -321,13 +323,13 @@ void CCallback::castSpell(const CGHeroInstance *hero, SpellID spellID, const int
 
 void CCallback::unregisterAllInterfaces()
 {
-	for (auto& pi : cl->playerint)
+	for(auto & pi : cl->playerint)
 		pi.second->finish();
 	cl->playerint.clear();
 	cl->battleints.clear();
 }
 
-int CCallback::mergeOrSwapStacks(const CArmedInstance *s1, const CArmedInstance *s2, SlotID p1, SlotID p2)
+int CCallback::mergeOrSwapStacks(const CArmedInstance * s1, const CArmedInstance * s2, SlotID p1, SlotID p2)
 {
 	if(s1->getCreature(p1) == s2->getCreature(p2))
 		return mergeStacks(s1, s2, p1, p2);
@@ -355,14 +357,14 @@ void CCallback::unregisterBattleInterface(std::shared_ptr<IBattleEventsReceiver>
 	cl->additionalBattleInts[*player] -= battleEvents;
 }
 
-CBattleCallback::CBattleCallback(CGameState *GS, boost::optional<PlayerColor> Player, CClient *C )
+CBattleCallback::CBattleCallback(CGameState * GS, boost::optional<PlayerColor> Player, CClient * C)
 {
 	gs = GS;
 	player = Player;
 	cl = C;
 }
 
-bool CBattleCallback::battleMakeTacticAction( BattleAction * action )
+bool CBattleCallback::battleMakeTacticAction(BattleAction * action)
 {
 	assert(cl->gs->curB->tacticDistance);
 	MakeAction ma;

+ 59 - 59
CCallback.h

@@ -34,47 +34,47 @@ class IBattleCallback
 {
 public:
 	bool waitTillRealize; //if true, request functions will return after they are realized by server
-	bool unlockGsWhenWaiting;//if true after sending each request, gs mutex will be unlocked so the changes can be applied; NOTICE caller must have gs mx locked prior to any call to actiob callback!
+	bool unlockGsWhenWaiting; //if true after sending each request, gs mutex will be unlocked so the changes can be applied; NOTICE caller must have gs mx locked prior to any call to actiob callback!
 	//battle
-	virtual int battleMakeAction(BattleAction* action)=0;//for casting spells by hero - DO NOT use it for moving active stack
-	virtual bool battleMakeTacticAction(BattleAction * action) =0; // performs tactic phase actions
+	virtual int battleMakeAction(BattleAction * action) = 0; //for casting spells by hero - DO NOT use it for moving active stack
+	virtual bool battleMakeTacticAction(BattleAction * action) = 0; // performs tactic phase actions
 };
 
 class IGameActionCallback
 {
 public:
 	//hero
-	virtual bool moveHero(const CGHeroInstance *h, int3 dst, bool transit) =0; //dst must be free, neighbouring tile (this function can move hero only by one tile)
-	virtual bool dismissHero(const CGHeroInstance * hero)=0; //dismisses given hero; true - successfuly, false - not successfuly
-	virtual void dig(const CGObjectInstance *hero)=0;
-	virtual void castSpell(const CGHeroInstance *hero, SpellID spellID, const int3 &pos = int3(-1, -1, -1))=0; //cast adventure map spell
+	virtual bool moveHero(const CGHeroInstance * h, int3 dst, bool transit) = 0; //dst must be free, neighbouring tile (this function can move hero only by one tile)
+	virtual bool dismissHero(const CGHeroInstance * hero) = 0; //dismisses given hero; true - successfuly, false - not successfuly
+	virtual void dig(const CGObjectInstance * hero) = 0;
+	virtual void castSpell(const CGHeroInstance * hero, SpellID spellID, const int3 & pos = int3(-1, -1, -1)) = 0; //cast adventure map spell
 
 	//town
-	virtual void recruitHero(const CGObjectInstance *townOrTavern, const CGHeroInstance *hero)=0;
-	virtual bool buildBuilding(const CGTownInstance *town, BuildingID buildingID)=0;
-	virtual void recruitCreatures(const CGDwelling *obj, const CArmedInstance * dst, CreatureID ID, ui32 amount, si32 level=-1)=0;
-	virtual bool upgradeCreature(const CArmedInstance *obj, SlotID stackPos, CreatureID newID=CreatureID::NONE)=0; //if newID==-1 then best possible upgrade will be made
-	virtual void swapGarrisonHero(const CGTownInstance *town)=0;
-
-	virtual void trade(const CGObjectInstance *market, EMarketMode::EMarketMode mode, int id1, int id2, int val1, const CGHeroInstance *hero = nullptr)=0; //mode==0: sell val1 units of id1 resource for id2 resiurce
-
-	virtual int selectionMade(int selection, QueryID queryID) =0;
-	virtual int sendQueryReply(const JsonNode & reply, QueryID queryID) =0;
-	virtual int swapCreatures(const CArmedInstance *s1, const CArmedInstance *s2, SlotID p1, SlotID p2)=0;//swaps creatures between two possibly different garrisons // TODO: AI-unsafe code - fix it!
-	virtual int mergeStacks(const CArmedInstance *s1, const CArmedInstance *s2, SlotID p1, SlotID p2)=0;//joins first stack to the second (creatures must be same type)
-	virtual int mergeOrSwapStacks(const CArmedInstance *s1, const CArmedInstance *s2, SlotID p1, SlotID p2) =0; //first goes to the second
-	virtual int splitStack(const CArmedInstance *s1, const CArmedInstance *s2, SlotID p1, SlotID p2, int val)=0;//split creatures from the first stack
+	virtual void recruitHero(const CGObjectInstance * townOrTavern, const CGHeroInstance * hero) = 0;
+	virtual bool buildBuilding(const CGTownInstance * town, BuildingID buildingID) = 0;
+	virtual void recruitCreatures(const CGDwelling * obj, const CArmedInstance * dst, CreatureID ID, ui32 amount, si32 level = -1) = 0;
+	virtual bool upgradeCreature(const CArmedInstance * obj, SlotID stackPos, CreatureID newID = CreatureID::NONE) = 0; //if newID==-1 then best possible upgrade will be made
+	virtual void swapGarrisonHero(const CGTownInstance * town) = 0;
+
+	virtual void trade(const CGObjectInstance * market, EMarketMode::EMarketMode mode, int id1, int id2, int val1, const CGHeroInstance * hero = nullptr) = 0; //mode==0: sell val1 units of id1 resource for id2 resiurce
+
+	virtual int selectionMade(int selection, QueryID queryID) = 0;
+	virtual int sendQueryReply(const JsonNode & reply, QueryID queryID) = 0;
+	virtual int swapCreatures(const CArmedInstance * s1, const CArmedInstance * s2, SlotID p1, SlotID p2) = 0; //swaps creatures between two possibly different garrisons // TODO: AI-unsafe code - fix it!
+	virtual int mergeStacks(const CArmedInstance * s1, const CArmedInstance * s2, SlotID p1, SlotID p2) = 0; //joins first stack to the second (creatures must be same type)
+	virtual int mergeOrSwapStacks(const CArmedInstance * s1, const CArmedInstance * s2, SlotID p1, SlotID p2) = 0; //first goes to the second
+	virtual int splitStack(const CArmedInstance * s1, const CArmedInstance * s2, SlotID p1, SlotID p2, int val) = 0; //split creatures from the first stack
 	//virtual bool swapArtifacts(const CGHeroInstance * hero1, ui16 pos1, const CGHeroInstance * hero2, ui16 pos2)=0; //swaps artifacts between two given heroes
-	virtual bool swapArtifacts(const ArtifactLocation &l1, const ArtifactLocation &l2)=0;
-	virtual bool assembleArtifacts(const CGHeroInstance * hero, ArtifactPosition artifactSlot, bool assemble, ArtifactID assembleTo)=0;
-	virtual bool dismissCreature(const CArmedInstance *obj, SlotID stackPos)=0;
-	virtual void endTurn()=0;
-	virtual void buyArtifact(const CGHeroInstance *hero, ArtifactID aid)=0; //used to buy artifacts in towns (including spell book in the guild and war machines in blacksmith)
-	virtual void setFormation(const CGHeroInstance * hero, bool tight)=0;
-
-	virtual void save(const std::string &fname) = 0;
-	virtual void sendMessage(const std::string &mess, const CGObjectInstance * currentObject = nullptr) = 0;
-	virtual void buildBoat(const IShipyard *obj) = 0;
+	virtual bool swapArtifacts(const ArtifactLocation & l1, const ArtifactLocation & l2) = 0;
+	virtual bool assembleArtifacts(const CGHeroInstance * hero, ArtifactPosition artifactSlot, bool assemble, ArtifactID assembleTo) = 0;
+	virtual bool dismissCreature(const CArmedInstance * obj, SlotID stackPos) = 0;
+	virtual void endTurn() = 0;
+	virtual void buyArtifact(const CGHeroInstance * hero, ArtifactID aid) = 0; //used to buy artifacts in towns (including spell book in the guild and war machines in blacksmith)
+	virtual void setFormation(const CGHeroInstance * hero, bool tight) = 0;
+
+	virtual void save(const std::string & fname) = 0;
+	virtual void sendMessage(const std::string & mess, const CGObjectInstance * currentObject = nullptr) = 0;
+	virtual void buildBoat(const IShipyard * obj) = 0;
 };
 
 struct CPack;
@@ -82,13 +82,13 @@ struct CPack;
 class CBattleCallback : public IBattleCallback, public CPlayerBattleCallback
 {
 protected:
-	int sendRequest(const CPack *request); //returns requestID (that'll be matched to requestID in PackageApplied)
-	CClient *cl;
+	int sendRequest(const CPack * request); //returns requestID (that'll be matched to requestID in PackageApplied)
+	CClient * cl;
 	//virtual bool hasAccess(int playerId) const;
 
 public:
-	CBattleCallback(CGameState *GS, boost::optional<PlayerColor> Player, CClient *C);
-	int battleMakeAction(BattleAction* action) override;//for casting spells by hero - DO NOT use it for moving active stack
+	CBattleCallback(CGameState * GS, boost::optional<PlayerColor> Player, CClient * C);
+	int battleMakeAction(BattleAction * action) override; //for casting spells by hero - DO NOT use it for moving active stack
 	bool battleMakeTacticAction(BattleAction * action) override; // performs tactic phase actions
 
 	friend class CCallback;
@@ -98,15 +98,15 @@ public:
 class CCallback : public CPlayerSpecificInfoCallback, public IGameActionCallback, public CBattleCallback
 {
 public:
-	CCallback(CGameState * GS, boost::optional<PlayerColor> Player, CClient *C);
+	CCallback(CGameState * GS, boost::optional<PlayerColor> Player, CClient * C);
 	virtual ~CCallback();
 
 	//client-specific functionalities (pathfinding)
-	virtual bool canMoveBetween(const int3 &a, const int3 &b);
+	virtual bool canMoveBetween(const int3 & a, const int3 & b);
 	virtual int3 getGuardingCreaturePosition(int3 tile);
-	virtual const CPathsInfo * getPathsInfo(const CGHeroInstance *h);
+	virtual const CPathsInfo * getPathsInfo(const CGHeroInstance * h);
 
-	virtual void calculatePaths(const CGHeroInstance *hero, CPathsInfo &out);
+	virtual void calculatePaths(const CGHeroInstance * hero, CPathsInfo & out);
 
 	//Set of metrhods that allows adding more interfaces for this player that'll receive game event call-ins.
 	void registerGameInterface(std::shared_ptr<IGameEventsReceiver> gameEvents);
@@ -117,35 +117,35 @@ public:
 	void unregisterAllInterfaces(); //stops delivering information about game events to player interfaces -> can be called ONLY after victory/loss
 
 //commands
-	bool moveHero(const CGHeroInstance *h, int3 dst, bool transit = false) override; //dst must be free, neighbouring tile (this function can move hero only by one tile)
-	bool teleportHero(const CGHeroInstance *who, const CGTownInstance *where);
+	bool moveHero(const CGHeroInstance * h, int3 dst, bool transit = false) override; //dst must be free, neighbouring tile (this function can move hero only by one tile)
+	bool teleportHero(const CGHeroInstance * who, const CGTownInstance * where);
 	int selectionMade(int selection, QueryID queryID) override;
 	int sendQueryReply(const JsonNode & reply, QueryID queryID) override;
-	int swapCreatures(const CArmedInstance *s1, const CArmedInstance *s2, SlotID p1, SlotID p2) override;
-	int mergeOrSwapStacks(const CArmedInstance *s1, const CArmedInstance *s2, SlotID p1, SlotID p2) override; //first goes to the second
-	int mergeStacks(const CArmedInstance *s1, const CArmedInstance *s2, SlotID p1, SlotID p2) override; //first goes to the second
-	int splitStack(const CArmedInstance *s1, const CArmedInstance *s2, SlotID p1, SlotID p2, int val) override;
+	int swapCreatures(const CArmedInstance * s1, const CArmedInstance * s2, SlotID p1, SlotID p2) override;
+	int mergeOrSwapStacks(const CArmedInstance * s1, const CArmedInstance * s2, SlotID p1, SlotID p2) override; //first goes to the second
+	int mergeStacks(const CArmedInstance * s1, const CArmedInstance * s2, SlotID p1, SlotID p2) override; //first goes to the second
+	int splitStack(const CArmedInstance * s1, const CArmedInstance * s2, SlotID p1, SlotID p2, int val) override;
 	bool dismissHero(const CGHeroInstance * hero) override;
 	//bool swapArtifacts(const CGHeroInstance * hero1, ui16 pos1, const CGHeroInstance * hero2, ui16 pos2);
-	bool swapArtifacts(const ArtifactLocation &l1, const ArtifactLocation &l2) override;
+	bool swapArtifacts(const ArtifactLocation & l1, const ArtifactLocation & l2) override;
 	//bool moveArtifact(const CGHeroInstance * hero, ui16 src, const CStackInstance * stack, ui16 dest); // TODO: unify classes
 	//bool moveArtifact(const CStackInstance * stack, ui16 src , const CGHeroInstance * hero, ui16 dest); // TODO: unify classes
 	bool assembleArtifacts(const CGHeroInstance * hero, ArtifactPosition artifactSlot, bool assemble, ArtifactID assembleTo) override;
-	bool buildBuilding(const CGTownInstance *town, BuildingID buildingID) override;
-	void recruitCreatures(const CGDwelling * obj, const CArmedInstance * dst, CreatureID ID, ui32 amount, si32 level=-1) override;
-	bool dismissCreature(const CArmedInstance *obj, SlotID stackPos) override;
-	bool upgradeCreature(const CArmedInstance *obj, SlotID stackPos, CreatureID newID=CreatureID::NONE) override;
+	bool buildBuilding(const CGTownInstance * town, BuildingID buildingID) override;
+	void recruitCreatures(const CGDwelling * obj, const CArmedInstance * dst, CreatureID ID, ui32 amount, si32 level = -1) override;
+	bool dismissCreature(const CArmedInstance * obj, SlotID stackPos) override;
+	bool upgradeCreature(const CArmedInstance * obj, SlotID stackPos, CreatureID newID = CreatureID::NONE) override;
 	void endTurn() override;
-	void swapGarrisonHero(const CGTownInstance *town) override;
-	void buyArtifact(const CGHeroInstance *hero, ArtifactID aid) override;
-	void trade(const CGObjectInstance *market, EMarketMode::EMarketMode mode, int id1, int id2, int val1, const CGHeroInstance *hero = nullptr) override;
+	void swapGarrisonHero(const CGTownInstance * town) override;
+	void buyArtifact(const CGHeroInstance * hero, ArtifactID aid) override;
+	void trade(const CGObjectInstance * market, EMarketMode::EMarketMode mode, int id1, int id2, int val1, const CGHeroInstance * hero = nullptr) override;
 	void setFormation(const CGHeroInstance * hero, bool tight) override;
-	void recruitHero(const CGObjectInstance *townOrTavern, const CGHeroInstance *hero) override;
-	void save(const std::string &fname) override;
-	void sendMessage(const std::string &mess, const CGObjectInstance * currentObject = nullptr) override;
-	void buildBoat(const IShipyard *obj) override;
-	void dig(const CGObjectInstance *hero) override;
-	void castSpell(const CGHeroInstance *hero, SpellID spellID, const int3 &pos = int3(-1, -1, -1)) override;
+	void recruitHero(const CGObjectInstance * townOrTavern, const CGHeroInstance * hero) override;
+	void save(const std::string & fname) override;
+	void sendMessage(const std::string & mess, const CGObjectInstance * currentObject = nullptr) override;
+	void buildBoat(const IShipyard * obj) override;
+	void dig(const CGObjectInstance * hero) override;
+	void castSpell(const CGHeroInstance * hero, SpellID spellID, const int3 & pos = int3(-1, -1, -1)) override;
 
 //friends
 	friend class CClient;

+ 359 - 356
Global.h

@@ -40,12 +40,12 @@ static_assert(sizeof(bool) == 1, "Bool needs to be 1 byte in size.");
 // Based on: http://sourceforge.net/p/predef/wiki/OperatingSystems/
 //	 and on: http://stackoverflow.com/questions/5919996/how-to-detect-reliably-mac-os-x-ios-linux-windows-in-c-preprocessor
 // TODO?: Should be moved to vstd\os_detect.h (and then included by Global.h)
-#ifdef _WIN16			// Defined for 16-bit environments
+#ifdef _WIN16 // Defined for 16-bit environments
 #  error "16-bit Windows isn't supported"
-#elif defined(_WIN64)	// Defined for 64-bit environments
+#elif defined(_WIN64) // Defined for 64-bit environments
 #  define VCMI_WINDOWS
 #  define VCMI_WINDOWS_64
-#elif defined(_WIN32)	// Defined for both 32-bit and 64-bit environments
+#elif defined(_WIN32) // Defined for both 32-bit and 64-bit environments
 #  define VCMI_WINDOWS
 #  define VCMI_WINDOWS_32
 #elif defined(_WIN32_WCE)
@@ -90,8 +90,8 @@ static_assert(sizeof(bool) == 1, "Bool needs to be 1 byte in size.");
 /* Commonly used C++, Boost headers */
 /* ---------------------------------------------------------------------------- */
 #ifdef VCMI_WINDOWS
-#  define WIN32_LEAN_AND_MEAN		// Exclude rarely-used stuff from Windows headers - delete this line if something is missing.
-#  define NOMINMAX					// Exclude min/max macros from <Windows.h>. Use std::[min/max] from <algorithm> instead.
+#  define WIN32_LEAN_AND_MEAN           // Exclude rarely-used stuff from Windows headers - delete this line if something is missing.
+#  define NOMINMAX                                      // Exclude min/max macros from <Windows.h>. Use std::[min/max] from <algorithm> instead.
 #  define _NO_W32_PSEUDO_MODIFIERS  // Exclude more macros for compiling with MinGW on Linux.
 #endif
 
@@ -203,7 +203,7 @@ namespace range = boost::range;
 /* ---------------------------------------------------------------------------- */
 // Integral data types
 typedef uint64_t ui64; //unsigned int 64 bits (8 bytes)
-typedef uint32_t ui32;  //unsigned int 32 bits (4 bytes)
+typedef uint32_t ui32; //unsigned int 32 bits (4 bytes)
 typedef uint16_t ui16; //unsigned int 16 bits (2 bytes)
 typedef uint8_t ui8; //unsigned int 8 bits (1 byte)
 typedef int64_t si64; //signed int 64 bits (8 bytes)
@@ -230,9 +230,9 @@ typedef boost::lock_guard<boost::recursive_mutex> TLockGuardRec;
 #  define ELF_VISIBILITY
 #else
 #  ifdef __GNUC__
-#    define DLL_IMPORT	__attribute__ ((visibility("default")))
-#    define DLL_EXPORT __attribute__ ((visibility("default")))
-#    define ELF_VISIBILITY __attribute__ ((visibility("default")))
+#    define DLL_IMPORT  __attribute__((visibility("default")))
+#    define DLL_EXPORT __attribute__((visibility("default")))
+#    define ELF_VISIBILITY __attribute__((visibility("default")))
 #  endif
 #endif
 
@@ -247,7 +247,7 @@ typedef boost::lock_guard<boost::recursive_mutex> TLockGuardRec;
 #define ASSERT_IF_CALLED_WITH_PLAYER if(!player) {logGlobal->errorStream() << BOOST_CURRENT_FUNCTION; assert(0);}
 
 // can be used for counting arrays
-template<typename T, size_t N> char (&_ArrayCountObj(const T (&)[N]))[N];
+template<typename T, size_t N> char(&_ArrayCountObj(const T(&)[N]))[N];
 #define ARRAY_COUNT(arr)    (sizeof(_ArrayCountObj(arr)))
 
 // should be used for variables that becomes unused in release builds (e.g. only used for assert checks)
@@ -282,8 +282,10 @@ void inline handleException()
 template<typename T>
 std::ostream & operator<<(std::ostream & out, const boost::optional<T> & opt)
 {
-	if(opt) return out << *opt;
-	else return out << "empty";
+	if(opt)
+		return out << *opt;
+	else
+		return out << "empty";
 }
 
 template<typename T>
@@ -293,7 +295,8 @@ std::ostream & operator<<(std::ostream & out, const std::vector<T> & container)
 	for(auto it = container.begin(); it != container.end(); ++it)
 	{
 		out << *it;
-		if(std::prev(container.end()) != it) out << ", ";
+		if(std::prev(container.end()) != it)
+			out << ", ";
 	}
 	return out << "]";
 }
@@ -301,407 +304,407 @@ std::ostream & operator<<(std::ostream & out, const std::vector<T> & container)
 namespace vstd
 {
 
-	// combine hashes. Present in boost but not in std
-	template <class T>
-	inline void hash_combine(std::size_t& seed, const T& v)
-	{
-		std::hash<T> hasher;
-		seed ^= hasher(v) + 0x9e3779b9 + (seed<<6) + (seed>>2);
-	}
-
-	//returns true if container c contains item i
-	template <typename Container, typename Item>
-	bool contains(const Container & c, const Item &i)
-	{
-		return std::find(std::begin(c), std::end(c),i) != std::end(c);
-	}
+// combine hashes. Present in boost but not in std
+template<class T>
+inline void hash_combine(std::size_t & seed, const T & v)
+{
+	std::hash<T> hasher;
+	seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
+}
 
-	//returns true if container c contains item i
-	template <typename Container, typename Pred>
-	bool contains_if(const Container & c, Pred p)
-	{
-		return std::find_if(std::begin(c), std::end(c), p) != std::end(c);
-	}
+//returns true if container c contains item i
+template<typename Container, typename Item>
+bool contains(const Container & c, const Item & i)
+{
+	return std::find(std::begin(c), std::end(c), i) != std::end(c);
+}
 
-	//returns true if map c contains item i
-	template <typename V, typename Item, typename Item2>
-	bool contains(const std::map<Item,V> & c, const Item2 &i)
-	{
-		return c.find(i)!=c.end();
-	}
+//returns true if container c contains item i
+template<typename Container, typename Pred>
+bool contains_if(const Container & c, Pred p)
+{
+	return std::find_if(std::begin(c), std::end(c), p) != std::end(c);
+}
 
-	//returns true if unordered set c contains item i
-	template <typename Item>
-	bool contains(const std::unordered_set<Item> & c, const Item &i)
-	{
-		return c.find(i)!=c.end();
-	}
+//returns true if map c contains item i
+template<typename V, typename Item, typename Item2>
+bool contains(const std::map<Item, V> & c, const Item2 & i)
+{
+	return c.find(i) != c.end();
+}
 
-	template <typename V, typename Item, typename Item2>
-	bool contains(const std::unordered_map<Item,V> & c, const Item2 &i)
-	{
-		return c.find(i)!=c.end();
-	}
+//returns true if unordered set c contains item i
+template<typename Item>
+bool contains(const std::unordered_set<Item> & c, const Item & i)
+{
+	return c.find(i) != c.end();
+}
 
-	//returns position of first element in vector c equal to s, if there is no such element, -1 is returned
-	template <typename Container, typename T2>
-	int find_pos(const Container & c, const T2 &s)
-	{
-		size_t i=0;
-		for (auto iter = std::begin(c); iter != std::end(c); iter++, i++)
-			if(*iter == s)
-				return i;
-		return -1;
-	}
+template<typename V, typename Item, typename Item2>
+bool contains(const std::unordered_map<Item, V> & c, const Item2 & i)
+{
+	return c.find(i) != c.end();
+}
 
-	//Func f tells if element matches
-	template <typename Container, typename Func>
-	int find_pos_if(const Container & c, const Func &f)
-	{
-		auto ret = boost::range::find_if(c, f);
-		if(ret != std::end(c))
-			return std::distance(std::begin(c), ret);
+//returns position of first element in vector c equal to s, if there is no such element, -1 is returned
+template<typename Container, typename T2>
+int find_pos(const Container & c, const T2 & s)
+{
+	size_t i = 0;
+	for(auto iter = std::begin(c); iter != std::end(c); iter++, i++)
+		if(*iter == s)
+			return i;
+	return -1;
+}
 
-		return -1;
-	}
+//Func f tells if element matches
+template<typename Container, typename Func>
+int find_pos_if(const Container & c, const Func & f)
+{
+	auto ret = boost::range::find_if(c, f);
+	if(ret != std::end(c))
+		return std::distance(std::begin(c), ret);
 
-	//returns iterator to the given element if present in container, end() if not
-	template <typename Container, typename Item>
-	typename Container::iterator find(Container & c, const Item &i)
-	{
-		return std::find(c.begin(),c.end(),i);
-	}
+	return -1;
+}
 
-	//returns const iterator to the given element if present in container, end() if not
-	template <typename Container, typename Item>
-	typename Container::const_iterator find(const Container & c, const Item &i)
-	{
-		return std::find(c.begin(),c.end(),i);
-	}
+//returns iterator to the given element if present in container, end() if not
+template<typename Container, typename Item>
+typename Container::iterator find(Container & c, const Item & i)
+{
+	return std::find(c.begin(), c.end(), i);
+}
 
-	//removes element i from container c, returns false if c does not contain i
-	template <typename Container, typename Item>
-	typename Container::size_type operator-=(Container &c, const Item &i)
-	{
-		typename Container::iterator itr = find(c,i);
-		if(itr == c.end())
-			return false;
-		c.erase(itr);
-		return true;
-	}
+//returns const iterator to the given element if present in container, end() if not
+template<typename Container, typename Item>
+typename Container::const_iterator find(const Container & c, const Item & i)
+{
+	return std::find(c.begin(), c.end(), i);
+}
 
-	//assigns greater of (a, b) to a and returns maximum of (a, b)
-	template <typename t1, typename t2>
-	t1 &amax(t1 &a, const t2 &b)
-	{
-		if(a >= b)
-			return a;
-		else
-		{
-			a = b;
-			return a;
-		}
-	}
+//removes element i from container c, returns false if c does not contain i
+template<typename Container, typename Item>
+typename Container::size_type operator-=(Container & c, const Item & i)
+{
+	typename Container::iterator itr = find(c, i);
+	if(itr == c.end())
+		return false;
+	c.erase(itr);
+	return true;
+}
 
-	//assigns smaller of (a, b) to a and returns minimum of (a, b)
-	template <typename t1, typename t2>
-	t1 &amin(t1 &a, const t2 &b)
+//assigns greater of (a, b) to a and returns maximum of (a, b)
+template<typename t1, typename t2>
+t1 & amax(t1 & a, const t2 & b)
+{
+	if(a >= b)
+		return a;
+	else
 	{
-		if(a <= b)
-			return a;
-		else
-		{
-			a = b;
-			return a;
-		}
+		a = b;
+		return a;
 	}
+}
 
-	//makes a to fit the range <b, c>
-	template <typename t1, typename t2, typename t3>
-	t1 &abetween(t1 &a, const t2 &b, const t3 &c)
+//assigns smaller of (a, b) to a and returns minimum of (a, b)
+template<typename t1, typename t2>
+t1 & amin(t1 & a, const t2 & b)
+{
+	if(a <= b)
+		return a;
+	else
 	{
-		amax(a,b);
-		amin(a,c);
+		a = b;
 		return a;
 	}
+}
 
-	//checks if a is between b and c
-	template <typename t1, typename t2, typename t3>
-	bool isbetween(const t1 &value, const t2 &min, const t3 &max)
-	{
-		return value > min && value < max;
-	}
+//makes a to fit the range <b, c>
+template<typename t1, typename t2, typename t3>
+t1 & abetween(t1 & a, const t2 & b, const t3 & c)
+{
+	amax(a, b);
+	amin(a, c);
+	return a;
+}
 
-	//checks if a is within b and c
-	template <typename t1, typename t2, typename t3>
-	bool iswithin(const t1 &value, const t2 &min, const t3 &max)
-	{
-		return value >= min && value <= max;
-	}
+//checks if a is between b and c
+template<typename t1, typename t2, typename t3>
+bool isbetween(const t1 & value, const t2 & min, const t3 & max)
+{
+	return value > min && value < max;
+}
 
-	template <typename t1, typename t2>
-	struct assigner
-	{
-	public:
-		t1 &op1;
-		t2 op2;
-		assigner(t1 &a1, const t2 & a2)
-			:op1(a1), op2(a2)
-		{}
-		void operator()()
-		{
-			op1 = op2;
-		}
-	};
-
-	// Assigns value a2 to a1. The point of time of the real operation can be controlled
-	// with the () operator.
-	template <typename t1, typename t2>
-	assigner<t1,t2> assigno(t1 &a1, const t2 &a2)
-	{
-		return assigner<t1,t2>(a1,a2);
-	}
+//checks if a is within b and c
+template<typename t1, typename t2, typename t3>
+bool iswithin(const t1 & value, const t2 & min, const t3 & max)
+{
+	return value >= min && value <= max;
+}
 
-	//deleted pointer and sets it to nullptr
-	template <typename T>
-	void clear_pointer(T* &ptr)
-	{
-		delete ptr;
-		ptr = nullptr;
-	}
+template<typename t1, typename t2>
+struct assigner
+{
+public:
+	t1 & op1;
+	t2 op2;
+	assigner(t1 & a1, const t2 & a2)
+		: op1(a1), op2(a2)
+	{}
+	void operator()()
+	{
+		op1 = op2;
+	}
+};
+
+// Assigns value a2 to a1. The point of time of the real operation can be controlled
+// with the () operator.
+template<typename t1, typename t2>
+assigner<t1, t2> assigno(t1 & a1, const t2 & a2)
+{
+	return assigner<t1, t2>(a1, a2);
+}
+
+//deleted pointer and sets it to nullptr
+template<typename T>
+void clear_pointer(T * & ptr)
+{
+	delete ptr;
+	ptr = nullptr;
+}
 
 #if _MSC_VER >= 1800
-	using std::make_unique;
+using std::make_unique;
 #else
-	template<typename T>
-	std::unique_ptr<T> make_unique()
-	{
-		return std::unique_ptr<T>(new T());
-	}
-	template<typename T, typename Arg1>
-	std::unique_ptr<T> make_unique(Arg1 &&arg1)
-	{
-		return std::unique_ptr<T>(new T(std::forward<Arg1>(arg1)));
-	}
-	template<typename T, typename Arg1, typename Arg2>
-	std::unique_ptr<T> make_unique(Arg1 &&arg1, Arg2 &&arg2)
-	{
-		return std::unique_ptr<T>(new T(std::forward<Arg1>(arg1), std::forward<Arg2>(arg2)));
-	}
-	template<typename T, typename Arg1, typename Arg2, typename Arg3>
-	std::unique_ptr<T> make_unique(Arg1 &&arg1, Arg2 &&arg2, Arg3 &&arg3)
-	{
-		return std::unique_ptr<T>(new T(std::forward<Arg1>(arg1), std::forward<Arg2>(arg2), std::forward<Arg3>(arg3)));
-	}
-	template<typename T, typename Arg1, typename Arg2, typename Arg3, typename Arg4>
-	std::unique_ptr<T> make_unique(Arg1 &&arg1, Arg2 &&arg2, Arg3 &&arg3, Arg4 &&arg4)
-	{
-		return std::unique_ptr<T>(new T(std::forward<Arg1>(arg1), std::forward<Arg2>(arg2), std::forward<Arg3>(arg3), std::forward<Arg4>(arg4)));
-	}
+template<typename T>
+std::unique_ptr<T> make_unique()
+{
+	return std::unique_ptr<T>(new T());
+}
+template<typename T, typename Arg1>
+std::unique_ptr<T> make_unique(Arg1 && arg1)
+{
+	return std::unique_ptr<T>(new T(std::forward<Arg1>(arg1)));
+}
+template<typename T, typename Arg1, typename Arg2>
+std::unique_ptr<T> make_unique(Arg1 && arg1, Arg2 && arg2)
+{
+	return std::unique_ptr<T>(new T(std::forward<Arg1>(arg1), std::forward<Arg2>(arg2)));
+}
+template<typename T, typename Arg1, typename Arg2, typename Arg3>
+std::unique_ptr<T> make_unique(Arg1 && arg1, Arg2 && arg2, Arg3 && arg3)
+{
+	return std::unique_ptr<T>(new T(std::forward<Arg1>(arg1), std::forward<Arg2>(arg2), std::forward<Arg3>(arg3)));
+}
+template<typename T, typename Arg1, typename Arg2, typename Arg3, typename Arg4>
+std::unique_ptr<T> make_unique(Arg1 && arg1, Arg2 && arg2, Arg3 && arg3, Arg4 && arg4)
+{
+	return std::unique_ptr<T>(new T(std::forward<Arg1>(arg1), std::forward<Arg2>(arg2), std::forward<Arg3>(arg3), std::forward<Arg4>(arg4)));
+}
 #endif
 
-	template <typename Container>
-	typename Container::const_reference circularAt(const Container &r, size_t index)
-	{
-		assert(r.size());
-		index %= r.size();
-		auto itr = std::begin(r);
-		std::advance(itr, index);
-		return *itr;
-	}
+template<typename Container>
+typename Container::const_reference circularAt(const Container & r, size_t index)
+{
+	assert(r.size());
+	index %= r.size();
+	auto itr = std::begin(r);
+	std::advance(itr, index);
+	return *itr;
+}
 
-	template<typename Range, typename Predicate>
-	void erase_if(Range &vec, Predicate pred)
-	{
-		vec.erase(boost::remove_if(vec, pred),vec.end());
-	}
+template<typename Range, typename Predicate>
+void erase_if(Range & vec, Predicate pred)
+{
+	vec.erase(boost::remove_if(vec, pred), vec.end());
+}
 
-	template<typename Elem, typename Predicate>
-	void erase_if(std::set<Elem> &setContainer, Predicate pred)
+template<typename Elem, typename Predicate>
+void erase_if(std::set<Elem> & setContainer, Predicate pred)
+{
+	auto itr = setContainer.begin();
+	auto endItr = setContainer.end();
+	while(itr != endItr)
 	{
-		auto itr = setContainer.begin();
-		auto endItr = setContainer.end();
-		while(itr != endItr)
-		{
-			auto tmpItr = itr++;
-			if(pred(*tmpItr))
-				setContainer.erase(tmpItr);
-		}
+		auto tmpItr = itr++;
+		if(pred(*tmpItr))
+			setContainer.erase(tmpItr);
 	}
+}
 
-	//works for map and std::map, maybe something else
-	template<typename Key, typename Val, typename Predicate>
-	void erase_if(std::map<Key, Val> &container, Predicate pred)
+//works for map and std::map, maybe something else
+template<typename Key, typename Val, typename Predicate>
+void erase_if(std::map<Key, Val> & container, Predicate pred)
+{
+	auto itr = container.begin();
+	auto endItr = container.end();
+	while(itr != endItr)
 	{
-		auto itr = container.begin();
-		auto endItr = container.end();
-		while(itr != endItr)
-		{
-			auto tmpItr = itr++;
-			if(pred(*tmpItr))
-				container.erase(tmpItr);
-		}
+		auto tmpItr = itr++;
+		if(pred(*tmpItr))
+			container.erase(tmpItr);
 	}
+}
 
-	template<typename InputRange, typename OutputIterator, typename Predicate>
-	OutputIterator copy_if(const InputRange &input, OutputIterator result, Predicate pred)
-	{
-		return std::copy_if(boost::const_begin(input), std::end(input), result, pred);
-	}
+template<typename InputRange, typename OutputIterator, typename Predicate>
+OutputIterator copy_if(const InputRange & input, OutputIterator result, Predicate pred)
+{
+	return std::copy_if(boost::const_begin(input), std::end(input), result, pred);
+}
 
-	template <typename Container>
-	std::insert_iterator<Container> set_inserter(Container &c)
-	{
-		return std::inserter(c, c.end());
-	}
+template<typename Container>
+std::insert_iterator<Container> set_inserter(Container & c)
+{
+	return std::inserter(c, c.end());
+}
 
-	//Returns iterator to the element for which the value of ValueFunction is minimal
-	template<class ForwardRange, class ValueFunction>
-	auto minElementByFun(const ForwardRange& rng, ValueFunction vf) -> decltype(std::begin(rng))
-	{
-		/* Clang crashes when instantiating this function template and having PCH compilation enabled.
-		 * There is a bug report here: http://llvm.org/bugs/show_bug.cgi?id=18744
-		 * Current bugfix is to don't use a typedef for decltype(*std::begin(rng)) and to use decltype
-		 * directly for both function parameters.
-		 */
-		return boost::min_element(rng, [&] (decltype(*std::begin(rng)) lhs, decltype(*std::begin(rng)) rhs) -> bool
+//Returns iterator to the element for which the value of ValueFunction is minimal
+template<class ForwardRange, class ValueFunction>
+auto minElementByFun(const ForwardRange & rng, ValueFunction vf)->decltype(std::begin(rng))
+{
+	/* Clang crashes when instantiating this function template and having PCH compilation enabled.
+	 * There is a bug report here: http://llvm.org/bugs/show_bug.cgi?id=18744
+	 * Current bugfix is to don't use a typedef for decltype(*std::begin(rng)) and to use decltype
+	 * directly for both function parameters.
+	 */
+	return boost::min_element(rng, [&](decltype(*std::begin(rng)) lhs, decltype(*std::begin(rng)) rhs) -> bool
 		{
 			return vf(lhs) < vf(rhs);
 		});
-	}
+}
 
-	//Returns iterator to the element for which the value of ValueFunction is maximal
-	template<class ForwardRange, class ValueFunction>
-	auto maxElementByFun(const ForwardRange& rng, ValueFunction vf) -> decltype(std::begin(rng))
-	{
-		/* Clang crashes when instantiating this function template and having PCH compilation enabled.
-		 * There is a bug report here: http://llvm.org/bugs/show_bug.cgi?id=18744
-		 * Current bugfix is to don't use a typedef for decltype(*std::begin(rng)) and to use decltype
-		 * directly for both function parameters.
-		 */
-		return boost::max_element(rng, [&] (decltype(*std::begin(rng)) lhs, decltype(*std::begin(rng)) rhs) -> bool
+//Returns iterator to the element for which the value of ValueFunction is maximal
+template<class ForwardRange, class ValueFunction>
+auto maxElementByFun(const ForwardRange & rng, ValueFunction vf)->decltype(std::begin(rng))
+{
+	/* Clang crashes when instantiating this function template and having PCH compilation enabled.
+	 * There is a bug report here: http://llvm.org/bugs/show_bug.cgi?id=18744
+	 * Current bugfix is to don't use a typedef for decltype(*std::begin(rng)) and to use decltype
+	 * directly for both function parameters.
+	 */
+	return boost::max_element(rng, [&](decltype(*std::begin(rng)) lhs, decltype(*std::begin(rng)) rhs) -> bool
 		{
 			return vf(lhs) < vf(rhs);
 		});
-	}
+}
 
-	template<typename T>
-	void advance(T &obj, int change)
-	{
-		obj = (T)(((int)obj) + change);
-	}
+template<typename T>
+void advance(T & obj, int change)
+{
+	obj = (T)(((int)obj) + change);
+}
 
-	template <typename Container>
-	typename Container::value_type backOrNull(const Container &c) //returns last element of container or nullptr if it is empty (to be used with containers of pointers)
-	{
-		if(c.size())
-			return c.back();
-		else
-			return typename Container::value_type();
-	}
+template<typename Container>
+typename Container::value_type backOrNull(const Container & c) //returns last element of container or nullptr if it is empty (to be used with containers of pointers)
+{
+	if(c.size())
+		return c.back();
+	else
+		return typename Container::value_type();
+}
 
-	template <typename Container>
-	typename Container::value_type frontOrNull(const Container &c) //returns first element of container or nullptr if it is empty (to be used with containers of pointers)
-	{
-		if(c.size())
-			return c.front();
-		else
-			return nullptr;
-	}
+template<typename Container>
+typename Container::value_type frontOrNull(const Container & c) //returns first element of container or nullptr if it is empty (to be used with containers of pointers)
+{
+	if(c.size())
+		return c.front();
+	else
+		return nullptr;
+}
 
-	template <typename Container, typename Index>
-	bool isValidIndex(const Container &c, Index i)
-	{
-		return i >= 0  &&  i < c.size();
-	}
+template<typename Container, typename Index>
+bool isValidIndex(const Container & c, Index i)
+{
+	return i >= 0 && i < c.size();
+}
 
-	template <typename Container, typename Index>
-	boost::optional<typename Container::const_reference> tryAt(const Container &c, Index i)
+template<typename Container, typename Index>
+boost::optional<typename Container::const_reference> tryAt(const Container & c, Index i)
+{
+	if(isValidIndex(c, i))
 	{
-		if(isValidIndex(c, i))
-		{
-			auto itr = c.begin();
-			std::advance(itr, i);
-			return *itr;
-		}
-		return boost::none;
+		auto itr = c.begin();
+		std::advance(itr, i);
+		return *itr;
 	}
+	return boost::none;
+}
 
-	template <typename Container, typename Pred>
-	static boost::optional<typename Container::const_reference> tryFindIf(const Container &r, const Pred &t)
-	{
-		auto pos = range::find_if(r, t);
-		if(pos == boost::end(r))
-			return boost::none;
-		else
-			return *pos;
-	}
+template<typename Container, typename Pred>
+static boost::optional<typename Container::const_reference> tryFindIf(const Container & r, const Pred & t)
+{
+	auto pos = range::find_if(r, t);
+	if(pos == boost::end(r))
+		return boost::none;
+	else
+		return *pos;
+}
 
-	template <typename Container>
-	typename Container::const_reference atOrDefault(const Container &r, size_t index, const typename Container::const_reference &defaultValue)
-	{
-		if(index < r.size())
-			return r[index];
+template<typename Container>
+typename Container::const_reference atOrDefault(const Container & r, size_t index, const typename Container::const_reference & defaultValue)
+{
+	if(index < r.size())
+		return r[index];
 
-		return defaultValue;
-	}
+	return defaultValue;
+}
 
-	template <typename Container, typename Item>
-	bool erase_if_present(Container &c, const Item &item)
+template<typename Container, typename Item>
+bool erase_if_present(Container & c, const Item & item)
+{
+	auto i = std::find(c.begin(), c.end(), item);
+	if(i != c.end())
 	{
-		auto i = std::find(c.begin(), c.end(), item);
-		if (i != c.end())
-		{
-			c.erase(i);
-			return true;
-		}
-
-		return false;
+		c.erase(i);
+		return true;
 	}
 
-	template <typename V, typename Item, typename Item2>
-	bool erase_if_present(std::map<Item,V> & c, const Item2 &item)
-	{
-		auto i = c.find(item);
-		if (i != c.end())
-		{
-			c.erase(i);
-			return true;
-		}
-		return false;
-	}
+	return false;
+}
 
-	template <typename Container, typename Pred>
-	void erase(Container &c, Pred pred)
+template<typename V, typename Item, typename Item2>
+bool erase_if_present(std::map<Item, V> & c, const Item2 & item)
+{
+	auto i = c.find(item);
+	if(i != c.end())
 	{
-		c.erase(boost::remove_if(c, pred), c.end());
+		c.erase(i);
+		return true;
 	}
+	return false;
+}
 
-	template<typename T>
-	void removeDuplicates(std::vector<T> &vec)
-	{
-		boost::sort(vec);
-		vec.erase(std::unique(vec.begin(), vec.end()), vec.end());
-	}
+template<typename Container, typename Pred>
+void erase(Container & c, Pred pred)
+{
+	c.erase(boost::remove_if(c, pred), c.end());
+}
 
-	template <typename T>
-	void concatenate(std::vector<T> &dest, const std::vector<T> &src)
-	{
-		dest.reserve(dest.size() + src.size());
-		dest.insert(dest.end(), src.begin(), src.end());
-	}
+template<typename T>
+void removeDuplicates(std::vector<T> & vec)
+{
+	boost::sort(vec);
+	vec.erase(std::unique(vec.begin(), vec.end()), vec.end());
+}
 
-	template <typename T>
-	std::vector<T> intersection(std::vector<T> &v1, std::vector<T> &v2)
-	{
-		std::vector<T> v3;
-		std::sort(v1.begin(), v1.end());
-		std::sort(v2.begin(), v2.end());
-		std::set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), std::back_inserter(v3));
-		return v3;
-	}
+template<typename T>
+void concatenate(std::vector<T> & dest, const std::vector<T> & src)
+{
+	dest.reserve(dest.size() + src.size());
+	dest.insert(dest.end(), src.begin(), src.end());
+}
+
+template<typename T>
+std::vector<T> intersection(std::vector<T> & v1, std::vector<T> & v2)
+{
+	std::vector<T> v3;
+	std::sort(v1.begin(), v1.end());
+	std::sort(v2.begin(), v2.end());
+	std::set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), std::back_inserter(v3));
+	return v3;
+}
 
-	using boost::math::round;
+using boost::math::round;
 }
 using vstd::operator-=;
 using vstd::make_unique;
@@ -709,12 +712,12 @@ using vstd::make_unique;
 #ifdef NO_STD_TOSTRING
 namespace std
 {
-	template <typename T>
-	inline std::string to_string(const T& value)
-	{
-		std::ostringstream ss;
-		ss << value;
-		return ss.str();
-	}
+template<typename T>
+inline std::string to_string(const T & value)
+{
+	std::ostringstream ss;
+	ss << value;
+	return ss.str();
+}
 }
 #endif // NO_STD_TOSTRING

+ 47 - 44
client/CBitmapHandler.cpp

@@ -18,17 +18,17 @@
 
 namespace BitmapHandler
 {
-	SDL_Surface * loadH3PCX(ui8 * data, size_t size);
+SDL_Surface * loadH3PCX(ui8 * data, size_t size);
 
-	SDL_Surface * loadBitmapFromDir(std::string path, std::string fname, bool setKey=true);
+SDL_Surface * loadBitmapFromDir(std::string path, std::string fname, bool setKey = true);
 }
 
-bool isPCX(const ui8 *header)//check whether file can be PCX according to header
+bool isPCX(const ui8 * header) //check whether file can be PCX according to header
 {
-	int fSize  = read_le_u32(header + 0);
-	int width  = read_le_u32(header + 4);
+	int fSize = read_le_u32(header + 0);
+	int width = read_le_u32(header + 4);
 	int height = read_le_u32(header + 8);
-	return fSize == width*height || fSize == width*height*3;
+	return fSize == width * height || fSize == width * height * 3;
 }
 
 enum Epcxformat
@@ -42,33 +42,36 @@ SDL_Surface * BitmapHandler::loadH3PCX(ui8 * pcx, size_t size)
 	SDL_Surface * ret;
 
 	Epcxformat format;
-	int it=0;
-
-	ui32 fSize = read_le_u32(pcx + it); it+=4;
-	ui32 width = read_le_u32(pcx + it); it+=4;
-	ui32 height = read_le_u32(pcx + it); it+=4;
-
-	if (fSize==width*height*3)
-		format=PCX24B;
-	else if (fSize==width*height)
-		format=PCX8B;
+	int it = 0;
+
+	ui32 fSize = read_le_u32(pcx + it);
+	it += 4;
+	ui32 width = read_le_u32(pcx + it);
+	it += 4;
+	ui32 height = read_le_u32(pcx + it);
+	it += 4;
+
+	if(fSize == width * height * 3)
+		format = PCX24B;
+	else if(fSize == width * height)
+		format = PCX8B;
 	else
 		return nullptr;
 
-	if (format==PCX8B)
+	if(format == PCX8B)
 	{
 		ret = SDL_CreateRGBSurface(SDL_SWSURFACE, width, height, 8, 0, 0, 0, 0);
 
 		it = 0xC;
-		for (int i=0; i<height; i++)
+		for(int i = 0; i < height; i++)
 		{
-			memcpy((char*)ret->pixels + ret->pitch * i, pcx + it, width);
-			it+= width;
+			memcpy((char *)ret->pixels + ret->pitch * i, pcx + it, width);
+			it += width;
 		}
 
 		//palette - last 256*3 bytes
-		it = size-256*3;
-		for (int i=0;i<256;i++)
+		it = size - 256 * 3;
+		for(int i = 0; i < 256; i++)
 		{
 			SDL_Color tp;
 			tp.r = pcx[it++];
@@ -92,10 +95,10 @@ SDL_Surface * BitmapHandler::loadH3PCX(ui8 * pcx, size_t size)
 		ret = SDL_CreateRGBSurface(SDL_SWSURFACE, width, height, 24, rmask, gmask, bmask, 0);
 
 		//it == 0xC;
-		for (int i=0; i<height; i++)
+		for(int i = 0; i < height; i++)
 		{
-			memcpy((char*)ret->pixels + ret->pitch * i, pcx + it, width*3);
-			it+= width*3;
+			memcpy((char *)ret->pixels + ret->pitch * i, pcx + it, width * 3);
+			it += width * 3;
 		}
 
 	}
@@ -109,43 +112,43 @@ SDL_Surface * BitmapHandler::loadBitmapFromDir(std::string path, std::string fna
 		logGlobal->warnStream() << "Call to loadBitmap with void fname!";
 		return nullptr;
 	}
-	if (!CResourceHandler::get()->existsResource(ResourceID(path + fname, EResType::IMAGE)))
+	if(!CResourceHandler::get()->existsResource(ResourceID(path + fname, EResType::IMAGE)))
 	{
 		return nullptr;
 	}
 
-	SDL_Surface * ret=nullptr;
+	SDL_Surface * ret = nullptr;
 
 	auto readFile = CResourceHandler::get()->load(ResourceID(path + fname, EResType::IMAGE))->readAll();
 
-	if (isPCX(readFile.first.get()))
-	{//H3-style PCX
+	if(isPCX(readFile.first.get()))
+	{ //H3-style PCX
 		ret = loadH3PCX(readFile.first.get(), readFile.second);
-		if (ret)
+		if(ret)
 		{
-			if(ret->format->BytesPerPixel == 1  &&  setKey)
+			if(ret->format->BytesPerPixel == 1 && setKey)
 			{
-				CSDL_Ext::setColorKey(ret,ret->format->palette->colors[0]);
+				CSDL_Ext::setColorKey(ret, ret->format->palette->colors[0]);
 			}
 		}
 		else
 		{
-			logGlobal->errorStream()<<"Failed to open "<<fname<<" as H3 PCX!";
+			logGlobal->errorStream() << "Failed to open " << fname << " as H3 PCX!";
 			return nullptr;
 		}
 	}
 	else
 	{ //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),
-		          1); // mark it for auto-deleting
-		if (ret)
+				//create SDL_RW with our data (will be deleted by SDL)
+				SDL_RWFromConstMem((void *)readFile.first.get(), readFile.second),
+				1); // mark it for auto-deleting
+		if(ret)
 		{
-			if (ret->format->palette)
+			if(ret->format->palette)
 			{
 				//set correct value for alpha\unused channel
-				for (int i=0; i < ret->format->palette->ncolors; i++)
+				for(int i = 0; i < ret->format->palette->ncolors; i++)
 					ret->format->palette->colors[i].a = SDL_ALPHA_OPAQUE;
 			}
 		}
@@ -161,11 +164,11 @@ SDL_Surface * BitmapHandler::loadBitmapFromDir(std::string path, std::string fna
 	// 1) Vampire mansion in Necropolis (not 1st color is transparent)
 	// 2) Battle background when fighting on grass/dirt, topmost sky part (NO transparent color)
 	// 3) New objects that may use 24-bit images for icons (e.g. witchking arts)
-	if (ret->format->palette)
+	if(ret->format->palette)
 	{
 		CSDL_Ext::setDefaultColorKeyPresize(ret);
 	}
-	else if (ret->format->Amask)
+	else if(ret->format->Amask)
 	{
 		SDL_SetSurfaceBlendMode(ret, SDL_BLENDMODE_BLEND);
 	}
@@ -178,10 +181,10 @@ SDL_Surface * BitmapHandler::loadBitmapFromDir(std::string path, std::string fna
 
 SDL_Surface * BitmapHandler::loadBitmap(std::string fname, bool setKey)
 {
-	SDL_Surface *bitmap;
+	SDL_Surface * bitmap;
 
-	if (!(bitmap = loadBitmapFromDir("DATA/", fname, setKey)) &&
-		!(bitmap = loadBitmapFromDir("SPRITES/", fname, setKey)))
+	if(!(bitmap = loadBitmapFromDir("DATA/", fname, setKey)) &&
+	   !(bitmap = loadBitmapFromDir("SPRITES/", fname, setKey)))
 	{
 		logGlobal->errorStream() << "Error: Failed to find file " << fname;
 	}

+ 2 - 2
client/CBitmapHandler.h

@@ -13,6 +13,6 @@ struct SDL_Surface;
 
 namespace BitmapHandler
 {
-	//Load file from /DATA or /SPRITES
-	SDL_Surface * loadBitmap(std::string fname, bool setKey=true);
+//Load file from /DATA or /SPRITES
+SDL_Surface * loadBitmap(std::string fname, bool setKey = true);
 }

+ 104 - 102
client/CDefHandler.cpp

@@ -19,10 +19,11 @@
 #ifdef unused
 static long long pow(long long a, int b)
 {
-	if (!b) return 1;
+	if(!b)
+		return 1;
 	long c = a;
-	while (--b)
-		a*=c;
+	while(--b)
+		a *= c;
 	return a;
 }
 #endif
@@ -33,14 +34,14 @@ CDefHandler::CDefHandler()
 }
 CDefHandler::~CDefHandler()
 {
-	if (notFreeImgs)
+	if(notFreeImgs)
 		return;
-	for (auto & elem : ourImages)
+	for(auto & elem : ourImages)
 	{
-		if (elem.bitmap)
+		if(elem.bitmap)
 		{
 			SDL_FreeSurface(elem.bitmap);
-			elem.bitmap=nullptr;
+			elem.bitmap = nullptr;
 		}
 	}
 }
@@ -50,11 +51,11 @@ CDefEssential::~CDefEssential()
 		SDL_FreeSurface(elem.bitmap);
 }
 
-void CDefHandler::openFromMemory(ui8 *table, const std::string & name)
+void CDefHandler::openFromMemory(ui8 * table, const std::string & name)
 {
 	SDL_Color palette[256];
-	SDefEntry &de = * reinterpret_cast<SDefEntry *>(table);
-	ui8 *p;
+	SDefEntry & de = *reinterpret_cast<SDefEntry *>(table);
+	ui8 * p;
 
 	defName = name;
 	DEFType = read_le_u32(&de.DEFType);
@@ -62,45 +63,45 @@ void CDefHandler::openFromMemory(ui8 *table, const std::string & name)
 	height = read_le_u32(&de.height);
 	ui32 totalBlocks = read_le_u32(&de.totalBlocks);
 
-	for (ui32 it=0;it<256;it++)
+	for(ui32 it = 0; it < 256; it++)
 	{
 		palette[it].r = de.palette[it].R;
 		palette[it].g = de.palette[it].G;
 		palette[it].b = de.palette[it].B;
-		palette[it].a = SDL_ALPHA_OPAQUE;	
+		palette[it].a = SDL_ALPHA_OPAQUE;
 	}
 
 	// The SDefEntryBlock starts just after the SDefEntry
 	p = reinterpret_cast<ui8 *>(&de);
 	p += sizeof(de);
 
-	int totalEntries=0;
-	for (ui32 z=0; z<totalBlocks; z++)
+	int totalEntries = 0;
+	for(ui32 z = 0; z < totalBlocks; z++)
 	{
-		SDefEntryBlock &block = * reinterpret_cast<SDefEntryBlock *>(p);
+		SDefEntryBlock & block = *reinterpret_cast<SDefEntryBlock *>(p);
 		ui32 totalInBlock;
 
 		totalInBlock = read_le_u32(&block.totalInBlock);
 
-		for (ui32 j=SEntries.size(); j<totalEntries+totalInBlock; j++)
+		for(ui32 j = SEntries.size(); j < totalEntries + totalInBlock; j++)
 			SEntries.push_back(SEntry());
 
 		p = block.data;
-		for (ui32 j=0; j<totalInBlock; j++)
+		for(ui32 j = 0; j < totalInBlock; j++)
 		{
 			char Buffer[13];
 			memcpy(Buffer, p, 12);
 			Buffer[12] = 0;
-			SEntries[totalEntries+j].name=Buffer;
+			SEntries[totalEntries + j].name = Buffer;
 			p += 13;
 		}
-		for (ui32 j=0; j<totalInBlock; j++)
+		for(ui32 j = 0; j < totalInBlock; j++)
 		{
-			SEntries[totalEntries+j].offset = read_le_u32(p);
+			SEntries[totalEntries + j].offset = read_le_u32(p);
 			p += 4;
 		}
 		//totalEntries+=totalInBlock;
-		for(ui32 hh=0; hh<totalInBlock; ++hh)
+		for(ui32 hh = 0; hh < totalInBlock; ++hh)
 		{
 			SEntries[totalEntries].group = z;
 			++totalEntries;
@@ -109,10 +110,10 @@ void CDefHandler::openFromMemory(ui8 *table, const std::string & name)
 
 	for(auto & elem : SEntries)
 	{
-		elem.name = elem.name.substr(0, elem.name.find('.')+4);
+		elem.name = elem.name.substr(0, elem.name.find('.') + 4);
 	}
 	//RWEntries = new ui32[height];
-	for(ui32 i=0; i < SEntries.size(); ++i)
+	for(ui32 i = 0; i < SEntries.size(); ++i)
 	{
 		Cimage nimg;
 		nimg.bitmap = getSprite(i, table, palette);
@@ -122,23 +123,23 @@ void CDefHandler::openFromMemory(ui8 *table, const std::string & name)
 	}
 }
 
-SDL_Surface * CDefHandler::getSprite (int SIndex, const ui8 * FDef, const SDL_Color * palette) const
+SDL_Surface * CDefHandler::getSprite(int SIndex, const ui8 * FDef, const SDL_Color * palette) const
 {
-	SDL_Surface * ret=nullptr;
+	SDL_Surface * ret = nullptr;
 
 	ui32 BaseOffset,
-		SpriteWidth, SpriteHeight, //format of sprite
-		TotalRowLength,			// length of read segment
-		add, FullHeight,FullWidth,
-		RowAdd,
-		defType2;
+	     SpriteWidth, SpriteHeight, //format of sprite
+	     TotalRowLength, // length of read segment
+	     add, FullHeight, FullWidth,
+	     RowAdd,
+	     defType2;
 	int LeftMargin, RightMargin, TopMargin, BottomMargin;
 
 
 	ui8 SegmentType;
 
 	BaseOffset = SEntries[SIndex].offset;
-	SSpriteDef sd = * reinterpret_cast<const SSpriteDef *>(FDef + BaseOffset);
+	SSpriteDef sd = *reinterpret_cast<const SSpriteDef *>(FDef + BaseOffset);
 
 	defType2 = read_le_u32(&sd.defType2);
 	FullWidth = read_le_u32(&sd.FullWidth);
@@ -152,59 +153,60 @@ SDL_Surface * CDefHandler::getSprite (int SIndex, const ui8 * FDef, const SDL_Co
 
 	//if(LeftMargin + RightMargin < 0)
 	//	SpriteWidth += LeftMargin + RightMargin; //ugly construction... TODO: check how to do it nicer
-	if(LeftMargin<0)
-		SpriteWidth+=LeftMargin;
-	if(RightMargin<0)
-		SpriteWidth+=RightMargin;
+	if(LeftMargin < 0)
+		SpriteWidth += LeftMargin;
+	if(RightMargin < 0)
+		SpriteWidth += RightMargin;
 
 	// Note: this looks bogus because we allocate only FullWidth, not FullWidth+add
-	add = 4 - FullWidth%4;
-	if (add==4)
-		add=0;
+	add = 4 - FullWidth % 4;
+	if(add == 4)
+		add = 0;
 
 	ret = SDL_CreateRGBSurface(SDL_SWSURFACE, FullWidth, FullHeight, 8, 0, 0, 0, 0);
-	
+
 	if(nullptr == ret)
 	{
-		logGlobal->errorStream() << __FUNCTION__ <<": Unable to create surface";
+		logGlobal->errorStream() << __FUNCTION__ << ": Unable to create surface";
 		logGlobal->errorStream() << FullWidth << "X" << FullHeight;
 		logGlobal->errorStream() << SDL_GetError();
-		throw std::runtime_error("Unable to create surface");		
+		throw std::runtime_error("Unable to create surface");
 	}
 
 	BaseOffset += sizeof(SSpriteDef);
 	int BaseOffsetor = BaseOffset;
-	
-	SDL_Palette * p = SDL_AllocPalette(256);	
+
+	SDL_Palette * p = SDL_AllocPalette(256);
 	SDL_SetPaletteColors(p, palette, 0, 256);
 	SDL_SetSurfacePalette(ret, p);
-	SDL_FreePalette(p);	
+	SDL_FreePalette(p);
 
-	int ftcp=0;
+	int ftcp = 0;
 
 	// If there's a margin anywhere, just blank out the whole surface.
-	if (TopMargin > 0 || BottomMargin > 0 || LeftMargin > 0 || RightMargin > 0) {
-		memset( reinterpret_cast<char*>(ret->pixels), 0, FullHeight*FullWidth);
+	if(TopMargin > 0 || BottomMargin > 0 || LeftMargin > 0 || RightMargin > 0)
+	{
+		memset(reinterpret_cast<char *>(ret->pixels), 0, FullHeight * FullWidth);
 	}
 
 	// Skip top margin
-	if (TopMargin > 0)
-		ftcp += TopMargin*(FullWidth+add);
+	if(TopMargin > 0)
+		ftcp += TopMargin * (FullWidth + add);
 
 	switch(defType2)
 	{
 	case 0:
 	{
-		for (ui32 i=0;i<SpriteHeight;i++)
+		for(ui32 i = 0; i < SpriteHeight; i++)
 		{
-			if (LeftMargin>0)
+			if(LeftMargin > 0)
 				ftcp += LeftMargin;
 
-			memcpy(reinterpret_cast<char*>(ret->pixels)+ftcp, &FDef[BaseOffset], SpriteWidth);
+			memcpy(reinterpret_cast<char *>(ret->pixels) + ftcp, &FDef[BaseOffset], SpriteWidth);
 			ftcp += SpriteWidth;
 			BaseOffset += SpriteWidth;
 
-			if (RightMargin>0)
+			if(RightMargin > 0)
 				ftcp += RightMargin;
 		}
 	}
@@ -212,42 +214,43 @@ SDL_Surface * CDefHandler::getSprite (int SIndex, const ui8 * FDef, const SDL_Co
 
 	case 1:
 	{
-		const ui32 * RWEntriesLoc = reinterpret_cast<const ui32 *>(FDef+BaseOffset);
+		const ui32 * RWEntriesLoc = reinterpret_cast<const ui32 *>(FDef + BaseOffset);
 		BaseOffset += sizeof(int) * SpriteHeight;
-		for (ui32 i=0;i<SpriteHeight;i++)
+		for(ui32 i = 0; i < SpriteHeight; i++)
 		{
-			BaseOffset=BaseOffsetor + read_le_u32(RWEntriesLoc + i);
-			if (LeftMargin>0)
+			BaseOffset = BaseOffsetor + read_le_u32(RWEntriesLoc + i);
+			if(LeftMargin > 0)
 				ftcp += LeftMargin;
 
-			TotalRowLength=0;
+			TotalRowLength = 0;
 			do
 			{
 				ui32 SegmentLength;
 
-				SegmentType=FDef[BaseOffset++];
-				SegmentLength=FDef[BaseOffset++] + 1;
+				SegmentType = FDef[BaseOffset++];
+				SegmentLength = FDef[BaseOffset++] + 1;
 
-				if (SegmentType==0xFF)
+				if(SegmentType == 0xFF)
 				{
-					memcpy(reinterpret_cast<char*>(ret->pixels)+ftcp, FDef + BaseOffset, SegmentLength);
-					BaseOffset+=SegmentLength;
+					memcpy(reinterpret_cast<char *>(ret->pixels) + ftcp, FDef + BaseOffset, SegmentLength);
+					BaseOffset += SegmentLength;
 				}
 				else
 				{
-					memset(reinterpret_cast<char*>(ret->pixels)+ftcp, SegmentType, SegmentLength);
+					memset(reinterpret_cast<char *>(ret->pixels) + ftcp, SegmentType, SegmentLength);
 				}
 				ftcp += SegmentLength;
 				TotalRowLength += SegmentLength;
-			}while(TotalRowLength<SpriteWidth);
+			}
+			while(TotalRowLength < SpriteWidth);
 
-			RowAdd=SpriteWidth-TotalRowLength;
+			RowAdd = SpriteWidth - TotalRowLength;
 
-			if (RightMargin>0)
+			if(RightMargin > 0)
 				ftcp += RightMargin;
 
-			if (add>0)
-				ftcp += add+RowAdd;
+			if(add > 0)
+				ftcp += add + RowAdd;
 		}
 	}
 	break;
@@ -256,84 +259,84 @@ SDL_Surface * CDefHandler::getSprite (int SIndex, const ui8 * FDef, const SDL_Co
 	{
 		BaseOffset = BaseOffsetor + read_le_u16(FDef + BaseOffsetor);
 
-		for (ui32 i=0;i<SpriteHeight;i++)
+		for(ui32 i = 0; i < SpriteHeight; i++)
 		{
 			//BaseOffset = BaseOffsetor+RWEntries[i];
-			if (LeftMargin>0)
+			if(LeftMargin > 0)
 				ftcp += LeftMargin;
 
-			TotalRowLength=0;
-
+			TotalRowLength = 0;
 			do
 			{
-				SegmentType=FDef[BaseOffset++];
+				SegmentType = FDef[BaseOffset++];
 				ui8 code = SegmentType / 32;
 				ui8 value = (SegmentType & 31) + 1;
-				if(code==7)
+				if(code == 7)
 				{
-					memcpy(reinterpret_cast<char*>(ret->pixels)+ftcp, &FDef[BaseOffset], value);
+					memcpy(reinterpret_cast<char *>(ret->pixels) + ftcp, &FDef[BaseOffset], value);
 					ftcp += value;
 					BaseOffset += value;
 				}
 				else
 				{
-					memset(reinterpret_cast<char*>(ret->pixels)+ftcp, code, value);
+					memset(reinterpret_cast<char *>(ret->pixels) + ftcp, code, value);
 					ftcp += value;
 				}
-				TotalRowLength+=value;
-			} while(TotalRowLength<SpriteWidth);
+				TotalRowLength += value;
+			}
+			while(TotalRowLength < SpriteWidth);
 
-			if (RightMargin>0)
+			if(RightMargin > 0)
 				ftcp += RightMargin;
 
-			RowAdd=SpriteWidth-TotalRowLength;
+			RowAdd = SpriteWidth - TotalRowLength;
 
-			if (add>0)
-				ftcp += add+RowAdd;
+			if(add > 0)
+				ftcp += add + RowAdd;
 		}
 	}
 	break;
 
 	case 3:
 	{
-		for (ui32 i=0;i<SpriteHeight;i++)
+		for(ui32 i = 0; i < SpriteHeight; i++)
 		{
-			BaseOffset = BaseOffsetor + read_le_u16(FDef + BaseOffsetor+i*2*(SpriteWidth/32));
-			if (LeftMargin>0)
+			BaseOffset = BaseOffsetor + read_le_u16(FDef + BaseOffsetor + i * 2 * (SpriteWidth / 32));
+			if(LeftMargin > 0)
 				ftcp += LeftMargin;
 
-			TotalRowLength=0;
-
+			TotalRowLength = 0;
 			do
 			{
-				SegmentType=FDef[BaseOffset++];
+				SegmentType = FDef[BaseOffset++];
 				ui8 code = SegmentType / 32;
 				ui8 value = (SegmentType & 31) + 1;
 
 				int len = std::min<ui32>(value, SpriteWidth - TotalRowLength) - std::max(0, -LeftMargin);
 				vstd::amax(len, 0);
 
-				if(code==7)
+				if(code == 7)
 				{
-					memcpy((ui8*)ret->pixels + ftcp, FDef + BaseOffset, len);
+					memcpy((ui8 *)ret->pixels + ftcp, FDef + BaseOffset, len);
 					ftcp += len;
 					BaseOffset += len;
 				}
 				else
 				{
-					memset((ui8*)ret->pixels + ftcp, code, len);
+					memset((ui8 *)ret->pixels + ftcp, code, len);
 					ftcp += len;
 				}
-				TotalRowLength+=( LeftMargin>=0 ? value : value+LeftMargin );
-			}while(TotalRowLength<SpriteWidth);
+				TotalRowLength += (LeftMargin >= 0 ? value : value + LeftMargin);
+			}
+			while(TotalRowLength < SpriteWidth);
 
-			if (RightMargin>0)
+			if(RightMargin > 0)
 				ftcp += RightMargin;
 
-			RowAdd=SpriteWidth-TotalRowLength;
+			RowAdd = SpriteWidth - TotalRowLength;
 
-			if (add>0)
-				ftcp += add+RowAdd;
+			if(add > 0)
+				ftcp += add + RowAdd;
 		}
 	}
 	break;
@@ -344,8 +347,8 @@ SDL_Surface * CDefHandler::getSprite (int SIndex, const ui8 * FDef, const SDL_Co
 	}
 
 	SDL_Color ttcol = ret->format->palette->colors[0];
-	Uint32 keycol = SDL_MapRGBA(ret->format, ttcol.r, ttcol.b, ttcol.g, ttcol.a);	
-	SDL_SetColorKey(ret, SDL_TRUE, keycol);	
+	Uint32 keycol = SDL_MapRGBA(ret->format, ttcol.r, ttcol.b, ttcol.g, ttcol.a);
+	SDL_SetColorKey(ret, SDL_TRUE, keycol);
 
 	return ret;
 }
@@ -365,7 +368,7 @@ CDefHandler * CDefHandler::giveDef(const std::string & defName)
 	auto data = CResourceHandler::get()->load(resID)->readAll().first;
 	if(!data)
 		throw std::runtime_error("bad def name!");
-	auto   nh = new CDefHandler();
+	auto nh = new CDefHandler();
 	nh->openFromMemory(data.get(), defName);
 	return nh;
 }
@@ -377,4 +380,3 @@ CDefEssential * CDefHandler::giveDefEss(const std::string & defName)
 	delete temp;
 	return ret;
 }
-

+ 9 - 7
client/CDefHandler.h

@@ -41,7 +41,8 @@ struct SDefEntry
 	ui32 height;
 	ui32 totalBlocks;
 
-	struct {
+	struct
+	{
 		ui8 R;
 		ui8 G;
 		ui8 B;
@@ -82,11 +83,12 @@ private:
 		std::string name;
 		int offset;
 		int group;
-	} ;
-	std::vector<SEntry> SEntries ;
-	
-	void openFromMemory(ui8 * table, const std::string & name);	
-	SDL_Surface * getSprite (int SIndex, const ui8 * FDef, const SDL_Color * palette) const;
+	};
+	std::vector<SEntry> SEntries;
+
+	void openFromMemory(ui8 * table, const std::string & name);
+	SDL_Surface * getSprite(int SIndex, const ui8 * FDef, const SDL_Color * palette) const;
+
 public:
 	int width, height; //width and height
 	std::string defName;
@@ -95,7 +97,7 @@ public:
 
 	CDefHandler();
 	~CDefHandler();
-	
+
 	CDefEssential * essentialize();
 
 	static CDefHandler * giveDef(const std::string & defName);

+ 5 - 1
client/CGameInfo.h

@@ -34,6 +34,7 @@ class CMap;
 
 
 //a class for non-mechanical client GUI classes
+
 class CClientState
 {
 public:
@@ -43,10 +44,12 @@ public:
 	CCursorHandler * curh;
 	IMainVideoPlayer * videoh;
 };
+
 extern CClientState * CCS;
 
 /// CGameInfo class
 /// for allowing different functions for accessing game informations
+
 class CGameInfo
 {
 public:
@@ -67,4 +70,5 @@ public:
 
 	CGameInfo();
 };
-extern const CGameInfo* CGI;
+
+extern const CGameInfo * CGI;

+ 202 - 203
client/CMT.cpp

@@ -75,7 +75,7 @@ namespace bfs = boost::filesystem;
 std::string NAME_AFFIX = "client";
 std::string NAME = GameConstants::VCMI_VERSION + std::string(" (") + NAME_AFFIX + ')'; //application name
 CGuiHandler GH;
-static CClient *client = nullptr;
+static CClient * client = nullptr;
 
 int preferredDriverIndex = -1;
 SDL_Window * mainWindow = nullptr;
@@ -84,9 +84,9 @@ SDL_Texture * screenTexture = nullptr;
 
 extern boost::thread_specific_ptr<bool> inGuiThread;
 
-SDL_Surface *screen = nullptr, //main screen surface
-	*screen2 = nullptr, //and hlp surface (used to store not-active interfaces layer)
-	*screenBuf = screen; //points to screen (if only advmapint is present) or screen2 (else) - should be used when updating controls which are not regularly redrawed
+SDL_Surface * screen = nullptr, //main screen surface
+	    * screen2 = nullptr, //and hlp surface (used to store not-active interfaces layer)
+	    * screenBuf = screen; //points to screen (if only advmapint is present) or screen2 (else) - should be used when updating controls which are not regularly redrawed
 
 std::queue<SDL_Event> events;
 boost::mutex eventsM;
@@ -97,13 +97,13 @@ static po::variables_map vm;
 //static bool setResolution = false; //set by event handling thread after resolution is adjusted
 
 static bool ermInteractiveMode = false; //structurize when time is right
-void processCommand(const std::string &message);
-static void setScreenRes(int w, int h, int bpp, bool fullscreen, int displayIndex, bool resetVideo=true);
+void processCommand(const std::string & message);
+static void setScreenRes(int w, int h, int bpp, bool fullscreen, int displayIndex, bool resetVideo = true);
 void dispose();
 void playIntro();
 static void mainLoop();
 //void requestChangingResolution();
-void startGame(StartInfo * options, CConnection *serv = nullptr);
+void startGame(StartInfo * options, CConnection * serv = nullptr);
 void endGame();
 
 #ifndef VCMI_WINDOWS
@@ -113,16 +113,16 @@ void endGame();
 #include <getopt.h>
 #endif
 
-void startTestMap(const std::string &mapname)
+void startTestMap(const std::string & mapname)
 {
 	StartInfo si;
 	si.mapname = mapname;
 	si.mode = StartInfo::NEW_GAME;
-	for (int i = 0; i < 8; i++)
+	for(int i = 0; i < 8; i++)
 	{
-		PlayerSettings &pset = si.playerInfos[PlayerColor(i)];
+		PlayerSettings & pset = si.playerInfos[PlayerColor(i)];
 		pset.color = PlayerColor(i);
-		pset.name = CGI->generaltexth->allTexts[468];//Computer
+		pset.name = CGI->generaltexth->allTexts[468]; //Computer
 		pset.playerID = PlayerSettings::PLAYER_AI;
 		pset.compOnly = true;
 		pset.castle = 0;
@@ -136,7 +136,7 @@ void startTestMap(const std::string &mapname)
 	startGame(&si);
 }
 
-void startGameFromFile(const bfs::path &fname)
+void startGameFromFile(const bfs::path & fname)
 {
 	StartInfo si;
 	try //attempt retrieving start info from given file
@@ -145,14 +145,14 @@ void startGameFromFile(const bfs::path &fname)
 			throw std::runtime_error("Startfile \"" + fname.string() + "\" does not exist!");
 
 		CLoadFile out(fname);
-		if (!out.sfile || !*out.sfile)
-			throw std::runtime_error("Cannot read from startfile \"" + fname.string() +"\"!");
+		if(!out.sfile || !*out.sfile)
+			throw std::runtime_error("Cannot read from startfile \"" + fname.string() + "\"!");
 		out >> si;
 	}
-	catch(std::exception &e)
+	catch(std::exception & e)
 	{
 		logGlobal->errorStream() << "Failed to start from the file: " << fname << ". Error: " << e.what()
-			<< " Falling back to main menu.";
+		<< " Falling back to main menu.";
 		GH.curInt = CGPreGame::create();
 		return;
 	}
@@ -167,9 +167,9 @@ void init()
 	CStopWatch tmh, pomtime;
 
 	loadDLLClasses();
-	const_cast<CGameInfo*>(CGI)->setFromLib();
+	const_cast<CGameInfo *>(CGI)->setFromLib();
 
-	logGlobal->infoStream()<<"Initializing VCMI_Lib: "<<tmh.getDiff();
+	logGlobal->infoStream() << "Initializing VCMI_Lib: " << tmh.getDiff();
 
 
 	if(!settings["session"]["headless"].Bool())
@@ -180,15 +180,15 @@ void init()
 
 		CCS->curh->initCursor();
 		CCS->curh->show();
-		logGlobal->infoStream()<<"Screen handler: "<<pomtime.getDiff();
+		logGlobal->infoStream() << "Screen handler: " << pomtime.getDiff();
 		pomtime.getDiff();
 
 		graphics->load();
-		logGlobal->infoStream()<<"\tMain graphics: "<<pomtime.getDiff();
-		logGlobal->infoStream()<<"Initializing game graphics: "<<tmh.getDiff();
+		logGlobal->infoStream() << "\tMain graphics: " << pomtime.getDiff();
+		logGlobal->infoStream() << "Initializing game graphics: " << tmh.getDiff();
 
 		CMessage::init();
-		logGlobal->infoStream()<<"Message handler: "<<tmh.getDiff();
+		logGlobal->infoStream() << "Message handler: " << tmh.getDiff();
 	}
 }
 
@@ -198,7 +198,7 @@ static void prog_version(void)
 	std::cout << VCMIDirs::get().genHelpString();
 }
 
-static void prog_help(const po::options_description &opts)
+static void prog_help(const po::options_description & opts)
 {
 	auto time = std::time(0);
 	printf("%s - A Heroes of Might and Magic 3 clone\n", GameConstants::VCMI_VERSION.c_str());
@@ -209,27 +209,24 @@ static void prog_help(const po::options_description &opts)
 	std::cout << opts;
 }
 
-static void SDLLogCallback(void*           userdata,
-                           int             category,
-                           SDL_LogPriority priority,
-                           const char*     message)
+static void SDLLogCallback(void * userdata, int category, SDL_LogPriority priority, const char * message)
 {
 	//todo: convert SDL log priority to vcmi log priority
 	//todo: make separate log domain for SDL
 
-	logGlobal->debugStream() << "SDL(category " << category << "; priority " <<priority <<") "<<message;
+	logGlobal->debugStream() << "SDL(category " << category << "; priority " << priority << ") " << message;
 }
 
 #ifdef VCMI_APPLE
 void OSX_checkForUpdates();
 #endif
 
-#if defined(VCMI_WINDOWS) && !defined (__GNUC__)
-int wmain(int argc, wchar_t* argv[])
+#if defined(VCMI_WINDOWS) && !defined(__GNUC__)
+int wmain(int argc, wchar_t * argv[])
 #elif defined(VCMI_APPLE) || defined(VCMI_ANDROID)
-int SDL_main(int argc, char *argv[])
+int SDL_main(int argc, char * argv[])
 #else
-int main(int argc, char** argv)
+int main(int argc, char * * argv)
 #endif
 {
 #ifdef VCMI_ANDROID
@@ -238,22 +235,23 @@ int main(int argc, char** argv)
 #endif
 #ifdef VCMI_APPLE
 	// Correct working dir executable folder (not bundle folder) so we can use executable relative paths
-    std::string executablePath = argv[0];
-    std::string workDir = executablePath.substr(0, executablePath.rfind('/'));
-    chdir(workDir.c_str());
-
-    // Check for updates
-    OSX_checkForUpdates();
-
-    // Check that game data is prepared. Otherwise run vcmibuilder helper application
-    FILE* check = fopen((VCMIDirs::get().userDataPath() / "game_data_prepared").string().c_str(), "r");
-    if (check == nullptr) {
-        system("open ./vcmibuilder.app");
-        return 0;
-    }
-    fclose(check);
+	std::string executablePath = argv[0];
+	std::string workDir = executablePath.substr(0, executablePath.rfind('/'));
+	chdir(workDir.c_str());
+
+	// Check for updates
+	OSX_checkForUpdates();
+
+	// Check that game data is prepared. Otherwise run vcmibuilder helper application
+	FILE * check = fopen((VCMIDirs::get().userDataPath() / "game_data_prepared").string().c_str(), "r");
+	if(check == nullptr)
+	{
+		system("open ./vcmibuilder.app");
+		return 0;
+	}
+	fclose(check);
 #endif
-    std::cout << "Starting... " << std::endl;
+	std::cout << "Starting... " << std::endl;
 	po::options_description opts("Allowed options");
 	opts.add_options()
 		("help,h", "display help and exit")
@@ -275,13 +273,13 @@ int main(int argc, char** argv)
 		("autoSkip", "automatically skip turns in GUI")
 		("disable-video", "disable video player")
 		("nointro,i", "skips intro movies")
-		("donotstartserver,d","do not attempt to start server and just connect to it instead server")
-        ("loadserver","specifies we are the multiplayer server for loaded games")
-        ("loadnumplayers",po::value<int>(),"specifies the number of players connecting to a multiplayer game")
-        ("loadhumanplayerindices",po::value<std::vector<int>>(),"Indexes of human players (0=Red, etc.)")
-        ("loadplayer", po::value<int>(),"specifies which player we are in multiplayer loaded games (0=Red, etc.)")
-        ("loadserverip",po::value<std::string>(),"IP for loaded game server")
-		("loadserverport",po::value<std::string>(),"port for loaded game server")
+		("donotstartserver,d", "do not attempt to start server and just connect to it instead server")
+		("loadserver", "specifies we are the multiplayer server for loaded games")
+		("loadnumplayers", po::value<int>(), "specifies the number of players connecting to a multiplayer game")
+		("loadhumanplayerindices", po::value<std::vector<int>>(), "Indexes of human players (0=Red, etc.)")
+		("loadplayer", po::value<int>(), "specifies which player we are in multiplayer loaded games (0=Red, etc.)")
+		("loadserverip", po::value<std::string>(), "IP for loaded game server")
+		("loadserverport", po::value<std::string>(), "port for loaded game server")
 		("serverport", po::value<si64>(), "override port specified in config file")
 		("saveprefix", po::value<std::string>(), "prefix for auto save files")
 		("savefrequency", po::value<si64>(), "limit auto save creation to each N days");
@@ -290,11 +288,11 @@ int main(int argc, char** argv)
 	{
 		try
 		{
-			po::store(po::parse_command_line(argc, argv, opts, po_style::unix_style|po_style::case_insensitive), vm);
+			po::store(po::parse_command_line(argc, argv, opts, po_style::unix_style | po_style::case_insensitive), vm);
 		}
-		catch(std::exception &e)
+		catch(std::exception & e)
 		{
-            std::cerr << "Failure during parsing command-line options:\n" << e.what() << std::endl;
+			std::cerr << "Failure during parsing command-line options:\n" << e.what() << std::endl;
 		}
 	}
 
@@ -351,16 +349,16 @@ int main(int argc, char** argv)
 
 	// Some basic data validation to produce better error messages in cases of incorrect install
 	auto testFile = [](std::string filename, std::string message) -> bool
-	{
-		if (CResourceHandler::get()->existsResource(ResourceID(filename)))
-			return true;
+		{
+			if(CResourceHandler::get()->existsResource(ResourceID(filename)))
+				return true;
 
-		logGlobal->errorStream() << "Error: " << message << " was not found!";
-		return false;
-	};
+			logGlobal->errorStream() << "Error: " << message << " was not found!";
+			return false;
+		};
 
-	if (!testFile("DATA/HELP.TXT", "Heroes III data") ||
-		!testFile("MODS/VCMI/MOD.JSON", "VCMI data"))
+	if(!testFile("DATA/HELP.TXT", "Heroes III data") ||
+	   !testFile("MODS/VCMI/MOD.JSON", "VCMI data"))
 	{
 		exit(1); // These are unrecoverable errors
 	}
@@ -372,14 +370,14 @@ int main(int argc, char** argv)
 	conf.init();
 	logGlobal->infoStream() << "Loading settings: " << pomtime.getDiff();
 
-	srand ( time(nullptr) );
+	srand(time(nullptr));
 
 
-	const JsonNode& video = settings["video"];
-	const JsonNode& res = video["screenRes"];
+	const JsonNode & video = settings["video"];
+	const JsonNode & res = video["screenRes"];
 
 	//something is really wrong...
-	if (res["width"].Float() < 100 || res["height"].Float() < 100)
+	if(res["width"].Float() < 100 || res["height"].Float() < 100)
 	{
 		logGlobal->errorStream() << "Fatal error: failed to load settings!";
 		logGlobal->errorStream() << "Possible reasons:";
@@ -391,9 +389,9 @@ int main(int argc, char** argv)
 
 	if(!settings["session"]["headless"].Bool())
 	{
-		if(SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER|SDL_INIT_AUDIO|SDL_INIT_NOPARACHUTE))
+		if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_AUDIO | SDL_INIT_NOPARACHUTE))
 		{
-			logGlobal->errorStream()<<"Something was wrong: "<< SDL_GetError();
+			logGlobal->errorStream() << "Something was wrong: " << SDL_GetError();
 			exit(-1);
 		}
 
@@ -418,7 +416,7 @@ int main(int argc, char** argv)
 		for(int it = 0; it < driversCount; it++)
 		{
 			SDL_RendererInfo info;
-			SDL_GetRenderDriverInfo(it,&info);
+			SDL_GetRenderDriverInfo(it, &info);
 
 			std::string driverName(info.name);
 
@@ -432,11 +430,11 @@ int main(int argc, char** argv)
 		}
 
 		config::CConfigHandler::GuiOptionsMap::key_type resPair(res["width"].Float(), res["height"].Float());
-		if (conf.guiOptions.count(resPair) == 0)
+		if(conf.guiOptions.count(resPair) == 0)
 		{
 			// selected resolution was not found - complain & fallback to something that we do have.
 			logGlobal->errorStream() << "Selected resolution " << resPair.first << "x" << resPair.second << " was not found!";
-			if (conf.guiOptions.empty())
+			if(conf.guiOptions.empty())
 			{
 				logGlobal->errorStream() << "Unable to continue - no valid resolutions found! Please reinstall VCMI to fix this";
 				exit(1);
@@ -444,7 +442,7 @@ int main(int argc, char** argv)
 			else
 			{
 				Settings newRes = settings.write["video"]["screenRes"];
-				newRes["width"].Float()  = conf.guiOptions.begin()->first.first;
+				newRes["width"].Float() = conf.guiOptions.begin()->first.first;
 				newRes["height"].Float() = conf.guiOptions.begin()->first.second;
 				conf.SetResolution(newRes["width"].Float(), newRes["height"].Float());
 
@@ -453,7 +451,7 @@ int main(int argc, char** argv)
 		}
 
 		setScreenRes(res["width"].Float(), res["height"].Float(), video["bitsPerPixel"].Float(), video["fullscreen"].Bool(), video["displayIndex"].Float());
-		logGlobal->infoStream() <<"\tInitializing screen: "<<pomtime.getDiff();
+		logGlobal->infoStream() << "\tInitializing screen: " << pomtime.getDiff();
 	}
 
 	CCS = new CClientState();
@@ -462,13 +460,13 @@ int main(int argc, char** argv)
 #ifdef DISABLE_VIDEO
 	CCS->videoh = new CEmptyVideoPlayer();
 #else
-	if (!settings["session"]["headless"].Bool() && !vm.count("disable-video"))
+	if(!settings["session"]["headless"].Bool() && !vm.count("disable-video"))
 		CCS->videoh = new CVideoPlayer();
 	else
 		CCS->videoh = new CEmptyVideoPlayer();
 #endif
 
-	logGlobal->infoStream()<<"\tInitializing video: "<<pomtime.getDiff();
+	logGlobal->infoStream() << "\tInitializing video: " << pomtime.getDiff();
 
 	//initializing audio
 	CCS->soundh = new CSoundHandler();
@@ -477,7 +475,7 @@ int main(int argc, char** argv)
 	CCS->musich = new CMusicHandler();
 	CCS->musich->init();
 	CCS->musich->setVolume(settings["general"]["music"].Float());
-	logGlobal->infoStream()<<"Initializing screen and sound handling: "<<pomtime.getDiff();
+	logGlobal->infoStream() << "Initializing screen and sound handling: " << pomtime.getDiff();
 
 #ifdef __APPLE__
 	// Ctrl+click should be treated as a right click on Mac OS X
@@ -505,15 +503,15 @@ int main(int argc, char** argv)
 		CAndroidVMHelper vmHelper;
 		vmHelper.callStaticVoidMethod(CAndroidVMHelper::NATIVE_METHODS_DEFAULT_CLASS, "showProgress");
 	#endif // ANDROID
-		loading.join();
+	loading.join();
 	#ifdef VCMI_ANDROID
-		vmHelper.callStaticVoidMethod(CAndroidVMHelper::NATIVE_METHODS_DEFAULT_CLASS, "hideProgress");
-	}
+	vmHelper.callStaticVoidMethod(CAndroidVMHelper::NATIVE_METHODS_DEFAULT_CLASS, "hideProgress");
+}
 	#endif // ANDROID
 #endif // THREADED
-	logGlobal->infoStream()<<"Initialization of VCMI (together): "<<total.getDiff();
+	logGlobal->infoStream() << "Initialization of VCMI (together): " << total.getDiff();
 
-	session["autoSkip"].Bool()  = vm.count("autoSkip");
+	session["autoSkip"].Bool() = vm.count("autoSkip");
 	session["oneGoodAI"].Bool() = vm.count("oneGoodAI");
 	session["aiSolo"].Bool() = false;
 
@@ -549,7 +547,7 @@ int main(int argc, char** argv)
 			if(!fileToStartFrom.empty())
 			{
 				logGlobal->warnStream() << "Warning: cannot find given file to start from (" << fileToStartFrom
-					<< "). Falling back to main menu.";
+				<< "). Falling back to main menu.";
 			}
 			GH.curInt = CGPreGame::create(); //will set CGP pointer to itself
 		}
@@ -568,15 +566,15 @@ int main(int argc, char** argv)
 	return 0;
 }
 
-void printInfoAboutIntObject(const CIntObject *obj, int level)
+void printInfoAboutIntObject(const CIntObject * obj, int level)
 {
 	std::stringstream sbuffer;
 	sbuffer << std::string(level, '\t');
 
 	sbuffer << typeid(*obj).name() << " *** ";
-	if (obj->active)
+	if(obj->active)
 	{
-#define PRINT(check, text) if (obj->active & CIntObject::check) sbuffer << text
+#define PRINT(check, text) if(obj->active & CIntObject::check) sbuffer << text
 		PRINT(LCLICK, 'L');
 		PRINT(RCLICK, 'R');
 		PRINT(HOVER, 'H');
@@ -590,12 +588,12 @@ void printInfoAboutIntObject(const CIntObject *obj, int level)
 	}
 	else
 		sbuffer << "inactive";
-	sbuffer << " at " << obj->pos.x <<"x"<< obj->pos.y;
-	sbuffer << " (" << obj->pos.w <<"x"<< obj->pos.h << ")";
+	sbuffer << " at " << obj->pos.x << "x" << obj->pos.y;
+	sbuffer << " (" << obj->pos.w << "x" << obj->pos.h << ")";
 	logGlobal->infoStream() << sbuffer.str();
 
-	for(const CIntObject *child : obj->children)
-		printInfoAboutIntObject(child, level+1);
+	for(const CIntObject * child : obj->children)
+		printInfoAboutIntObject(child, level + 1);
 }
 
 void removeGUI()
@@ -612,7 +610,7 @@ void removeGUI()
 	LOCPLINT = nullptr;
 }
 
-void processCommand(const std::string &message)
+void processCommand(const std::string & message)
 {
 	std::istringstream readed;
 	readed.str(message);
@@ -637,7 +635,7 @@ void processCommand(const std::string &message)
 			std::cout << "erm>";
 		}
 	}
-	else if(message==std::string("die, fool"))
+	else if(message == std::string("die, fool"))
 	{
 		exit(EXIT_SUCCESS);
 	}
@@ -646,11 +644,11 @@ void processCommand(const std::string &message)
 		ermInteractiveMode = true;
 		std::cout << "erm>";
 	}
-	else if(cn==std::string("activate"))
+	else if(cn == std::string("activate"))
 	{
 		int what;
 		readed >> what;
-		switch (what)
+		switch(what)
 		{
 		case 0:
 			GH.topInt()->activate();
@@ -663,11 +661,11 @@ void processCommand(const std::string &message)
 			break;
 		}
 	}
-	else if(cn=="redraw")
+	else if(cn == "redraw")
 	{
 		GH.totalRedraw();
 	}
-	else if(cn=="screen")
+	else if(cn == "screen")
 	{
 		std::cout << "Screenbuf points to ";
 
@@ -681,7 +679,7 @@ void processCommand(const std::string &message)
 		SDL_SaveBMP(screen, "Screen_c.bmp");
 		SDL_SaveBMP(screen2, "Screen2_c.bmp");
 	}
-	else if(cn=="save")
+	else if(cn == "save")
 	{
 		if(!client)
 		{
@@ -699,7 +697,7 @@ void processCommand(const std::string &message)
 //		readed >> fname;
 //		client->loadGame(fname);
 //	}
-	else if(message=="get txt")
+	else if(message == "get txt")
 	{
 		std::cout << "Command accepted.\t";
 
@@ -711,7 +709,7 @@ void processCommand(const std::string &message)
 			return ident.getType() == EResType::TEXT && boost::algorithm::starts_with(ident.getName(), "DATA/");
 		});
 
-		for (auto & filename : list)
+		for(auto & filename : list)
 		{
 			const bfs::path filePath = outPath / (filename.getName() + ".TXT");
 
@@ -720,32 +718,32 @@ void processCommand(const std::string &message)
 			bfs::ofstream file(filePath);
 			auto text = CResourceHandler::get()->load(filename)->readAll();
 
-			file.write((char*)text.first.get(), text.second);
+			file.write((char *)text.first.get(), text.second);
 		}
 
 		std::cout << "\rExtracting done :)\n";
 		std::cout << " Extracted files can be found in " << outPath << " directory\n";
 	}
-	else if(cn=="crash")
+	else if(cn == "crash")
 	{
-		int *ptr = nullptr;
+		int * ptr = nullptr;
 		*ptr = 666;
 		//disaster!
 	}
 	else if(cn == "mp" && adventureInt)
 	{
-		if(const CGHeroInstance *h = dynamic_cast<const CGHeroInstance *>(adventureInt->selection))
+		if(const CGHeroInstance * h = dynamic_cast<const CGHeroInstance *>(adventureInt->selection))
 			std::cout << h->movement << "; max: " << h->maxMovePoints(true) << "/" << h->maxMovePoints(false) << std::endl;
 	}
 	else if(cn == "bonuses")
 	{
 		std::cout << "Bonuses of " << adventureInt->selection->getObjectName() << std::endl
-			<< adventureInt->selection->getBonusList() << std::endl;
+		<< adventureInt->selection->getBonusList() << std::endl;
 
 		std::cout << "\nInherited bonuses:\n";
 		TCNodes parents;
 		adventureInt->selection->getParents(parents);
-		for(const CBonusSystemNode *parent : parents)
+		for(const CBonusSystemNode * parent : parents)
 		{
 			std::cout << "\nBonuses from " << typeid(*parent).name() << std::endl << parent->getBonusList() << std::endl;
 		}
@@ -756,28 +754,28 @@ void processCommand(const std::string &message)
 	}
 	else if(cn == "gui")
 	{
-		for(const IShowActivatable *child : GH.listInt)
+		for(const IShowActivatable * child : GH.listInt)
 		{
-			if(const CIntObject *obj = dynamic_cast<const CIntObject *>(child))
+			if(const CIntObject * obj = dynamic_cast<const CIntObject *>(child))
 				printInfoAboutIntObject(obj, 0);
 			else
 				std::cout << typeid(*child).name() << std::endl;
 		}
 	}
-	else if(cn=="tell")
+	else if(cn == "tell")
 	{
 		std::string what;
 		int id1, id2;
 		readed >> what >> id1 >> id2;
 		if(what == "hs")
 		{
-			for(const CGHeroInstance *h : LOCPLINT->cb->getHeroesInfo())
+			for(const CGHeroInstance * h : LOCPLINT->cb->getHeroesInfo())
 				if(h->type->ID.getNum() == id1)
-					if(const CArtifactInstance *a = h->getArt(ArtifactPosition(id2)))
+					if(const CArtifactInstance * a = h->getArt(ArtifactPosition(id2)))
 						std::cout << a->nodeName();
 		}
 	}
-	else if (cn == "set")
+	else if(cn == "set")
 	{
 		std::string what, value;
 		readed >> what;
@@ -786,12 +784,12 @@ void processCommand(const std::string &message)
 
 		readed >> value;
 
-		if (value == "on")
+		if(value == "on")
 		{
 			conf->Bool() = true;
 			logGlobal->info("Option %s enabled!", what);
 		}
-		else if (value == "off")
+		else if(value == "off")
 		{
 			conf->Bool() = false;
 			logGlobal->info("Option %s disabled!", what);
@@ -833,7 +831,7 @@ void processCommand(const std::string &message)
 		std::string URI;
 		readed >> URI;
 
-		if (CResourceHandler::get()->existsResource(ResourceID(URI)))
+		if(CResourceHandler::get()->existsResource(ResourceID(URI)))
 		{
 			const bfs::path outPath = VCMIDirs::get().userCachePath() / "extracted" / URI;
 
@@ -841,7 +839,7 @@ void processCommand(const std::string &message)
 
 			bfs::create_directories(outPath.parent_path());
 			bfs::ofstream outFile(outPath, bfs::ofstream::binary);
-			outFile.write((char*)data.first.get(), data.second);
+			outFile.write((char *)data.first.get(), data.second);
 		}
 		else
 			logGlobal->errorStream() << "File not found!";
@@ -860,7 +858,7 @@ void processCommand(const std::string &message)
 				std::cout << "Setting changed, from now the battle ai will be " << fname << "!\n";
 			}
 		}
-		catch(std::exception &e)
+		catch(std::exception & e)
 		{
 			logGlobal->warnStream() << "Failed opening " << fname << ": " << e.what();
 			logGlobal->warnStream() << "Setting not changes, AI not found or invalid!";
@@ -868,12 +866,12 @@ void processCommand(const std::string &message)
 	}
 
 	auto giveTurn = [&](PlayerColor player)
-	{
-		YourTurn yt;
-		yt.player = player;
-		yt.daysWithoutCastle = client->getPlayer(player)->daysWithoutCastle;
-		yt.applyCl(client);
-	};
+		{
+			YourTurn yt;
+			yt.player = player;
+			yt.daysWithoutCastle = client->getPlayer(player)->daysWithoutCastle;
+			yt.applyCl(client);
+		};
 
 	Settings session = settings.write["session"];
 	if(cn == "autoskip")
@@ -933,7 +931,7 @@ void processCommand(const std::string &message)
 		for(auto & elem : client->gameState()->players)
 		{
 			if(elem.second.human || (colorName.length() &&
-				elem.first.getNum() != vstd::find_pos(GameConstants::PLAYER_COLOR_NAMES, colorName)))
+						 elem.first.getNum() != vstd::find_pos(GameConstants::PLAYER_COLOR_NAMES, colorName)))
 			{
 				continue;
 			}
@@ -946,11 +944,11 @@ void processCommand(const std::string &message)
 			giveTurn(color);
 	}
 	// Check mantis issue 2292 for details
-/* 	else if(client && client->serv && client->serv->connected && LOCPLINT) //send to server
-	{
-		boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
-		LOCPLINT->cb->sendMessage(message);
-	}*/
+/*      else if(client && client->serv && client->serv->connected && LOCPLINT) //send to server
+        {
+                boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
+                LOCPLINT->cb->sendMessage(message);
+        }*/
 }
 
 //plays intro, ends when intro is over or button has been pressed (handles events)
@@ -993,7 +991,7 @@ static bool checkVideoMode(int monitorIndex, int w, int h)
 	//we only check that our desired window size fits on screen
 	SDL_DisplayMode mode;
 
-	if (0 != SDL_GetDesktopDisplayMode(monitorIndex, &mode))
+	if(0 != SDL_GetDesktopDisplayMode(monitorIndex, &mode))
 	{
 		logGlobal->error("SDL_GetDesktopDisplayMode failed");
 		logGlobal->error(SDL_GetError());
@@ -1002,7 +1000,7 @@ static bool checkVideoMode(int monitorIndex, int w, int h)
 
 	logGlobal->info("Check display mode: requested %d x %d; available up to %d x %d ", w, h, mode.w, mode.h);
 
-	if (!mode.w || !mode.h || (w <= mode.w && h <= mode.h))
+	if(!mode.w || !mode.h || (w <= mode.w && h <= mode.h))
 	{
 		return true;
 	}
@@ -1050,14 +1048,14 @@ static bool recreateWindow(int w, int h, int bpp, bool fullscreen, int displayIn
 	// VCMI will only work with 2 or 4 bytes per pixel
 	vstd::amax(bpp, 16);
 	vstd::amin(bpp, 32);
-	if(bpp>16)
+	if(bpp > 16)
 		bpp = 32;
 
 	if(displayIndex < 0)
 	{
-		if (mainWindow != nullptr)
+		if(mainWindow != nullptr)
 			displayIndex = SDL_GetWindowDisplayIndex(mainWindow);
-		if (displayIndex < 0)
+		if(displayIndex < 0)
 			displayIndex = 0;
 	}
 	if(!checkVideoMode(displayIndex, w, h))
@@ -1073,7 +1071,7 @@ static bool recreateWindow(int w, int h, int bpp, bool fullscreen, int displayIn
 	bool realFullscreen = settings["video"]["realFullscreen"].Bool();
 
 #ifdef VCMI_ANDROID
-	mainWindow = SDL_CreateWindow(NAME.c_str(), SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex),SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), 0, 0, SDL_WINDOW_FULLSCREEN);
+	mainWindow = SDL_CreateWindow(NAME.c_str(), SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), 0, 0, SDL_WINDOW_FULLSCREEN);
 #else
 
 	if(fullscreen)
@@ -1081,12 +1079,12 @@ static bool recreateWindow(int w, int h, int bpp, bool fullscreen, int displayIn
 		if(realFullscreen)
 			mainWindow = SDL_CreateWindow(NAME.c_str(), SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), w, h, SDL_WINDOW_FULLSCREEN);
 		else //in windowed full-screen mode use desktop resolution
-			mainWindow = SDL_CreateWindow(NAME.c_str(), SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex),SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), 0, 0, SDL_WINDOW_FULLSCREEN_DESKTOP);
+			mainWindow = SDL_CreateWindow(NAME.c_str(), SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), 0, 0, SDL_WINDOW_FULLSCREEN_DESKTOP);
 		SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "linear");
 	}
 	else
 	{
-		mainWindow = SDL_CreateWindow(NAME.c_str(), SDL_WINDOWPOS_CENTERED_DISPLAY(displayIndex),SDL_WINDOWPOS_CENTERED_DISPLAY(displayIndex), w, h, 0);
+		mainWindow = SDL_CreateWindow(NAME.c_str(), SDL_WINDOWPOS_CENTERED_DISPLAY(displayIndex), SDL_WINDOWPOS_CENTERED_DISPLAY(displayIndex), w, h, 0);
 	}
 #endif
 
@@ -1097,7 +1095,7 @@ static bool recreateWindow(int w, int h, int bpp, bool fullscreen, int displayIn
 
 
 	//create first available renderer if preferred not set. Use no flags, so HW accelerated will be preferred but SW renderer also will possible
-	mainRenderer = SDL_CreateRenderer(mainWindow,preferredDriverIndex,0);
+	mainRenderer = SDL_CreateRenderer(mainWindow, preferredDriverIndex, 0);
 
 	if(nullptr == mainRenderer)
 	{
@@ -1105,7 +1103,7 @@ static bool recreateWindow(int w, int h, int bpp, bool fullscreen, int displayIn
 	}
 
 	SDL_RendererInfo info;
-	SDL_GetRendererInfo(mainRenderer,&info);
+	SDL_GetRendererInfo(mainRenderer, &info);
 	logGlobal->infoStream() << "Created renderer " << info.name;
 
 	if(!(fullscreen && realFullscreen))
@@ -1120,22 +1118,22 @@ static bool recreateWindow(int w, int h, int bpp, bool fullscreen, int displayIn
 
 
 	#if (SDL_BYTEORDER == SDL_BIG_ENDIAN)
-		int bmask = 0xff000000;
-		int gmask = 0x00ff0000;
-		int rmask = 0x0000ff00;
-		int amask = 0x000000ff;
+	int bmask = 0xff000000;
+	int gmask = 0x00ff0000;
+	int rmask = 0x0000ff00;
+	int amask = 0x000000ff;
 	#else
-		int bmask = 0x000000ff;
-		int gmask = 0x0000ff00;
-		int rmask = 0x00ff0000;
-		int amask = 0xFF000000;
+	int bmask = 0x000000ff;
+	int gmask = 0x0000ff00;
+	int rmask = 0x00ff0000;
+	int amask = 0xFF000000;
 	#endif
 
-	screen = SDL_CreateRGBSurface(0,w,h,bpp,rmask,gmask,bmask,amask);
+	screen = SDL_CreateRGBSurface(0, w, h, bpp, rmask, gmask, bmask, amask);
 	if(nullptr == screen)
 	{
 		logGlobal->errorStream() << "Unable to create surface";
-		logGlobal->errorStream() << w << " "<<  h << " "<< bpp;
+		logGlobal->errorStream() << w << " " << h << " " << bpp;
 
 		logGlobal->errorStream() << SDL_GetError();
 		throw std::runtime_error("Unable to create surface");
@@ -1144,9 +1142,9 @@ static bool recreateWindow(int w, int h, int bpp, bool fullscreen, int displayIn
 	SDL_SetSurfaceBlendMode(screen, SDL_BLENDMODE_NONE);
 
 	screenTexture = SDL_CreateTexture(mainRenderer,
-                                            SDL_PIXELFORMAT_ARGB8888,
-                                            SDL_TEXTUREACCESS_STREAMING,
-                                            w, h);
+					  SDL_PIXELFORMAT_ARGB8888,
+					  SDL_TEXTUREACCESS_STREAMING,
+					  w, h);
 
 	if(nullptr == screenTexture)
 	{
@@ -1204,7 +1202,7 @@ static void fullScreenChanged()
 
 static void handleEvent(SDL_Event & ev)
 {
-	if((ev.type==SDL_QUIT) ||(ev.type == SDL_KEYDOWN && ev.key.keysym.sym==SDLK_F4 && (ev.key.keysym.mod & KMOD_ALT)))
+	if((ev.type == SDL_QUIT) || (ev.type == SDL_KEYDOWN && ev.key.keysym.sym == SDLK_F4 && (ev.key.keysym.mod & KMOD_ALT)))
 	{
 #ifdef VCMI_ANDROID
 		handleQuit(false);
@@ -1214,12 +1212,12 @@ static void handleEvent(SDL_Event & ev)
 		return;
 	}
 #ifdef VCMI_ANDROID
-	else if (ev.type == SDL_KEYDOWN && ev.key.keysym.scancode == SDL_SCANCODE_AC_BACK)
+	else if(ev.type == SDL_KEYDOWN && ev.key.keysym.scancode == SDL_SCANCODE_AC_BACK)
 	{
 		handleQuit(true);
 	}
 #endif
-	else if(ev.type == SDL_KEYDOWN && ev.key.keysym.sym==SDLK_F4)
+	else if(ev.type == SDL_KEYDOWN && ev.key.keysym.sym == SDLK_F4)
 	{
 		Settings full = settings.write["video"]["fullscreen"];
 		full->Bool() = !full->Bool();
@@ -1230,33 +1228,33 @@ static void handleEvent(SDL_Event & ev)
 		switch(ev.user.code)
 		{
 		case FORCE_QUIT:
-			{
-				handleQuit(false);
-				return;
-			}
-		    break;
+		{
+			handleQuit(false);
+			return;
+		}
+		break;
 		case RETURN_TO_MAIN_MENU:
-			{
-				endGame();
-				GH.curInt = CGPreGame::create();
-				GH.defActionsDef = 63;
-			}
-			break;
+		{
+			endGame();
+			GH.curInt = CGPreGame::create();
+			GH.defActionsDef = 63;
+		}
+		break;
 		case RESTART_GAME:
-			{
-				StartInfo si = *client->getStartInfo(true);
-				si.seedToBeUsed = 0; //server gives new random generator seed if 0
-				endGame();
-				startGame(&si);
-			}
-			break;
+		{
+			StartInfo si = *client->getStartInfo(true);
+			si.seedToBeUsed = 0; //server gives new random generator seed if 0
+			endGame();
+			startGame(&si);
+		}
+		break;
 		case PREPARE_RESTART_CAMPAIGN:
-			{
-				auto si = reinterpret_cast<StartInfo *>(ev.user.data1);
-				endGame();
-				startGame(si);
-			}
-			break;
+		{
+			auto si = reinterpret_cast<StartInfo *>(ev.user.data1);
+			endGame();
+			startGame(si);
+		}
+		break;
 		case RETURN_TO_MENU_LOAD:
 			endGame();
 			CGPreGame::create();
@@ -1277,7 +1275,8 @@ static void handleEvent(SDL_Event & ev)
 	}
 	else if(ev.type == SDL_WINDOWEVENT)
 	{
-		switch (ev.window.event) {
+		switch(ev.window.event)
+		{
 		case SDL_WINDOWEVENT_RESTORED:
 			fullScreenChanged();
 			break;
@@ -1295,9 +1294,9 @@ static void handleEvent(SDL_Event & ev)
 static void mainLoop()
 {
 	SettingsListener resChanged = settings.listen["video"]["fullscreen"];
-	resChanged([](const JsonNode &newState){  CGuiHandler::pushSDLEvent(SDL_USEREVENT, FULLSCREEN_TOGGLED); });
+	resChanged([](const JsonNode & newState){  CGuiHandler::pushSDLEvent(SDL_USEREVENT, FULLSCREEN_TOGGLED); });
 
-	inGuiThread.reset(new bool(true));
+	inGuiThread.reset(new bool (true));
 	GH.mainFPSmng->init();
 
 	while(1) //main SDL events loop
@@ -1314,7 +1313,7 @@ static void mainLoop()
 	}
 }
 
-void startGame(StartInfo * options, CConnection *serv)
+void startGame(StartInfo * options, CConnection * serv)
 {
 	if(!settings["session"]["donotstartserver"].Bool())
 	{
@@ -1337,7 +1336,7 @@ void startGame(StartInfo * options, CConnection *serv)
 		}
 	}
 
-    client = new CClient();
+	client = new CClient();
 	CPlayerInterface::howManyPeople = 0;
 	switch(options->mode) //new game
 	{
@@ -1347,11 +1346,11 @@ void startGame(StartInfo * options, CConnection *serv)
 		break;
 	case StartInfo::LOAD_GAME:
 		std::string fname = options->mapname;
-		boost::algorithm::erase_last(fname,".vlgm1");
-        if(!vm.count("loadplayer"))
-            client->loadGame(fname);
-        else
-			client->loadGame(fname,vm.count("loadserver"),vm.count("loadhumanplayerindices") ? vm["loadhumanplayerindices"].as<std::vector<int>>() : std::vector<int>(),vm.count("loadnumplayers") ? vm["loadnumplayers"].as<int>() : 1,vm["loadplayer"].as<int>(),vm.count("loadserverip") ? vm["loadserverip"].as<std::string>() : "", vm.count("loadserverport") ? vm["loadserverport"].as<ui16>() : CServerHandler::getDefaultPort());
+		boost::algorithm::erase_last(fname, ".vlgm1");
+		if(!vm.count("loadplayer"))
+			client->loadGame(fname);
+		else
+			client->loadGame(fname, vm.count("loadserver"), vm.count("loadhumanplayerindices") ? vm["loadhumanplayerindices"].as<std::vector<int>>() : std::vector<int>(), vm.count("loadnumplayers") ? vm["loadnumplayers"].as<int>() : 1, vm["loadplayer"].as<int>(), vm.count("loadserverip") ? vm["loadserverip"].as<std::string>() : "", vm.count("loadserverport") ? vm["loadserverport"].as<ui16>() : CServerHandler::getDefaultPort());
 		break;
 	}
 	{
@@ -1369,21 +1368,21 @@ void endGame()
 void handleQuit(bool ask)
 {
 	auto quitApplication = []()
-	{
-		if(client)
-			endGame();
-		dispose();
-		vstd::clear_pointer(console);
-		boost::this_thread::sleep(boost::posix_time::milliseconds(750));
-		if(!settings["session"]["headless"].Bool())
 		{
-			cleanupRenderer();
-			SDL_Quit();
-		}
+			if(client)
+				endGame();
+			dispose();
+			vstd::clear_pointer(console);
+			boost::this_thread::sleep(boost::posix_time::milliseconds(750));
+			if(!settings["session"]["headless"].Bool())
+			{
+				cleanupRenderer();
+				SDL_Quit();
+			}
 
-		std::cout << "Ending...\n";
-		exit(0);
-	};
+			std::cout << "Ending...\n";
+			exit(0);
+		};
 
 	if(client && LOCPLINT && ask)
 	{

+ 3 - 3
client/CMT.h

@@ -16,9 +16,9 @@ extern SDL_Texture * screenTexture;
 extern SDL_Window * mainWindow;
 extern SDL_Renderer * mainRenderer;
 
-extern SDL_Surface *screen;      // main screen surface
-extern SDL_Surface *screen2;     // and hlp surface (used to store not-active interfaces layer)
-extern SDL_Surface *screenBuf; // points to screen (if only advmapint is present) or screen2 (else) - should be used when updating controls which are not regularly redrawed
+extern SDL_Surface * screen; // main screen surface
+extern SDL_Surface * screen2; // and hlp surface (used to store not-active interfaces layer)
+extern SDL_Surface * screenBuf; // points to screen (if only advmapint is present) or screen2 (else) - should be used when updating controls which are not regularly redrawed
 
 extern CondSh<bool> serverAlive; //used to prevent game start from executing if server is already running
 

+ 105 - 101
client/CMessage.cpp

@@ -27,54 +27,56 @@ const int BEFORE_COMPONENTS = 30;
 const int BETWEEN_COMPS = 30;
 const int SIDE_MARGIN = 30;
 
-template <typename T, typename U> std::pair<T,U> max(const std::pair<T,U> &x, const std::pair<T,U> &y)
+template<typename T, typename U> std::pair<T, U> max(const std::pair<T, U> & x, const std::pair<T, U> & y)
 {
-	std::pair<T,U> ret;
-	ret.first = std::max(x.first,y.first);
-	ret.second = std::max(x.second,y.second);
+	std::pair<T, U> ret;
+	ret.first = std::max(x.first, y.first);
+	ret.second = std::max(x.second, y.second);
 	return ret;
 }
 
 //One image component + subtitles below it
+
 class ComponentResolved : public CIntObject
 {
 public:
-	CComponent *comp;
+	CComponent * comp;
 
 	//blit component with image centered at this position
 	void showAll(SDL_Surface * to) override;
 
 	//ComponentResolved();
-	ComponentResolved(CComponent *Comp);
+	ComponentResolved(CComponent * Comp);
 	~ComponentResolved();
 };
+
 // Full set of components for blitting on dialog box
 struct ComponentsToBlit
 {
-	std::vector< std::vector<ComponentResolved*> > comps;
+	std::vector<std::vector<ComponentResolved *>> comps;
 	int w, h;
 
-	void blitCompsOnSur(bool blitOr, int inter, int &curh, SDL_Surface *ret);
-	ComponentsToBlit(std::vector<CComponent*> & SComps, int maxw, bool blitOr);
+	void blitCompsOnSur(bool blitOr, int inter, int & curh, SDL_Surface * ret);
+	ComponentsToBlit(std::vector<CComponent *> & SComps, int maxw, bool blitOr);
 	~ComponentsToBlit();
 };
 
 namespace
 {
-	std::array<std::unique_ptr<CAnimation>, PlayerColor::PLAYER_LIMIT_I> dialogBorders;
-	std::array<std::vector<const IImage*>, PlayerColor::PLAYER_LIMIT_I> piecesOfBox;
+std::array<std::unique_ptr<CAnimation>, PlayerColor::PLAYER_LIMIT_I> dialogBorders;
+std::array<std::vector<const IImage *>, PlayerColor::PLAYER_LIMIT_I> piecesOfBox;
 
-	SDL_Surface * background = nullptr;//todo: should be CFilledTexture
+SDL_Surface * background = nullptr; //todo: should be CFilledTexture
 }
 
 void CMessage::init()
 {
-	for(int i=0; i<PlayerColor::PLAYER_LIMIT_I; i++)
+	for(int i = 0; i < PlayerColor::PLAYER_LIMIT_I; i++)
 	{
 		dialogBorders[i] = make_unique<CAnimation>("DIALGBOX");
 		dialogBorders[i]->preload();
 
-        for(int j=0; j < dialogBorders[i]->size(0); j++)
+		for(int j = 0; j < dialogBorders[i]->size(0); j++)
 		{
 			IImage * image = dialogBorders[i]->getImage(j, 0);
 			//assume blue color initially
@@ -98,12 +100,12 @@ SDL_Surface * CMessage::drawDialogBox(int w, int h, PlayerColor playerColor)
 {
 	//prepare surface
 	SDL_Surface * ret = SDL_CreateRGBSurface(SDL_SWSURFACE, w, h, screen->format->BitsPerPixel, screen->format->Rmask, screen->format->Gmask, screen->format->Bmask, screen->format->Amask);
-	for (int i=0; i<w; i+=background->w)//background
+	for(int i = 0; i < w; i += background->w) //background
 	{
-		for (int j=0; j<h; j+=background->h)
+		for(int j = 0; j < h; j += background->h)
 		{
-			Rect srcR(0,0,background->w, background->h);
-			Rect dstR(i,j,w,h);
+			Rect srcR(0, 0, background->w, background->h);
+			Rect dstR(i, j, w, h);
 			CSDL_Ext::blitSurface(background, &srcR, ret, &dstR);
 		}
 	}
@@ -111,47 +113,47 @@ SDL_Surface * CMessage::drawDialogBox(int w, int h, PlayerColor playerColor)
 	return ret;
 }
 
-std::vector<std::string> CMessage::breakText( std::string text, size_t maxLineWidth, EFonts font )
+std::vector<std::string> CMessage::breakText(std::string text, size_t maxLineWidth, EFonts font)
 {
 	std::vector<std::string> ret;
 
-	boost::algorithm::trim_right_if(text,boost::algorithm::is_any_of(std::string(" ")));
+	boost::algorithm::trim_right_if(text, boost::algorithm::is_any_of(std::string(" ")));
 
 	// each iteration generates one output line
-	while (text.length())
+	while(text.length())
 	{
-		ui32 lineWidth = 0;    //in characters or given char metric
-		ui32 wordBreak = -1;    //last position for line break (last space character)
-		ui32 currPos = 0;       //current position in text
-		bool opened = false;    //set to true when opening brace is found
+		ui32 lineWidth = 0; //in characters or given char metric
+		ui32 wordBreak = -1; //last position for line break (last space character)
+		ui32 currPos = 0; //current position in text
+		bool opened = false; //set to true when opening brace is found
 
 		size_t symbolSize = 0; // width of character, in bytes
 		size_t glyphWidth = 0; // width of printable glyph, pixels
 
 		// loops till line is full or end of text reached
-		while(currPos < text.length()  &&  text[currPos] != 0x0a  &&  lineWidth < maxLineWidth)
+		while(currPos < text.length() && text[currPos] != 0x0a && lineWidth < maxLineWidth)
 		{
 			symbolSize = Unicode::getCharacterSize(text[currPos]);
 			glyphWidth = graphics->fonts[font]->getGlyphWidth(text.data() + currPos);
 
 			// candidate for line break
-			if (ui8(text[currPos]) <= ui8(' '))
+			if(ui8(text[currPos]) <= ui8(' '))
 				wordBreak = currPos;
 
 			/* We don't count braces in string length. */
-			if (text[currPos] == '{')
-				opened=true;
-			else if (text[currPos]=='}')
-				opened=false;
+			if(text[currPos] == '{')
+				opened = true;
+			else if(text[currPos] == '}')
+				opened = false;
 			else
 				lineWidth += glyphWidth;
 			currPos += symbolSize;
 		}
 
 		// long line, create line break
-		if (currPos < text.length()  &&  (text[currPos] != 0x0a))
+		if(currPos < text.length() && (text[currPos] != 0x0a))
 		{
-			if (wordBreak != ui32(-1))
+			if(wordBreak != ui32(-1))
 				currPos = wordBreak;
 			else
 				currPos -= symbolSize;
@@ -162,7 +164,7 @@ std::vector<std::string> CMessage::breakText( std::string text, size_t maxLineWi
 		{
 			ret.push_back(text.substr(0, currPos));
 
-			if (opened)
+			if(opened)
 				/* Close the brace for the current line. */
 				ret.back() += '}';
 
@@ -173,7 +175,7 @@ std::vector<std::string> CMessage::breakText( std::string text, size_t maxLineWi
 			ret.push_back(""); //add empty string, no extra actions needed
 		}
 
-		if (text.length() != 0 && text[0] == 0x0a)
+		if(text.length() != 0 && text[0] == 0x0a)
 		{
 			/* Remove LF */
 			text.erase(0, 1);
@@ -182,19 +184,19 @@ std::vector<std::string> CMessage::breakText( std::string text, size_t maxLineWi
 		{
 			// trim only if line does not starts with LF
 			// FIXME: necessary? All lines will be trimmed before returning anyway
-			boost::algorithm::trim_left_if(text,boost::algorithm::is_any_of(std::string(" ")));
+			boost::algorithm::trim_left_if(text, boost::algorithm::is_any_of(std::string(" ")));
 		}
 
-		if (opened)
+		if(opened)
 		{
 			/* Add an opening brace for the next line. */
-			if (text.length() != 0)
+			if(text.length() != 0)
 				text.insert(0, "{");
 		}
 	}
 
 	/* Trim whitespaces of every line. */
-	for (auto & elem : ret)
+	for(auto & elem : ret)
 		boost::algorithm::trim(elem);
 
 	return ret;
@@ -203,17 +205,17 @@ std::vector<std::string> CMessage::breakText( std::string text, size_t maxLineWi
 void CMessage::drawIWindow(CInfoWindow * ret, std::string text, PlayerColor player)
 {
 	bool blitOr = false;
-	if(dynamic_cast<CSelWindow*>(ret)) //it's selection window, so we'll blit "or" between components
+	if(dynamic_cast<CSelWindow *>(ret)) //it's selection window, so we'll blit "or" between components
 		blitOr = true;
 
 	const int sizes[][2] = {{400, 125}, {500, 150}, {600, 200}, {480, 400}};
 
 	for(int i = 0;
-		i < ARRAY_COUNT(sizes)
-			&& sizes[i][0] < screen->w - 150
-			&& sizes[i][1] < screen->h - 150
-			&& ret->text->slider;
-		i++)
+	    i < ARRAY_COUNT(sizes)
+	    && sizes[i][0] < screen->w - 150
+	    && sizes[i][1] < screen->h - 150
+	    && ret->text->slider;
+	    i++)
 	{
 		ret->text->resize(Point(sizes[i][0], sizes[i][1]));
 	}
@@ -227,24 +229,24 @@ void CMessage::drawIWindow(CInfoWindow * ret, std::string text, PlayerColor play
 		ret->text->resize(ret->text->label->textSize + Point(10, 10));
 	}
 
-	std::pair<int,int> winSize(ret->text->pos.w, ret->text->pos.h); //start with text size
+	std::pair<int, int> winSize(ret->text->pos.w, ret->text->pos.h); //start with text size
 
-	ComponentsToBlit comps(ret->components,500, blitOr);
-	if (ret->components.size())
+	ComponentsToBlit comps(ret->components, 500, blitOr);
+	if(ret->components.size())
 		winSize.second += 10 + comps.h; //space to first component
 
 	int bw = 0;
-	if (ret->buttons.size())
+	if(ret->buttons.size())
 	{
 		int bh = 0;
 		// Compute total width of buttons
-		bw = 20*(ret->buttons.size()-1); // space between all buttons
+		bw = 20 * (ret->buttons.size() - 1); // space between all buttons
 		for(auto & elem : ret->buttons) //and add buttons width
 		{
-			bw+=elem->pos.w;
+			bw += elem->pos.w;
 			vstd::amax(bh, elem->pos.h);
 		}
-		winSize.second += 20 + bh;//before button + button
+		winSize.second += 20 + bh; //before button + button
 	}
 
 	// Clip window size
@@ -255,33 +257,33 @@ void CMessage::drawIWindow(CInfoWindow * ret, std::string text, PlayerColor play
 
 	vstd::amin(winSize.first, screen->w - 150);
 
-	ret->bitmap = drawDialogBox (winSize.first + 2*SIDE_MARGIN, winSize.second + 2*SIDE_MARGIN, player);
-	ret->pos.h=ret->bitmap->h;
-	ret->pos.w=ret->bitmap->w;
+	ret->bitmap = drawDialogBox(winSize.first + 2 * SIDE_MARGIN, winSize.second + 2 * SIDE_MARGIN, player);
+	ret->pos.h = ret->bitmap->h;
+	ret->pos.w = ret->bitmap->w;
 	ret->center();
 
 	int curh = SIDE_MARGIN;
-	int xOffset = (ret->pos.w - ret->text->pos.w)/2;
+	int xOffset = (ret->pos.w - ret->text->pos.w) / 2;
 
 	if(!ret->buttons.size() && !ret->components.size()) //improvement for very small text only popups -> center text vertically
 	{
-		if(ret->bitmap->h > ret->text->pos.h + 2*SIDE_MARGIN)
-			curh = (ret->bitmap->h - ret->text->pos.h)/2;
+		if(ret->bitmap->h > ret->text->pos.h + 2 * SIDE_MARGIN)
+			curh = (ret->bitmap->h - ret->text->pos.h) / 2;
 	}
 
 	ret->text->moveBy(Point(xOffset, curh));
 
 	curh += ret->text->pos.h;
 
-	if (ret->components.size())
+	if(ret->components.size())
 	{
 		curh += BEFORE_COMPONENTS;
-		comps.blitCompsOnSur (blitOr, BETWEEN_COMPS, curh, ret->bitmap);
+		comps.blitCompsOnSur(blitOr, BETWEEN_COMPS, curh, ret->bitmap);
 	}
 	if(ret->buttons.size())
 	{
 		// Position the buttons at the bottom of the window
-		bw = (ret->bitmap->w/2) - (bw/2);
+		bw = (ret->bitmap->w / 2) - (bw / 2);
 		curh = ret->bitmap->h - SIDE_MARGIN - ret->buttons[0]->pos.h;
 
 		for(auto & elem : ret->buttons)
@@ -290,7 +292,7 @@ void CMessage::drawIWindow(CInfoWindow * ret, std::string text, PlayerColor play
 			bw += elem->pos.w + 20;
 		}
 	}
-	for(size_t i=0; i<ret->components.size(); i++)
+	for(size_t i = 0; i < ret->components.size(); i++)
 		ret->components[i]->moveBy(Point(ret->pos.x, ret->pos.y));
 }
 
@@ -298,17 +300,18 @@ void CMessage::drawBorder(PlayerColor playerColor, SDL_Surface * ret, int w, int
 {
 	if(playerColor.isSpectator())
 		playerColor = PlayerColor(1);
-	std::vector<const IImage*> &box = piecesOfBox.at(playerColor.getNum());
+	std::vector<const IImage *> & box = piecesOfBox.at(playerColor.getNum());
 
 	// Note: this code assumes that the corner dimensions are all the same.
 
 	// Horizontal borders
 	int start_x = x + box[0]->width();
 	const int stop_x = x + w - box[1]->width();
-	const int bottom_y = y+h-box[7]->height()+1;
-	while (start_x < stop_x) {
+	const int bottom_y = y + h - box[7]->height() + 1;
+	while(start_x < stop_x)
+	{
 		int cur_w = stop_x - start_x;
-		if (cur_w > box[6]->width())
+		if(cur_w > box[6]->width())
 			cur_w = box[6]->width();
 
 		// Top border
@@ -325,11 +328,12 @@ void CMessage::drawBorder(PlayerColor playerColor, SDL_Surface * ret, int w, int
 
 	// Vertical borders
 	int start_y = y + box[0]->height();
-	const int stop_y = y + h - box[2]->height()+1;
-	const int right_x = x+w-box[5]->width();
-	while (start_y < stop_y) {
+	const int stop_y = y + h - box[2]->height() + 1;
+	const int right_x = x + w - box[5]->width();
+	while(start_y < stop_y)
+	{
 		int cur_h = stop_y - start_y;
-		if (cur_h > box[4]->height())
+		if(cur_h > box[4]->height())
 			cur_h = box[4]->height();
 
 		// Left border
@@ -348,23 +352,23 @@ void CMessage::drawBorder(PlayerColor playerColor, SDL_Surface * ret, int w, int
 	Rect dstR(x, y, box[0]->width(), box[0]->height());
 	box[0]->draw(ret, &dstR, nullptr);
 
-	dstR=Rect(x+w-box[1]->width(), y,   box[1]->width(), box[1]->height());
+	dstR = Rect(x + w - box[1]->width(), y, box[1]->width(), box[1]->height());
 	box[1]->draw(ret, &dstR, nullptr);
 
-	dstR=Rect(x, y+h-box[2]->height()+1, box[2]->width(), box[2]->height());
+	dstR = Rect(x, y + h - box[2]->height() + 1, box[2]->width(), box[2]->height());
 	box[2]->draw(ret, &dstR, nullptr);
 
-	dstR=Rect(x+w-box[3]->width(), y+h-box[3]->height()+1, box[3]->width(), box[3]->height());
+	dstR = Rect(x + w - box[3]->width(), y + h - box[3]->height() + 1, box[3]->width(), box[3]->height());
 	box[3]->draw(ret, &dstR, nullptr);
 }
 
-ComponentResolved::ComponentResolved( CComponent *Comp ):
-	comp(Comp)
+ComponentResolved::ComponentResolved(CComponent * Comp)
+	: comp(Comp)
 {
 	//Temporary assign ownership on comp
-	if (parent)
+	if(parent)
 		parent->removeChild(this);
-	if (comp->parent)
+	if(comp->parent)
 	{
 		comp->parent->addChild(this);
 		comp->parent->removeChild(comp);
@@ -380,14 +384,14 @@ ComponentResolved::ComponentResolved( CComponent *Comp ):
 
 ComponentResolved::~ComponentResolved()
 {
-	if (parent)
+	if(parent)
 	{
 		removeChild(comp);
 		parent->addChild(comp);
 	}
 }
 
-void ComponentResolved::showAll(SDL_Surface *to)
+void ComponentResolved::showAll(SDL_Surface * to)
 {
 	CIntObject::showAll(to);
 	comp->showAll(to);
@@ -401,7 +405,7 @@ ComponentsToBlit::~ComponentsToBlit()
 
 }
 
-ComponentsToBlit::ComponentsToBlit(std::vector<CComponent*> & SComps, int maxw, bool blitOr)
+ComponentsToBlit::ComponentsToBlit(std::vector<CComponent *> & SComps, int maxw, bool blitOr)
 {
 	int orWidth = graphics->fonts[FONT_MEDIUM]->getStringWidth(CGI->generaltexth->allTexts[4]);
 
@@ -415,20 +419,20 @@ ComponentsToBlit::ComponentsToBlit(std::vector<CComponent*> & SComps, int maxw,
 
 	for(auto & SComp : SComps)
 	{
-		auto  cur = new ComponentResolved(SComp);
+		auto cur = new ComponentResolved(SComp);
 
 		int toadd = (cur->pos.w + BETWEEN_COMPS + (blitOr ? orWidth : 0));
-		if (curw + toadd > maxw)
+		if(curw + toadd > maxw)
 		{
 			curr++;
-			vstd::amax(w,curw);
+			vstd::amax(w, curw);
 			curw = cur->pos.w;
-			comps.resize(curr+1);
+			comps.resize(curr + 1);
 		}
 		else
 		{
 			curw += toadd;
-			vstd::amax(w,curw);
+			vstd::amax(w, curw);
 		}
 
 		comps[curr].push_back(cur);
@@ -437,39 +441,39 @@ ComponentsToBlit::ComponentsToBlit(std::vector<CComponent*> & SComps, int maxw,
 	for(auto & elem : comps)
 	{
 		int maxHeight = 0;
-		for(size_t j=0;j<elem.size();j++)
+		for(size_t j = 0; j < elem.size(); j++)
 			vstd::amax(maxHeight, elem[j]->pos.h);
 
 		h += maxHeight + BETWEEN_COMPS_ROWS;
 	}
 }
 
-void ComponentsToBlit::blitCompsOnSur( bool blitOr, int inter, int &curh, SDL_Surface *ret )
+void ComponentsToBlit::blitCompsOnSur(bool blitOr, int inter, int & curh, SDL_Surface * ret)
 {
 	int orWidth = graphics->fonts[FONT_MEDIUM]->getStringWidth(CGI->generaltexth->allTexts[4]);
 
-	for (auto & elem : comps)//for each row
+	for(auto & elem : comps) //for each row
 	{
-		int totalw=0, maxHeight=0;
-		for(size_t j=0;j<elem.size();j++)//find max height & total width in this row
+		int totalw = 0, maxHeight = 0;
+		for(size_t j = 0; j < elem.size(); j++) //find max height & total width in this row
 		{
-			ComponentResolved *cur = elem[j];
+			ComponentResolved * cur = elem[j];
 			totalw += cur->pos.w;
 			vstd::amax(maxHeight, cur->pos.h);
 		}
 
 		//add space between comps in this row
 		if(blitOr)
-			totalw += (inter*2+orWidth) * (elem.size() - 1);
+			totalw += (inter * 2 + orWidth) * (elem.size() - 1);
 		else
 			totalw += (inter) * (elem.size() - 1);
 
-		int middleh = curh + maxHeight/2;//axis for image aligment
-		int curw = ret->w/2 - totalw/2;
+		int middleh = curh + maxHeight / 2; //axis for image aligment
+		int curw = ret->w / 2 - totalw / 2;
 
-		for(size_t j=0;j<elem.size();j++)
+		for(size_t j = 0; j < elem.size(); j++)
 		{
-			ComponentResolved *cur = elem[j];
+			ComponentResolved * cur = elem[j];
 			cur->moveTo(Point(curw, curh));
 
 			//blit component
@@ -477,18 +481,18 @@ void ComponentsToBlit::blitCompsOnSur( bool blitOr, int inter, int &curh, SDL_Su
 			curw += cur->pos.w;
 
 			//if there is subsequent component blit "or"
-			if(j<(elem.size()-1))
+			if(j < (elem.size() - 1))
 			{
 				if(blitOr)
 				{
-					curw+=inter;
+					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 - (graphics->fonts[FONT_MEDIUM]->getLineHeight() / 2)));
 
-					curw+=orWidth;
+					curw += orWidth;
 				}
-				curw+=inter;
+				curw += inter;
 			}
 		}
 		curh += maxHeight + BETWEEN_COMPS_ROWS;

+ 2 - 2
client/CMessage.h

@@ -21,10 +21,10 @@ class CMessage
 {
 public:
 	//Function usd only in CMessage.cpp
-	static std::pair<int,int> getMaxSizes(std::vector<std::vector<SDL_Surface*> > * txtg, int fontHeight);
+	static std::pair<int, int> getMaxSizes(std::vector<std::vector<SDL_Surface *>> * txtg, int fontHeight);
 
 	/// Draw border on exiting surface
-	static void drawBorder(PlayerColor playerColor, SDL_Surface * ret, int w, int h, int x=0, int y=0);
+	static void drawBorder(PlayerColor playerColor, SDL_Surface * ret, int w, int h, int x = 0, int y = 0);
 
 	/// Draw simple dialog box (borders and background only)
 	static SDL_Surface * drawDialogBox(int w, int h, PlayerColor playerColor = PlayerColor(1));

+ 81 - 83
client/CMusicHandler.cpp

@@ -25,9 +25,10 @@
 #define VCMI_SOUND_FILE(y) #y,
 
 // sounds mapped to soundBase enum
-static std::string sounds[] = {
-    "", // invalid
-    "", // todo
+static std::string sounds[] =
+{
+	"", // invalid
+	"", // todo
 	VCMI_SOUND_LIST
 };
 #undef VCMI_SOUND_NAME
@@ -46,10 +47,10 @@ static void musicFinishedCallbackC(void)
 
 void CAudioBase::init()
 {
-	if (initialized)
+	if(initialized)
 		return;
 
-	if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 1024)==-1)
+	if(Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 1024) == -1)
 	{
 		logGlobal->errorStream() << "Mix_OpenAudio error: " << Mix_GetError();
 		return;
@@ -60,7 +61,7 @@ void CAudioBase::init()
 
 void CAudioBase::release()
 {
-	if (initialized)
+	if(initialized)
 	{
 		Mix_CloseAudio();
 		initialized = false;
@@ -69,19 +70,19 @@ void CAudioBase::release()
 
 void CAudioBase::setVolume(ui32 percent)
 {
-	if (percent > 100)
+	if(percent > 100)
 		percent = 100;
 
 	volume = percent;
 }
 
-void CSoundHandler::onVolumeChange(const JsonNode &volumeNode)
+void CSoundHandler::onVolumeChange(const JsonNode & volumeNode)
 {
 	setVolume(volumeNode.Float());
 }
 
-CSoundHandler::CSoundHandler():
-	listener(settings.listen["general"]["sound"])
+CSoundHandler::CSoundHandler()
+	: listener(settings.listen["general"]["sound"])
 {
 	listener(std::bind(&CSoundHandler::onVolumeChange, this, _1));
 
@@ -92,19 +93,19 @@ CSoundHandler::CSoundHandler():
 		soundBase::pickup04, soundBase::pickup05, soundBase::pickup06, soundBase::pickup07
 	};
 
-    horseSounds =  // must be the same order as terrains (see ETerrainType);
-    {
+	horseSounds = // must be the same order as terrains (see ETerrainType);
+	{
 		soundBase::horseDirt, soundBase::horseSand, soundBase::horseGrass,
 		soundBase::horseSnow, soundBase::horseSwamp, soundBase::horseRough,
 		soundBase::horseSubterranean, soundBase::horseLava,
 		soundBase::horseWater, soundBase::horseRock
-    };
+	};
 
 	battleIntroSounds =
 	{
 		soundBase::battle00, soundBase::battle01,
-	    soundBase::battle02, soundBase::battle03, soundBase::battle04,
-	    soundBase::battle05, soundBase::battle06, soundBase::battle07
+		soundBase::battle02, soundBase::battle03, soundBase::battle04,
+		soundBase::battle05, soundBase::battle06, soundBase::battle07
 	};
 };
 
@@ -112,7 +113,7 @@ void CSoundHandler::init()
 {
 	CAudioBase::init();
 
-	if (initialized)
+	if(initialized)
 	{
 		// Load sounds
 		Mix_ChannelFinished(soundFinishedCallbackC);
@@ -121,13 +122,13 @@ void CSoundHandler::init()
 
 void CSoundHandler::release()
 {
-	if (initialized)
+	if(initialized)
 	{
 		Mix_HaltChannel(-1);
 
-		for (auto &chunk : soundChunks)
+		for(auto & chunk : soundChunks)
 		{
-			if (chunk.second.first)
+			if(chunk.second.first)
 				Mix_FreeChunk(chunk.second.first);
 		}
 	}
@@ -136,23 +137,23 @@ void CSoundHandler::release()
 }
 
 // Allocate an SDL chunk and cache it.
-Mix_Chunk *CSoundHandler::GetSoundChunk(std::string &sound, bool cache)
+Mix_Chunk * CSoundHandler::GetSoundChunk(std::string & sound, bool cache)
 {
 	try
 	{
-		if (cache && soundChunks.find(sound) != soundChunks.end())
+		if(cache && soundChunks.find(sound) != soundChunks.end())
 			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);
-		Mix_Chunk *chunk = Mix_LoadWAV_RW(ops, 1);	// will free ops
+		SDL_RWops * ops = SDL_RWFromMem(data.first.get(), data.second);
+		Mix_Chunk * chunk = Mix_LoadWAV_RW(ops, 1); // will free ops
 
-		if (cache)
-			soundChunks.insert(std::pair<std::string, CachedChunk>(sound, std::make_pair (chunk, std::move (data.first))));
+		if(cache)
+			soundChunks.insert(std::pair<std::string, CachedChunk>(sound, std::make_pair(chunk, std::move(data.first))));
 
 		return chunk;
 	}
-	catch(std::exception &e)
+	catch(std::exception & e)
 	{
 		logGlobal->warnStream() << "Cannot get sound " << sound << " chunk: " << e.what();
 		return nullptr;
@@ -171,22 +172,22 @@ int CSoundHandler::playSound(soundBase::soundID soundID, int repeats)
 
 int CSoundHandler::playSound(std::string sound, int repeats, bool cache)
 {
-	if (!initialized || sound.empty())
+	if(!initialized || sound.empty())
 		return -1;
 
 	int channel;
-	Mix_Chunk *chunk = GetSoundChunk(sound, cache);
+	Mix_Chunk * chunk = GetSoundChunk(sound, cache);
 
-	if (chunk)
+	if(chunk)
 	{
 		channel = Mix_PlayChannel(-1, chunk, repeats);
-		if (channel == -1)
+		if(channel == -1)
 		{
 			logGlobal->errorStream() << "Unable to play sound file " << sound << " , error " << Mix_GetError();
-			if (!cache)
+			if(!cache)
 				Mix_FreeChunk(chunk);
 		}
-		else if (cache)
+		else if(cache)
 			callbacks[channel];
 		else
 			callbacks[channel] = [chunk](){ Mix_FreeChunk(chunk);};
@@ -198,14 +199,14 @@ int CSoundHandler::playSound(std::string sound, int repeats, bool cache)
 }
 
 // Helper. Randomly select a sound from an array and play it
-int CSoundHandler::playSoundFromSet(std::vector<soundBase::soundID> &sound_vec)
+int CSoundHandler::playSoundFromSet(std::vector<soundBase::soundID> & sound_vec)
 {
 	return playSound(*RandomGeneratorUtil::nextItem(sound_vec, CRandomGenerator::getDefault()));
 }
 
-void CSoundHandler::stopSound( int handler )
+void CSoundHandler::stopSound(int handler)
 {
-	if (initialized && handler != -1)
+	if(initialized && handler != -1)
 		Mix_HaltChannel(handler);
 }
 
@@ -214,13 +215,13 @@ void CSoundHandler::setVolume(ui32 percent)
 {
 	CAudioBase::setVolume(percent);
 
-	if (initialized)
-		Mix_Volume(-1, (MIX_MAX_VOLUME * volume)/100);
+	if(initialized)
+		Mix_Volume(-1, (MIX_MAX_VOLUME * volume) / 100);
 }
 
 void CSoundHandler::setCallback(int channel, std::function<void()> function)
 {
-	std::map<int, std::function<void()> >::iterator iter;
+	std::map<int, std::function<void()>>::iterator iter;
 	iter = callbacks.find(channel);
 
 	//channel not found. It may have finished so fire callback now
@@ -232,24 +233,24 @@ void CSoundHandler::setCallback(int channel, std::function<void()> function)
 
 void CSoundHandler::soundFinishedCallback(int channel)
 {
-	std::map<int, std::function<void()> >::iterator iter;
+	std::map<int, std::function<void()>>::iterator iter;
 	iter = callbacks.find(channel);
 
 	assert(iter != callbacks.end());
 
-	if (iter->second)
+	if(iter->second)
 		iter->second();
 
 	callbacks.erase(iter);
 }
 
-void CMusicHandler::onVolumeChange(const JsonNode &volumeNode)
+void CMusicHandler::onVolumeChange(const JsonNode & volumeNode)
 {
 	setVolume(volumeNode.Float());
 }
 
-CMusicHandler::CMusicHandler():
-	listener(settings.listen["general"]["music"])
+CMusicHandler::CMusicHandler()
+	: listener(settings.listen["general"]["music"])
 {
 	listener(std::bind(&CMusicHandler::onVolumeChange, this, _1));
 	// Map music IDs
@@ -258,15 +259,15 @@ CMusicHandler::CMusicHandler():
 	const std::string setBattle[] = {"Combat01", "Combat02", "Combat03", "Combat04"};
 
 	auto fillSet = [=](std::string setName, const std::string list[], size_t amount)
-	{
-		for (size_t i=0; i < amount; i++)
-			addEntryToSet(setName, i, "music/" + list[i]);
-	};
+		{
+			for(size_t i = 0; i < amount; i++)
+				addEntryToSet(setName, i, "music/" + list[i]);
+		};
 	fillSet("enemy-turn", setEnemy, ARRAY_COUNT(setEnemy));
 	fillSet("battle", setBattle, ARRAY_COUNT(setBattle));
 
 	JsonNode terrains(ResourceID("config/terrains.json"));
-	for (auto entry : terrains.Struct())
+	for(auto entry : terrains.Struct())
 	{
 		int terrIndex = vstd::find_pos(GameConstants::TERRAIN_NAMES, entry.first);
 		addEntryToSet("terrain", terrIndex, "Music/" + entry.second["music"].String());
@@ -282,13 +283,13 @@ void CMusicHandler::init()
 {
 	CAudioBase::init();
 
-	if (initialized)
+	if(initialized)
 		Mix_HookMusicFinished(musicFinishedCallbackC);
 }
 
 void CMusicHandler::release()
 {
-	if (initialized)
+	if(initialized)
 	{
 		boost::mutex::scoped_lock guard(musicMutex);
 
@@ -303,7 +304,7 @@ void CMusicHandler::release()
 
 void CMusicHandler::playMusic(std::string musicURI, bool loop)
 {
-	if (current && current->isTrack(musicURI))
+	if(current && current->isTrack(musicURI))
 		return;
 
 	queueNext(this, "", musicURI, loop);
@@ -312,13 +313,13 @@ void CMusicHandler::playMusic(std::string musicURI, bool loop)
 void CMusicHandler::playMusicFromSet(std::string whichSet, bool loop)
 {
 	auto selectedSet = musicsSet.find(whichSet);
-	if (selectedSet == musicsSet.end())
+	if(selectedSet == musicsSet.end())
 	{
 		logGlobal->errorStream() << "Error: playing music from non-existing set: " << whichSet;
 		return;
 	}
 
-	if (current && current->isSet(whichSet))
+	if(current && current->isSet(whichSet))
 		return;
 
 	// in this mode - play random track from set
@@ -329,20 +330,20 @@ void CMusicHandler::playMusicFromSet(std::string whichSet, bool loop)
 void CMusicHandler::playMusicFromSet(std::string whichSet, int entryID, bool loop)
 {
 	auto selectedSet = musicsSet.find(whichSet);
-	if (selectedSet == musicsSet.end())
+	if(selectedSet == musicsSet.end())
 	{
 		logGlobal->errorStream() << "Error: playing music from non-existing set: " << whichSet;
 		return;
 	}
 
 	auto selectedEntry = selectedSet->second.find(entryID);
-	if (selectedEntry == selectedSet->second.end())
+	if(selectedEntry == selectedSet->second.end())
 	{
 		logGlobal->errorStream() << "Error: playing non-existing entry " << entryID << " from set: " << whichSet;
 		return;
 	}
 
-	if (current && current->isTrack(selectedEntry->second))
+	if(current && current->isTrack(selectedEntry->second))
 		return;
 
 	// in this mode - play specific track from set
@@ -351,27 +352,27 @@ void CMusicHandler::playMusicFromSet(std::string whichSet, int entryID, bool loo
 
 void CMusicHandler::queueNext(std::unique_ptr<MusicEntry> queued)
 {
-	if (!initialized)
+	if(!initialized)
 		return;
 
 	boost::mutex::scoped_lock guard(musicMutex);
 
 	next = std::move(queued);
 
-	if (current.get() == nullptr || !current->stop(1000))
+	if(current.get() == nullptr || !current->stop(1000))
 	{
 		current.reset(next.release());
 		current->play();
 	}
 }
 
-void CMusicHandler::queueNext(CMusicHandler *owner, std::string setName, std::string musicURI, bool looped)
+void CMusicHandler::queueNext(CMusicHandler * owner, std::string setName, std::string musicURI, bool looped)
 {
 	try
 	{
 		queueNext(make_unique<MusicEntry>(owner, setName, musicURI, looped));
 	}
-	catch(std::exception &e)
+	catch(std::exception & e)
 	{
 		logGlobal->errorStream() << "Failed to queue music. setName=" << setName << "\tmusicURI=" << musicURI;
 		logGlobal->errorStream() << "Exception: " << e.what();
@@ -380,12 +381,12 @@ void CMusicHandler::queueNext(CMusicHandler *owner, std::string setName, std::st
 
 void CMusicHandler::stopMusic(int fade_ms)
 {
-	if (!initialized)
+	if(!initialized)
 		return;
 
 	boost::mutex::scoped_lock guard(musicMutex);
 
-	if (current.get() != nullptr)
+	if(current.get() != nullptr)
 		current->stop(fade_ms);
 	next.reset();
 }
@@ -394,58 +395,55 @@ void CMusicHandler::setVolume(ui32 percent)
 {
 	CAudioBase::setVolume(percent);
 
-	if (initialized)
-		Mix_VolumeMusic((MIX_MAX_VOLUME * volume)/100);
+	if(initialized)
+		Mix_VolumeMusic((MIX_MAX_VOLUME * volume) / 100);
 }
 
 void CMusicHandler::musicFinishedCallback(void)
 {
 	boost::mutex::scoped_lock guard(musicMutex);
 
-	if (current.get() != nullptr)
+	if(current.get() != nullptr)
 	{
 		//return if current music still not finished
-		if (current->play())
+		if(current->play())
 			return;
 		else
 			current.reset();
 	}
 
-	if (current.get() == nullptr && next.get() != nullptr)
+	if(current.get() == nullptr && next.get() != nullptr)
 	{
 		current.reset(next.release());
 		current->play();
 	}
 }
 
-MusicEntry::MusicEntry(CMusicHandler *owner, std::string setName, std::string musicURI, bool looped):
-	owner(owner),
-	music(nullptr),
-	loop(looped ? -1 : 1),
-    setName(std::move(setName))
+MusicEntry::MusicEntry(CMusicHandler * owner, std::string setName, std::string musicURI, bool looped)
+	: owner(owner), music(nullptr), loop(looped ? -1 : 1), setName(std::move(setName))
 {
-	if (!musicURI.empty())
+	if(!musicURI.empty())
 		load(std::move(musicURI));
 }
 MusicEntry::~MusicEntry()
 {
-	logGlobal->traceStream()<<"Del-ing music file "<<currentName;
-	if (music)
+	logGlobal->traceStream() << "Del-ing music file " << currentName;
+	if(music)
 		Mix_FreeMusic(music);
 }
 
 void MusicEntry::load(std::string musicURI)
 {
-	if (music)
+	if(music)
 	{
-		logGlobal->traceStream()<<"Del-ing music file "<<currentName;
+		logGlobal->traceStream() << "Del-ing music file " << currentName;
 		Mix_FreeMusic(music);
 		music = nullptr;
 	}
 
 	currentName = musicURI;
 
-	logGlobal->traceStream()<<"Loading music file "<<musicURI;
+	logGlobal->traceStream() << "Loading music file " << musicURI;
 
 	auto musicFile = MakeSDLRWops(CResourceHandler::get()->load(ResourceID(std::move(musicURI), EResType::MUSIC)));
 
@@ -460,16 +458,16 @@ void MusicEntry::load(std::string musicURI)
 
 bool MusicEntry::play()
 {
-	if (!(loop--) && music) //already played once - return
+	if(!(loop--) && music) //already played once - return
 		return false;
 
-	if (!setName.empty())
+	if(!setName.empty())
 	{
 		auto set = owner->musicsSet[setName];
 		load(RandomGeneratorUtil::nextItem(set, CRandomGenerator::getDefault())->second);
 	}
 
-	logGlobal->traceStream()<<"Playing music file "<<currentName;
+	logGlobal->traceStream() << "Playing music file " << currentName;
 	if(Mix_PlayMusic(music, 1) == -1)
 	{
 		logGlobal->errorStream() << "Unable to play music (" << Mix_GetError() << ")";
@@ -480,9 +478,9 @@ bool MusicEntry::play()
 
 bool MusicEntry::stop(int fade_ms)
 {
-	if (Mix_PlayingMusic())
+	if(Mix_PlayingMusic())
 	{
-		logGlobal->traceStream()<<"Stopping music file "<<currentName;
+		logGlobal->traceStream() << "Stopping music file " << currentName;
 		loop = 0;
 		Mix_FadeOutMusic(fade_ms);
 		return true;

+ 23 - 20
client/CMusicHandler.h

@@ -18,13 +18,15 @@ struct SDL_RWops;
 typedef struct _Mix_Music Mix_Music;
 struct Mix_Chunk;
 
-class CAudioBase {
+class CAudioBase
+{
 protected:
 	bool initialized;
-	int volume;					// from 0 (mute) to 100
+	int volume; // from 0 (mute) to 100
 
 public:
-	CAudioBase(): initialized(false), volume(0) {};
+	CAudioBase()
+		: initialized(false), volume(0) {};
 	virtual void init() = 0;
 	virtual void release() = 0;
 
@@ -32,22 +34,22 @@ public:
 	ui32 getVolume() { return volume; };
 };
 
-class CSoundHandler: public CAudioBase
+class CSoundHandler : public CAudioBase
 {
 private:
 	//soundBase::soundID getSoundID(const std::string &fileName);
 	//update volume on configuration change
 	SettingsListener listener;
-	void onVolumeChange(const JsonNode &volumeNode);
+	void onVolumeChange(const JsonNode & volumeNode);
 
 	using CachedChunk = std::pair<Mix_Chunk *, std::unique_ptr<ui8[]>>;
 	std::map<std::string, CachedChunk> soundChunks;
 
-	Mix_Chunk *GetSoundChunk(std::string &sound, bool cache);
+	Mix_Chunk * GetSoundChunk(std::string & sound, bool cache);
 
 	//have entry for every currently active channel
 	//std::function will be nullptr if callback was not set
-	std::map<int, std::function<void()> > callbacks;
+	std::map<int, std::function<void()>> callbacks;
 
 public:
 	CSoundHandler();
@@ -58,9 +60,9 @@ public:
 	void setVolume(ui32 percent) override;
 
 	// Sounds
-	int playSound(soundBase::soundID soundID, int repeats=0);
-	int playSound(std::string sound, int repeats=0, bool cache=false);
-	int playSoundFromSet(std::vector<soundBase::soundID> &sound_vec);
+	int playSound(soundBase::soundID soundID, int repeats = 0);
+	int playSound(std::string sound, int repeats = 0, bool cache = false);
+	int playSoundFromSet(std::vector<soundBase::soundID> & sound_vec);
 	void stopSound(int handler);
 
 	void setCallback(int channel, std::function<void()> function);
@@ -73,15 +75,15 @@ public:
 };
 
 // Helper //now it looks somewhat useless
-#define battle_sound(creature,what_sound) creature->sounds.what_sound
+#define battle_sound(creature, what_sound) creature->sounds.what_sound
 
 class CMusicHandler;
 
 //Class for handling one music file
 class MusicEntry
 {
-	CMusicHandler *owner;
-	Mix_Music *music;
+	CMusicHandler * owner;
+	Mix_Music * music;
 
 	int loop; // -1 = indefinite
 	//if not null - set from which music will be randomly selected
@@ -95,14 +97,14 @@ public:
 	bool isSet(std::string setName);
 	bool isTrack(std::string trackName);
 
-	MusicEntry(CMusicHandler *owner, std::string setName, std::string musicURI, bool looped);
+	MusicEntry(CMusicHandler * owner, std::string setName, std::string musicURI, bool looped);
 	~MusicEntry();
 
 	bool play();
-	bool stop(int fade_ms=0);
+	bool stop(int fade_ms = 0);
 };
 
-class CMusicHandler: public CAudioBase
+class CMusicHandler : public CAudioBase
 {
 private:
 	// Because we use the SDL music callback, our music variables must
@@ -110,15 +112,16 @@ private:
 	boost::mutex musicMutex;
 	//update volume on configuration change
 	SettingsListener listener;
-	void onVolumeChange(const JsonNode &volumeNode);
+	void onVolumeChange(const JsonNode & volumeNode);
 
 	std::unique_ptr<MusicEntry> current;
 	std::unique_ptr<MusicEntry> next;
 
-	void queueNext(CMusicHandler *owner, std::string setName, std::string musicURI, bool looped);
+	void queueNext(CMusicHandler * owner, std::string setName, std::string musicURI, bool looped);
 	void queueNext(std::unique_ptr<MusicEntry> queued);
 
-	std::map<std::string, std::map<int, std::string> > musicsSet;
+	std::map<std::string, std::map<int, std::string>> musicsSet;
+
 public:
 	CMusicHandler();
 
@@ -135,7 +138,7 @@ public:
 	void playMusicFromSet(std::string musicSet, bool loop);
 	/// play specific track from set
 	void playMusicFromSet(std::string musicSet, int entryID, bool loop);
-	void stopMusic(int fade_ms=1000);
+	void stopMusic(int fade_ms = 1000);
 	void musicFinishedCallback(void);
 
 	friend class MusicEntry;

File diff suppressed because it is too large
+ 198 - 185
client/CPlayerInterface.cpp


+ 75 - 73
client/CPlayerInterface.h

@@ -44,7 +44,7 @@ class CCreatureSet;
 class CGObjectInstance;
 class CSlider;
 struct UpgradeInfo;
-template <typename T> struct CondSh;
+template<typename T> struct CondSh;
 class CInGameConsole;
 class CGarrisonInt;
 class CInGameConsole;
@@ -62,8 +62,8 @@ struct CPathsInfo;
 
 namespace boost
 {
-	class mutex;
-	class recursive_mutex;
+class mutex;
+class recursive_mutex;
 }
 
 enum
@@ -82,14 +82,15 @@ enum
 class CPlayerInterface : public CGameInterface, public IUpdateable
 {
 	const CArmedInstance * currentSelection;
+
 public:
 	ObjectInstanceID destinationTeleport; //contain -1 or object id if teleportation
 	int3 destinationTeleportPos;
 
 	//minor interfaces
-	CondSh<bool> *showingDialog; //indicates if dialog box is displayed
+	CondSh<bool> * showingDialog; //indicates if dialog box is displayed
 
-	static boost::recursive_mutex *pim;
+	static boost::recursive_mutex * pim;
 	bool makingTurn; //if player is already making his turn
 	int firstCall; // -1 - just loaded game; 1 - just started game; 0 otherwise
 	int autosaveCount;
@@ -101,7 +102,7 @@ public:
 	CInGameConsole * cingconsole;
 
 	std::shared_ptr<CCallback> cb; //to communicate with engine
-	const BattleAction *curAction; //during the battle - action currently performed by active stack (or nullptr)
+	const BattleAction * curAction; //during the battle - action currently performed by active stack (or nullptr)
 
 	std::list<CInfoWindow *> dialogs; //queue of dialogs awaiting to be shown (not currently shown!)
 
@@ -123,7 +124,7 @@ public:
 		int spellbookLastTabBattle, spellbookLastTabAdvmap; //on which page we left spellbook
 
 		SpellbookLastSetting();
-		template <typename Handler> void serialize( Handler &h, const int version )
+		template<typename Handler> void serialize(Handler & h, const int version)
 		{
 			h & spellbookLastPageBattle & spellbokLastPageAdvmap & spellbookLastTabBattle & spellbookLastTabAdvmap;
 		}
@@ -134,88 +135,88 @@ public:
 	int getLastIndex(std::string namePrefix);
 
 	//overridden funcs from CGameInterface
-	void buildChanged(const CGTownInstance *town, BuildingID buildingID, int what) override; //what: 1 - built, 2 - demolished
-	void stackChagedCount(const StackLocation &location, const TQuantity &change, bool isAbsolute) override; //if absolute, change is the new count; otherwise count was modified by adding change
-	void stackChangedType(const StackLocation &location, const CCreature &newType) override; //used eg. when upgrading creatures
-	void stacksErased(const StackLocation &location) override; //stack removed from previously filled slot
-	void stacksSwapped(const StackLocation &loc1, const StackLocation &loc2) override;
-	void newStackInserted(const StackLocation &location, const CStackInstance &stack) override; //new stack inserted at given (previously empty position)
-	void stacksRebalanced(const StackLocation &src, const StackLocation &dst, TQuantity count) override; //moves creatures from src stack to dst slot, may be used for merging/splittint/moving stacks
-
-	void artifactPut(const ArtifactLocation &al) override;
-	void artifactRemoved(const ArtifactLocation &al) override;
-	void artifactMoved(const ArtifactLocation &src, const ArtifactLocation &dst) override;
-	void artifactAssembled(const ArtifactLocation &al) override;
-	void artifactDisassembled(const ArtifactLocation &al) override;
-
-	void heroCreated(const CGHeroInstance* hero) override;
-	void heroGotLevel(const CGHeroInstance *hero, PrimarySkill::PrimarySkill pskill, std::vector<SecondarySkill> &skills, QueryID queryID) override;
-	void commanderGotLevel (const CCommanderInstance * commander, std::vector<ui32> skills, QueryID queryID) override;
-	void heroInGarrisonChange(const CGTownInstance *town) override;
+	void buildChanged(const CGTownInstance * town, BuildingID buildingID, int what) override; //what: 1 - built, 2 - demolished
+	void stackChagedCount(const StackLocation & location, const TQuantity & change, bool isAbsolute) override; //if absolute, change is the new count; otherwise count was modified by adding change
+	void stackChangedType(const StackLocation & location, const CCreature & newType) override; //used eg. when upgrading creatures
+	void stacksErased(const StackLocation & location) override; //stack removed from previously filled slot
+	void stacksSwapped(const StackLocation & loc1, const StackLocation & loc2) override;
+	void newStackInserted(const StackLocation & location, const CStackInstance & stack) override; //new stack inserted at given (previously empty position)
+	void stacksRebalanced(const StackLocation & src, const StackLocation & dst, TQuantity count) override; //moves creatures from src stack to dst slot, may be used for merging/splittint/moving stacks
+
+	void artifactPut(const ArtifactLocation & al) override;
+	void artifactRemoved(const ArtifactLocation & al) override;
+	void artifactMoved(const ArtifactLocation & src, const ArtifactLocation & dst) override;
+	void artifactAssembled(const ArtifactLocation & al) override;
+	void artifactDisassembled(const ArtifactLocation & al) override;
+
+	void heroCreated(const CGHeroInstance * hero) override;
+	void heroGotLevel(const CGHeroInstance * hero, PrimarySkill::PrimarySkill pskill, std::vector<SecondarySkill> & skills, QueryID queryID) override;
+	void commanderGotLevel(const CCommanderInstance * commander, std::vector<ui32> skills, QueryID queryID) override;
+	void heroInGarrisonChange(const CGTownInstance * town) override;
 	void heroMoved(const TryMoveHero & details) override;
 	void heroPrimarySkillChanged(const CGHeroInstance * hero, int which, si64 val) override;
 	void heroSecondarySkillChanged(const CGHeroInstance * hero, int which, int val) override;
 	void heroManaPointsChanged(const CGHeroInstance * hero) override;
 	void heroMovePointsChanged(const CGHeroInstance * hero) override;
-	void heroVisitsTown(const CGHeroInstance* hero, const CGTownInstance * town) override;
+	void heroVisitsTown(const CGHeroInstance * hero, const CGTownInstance * town) override;
 	void receivedResource() override;
-	void showInfoDialog(const std::string &text, const std::vector<Component*> &components, int soundID) override;
-	void showRecruitmentDialog(const CGDwelling *dwelling, const CArmedInstance *dst, int level) override;
-	void showShipyardDialog(const IShipyard *obj) override; //obj may be town or shipyard;
-	void showBlockingDialog(const std::string &text, const std::vector<Component> &components, QueryID askID, const int soundID, bool selection, bool cancel) override; //Show a dialog, player must take decision. If selection then he has to choose between one of given components, if cancel he is allowed to not choose. After making choice, CCallback::selectionMade should be called with number of selected component (1 - n) or 0 for cancel (if allowed) and askID.
+	void showInfoDialog(const std::string & text, const std::vector<Component *> & components, int soundID) override;
+	void showRecruitmentDialog(const CGDwelling * dwelling, const CArmedInstance * dst, int level) override;
+	void showShipyardDialog(const IShipyard * obj) override; //obj may be town or shipyard;
+	void showBlockingDialog(const std::string & text, const std::vector<Component> & components, QueryID askID, const int soundID, bool selection, bool cancel) override; //Show a dialog, player must take decision. If selection then he has to choose between one of given components, if cancel he is allowed to not choose. After making choice, CCallback::selectionMade should be called with number of selected component (1 - n) or 0 for cancel (if allowed) and askID.
 	void showTeleportDialog(TeleportChannelID channel, TTeleportExitsList exits, bool impassable, QueryID askID) override;
-	void showGarrisonDialog(const CArmedInstance *up, const CGHeroInstance *down, bool removableUnits, QueryID queryID) override;
+	void showGarrisonDialog(const CArmedInstance * up, const CGHeroInstance * down, bool removableUnits, QueryID queryID) override;
 	void showMapObjectSelectDialog(QueryID askID, const Component & icon, const MetaString & title, const MetaString & description, const std::vector<ObjectInstanceID> & objects) override;
 	void showPuzzleMap() override;
 	void viewWorldMap() override;
-	void showMarketWindow(const IMarket *market, const CGHeroInstance *visitor) override;
-	void showUniversityWindow(const IMarket *market, const CGHeroInstance *visitor) override;
-	void showHillFortWindow(const CGObjectInstance *object, const CGHeroInstance *visitor) override;
-	void showTavernWindow(const CGObjectInstance *townOrTavern) override;
-	void showThievesGuildWindow (const CGObjectInstance * obj) override;
+	void showMarketWindow(const IMarket * market, const CGHeroInstance * visitor) override;
+	void showUniversityWindow(const IMarket * market, const CGHeroInstance * visitor) override;
+	void showHillFortWindow(const CGObjectInstance * object, const CGHeroInstance * visitor) override;
+	void showTavernWindow(const CGObjectInstance * townOrTavern) override;
+	void showThievesGuildWindow(const CGObjectInstance * obj) override;
 	void showQuestLog() override;
 	void advmapSpellCast(const CGHeroInstance * caster, int spellID) override; //called when a hero casts a spell
-	void tileHidden(const std::unordered_set<int3, ShashInt3> &pos) override; //called when given tiles become hidden under fog of war
-	void tileRevealed(const std::unordered_set<int3, ShashInt3> &pos) override; //called when fog of war disappears from given tiles
+	void tileHidden(const std::unordered_set<int3, ShashInt3> & pos) override; //called when given tiles become hidden under fog of war
+	void tileRevealed(const std::unordered_set<int3, ShashInt3> & pos) override; //called when fog of war disappears from given tiles
 	void newObject(const CGObjectInstance * obj) override;
-	void availableArtifactsChanged(const CGBlackMarket *bm = nullptr) override; //bm may be nullptr, then artifacts are changed in the global pool (used by merchants in towns)
+	void availableArtifactsChanged(const CGBlackMarket * bm = nullptr) override; //bm may be nullptr, then artifacts are changed in the global pool (used by merchants in towns)
 	void yourTurn() override;
-	void availableCreaturesChanged(const CGDwelling *town) override;
-	void heroBonusChanged(const CGHeroInstance *hero, const Bonus &bonus, bool gain) override;//if gain hero received bonus, else he lost it
-	void playerBonusChanged(const Bonus &bonus, bool gain) override;
-	void requestRealized(PackageApplied *pa) override;
+	void availableCreaturesChanged(const CGDwelling * town) override;
+	void heroBonusChanged(const CGHeroInstance * hero, const Bonus & bonus, bool gain) override; //if gain hero received bonus, else he lost it
+	void playerBonusChanged(const Bonus & bonus, bool gain) override;
+	void requestRealized(PackageApplied * pa) override;
 	void heroExchangeStarted(ObjectInstanceID hero1, ObjectInstanceID hero2, QueryID query) override;
-	void centerView (int3 pos, int focusTime) override;
+	void centerView(int3 pos, int focusTime) override;
 	void objectPropertyChanged(const SetObjectProperty * sop) override;
-	void objectRemoved(const CGObjectInstance *obj) override;
+	void objectRemoved(const CGObjectInstance * obj) override;
 	void gameOver(PlayerColor player, const EVictoryLossCheckResult & victoryLossCheckResult) override;
 	void playerStartsTurn(PlayerColor player) override; //called before yourTurn on active itnerface
-	void showComp(const Component &comp, std::string message) override; //display component in the advmapint infobox
+	void showComp(const Component & comp, std::string message) override; //display component in the advmapint infobox
 	void saveGame(BinarySerializer & h, const int version) override; //saving
 	void loadGame(BinaryDeserializer & h, const int version) override; //loading
 	void showWorldViewEx(const std::vector<ObjectPosInfo> & objectPositions) override;
 
 	//for battles
-	void actionFinished(const BattleAction& action) override;//occurs AFTER action taken by active stack or by the hero
-	void actionStarted(const BattleAction& action) override;//occurs BEFORE action taken by active stack or by the hero
+	void actionFinished(const BattleAction & action) override; //occurs AFTER action taken by active stack or by the hero
+	void actionStarted(const BattleAction & action) override; //occurs BEFORE action taken by active stack or by the hero
 	BattleAction activeStack(const CStack * stack) override; //called when it's turn of that stack
-	void battleAttack(const BattleAttack *ba) override; //stack performs attack
-	void battleEnd(const BattleResult *br) override; //end of battle
+	void battleAttack(const BattleAttack * ba) override; //stack performs attack
+	void battleEnd(const BattleResult * br) override; //end of battle
 	void battleNewRoundFirst(int round) override; //called at the beginning of each turn before changes are applied; used for HP regen handling
 	void battleNewRound(int round) override; //called at the beginning of each turn, round=-1 is the tactic phase, round=0 is the first "normal" turn
 	void battleStackMoved(const CStack * stack, std::vector<BattleHex> dest, int distance) override;
-	void battleSpellCast(const BattleSpellCast *sc) override;
+	void battleSpellCast(const BattleSpellCast * sc) override;
 	void battleStacksEffectsSet(const SetStackEffect & sse) override; //called when a specific effect is set to stacks
 	void battleTriggerEffect(const BattleTriggerEffect & bte) override; //various one-shot effect
 	void battleStacksAttacked(const std::vector<BattleStackAttacked> & bsa) override;
-	void battleStartBefore(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2) override; //called by engine just before battle starts; side=0 - left, side=1 - right
-	void battleStart(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool side) override; //called by engine when battle starts; side=0 - left, side=1 - right
-	void battleStacksHealedRes(const std::vector<std::pair<ui32, ui32> > & healedStacks, bool lifeDrain, bool tentHeal, si32 lifeDrainFrom) override; //called when stacks are healed / resurrected
+	void battleStartBefore(const CCreatureSet * army1, const CCreatureSet * army2, int3 tile, const CGHeroInstance * hero1, const CGHeroInstance * hero2) override; //called by engine just before battle starts; side=0 - left, side=1 - right
+	void battleStart(const CCreatureSet * army1, const CCreatureSet * army2, int3 tile, const CGHeroInstance * hero1, const CGHeroInstance * hero2, bool side) override; //called by engine when battle starts; side=0 - left, side=1 - right
+	void battleStacksHealedRes(const std::vector<std::pair<ui32, ui32>> & healedStacks, bool lifeDrain, bool tentHeal, si32 lifeDrainFrom) override; //called when stacks are healed / resurrected
 	void battleNewStackAppeared(const CStack * stack) override; //not called at the beginning of a battle or by resurrection; called eg. when elemental is summoned
 	void battleObstaclesRemoved(const std::set<si32> & removedObstacles) override; //called when a certain set  of obstacles is removed from batlefield; IDs of them are given
 	void battleCatapultAttacked(const CatapultAttack & ca) override; //called when catapult makes an attack
 	void battleStacksRemoved(const BattleStacksRemoved & bsr) override; //called when certain stack is completely removed from battlefield
-	void battleObstaclePlaced(const CObstacleInstance &obstacle) override;
+	void battleObstaclePlaced(const CObstacleInstance & obstacle) override;
 	void battleGateStateChanged(const EGateState state) override;
 	void yourTacticPhase(int distance) override;
 
@@ -223,7 +224,7 @@ public:
 	void showArtifactAssemblyDialog(ui32 artifactID, ui32 assembleTo, bool assemble, CFunctionList<bool()> onYes, CFunctionList<bool()> onNo);
 	void garrisonsChanged(std::vector<const CGObjectInstance *> objs);
 	void garrisonChanged(const CGObjectInstance * obj);
-	void heroKilled(const CGHeroInstance* hero);
+	void heroKilled(const CGHeroInstance * hero);
 	void waitWhileDialog(bool unlockPim = true);
 	void waitForAllDialogs(bool unlockPim = true);
 	bool shiftPressed() const; //determines if shift key is pressed (left or right or both)
@@ -238,24 +239,24 @@ public:
 	void activateForSpectator(); // TODO: spectator probably need own player interface class
 
 	// show dialogs
-	void showInfoDialog(const std::string &text, CComponent * component);
-	void showInfoDialog(const std::string &text, const std::vector<CComponent*> & components = std::vector<CComponent*>(), int soundID = 0, bool delComps = false);
+	void showInfoDialog(const std::string & text, CComponent * component);
+	void showInfoDialog(const std::string & text, const std::vector<CComponent *> & components = std::vector<CComponent *>(), int soundID = 0, bool delComps = false);
 	void showInfoDialogAndWait(std::vector<Component> & components, const MetaString & text);
 	void showOkDialog(std::vector<Component> & components, const MetaString & text, const std::function<void()> & onOk);
-	void showYesNoDialog(const std::string &text, CFunctionList<void()> onYes, CFunctionList<void()> onNo, bool DelComps = false, const std::vector<CComponent*> & components = std::vector<CComponent*>()); //deactivateCur - whether current main interface should be deactivated; delComps - if components will be deleted on window close
+	void showYesNoDialog(const std::string & text, CFunctionList<void()> onYes, CFunctionList<void()> onNo, bool DelComps = false, const std::vector<CComponent *> & components = std::vector<CComponent *>()); //deactivateCur - whether current main interface should be deactivated; delComps - if components will be deleted on window close
 
 	void stopMovement();
-	void moveHero(const CGHeroInstance *h, CGPath path);
-	void initMovement(const TryMoveHero &details, const CGHeroInstance * ho, const int3 &hp );//initializing objects and performing first step of move
-	void movementPxStep( const TryMoveHero &details, int i, const int3 &hp, const CGHeroInstance * ho );//performing step of movement
-	void finishMovement( const TryMoveHero &details, const int3 &hp, const CGHeroInstance * ho ); //finish movement
-	void eraseCurrentPathOf( const CGHeroInstance * ho, bool checkForExistanceOfPath = true );
-
-	void removeLastNodeFromPath(const CGHeroInstance *ho);
-	CGPath *getAndVerifyPath( const CGHeroInstance * h );
+	void moveHero(const CGHeroInstance * h, CGPath path);
+	void initMovement(const TryMoveHero & details, const CGHeroInstance * ho, const int3 & hp); //initializing objects and performing first step of move
+	void movementPxStep(const TryMoveHero & details, int i, const int3 & hp, const CGHeroInstance * ho); //performing step of movement
+	void finishMovement(const TryMoveHero & details, const int3 & hp, const CGHeroInstance * ho); //finish movement
+	void eraseCurrentPathOf(const CGHeroInstance * ho, bool checkForExistanceOfPath = true);
+
+	void removeLastNodeFromPath(const CGHeroInstance * ho);
+	CGPath * getAndVerifyPath(const CGHeroInstance * h);
 	void acceptTurn(); //used during hot seat after your turn message is close
-	void tryDiggging(const CGHeroInstance *h);
-	void showShipyardDialogOrProblemPopup(const IShipyard *obj); //obj may be town or shipyard;
+	void tryDiggging(const CGHeroInstance * h);
+	void showShipyardDialogOrProblemPopup(const IShipyard * obj); //obj may be town or shipyard;
 	void requestReturningToMainMenu();
 	void sendCustomEvent(int code);
 	void proposeLoadingGame();
@@ -268,14 +269,15 @@ public:
 
 private:
 
-	template <typename Handler> void serializeTempl(Handler &h, const int version);
+	template<typename Handler> void serializeTempl(Handler & h, const int version);
 
 private:
 
 	struct IgnoreEvents
 	{
 		CPlayerInterface & owner;
-		IgnoreEvents(CPlayerInterface & Owner):owner(Owner)
+		IgnoreEvents(CPlayerInterface & Owner)
+			: owner(Owner)
 		{
 			owner.ignoreEvents = true;
 		};
@@ -291,9 +293,9 @@ private:
 	bool duringMovement;
 	bool ignoreEvents;
 
-	void doMoveHero(const CGHeroInstance *h, CGPath path);
+	void doMoveHero(const CGHeroInstance * h, CGPath path);
 	void setMovementStatus(bool value);
-	void askToAssembleArtifact(const ArtifactLocation &al);
+	void askToAssembleArtifact(const ArtifactLocation & al);
 };
 
 extern CPlayerInterface * LOCPLINT;

File diff suppressed because it is too large
+ 217 - 201
client/CPreGame.cpp


+ 184 - 125
client/CPreGame.h

@@ -41,41 +41,69 @@ class CButton;
 class CLabel;
 class CSlider;
 
-namespace boost{ class thread; class recursive_mutex;}
+namespace boost
+{
+class thread;
+class recursive_mutex;
+}
 
-enum ESortBy{_playerAm, _size, _format, _name, _viccon, _loscon, _numOfMaps, _fileName}; //_numOfMaps is for campaigns
+enum ESortBy
+{
+	_playerAm,
+	_size,
+	_format,
+	_name,
+	_viccon,
+	_loscon,
+	_numOfMaps,
+	_fileName
+}; //_numOfMaps is for campaigns
 
 /// Class which handles map sorting by different criteria
 class mapSorter
 {
 public:
 	ESortBy sortBy;
-	bool operator()(const CMapInfo *aaa, const CMapInfo *bbb);
-	mapSorter(ESortBy es):sortBy(es){};
+	bool operator()(const CMapInfo * aaa, const CMapInfo * bbb);
+	mapSorter(ESortBy es)
+		: sortBy(es){};
 };
 
 /// The main menu screens listed in the EState enum
 class CMenuScreen : public CIntObject
 {
-	const JsonNode& config;
+	const JsonNode & config;
 
-	CTabbedInt *tabs;
+	CTabbedInt * tabs;
 
 	CPicture * background;
-	std::vector<CPicture*> images;
+	std::vector<CPicture *> images;
+
+	CIntObject * createTab(size_t index);
 
-	CIntObject *createTab(size_t index);
 public:
 	std::vector<std::string> menuNameToEntry;
 
-	enum EState { //where are we?
-		mainMenu, newGame, loadGame, campaignMain, saveGame, scenarioInfo, campaignList
+	enum EState //where are we?
+	{
+		mainMenu,
+		newGame,
+		loadGame,
+		campaignMain,
+		saveGame,
+		scenarioInfo,
+		campaignList
 	};
 
-	enum EGameMode {
-		SINGLE_PLAYER = 0, MULTI_HOT_SEAT, MULTI_NETWORK_HOST, MULTI_NETWORK_GUEST, SINGLE_CAMPAIGN
+	enum EGameMode
+	{
+		SINGLE_PLAYER = 0,
+		MULTI_HOT_SEAT,
+		MULTI_NETWORK_HOST,
+		MULTI_NETWORK_GUEST,
+		SINGLE_CAMPAIGN
 	};
-	CMenuScreen(const JsonNode& configNode);
+	CMenuScreen(const JsonNode & configNode);
 
 	void showAll(SDL_Surface * to) override;
 	void show(SDL_Surface * to) override;
@@ -87,18 +115,20 @@ public:
 
 class CMenuEntry : public CIntObject
 {
-	std::vector<CPicture*> images;
-	std::vector<CButton*> buttons;
+	std::vector<CPicture *> images;
+	std::vector<CButton *> buttons;
+
+	CButton * createButton(CMenuScreen * parent, const JsonNode & button);
 
-	CButton* createButton(CMenuScreen* parent, const JsonNode& button);
 public:
-	CMenuEntry(CMenuScreen* parent, const JsonNode &config);
+	CMenuEntry(CMenuScreen * parent, const JsonNode & config);
 };
 
 class CreditsScreen : public CIntObject
 {
 	int positionCounter;
-	CMultiLineLabel* credits;
+	CMultiLineLabel * credits;
+
 public:
 	CreditsScreen();
 
@@ -112,32 +142,33 @@ public:
 class CChatBox : public CIntObject
 {
 public:
-	CTextBox *chatHistory;
-	CTextInput *inputBox;
+	CTextBox * chatHistory;
+	CTextInput * inputBox;
 
-	CChatBox(const Rect &rect);
+	CChatBox(const Rect & rect);
 
 	void keyPressed(const SDL_KeyboardEvent & key) override;
 
-	void addNewMessage(const std::string &text);
+	void addNewMessage(const std::string & text);
 };
 
 class InfoCard : public CIntObject
 {
-	CAnimImage * victory, * loss, *sizes;
+	CAnimImage * victory, * loss, * sizes;
 	std::shared_ptr<CAnimation> sFlags;
+
 public:
-	CPicture *bg;
+	CPicture * bg;
 
 	bool network;
-	bool chatOn;  //if chat is shown, then description is hidden
-	CTextBox *mapDescription;
-	CChatBox *chat;
-	CPicture *playerListBg;
+	bool chatOn; //if chat is shown, then description is hidden
+	CTextBox * mapDescription;
+	CChatBox * chat;
+	CPicture * playerListBg;
 
-	CToggleGroup *difficulty;
+	CToggleGroup * difficulty;
 
-	void changeSelection(const CMapInfo *to);
+	void changeSelection(const CMapInfo * to);
 	void showAll(SDL_Surface * to) override;
 	void clickRight(tribool down, bool previousState) override;
 	void showTeamsPopup();
@@ -153,17 +184,18 @@ class SelectionTab : public CIntObject
 private:
 	std::shared_ptr<CAnimation> formatIcons;
 
-	void parseMaps(const std::unordered_set<ResourceID> &files);
-	void parseGames(const std::unordered_set<ResourceID> &files, CMenuScreen::EGameMode gameMode);
+	void parseMaps(const std::unordered_set<ResourceID> & files);
+	void parseGames(const std::unordered_set<ResourceID> & files, CMenuScreen::EGameMode gameMode);
 	std::unordered_set<ResourceID> getFiles(std::string dirURI, int resType);
-	void parseCampaigns(const std::unordered_set<ResourceID> & files );
+	void parseCampaigns(const std::unordered_set<ResourceID> & files);
 	CMenuScreen::EState tabType;
+
 public:
 	int positions; //how many entries (games/maps) can be shown
-	CPicture *bg; //general bg image
-	CSlider *slider;
+	CPicture * bg; //general bg image
+	CSlider * slider;
 	std::vector<CMapInfo> allItems;
-	std::vector<CMapInfo*> curItems;
+	std::vector<CMapInfo *> curItems;
 	size_t selectionPos;
 	std::function<void(CMapInfo *)> onSelect;
 
@@ -171,7 +203,7 @@ public:
 	ESortBy generalSortingBy;
 	bool ascending;
 
-	CTextInput *txt;
+	CTextInput * txt;
 
 
 	void filter(int size, bool selectFirst = false); //0 - all
@@ -181,7 +213,7 @@ public:
 	void sliderMove(int slidPos);
 	void sortBy(int criteria);
 	void sort();
-	void printMaps(SDL_Surface *to);
+	void printMaps(SDL_Surface * to);
 	int getLine();
 	void selectFName(std::string fname);
 	const CMapInfo * getSelectedMapInfo() const;
@@ -190,35 +222,40 @@ public:
 	void clickLeft(tribool down, bool previousState) override;
 	void keyPressed(const SDL_KeyboardEvent & key) override;
 	void onDoubleClick() override;
-	SelectionTab(CMenuScreen::EState Type, const std::function<void(CMapInfo *)> &OnSelect, CMenuScreen::EGameMode GameMode = CMenuScreen::SINGLE_PLAYER);
-    ~SelectionTab();
+	SelectionTab(CMenuScreen::EState Type, const std::function<void(CMapInfo *)> & OnSelect, CMenuScreen::EGameMode GameMode = CMenuScreen::SINGLE_PLAYER);
+	~SelectionTab();
 };
 
 /// The options tab which is shown at the map selection phase.
 class OptionsTab : public CIntObject
 {
-	CPicture *bg;
+	CPicture * bg;
+
 public:
-	enum SelType {TOWN, HERO, BONUS};
+	enum SelType
+	{
+		TOWN,
+		HERO,
+		BONUS
+	};
 
 	struct CPlayerSettingsHelper
 	{
 		const PlayerSettings & settings;
 		const SelType type;
 
-		CPlayerSettingsHelper(const PlayerSettings & settings, SelType type):
-		    settings(settings),
-		    type(type)
+		CPlayerSettingsHelper(const PlayerSettings & settings, SelType type)
+			: settings(settings), type(type)
 		{}
 
 		/// visible image settings
 		size_t getImageIndex();
 		std::string getImageName();
 
-		std::string getName();       /// name visible in options dialog
-		std::string getTitle();      /// title in popup box
-		std::string getSubtitle();   /// popup box subtitle
-		std::string getDescription();/// popup box description, not always present
+		std::string getName(); /// name visible in options dialog
+		std::string getTitle(); /// title in popup box
+		std::string getSubtitle(); /// popup box subtitle
+		std::string getDescription(); /// popup box description, not always present
 	};
 
 	class CPregameTooltipBox : public CWindowObject, public CPlayerSettingsHelper
@@ -227,14 +264,15 @@ public:
 		void genTownWindow();
 		void genHeroWindow();
 		void genBonusWindow();
-	public:
+
+public:
 		CPregameTooltipBox(CPlayerSettingsHelper & helper);
 	};
 
 	struct SelectedBox : public CIntObject, public CPlayerSettingsHelper //img with current town/hero/bonus
 	{
 		CAnimImage * image;
-		CLabel *subtitle;
+		CLabel * subtitle;
 
 		SelectedBox(Point position, PlayerSettings & settings, SelType type);
 		void clickRight(tribool down, bool previousState) override;
@@ -244,23 +282,28 @@ public:
 
 	struct PlayerOptionsEntry : public CIntObject
 	{
-		PlayerInfo &pi;
-		PlayerSettings &s;
-		CPicture *bg;
-		CButton *btns[6]; //left and right for town, hero, bonus
-		CButton *flag;
-		SelectedBox *town;
-		SelectedBox *hero;
-		SelectedBox *bonus;
-		enum {HUMAN_OR_CPU, HUMAN, CPU} whoCanPlay;
-
-		PlayerOptionsEntry(OptionsTab *owner, PlayerSettings &S);
+		PlayerInfo & pi;
+		PlayerSettings & s;
+		CPicture * bg;
+		CButton * btns[6]; //left and right for town, hero, bonus
+		CButton * flag;
+		SelectedBox * town;
+		SelectedBox * hero;
+		SelectedBox * bonus;
+		enum
+		{
+			HUMAN_OR_CPU,
+			HUMAN,
+			CPU
+		} whoCanPlay;
+
+		PlayerOptionsEntry(OptionsTab * owner, PlayerSettings & S);
 		void selectButtons(); //hides unavailable buttons
 		void showAll(SDL_Surface * to) override;
 		void update();
 	};
 
-	CSlider *turnDuration;
+	CSlider * turnDuration;
 
 	std::set<int> usedHeroes;
 
@@ -286,9 +329,9 @@ public:
 	~OptionsTab();
 	void showAll(SDL_Surface * to) override;
 
-	int nextAllowedHero(PlayerColor player, int min, int max, int incl, int dir );
+	int nextAllowedHero(PlayerColor player, int min, int max, int incl, int dir);
 
-	bool canUseThisHero(PlayerColor player, int ID );
+	bool canUseThisHero(PlayerColor player, int ID);
 };
 
 /// The random map tab shows options for generating a random map.
@@ -297,26 +340,26 @@ class CRandomMapTab : public CIntObject
 public:
 	CRandomMapTab();
 
-    void showAll(SDL_Surface * to) override;
+	void showAll(SDL_Surface * to) override;
 	void updateMapInfo();
-	CFunctionList<void (const CMapInfo *)> & getMapInfoChanged();
+	CFunctionList<void(const CMapInfo *)> & getMapInfoChanged();
 	const CMapInfo * getMapInfo() const;
 	const CMapGenOptions & getMapGenOptions() const;
 	void setMapGenOptions(std::shared_ptr<CMapGenOptions> opts);
 
 private:
-    void addButtonsToGroup(CToggleGroup * group, const std::vector<std::string> & defs, int startIndex, int endIndex, int btnWidth, int helpStartIndex) const;
-    void addButtonsWithRandToGroup(CToggleGroup * group, const std::vector<std::string> & defs, int startIndex, int endIndex, int btnWidth, int helpStartIndex, int helpRandIndex) const;
-    void deactivateButtonsFrom(CToggleGroup * group, int startId);
-    void validatePlayersCnt(int playersCnt);
-    void validateCompOnlyPlayersCnt(int compOnlyPlayersCnt);
+	void addButtonsToGroup(CToggleGroup * group, const std::vector<std::string> & defs, int startIndex, int endIndex, int btnWidth, int helpStartIndex) const;
+	void addButtonsWithRandToGroup(CToggleGroup * group, const std::vector<std::string> & defs, int startIndex, int endIndex, int btnWidth, int helpStartIndex, int helpRandIndex) const;
+	void deactivateButtonsFrom(CToggleGroup * group, int startId);
+	void validatePlayersCnt(int playersCnt);
+	void validateCompOnlyPlayersCnt(int compOnlyPlayersCnt);
 	std::vector<int> getPossibleMapSizes();
 
-    CPicture * bg;
+	CPicture * bg;
 	CToggleButton * twoLevelsBtn;
 	CToggleGroup * mapSizeBtnGroup, * playersCntGroup, * teamsCntGroup, * compOnlyPlayersCntGroup,
-		* compOnlyTeamsCntGroup, * waterContentGroup, * monsterStrengthGroup;
-    CButton * showRandMaps;
+		     * compOnlyTeamsCntGroup, * waterContentGroup, * monsterStrengthGroup;
+	CButton * showRandMaps;
 	CMapGenOptions mapGenOptions;
 	std::unique_ptr<CMapInfo> mapInfo;
 	CFunctionList<void(const CMapInfo *)> mapInfoChanged;
@@ -328,18 +371,18 @@ class ISelectionScreenInfo
 public:
 	CMenuScreen::EGameMode gameMode;
 	CMenuScreen::EState screenType; //new/save/load#Game
-	const CMapInfo *current;
+	const CMapInfo * current;
 	StartInfo sInfo;
 	std::map<ui8, std::string> playerNames; // id of player <-> player name; 0 is reserved as ID of AI "players"
 
-	ISelectionScreenInfo(const std::map<ui8, std::string> *Names = nullptr);
+	ISelectionScreenInfo(const std::map<ui8, std::string> * Names = nullptr);
 	virtual ~ISelectionScreenInfo();
 	virtual void update(){};
 	virtual void propagateOptions() {};
 	virtual void postRequest(ui8 what, ui8 dir) {};
-	virtual void postChatMessage(const std::string &txt){};
+	virtual void postChatMessage(const std::string & txt){};
 
-	void setPlayer(PlayerSettings &pset, ui8 player);
+	void setPlayer(PlayerSettings & pset, ui8 player);
 	void updateStartInfo(std::string filename, StartInfo & sInfo, const std::unique_ptr<CMapHeader> & mapHeader);
 
 	ui8 getIdOfFirstUnallocatedPlayer(); //returns 0 if none
@@ -352,28 +395,29 @@ public:
 class CSelectionScreen : public CIntObject, public ISelectionScreenInfo
 {
 	bool bordered;
+
 public:
-	CPicture *bg; //general bg image
-	InfoCard *card;
-	OptionsTab *opt;
+	CPicture * bg; //general bg image
+	InfoCard * card;
+	OptionsTab * opt;
 	CRandomMapTab * randMapTab;
-	CButton *start, *back;
+	CButton * start, * back;
 
-	SelectionTab *sel;
-	CIntObject *curTab;
+	SelectionTab * sel;
+	CIntObject * curTab;
 
-	boost::thread *serverHandlingThread;
-	boost::recursive_mutex *mx;
+	boost::thread * serverHandlingThread;
+	boost::recursive_mutex * mx;
 	std::list<CPackForSelectionScreen *> upcomingPacks; //protected by mx
 
-	CConnection *serv; //connection to server, used in MP mode
+	CConnection * serv; //connection to server, used in MP mode
 	bool ongoingClosing;
 	ui8 myNameID; //used when networking - otherwise all player are "mine"
 
 	CSelectionScreen(CMenuScreen::EState Type, CMenuScreen::EGameMode GameMode = CMenuScreen::SINGLE_PLAYER, const std::map<ui8, std::string> * Names = nullptr, const std::string & Address = "", const ui16 Port = 0);
 	~CSelectionScreen();
-	void toggleTab(CIntObject *tab);
-	void changeSelection(const CMapInfo *to);
+	void toggleTab(CIntObject * tab);
+	void changeSelection(const CMapInfo * to);
 	void startCampaign();
 	void startScenario();
 	void difficultyChange(int to);
@@ -381,20 +425,20 @@ public:
 	void handleConnection();
 
 	void processPacks();
-	void setSInfo(const StartInfo &si);
+	void setSInfo(const StartInfo & si);
 	void update() override;
 	void propagateOptions() override;
 	void postRequest(ui8 what, ui8 dir) override;
-	void postChatMessage(const std::string &txt) override;
+	void postChatMessage(const std::string & txt) override;
 	void propagateNames();
-	void showAll(SDL_Surface *to) override;
+	void showAll(SDL_Surface * to) override;
 };
 
 /// Save game screen
 class CSavingScreen : public CSelectionScreen
 {
 public:
-	const CMapInfo *ourGame;
+	const CMapInfo * ourGame;
 
 
 	CSavingScreen(bool hotseat = false);
@@ -405,11 +449,11 @@ public:
 class CScenarioInfo : public CIntObject, public ISelectionScreenInfo
 {
 public:
-	CButton *back;
-	InfoCard *card;
-	OptionsTab *opt;
+	CButton * back;
+	InfoCard * card;
+	OptionsTab * opt;
 
-	CScenarioInfo(const CMapHeader *mapHeader, const StartInfo *startInfo);
+	CScenarioInfo(const CMapHeader * mapHeader, const StartInfo * startInfo);
 	~CScenarioInfo();
 };
 
@@ -417,10 +461,10 @@ public:
 class CMultiMode : public CIntObject
 {
 public:
-	CPicture *bg;
-	CTextInput *txt;
-	CButton *btns[7]; //0 - hotseat, 6 - cancel
-	CGStatusBar *bar;
+	CPicture * bg;
+	CTextInput * txt;
+	CButton * btns[7]; //0 - hotseat, 6 - cancel
+	CGStatusBar * bar;
 
 	CMultiMode();
 	void openHotseat();
@@ -431,17 +475,17 @@ public:
 /// Hot seat player window
 class CHotSeatPlayers : public CIntObject
 {
-	CPicture *bg;
-	CTextBox *title;
-	CTextInput* txt[8];
-	CButton *ok, *cancel;
-	CGStatusBar *bar;
+	CPicture * bg;
+	CTextBox * title;
+	CTextInput * txt[8];
+	CButton * ok, * cancel;
+	CGStatusBar * bar;
 
 	void onChange(std::string newText);
 	void enterSelectionScreen();
 
 public:
-	CHotSeatPlayers(const std::string &firstPlayer);
+	CHotSeatPlayers(const std::string & firstPlayer);
 };
 
 
@@ -453,6 +497,7 @@ class CPrologEpilogVideo : public CWindowObject
 	std::function<void()> exitCb;
 
 	CMultiLineLabel * text;
+
 public:
 	CPrologEpilogVideo(CCampaignScenario::SScenarioPrologEpilog _spe, std::function<void()> callback);
 
@@ -490,12 +535,12 @@ private:
 	class CRegion : public CIntObject
 	{
 		CBonusSelection * owner;
-		SDL_Surface* graphics[3]; //[0] - not selected, [1] - selected, [2] - striped
+		SDL_Surface * graphics[3]; //[0] - not selected, [1] - selected, [2] - striped
 		bool accessible; //false if region should be striped
 		bool selectable; //true if region should be selectable
 		int myNumber; //number of region
 
-	public:
+public:
 		std::string rclickText;
 		CRegion(CBonusSelection * _owner, bool _accessible, bool _selectable, int _myNumber);
 		~CRegion();
@@ -530,7 +575,7 @@ private:
 	CToggleGroup * bonuses;
 	std::array<CAnimImage *, 5> diffPics; //pictures of difficulties, user-selectable (or not if campaign locks this)
 	CButton * diffLb, * diffRb; //buttons for changing difficulty
-	CAnimImage * sizes;//icons of map sizes
+	CAnimImage * sizes; //icons of map sizes
 	std::shared_ptr<CAnimation> sFlags;
 
 	// Data
@@ -545,14 +590,20 @@ private:
 class CCampaignScreen : public CIntObject
 {
 public:
-	enum CampaignStatus {DEFAULT = 0, ENABLED, DISABLED, COMPLETED}; // the status of the campaign
+	enum CampaignStatus
+	{
+		DEFAULT = 0,
+		ENABLED,
+		DISABLED,
+		COMPLETED
+	}; // the status of the campaign
 
 private:
 	/// A button which plays a video when you move the mouse cursor over it
 	class CCampaignButton : public CIntObject
 	{
-	private:
-		CLabel *hoverLabel;
+private:
+		CLabel * hoverLabel;
 		CampaignStatus status;
 
 		std::string campFile; // the filename/resourcename of the campaign
@@ -562,21 +613,27 @@ private:
 		void clickLeft(tribool down, bool previousState) override;
 		void hover(bool on) override;
 
-	public:
-		CCampaignButton(const JsonNode &config );
+public:
+		CCampaignButton(const JsonNode & config);
 		void show(SDL_Surface * to) override;
 	};
 
-	std::vector<CCampaignButton*> campButtons;
-	std::vector<CPicture*> images;
+	std::vector<CCampaignButton *> campButtons;
+	std::vector<CPicture *> images;
 
-	CButton* createExitButton(const JsonNode& button);
+	CButton * createExitButton(const JsonNode & button);
 
 public:
-	enum CampaignSet {ROE, AB, SOD, WOG};
+	enum CampaignSet
+	{
+		ROE,
+		AB,
+		SOD,
+		WOG
+	};
 
-	CCampaignScreen(const JsonNode &config);
-	void showAll(SDL_Surface *to) override;
+	CCampaignScreen(const JsonNode & config);
+	void showAll(SDL_Surface * to) override;
 };
 
 /// Manages the configuration of pregame GUI elements like campaign screen, main menu, loading screen,...
@@ -623,11 +680,12 @@ class CLoadingScreen : public CWindowObject
 	boost::thread loadingThread;
 
 	std::string getBackground();
+
 public:
 	CLoadingScreen(std::function<void()> loader);
 	~CLoadingScreen();
 
-	void showAll(SDL_Surface *to) override;
+	void showAll(SDL_Surface * to) override;
 };
 
 /// Simple window to enter the server's address.
@@ -642,9 +700,10 @@ class CSimpleJoinScreen : public CIntObject
 
 	void enterSelectionScreen(CMenuScreen::EGameMode mode);
 	void onChange(const std::string & newText);
+
 public:
 	CSimpleJoinScreen(CMenuScreen::EGameMode mode);
 };
 
-extern ISelectionScreenInfo *SEL;
-extern CGPreGame *CGP;
+extern ISelectionScreenInfo * SEL;
+extern CGPreGame * CGP;

+ 82 - 68
client/CVideoHandler.cpp

@@ -39,7 +39,7 @@ static bool keyDown()
 #endif // _MSC_VER
 
 // Define a set of functions to read data
-static int lodRead(void* opaque, uint8_t* buf, int size)
+static int lodRead(void * opaque, uint8_t * buf, int size)
 {
 	auto video = reinterpret_cast<CVideoPlayer *>(opaque);
 
@@ -50,7 +50,7 @@ static si64 lodSeek(void * opaque, si64 pos, int whence)
 {
 	auto video = reinterpret_cast<CVideoPlayer *>(opaque);
 
-	if (whence & AVSEEK_SIZE)
+	if(whence & AVSEEK_SIZE)
 		return video->data->getSize();
 
 	return video->data->seek(pos);
@@ -67,8 +67,8 @@ CVideoPlayer::CVideoPlayer()
 	context = nullptr;
 	texture = nullptr;
 	dest = nullptr;
-	destRect = genRect(0,0,0,0);
-	pos = genRect(0,0,0,0);
+	destRect = genRect(0, 0, 0, 0);
+	pos = genRect(0, 0, 0, 0);
 	refreshWait = 0;
 	refreshCount = 0;
 	doLoop = false;
@@ -97,7 +97,7 @@ bool CVideoPlayer::open(std::string fname, bool loop, bool useOverlay, bool scal
 
 	ResourceID resource(std::string("Video/") + fname, EResType::VIDEO);
 
-	if (!CResourceHandler::get()->existsResource(resource))
+	if(!CResourceHandler::get()->existsResource(resource))
 	{
 		logGlobal->errorStream() << "Error: video " << resource.getName() << " was not found";
 		return false;
@@ -107,34 +107,34 @@ bool CVideoPlayer::open(std::string fname, bool loop, bool useOverlay, bool scal
 
 	static const int BUFFER_SIZE = 4096;
 
-	unsigned char * buffer  = (unsigned char *)av_malloc(BUFFER_SIZE);// will be freed by ffmpeg
-	context = avio_alloc_context( buffer, BUFFER_SIZE, 0, (void *)this, lodRead, nullptr, lodSeek);
+	unsigned char * buffer = (unsigned char *)av_malloc(BUFFER_SIZE); // will be freed by ffmpeg
+	context = avio_alloc_context(buffer, BUFFER_SIZE, 0, (void *)this, lodRead, nullptr, lodSeek);
 
 	format = avformat_alloc_context();
 	format->pb = context;
 	// filename is not needed - file was already open and stored in this->data;
 	int avfopen = avformat_open_input(&format, "dummyFilename", nullptr, nullptr);
 
-	if (avfopen != 0)
+	if(avfopen != 0)
 	{
 		return false;
 	}
 	// Retrieve stream information
-	if (avformat_find_stream_info(format, nullptr) < 0)
+	if(avformat_find_stream_info(format, nullptr) < 0)
 		return false;
 
 	// Find the first video stream
 	stream = -1;
-	for(ui32 i=0; i<format->nb_streams; i++)
+	for(ui32 i = 0; i < format->nb_streams; i++)
 	{
-		if (format->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO)
+		if(format->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO)
 		{
 			stream = i;
 			break;
 		}
 	}
 
-	if (stream < 0)
+	if(stream < 0)
 		// No video stream in that file
 		return false;
 
@@ -144,14 +144,14 @@ bool CVideoPlayer::open(std::string fname, bool loop, bool useOverlay, bool scal
 	// Find the decoder for the video stream
 	codec = avcodec_find_decoder(codecContext->codec_id);
 
-	if (codec == nullptr)
+	if(codec == nullptr)
 	{
 		// Unsupported codec
 		return false;
 	}
 
 	// Open codec
-	if ( avcodec_open2(codecContext, codec, nullptr) < 0 )
+	if(avcodec_open2(codecContext, codec, nullptr) < 0)
 	{
 		// Could not open codec
 		codec = nullptr;
@@ -168,14 +168,14 @@ bool CVideoPlayer::open(std::string fname, bool loop, bool useOverlay, bool scal
 	}
 	else
 	{
-		pos.w  = codecContext->width;
+		pos.w = codecContext->width;
 		pos.h = codecContext->height;
 	}
 
 	// Allocate a place to put our YUV image on that screen
-	if (useOverlay)
+	if(useOverlay)
 	{
-		texture = SDL_CreateTexture( mainRenderer, SDL_PIXELFORMAT_IYUV, SDL_TEXTUREACCESS_STATIC, pos.w, pos.h);
+		texture = SDL_CreateTexture(mainRenderer, SDL_PIXELFORMAT_IYUV, SDL_TEXTUREACCESS_STATIC, pos.w, pos.h);
 	}
 	else
 	{
@@ -185,48 +185,62 @@ bool CVideoPlayer::open(std::string fname, bool loop, bool useOverlay, bool scal
 		destRect.h = pos.h;
 	}
 
-	if (texture == nullptr && dest == nullptr)
+	if(texture == nullptr && dest == nullptr)
 		return false;
 
-	if (texture)
+	if(texture)
 	{ // Convert the image into YUV format that SDL uses
 		sws = sws_getContext(codecContext->width, codecContext->height, codecContext->pix_fmt,
-							 pos.w, pos.h,
-							 AV_PIX_FMT_YUV420P,
-							 SWS_BICUBIC, nullptr, nullptr, nullptr);
+				     pos.w, pos.h,
+				     AV_PIX_FMT_YUV420P,
+				     SWS_BICUBIC, nullptr, nullptr, nullptr);
 	}
 	else
 	{
 		AVPixelFormat screenFormat = AV_PIX_FMT_NONE;
-		if (screen->format->Bshift > screen->format->Rshift)
+		if(screen->format->Bshift > screen->format->Rshift)
 		{
 			// this a BGR surface
-			switch (screen->format->BytesPerPixel)
+			switch(screen->format->BytesPerPixel)
 			{
-				case 2: screenFormat = AV_PIX_FMT_BGR565; break;
-				case 3: screenFormat = AV_PIX_FMT_BGR24; break;
-				case 4: screenFormat = AV_PIX_FMT_BGR32; break;
-				default: return false;
+			case 2:
+				screenFormat = AV_PIX_FMT_BGR565;
+				break;
+			case 3:
+				screenFormat = AV_PIX_FMT_BGR24;
+				break;
+			case 4:
+				screenFormat = AV_PIX_FMT_BGR32;
+				break;
+			default:
+				return false;
 			}
 		}
 		else
 		{
 			// this a RGB surface
-			switch (screen->format->BytesPerPixel)
+			switch(screen->format->BytesPerPixel)
 			{
-				case 2: screenFormat = AV_PIX_FMT_RGB565; break;
-				case 3: screenFormat = AV_PIX_FMT_RGB24; break;
-				case 4: screenFormat = AV_PIX_FMT_RGB32; break;
-				default: return false;
+			case 2:
+				screenFormat = AV_PIX_FMT_RGB565;
+				break;
+			case 3:
+				screenFormat = AV_PIX_FMT_RGB24;
+				break;
+			case 4:
+				screenFormat = AV_PIX_FMT_RGB32;
+				break;
+			default:
+				return false;
 			}
 		}
 
 		sws = sws_getContext(codecContext->width, codecContext->height, codecContext->pix_fmt,
-							 pos.w, pos.h, screenFormat,
-							 SWS_BICUBIC, nullptr, nullptr, nullptr);
+				     pos.w, pos.h, screenFormat,
+				     SWS_BICUBIC, nullptr, nullptr, nullptr);
 	}
 
-	if (sws == nullptr)
+	if(sws == nullptr)
 		return false;
 
 	return true;
@@ -239,19 +253,19 @@ bool CVideoPlayer::nextFrame()
 	int frameFinished = 0;
 	bool gotError = false;
 
-	if (sws == nullptr)
+	if(sws == nullptr)
 		return false;
 
 	while(!frameFinished)
 	{
 		int ret = av_read_frame(format, &packet);
-		if (ret < 0)
+		if(ret < 0)
 		{
 			// Error. It's probably an end of file.
-			if (doLoop && !gotError)
+			if(doLoop && !gotError)
 			{
 				// Rewind
-				if (av_seek_frame(format, stream, 0, AVSEEK_FLAG_BYTE) < 0)
+				if(av_seek_frame(format, stream, 0, AVSEEK_FLAG_BYTE) < 0)
 					break;
 				gotError = true;
 			}
@@ -263,26 +277,27 @@ bool CVideoPlayer::nextFrame()
 		else
 		{
 			// Is this a packet from the video stream?
-			if (packet.stream_index == stream)
+			if(packet.stream_index == stream)
 			{
 				// Decode video frame
 
 				avcodec_decode_video2(codecContext, frame, &frameFinished, &packet);
 
 				// Did we get a video frame?
-				if (frameFinished)
+				if(frameFinished)
 				{
 					AVPicture pict;
 
-					if (texture) {
+					if(texture)
+					{
 						avpicture_alloc(&pict, AV_PIX_FMT_YUV420P, pos.w, pos.h);
 
 						sws_scale(sws, frame->data, frame->linesize,
-								  0, codecContext->height, pict.data, pict.linesize);
+							  0, codecContext->height, pict.data, pict.linesize);
 
 						SDL_UpdateYUVTexture(texture, NULL, pict.data[0], pict.linesize[0],
-								pict.data[1], pict.linesize[1],
-								pict.data[2], pict.linesize[2]);
+								     pict.data[1], pict.linesize[1],
+								     pict.data[2], pict.linesize[2]);
 						avpicture_free(&pict);
 					}
 					else
@@ -291,7 +306,7 @@ bool CVideoPlayer::nextFrame()
 						pict.linesize[0] = dest->pitch;
 
 						sws_scale(sws, frame->data, frame->linesize,
-								  0, codecContext->height, pict.data, pict.linesize);
+							  0, codecContext->height, pict.data, pict.linesize);
 					}
 				}
 			}
@@ -303,34 +318,34 @@ bool CVideoPlayer::nextFrame()
 	return frameFinished != 0;
 }
 
-void CVideoPlayer::show( int x, int y, SDL_Surface *dst, bool update )
+void CVideoPlayer::show(int x, int y, SDL_Surface * dst, bool update)
 {
-	if (sws == nullptr)
+	if(sws == nullptr)
 		return;
 
 	pos.x = x;
 	pos.y = y;
 	CSDL_Ext::blitSurface(dest, &destRect, dst, &pos);
 
-	if (update)
+	if(update)
 		SDL_UpdateRect(dst, pos.x, pos.y, pos.w, pos.h);
 }
 
-void CVideoPlayer::redraw( int x, int y, SDL_Surface *dst, bool update )
+void CVideoPlayer::redraw(int x, int y, SDL_Surface * dst, bool update)
 {
 	show(x, y, dst, update);
 }
 
-void CVideoPlayer::update( int x, int y, SDL_Surface *dst, bool forceRedraw, bool update )
+void CVideoPlayer::update(int x, int y, SDL_Surface * dst, bool forceRedraw, bool update)
 {
-	if (sws == nullptr)
+	if(sws == nullptr)
 		return;
 
-	if (refreshCount <= 0)
+	if(refreshCount <= 0)
 	{
 		refreshCount = refreshWait;
-		if (nextFrame())
-			show(x,y,dst,update);
+		if(nextFrame())
+			show(x, y, dst, update);
 		else
 		{
 			open(fname);
@@ -347,48 +362,48 @@ void CVideoPlayer::update( int x, int y, SDL_Surface *dst, bool forceRedraw, boo
 		redraw(x, y, dst, update);
 	}
 
-	refreshCount --;
+	refreshCount--;
 }
 
 void CVideoPlayer::close()
 {
 	fname = "";
-	if (sws)
+	if(sws)
 	{
 		sws_freeContext(sws);
 		sws = nullptr;
 	}
 
-	if (texture)
+	if(texture)
 	{
 		SDL_DestroyTexture(texture);
 		texture = nullptr;
 	}
 
-	if (dest)
+	if(dest)
 	{
 		SDL_FreeSurface(dest);
 		dest = nullptr;
 	}
 
-	if (frame)
+	if(frame)
 	{
-		av_frame_free(&frame);//will be set to null
+		av_frame_free(&frame); //will be set to null
 	}
 
-	if (codec)
+	if(codec)
 	{
 		avcodec_close(codecContext);
 		codec = nullptr;
 		codecContext = nullptr;
 	}
 
-	if (format)
+	if(format)
 	{
 		avformat_close_input(&format);
 	}
 
-	if (context)
+	if(context)
 	{
 		av_free(context);
 		context = nullptr;
@@ -396,7 +411,7 @@ void CVideoPlayer::close()
 }
 
 // Plays a video. Only works for overlays.
-bool CVideoPlayer::playVideo(int x, int y, SDL_Surface *dst, bool stopOnKey)
+bool CVideoPlayer::playVideo(int x, int y, SDL_Surface * dst, bool stopOnKey)
 {
 	// Note: either the windows player or the linux player is
 	// broken. Compensate here until the bug is found.
@@ -423,7 +438,7 @@ bool CVideoPlayer::playVideo(int x, int y, SDL_Surface *dst, bool stopOnKey)
 	return true;
 }
 
-bool CVideoPlayer::openAndPlayVideo(std::string name, int x, int y, SDL_Surface *dst, bool stopOnKey, bool scale)
+bool CVideoPlayer::openAndPlayVideo(std::string name, int x, int y, SDL_Surface * dst, bool stopOnKey, bool scale)
 {
 	open(name, false, true, scale);
 	bool ret = playVideo(x, y, dst, stopOnKey);
@@ -437,4 +452,3 @@ CVideoPlayer::~CVideoPlayer()
 }
 
 #endif
-

+ 31 - 32
client/CVideoHandler.h

@@ -15,23 +15,23 @@ struct SDL_Surface;
 class IVideoPlayer
 {
 public:
-	virtual bool open(std::string name, bool scale = false)=0; //true - succes
-	virtual void close()=0;
-	virtual bool nextFrame()=0;
-	virtual void show(int x, int y, SDL_Surface *dst, bool update = true)=0;
-	virtual void redraw(int x, int y, SDL_Surface *dst, bool update = true)=0; //reblits buffer
-	virtual bool wait()=0;
-	virtual int curFrame() const =0;
-	virtual int frameCount() const =0;
+	virtual bool open(std::string name, bool scale = false) = 0; //true - succes
+	virtual void close() = 0;
+	virtual bool nextFrame() = 0;
+	virtual void show(int x, int y, SDL_Surface * dst, bool update = true) = 0;
+	virtual void redraw(int x, int y, SDL_Surface * dst, bool update = true) = 0; //reblits buffer
+	virtual bool wait() = 0;
+	virtual int curFrame() const = 0;
+	virtual int frameCount() const = 0;
 };
 
 class IMainVideoPlayer : public IVideoPlayer
 {
 public:
-	std::string fname;  //name of current video file (empty if idle)
+	std::string fname; //name of current video file (empty if idle)
 
-	virtual void update(int x, int y, SDL_Surface *dst, bool forceRedraw, bool update = true){}
-	virtual bool openAndPlayVideo(std::string name, int x, int y, SDL_Surface *dst, bool stopOnKey = false, bool scale = false)
+	virtual void update(int x, int y, SDL_Surface * dst, bool forceRedraw, bool update = true){}
+	virtual bool openAndPlayVideo(std::string name, int x, int y, SDL_Surface * dst, bool stopOnKey = false, bool scale = false)
 	{
 		return false;
 	}
@@ -42,8 +42,8 @@ class CEmptyVideoPlayer : public IMainVideoPlayer
 public:
 	int curFrame() const override {return -1;};
 	int frameCount() const override {return -1;};
-	void redraw( int x, int y, SDL_Surface *dst, bool update = true ) override {};
-	void show( int x, int y, SDL_Surface *dst, bool update = true ) override {};
+	void redraw(int x, int y, SDL_Surface * dst, bool update = true) override {};
+	void show(int x, int y, SDL_Surface * dst, bool update = true) override {};
 	bool nextFrame() override {return false;};
 	void close() override {};
 	bool wait() override {return false;};
@@ -69,7 +69,7 @@ inline AVFrame * av_frame_alloc()
 	return avcodec_alloc_frame();
 }
 
-inline void av_frame_free(AVFrame ** frame)
+inline void av_frame_free(AVFrame * * frame)
 {
 	av_free(*frame);
 	*frame = nullptr;
@@ -91,27 +91,27 @@ inline void av_frame_free(AVFrame ** frame)
 
 class CVideoPlayer : public IMainVideoPlayer
 {
-	int stream;					// stream index in video
-	AVFormatContext *format;
-	AVCodecContext *codecContext; // codec context for stream
-	AVCodec *codec;
-	AVFrame *frame;
-	struct SwsContext *sws;
+	int stream; // stream index in video
+	AVFormatContext * format;
+	AVCodecContext * codecContext; // codec context for stream
+	AVCodec * codec;
+	AVFrame * frame;
+	struct SwsContext * sws;
 
 	AVIOContext * context;
 
 	// Destination. Either overlay or dest.
 
-	SDL_Texture *texture;
-	SDL_Surface *dest;
-	SDL_Rect destRect;			// valid when dest is used
-	SDL_Rect pos;				// destination on screen
+	SDL_Texture * texture;
+	SDL_Surface * dest;
+	SDL_Rect destRect; // valid when dest is used
+	SDL_Rect pos; // destination on screen
 
 	int refreshWait; // Wait several refresh before updating the image
 	int refreshCount;
-	bool doLoop;				// loop through video
+	bool doLoop; // loop through video
 
-	bool playVideo(int x, int y, SDL_Surface *dst, bool stopOnKey);
+	bool playVideo(int x, int y, SDL_Surface * dst, bool stopOnKey);
 	bool open(std::string fname, bool loop, bool useOverlay = false, bool scale = false);
 
 public:
@@ -121,14 +121,14 @@ public:
 	bool init();
 	bool open(std::string fname, bool scale = false) override;
 	void close() override;
-	bool nextFrame() override;			// display next frame
+	bool nextFrame() override; // display next frame
 
-	void show(int x, int y, SDL_Surface *dst, bool update = true) override; //blit current frame
-	void redraw(int x, int y, SDL_Surface *dst, bool update = true) override; //reblits buffer
-	void update(int x, int y, SDL_Surface *dst, bool forceRedraw, bool update = true) override; //moves to next frame if appropriate, and blits it or blits only if redraw parameter is set true
+	void show(int x, int y, SDL_Surface * dst, bool update = true) override; //blit current frame
+	void redraw(int x, int y, SDL_Surface * dst, bool update = true) override; //reblits buffer
+	void update(int x, int y, SDL_Surface * dst, bool forceRedraw, bool update = true) override; //moves to next frame if appropriate, and blits it or blits only if redraw parameter is set true
 
 	// Opens video, calls playVideo, closes video; returns playVideo result (if whole video has been played)
-	bool openAndPlayVideo(std::string name, int x, int y, SDL_Surface *dst, bool stopOnKey = false, bool scale = false) override;
+	bool openAndPlayVideo(std::string name, int x, int y, SDL_Surface * dst, bool stopOnKey = false, bool scale = false) override;
 
 	//TODO:
 	bool wait() override {return false;};
@@ -140,4 +140,3 @@ public:
 };
 
 #endif
-

+ 129 - 122
client/Client.cpp

@@ -60,45 +60,45 @@ std::atomic_bool androidTestServerReadyFlag;
 
 ThreadSafeVector<int> CClient::waitingRequest;
 
-template <typename T> class CApplyOnCL;
+template<typename T> class CApplyOnCL;
 
 class CBaseForCLApply
 {
 public:
-	virtual void applyOnClAfter(CClient *cl, void *pack) const =0;
-	virtual void applyOnClBefore(CClient *cl, void *pack) const =0;
+	virtual void applyOnClAfter(CClient * cl, void * pack) const = 0;
+	virtual void applyOnClBefore(CClient * cl, void * pack) const = 0;
 	virtual ~CBaseForCLApply(){}
 
-	template<typename U> static CBaseForCLApply *getApplier(const U * t=nullptr)
+	template<typename U> static CBaseForCLApply * getApplier(const U * t = nullptr)
 	{
 		return new CApplyOnCL<U>();
 	}
 };
 
-template <typename T> class CApplyOnCL : public CBaseForCLApply
+template<typename T> class CApplyOnCL : public CBaseForCLApply
 {
 public:
-	void applyOnClAfter(CClient *cl, void *pack) const override
+	void applyOnClAfter(CClient * cl, void * pack) const override
 	{
-		T *ptr = static_cast<T*>(pack);
+		T * ptr = static_cast<T *>(pack);
 		ptr->applyCl(cl);
 	}
-	void applyOnClBefore(CClient *cl, void *pack) const override
+	void applyOnClBefore(CClient * cl, void * pack) const override
 	{
-		T *ptr = static_cast<T*>(pack);
+		T * ptr = static_cast<T *>(pack);
 		ptr->applyFirstCl(cl);
 	}
 };
 
-template <> class CApplyOnCL<CPack> : public CBaseForCLApply
+template<> class CApplyOnCL<CPack>: public CBaseForCLApply
 {
 public:
-	void applyOnClAfter(CClient *cl, void *pack) const override
+	void applyOnClAfter(CClient * cl, void * pack) const override
 	{
 		logGlobal->errorStream() << "Cannot apply on CL plain CPack!";
 		assert(0);
 	}
-	void applyOnClBefore(CClient *cl, void *pack) const override
+	void applyOnClBefore(CClient * cl, void * pack) const override
 	{
 		logGlobal->errorStream() << "Cannot apply on CL plain CPack!";
 		assert(0);
@@ -106,7 +106,7 @@ public:
 };
 
 
-static CApplier<CBaseForCLApply> *applier = nullptr;
+static CApplier<CBaseForCLApply> * applier = nullptr;
 
 void CClient::init()
 {
@@ -132,10 +132,10 @@ CClient::CClient(void)
 	init();
 }
 
-CClient::CClient(CConnection *con, StartInfo *si)
+CClient::CClient(CConnection * con, StartInfo * si)
 {
 	init();
-	newGame(con,si);
+	newGame(con, si);
 }
 
 CClient::~CClient(void)
@@ -157,7 +157,7 @@ void CClient::waitForMoveAndSend(PlayerColor color)
 			sendRequest(&temp_action, color);
 		}
 	}
-	catch(boost::thread_interrupted&)
+	catch(boost::thread_interrupted &)
 	{
 		logNetwork->debugStream() << "Wait for move thread was interrupted and no action will be send. Was a battle ended by spell?";
 	}
@@ -174,9 +174,9 @@ void CClient::run()
 	{
 		while(!terminate)
 		{
-			CPack *pack = serv->retreivePack(); //get the package from the server
+			CPack * pack = serv->retreivePack(); //get the package from the server
 
-			if (terminate)
+			if(terminate)
 			{
 				vstd::clear_pointer(pack);
 				break;
@@ -186,7 +186,7 @@ void CClient::run()
 		}
 	}
 	//catch only asio exceptions
-	catch (const boost::system::system_error& e)
+	catch(const boost::system::system_error & e)
 	{
 		logNetwork->errorStream() << "Lost connection to server, ending listening thread!";
 		logNetwork->errorStream() << e.what();
@@ -207,18 +207,18 @@ void CClient::save(const std::string & fname)
 	}
 
 	SaveGame save_game(fname);
-	sendRequest((CPackForClient*)&save_game, PlayerColor::NEUTRAL);
+	sendRequest((CPackForClient *)&save_game, PlayerColor::NEUTRAL);
 }
 
 void CClient::endGame(bool closeConnection)
 {
 	//suggest interfaces to finish their stuff (AI should interrupt any bg working threads)
-	for (auto& i : playerint)
+	for(auto & i : playerint)
 		i.second->finish();
 
 	// Game is ending
 	// Tell the network thread to reach a stable state
-	if (closeConnection)
+	if(closeConnection)
 		stopConnection();
 	logNetwork->infoStream() << "Closed connection.";
 
@@ -235,7 +235,7 @@ void CClient::endGame(bool closeConnection)
 		GH.statusbar = nullptr;
 		logNetwork->infoStream() << "Removed GUI.";
 
-		vstd::clear_pointer(const_cast<CGameInfo*>(CGI)->mh);
+		vstd::clear_pointer(const_cast<CGameInfo *>(CGI)->mh);
 		vstd::clear_pointer(gs);
 
 		logNetwork->infoStream() << "Deleted mapHandler and gameState.";
@@ -254,7 +254,7 @@ void CClient::endGame(bool closeConnection)
 }
 
 #if 1
-void CClient::loadGame(const std::string & fname, const bool server, const std::vector<int>& humanplayerindices, const int loadNumPlayers, int player_, const std::string & ipaddr, const ui16 port)
+void CClient::loadGame(const std::string & fname, const bool server, const std::vector<int> & humanplayerindices, const int loadNumPlayers, int player_, const std::string & ipaddr, const ui16 port)
 {
 	PlayerColor player(player_); //intentional shadowing
 	logNetwork->infoStream() << "Loading procedure started!";
@@ -272,11 +272,11 @@ void CClient::loadGame(const std::string & fname, const bool server, const std::
 		boost::filesystem::path clientSaveName = *CResourceHandler::get("local")->getResourceName(ResourceID(fname, EResType::CLIENT_SAVEGAME));
 		boost::filesystem::path controlServerSaveName;
 
-		if (CResourceHandler::get("local")->existsResource(ResourceID(fname, EResType::SERVER_SAVEGAME)))
+		if(CResourceHandler::get("local")->existsResource(ResourceID(fname, EResType::SERVER_SAVEGAME)))
 		{
 			controlServerSaveName = *CResourceHandler::get("local")->getResourceName(ResourceID(fname, EResType::SERVER_SAVEGAME));
 		}
-		else// create entry for server savegame. Triggered if save was made after launch and not yet present in res handler
+		else // create entry for server savegame. Triggered if save was made after launch and not yet present in res handler
 		{
 			controlServerSaveName = boost::filesystem::path(clientSaveName).replace_extension(".vsgm1");
 			CResourceHandler::get("local")->createResource(controlServerSaveName.string(), true);
@@ -293,13 +293,13 @@ void CClient::loadGame(const std::string & fname, const bool server, const std::
 			loader = checkingLoader.decay();
 		}
 		logNetwork->infoStream() << "Loaded common part of save " << tmh.getDiff();
-		const_cast<CGameInfo*>(CGI)->mh = new CMapHandler();
-		const_cast<CGameInfo*>(CGI)->mh->map = gs->map;
+		const_cast<CGameInfo *>(CGI)->mh = new CMapHandler();
+		const_cast<CGameInfo *>(CGI)->mh->map = gs->map;
 		pathInfo = make_unique<CPathsInfo>(getMapSize());
 		CGI->mh->init();
-		logNetwork->infoStream() <<"Initing maphandler: "<<tmh.getDiff();
+		logNetwork->infoStream() << "Initing maphandler: " << tmh.getDiff();
 	}
-	catch(std::exception &e)
+	catch(std::exception & e)
 	{
 		logGlobal->errorStream() << "Cannot load game " << fname << ". Error: " << e.what();
 		throw; //obviously we cannot continue here
@@ -312,8 +312,8 @@ void CClient::loadGame(const std::string & fname, const bool server, const std::
 
 	std::set<PlayerColor> clientPlayers;
 	if(server)
-	serv = sh.connectToServer();
-    //*loader >> *this;
+		serv = sh.connectToServer();
+	//*loader >> *this;
 
 	if(server)
 	{
@@ -332,7 +332,7 @@ void CClient::loadGame(const std::string & fname, const bool server, const std::
 	{
 		for(auto & elem : gs->scenarioOps->playerInfos)
 		{
-			if(!std::count(humanplayerindices.begin(),humanplayerindices.end(),elem.first.getNum()) || elem.first==player)
+			if(!std::count(humanplayerindices.begin(), humanplayerindices.end(), elem.first.getNum()) || elem.first == player)
 				clientPlayers.insert(elem.first);
 		}
 		clientPlayers.insert(PlayerColor::NEUTRAL);
@@ -353,32 +353,37 @@ void CClient::loadGame(const std::string & fname, const bool server, const std::
 		*serv << ui8(elem.getNum());
 	serv->addStdVecItems(gs); /*why is this here?*/
 
-    //*loader >> *this;
+	//*loader >> *this;
 	logNetwork->infoStream() << "Loaded client part of save " << tmh.getDiff();
 
-	logNetwork->infoStream() <<"Sent info to server: "<<tmh.getDiff();
+	logNetwork->infoStream() << "Sent info to server: " << tmh.getDiff();
 
-    //*serv << clientPlayers;
+	//*serv << clientPlayers;
 	serv->enableStackSendingByID();
 	serv->disableSmartPointerSerialization();
 
-// 	logGlobal->traceStream() << "Objects:";
-// 	for(int i = 0; i < gs->map->objects.size(); i++)
-// 	{
-// 		auto o = gs->map->objects[i];
-// 		if(o)
-// 			logGlobal->traceStream() << boost::format("\tindex=%5d, id=%5d; address=%5d, pos=%s, name=%s") % i % o->id % (int)o.get() % o->pos % o->getHoverText();
-// 		else
-// 			logGlobal->traceStream() << boost::format("\tindex=%5d --- nullptr") % i;
-// 	}
+//      logGlobal->traceStream() << "Objects:";
+//      for(int i = 0; i < gs->map->objects.size(); i++)
+//      {
+//              auto o = gs->map->objects[i];
+//              if(o)
+//                      logGlobal->traceStream() << boost::format("\tindex=%5d, id=%5d; address=%5d, pos=%s, name=%s") % i % o->id % (int)o.get() % o->pos % o->getHoverText();
+//              else
+//                      logGlobal->traceStream() << boost::format("\tindex=%5d --- nullptr") % i;
+//      }
 }
 #endif
 
-void CClient::newGame( CConnection *con, StartInfo *si )
+void CClient::newGame(CConnection * con, StartInfo * si)
 {
-	enum {SINGLE, HOST, GUEST} networkMode = SINGLE;
+	enum
+	{
+		SINGLE,
+		HOST,
+		GUEST
+	} networkMode = SINGLE;
 
-	if (con == nullptr)
+	if(con == nullptr)
 	{
 		CServerHandler sh;
 		serv = sh.connectToServer();
@@ -389,10 +394,10 @@ void CClient::newGame( CConnection *con, StartInfo *si )
 		networkMode = con->isHost() ? HOST : GUEST;
 	}
 
-	CConnection &c = *serv;
+	CConnection & c = *serv;
 	////////////////////////////////////////////////////
 
-	logNetwork->infoStream() <<"\tWill send info to server...";
+	logNetwork->infoStream() << "\tWill send info to server...";
 	CStopWatch tmh;
 
 	if(networkMode == SINGLE)
@@ -401,29 +406,30 @@ void CClient::newGame( CConnection *con, StartInfo *si )
 		c << ui8(2) << ui8(1); //new game; one client
 		c << *si;
 		c >> pom8;
-		if(pom8) throw std::runtime_error("Server cannot open the map!");
+		if(pom8)
+			throw std::runtime_error("Server cannot open the map!");
 	}
 
 	c >> si;
-	logNetwork->infoStream() <<"\tSending/Getting info to/from the server: "<<tmh.getDiff();
+	logNetwork->infoStream() << "\tSending/Getting info to/from the server: " << tmh.getDiff();
 	c.enableStackSendingByID();
 	c.disableSmartPointerSerialization();
 
 	// Initialize game state
 	gs = new CGameState();
-	logNetwork->info("\tCreating gamestate: %i",tmh.getDiff());
+	logNetwork->info("\tCreating gamestate: %i", tmh.getDiff());
 
 	gs->init(si, settings["general"]["saveRandomMaps"].Bool());
-	logNetwork->infoStream() <<"Initializing GameState (together): "<<tmh.getDiff();
+	logNetwork->infoStream() << "Initializing GameState (together): " << tmh.getDiff();
 
 	// Now after possible random map gen, we know exact player count.
 	// Inform server about how many players client handles
 	std::set<PlayerColor> myPlayers;
 	for(auto & elem : gs->scenarioOps->playerInfos)
 	{
-		if((networkMode == SINGLE)                                                      //single - one client has all player
-		   || (networkMode != SINGLE && serv->connectionID == elem.second.playerID)      //multi - client has only "its players"
-		   || (networkMode == HOST && elem.second.playerID == PlayerSettings::PLAYER_AI))//multi - host has all AI players
+		if((networkMode == SINGLE) //single - one client has all player
+		   || (networkMode != SINGLE && serv->connectionID == elem.second.playerID) //multi - client has only "its players"
+		   || (networkMode == HOST && elem.second.playerID == PlayerSettings::PLAYER_AI)) //multi - host has all AI players
 		{
 			myPlayers.insert(elem.first); //add player
 		}
@@ -437,7 +443,7 @@ void CClient::newGame( CConnection *con, StartInfo *si )
 	{
 		if(!settings["session"]["headless"].Bool())
 		{
-			const_cast<CGameInfo*>(CGI)->mh = new CMapHandler();
+			const_cast<CGameInfo *>(CGI)->mh = new CMapHandler();
 			CGI->mh->map = gs->map;
 			logNetwork->infoStream() << "Creating mapHandler: " << tmh.getDiff();
 			CGI->mh->init();
@@ -447,7 +453,7 @@ void CClient::newGame( CConnection *con, StartInfo *si )
 	}
 
 	int humanPlayers = 0;
-	for(auto & elem : gs->scenarioOps->playerInfos)//initializing interfaces for players
+	for(auto & elem : gs->scenarioOps->playerInfos) //initializing interfaces for players
 	{
 		PlayerColor color = elem.first;
 		gs->currentPlayer = color;
@@ -477,19 +483,19 @@ void CClient::newGame( CConnection *con, StartInfo *si )
 	serv->addStdVecItems(gs);
 	hotSeat = (humanPlayers > 1);
 
-// 	std::vector<FileInfo> scriptModules;
-// 	CFileUtility::getFilesWithExt(scriptModules, LIB_DIR "/scripting", "." LIB_EXT);
-// 	for(FileInfo &m : scriptModules)
-// 	{
-// 		CScriptingModule * nm = CDynLibHandler::getNewScriptingModule(m.name);
-// 		privilagedGameEventReceivers.push_back(nm);
-// 		privilagedBattleEventReceivers.push_back(nm);
-// 		nm->giveActionCB(this);
-// 		nm->giveInfoCB(this);
-// 		nm->init();
+//      std::vector<FileInfo> scriptModules;
+//      CFileUtility::getFilesWithExt(scriptModules, LIB_DIR "/scripting", "." LIB_EXT);
+//      for(FileInfo &m : scriptModules)
+//      {
+//              CScriptingModule * nm = CDynLibHandler::getNewScriptingModule(m.name);
+//              privilagedGameEventReceivers.push_back(nm);
+//              privilagedBattleEventReceivers.push_back(nm);
+//              nm->giveActionCB(this);
+//              nm->giveInfoCB(this);
+//              nm->init();
 //
-// 		erm = nm; //something tells me that there'll at most one module and it'll be ERM
-// 	}
+//              erm = nm; //something tells me that there'll at most one module and it'll be ERM
+//      }
 }
 
 void CClient::serialize(BinarySerializer & h, const int version)
@@ -518,7 +524,7 @@ void CClient::serialize(BinaryDeserializer & h, const int version)
 		ui8 players = 0; //fix for uninitialized warning
 		h & players;
 
-		for(int i=0; i < players; i++)
+		for(int i = 0; i < players; i++)
 		{
 			std::string dllname;
 			PlayerColor pid;
@@ -587,7 +593,7 @@ void CClient::serialize(BinaryDeserializer & h, const int version, const std::se
 		ui8 players = 0; //fix for uninitialized warning
 		h & players;
 
-		for(int i=0; i < players; i++)
+		for(int i = 0; i < players; i++)
 		{
 			std::string dllname;
 			PlayerColor pid;
@@ -656,14 +662,14 @@ void CClient::serialize(BinaryDeserializer & h, const int version, const std::se
 	}
 }
 
-void CClient::handlePack( CPack * pack )
+void CClient::handlePack(CPack * pack)
 {
 	if(pack == nullptr)
 	{
 		logNetwork->error("Dropping nullptr CPack! You should check whether client and server ABI matches.");
 		return;
 	}
-	CBaseForCLApply *apply = applier->getApplier(typeList.getTypeID(pack)); //find the applier
+	CBaseForCLApply * apply = applier->getApplier(typeList.getTypeID(pack)); //find the applier
 	if(apply)
 	{
 		boost::unique_lock<boost::recursive_mutex> guiLock(*CPlayerInterface::pim);
@@ -681,7 +687,7 @@ void CClient::handlePack( CPack * pack )
 	delete pack;
 }
 
-void CClient::finishCampaign( std::shared_ptr<CCampaignState> camp )
+void CClient::finishCampaign(std::shared_ptr<CCampaignState> camp)
 {
 }
 
@@ -714,7 +720,7 @@ void CClient::stopConnection()
 
 	{
 		TLockGuard _(connectionHandlerMutex);
-		if(connectionHandler)//end connection handler
+		if(connectionHandler) //end connection handler
 		{
 			if(connectionHandler->get_id() != boost::this_thread::get_id())
 				connectionHandler->join();
@@ -725,7 +731,7 @@ void CClient::stopConnection()
 	}
 
 
-	if (serv) //and delete connection
+	if(serv) //and delete connection
 	{
 		serv->close();
 		vstd::clear_pointer(serv);
@@ -735,30 +741,30 @@ void CClient::stopConnection()
 
 void CClient::battleStarted(const BattleInfo * info)
 {
-	for(auto &battleCb : battleCallbacks)
+	for(auto & battleCb : battleCallbacks)
 	{
-		if(vstd::contains_if(info->sides, [&](const SideInBattle& side) {return side.color == battleCb.first; })
-			||  battleCb.first >= PlayerColor::PLAYER_LIMIT)
+		if(vstd::contains_if(info->sides, [&](const SideInBattle & side) {return side.color == battleCb.first; })
+		   || battleCb.first >= PlayerColor::PLAYER_LIMIT)
 		{
 			battleCb.second->setBattle(info);
 		}
 	}
-// 	for(ui8 side : info->sides)
-// 		if(battleCallbacks.count(side))
-// 			battleCallbacks[side]->setBattle(info);
+//      for(ui8 side : info->sides)
+//              if(battleCallbacks.count(side))
+//                      battleCallbacks[side]->setBattle(info);
 
 	std::shared_ptr<CPlayerInterface> att, def;
-	auto &leftSide = info->sides[0], &rightSide = info->sides[1];
+	auto & leftSide = info->sides[0], & rightSide = info->sides[1];
 
 
 	//If quick combat is not, do not prepare interfaces for battleint
 	if(!settings["adventure"]["quickCombat"].Bool())
 	{
 		if(vstd::contains(playerint, leftSide.color) && playerint[leftSide.color]->human)
-			att = std::dynamic_pointer_cast<CPlayerInterface>( playerint[leftSide.color] );
+			att = std::dynamic_pointer_cast<CPlayerInterface>(playerint[leftSide.color]);
 
 		if(vstd::contains(playerint, rightSide.color) && playerint[rightSide.color]->human)
-			def = std::dynamic_pointer_cast<CPlayerInterface>( playerint[rightSide.color] );
+			def = std::dynamic_pointer_cast<CPlayerInterface>(playerint[rightSide.color]);
 	}
 
 	if(!settings["session"]["headless"].Bool())
@@ -767,8 +773,8 @@ void CClient::battleStarted(const BattleInfo * info)
 		{
 			boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
 			auto bi = new CBattleInterface(leftSide.armyObject, rightSide.armyObject, leftSide.hero, rightSide.hero,
-				Rect((screen->w - 800)/2,
-					 (screen->h - 600)/2, 800, 600), att, def);
+						       Rect((screen->w - 800) / 2,
+							    (screen->h - 600) / 2, 800, 600), att, def);
 
 			GH.pushInt(bi);
 		}
@@ -779,17 +785,18 @@ void CClient::battleStarted(const BattleInfo * info)
 			spectratorInt->cb->setBattle(info);
 			boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
 			auto bi = new CBattleInterface(leftSide.armyObject, rightSide.armyObject, leftSide.hero, rightSide.hero,
-				Rect((screen->w - 800)/2,
-					 (screen->h - 600)/2, 800, 600), att, def, spectratorInt);
+						       Rect((screen->w - 800) / 2,
+							    (screen->h - 600) / 2, 800, 600), att, def, spectratorInt);
 
 			GH.pushInt(bi);
 		}
 	}
 
-	auto callBattleStart = [&](PlayerColor color, ui8 side){
-		if(vstd::contains(battleints, color))
-			battleints[color]->battleStart(leftSide.armyObject, rightSide.armyObject, info->tile, leftSide.hero, rightSide.hero, side);
-	};
+	auto callBattleStart = [&](PlayerColor color, ui8 side)
+		{
+			if(vstd::contains(battleints, color))
+				battleints[color]->battleStart(leftSide.armyObject, rightSide.armyObject, info->tile, leftSide.hero, rightSide.hero, side);
+		};
 
 	callBattleStart(leftSide.color, 0);
 	callBattleStart(rightSide.color, 1);
@@ -797,7 +804,7 @@ void CClient::battleStarted(const BattleInfo * info)
 	if(settings["session"]["spectate"].Bool() && !settings["session"]["spectate-skip-battle"].Bool())
 		callBattleStart(PlayerColor::SPECTATOR, 1);
 
-	if(info->tacticDistance && vstd::contains(battleints,info->sides[info->tacticsSide].color))
+	if(info->tacticDistance && vstd::contains(battleints, info->sides[info->tacticsSide].color))
 	{
 		boost::thread(&CClient::commenceTacticPhaseForInt, this, battleints[info->sides[info->tacticsSide].color]);
 	}
@@ -818,7 +825,7 @@ void CClient::loadNeutralBattleAI()
 	installNewBattleInterface(CDynLibHandler::getNewBattleAI(settings["server"]["neutralAI"].String()), PlayerColor::NEUTRAL);
 }
 
-void CClient::commitPackage( CPackForClient *pack )
+void CClient::commitPackage(CPackForClient * pack)
 {
 	CommitPackage cp;
 	cp.freePack = false;
@@ -858,46 +865,46 @@ void CClient::invalidatePaths()
 	pathInfo->hero = nullptr;
 }
 
-const CPathsInfo * CClient::getPathsInfo(const CGHeroInstance *h)
+const CPathsInfo * CClient::getPathsInfo(const CGHeroInstance * h)
 {
 	assert(h);
 	boost::unique_lock<boost::mutex> pathLock(pathInfo->pathMx);
-	if (pathInfo->hero != h)
+	if(pathInfo->hero != h)
 	{
 		gs->calculatePaths(h, *pathInfo.get());
 	}
 	return pathInfo.get();
 }
 
-int CClient::sendRequest(const CPack *request, PlayerColor player)
+int CClient::sendRequest(const CPack * request, PlayerColor player)
 {
 	static ui32 requestCounter = 0;
 
 	ui32 requestID = requestCounter++;
 	logNetwork->traceStream() << boost::format("Sending a request \"%s\". It'll have an ID=%d.")
-				% typeid(*request).name() % requestID;
+	% typeid(*request).name() % requestID;
 
 	waitingRequest.pushBack(requestID);
 	serv->sendPackToServer(*request, player, requestID);
 	if(vstd::contains(playerint, player))
-		playerint[player]->requestSent(dynamic_cast<const CPackForServer*>(request), requestID);
+		playerint[player]->requestSent(dynamic_cast<const CPackForServer *>(request), requestID);
 
 	return requestID;
 }
 
-void CClient::campaignMapFinished( std::shared_ptr<CCampaignState> camp )
+void CClient::campaignMapFinished(std::shared_ptr<CCampaignState> camp)
 {
 	endGame(false);
 
 	GH.curInt = CGPreGame::create();
 	auto & epilogue = camp->camp->scenarios[camp->mapsConquered.back()].epilog;
 	auto finisher = [=]()
-	{
-		if(camp->mapsRemaining.size())
-			proposeNextMission(camp);
-		else
-			finishCampaign(camp);
-	};
+		{
+			if(camp->mapsRemaining.size())
+				proposeNextMission(camp);
+			else
+				finishCampaign(camp);
+		};
 	if(epilogue.hasPrologEpilog)
 	{
 		GH.pushInt(new CPrologEpilogVideo(epilogue, finisher));
@@ -946,12 +953,12 @@ void CClient::installNewBattleInterface(std::shared_ptr<CBattleGameInterface> ba
 	}
 }
 
-std::string CClient::aiNameForPlayer(const PlayerSettings &ps, bool battleAI)
+std::string CClient::aiNameForPlayer(const PlayerSettings & ps, bool battleAI)
 {
 	if(ps.name.size())
 	{
 		const boost::filesystem::path aiPath = VCMIDirs::get().fullLibraryPath("AI", ps.name);
-		if (boost::filesystem::exists(aiPath))
+		if(boost::filesystem::exists(aiPath))
 			return ps.name;
 	}
 
@@ -1004,7 +1011,7 @@ void CServerHandler::waitForServer()
 		shared->sr->waitTillReady();
 #else
 	logNetwork->infoStream() << "waiting for server";
-	while (!androidTestServerReadyFlag.load())
+	while(!androidTestServerReadyFlag.load())
 	{
 		logNetwork->infoStream() << "still waiting...";
 		boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
@@ -1023,13 +1030,13 @@ CConnection * CServerHandler::connectToServer()
 	th.update(); //put breakpoint here to attach to server before it does something stupid
 
 #ifndef VCMI_ANDROID
-	CConnection *ret = justConnectToServer(settings["server"]["server"].String(), shared ? shared->sr->port : 0);
+	CConnection * ret = justConnectToServer(settings["server"]["server"].String(), shared ? shared->sr->port : 0);
 #else
-	CConnection *ret = justConnectToServer(settings["server"]["server"].String());
+	CConnection * ret = justConnectToServer(settings["server"]["server"].String());
 #endif
 
 	if(verbose)
-		logNetwork->infoStream()<<"\tConnecting to the server: "<<th.getDiff();
+		logNetwork->infoStream() << "\tConnecting to the server: " << th.getDiff();
 
 	return ret;
 }
@@ -1102,7 +1109,7 @@ void CServerHandler::callServer()
 	comm += " > \"" + logName + '\"';
 
 	int result = std::system(comm.c_str());
-	if (result == 0)
+	if(result == 0)
 	{
 		logNetwork->infoStream() << "Server closed correctly";
 		serverAlive.setn(false);
@@ -1111,22 +1118,22 @@ void CServerHandler::callServer()
 	{
 		logNetwork->errorStream() << "Error: server failed to close correctly or crashed!";
 		logNetwork->errorStream() << "Check " << logName << " for more info";
-		exit(1);// exit in case of error. Othervice without working server VCMI will hang
+		exit(1); // exit in case of error. Othervice without working server VCMI will hang
 	}
 #endif
 }
 
-CConnection * CServerHandler::justConnectToServer(const std::string &host, const ui16 port)
+CConnection * CServerHandler::justConnectToServer(const std::string & host, const ui16 port)
 {
-	CConnection *ret = nullptr;
+	CConnection * ret = nullptr;
 	while(!ret)
 	{
 		try
 		{
 			logNetwork->infoStream() << "Establishing connection...";
-			ret = new CConnection(	host.size() ? host : settings["server"]["server"].String(),
-									port ? port : getDefaultPort(),
-									NAME);
+			ret = new CConnection(host.size() ? host : settings["server"]["server"].String(),
+					      port ? port : getDefaultPort(),
+					      NAME);
 			ret->connectionID = 1; // TODO: Refactoring for the server so IDs set outside of CConnection
 		}
 		catch(...)

+ 64 - 59
client/Client.h

@@ -33,16 +33,20 @@ class CScriptingModule;
 struct CPathsInfo;
 class BinaryDeserializer;
 class BinarySerializer;
-namespace boost { class thread; }
+namespace boost
+{
+class thread;
+}
 
 /// structure to handle running server and connecting to it
 class CServerHandler
 {
 private:
 	void callServer(); //calls server via system(), should be called as thread
+
 public:
 	CStopWatch th;
-	boost::thread *serverThread; //thread that called system to run server
+	boost::thread * serverThread; //thread that called system to run server
 	SharedMemory * shared;
 	std::string uuid;
 	bool verbose; //whether to print log msgs
@@ -53,7 +57,7 @@ public:
 	CConnection * connectToServer(); //connects to server
 
 	//////////////////////////////////////////////////////////////////////////
-	static CConnection * justConnectToServer(const std::string &host = "", const ui16 port = 0); //connects to given host without taking any other actions (like setting up server)
+	static CConnection * justConnectToServer(const std::string & host = "", const ui16 port = 0); //connects to given host without taking any other actions (like setting up server)
 	static ui16 getDefaultPort();
 	static std::string getDefaultPortStr();
 
@@ -78,33 +82,33 @@ public:
 		cond.notify_all();
 	}
 
-	void pushBack(const T &item)
+	void pushBack(const T & item)
 	{
 		TLock lock(mx);
 		items.push_back(item);
 		cond.notify_all();
 	}
 
-// 	//to access list, caller must present a lock used to lock mx
-// 	TVector &getList(TLock &lockedLock)
-// 	{
-// 		assert(lockedLock.owns_lock() && lockedLock.mutex() == &mx);
-// 		return items;
-// 	}
+//      //to access list, caller must present a lock used to lock mx
+//      TVector &getList(TLock &lockedLock)
+//      {
+//              assert(lockedLock.owns_lock() && lockedLock.mutex() == &mx);
+//              return items;
+//      }
 
 	TLock getLock()
 	{
 		return TLock(mx);
 	}
 
-	void waitWhileContains(const T &item)
+	void waitWhileContains(const T & item)
 	{
 		auto lock = getLock();
 		while(vstd::contains(items, item))
 			cond.wait(lock);
 	}
 
-	bool tryRemovingElement(const T&item) //returns false if element was not present
+	bool tryRemovingElement(const T & item) //returns false if element was not present
 	{
 		auto lock = getLock();
 		auto itr = vstd::find(items, item);
@@ -123,54 +127,55 @@ public:
 class CClient : public IGameCallback
 {
 	std::unique_ptr<CPathsInfo> pathInfo;
+
 public:
-	std::map<PlayerColor,std::shared_ptr<CCallback> > callbacks; //callbacks given to player interfaces
-	std::map<PlayerColor,std::shared_ptr<CBattleCallback> > battleCallbacks; //callbacks given to player interfaces
+	std::map<PlayerColor, std::shared_ptr<CCallback>> callbacks; //callbacks given to player interfaces
+	std::map<PlayerColor, std::shared_ptr<CBattleCallback>> battleCallbacks; //callbacks given to player interfaces
 	std::vector<std::shared_ptr<IGameEventsReceiver>> privilagedGameEventReceivers; //scripting modules, spectator interfaces
 	std::vector<std::shared_ptr<IBattleEventsReceiver>> privilagedBattleEventReceivers; //scripting modules, spectator interfaces
 	std::map<PlayerColor, std::shared_ptr<CGameInterface>> playerint;
 	std::map<PlayerColor, std::shared_ptr<CBattleGameInterface>> battleints;
 
-	std::map<PlayerColor,std::vector<std::shared_ptr<IGameEventsReceiver>>> additionalPlayerInts;
-	std::map<PlayerColor,std::vector<std::shared_ptr<IBattleEventsReceiver>>> additionalBattleInts;
+	std::map<PlayerColor, std::vector<std::shared_ptr<IGameEventsReceiver>>> additionalPlayerInts;
+	std::map<PlayerColor, std::vector<std::shared_ptr<IBattleEventsReceiver>>> additionalBattleInts;
 
 	bool hotSeat;
-	CConnection *serv;
+	CConnection * serv;
 
 	boost::optional<BattleAction> curbaction;
 
-	CScriptingModule *erm;
+	CScriptingModule * erm;
 
-	static ThreadSafeVector<int> waitingRequest;//FIXME: make this normal field (need to join all threads before client destruction)
+	static ThreadSafeVector<int> waitingRequest; //FIXME: make this normal field (need to join all threads before client destruction)
 
 	void waitForMoveAndSend(PlayerColor color);
 	//void sendRequest(const CPackForServer *request, bool waitForRealization);
 	CClient(void);
-	CClient(CConnection *con, StartInfo *si);
+	CClient(CConnection * con, StartInfo * si);
 	~CClient(void);
 
 	void init();
-	void newGame(CConnection *con, StartInfo *si); //con - connection to server
+	void newGame(CConnection * con, StartInfo * si); //con - connection to server
 
 	void loadNeutralBattleAI();
 	void installNewPlayerInterface(std::shared_ptr<CGameInterface> gameInterface, boost::optional<PlayerColor> color, bool battlecb = false);
 	void installNewBattleInterface(std::shared_ptr<CBattleGameInterface> battleInterface, boost::optional<PlayerColor> color, bool needCallback = true);
-	std::string aiNameForPlayer(const PlayerSettings &ps, bool battleAI); //empty means no AI -> human
+	std::string aiNameForPlayer(const PlayerSettings & ps, bool battleAI); //empty means no AI -> human
 	std::string aiNameForPlayer(bool battleAI);
 
 	void endGame(bool closeConnection = true);
 	void stopConnection();
 	void save(const std::string & fname);
-	void loadGame(const std::string & fname, const bool server = true, const std::vector<int>& humanplayerindices = std::vector<int>(), const int loadnumplayers = 1, int player_ = -1, const std::string & ipaddr = "", const ui16 port = 0);
+	void loadGame(const std::string & fname, const bool server = true, const std::vector<int> & humanplayerindices = std::vector<int>(), const int loadnumplayers = 1, int player_ = -1, const std::string & ipaddr = "", const ui16 port = 0);
 	void run();
-	void campaignMapFinished( std::shared_ptr<CCampaignState> camp );
-	void finishCampaign( std::shared_ptr<CCampaignState> camp );
+	void campaignMapFinished(std::shared_ptr<CCampaignState> camp);
+	void finishCampaign(std::shared_ptr<CCampaignState> camp);
 	void proposeNextMission(std::shared_ptr<CCampaignState> camp);
 
 	void invalidatePaths();
-	const CPathsInfo * getPathsInfo(const CGHeroInstance *h);
+	const CPathsInfo * getPathsInfo(const CGHeroInstance * h);
 
-	bool terminate;	// tell to terminate
+	bool terminate; // tell to terminate
 	std::unique_ptr<boost::thread> connectionHandler; //thread running run() method
 	boost::mutex connectionHandlerMutex;
 
@@ -179,46 +184,46 @@ public:
 
 	//////////////////////////////////////////////////////////////////////////
 	//not working yet, will be implement somewhen later with support for local-sim-based gameplay
-	void changeSpells(const CGHeroInstance * hero, bool give, const std::set<SpellID> &spells) override {};
+	void changeSpells(const CGHeroInstance * hero, bool give, const std::set<SpellID> & spells) override {};
 	bool removeObject(const CGObjectInstance * obj) override {return false;};
 	void setBlockVis(ObjectInstanceID objid, bool bv) override {};
 	void setOwner(const CGObjectInstance * obj, PlayerColor owner) override {};
-	void changePrimSkill(const CGHeroInstance * hero, PrimarySkill::PrimarySkill which, si64 val, bool abs=false) override {};
-	void changeSecSkill(const CGHeroInstance * hero, SecondarySkill which, int val, bool abs=false) override {};
+	void changePrimSkill(const CGHeroInstance * hero, PrimarySkill::PrimarySkill which, si64 val, bool abs = false) override {};
+	void changeSecSkill(const CGHeroInstance * hero, SecondarySkill which, int val, bool abs = false) override {};
 
-	void showBlockingDialog(BlockingDialog *iw) override {};
+	void showBlockingDialog(BlockingDialog * iw) override {};
 	void showGarrisonDialog(ObjectInstanceID upobj, ObjectInstanceID hid, bool removableUnits) override {};
-	void showTeleportDialog(TeleportDialog *iw) override {};
+	void showTeleportDialog(TeleportDialog * iw) override {};
 	void showThievesGuildWindow(PlayerColor player, ObjectInstanceID requestingObjId) override {};
 	void giveResource(PlayerColor player, Res::ERes which, int val) override {};
 	virtual void giveResources(PlayerColor player, TResources resources) override {};
 
-	void giveCreatures(const CArmedInstance * objid, const CGHeroInstance * h, const CCreatureSet &creatures, bool remove) override {};
-	void takeCreatures(ObjectInstanceID objid, const std::vector<CStackBasicDescriptor> &creatures) override {};
-	bool changeStackType(const StackLocation &sl, const CCreature *c) override {return false;};
-	bool changeStackCount(const StackLocation &sl, TQuantity count, bool absoluteValue = false) override {return false;};
-	bool insertNewStack(const StackLocation &sl, const CCreature *c, TQuantity count) override {return false;};
-	bool eraseStack(const StackLocation &sl, bool forceRemoval = false) override{return false;};
-	bool swapStacks(const StackLocation &sl1, const StackLocation &sl2) override {return false;}
-	bool addToSlot(const StackLocation &sl, const CCreature *c, TQuantity count) override {return false;}
-	void tryJoiningArmy(const CArmedInstance *src, const CArmedInstance *dst, bool removeObjWhenFinished, bool allowMerging) override {}
-	bool moveStack(const StackLocation &src, const StackLocation &dst, TQuantity count = -1) override {return false;}
-
-	void removeAfterVisit(const CGObjectInstance *object) override {};
-
-	void giveHeroNewArtifact(const CGHeroInstance *h, const CArtifact *artType, ArtifactPosition pos) override {};
-	void giveHeroArtifact(const CGHeroInstance *h, const CArtifactInstance *a, ArtifactPosition pos) override {};
-	void putArtifact(const ArtifactLocation &al, const CArtifactInstance *a) override {};
-	void removeArtifact(const ArtifactLocation &al) override {};
-	bool moveArtifact(const ArtifactLocation &al1, const ArtifactLocation &al2) override {return false;};
+	void giveCreatures(const CArmedInstance * objid, const CGHeroInstance * h, const CCreatureSet & creatures, bool remove) override {};
+	void takeCreatures(ObjectInstanceID objid, const std::vector<CStackBasicDescriptor> & creatures) override {};
+	bool changeStackType(const StackLocation & sl, const CCreature * c) override {return false;};
+	bool changeStackCount(const StackLocation & sl, TQuantity count, bool absoluteValue = false) override {return false;};
+	bool insertNewStack(const StackLocation & sl, const CCreature * c, TQuantity count) override {return false;};
+	bool eraseStack(const StackLocation & sl, bool forceRemoval = false) override {return false;};
+	bool swapStacks(const StackLocation & sl1, const StackLocation & sl2) override {return false;}
+	bool addToSlot(const StackLocation & sl, const CCreature * c, TQuantity count) override {return false;}
+	void tryJoiningArmy(const CArmedInstance * src, const CArmedInstance * dst, bool removeObjWhenFinished, bool allowMerging) override {}
+	bool moveStack(const StackLocation & src, const StackLocation & dst, TQuantity count = -1) override {return false;}
+
+	void removeAfterVisit(const CGObjectInstance * object) override {};
+
+	void giveHeroNewArtifact(const CGHeroInstance * h, const CArtifact * artType, ArtifactPosition pos) override {};
+	void giveHeroArtifact(const CGHeroInstance * h, const CArtifactInstance * a, ArtifactPosition pos) override {};
+	void putArtifact(const ArtifactLocation & al, const CArtifactInstance * a) override {};
+	void removeArtifact(const ArtifactLocation & al) override {};
+	bool moveArtifact(const ArtifactLocation & al1, const ArtifactLocation & al2) override {return false;};
 	void synchronizeArtifactHandlerLists() override {};
 
 	void showCompInfo(ShowInInfobox * comp) override {};
 	void heroVisitCastle(const CGTownInstance * obj, const CGHeroInstance * hero) override {};
 	void stopHeroVisitCastle(const CGTownInstance * obj, const CGHeroInstance * hero) override {};
-	void startBattlePrimary(const CArmedInstance *army1, const CArmedInstance *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool creatureBank = false, const CGTownInstance *town = nullptr) override {}; //use hero=nullptr for no hero
-	void startBattleI(const CArmedInstance *army1, const CArmedInstance *army2, int3 tile, bool creatureBank = false) override {}; //if any of armies is hero, hero will be used
-	void startBattleI(const CArmedInstance *army1, const CArmedInstance *army2, bool creatureBank = false) override {}; //if any of armies is hero, hero will be used, visitable tile of second obj is place of battle
+	void startBattlePrimary(const CArmedInstance * army1, const CArmedInstance * army2, int3 tile, const CGHeroInstance * hero1, const CGHeroInstance * hero2, bool creatureBank = false, const CGTownInstance * town = nullptr) override {}; //use hero=nullptr for no hero
+	void startBattleI(const CArmedInstance * army1, const CArmedInstance * army2, int3 tile, bool creatureBank = false) override {}; //if any of armies is hero, hero will be used
+	void startBattleI(const CArmedInstance * army1, const CArmedInstance * army2, bool creatureBank = false) override {}; //if any of armies is hero, hero will be used, visitable tile of second obj is place of battle
 	void setAmount(ObjectInstanceID objid, ui32 val) override {};
 	bool moveHero(ObjectInstanceID hid, int3 dst, ui8 teleporting, bool transit = false, PlayerColor asker = PlayerColor::NEUTRAL) override {return false;};
 	void giveHeroBonus(GiveBonus * bonus) override {};
@@ -230,26 +235,26 @@ public:
 	void heroExchange(ObjectInstanceID hero1, ObjectInstanceID hero2) override {};
 
 	void changeFogOfWar(int3 center, ui32 radius, PlayerColor player, bool hide) override {}
-	void changeFogOfWar(std::unordered_set<int3, ShashInt3> &tiles, PlayerColor player, bool hide) override {}
+	void changeFogOfWar(std::unordered_set<int3, ShashInt3> & tiles, PlayerColor player, bool hide) override {}
 
 	//////////////////////////////////////////////////////////////////////////
 	friend class CCallback; //handling players actions
 	friend class CBattleCallback; //handling players actions
 
-	int sendRequest(const CPack *request, PlayerColor player); //returns ID given to that request
+	int sendRequest(const CPack * request, PlayerColor player); //returns ID given to that request
 
-	void handlePack( CPack * pack ); //applies the given pack and deletes it
+	void handlePack(CPack * pack); //applies the given pack and deletes it
 	void battleStarted(const BattleInfo * info);
 	void commenceTacticPhaseForInt(std::shared_ptr<CBattleGameInterface> battleInt); //will be called as separate thread
 
-	void commitPackage(CPackForClient *pack) override;
+	void commitPackage(CPackForClient * pack) override;
 
 	//////////////////////////////////////////////////////////////////////////
 
 	void serialize(BinarySerializer & h, const int version);
 	void serialize(BinaryDeserializer & h, const int version);
 
-	void serialize(BinarySerializer & h, const int version, const std::set<PlayerColor>& playerIDs);
-	void serialize(BinaryDeserializer & h, const int version, const std::set<PlayerColor>& playerIDs);
+	void serialize(BinarySerializer & h, const int version, const std::set<PlayerColor> & playerIDs);
+	void serialize(BinaryDeserializer & h, const int version, const std::set<PlayerColor> & playerIDs);
 	void battleFinished();
 };

+ 70 - 63
client/Graphics.cpp

@@ -45,13 +45,13 @@ Graphics * graphics = nullptr;
 void Graphics::loadPaletteAndColors()
 {
 	auto textFile = CResourceHandler::get()->load(ResourceID("DATA/PLAYERS.PAL"))->readAll();
-	std::string pals((char*)textFile.first.get(), textFile.second);
+	std::string pals((char *)textFile.first.get(), textFile.second);
 
 	playerColorPalette = new SDL_Color[256];
 	neutralColor = new SDL_Color;
 	playerColors = new SDL_Color[PlayerColor::PLAYER_LIMIT_I];
 	int startPoint = 24; //beginning byte; used to read
-	for(int i=0; i<256; ++i)
+	for(int i = 0; i < 256; ++i)
 	{
 		SDL_Color col;
 		col.r = pals[startPoint++];
@@ -67,7 +67,7 @@ void Graphics::loadPaletteAndColors()
 	auto stream = CResourceHandler::get()->load(ResourceID("config/NEUTRAL.PAL"));
 	CBinaryReader reader(stream.get());
 
-	for(int i=0; i<32; ++i)
+	for(int i = 0; i < 32; ++i)
 	{
 		neutralColorPalette[i].r = reader.readUInt8();
 		neutralColorPalette[i].g = reader.readUInt8();
@@ -76,18 +76,20 @@ void Graphics::loadPaletteAndColors()
 		neutralColorPalette[i].a = SDL_ALPHA_OPAQUE;
 	}
 	//colors initialization
-	SDL_Color colors[]  = {
-		{0xff,0,  0,    SDL_ALPHA_OPAQUE},
-		{0x31,0x52,0xff,SDL_ALPHA_OPAQUE},
-		{0x9c,0x73,0x52,SDL_ALPHA_OPAQUE},
-		{0x42,0x94,0x29,SDL_ALPHA_OPAQUE},
-
-		{0xff,0x84,0,   SDL_ALPHA_OPAQUE},
-		{0x8c,0x29,0xa5,SDL_ALPHA_OPAQUE},
-		{0x09,0x9c,0xa5,SDL_ALPHA_OPAQUE},
-		{0xc6,0x7b,0x8c,SDL_ALPHA_OPAQUE}};
-
-	for(int i=0;i<8;i++)
+	SDL_Color colors[] =
+	{
+		{0xff, 0, 0, SDL_ALPHA_OPAQUE},
+		{0x31, 0x52, 0xff, SDL_ALPHA_OPAQUE},
+		{0x9c, 0x73, 0x52, SDL_ALPHA_OPAQUE},
+		{0x42, 0x94, 0x29, SDL_ALPHA_OPAQUE},
+
+		{0xff, 0x84, 0, SDL_ALPHA_OPAQUE},
+		{0x8c, 0x29, 0xa5, SDL_ALPHA_OPAQUE},
+		{0x09, 0x9c, 0xa5, SDL_ALPHA_OPAQUE},
+		{0xc6, 0x7b, 0x8c, SDL_ALPHA_OPAQUE}
+	};
+
+	for(int i = 0; i < 8; i++)
 	{
 		playerColors[i] = colors[i];
 	}
@@ -104,20 +106,23 @@ void Graphics::initializeBattleGraphics()
 
 	// Reserve enough space for the terrains
 	int idx = config["backgrounds"].Vector().size();
-	battleBacks.resize(idx+1);	// 1 to idx, 0 is unused
+	battleBacks.resize(idx + 1); // 1 to idx, 0 is unused
 
 	idx = 1;
-	for(const JsonNode &t : config["backgrounds"].Vector()) {
+	for(const JsonNode & t : config["backgrounds"].Vector())
+	{
 		battleBacks[idx].push_back(t.String());
 		idx++;
 	}
 
 	//initialization of AC->def name mapping
-	for(const JsonNode &ac : config["ac_mapping"].Vector()) {
+	for(const JsonNode & ac : config["ac_mapping"].Vector())
+	{
 		int ACid = ac["id"].Float();
-		std::vector< std::string > toAdd;
+		std::vector<std::string> toAdd;
 
-		for(const JsonNode &defname : ac["defnames"].Vector()) {
+		for(const JsonNode & defname : ac["defnames"].Vector())
+		{
 			toAdd.push_back(defname.String());
 		}
 
@@ -129,13 +134,13 @@ Graphics::Graphics()
 	#if 0
 
 	std::vector<Task> tasks; //preparing list of graphics to load
-	tasks += std::bind(&Graphics::loadFonts,this);
-	tasks += std::bind(&Graphics::loadPaletteAndColors,this);
-	tasks += std::bind(&Graphics::initializeBattleGraphics,this);
-	tasks += std::bind(&Graphics::loadErmuToPicture,this);
-	tasks += std::bind(&Graphics::initializeImageLists,this);
+	tasks += std::bind(&Graphics::loadFonts, this);
+	tasks += std::bind(&Graphics::loadPaletteAndColors, this);
+	tasks += std::bind(&Graphics::initializeBattleGraphics, this);
+	tasks += std::bind(&Graphics::loadErmuToPicture, this);
+	tasks += std::bind(&Graphics::initializeImageLists, this);
 
-	CThreadHelper th(&tasks,std::max((ui32)1,boost::thread::hardware_concurrency()));
+	CThreadHelper th(&tasks, std::max((ui32)1, boost::thread::hardware_concurrency()));
 	th.run();
 	#else
 	loadFonts();
@@ -170,9 +175,9 @@ void Graphics::loadHeroAnimations()
 {
 	for(auto & elem : CGI->heroh->classes.heroClasses)
 	{
-		for (auto & templ : VLC->objtypeh->getHandlerFor(Obj::HERO, elem->id)->getTemplates())
+		for(auto & templ : VLC->objtypeh->getHandlerFor(Obj::HERO, elem->id)->getTemplates())
 		{
-			if (!heroAnimations.count(templ.animationFile))
+			if(!heroAnimations.count(templ.animationFile))
 				heroAnimations[templ.animationFile] = loadHeroAnimation(templ.animationFile);
 		}
 	}
@@ -190,11 +195,11 @@ void Graphics::loadHeroFlagAnimations()
 {
 	static const std::vector<std::string> HERO_FLAG_ANIMATIONS =
 	{
-		"AF00", "AF01","AF02","AF03",
-		"AF04", "AF05","AF06","AF07"
+		"AF00", "AF01", "AF02", "AF03",
+		"AF04", "AF05", "AF06", "AF07"
 	};
 
-	static const std::vector< std::vector<std::string> > BOAT_FLAG_ANIMATIONS =
+	static const std::vector<std::vector<std::string>> BOAT_FLAG_ANIMATIONS =
 	{
 		{
 			"ABF01L", "ABF01G", "ABF01R", "ABF01D",
@@ -221,10 +226,10 @@ void Graphics::loadHeroFlagAnimations()
 std::shared_ptr<CAnimation> Graphics::loadHeroFlagAnimation(const std::string & name)
 {
 	//first - group number to be rotated, second - group number after rotation
-	static const std::vector<std::pair<int,int> > rotations =
+	static const std::vector<std::pair<int, int>> rotations =
 	{
-		{6,10}, {7,11}, {8,12}, {1,13},
-		{2,14}, {3,15}
+		{6, 10}, {7, 11}, {8, 12}, {1, 13},
+		{2, 14}, {3, 15}
 	};
 
 	std::shared_ptr<CAnimation> anim = std::make_shared<CAnimation>(name);
@@ -232,10 +237,10 @@ std::shared_ptr<CAnimation> Graphics::loadHeroFlagAnimation(const std::string &
 
 	for(const auto & rotation : rotations)
 	{
-        const int sourceGroup = rotation.first;
-        const int targetGroup = rotation.second;
+		const int sourceGroup = rotation.first;
+		const int targetGroup = rotation.second;
 
-        for(size_t frame = 0; frame < anim->size(sourceGroup); ++frame)
+		for(size_t frame = 0; frame < anim->size(sourceGroup); ++frame)
 		{
 			anim->duplicateImage(sourceGroup, frame, targetGroup);
 
@@ -247,13 +252,13 @@ std::shared_ptr<CAnimation> Graphics::loadHeroFlagAnimation(const std::string &
 	return anim;
 }
 
-std::shared_ptr<CAnimation> Graphics::loadHeroAnimation(const std::string &name)
+std::shared_ptr<CAnimation> Graphics::loadHeroAnimation(const std::string & name)
 {
 	//first - group number to be rotated, second - group number after rotation
-	static const std::vector<std::pair<int,int> > rotations =
+	static const std::vector<std::pair<int, int>> rotations =
 	{
-		{6,10}, {7,11}, {8,12}, {1,13},
-		{2,14}, {3,15}
+		{6, 10}, {7, 11}, {8, 12}, {1, 13},
+		{2, 14}, {3, 15}
 	};
 
 	std::shared_ptr<CAnimation> anim = std::make_shared<CAnimation>(name);
@@ -262,10 +267,10 @@ std::shared_ptr<CAnimation> Graphics::loadHeroAnimation(const std::string &name)
 
 	for(const auto & rotation : rotations)
 	{
-        const int sourceGroup = rotation.first;
-        const int targetGroup = rotation.second;
+		const int sourceGroup = rotation.first;
+		const int targetGroup = rotation.second;
 
-        for(size_t frame = 0; frame < anim->size(sourceGroup); ++frame)
+		for(size_t frame = 0; frame < anim->size(sourceGroup); ++frame)
 		{
 			anim->duplicateImage(sourceGroup, frame, targetGroup);
 			IImage * image = anim->getImage(frame, targetGroup);
@@ -280,10 +285,10 @@ void Graphics::blueToPlayersAdv(SDL_Surface * sur, PlayerColor player)
 {
 	if(sur->format->palette)
 	{
-		SDL_Color *palette = nullptr;
+		SDL_Color * palette = nullptr;
 		if(player < PlayerColor::PLAYER_LIMIT)
 		{
-			palette = playerColorPalette + 32*player.getNum();
+			palette = playerColorPalette + 32 * player.getNum();
 		}
 		else if(player == PlayerColor::NEUTRAL)
 		{
@@ -313,9 +318,9 @@ void Graphics::loadFogOfWar()
 	fogOfWarPartialHide = std::make_shared<CAnimation>("TSHRE");
 	fogOfWarPartialHide->preload();
 
-	static const int rotations [] = {22, 15, 2, 13, 12, 16, 28, 17, 20, 19, 7, 24, 26, 25, 30, 32, 27};
+	static const int rotations[] = {22, 15, 2, 13, 12, 16, 28, 17, 20, 19, 7, 24, 26, 25, 30, 32, 27};
 
-	size_t size = fogOfWarPartialHide->size(0);//group size after next rotation
+	size_t size = fogOfWarPartialHide->size(0); //group size after next rotation
 
 	for(const int rotation : rotations)
 	{
@@ -331,25 +336,25 @@ void Graphics::loadFonts()
 	const JsonNode config(ResourceID("config/fonts.json"));
 
 	const JsonVector & bmpConf = config["bitmap"].Vector();
-	const JsonNode   & ttfConf = config["trueType"];
-	const JsonNode   & hanConf = config["bitmapHan"];
+	const JsonNode & ttfConf = config["trueType"];
+	const JsonNode & hanConf = config["bitmapHan"];
 
 	assert(bmpConf.size() == FONTS_NUMBER);
 
-	for (size_t i=0; i<FONTS_NUMBER; i++)
+	for(size_t i = 0; i < FONTS_NUMBER; i++)
 	{
 		std::string filename = bmpConf[i].String();
 
-		if (!hanConf[filename].isNull())
+		if(!hanConf[filename].isNull())
 			fonts[i] = std::make_shared<CBitmapHanFont>(hanConf[filename]);
-		else if (!ttfConf[filename].isNull()) // no ttf override
+		else if(!ttfConf[filename].isNull()) // no ttf override
 			fonts[i] = std::make_shared<CTrueTypeFont>(ttfConf[filename]);
 		else
 			fonts[i] = std::make_shared<CBitmapFont>(filename);
 	}
 }
 
-std::shared_ptr<CAnimation> Graphics::getAnimation(const CGObjectInstance* obj)
+std::shared_ptr<CAnimation> Graphics::getAnimation(const CGObjectInstance * obj)
 {
 	return getAnimation(obj->appearance);
 }
@@ -389,22 +394,24 @@ void Graphics::loadErmuToPicture()
 	//loading ERMU to picture
 	const JsonNode config(ResourceID("config/ERMU_to_picture.json"));
 	int etp_idx = 0;
-	for(const JsonNode &etp : config["ERMU_to_picture"].Vector()) {
+	for(const JsonNode & etp : config["ERMU_to_picture"].Vector())
+	{
 		int idx = 0;
-		for(const JsonNode &n : etp.Vector()) {
+		for(const JsonNode & n : etp.Vector())
+		{
 			ERMUtoPicture[idx][etp_idx] = n.String();
-			idx ++;
+			idx++;
 		}
-		assert (idx == ARRAY_COUNT(ERMUtoPicture));
+		assert(idx == ARRAY_COUNT(ERMUtoPicture));
 
-		etp_idx ++;
+		etp_idx++;
 	}
-	assert (etp_idx == 44);
+	assert(etp_idx == 44);
 }
 
 void Graphics::addImageListEntry(size_t index, std::string listName, std::string imageName)
 {
-	if (!imageName.empty())
+	if(!imageName.empty())
 	{
 		JsonNode entry;
 		entry["frame"].Float() = index;
@@ -438,7 +445,7 @@ void Graphics::initializeImageLists()
 
 	for(const CFaction * faction : CGI->townh->factions)
 	{
-		if (faction->town)
+		if(faction->town)
 		{
 			auto & info = faction->town->clientInfo;
 			addImageListEntry(info.icons[0][0], "ITPT", info.iconLarge[0][0]);
@@ -456,7 +463,7 @@ void Graphics::initializeImageLists()
 	for(const CSpell * spell : CGI->spellh->objects)
 	{
 		addImageListEntry(spell->id, "SPELLS", spell->iconBook);
-		addImageListEntry(spell->id+1, "SPELLINT", spell->iconEffect);
+		addImageListEntry(spell->id + 1, "SPELLINT", spell->iconEffect);
 		addImageListEntry(spell->id, "SPELLBON", spell->iconScenarioBonus);
 		addImageListEntry(spell->id, "SPELLSCR", spell->iconScroll);
 	}

+ 19 - 11
client/Graphics.h

@@ -26,7 +26,15 @@ class CAnimation;
 
 enum EFonts
 {
-	FONT_BIG, FONT_CALLI, FONT_CREDITS, FONT_HIGH_SCORE, FONT_MEDIUM, FONT_SMALL, FONT_TIMES, FONT_TINY, FONT_VERD
+	FONT_BIG,
+	FONT_CALLI,
+	FONT_CREDITS,
+	FONT_HIGH_SCORE,
+	FONT_MEDIUM,
+	FONT_SMALL,
+	FONT_TIMES,
+	FONT_TINY,
+	FONT_VERD
 };
 
 /// Handles fonts, hero images, town images, various graphics
@@ -39,12 +47,12 @@ class Graphics
 
 	void loadHeroAnimations();
 	//loads animation and adds required rotated frames
-	std::shared_ptr<CAnimation> loadHeroAnimation(const std::string &name);
+	std::shared_ptr<CAnimation> loadHeroAnimation(const std::string & name);
 
 	void loadHeroFlagAnimations();
 
 	//loads animation and adds required rotated frames
-	std::shared_ptr<CAnimation> loadHeroFlagAnimation(const std::string &name);
+	std::shared_ptr<CAnimation> loadHeroFlagAnimation(const std::string & name);
 
 	void loadErmuToPicture();
 	void loadFogOfWar();
@@ -54,7 +62,7 @@ class Graphics
 public:
 	//Fonts
 	static const int FONTS_NUMBER = 9;
-	std::array< std::shared_ptr<IFont>, FONTS_NUMBER> fonts;
+	std::array<std::shared_ptr<IFont>, FONTS_NUMBER> fonts;
 
 	//various graphics
 	SDL_Color * playerColors; //array [8]
@@ -65,16 +73,16 @@ public:
 	std::shared_ptr<CAnimation> heroMoveArrows;
 
 	// [hero class def name]  //added group 10: up - left, 11 - left and 12 - left down // 13 - up-left standing; 14 - left standing; 15 - left down standing
-	std::map< std::string, std::shared_ptr<CAnimation> > heroAnimations;
-	std::vector< std::shared_ptr<CAnimation> > heroFlagAnimations;
+	std::map<std::string, std::shared_ptr<CAnimation>> heroAnimations;
+	std::vector<std::shared_ptr<CAnimation>> heroFlagAnimations;
 
 	// [boat type: 0 .. 2]  //added group 10: up - left, 11 - left and 12 - left down // 13 - up-left standing; 14 - left standing; 15 - left down standing
-	std::array< std::shared_ptr<CAnimation>, 3> boatAnimations;
+	std::array<std::shared_ptr<CAnimation>, 3> boatAnimations;
 
-	std::array< std::vector<std::shared_ptr<CAnimation> >, 3> boatFlagAnimations;
+	std::array<std::vector<std::shared_ptr<CAnimation>>, 3> boatFlagAnimations;
 
 	//all other objects (not hero or boat)
-	std::map< std::string, std::shared_ptr<CAnimation> > mapObjectAnimations;
+	std::map<std::string, std::shared_ptr<CAnimation>> mapObjectAnimations;
 
 	std::shared_ptr<CAnimation> fogOfWarFullHide;
 	std::shared_ptr<CAnimation> fogOfWarPartialHide;
@@ -84,8 +92,8 @@ public:
 	//towns
 	std::map<int, std::string> ERMUtoPicture[GameConstants::F_NUMBER]; //maps building ID to it's picture's name for each town type
 	//for battles
-	std::vector< std::vector< std::string > > battleBacks; //battleBacks[terType] - vector of possible names for certain terrain type
-	std::map< int, std::vector < std::string > > battleACToDef; //maps AC format to vector of appropriate def names
+	std::vector<std::vector<std::string>> battleBacks; //battleBacks[terType] - vector of possible names for certain terrain type
+	std::map<int, std::vector<std::string>> battleACToDef; //maps AC format to vector of appropriate def names
 
 	//functions
 	Graphics();

File diff suppressed because it is too large
+ 282 - 284
client/NetPacksClient.cpp


+ 25 - 25
client/SDLRWwrapper.cpp

@@ -13,20 +13,20 @@
 #include "../lib/filesystem/CInputStream.h"
 #include <SDL_rwops.h>
 
-static inline CInputStream* get_stream(SDL_RWops* context)
+static inline CInputStream * get_stream(SDL_RWops * context)
 {
-	return static_cast<CInputStream*>(context->hidden.unknown.data1);
+	return static_cast<CInputStream *>(context->hidden.unknown.data1);
 }
 
-static Sint64 impl_size(SDL_RWops* context)
+static Sint64 impl_size(SDL_RWops * context)
 {
-    return get_stream(context)->getSize();
+	return get_stream(context)->getSize();
 }
 
-static Sint64 impl_seek(SDL_RWops* context, Sint64 offset, int whence)
+static Sint64 impl_seek(SDL_RWops * context, Sint64 offset, int whence)
 {
 	auto stream = get_stream(context);
-	switch (whence)
+	switch(whence)
 	{
 	case RW_SEEK_SET:
 		return stream->seek(offset);
@@ -43,48 +43,48 @@ static Sint64 impl_seek(SDL_RWops* context, Sint64 offset, int whence)
 
 }
 
-static std::size_t impl_read(SDL_RWops* context, void *ptr, size_t size, size_t maxnum)
+static std::size_t impl_read(SDL_RWops * context, void * ptr, size_t size, size_t maxnum)
 {
-    auto stream = get_stream(context);
-    auto oldpos = stream->tell();
+	auto stream = get_stream(context);
+	auto oldpos = stream->tell();
 
-    auto count = stream->read(static_cast<ui8*>(ptr), size*maxnum);
+	auto count = stream->read(static_cast<ui8 *>(ptr), size * maxnum);
 
-	if (count != 0 && count != size*maxnum)
+	if(count != 0 && count != size * maxnum)
 	{
 		// if not a whole amount of objects of size has been read, we need to seek
 		stream->seek(oldpos + size * (count / size));
 	}
 
-    return count / size;
+	return count / size;
 }
 
-static std::size_t impl_write(SDL_RWops* context, const void *ptr, size_t size, size_t num)
+static std::size_t impl_write(SDL_RWops * context, const void * ptr, size_t size, size_t num)
 {
 	// writing is not supported
-    return 0;
+	return 0;
 }
 
-static int impl_close(SDL_RWops* context)
+static int impl_close(SDL_RWops * context)
 {
-	if (context == nullptr)
+	if(context == nullptr)
 		return 0;
 
-    delete get_stream(context);
-    SDL_FreeRW(context);
-    return 0;
+	delete get_stream(context);
+	SDL_FreeRW(context);
+	return 0;
 }
 
 
-SDL_RWops* MakeSDLRWops(std::unique_ptr<CInputStream> in)
+SDL_RWops * MakeSDLRWops(std::unique_ptr<CInputStream> in)
 {
-	SDL_RWops* result = SDL_AllocRW();
-	if (!result)
+	SDL_RWops * result = SDL_AllocRW();
+	if(!result)
 		return nullptr;
 
-	result->size  = &impl_size;
-	result->seek  = &impl_seek;
-	result->read  = &impl_read;
+	result->size = &impl_size;
+	result->seek = &impl_seek;
+	result->read = &impl_read;
 	result->write = &impl_write;
 	result->close = &impl_close;
 

+ 1 - 1
client/SDLRWwrapper.h

@@ -12,4 +12,4 @@
 struct SDL_RWops;
 class CInputStream;
 
-SDL_RWops* MakeSDLRWops(std::unique_ptr<CInputStream> in);
+SDL_RWops * MakeSDLRWops(std::unique_ptr<CInputStream> in);

+ 1 - 1
client/StdInc.cpp

@@ -1,2 +1,2 @@
 // Creates the precompiled header
-#include "StdInc.h"
+#include "StdInc.h"

+ 133 - 140
client/battle/CBattleAnimations.cpp

@@ -32,7 +32,7 @@
 #include "../../lib/spells/CSpellHandler.h"
 
 CBattleAnimation::CBattleAnimation(CBattleInterface * _owner)
-    : owner(_owner), ID(_owner->animIDhelper++)
+	: owner(_owner), ID(_owner->animIDhelper++)
 {
 	logAnim->traceStream() << "Animation #" << ID << " created";
 }
@@ -83,9 +83,7 @@ bool CBattleAnimation::isEarliest(bool perStackConcurrency)
 }
 
 CBattleStackAnimation::CBattleStackAnimation(CBattleInterface * owner, const CStack * stack)
-    : CBattleAnimation(owner),
-      myAnim(owner->creAnims[stack->ID]),
-      stack(stack)
+	: CBattleAnimation(owner), myAnim(owner->creAnims[stack->ID]), stack(stack)
 {
 	assert(myAnim);
 }
@@ -124,22 +122,19 @@ bool CAttackAnimation::checkInitialConditions()
 
 		if(revAnim && attackedStack) // enemy must be fully reversed
 		{
-			if (revAnim->stack->ID == attackedStack->ID)
+			if(revAnim->stack->ID == attackedStack->ID)
 				return false;
 		}
 	}
 	return isEarliest(false);
 }
 
-CAttackAnimation::CAttackAnimation(CBattleInterface *_owner, const CStack *attacker, BattleHex _dest, const CStack *defender)
-	: CBattleStackAnimation(_owner, attacker),
-		shooting(false), group(CCreatureAnim::SHOOT_FRONT),
-		soundPlayed(false),
-		dest(_dest), attackedStack(defender), attackingStack(attacker)
+CAttackAnimation::CAttackAnimation(CBattleInterface * _owner, const CStack * attacker, BattleHex _dest, const CStack * defender)
+	: CBattleStackAnimation(_owner, attacker), shooting(false), group(CCreatureAnim::SHOOT_FRONT), soundPlayed(false), dest(_dest), attackedStack(defender), attackingStack(attacker)
 {
 	assert(attackingStack && "attackingStack is nullptr in CBattleAttack::CBattleAttack !\n");
 	bool isCatapultAttack = attackingStack->hasBonusOfType(Bonus::CATAPULT)
-							&& owner->getCurrentPlayerInterface()->cb->battleHexToWallPart(_dest) >= 0;
+		&& owner->getCurrentPlayerInterface()->cb->battleHexToWallPart(_dest) >= 0;
 
 	assert(attackedStack || isCatapultAttack);
 	UNUSED(isCatapultAttack);
@@ -147,9 +142,7 @@ CAttackAnimation::CAttackAnimation(CBattleInterface *_owner, const CStack *attac
 }
 
 CDefenceAnimation::CDefenceAnimation(StackAttackedInfo _attackedInfo, CBattleInterface * _owner)
-: CBattleStackAnimation(_owner, _attackedInfo.defender),
-attacker(_attackedInfo.attacker), rangedAttack(_attackedInfo.indirectAttack),
-killed(_attackedInfo.killed), timeToWait(0)
+	: CBattleStackAnimation(_owner, _attackedInfo.defender), attacker(_attackedInfo.attacker), rangedAttack(_attackedInfo.indirectAttack), killed(_attackedInfo.killed), timeToWait(0)
 {
 	logAnim->debugStream() << "Created defence anim for " << _attackedInfo.defender->getName();
 }
@@ -172,7 +165,7 @@ bool CDefenceAnimation::init()
 			continue;
 
 		CSpellEffectAnimation * sen = dynamic_cast<CSpellEffectAnimation *>(elem.first);
-		if (sen)
+		if(sen)
 			continue;
 
 		CReverseAnimation * animAsRev = dynamic_cast<CReverseAnimation *>(elem.first);
@@ -189,7 +182,7 @@ bool CDefenceAnimation::init()
 
 
 	//reverse unit if necessary
-	if (attacker && owner->getCurrentPlayerInterface()->cb->isToReverse(stack->position, attacker->position, owner->creDir[stack->ID], attacker->doubleWide(), owner->creDir[attacker->ID]))
+	if(attacker && owner->getCurrentPlayerInterface()->cb->isToReverse(stack->position, attacker->position, owner->creDir[stack->ID], attacker->doubleWide(), owner->creDir[attacker->ID]))
 	{
 		owner->addNewAnim(new CReverseAnimation(owner, stack, stack->position, true));
 		return false;
@@ -209,10 +202,10 @@ bool CDefenceAnimation::init()
 
 	// synchronize animation with attacker, unless defending or attacked by shooter:
 	// wait for 1/2 of attack animation
-	if (!rangedAttack && getMyAnimType() != CCreatureAnim::DEFENCE)
+	if(!rangedAttack && getMyAnimType() != CCreatureAnim::DEFENCE)
 	{
 		float frameLength = AnimationControls::getCreatureAnimationSpeed(
-		                          stack->getCreature(), owner->creAnims[stack->ID], getMyAnimType());
+				stack->getCreature(), owner->creAnims[stack->ID], getMyAnimType());
 
 		timeToWait = myAnim->framesInGroup(getMyAnimType()) * frameLength / 2;
 
@@ -232,7 +225,7 @@ std::string CDefenceAnimation::getMySound()
 	if(killed)
 		return battle_sound(stack->getCreature(), killed);
 
-	if (vstd::contains(stack->state, EBattleStackState::DEFENDING_ANIM))
+	if(vstd::contains(stack->state, EBattleStackState::DEFENDING_ANIM))
 		return battle_sound(stack->getCreature(), defend);
 
 	return battle_sound(stack->getCreature(), wince);
@@ -243,7 +236,7 @@ CCreatureAnim::EAnimType CDefenceAnimation::getMyAnimType()
 	if(killed)
 		return CCreatureAnim::DEATH;
 
-	if (vstd::contains(stack->state, EBattleStackState::DEFENDING_ANIM))
+	if(vstd::contains(stack->state, EBattleStackState::DEFENDING_ANIM))
 		return CCreatureAnim::DEFENCE;
 
 	return CCreatureAnim::HITTED;
@@ -258,10 +251,10 @@ void CDefenceAnimation::startAnimation()
 
 void CDefenceAnimation::nextFrame()
 {
-	if (timeToWait > 0)
+	if(timeToWait > 0)
 	{
 		timeToWait -= float(GH.mainFPSmng->getElapsedMilliseconds()) / 1000;
-		if (timeToWait <= 0)
+		if(timeToWait <= 0)
 			startAnimation();
 	}
 
@@ -270,7 +263,7 @@ void CDefenceAnimation::nextFrame()
 
 void CDefenceAnimation::endAnim()
 {
-	if (killed)
+	if(killed)
 		myAnim->setType(CCreatureAnim::DEAD);
 	else
 		myAnim->setType(CCreatureAnim::HOLDING);
@@ -281,9 +274,9 @@ void CDefenceAnimation::endAnim()
 }
 
 CDummyAnimation::CDummyAnimation(CBattleInterface * _owner, int howManyFrames)
-: CBattleAnimation(_owner), counter(0), howMany(howManyFrames)
+	: CBattleAnimation(_owner), counter(0), howMany(howManyFrames)
 {
-	logAnim->debugStream() << "Created dummy animation for " << howManyFrames <<" frames";
+	logAnim->debugStream() << "Created dummy animation for " << howManyFrames << " frames";
 }
 
 bool CDummyAnimation::init()
@@ -307,7 +300,7 @@ void CDummyAnimation::endAnim()
 
 bool CMeleeAttackAnimation::init()
 {
-	if( !CAttackAnimation::checkInitialConditions() )
+	if(!CAttackAnimation::checkInitialConditions())
 		return false;
 
 	if(!attackingStack || myAnim->isDead())
@@ -319,23 +312,26 @@ bool CMeleeAttackAnimation::init()
 
 	bool toReverse = owner->getCurrentPlayerInterface()->cb->isToReverse(attackingStackPosBeforeReturn, attackedStack->position, owner->creDir[stack->ID], attackedStack->doubleWide(), owner->creDir[attackedStack->ID]);
 
-	if (toReverse)
+	if(toReverse)
 	{
 		owner->addNewAnim(new CReverseAnimation(owner, stack, attackingStackPosBeforeReturn, true));
 		return false;
 	}
 
 	// opponent must face attacker ( = different directions) before he can be attacked
-	if (attackingStack && attackedStack &&
-	    owner->creDir[attackingStack->ID] == owner->creDir[attackedStack->ID])
+	if(attackingStack && attackedStack &&
+	   owner->creDir[attackingStack->ID] == owner->creDir[attackedStack->ID])
 		return false;
 
 	//reversed
 
 	shooting = false;
 
-	static const CCreatureAnim::EAnimType mutPosToGroup[] = {CCreatureAnim::ATTACK_UP, CCreatureAnim::ATTACK_UP,
-		CCreatureAnim::ATTACK_FRONT, CCreatureAnim::ATTACK_DOWN, CCreatureAnim::ATTACK_DOWN, CCreatureAnim::ATTACK_FRONT};
+	static const CCreatureAnim::EAnimType mutPosToGroup[] =
+	{
+		CCreatureAnim::ATTACK_UP, CCreatureAnim::ATTACK_UP,
+		CCreatureAnim::ATTACK_FRONT, CCreatureAnim::ATTACK_DOWN, CCreatureAnim::ATTACK_DOWN, CCreatureAnim::ATTACK_FRONT
+	};
 
 	int revShiftattacker = (attackingStack->side == BattleSide::ATTACKER ? -1 : 1);
 
@@ -344,11 +340,11 @@ bool CMeleeAttackAnimation::init()
 	{
 		mutPos = BattleHex::mutualPosition(attackingStackPosBeforeReturn + revShiftattacker, attackedStack->position);
 	}
-	if (mutPos == -1 && attackedStack->doubleWide())
+	if(mutPos == -1 && attackedStack->doubleWide())
 	{
 		mutPos = BattleHex::mutualPosition(attackingStackPosBeforeReturn, attackedStack->occupiedHex());
 	}
-	if (mutPos == -1 && attackedStack->doubleWide() && attackingStack->doubleWide())
+	if(mutPos == -1 && attackedStack->doubleWide() && attackingStack->doubleWide())
 	{
 		mutPos = BattleHex::mutualPosition(attackingStackPosBeforeReturn + revShiftattacker, attackedStack->occupiedHex());
 	}
@@ -356,11 +352,16 @@ bool CMeleeAttackAnimation::init()
 
 	switch(mutPos) //attack direction
 	{
-	case 0: case 1: case 2: case 3: case 4: case 5:
+	case 0:
+	case 1:
+	case 2:
+	case 3:
+	case 4:
+	case 5:
 		group = mutPosToGroup[mutPos];
 		break;
 	default:
-		logGlobal->errorStream()<<"Critical Error! Wrong dest in stackAttacking! dest: "<<dest<<" attacking stack pos: "<<attackingStackPosBeforeReturn<<" mutual pos: "<<mutPos;
+		logGlobal->errorStream() << "Critical Error! Wrong dest in stackAttacking! dest: " << dest << " attacking stack pos: " << attackingStackPosBeforeReturn << " mutual pos: " << mutPos;
 		group = CCreatureAnim::ATTACK_FRONT;
 		break;
 	}
@@ -369,7 +370,7 @@ bool CMeleeAttackAnimation::init()
 }
 
 CMeleeAttackAnimation::CMeleeAttackAnimation(CBattleInterface * _owner, const CStack * attacker, BattleHex _dest, const CStack * _attacked)
-: CAttackAnimation(_owner, attacker, _dest, _attacked)
+	: CAttackAnimation(_owner, attacker, _dest, _attacked)
 {
 	logAnim->debugStream() << "Created melee attack anim for " << attacker->getName();
 }
@@ -389,7 +390,7 @@ bool CMovementAnimation::shouldRotate()
 	{
 		return true;
 	}
-	else if ((begPosition.x < endPosition.x) && owner->creDir[stack->ID] == false)
+	else if((begPosition.x < endPosition.x) && owner->creDir[stack->ID] == false)
 	{
 		return true;
 	}
@@ -398,7 +399,7 @@ bool CMovementAnimation::shouldRotate()
 
 bool CMovementAnimation::init()
 {
-	if( !isEarliest(false) )
+	if(!isEarliest(false))
 		return false;
 
 	if(!stack || myAnim->isDead())
@@ -420,7 +421,7 @@ bool CMovementAnimation::init()
 	{
 		// it seems that H3 does NOT plays full rotation animation here in most situations
 		// Logical since it takes quite a lot of time
-		if (curentMoveIndex == 0) // full rotation only for moving towards first tile.
+		if(curentMoveIndex == 0) // full rotation only for moving towards first tile.
 		{
 			owner->addNewAnim(new CReverseAnimation(owner, stack, oldPos, true));
 			return false;
@@ -436,7 +437,7 @@ bool CMovementAnimation::init()
 		myAnim->setType(CCreatureAnim::MOVING);
 	}
 
-	if (owner->moveSoundHander == -1)
+	if(owner->moveSoundHander == -1)
 	{
 		owner->moveSoundHander = CCS->soundh->playSound(battle_sound(stack->getCreature(), move), -1);
 	}
@@ -452,7 +453,7 @@ bool CMovementAnimation::init()
 	distanceX = endPosition.x - begPosition.x;
 	distanceY = endPosition.y - begPosition.y;
 
-	if (stack->hasBonus(Selector::type(Bonus::FLYING)))
+	if(stack->hasBonus(Selector::type(Bonus::FLYING)))
 	{
 		float distance = sqrt(distanceX * distanceX + distanceY * distanceY);
 
@@ -467,8 +468,8 @@ void CMovementAnimation::nextFrame()
 	progress += float(GH.mainFPSmng->getElapsedMilliseconds()) / 1000 * timeToMove;
 
 	//moving instructions
-	myAnim->pos.x = static_cast<Sint16>(begX + distanceX * progress );
-	myAnim->pos.y = static_cast<Sint16>(begY + distanceY * progress );
+	myAnim->pos.x = static_cast<Sint16>(begX + distanceX * progress);
+	myAnim->pos.y = static_cast<Sint16>(begY + distanceY * progress);
 
 	CBattleAnimation::nextFrame();
 
@@ -479,7 +480,7 @@ void CMovementAnimation::nextFrame()
 		myAnim->pos = coords;
 
 		// true if creature haven't reached the final destination hex
-		if ((curentMoveIndex + 1) < destTiles.size())
+		if((curentMoveIndex + 1) < destTiles.size())
 		{
 			// update the next hex field which has to be reached by the stack
 			curentMoveIndex++;
@@ -489,7 +490,7 @@ void CMovementAnimation::nextFrame()
 			// re-init animation
 			for(auto & elem : owner->pendingAnims)
 			{
-				if (elem.first == this)
+				if(elem.first == this)
 				{
 					elem.second = false;
 					break;
@@ -518,33 +519,25 @@ void CMovementAnimation::endAnim()
 	delete this;
 }
 
-CMovementAnimation::CMovementAnimation(CBattleInterface *_owner, const CStack *_stack, std::vector<BattleHex> _destTiles, int _distance)
-    : CBattleStackAnimation(_owner, _stack),
-      destTiles(_destTiles),
-      curentMoveIndex(0),
-      oldPos(stack->position),
-      begX(0), begY(0),
-      distanceX(0), distanceY(0),
-      timeToMove(0.0),
-      progress(0.0),
-      nextHex(destTiles.front())
+CMovementAnimation::CMovementAnimation(CBattleInterface * _owner, const CStack * _stack, std::vector<BattleHex> _destTiles, int _distance)
+	: CBattleStackAnimation(_owner, _stack), destTiles(_destTiles), curentMoveIndex(0), oldPos(stack->position), begX(0), begY(0), distanceX(0), distanceY(0), timeToMove(0.0), progress(0.0), nextHex(destTiles.front())
 {
 	logAnim->debugStream() << "Created movement anim for " << stack->getName();
 }
 
 CMovementEndAnimation::CMovementEndAnimation(CBattleInterface * _owner, const CStack * _stack, BattleHex destTile)
-: CBattleStackAnimation(_owner, _stack), destinationTile(destTile)
+	: CBattleStackAnimation(_owner, _stack), destinationTile(destTile)
 {
 	logAnim->debugStream() << "Created movement end anim for " << stack->getName();
 }
 
 bool CMovementEndAnimation::init()
 {
-	if( !isEarliest(true) )
+	if(!isEarliest(true))
 		return false;
 
 	if(!stack || myAnim->framesInGroup(CCreatureAnim::MOVE_END) == 0 ||
-		myAnim->isDead())
+	   myAnim->isDead())
 	{
 		endAnim();
 
@@ -572,14 +565,14 @@ void CMovementEndAnimation::endAnim()
 }
 
 CMovementStartAnimation::CMovementStartAnimation(CBattleInterface * _owner, const CStack * _stack)
-: CBattleStackAnimation(_owner, _stack)
+	: CBattleStackAnimation(_owner, _stack)
 {
 	logAnim->debugStream() << "Created movement start anim for " << stack->getName();
 }
 
 bool CMovementStartAnimation::init()
 {
-	if( !isEarliest(false) )
+	if(!isEarliest(false))
 		return false;
 
 
@@ -604,7 +597,7 @@ void CMovementStartAnimation::endAnim()
 }
 
 CReverseAnimation::CReverseAnimation(CBattleInterface * _owner, const CStack * stack, BattleHex dest, bool _priority)
-: CBattleStackAnimation(_owner, stack), hex(dest), priority(_priority)
+	: CBattleStackAnimation(_owner, stack), hex(dest), priority(_priority)
 {
 	logAnim->debugStream() << "Created reverse anim for " << stack->getName();
 }
@@ -635,7 +628,7 @@ bool CReverseAnimation::init()
 void CReverseAnimation::endAnim()
 {
 	CBattleAnimation::endAnim();
-	if( stack->alive() )//don't do that if stack is dead
+	if(stack->alive()) //don't do that if stack is dead
 		myAnim->setType(CCreatureAnim::HOLDING);
 
 	delete this;
@@ -668,14 +661,14 @@ void CReverseAnimation::setupSecondPart()
 }
 
 CShootingAnimation::CShootingAnimation(CBattleInterface * _owner, const CStack * attacker, BattleHex _dest, const CStack * _attacked, bool _catapult, int _catapultDmg)
-: CAttackAnimation(_owner, attacker, _dest, _attacked), catapultDamage(_catapultDmg)
+	: CAttackAnimation(_owner, attacker, _dest, _attacked), catapultDamage(_catapultDmg)
 {
 	logAnim->debugStream() << "Created shooting anim for " << stack->getName();
 }
 
 bool CShootingAnimation::init()
 {
-	if( !CAttackAnimation::checkInitialConditions() )
+	if(!CAttackAnimation::checkInitialConditions())
 		return false;
 
 	const CStack * shooter = attackingStack;
@@ -687,15 +680,15 @@ bool CShootingAnimation::init()
 	}
 
 	//reverse unit if necessary
-	if (attackingStack && attackedStack && owner->getCurrentPlayerInterface()->cb->isToReverse(attackingStack->position, attackedStack->position, owner->creDir[attackingStack->ID], attackingStack->doubleWide(), owner->creDir[attackedStack->ID]))
+	if(attackingStack && attackedStack && owner->getCurrentPlayerInterface()->cb->isToReverse(attackingStack->position, attackedStack->position, owner->creDir[attackingStack->ID], attackingStack->doubleWide(), owner->creDir[attackedStack->ID]))
 	{
 		owner->addNewAnim(new CReverseAnimation(owner, attackingStack, attackingStack->position, true));
 		return false;
 	}
 
 	// opponent must face attacker ( = different directions) before he can be attacked
-	if (attackingStack && attackedStack &&
-	    owner->creDir[attackingStack->ID] == owner->creDir[attackedStack->ID])
+	if(attackingStack && attackedStack &&
+	   owner->creDir[attackingStack->ID] == owner->creDir[attackedStack->ID])
 		return false;
 
 	// Create the projectile animation
@@ -706,8 +699,8 @@ bool CShootingAnimation::init()
 	// Get further info about the shooter e.g. relative pos of projectile to unit.
 	// If the creature id is 149 then it's a arrow tower which has no additional info so get the
 	// actual arrow tower shooter instead.
-	const CCreature *shooterInfo = shooter->getCreature();
-	if (shooterInfo->idNumber == CreatureID::ARROW_TOWERS)
+	const CCreature * shooterInfo = shooter->getCreature();
+	if(shooterInfo->idNumber == CreatureID::ARROW_TOWERS)
 	{
 		int creID = owner->siegeH->town->town->clientInfo.siegeShooter;
 		shooterInfo = CGI->creh->creatures[creID];
@@ -718,7 +711,7 @@ bool CShootingAnimation::init()
 	spi.creID = shooter->getCreature()->idNumber;
 	spi.stackID = shooter->ID;
 	// reverse if creature is facing right OR this is non-existing stack that is not tower (war machines)
-	spi.reverse = attackingStack ? !owner->creDir[attackingStack->ID] : shooter->getCreature()->idNumber != CreatureID::ARROW_TOWERS ;
+	spi.reverse = attackingStack ? !owner->creDir[attackingStack->ID] : shooter->getCreature()->idNumber != CreatureID::ARROW_TOWERS;
 
 	spi.step = 0;
 	spi.frameNum = 0;
@@ -740,22 +733,22 @@ bool CShootingAnimation::init()
 		projectileAngle = -projectileAngle;
 
 	// Calculate projectile start position. Offsets are read out of the CRANIM.TXT.
-	if (projectileAngle > straightAngle)
+	if(projectileAngle > straightAngle)
 	{
 		//upper shot
-		spi.x = fromPos.x + 222 + ( -25 + shooterInfo->animation.upperRightMissleOffsetX ) * multiplier;
+		spi.x = fromPos.x + 222 + (-25 + shooterInfo->animation.upperRightMissleOffsetX) * multiplier;
 		spi.y = fromPos.y + 265 + shooterInfo->animation.upperRightMissleOffsetY;
 	}
-	else if (projectileAngle < -straightAngle)
+	else if(projectileAngle < -straightAngle)
 	{
 		//lower shot
-		spi.x = fromPos.x + 222 + ( -25 + shooterInfo->animation.lowerRightMissleOffsetX ) * multiplier;
+		spi.x = fromPos.x + 222 + (-25 + shooterInfo->animation.lowerRightMissleOffsetX) * multiplier;
 		spi.y = fromPos.y + 265 + shooterInfo->animation.lowerRightMissleOffsetY;
 	}
 	else
 	{
 		//straight shot
-		spi.x = fromPos.x + 222 + ( -25 + shooterInfo->animation.rightMissleOffsetX ) * multiplier;
+		spi.x = fromPos.x + 222 + (-25 + shooterInfo->animation.rightMissleOffsetX) * multiplier;
 		spi.y = fromPos.y + 265 + shooterInfo->animation.rightMissleOffsetY;
 	}
 
@@ -766,7 +759,7 @@ bool CShootingAnimation::init()
 	//if(shooter->position < dest)
 	//	projectileAngle = -projectileAngle;
 
-	if (attackedStack)
+	if(attackedStack)
 	{
 		double animSpeed = AnimationControls::getProjectileSpeed(); // flight speed of projectile
 		spi.lastStep = static_cast<int>(sqrt(static_cast<double>((destPos.x - spi.x) * (destPos.x - spi.x) + (destPos.y - spi.y) * (destPos.y - spi.y))) / animSpeed);
@@ -789,15 +782,15 @@ bool CShootingAnimation::init()
 
 		// Add explosion anim
 		Point animPos(destPos.x - 126 + img->w / 2,
-		              destPos.y - 105 + img->h / 2);
+			      destPos.y - 105 + img->h / 2);
 
-		owner->addNewAnim( new CSpellEffectAnimation(owner, catapultDamage ? "SGEXPL.DEF" : "CSGRCK.DEF", animPos.x, animPos.y));
+		owner->addNewAnim(new CSpellEffectAnimation(owner, catapultDamage ? "SGEXPL.DEF" : "CSGRCK.DEF", animPos.x, animPos.y));
 	}
 
 	auto & angles = shooterInfo->animation.missleFrameAngles;
 	double pi = boost::math::constants::pi<double>();
 
-	if (owner->idToProjectile.count(spi.creID) == 0) //in some cases (known one: hero grants shooter bonus to unit) the shooter stack's projectile may not be properly initialized
+	if(owner->idToProjectile.count(spi.creID) == 0) //in some cases (known one: hero grants shooter bonus to unit) the shooter stack's projectile may not be properly initialized
 		owner->initStackProjectile(shooter);
 
 	// only frames below maxFrame are usable: anything  higher is either no present or we don't know when it should be used
@@ -808,12 +801,12 @@ bool CShootingAnimation::init()
 	// values in angles array indicate position from which this frame was rendered, in degrees.
 	// find frame that has closest angle to one that we need for this shot
 	size_t bestID = 0;
-	double bestDiff = fabs( angles[0] / 180 * pi - projectileAngle );
+	double bestDiff = fabs(angles[0] / 180 * pi - projectileAngle);
 
-	for (size_t i=1; i<maxFrame; i++)
+	for(size_t i = 1; i < maxFrame; i++)
 	{
-		double currentDiff = fabs( angles[i] / 180 * pi - projectileAngle );
-		if (currentDiff < bestDiff)
+		double currentDiff = fabs(angles[i] / 180 * pi - projectileAngle);
+		if(currentDiff < bestDiff)
 		{
 			bestID = i;
 			bestDiff = currentDiff;
@@ -846,7 +839,7 @@ void CShootingAnimation::nextFrame()
 	{
 		CMovementStartAnimation * anim = dynamic_cast<CMovementStartAnimation *>(it.first);
 		CReverseAnimation * anim2 = dynamic_cast<CReverseAnimation *>(it.first);
-		if( (anim && anim->stack->ID == stack->ID) || (anim2 && anim2->stack->ID == stack->ID && anim2->priority ) )
+		if((anim && anim->stack->ID == stack->ID) || (anim2 && anim2->stack->ID == stack->ID && anim2->priority))
 			return;
 	}
 
@@ -855,37 +848,37 @@ void CShootingAnimation::nextFrame()
 
 void CShootingAnimation::endAnim()
 {
-    // play wall hit/miss sound for catapult attack
-    if(!attackedStack)
-    {
-        if(catapultDamage > 0)
-        {
-            CCS->soundh->playSound("WALLHIT");
-        }
-        else
-        {
-            CCS->soundh->playSound("WALLMISS");
-        }
-    }
+	// play wall hit/miss sound for catapult attack
+	if(!attackedStack)
+	{
+		if(catapultDamage > 0)
+		{
+			CCS->soundh->playSound("WALLHIT");
+		}
+		else
+		{
+			CCS->soundh->playSound("WALLMISS");
+		}
+	}
 
 	CAttackAnimation::endAnim();
 	delete this;
 }
 
 CSpellEffectAnimation::CSpellEffectAnimation(CBattleInterface * _owner, ui32 _effect, BattleHex _destTile, int _dx, int _dy, bool _Vflip, bool _alignToBottom)
-	:CBattleAnimation(_owner), effect(_effect), destTile(_destTile), customAnim(""), x(-1), y(-1), dx(_dx), dy(_dy), Vflip(_Vflip), alignToBottom(_alignToBottom)
+	: CBattleAnimation(_owner), effect(_effect), destTile(_destTile), customAnim(""), x(-1), y(-1), dx(_dx), dy(_dy), Vflip(_Vflip), alignToBottom(_alignToBottom)
 {
 	logAnim->debugStream() << "Created spell anim for effect #" << effect;
 }
 
 CSpellEffectAnimation::CSpellEffectAnimation(CBattleInterface * _owner, std::string _customAnim, int _x, int _y, int _dx, int _dy, bool _Vflip, bool _alignToBottom)
-	:CBattleAnimation(_owner), effect(-1), destTile(BattleHex::INVALID), customAnim(_customAnim), x(_x), y(_y), dx(_dx), dy(_dy), Vflip(_Vflip), alignToBottom(_alignToBottom)
+	: CBattleAnimation(_owner), effect(-1), destTile(BattleHex::INVALID), customAnim(_customAnim), x(_x), y(_y), dx(_dx), dy(_dy), Vflip(_Vflip), alignToBottom(_alignToBottom)
 {
 	logAnim->debugStream() << "Created spell anim for " << customAnim;
 }
 
 CSpellEffectAnimation::CSpellEffectAnimation(CBattleInterface * _owner, std::string _customAnim, BattleHex _destTile, bool _Vflip, bool _alignToBottom)
-	:CBattleAnimation(_owner), effect(-1), destTile(_destTile), customAnim(_customAnim), x(-1), y(-1), dx(0), dy(0), Vflip(_Vflip), alignToBottom(_alignToBottom)
+	: CBattleAnimation(_owner), effect(-1), destTile(_destTile), customAnim(_customAnim), x(-1), y(-1), dx(0), dy(0), Vflip(_Vflip), alignToBottom(_alignToBottom)
 {
 	logAnim->debugStream() << "Created spell anim for " << customAnim;
 }
@@ -913,16 +906,16 @@ bool CSpellEffectAnimation::init()
 	{
 		CDefHandler * anim = CDefHandler::giveDef(customAnim);
 
-		for(int i=0; i * anim->width < owner->pos.w ; ++i)
+		for(int i = 0; i * anim->width < owner->pos.w; ++i)
 		{
-			for(int j=0; j * anim->height < owner->pos.h ; ++j)
+			for(int j = 0; j * anim->height < owner->pos.h; ++j)
 			{
 				BattleEffect be;
 				be.effectID = ID;
 				be.anim = CDefHandler::giveDef(customAnim);
-				if (Vflip)
+				if(Vflip)
 				{
-					for (auto & elem : be.anim->ourImages)
+					for(auto & elem : be.anim->ourImages)
 					{
 						CSDL_Ext::VflipSurf(elem.bitmap);
 					}
@@ -942,57 +935,57 @@ bool CSpellEffectAnimation::init()
 	else // Effects targeted at a specific creature/hex.
 	{
 
-			const CStack* destStack = owner->getCurrentPlayerInterface()->cb->battleGetStackByPos(destTile, false);
-			Rect & tilePos = owner->bfield[destTile]->pos;
-			BattleEffect be;
-			be.effectID = ID;
-			be.anim = CDefHandler::giveDef(customAnim);
+		const CStack * destStack = owner->getCurrentPlayerInterface()->cb->battleGetStackByPos(destTile, false);
+		Rect & tilePos = owner->bfield[destTile]->pos;
+		BattleEffect be;
+		be.effectID = ID;
+		be.anim = CDefHandler::giveDef(customAnim);
 
-			if (Vflip)
+		if(Vflip)
+		{
+			for(auto & elem : be.anim->ourImages)
 			{
-				for (auto & elem : be.anim->ourImages)
-				{
-					CSDL_Ext::VflipSurf(elem.bitmap);
-				}
+				CSDL_Ext::VflipSurf(elem.bitmap);
 			}
+		}
 
-			be.currentFrame = 0;
-			be.maxFrame = be.anim->ourImages.size();
+		be.currentFrame = 0;
+		be.maxFrame = be.anim->ourImages.size();
 
-			//todo: lightning anim frame count override
+		//todo: lightning anim frame count override
 
 //			if(effect == 1)
 //				be.maxFrame = 3;
 
-			if(x == -1)
-			{
-				be.x = tilePos.x + tilePos.w/2 - be.anim->width/2;
-			}
-			else
-			{
-				be.x = x;
-			}
+		if(x == -1)
+		{
+			be.x = tilePos.x + tilePos.w / 2 - be.anim->width / 2;
+		}
+		else
+		{
+			be.x = x;
+		}
 
-			if(y == -1)
-			{
-				if(alignToBottom)
-					be.y = tilePos.y + tilePos.h - be.anim->height;
-				else
-					be.y = tilePos.y - be.anim->height/2;
-			}
+		if(y == -1)
+		{
+			if(alignToBottom)
+				be.y = tilePos.y + tilePos.h - be.anim->height;
 			else
-			{
-				be.y = y;
-			}
+				be.y = tilePos.y - be.anim->height / 2;
+		}
+		else
+		{
+			be.y = y;
+		}
 
-			// Correction for 2-hex creatures.
-			if (destStack != nullptr && destStack->doubleWide())
-				be.x += (destStack->side == BattleSide::ATTACKER ? -1 : 1)*tilePos.w/2;
+		// Correction for 2-hex creatures.
+		if(destStack != nullptr && destStack->doubleWide())
+			be.x += (destStack->side == BattleSide::ATTACKER ? -1 : 1) * tilePos.w / 2;
 
-			//Indicate if effect should be drawn on top of everything or just on top of the hex
-			be.position = destTile;
+		//Indicate if effect should be drawn on top of everything or just on top of the hex
+		be.position = destTile;
 
-			owner->battleEffects.push_back(be);
+		owner->battleEffects.push_back(be);
 
 	}
 	//battleEffects

+ 15 - 8
client/battle/CBattleAnimations.h

@@ -23,6 +23,7 @@ class CBattleAnimation
 {
 protected:
 	CBattleInterface * owner;
+
 public:
 	virtual bool init() = 0; //to be called - if returned false, call again until returns true
 	virtual void nextFrame() {} //call every new frame
@@ -54,15 +55,16 @@ protected:
 	BattleHex dest; //attacked hex
 	bool shooting;
 	CCreatureAnim::EAnimType group; //if shooting is true, print this animation group
-	const CStack *attackedStack;
-	const CStack *attackingStack;
+	const CStack * attackedStack;
+	const CStack * attackingStack;
 	int attackingStackPosBeforeReturn; //for stacks with return_after_strike feature
+
 public:
 	void nextFrame() override;
 	void endAnim() override;
 	bool checkInitialConditions();
 
-	CAttackAnimation(CBattleInterface *_owner, const CStack *attacker, BattleHex _dest, const CStack *defender);
+	CAttackAnimation(CBattleInterface * _owner, const CStack * attacker, BattleHex _dest, const CStack * defender);
 };
 
 /// Animation of a defending unit
@@ -78,6 +80,7 @@ class CDefenceAnimation : public CBattleStackAnimation
 	bool killed; //if true, stack has been killed
 
 	float timeToWait; // for how long this animation should be paused
+
 public:
 	bool init() override;
 	void nextFrame() override;
@@ -92,6 +95,7 @@ class CDummyAnimation : public CBattleAnimation
 private:
 	int counter;
 	int howMany;
+
 public:
 	bool init() override;
 	void nextFrame() override;
@@ -136,7 +140,7 @@ public:
 	void nextFrame() override;
 	void endAnim() override;
 
-	CMovementAnimation(CBattleInterface *_owner, const CStack *_stack, std::vector<BattleHex> _destTiles, int _distance);
+	CMovementAnimation(CBattleInterface * _owner, const CStack * _stack, std::vector<BattleHex> _destTiles, int _distance);
 	virtual ~CMovementAnimation(){};
 };
 
@@ -145,6 +149,7 @@ class CMovementEndAnimation : public CBattleStackAnimation
 {
 private:
 	BattleHex destinationTile;
+
 public:
 	bool init() override;
 	void endAnim() override;
@@ -168,6 +173,7 @@ public:
 class CReverseAnimation : public CBattleStackAnimation
 {
 	BattleHex hex;
+
 public:
 	bool priority; //true - high, false - low
 	bool init() override;
@@ -202,14 +208,14 @@ class CShootingAnimation : public CAttackAnimation
 {
 private:
 	int catapultDamage;
+
 public:
 	bool init() override;
 	void nextFrame() override;
 	void endAnim() override;
 
 	//last two params only for catapult attacks
-	CShootingAnimation(CBattleInterface * _owner, const CStack * attacker, BattleHex _dest, 
-		const CStack * _attacked, bool _catapult = false, int _catapultDmg = 0); 
+	CShootingAnimation(CBattleInterface * _owner, const CStack * attacker, BattleHex _dest, const CStack * _attacked, bool _catapult = false, int _catapultDmg = 0);
 	virtual ~CShootingAnimation(){};
 };
 
@@ -219,10 +225,11 @@ class CSpellEffectAnimation : public CBattleAnimation
 private:
 	ui32 effect;
 	BattleHex destTile;
-	std::string	customAnim;
-	int	x, y, dx, dy;
+	std::string customAnim;
+	int x, y, dx, dy;
 	bool Vflip;
 	bool alignToBottom;
+
 public:
 	bool init() override;
 	void nextFrame() override;

File diff suppressed because it is too large
+ 219 - 227
client/battle/CBattleInterface.cpp


+ 102 - 84
client/battle/CBattleInterface.h

@@ -28,7 +28,7 @@ class CToggleGroup;
 struct BattleResult;
 struct BattleSpellCast;
 struct CObstacleInstance;
-template <typename T> struct CondSh;
+template<typename T> struct CondSh;
 struct SetStackEffect;
 struct BattleAction;
 class CGTownInstance;
@@ -52,10 +52,10 @@ class CBattleGameInterface;
 /// Small struct which contains information about the id of the attacked stack, the damage dealt,...
 struct StackAttackedInfo
 {
-	const CStack *defender; //attacked stack
+	const CStack * defender; //attacked stack
 	int32_t dmg; //damage dealt
 	unsigned int amountKilled; //how many creatures in stack has been killed
-	const CStack *attacker; //attacking stack
+	const CStack * attacker; //attacking stack
 	bool indirectAttack; //if true, stack was attacked indirectly - spell or ranged attack
 	bool killed; //if true, stack has been killed
 	bool rebirth; //if true, play rebirth animation after all
@@ -68,7 +68,7 @@ struct BattleEffect
 	int x, y; //position on the screen
 	float currentFrame;
 	int maxFrame;
-	CDefHandler *anim; //animation to display
+	CDefHandler * anim; //animation to display
 	int effectID; //uniqueID equal ot ID of appropriate CSpellEffectAnim
 	BattleHex position; //Indicates if effect which hex the effect is drawn on
 };
@@ -110,23 +110,39 @@ class CBattleInterface : public CIntObject
 {
 	enum PossibleActions // actions performed at l-click
 	{
-		INVALID = -1, CREATURE_INFO,
-		MOVE_TACTICS, CHOOSE_TACTICS_STACK,
-		MOVE_STACK, ATTACK, WALK_AND_ATTACK, ATTACK_AND_RETURN, SHOOT, //OPEN_GATE, //we can open castle gate during siege
-		NO_LOCATION, ANY_LOCATION, OBSTACLE, TELEPORT, SACRIFICE, RANDOM_GENIE_SPELL,
-		FREE_LOCATION, //used with Force Field and Fire Wall - all tiles affected by spell must be free
-		CATAPULT, HEAL, RISE_DEMONS,
+		INVALID = -1,
+		CREATURE_INFO,
+		MOVE_TACTICS,
+		CHOOSE_TACTICS_STACK,
+		MOVE_STACK,
+		ATTACK,
+		WALK_AND_ATTACK,
+		ATTACK_AND_RETURN,
+		SHOOT,
+		//OPEN_GATE, //we can open castle gate during siege
+		NO_LOCATION,
+		ANY_LOCATION,
+		OBSTACLE,
+		TELEPORT,
+		SACRIFICE,
+		RANDOM_GENIE_SPELL,
+		FREE_LOCATION,
+		//used with Force Field and Fire Wall - all tiles affected by spell must be free
+		CATAPULT,
+		HEAL,
+		RISE_DEMONS,
 		AIMED_SPELL_CREATURE
 	};
+
 private:
-	SDL_Surface *background, *menu, *amountNormal, *amountNegative, *amountPositive, *amountEffNeutral, *cellBorders, *backgroundWithHexes;
-	CButton *bOptions, *bSurrender, *bFlee, *bAutofight, *bSpell,
-		* bWait, *bDefence, *bConsoleUp, *bConsoleDown, *btactNext, *btactEnd;
-	CBattleConsole *console;
-	CBattleHero *attackingHero, *defendingHero; //fighting heroes
-	CStackQueue *queue;
-	const CCreatureSet *army1, *army2; //copy of initial armies (for result window)
-	const CGHeroInstance *attackingHeroInstance, *defendingHeroInstance;
+	SDL_Surface * background, * menu, * amountNormal, * amountNegative, * amountPositive, * amountEffNeutral, * cellBorders, * backgroundWithHexes;
+	CButton * bOptions, * bSurrender, * bFlee, * bAutofight, * bSpell,
+		* bWait, * bDefence, * bConsoleUp, * bConsoleDown, * btactNext, * btactEnd;
+	CBattleConsole * console;
+	CBattleHero * attackingHero, * defendingHero; //fighting heroes
+	CStackQueue * queue;
+	const CCreatureSet * army1, * army2; //copy of initial armies (for result window)
+	const CGHeroInstance * attackingHeroInstance, * defendingHeroInstance;
 	std::map<int, CCreatureAnimation *> creAnims; //animations of creatures from fighting armies (order by BattleInfo's stacks' ID)
 	std::map<int, CDefHandler *> idToProjectile; //projectiles of creatures (creatureID, defhandler)
 	std::map<int, CDefHandler *> idToObstacle; //obstacles located on the battlefield
@@ -134,20 +150,20 @@ private:
 
 	//TODO these should be loaded only when needed (and freed then) but I believe it's rather work for resource manager,
 	//so I didn't implement that (having ongoing RM development)
-	CDefHandler *landMine;
-	CDefHandler *quicksand;
-	CDefHandler *fireWall;
-	CDefHandler *smallForceField[2], *bigForceField[2]; // [side]
+	CDefHandler * landMine;
+	CDefHandler * quicksand;
+	CDefHandler * fireWall;
+	CDefHandler * smallForceField[2], * bigForceField[2]; // [side]
 
 	std::map<int, bool> creDir; // <creatureID, if false reverse creature's animation> //TODO: move it to battle callback
 	ui8 animCount;
-	const CStack *activeStack; //number of active stack; nullptr - no one
-	const CStack *mouseHoveredStack; // stack below mouse pointer, used for border animation
-	const CStack *stackToActivate; //when animation is playing, we should wait till the end to make the next stack active; nullptr of none
-	const CStack *selectedStack; //for Teleport / Sacrifice
+	const CStack * activeStack; //number of active stack; nullptr - no one
+	const CStack * mouseHoveredStack; // stack below mouse pointer, used for border animation
+	const CStack * stackToActivate; //when animation is playing, we should wait till the end to make the next stack active; nullptr of none
+	const CStack * selectedStack; //for Teleport / Sacrifice
 	void activateStack(); //sets activeStack to stackToActivate etc. //FIXME: No, it's not clear at all
 	std::vector<BattleHex> occupyableHexes, //hexes available for active stack
-		attackableHexes; //hexes attackable by active stack
+			       attackableHexes; //hexes attackable by active stack
 	bool stackCountOutsideHexes[GameConstants::BFIELD_SIZE]; // hexes that when in front of a unit cause it's amount box to move back
 	BattleHex previouslyHoveredHex; //number of hex that was hovered by the cursor a while ago
 	BattleHex currentlyHoveredHex; //number of hex that is supposed to be hovered (for a while it may be inappropriately set, but will be renewed soon)
@@ -158,8 +174,8 @@ private:
 	bool stackCanCastSpell; //if true, active stack could possibly cast some target spell
 	bool creatureCasting; //if true, stack currently aims to cats a spell
 	bool spellDestSelectMode; //if true, player is choosing destination for his spell - only for GUI / console
-	BattleAction *spellToCast; //spell for which player is choosing destination
-	const CSpell *sp; //spell pointer for convenience
+	BattleAction * spellToCast; //spell for which player is choosing destination
+	const CSpell * sp; //spell pointer for convenience
 	si32 creatureSpellToCast;
 	std::vector<PossibleActions> possibleActions; //all actions possible to call at the moment by player
 	std::vector<PossibleActions> localActions; //actions possible to take on hovered hex
@@ -168,21 +184,21 @@ private:
 	PossibleActions selectedAction; //last action chosen (and saved) by player
 	PossibleActions illegalAction; //most likely action that can't be performed here
 
-	void setActiveStack(const CStack *stack);
-	void setHoveredStack(const CStack *stack);
+	void setActiveStack(const CStack * stack);
+	void setHoveredStack(const CStack * stack);
 
 	void requestAutofightingAIToTakeAction();
 
-	void getPossibleActionsForStack (const CStack *stack, const bool forceCast); //called when stack gets its turn
+	void getPossibleActionsForStack(const CStack * stack, const bool forceCast); //called when stack gets its turn
 	void endCastingSpell(); //ends casting spell (eg. when spell has been cast or canceled)
 
 	//force active stack to cast a spell if possible
 	void enterCreatureCastingMode();
 
-	void printConsoleAttacked(const CStack *defender, int dmg, int killed, const CStack *attacker, bool Multiple);
+	void printConsoleAttacked(const CStack * defender, int dmg, int killed, const CStack * attacker, bool Multiple);
 
 	std::list<ProjectileInfo> projectiles; //projectiles flying on battlefield
-	void giveCommand(Battle::ActionType action, BattleHex tile, ui32 stackID, si32 additional=-1, si32 selectedStack = -1);
+	void giveCommand(Battle::ActionType action, BattleHex tile, ui32 stackID, si32 additional = -1, si32 selectedStack = -1);
 	bool isTileAttackable(const BattleHex & number) const; //returns true if tile 'number' is neighboring any tile from active stack's range or is one of these tiles
 	bool isCatapultAttackable(BattleHex hex) const; //returns true if given tile can be attacked by catapult
 
@@ -191,19 +207,20 @@ private:
 	/// Class which is responsible for drawing the wall of a siege during battle
 	class SiegeHelper
 	{
-	private:
-		SDL_Surface* walls[18];
-		const CBattleInterface *owner;
-	public:
-		const CGTownInstance *town; //besieged town
+private:
+		SDL_Surface * walls[18];
+		const CBattleInterface * owner;
 
-		SiegeHelper(const CGTownInstance *siegeTown, const CBattleInterface *_owner);
+public:
+		const CGTownInstance * town; //besieged town
+
+		SiegeHelper(const CGTownInstance * siegeTown, const CBattleInterface * _owner);
 		~SiegeHelper();
 
 		std::string getSiegeName(ui16 what) const;
 		std::string getSiegeName(ui16 what, int state) const; // state uses EWallState enum
 
-		void printPartOfWall(SDL_Surface *to, int what);
+		void printPartOfWall(SDL_Surface * to, int what);
 
 		enum EWallVisual
 		{
@@ -228,50 +245,51 @@ private:
 		};
 
 		friend class CBattleInterface;
-	} *siegeH;
+	} * siegeH;
 
 	std::shared_ptr<CPlayerInterface> attackerInt, defenderInt; //because LOCPLINT is not enough in hotSeat
 	std::shared_ptr<CPlayerInterface> curInt; //current player interface
-	const CGHeroInstance *getActiveHero(); //returns hero that can currently cast a spell
+	const CGHeroInstance * getActiveHero(); //returns hero that can currently cast a spell
 
 	/** Methods for displaying battle screen */
-	void showBackground(SDL_Surface *to);
+	void showBackground(SDL_Surface * to);
 
-	void showBackgroundImage(SDL_Surface *to);
-	void showAbsoluteObstacles(SDL_Surface *to);
-	void showHighlightedHexes(SDL_Surface *to);
-	void showHighlightedHex(SDL_Surface *to, BattleHex hex, bool darkBorder = false);
-	void showInterface(SDL_Surface *to);
+	void showBackgroundImage(SDL_Surface * to);
+	void showAbsoluteObstacles(SDL_Surface * to);
+	void showHighlightedHexes(SDL_Surface * to);
+	void showHighlightedHex(SDL_Surface * to, BattleHex hex, bool darkBorder = false);
+	void showInterface(SDL_Surface * to);
 
-	void showBattlefieldObjects(SDL_Surface *to);
+	void showBattlefieldObjects(SDL_Surface * to);
 
-	void showAliveStacks(SDL_Surface *to, std::vector<const CStack *> stacks);
-	void showStacks(SDL_Surface *to, std::vector<const CStack *> stacks);
-	void showObstacles(SDL_Surface *to, std::vector<std::shared_ptr<const CObstacleInstance>> &obstacles);
-	void showPiecesOfWall(SDL_Surface *to, std::vector<int> pieces);
+	void showAliveStacks(SDL_Surface * to, std::vector<const CStack *> stacks);
+	void showStacks(SDL_Surface * to, std::vector<const CStack *> stacks);
+	void showObstacles(SDL_Surface * to, std::vector<std::shared_ptr<const CObstacleInstance>> & obstacles);
+	void showPiecesOfWall(SDL_Surface * to, std::vector<int> pieces);
 
-	void showBattleEffects(SDL_Surface *to, const std::vector<const BattleEffect *> &battleEffects);
-	void showProjectiles(SDL_Surface *to);
+	void showBattleEffects(SDL_Surface * to, const std::vector<const BattleEffect *> & battleEffects);
+	void showProjectiles(SDL_Surface * to);
 
 	BattleObjectsByHex sortObjectsByHex();
 	void updateBattleAnimations();
 
-	SDL_Surface *getObstacleImage(const CObstacleInstance &oi);
-	Point getObstaclePosition(SDL_Surface *image, const CObstacleInstance &obstacle);
-	void redrawBackgroundWithHexes(const CStack *activeStack);
+	SDL_Surface * getObstacleImage(const CObstacleInstance & oi);
+	Point getObstaclePosition(SDL_Surface * image, const CObstacleInstance & obstacle);
+	void redrawBackgroundWithHexes(const CStack * activeStack);
 	/** End of battle screen blitting methods */
 
-	PossibleActions getCasterAction(const CSpell *spell, const ISpellCaster *caster, ECastingMode::ECastingMode mode) const;
+	PossibleActions getCasterAction(const CSpell * spell, const ISpellCaster * caster, ECastingMode::ECastingMode mode) const;
+
 public:
 	static CondSh<bool> animsAreDisplayed; //for waiting with the end of battle for end of anims
 	static CondSh<BattleAction *> givenCommand; //data != nullptr if we have i.e. moved current unit
 
 	std::list<std::pair<CBattleAnimation *, bool>> pendingAnims; //currently displayed animations <anim, initialized>
-	void addNewAnim(CBattleAnimation *anim); //adds new anim to pendingAnims
+	void addNewAnim(CBattleAnimation * anim); //adds new anim to pendingAnims
 	ui32 animIDhelper; //for giving IDs for animations
 
 
-	CBattleInterface(const CCreatureSet *army1, const CCreatureSet *army2, const CGHeroInstance *hero1, const CGHeroInstance *hero2, const SDL_Rect & myRect, std::shared_ptr<CPlayerInterface> att, std::shared_ptr<CPlayerInterface> defen, std::shared_ptr<CPlayerInterface> spectatorInt = nullptr);
+	CBattleInterface(const CCreatureSet * army1, const CCreatureSet * army2, const CGHeroInstance * hero1, const CGHeroInstance * hero2, const SDL_Rect & myRect, std::shared_ptr<CPlayerInterface> att, std::shared_ptr<CPlayerInterface> defen, std::shared_ptr<CPlayerInterface> spectatorInt = nullptr);
 	virtual ~CBattleInterface();
 
 	//std::vector<TimeInterested*> timeinterested; //animation handling
@@ -280,18 +298,18 @@ public:
 	void setPrintMouseShadow(bool set); //if true, hex under mouse will be shaded
 	void setAnimSpeed(int set); //speed of animation; range 1..100
 	int getAnimSpeed() const; //speed of animation; range 1..100
-	CPlayerInterface *getCurrentPlayerInterface() const;
+	CPlayerInterface * getCurrentPlayerInterface() const;
 
-	std::vector<CClickableHex*> bfield; //11 lines, 17 hexes on each
-	SDL_Surface *cellBorder, *cellShade;
+	std::vector<CClickableHex *> bfield; //11 lines, 17 hexes on each
+	SDL_Surface * cellBorder, * cellShade;
 
 	bool myTurn; //if true, interface is active (commands can be ordered)
-	CBattleResultWindow *resWindow; //window of end of battle
+	CBattleResultWindow * resWindow; //window of end of battle
 
 	bool moveStarted; //if true, the creature that is already moving is going to make its first step
 	int moveSoundHander; // sound handler used when moving a unit
 
-	const BattleResult *bresult; //result of a battle; if non-zero then display when all animations end
+	const BattleResult * bresult; //result of a battle; if non-zero then display when all animations end
 
 	// block all UI elements, e.g. during enemy turn
 	// unlike activate/deactivate this method will correctly grey-out all elements
@@ -309,35 +327,35 @@ public:
 	void bDefencef();
 	void bConsoleUpf();
 	void bConsoleDownf();
-	void bTacticNextStack(const CStack *current = nullptr);
+	void bTacticNextStack(const CStack * current = nullptr);
 	void bEndTacticPhase();
 	//end of button handle funcs
 	//napisz tu klase odpowiadajaca za wyswietlanie bitwy i obsluge uzytkownika, polecenia ma przekazywac callbackiem
 	void activate() override;
 	void deactivate() override;
 	void keyPressed(const SDL_KeyboardEvent & key) override;
-	void mouseMoved(const SDL_MouseMotionEvent &sEvent) override;
+	void mouseMoved(const SDL_MouseMotionEvent & sEvent) override;
 	void clickRight(tribool down, bool previousState) override;
 
-	void show(SDL_Surface *to) override;
-	void showAll(SDL_Surface *to) override;
+	void show(SDL_Surface * to) override;
+	void showAll(SDL_Surface * to) override;
 
 	//call-ins
-	void startAction(const BattleAction* action);
-	void newStack(const CStack *stack); //new stack appeared on battlefield
+	void startAction(const BattleAction * action);
+	void newStack(const CStack * stack); //new stack appeared on battlefield
 	void stackRemoved(int stackID); //stack disappeared from batlefiled
-	void stackActivated(const CStack *stack); //active stack has been changed
-	void stackMoved(const CStack *stack, std::vector<BattleHex> destHex, int distance); //stack with id number moved to destHex
+	void stackActivated(const CStack * stack); //active stack has been changed
+	void stackMoved(const CStack * stack, std::vector<BattleHex> destHex, int distance); //stack with id number moved to destHex
 	void waitForAnims();
 	void stacksAreAttacked(std::vector<StackAttackedInfo> attackedInfos); //called when a certain amount of stacks has been attacked
-	void stackAttacking(const CStack *attacker, BattleHex dest, const CStack *attacked, bool shooting); //called when stack with id ID is attacking something on hex dest
-	void newRoundFirst( int round );
+	void stackAttacking(const CStack * attacker, BattleHex dest, const CStack * attacked, bool shooting); //called when stack with id ID is attacking something on hex dest
+	void newRoundFirst(int round);
 	void newRound(int number); //caled when round is ended; number is the number of round
 	void hexLclicked(int whichOne); //hex only call-in
 	void stackIsCatapulting(const CatapultAttack & ca); //called when a stack is attacking walls
-	void battleFinished(const BattleResult& br); //called when battle is finished - battleresult window should be printed
+	void battleFinished(const BattleResult & br); //called when battle is finished - battleresult window should be printed
 	void displayBattleFinished(); //displays battle result
-	void spellCast(const BattleSpellCast *sc); //called when a hero casts a spell
+	void spellCast(const BattleSpellCast * sc); //called when a hero casts a spell
 	void battleStacksEffectsSet(const SetStackEffect & sse); //called when a specific effect is set to stacks
 	void castThisSpell(SpellID spellID); //called when player has chosen a spell from spellbook
 	void displayEffect(ui32 effect, int destTile); //displays custom effect on the battlefield
@@ -350,24 +368,24 @@ public:
 
 	void battleTriggerEffect(const BattleTriggerEffect & bte);
 	void setBattleCursor(const int myNumber); //really complex and messy, sets attackingHex
-	void endAction(const BattleAction* action);
+	void endAction(const BattleAction * action);
 	void hideQueue();
 	void showQueue();
 
 	Rect hexPosition(BattleHex hex) const;
 
 	void handleHex(BattleHex myNumber, int eventType);
-	bool isCastingPossibleHere (const CStack *sactive, const CStack *shere, BattleHex myNumber);
-	bool canStackMoveHere (const CStack *sactive, BattleHex MyNumber); //TODO: move to BattleState / callback
+	bool isCastingPossibleHere(const CStack * sactive, const CStack * shere, BattleHex myNumber);
+	bool canStackMoveHere(const CStack * sactive, BattleHex MyNumber); //TODO: move to BattleState / callback
 
 	BattleHex fromWhichHexAttack(BattleHex myNumber);
 	void obstaclePlaced(const CObstacleInstance & oi);
 
 	void gateStateChanged(const EGateState state);
 
-	void initStackProjectile(const CStack *stack);
+	void initStackProjectile(const CStack * stack);
 
-	const CGHeroInstance *currentHero() const;
+	const CGHeroInstance * currentHero() const;
 	InfoAboutHero enemyHero() const;
 
 	friend class CPlayerInterface;

+ 139 - 134
client/battle/CBattleInterfaceClasses.cpp

@@ -42,7 +42,7 @@
 
 void CBattleConsole::showAll(SDL_Surface * to)
 {
-	Point textPos(pos.x + pos.w/2, pos.y + 17);
+	Point textPos(pos.x + pos.w / 2, pos.y + 17);
 
 	if(ingcAlter.size())
 	{
@@ -54,7 +54,7 @@ void CBattleConsole::showAll(SDL_Surface * to)
 	}
 	else if(texts.size())
 	{
-		if(texts.size()==1)
+		if(texts.size() == 1)
 		{
 			graphics->fonts[FONT_SMALL]->renderTextLinesCenter(to, CMessage::breakText(texts[0], pos.w, FONT_SMALL), Colors::WHITE, textPos);
 		}
@@ -69,25 +69,25 @@ void CBattleConsole::showAll(SDL_Surface * to)
 
 bool CBattleConsole::addText(const std::string & text)
 {
-	logGlobal->traceStream() <<"CBattleConsole message: "<<text;
-	if(text.size()>70)
+	logGlobal->traceStream() << "CBattleConsole message: " << text;
+	if(text.size() > 70)
 		return false; //text too long!
 	int firstInToken = 0;
 	for(size_t i = 0; i < text.size(); ++i) //tokenize
 	{
 		if(text[i] == 10)
 		{
-			texts.push_back( text.substr(firstInToken, i-firstInToken) );
-			firstInToken = i+1;
+			texts.push_back(text.substr(firstInToken, i - firstInToken));
+			firstInToken = i + 1;
 		}
 	}
 
-	texts.push_back( text.substr(firstInToken, text.size()) );
-	lastShown = texts.size()-1;
+	texts.push_back(text.substr(firstInToken, text.size()));
+	lastShown = texts.size() - 1;
 	return true;
 }
 
-void CBattleConsole::alterText(const std::string &text)
+void CBattleConsole::alterText(const std::string & text)
 {
 	//char buf[500];
 	//sprintf(buf, text.c_str());
@@ -124,7 +124,8 @@ void CBattleConsole::scrollDown(ui32 by)
 		lastShown += by;
 }
 
-CBattleConsole::CBattleConsole() : lastShown(-1), alterTxt(""), whoSetAlter(0)
+CBattleConsole::CBattleConsole()
+	: lastShown(-1), alterTxt(""), whoSetAlter(0)
 {}
 
 void CBattleHero::show(SDL_Surface * to)
@@ -134,19 +135,19 @@ void CBattleHero::show(SDL_Surface * to)
 	if(flip)
 	{
 		temp_rect = genRect(
-			flag->ourImages[flagAnim].bitmap->h,
-			flag->ourImages[flagAnim].bitmap->w,
-			pos.x + 61,
-			pos.y + 39);
+				flag->ourImages[flagAnim].bitmap->h,
+				flag->ourImages[flagAnim].bitmap->w,
+				pos.x + 61,
+				pos.y + 39);
 
 	}
 	else
 	{
 		temp_rect = genRect(
-			flag->ourImages[flagAnim].bitmap->h,
-			flag->ourImages[flagAnim].bitmap->w,
-			pos.x + 72,
-			pos.y + 39);
+				flag->ourImages[flagAnim].bitmap->h,
+				flag->ourImages[flagAnim].bitmap->w,
+				pos.x + 72,
+				pos.y + 39);
 	}
 	CSDL_Ext::blit8bppAlphaTo24bpp(
 		flag->ourImages[flagAnim].bitmap,
@@ -158,13 +159,13 @@ void CBattleHero::show(SDL_Surface * to)
 	SDL_Rect rect = pos;
 	CSDL_Ext::blit8bppAlphaTo24bpp(dh->ourImages[currentFrame].bitmap, nullptr, to, &rect);
 
-	if ( ++animCount == 4 )
+	if(++animCount == 4)
 	{
 		animCount = 0;
-		if ( ++flagAnim >= flag->ourImages.size())
+		if(++flagAnim >= flag->ourImages.size())
 			flagAnim = 0;
 
-		if ( ++currentFrame >= lastFrame)
+		if(++currentFrame >= lastFrame)
 			switchToNextPhase();
 	}
 }
@@ -179,7 +180,7 @@ void CBattleHero::setPhase(int newPhase)
 void CBattleHero::hover(bool on)
 {
 	//TODO: Make lines below work properly
-	if (on)
+	if(on)
 		CCS->curh->changeGraphic(ECursor::COMBAT, 5);
 	else
 		CCS->curh->changeGraphic(ECursor::COMBAT, 0);
@@ -190,9 +191,9 @@ void CBattleHero::clickLeft(tribool down, bool previousState)
 	if(myOwner->spellDestSelectMode) //we are casting a spell
 		return;
 
-	if(myHero != nullptr && !down &&  myOwner->myTurn && myOwner->getCurrentPlayerInterface()->cb->battleCanCastSpell(myHero, ECastingMode::HERO_CASTING) == ESpellCastProblem::OK) //check conditions
+	if(myHero != nullptr && !down && myOwner->myTurn && myOwner->getCurrentPlayerInterface()->cb->battleCanCastSpell(myHero, ECastingMode::HERO_CASTING) == ESpellCastProblem::OK) //check conditions
 	{
-		for(int it=0; it<GameConstants::BFIELD_SIZE; ++it) //do nothing when any hex is hovered - hero's animation overlaps battlefield
+		for(int it = 0; it < GameConstants::BFIELD_SIZE; ++it) //do nothing when any hex is hovered - hero's animation overlaps battlefield
 		{
 			if(myOwner->bfield[it]->hovered && myOwner->bfield[it]->strictHovered)
 				return;
@@ -220,33 +221,29 @@ void CBattleHero::clickRight(tribool down, bool previousState)
 
 void CBattleHero::switchToNextPhase()
 {
-	if (phase != nextPhase)
+	if(phase != nextPhase)
 	{
 		phase = nextPhase;
 
 		//find first and last frames of our animation
-		for (firstFrame = 0;
-		     firstFrame < dh->ourImages.size() && dh->ourImages[firstFrame].groupNumber != phase;
-		     firstFrame++);
+		for(firstFrame = 0;
+		    firstFrame < dh->ourImages.size() && dh->ourImages[firstFrame].groupNumber != phase;
+		    firstFrame++)
+			;
 
-		for (lastFrame = firstFrame;
-			 lastFrame < dh->ourImages.size() && dh->ourImages[lastFrame].groupNumber == phase;
-			 lastFrame++);
+		for(lastFrame = firstFrame;
+		    lastFrame < dh->ourImages.size() && dh->ourImages[lastFrame].groupNumber == phase;
+		    lastFrame++)
+			;
 	}
 
 	currentFrame = firstFrame;
 }
 
-CBattleHero::CBattleHero(const std::string & defName, bool flipG, PlayerColor player, const CGHeroInstance * hero, const CBattleInterface * owner):
-    flip(flipG),
-    myHero(hero),
-    myOwner(owner),
-    phase(1),
-    nextPhase(0),
-    flagAnim(0),
-    animCount(0)
+CBattleHero::CBattleHero(const std::string & defName, bool flipG, PlayerColor player, const CGHeroInstance * hero, const CBattleInterface * owner)
+	: flip(flipG), myHero(hero), myOwner(owner), phase(1), nextPhase(0), flagAnim(0), animCount(0)
 {
-	dh = CDefHandler::giveDef( defName );
+	dh = CDefHandler::giveDef(defName);
 	for(auto & elem : dh->ourImages) //transforming images
 	{
 		if(flip)
@@ -280,14 +277,14 @@ CBattleHero::~CBattleHero()
 	delete flag;
 }
 
-CBattleOptionsWindow::CBattleOptionsWindow(const SDL_Rect & position, CBattleInterface *owner)
+CBattleOptionsWindow::CBattleOptionsWindow(const SDL_Rect & position, CBattleInterface * owner)
 {
 	OBJ_CONSTRUCTION_CAPTURING_ALL;
 	pos = position;
 	background = new CPicture("comopbck.bmp");
 	background->colorize(owner->getCurrentPlayerInterface()->playerID);
 
-	viewGrid = new CToggleButton(Point(25, 56), "sysopchk.def", CGI->generaltexth->zelp[427], [=](bool on){owner->setPrintCellBorders(on);} );
+	viewGrid = new CToggleButton(Point(25, 56), "sysopchk.def", CGI->generaltexth->zelp[427], [=](bool on){owner->setPrintCellBorders(on);});
 	viewGrid->setSelected(settings["battle"]["cellBorders"].Bool());
 	movementShadow = new CToggleButton(Point(25, 89), "sysopchk.def", CGI->generaltexth->zelp[428], [=](bool on){owner->setPrintStackRange(on);});
 	movementShadow->setSelected(settings["battle"]["stackRange"].Bool());
@@ -295,38 +292,38 @@ CBattleOptionsWindow::CBattleOptionsWindow(const SDL_Rect & position, CBattleInt
 	mouseShadow->setSelected(settings["battle"]["mouseShadow"].Bool());
 
 	animSpeeds = new CToggleGroup([=](int value){ owner->setAnimSpeed(value);});
-	animSpeeds->addToggle(40,  new CToggleButton(Point( 28, 225), "sysopb9.def", CGI->generaltexth->zelp[422]));
-	animSpeeds->addToggle(63,  new CToggleButton(Point( 92, 225), "sysob10.def", CGI->generaltexth->zelp[423]));
+	animSpeeds->addToggle(40, new CToggleButton(Point(28, 225), "sysopb9.def", CGI->generaltexth->zelp[422]));
+	animSpeeds->addToggle(63, new CToggleButton(Point(92, 225), "sysob10.def", CGI->generaltexth->zelp[423]));
 	animSpeeds->addToggle(100, new CToggleButton(Point(156, 225), "sysob11.def", CGI->generaltexth->zelp[424]));
 	animSpeeds->setSelected(owner->getAnimSpeed());
 
-	setToDefault = new CButton (Point(246, 359), "codefaul.def", CGI->generaltexth->zelp[393], [&](){ bDefaultf(); });
+	setToDefault = new CButton(Point(246, 359), "codefaul.def", CGI->generaltexth->zelp[393], [&](){ bDefaultf(); });
 	setToDefault->setImageOrder(1, 0, 2, 3);
-	exit = new CButton (Point(357, 359), "soretrn.def", CGI->generaltexth->zelp[392], [&](){ bExitf();}, SDLK_RETURN);
+	exit = new CButton(Point(357, 359), "soretrn.def", CGI->generaltexth->zelp[392], [&](){ bExitf();}, SDLK_RETURN);
 	exit->setImageOrder(1, 0, 2, 3);
 
 	//creating labels
-	labels.push_back(new CLabel(242,  32, FONT_BIG,    CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[392]));//window title
-	labels.push_back(new CLabel(122, 214, FONT_MEDIUM, CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[393]));//animation speed
-	labels.push_back(new CLabel(122, 293, FONT_MEDIUM, CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[394]));//music volume
-	labels.push_back(new CLabel(122, 359, FONT_MEDIUM, CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[395]));//effects' volume
-	labels.push_back(new CLabel(353,  66, FONT_MEDIUM, CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[396]));//auto - combat options
-	labels.push_back(new CLabel(353, 265, FONT_MEDIUM, CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[397]));//creature info
+	labels.push_back(new CLabel(242, 32, FONT_BIG, CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[392])); //window title
+	labels.push_back(new CLabel(122, 214, FONT_MEDIUM, CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[393])); //animation speed
+	labels.push_back(new CLabel(122, 293, FONT_MEDIUM, CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[394])); //music volume
+	labels.push_back(new CLabel(122, 359, FONT_MEDIUM, CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[395])); //effects' volume
+	labels.push_back(new CLabel(353, 66, FONT_MEDIUM, CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[396])); //auto - combat options
+	labels.push_back(new CLabel(353, 265, FONT_MEDIUM, CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[397])); //creature info
 
 	//auto - combat options
-	labels.push_back(new CLabel(283,  86, FONT_MEDIUM, TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[398]));//creatures
-	labels.push_back(new CLabel(283, 116, FONT_MEDIUM, TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[399]));//spells
-	labels.push_back(new CLabel(283, 146, FONT_MEDIUM, TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[400]));//catapult
-	labels.push_back(new CLabel(283, 176, FONT_MEDIUM, TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[151]));//ballista
-	labels.push_back(new CLabel(283, 206, FONT_MEDIUM, TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[401]));//first aid tent
+	labels.push_back(new CLabel(283, 86, FONT_MEDIUM, TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[398])); //creatures
+	labels.push_back(new CLabel(283, 116, FONT_MEDIUM, TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[399])); //spells
+	labels.push_back(new CLabel(283, 146, FONT_MEDIUM, TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[400])); //catapult
+	labels.push_back(new CLabel(283, 176, FONT_MEDIUM, TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[151])); //ballista
+	labels.push_back(new CLabel(283, 206, FONT_MEDIUM, TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[401])); //first aid tent
 
 	//creature info
-	labels.push_back(new CLabel(283, 285, FONT_MEDIUM, TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[402]));//all stats
-	labels.push_back(new CLabel(283, 315, FONT_MEDIUM, TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[403]));//spells only
+	labels.push_back(new CLabel(283, 285, FONT_MEDIUM, TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[402])); //all stats
+	labels.push_back(new CLabel(283, 315, FONT_MEDIUM, TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[403])); //spells only
 
 	//general options
-	labels.push_back(new CLabel(61,  57, FONT_MEDIUM, TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[404]));
-	labels.push_back(new CLabel(61,  90, FONT_MEDIUM, TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[405]));
+	labels.push_back(new CLabel(61, 57, FONT_MEDIUM, TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[404]));
+	labels.push_back(new CLabel(61, 90, FONT_MEDIUM, TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[405]));
 	labels.push_back(new CLabel(61, 123, FONT_MEDIUM, TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[406]));
 	labels.push_back(new CLabel(61, 156, FONT_MEDIUM, TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[407]));
 }
@@ -341,29 +338,29 @@ void CBattleOptionsWindow::bExitf()
 	GH.popIntTotally(this);
 }
 
-CBattleResultWindow::CBattleResultWindow(const BattleResult &br, const SDL_Rect & pos, CPlayerInterface &_owner)
-: owner(_owner)
+CBattleResultWindow::CBattleResultWindow(const BattleResult & br, const SDL_Rect & pos, CPlayerInterface & _owner)
+	: owner(_owner)
 {
 	OBJ_CONSTRUCTION_CAPTURING_ALL;
 	this->pos = pos;
 	CPicture * bg = new CPicture("CPRESULT");
 	bg->colorize(owner.playerID);
 
-	exit = new CButton (Point(384, 505), "iok6432.def", std::make_pair("", ""), [&](){ bExitf();}, SDLK_RETURN);
+	exit = new CButton(Point(384, 505), "iok6432.def", std::make_pair("", ""), [&](){ bExitf();}, SDLK_RETURN);
 	exit->borderColor = Colors::METALLIC_GOLD;
 
-	if(br.winner==0) //attacker won
+	if(br.winner == 0) //attacker won
 	{
-		new CLabel( 59, 124, FONT_SMALL, CENTER, Colors::WHITE, CGI->generaltexth->allTexts[410]);
+		new CLabel(59, 124, FONT_SMALL, CENTER, Colors::WHITE, CGI->generaltexth->allTexts[410]);
 		new CLabel(408, 124, FONT_SMALL, CENTER, Colors::WHITE, CGI->generaltexth->allTexts[411]);
 	}
 	else //if(br.winner==1)
 	{
-		new CLabel( 59, 124, FONT_SMALL, CENTER, Colors::WHITE, CGI->generaltexth->allTexts[411]);
+		new CLabel(59, 124, FONT_SMALL, CENTER, Colors::WHITE, CGI->generaltexth->allTexts[411]);
 		new CLabel(412, 124, FONT_SMALL, CENTER, Colors::WHITE, CGI->generaltexth->allTexts[410]);
 	}
 
-	new CLabel(232, 302, FONT_BIG, CENTER, Colors::YELLOW,  CGI->generaltexth->allTexts[407]);
+	new CLabel(232, 302, FONT_BIG, CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[407]);
 	new CLabel(232, 332, FONT_SMALL, CENTER, Colors::WHITE, CGI->generaltexth->allTexts[408]);
 	new CLabel(232, 428, FONT_SMALL, CENTER, Colors::WHITE, CGI->generaltexth->allTexts[409]);
 
@@ -382,39 +379,39 @@ CBattleResultWindow::CBattleResultWindow(const BattleResult &br, const SDL_Rect
 		else
 		{
 			auto stacks = owner.cb->battleGetAllStacks();
-			vstd::erase_if(stacks, [i](const CStack *stack) //erase stack of other side and not coming from garrison
-				{ return stack->side != i  ||  !stack->base; });
+			vstd::erase_if(stacks, [i](const CStack * stack) //erase stack of other side and not coming from garrison
+				       { return stack->side != i || !stack->base; });
 
-			auto best = vstd::maxElementByFun(stacks, [](const CStack *stack){ return stack->type->AIValue; });
+			auto best = vstd::maxElementByFun(stacks, [](const CStack * stack){ return stack->type->AIValue; });
 			if(best != stacks.end()) //should be always but to be safe...
 			{
-				new CAnimImage("TWCRPORT", (*best)->type->idNumber+2, 0, xs[i], 38);
+				new CAnimImage("TWCRPORT", (*best)->type->idNumber + 2, 0, xs[i], 38);
 				sideNames[i] = CGI->creh->creatures[(*best)->type->idNumber]->namePl;
 			}
 		}
 	}
 
 	//printing attacker and defender's names
-	new CLabel( 89, 37, FONT_SMALL, TOPLEFT, Colors::WHITE, sideNames[0]);
-	new CLabel( 381, 53, FONT_SMALL, BOTTOMRIGHT, Colors::WHITE, sideNames[1]);
+	new CLabel(89, 37, FONT_SMALL, TOPLEFT, Colors::WHITE, sideNames[0]);
+	new CLabel(381, 53, FONT_SMALL, BOTTOMRIGHT, Colors::WHITE, sideNames[1]);
 
 	//printing casualties
 	for(int step = 0; step < 2; ++step)
 	{
-		if(br.casualties[step].size()==0)
+		if(br.casualties[step].size() == 0)
 		{
-			new CLabel( 235, 360 + 97*step, FONT_SMALL, CENTER, Colors::WHITE, CGI->generaltexth->allTexts[523]);
+			new CLabel(235, 360 + 97 * step, FONT_SMALL, CENTER, Colors::WHITE, CGI->generaltexth->allTexts[523]);
 		}
 		else
 		{
-			int xPos = 235 - (br.casualties[step].size()*32 + (br.casualties[step].size() - 1)*10)/2; //increment by 42 with each picture
-			int yPos = 344 + step*97;
+			int xPos = 235 - (br.casualties[step].size() * 32 + (br.casualties[step].size() - 1) * 10) / 2; //increment by 42 with each picture
+			int yPos = 344 + step * 97;
 			for(auto & elem : br.casualties[step])
 			{
 				new CAnimImage("CPRSMALL", CGI->creh->creatures[elem.first]->iconIndex, 0, xPos, yPos);
 				std::ostringstream amount;
-				amount<<elem.second;
-				new CLabel( xPos+16, yPos + 42, FONT_SMALL, CENTER, Colors::WHITE, amount.str());
+				amount << elem.second;
+				new CLabel(xPos + 16, yPos + 42, FONT_SMALL, CENTER, Colors::WHITE, amount.str());
 				xPos += 42;
 			}
 		}
@@ -423,12 +420,18 @@ CBattleResultWindow::CBattleResultWindow(const BattleResult &br, const SDL_Rect
 	bool weAreAttacker = !(owner.cb->battleGetMySide());
 	if((br.winner == 0 && weAreAttacker) || (br.winner == 1 && !weAreAttacker)) //we've won
 	{
-		int text=-1;
+		int text = -1;
 		switch(br.result)
 		{
-		case BattleResult::NORMAL: text = 304; break;
-		case BattleResult::ESCAPE: text = 303; break;
-		case BattleResult::SURRENDER: text = 302; break;
+		case BattleResult::NORMAL:
+			text = 304;
+			break;
+		case BattleResult::ESCAPE:
+			text = 303;
+			break;
+		case BattleResult::SURRENDER:
+			text = 302;
+			break;
 		}
 
 		CCS->musich->playMusic("Music/Win Battle", false);
@@ -436,11 +439,11 @@ CBattleResultWindow::CBattleResultWindow(const BattleResult &br, const SDL_Rect
 		std::string str = CGI->generaltexth->allTexts[text];
 
 		const CGHeroInstance * ourHero = owner.cb->battleGetMyHero();
-		if (ourHero)
+		if(ourHero)
 		{
 			str += CGI->generaltexth->allTexts[305];
-			boost::algorithm::replace_first(str,"%s",ourHero->name);
-			boost::algorithm::replace_first(str,"%d",boost::lexical_cast<std::string>(br.exp[weAreAttacker?0:1]));
+			boost::algorithm::replace_first(str, "%s", ourHero->name);
+			boost::algorithm::replace_first(str, "%d", boost::lexical_cast<std::string>(br.exp[weAreAttacker ? 0 : 1]));
 		}
 
 		new CTextBox(str, Rect(69, 203, 330, 68), 0, FONT_SMALL, CENTER, Colors::WHITE);
@@ -450,26 +453,26 @@ CBattleResultWindow::CBattleResultWindow(const BattleResult &br, const SDL_Rect
 		switch(br.result)
 		{
 		case BattleResult::NORMAL:
-			{
-				CCS->musich->playMusic("Music/LoseCombat", false);
-				CCS->videoh->open("LBSTART.BIK");
-				new CLabel(235, 235, FONT_SMALL, CENTER, Colors::WHITE, CGI->generaltexth->allTexts[311]);
-				break;
-			}
+		{
+			CCS->musich->playMusic("Music/LoseCombat", false);
+			CCS->videoh->open("LBSTART.BIK");
+			new CLabel(235, 235, FONT_SMALL, CENTER, Colors::WHITE, CGI->generaltexth->allTexts[311]);
+			break;
+		}
 		case BattleResult::ESCAPE: //flee
-			{
-				CCS->musich->playMusic("Music/Retreat Battle", false);
-				CCS->videoh->open("RTSTART.BIK");
-				new CLabel(235, 235, FONT_SMALL, CENTER, Colors::WHITE, CGI->generaltexth->allTexts[310]);
-				break;
-			}
+		{
+			CCS->musich->playMusic("Music/Retreat Battle", false);
+			CCS->videoh->open("RTSTART.BIK");
+			new CLabel(235, 235, FONT_SMALL, CENTER, Colors::WHITE, CGI->generaltexth->allTexts[310]);
+			break;
+		}
 		case BattleResult::SURRENDER:
-			{
-				CCS->musich->playMusic("Music/Surrender Battle", false);
-				CCS->videoh->open("SURRENDER.BIK");
-				new CLabel(235, 235, FONT_SMALL, CENTER, Colors::WHITE, CGI->generaltexth->allTexts[309]);
-				break;
-			}
+		{
+			CCS->musich->playMusic("Music/Surrender Battle", false);
+			CCS->videoh->open("SURRENDER.BIK");
+			new CLabel(235, 235, FONT_SMALL, CENTER, Colors::WHITE, CGI->generaltexth->allTexts[309]);
+			break;
+		}
 		}
 	}
 }
@@ -492,9 +495,9 @@ void CBattleResultWindow::show(SDL_Surface * to)
 
 void CBattleResultWindow::bExitf()
 {
-	CPlayerInterface &intTmp = owner; //copy reference because "this" will be destructed soon
+	CPlayerInterface & intTmp = owner; //copy reference because "this" will be destructed soon
 	GH.popIntTotally(this);
-	if(dynamic_cast<CBattleInterface*>(GH.topInt()))
+	if(dynamic_cast<CBattleInterface *>(GH.topInt()))
 		GH.popInts(1); //pop battle interface if present
 
 	//Result window and battle interface are gone. We requested all dialogs to be closed before opening the battle,
@@ -528,10 +531,10 @@ Point CClickableHex::getXYUnitAnim(BattleHex hexNum, const CStack * stack, CBatt
 		static const Point basePos(-190, -139); // position of creature in topleft corner
 		static const int imageShiftX = 30; // X offset to base pos for facing right stacks, negative for facing left
 
-		ret.x = basePos.x + 22 * ( (hexNum.getY() + 1)%2 ) + 44 * hexNum.getX();
+		ret.x = basePos.x + 22 * ((hexNum.getY() + 1) % 2) + 44 * hexNum.getX();
 		ret.y = basePos.y + 42 * hexNum.getY();
 
-		if (stack)
+		if(stack)
 		{
 			if(cbi->creDir[stack->ID])
 				ret.x += imageShiftX;
@@ -569,16 +572,17 @@ void CClickableHex::hover(bool on)
 	}
 }
 
-CClickableHex::CClickableHex() : setAlterText(false), myNumber(-1), accessible(true), hovered(false), strictHovered(false), myInterface(nullptr)
+CClickableHex::CClickableHex()
+	: setAlterText(false), myNumber(-1), accessible(true), hovered(false), strictHovered(false), myInterface(nullptr)
 {
 	addUsedEvents(LCLICK | RCLICK | HOVER | MOVE);
 }
 
-void CClickableHex::mouseMoved(const SDL_MouseMotionEvent &sEvent)
+void CClickableHex::mouseMoved(const SDL_MouseMotionEvent & sEvent)
 {
 	if(myInterface->cellShade)
 	{
-		if(CSDL_Ext::SDL_GetPixel(myInterface->cellShade, sEvent.x-pos.x, sEvent.y-pos.y) == 0) //hovered pixel is outside hex
+		if(CSDL_Ext::SDL_GetPixel(myInterface->cellShade, sEvent.x - pos.x, sEvent.y - pos.y) == 0) //hovered pixel is outside hex
 		{
 			strictHovered = false;
 		}
@@ -591,9 +595,9 @@ void CClickableHex::mouseMoved(const SDL_MouseMotionEvent &sEvent)
 	if(hovered && strictHovered) //print attacked creature to console
 	{
 		const CStack * attackedStack = myInterface->getCurrentPlayerInterface()->cb->battleGetStackByPos(myNumber);
-		if(myInterface->console->alterTxt.size() == 0 &&attackedStack != nullptr &&
-			attackedStack->owner != myInterface->getCurrentPlayerInterface()->playerID &&
-			attackedStack->alive())
+		if(myInterface->console->alterTxt.size() == 0 && attackedStack != nullptr &&
+		   attackedStack->owner != myInterface->getCurrentPlayerInterface()->playerID &&
+		   attackedStack->alive())
 		{
 			MetaString text;
 			text.addTxt(MetaString::GENERAL_TXT, 220);
@@ -620,10 +624,11 @@ void CClickableHex::clickLeft(tribool down, bool previousState)
 void CClickableHex::clickRight(tribool down, bool previousState)
 {
 	const CStack * myst = myInterface->getCurrentPlayerInterface()->cb->battleGetStackByPos(myNumber); //stack info
-	if(hovered && strictHovered && myst!=nullptr)
+	if(hovered && strictHovered && myst != nullptr)
 	{
 
-		if(!myst->alive()) return;
+		if(!myst->alive())
+			return;
 		if(down)
 		{
 			GH.pushInt(new CStackWindow(myst, true));
@@ -631,10 +636,11 @@ void CClickableHex::clickRight(tribool down, bool previousState)
 	}
 }
 
-CHeroInfoWindow::CHeroInfoWindow(const InfoAboutHero &hero, Point *position) : CWindowObject(RCLICK_POPUP | SHADOW_DISABLED, "CHRPOP")
+CHeroInfoWindow::CHeroInfoWindow(const InfoAboutHero & hero, Point * position)
+	: CWindowObject(RCLICK_POPUP | SHADOW_DISABLED, "CHRPOP")
 {
 	OBJ_CONSTRUCTION_CAPTURING_ALL;
-	if (position != nullptr)
+	if(position != nullptr)
 		moveTo(*position);
 	background->colorize(hero.owner); //maybe add this functionality to base class?
 
@@ -678,7 +684,7 @@ void CStackQueue::update()
 	owner->getCurrentPlayerInterface()->cb->battleGetStackQueue(stacksSorted, stackBoxes.size());
 	if(stacksSorted.size())
 	{
-		for (int i = 0; i < stackBoxes.size() ; i++)
+		for(int i = 0; i < stackBoxes.size(); i++)
 		{
 			stackBoxes[i]->setStack(stacksSorted[i]);
 		}
@@ -690,7 +696,7 @@ void CStackQueue::update()
 }
 
 CStackQueue::CStackQueue(bool Embedded, CBattleInterface * _owner)
-:embedded(Embedded), owner(_owner)
+	: embedded(Embedded), owner(_owner)
 {
 	OBJ_CONSTRUCTION_CAPTURING_ALL;
 	if(embedded)
@@ -698,8 +704,8 @@ CStackQueue::CStackQueue(bool Embedded, CBattleInterface * _owner)
 		bg = nullptr;
 		pos.w = QUEUE_SIZE * 37;
 		pos.h = 46;
-		pos.x = screen->w/2 - pos.w/2;
-		pos.y = (screen->h - 600)/2 + 10;
+		pos.x = screen->w / 2 - pos.w / 2;
+		pos.y = (screen->h - 600) / 2 + 10;
 	}
 	else
 	{
@@ -709,10 +715,10 @@ CStackQueue::CStackQueue(bool Embedded, CBattleInterface * _owner)
 	}
 
 	stackBoxes.resize(QUEUE_SIZE);
-	for (int i = 0; i < stackBoxes.size(); i++)
+	for(int i = 0; i < stackBoxes.size(); i++)
 	{
 		stackBoxes[i] = new StackBox(embedded);
-		stackBoxes[i]->moveBy(Point(1 + (embedded ? 36 : 80)*i, 0));
+		stackBoxes[i]->moveBy(Point(1 + (embedded ? 36 : 80) * i, 0));
 	}
 }
 
@@ -728,7 +734,7 @@ void CStackQueue::showAll(SDL_Surface * to)
 	CIntObject::showAll(to);
 }
 
-void CStackQueue::blitBg( SDL_Surface * to )
+void CStackQueue::blitBg(SDL_Surface * to)
 {
 	if(bg)
 	{
@@ -745,26 +751,25 @@ void CStackQueue::StackBox::showAll(SDL_Surface * to)
 	CIntObject::showAll(to);
 
 	if(small)
-		printAtMiddleLoc(makeNumberShort(stack->getCount()), pos.w/2, pos.h - 7, FONT_SMALL, Colors::WHITE, to);
+		printAtMiddleLoc(makeNumberShort(stack->getCount()), pos.w / 2, pos.h - 7, FONT_SMALL, Colors::WHITE, to);
 	else
-		printAtMiddleLoc(makeNumberShort(stack->getCount()), pos.w/2, pos.h - 8, FONT_MEDIUM, Colors::WHITE, to);
+		printAtMiddleLoc(makeNumberShort(stack->getCount()), pos.w / 2, pos.h - 8, FONT_MEDIUM, Colors::WHITE, to);
 }
 
-void CStackQueue::StackBox::setStack( const CStack *stack )
+void CStackQueue::StackBox::setStack(const CStack * stack)
 {
 	this->stack = stack;
 	assert(stack);
 	icon->setFrame(stack->getCreature()->iconIndex);
 }
 
-CStackQueue::StackBox::StackBox(bool small):
-    stack(nullptr),
-    small(small)
+CStackQueue::StackBox::StackBox(bool small)
+	: stack(nullptr), small(small)
 {
 	OBJ_CONSTRUCTION_CAPTURING_ALL;
-	bg = new CPicture(small ? "StackQueueSmall" : "StackQueueLarge" );
+	bg = new CPicture(small ? "StackQueueSmall" : "StackQueueLarge");
 
-	if (small)
+	if(small)
 	{
 		icon = new CAnimImage("CPRSMALL", 0, 0, 5, 2);
 	}

+ 23 - 18
client/battle/CBattleInterfaceClasses.h

@@ -31,18 +31,19 @@ class CPlayerInterface;
 class CBattleConsole : public CIntObject
 {
 private:
-	std::vector< std::string > texts; //a place where texts are stored
+	std::vector<std::string> texts; //a place where texts are stored
 	int lastShown; //last shown line of text
+
 public:
 	std::string alterTxt; //if it's not empty, this text is displayed
 	std::string ingcAlter; //alternative text set by in-game console - very important!
 	int whoSetAlter; //who set alter text; 0 - battle interface or none, 1 - button
 	CBattleConsole();
 	void showAll(SDL_Surface * to = 0) override;
-	bool addText(const std::string &text); //adds text at the last position; returns false if failed (e.g. text longer than 70 characters)
-	void alterText(const std::string &text); //place string at alterTxt
+	bool addText(const std::string & text); //adds text at the last position; returns false if failed (e.g. text longer than 70 characters)
+	void alterText(const std::string & text); //place string at alterTxt
 	void eraseText(ui32 pos); //erases added text at position pos
-	void changeTextAt(const std::string &text, ui32 pos); //if we have more than pos texts, pos-th is changed to given one
+	void changeTextAt(const std::string & text, ui32 pos); //if we have more than pos texts, pos-th is changed to given one
 	void scrollUp(ui32 by = 1); //scrolls console up by 'by' positions
 	void scrollDown(ui32 by = 1); //scrolls console up by 'by' positions
 };
@@ -51,9 +52,10 @@ public:
 class CBattleHero : public CIntObject
 {
 	void switchToNextPhase();
+
 public:
 	bool flip; //false if it's attacking hero, true otherwise
-	CDefHandler *dh, *flag; //animation and flag
+	CDefHandler * dh, * flag; //animation and flag
 	const CGHeroInstance * myHero; //this animation's hero instance
 	const CBattleInterface * myOwner; //battle interface to which this animation is assigned
 	int phase; //stage of animation
@@ -65,14 +67,14 @@ public:
 	void hover(bool on) override;
 	void clickLeft(tribool down, bool previousState) override; //call-in
 	void clickRight(tribool down, bool previousState) override; //call-in
-	CBattleHero(const std::string &defName, bool filpG, PlayerColor player, const CGHeroInstance *hero, const CBattleInterface *owner);
+	CBattleHero(const std::string & defName, bool filpG, PlayerColor player, const CGHeroInstance * hero, const CBattleInterface * owner);
 	~CBattleHero();
 };
 
 class CHeroInfoWindow : public CWindowObject
 {
 public:
-	CHeroInfoWindow(const InfoAboutHero &hero, Point *position);
+	CHeroInfoWindow(const InfoAboutHero & hero, Point * position);
 };
 
 /// Class which manages the battle options window
@@ -84,9 +86,10 @@ private:
 	CToggleButton * viewGrid, * movementShadow, * mouseShadow;
 	CToggleGroup * animSpeeds;
 
-	std::vector<CLabel*> labels;
+	std::vector<CLabel *> labels;
+
 public:
-	CBattleOptionsWindow(const SDL_Rect &position, CBattleInterface *owner);
+	CBattleOptionsWindow(const SDL_Rect & position, CBattleInterface * owner);
 
 	void bDefaultf(); //default button callback
 	void bExitf(); //exit button callback
@@ -96,10 +99,11 @@ public:
 class CBattleResultWindow : public CIntObject
 {
 private:
-	CButton *exit;
-	CPlayerInterface &owner;
+	CButton * exit;
+	CPlayerInterface & owner;
+
 public:
-	CBattleResultWindow(const BattleResult & br, const SDL_Rect & pos, CPlayerInterface &_owner);
+	CBattleResultWindow(const BattleResult & br, const SDL_Rect & pos, CPlayerInterface & _owner);
 	~CBattleResultWindow();
 
 	void bExitf(); //exit button callback
@@ -113,6 +117,7 @@ class CClickableHex : public CIntObject
 {
 private:
 	bool setAlterText; //if true, this hex has set alternative text in console and will clean it
+
 public:
 	ui32 myNumber; //number of hex in commonly used format
 	bool accessible; //if true, this hex is accessible for units
@@ -122,8 +127,8 @@ public:
 	static Point getXYUnitAnim(BattleHex hexNum, const CStack * creature, CBattleInterface * cbi); //returns (x, y) of left top corner of animation
 
 	//for user interactions
-	void hover (bool on) override;
-	void mouseMoved (const SDL_MouseMotionEvent &sEvent) override;
+	void hover(bool on) override;
+	void mouseMoved(const SDL_MouseMotionEvent & sEvent) override;
 	void clickLeft(tribool down, bool previousState) override;
 	void clickRight(tribool down, bool previousState) override;
 	CClickableHex();
@@ -134,14 +139,14 @@ class CStackQueue : public CIntObject
 {
 	class StackBox : public CIntObject
 	{
-	public:
+public:
 		CPicture * bg;
 		CAnimImage * icon;
-		const CStack *stack;
+		const CStack * stack;
 		bool small;
 
 		void showAll(SDL_Surface * to) override;
-		void setStack(const CStack *nStack);
+		void setStack(const CStack * nStack);
 		StackBox(bool small);
 	};
 
@@ -158,6 +163,6 @@ public:
 	CStackQueue(bool Embedded, CBattleInterface * _owner);
 	~CStackQueue();
 	void update();
-	void showAll(SDL_Surface *to) override;
+	void showAll(SDL_Surface * to) override;
 	void blitBg(SDL_Surface * to);
 };

+ 48 - 52
client/battle/CCreatureAnimation.cpp

@@ -21,7 +21,7 @@
 
 static const SDL_Color creatureBlueBorder = { 0, 255, 255, 255 };
 static const SDL_Color creatureGoldBorder = { 255, 255, 0, 255 };
-static const SDL_Color creatureNoBorder  =  { 0, 0, 0, 0 };
+static const SDL_Color creatureNoBorder = { 0, 0, 0, 0 };
 
 SDL_Color AnimationControls::getBlueBorder()
 {
@@ -60,7 +60,7 @@ float AnimationControls::getCreatureAnimationSpeed(const CCreature * creature, c
 	const float speedMult = settings["battle"]["animationSpeed"].Float();
 	const float speed = baseSpeed / speedMult;
 
-	switch (type)
+	switch(type)
 	{
 	case CCreatureAnim::MOVING:
 		return speed * 2 * creature->animation.walkAnimationTime / anim->framesInGroup(type);
@@ -143,14 +143,7 @@ void CCreatureAnimation::setType(CCreatureAnim::EAnimType type)
 }
 
 CCreatureAnimation::CCreatureAnimation(std::string name, TSpeedController controller)
-    : defName(name),
-      speed(0.1),
-      currentFrame(0),
-      elapsedTime(0),
-	  type(CCreatureAnim::HOLDING),
-	  border(CSDL_Ext::makeColor(0, 0, 0, 0)),
-      speedController(controller),
-      once(false)
+	: defName(name), speed(0.1), currentFrame(0), elapsedTime(0), type(CCreatureAnim::HOLDING), border(CSDL_Ext::makeColor(0, 0, 0, 0)), speedController(controller), once(false)
 {
 	// separate block to avoid accidental use of "data" after it was moved into "pixelData"
 	{
@@ -168,12 +161,12 @@ CCreatureAnimation::CCreatureAnimation(std::string name, TSpeedController contro
 
 	reader.readInt32(); // def type, unused
 
-	fullWidth  = reader.readInt32();
+	fullWidth = reader.readInt32();
 	fullHeight = reader.readInt32();
 
 	int totalBlocks = reader.readInt32();
 
-	for (auto & elem : palette)
+	for(auto & elem : palette)
 	{
 		elem.r = reader.readUInt8();
 		elem.g = reader.readUInt8();
@@ -181,7 +174,7 @@ CCreatureAnimation::CCreatureAnimation(std::string name, TSpeedController contro
 		elem.a = SDL_ALPHA_OPAQUE;
 	}
 
-	for (int i=0; i<totalBlocks; i++)
+	for(int i = 0; i < totalBlocks; i++)
 	{
 		int groupID = reader.readInt32();
 
@@ -189,12 +182,12 @@ CCreatureAnimation::CCreatureAnimation(std::string name, TSpeedController contro
 
 		reader.skip(4 + 4 + 13 * totalInBlock); // some unused data
 
-		for (int j=0; j<totalInBlock; j++)
+		for(int j = 0; j < totalInBlock; j++)
 			dataOffsets[groupID].push_back(reader.readUInt32());
 	}
 
 	// if necessary, add one frame into vcmi-only group DEAD
-	if (dataOffsets.count(CCreatureAnim::DEAD) == 0)
+	if(dataOffsets.count(CCreatureAnim::DEAD) == 0)
 		dataOffsets[CCreatureAnim::DEAD].push_back(dataOffsets[CCreatureAnim::DEATH].back());
 
 	play();
@@ -212,13 +205,13 @@ bool CCreatureAnimation::incrementFrame(float timePassed)
 {
 	elapsedTime += timePassed;
 	currentFrame += timePassed * speed;
-	if (currentFrame >= float(framesInGroup(type)))
+	if(currentFrame >= float(framesInGroup(type)))
 	{
 		// just in case of extremely low fps (or insanely high speed)
-		while (currentFrame >= float(framesInGroup(type)))
+		while(currentFrame >= float(framesInGroup(type)))
 			currentFrame -= framesInGroup(type);
 
-		if (once)
+		if(once)
 			setType(CCreatureAnim::HOLDING);
 
 		endAnimation();
@@ -247,7 +240,7 @@ float CCreatureAnimation::getCurrentFrame() const
 	return currentFrame;
 }
 
-void CCreatureAnimation::playOnce( CCreatureAnim::EAnimType type )
+void CCreatureAnimation::playOnce(CCreatureAnim::EAnimType type)
 {
 	setType(type);
 	once = true;
@@ -272,17 +265,17 @@ static SDL_Color genBorderColor(ui8 alpha, const SDL_Color & base)
 
 static ui8 mixChannels(ui8 c1, ui8 c2, ui8 a1, ui8 a2)
 {
-	return c1*a1 / 256 + c2*a2*(255 - a1) / 256 / 256;
+	return c1 * a1 / 256 + c2 * a2 * (255 - a1) / 256 / 256;
 }
 
 static SDL_Color addColors(const SDL_Color & base, const SDL_Color & over)
 {
 	return CSDL_Ext::makeColor(
-			mixChannels(over.r, base.r, over.a, base.a),
-			mixChannels(over.g, base.g, over.a, base.a),
-			mixChannels(over.b, base.b, over.a, base.a),
-			ui8(over.a + base.a * (255 - over.a) / 256)
-			);
+		mixChannels(over.r, base.r, over.a, base.a),
+		mixChannels(over.g, base.g, over.a, base.a),
+		mixChannels(over.b, base.b, over.a, base.a),
+		ui8(over.a + base.a * (255 - over.a) / 256)
+		);
 }
 
 std::array<SDL_Color, 8> CCreatureAnimation::genSpecialPalette()
@@ -296,7 +289,7 @@ std::array<SDL_Color, 8> CCreatureAnimation::genSpecialPalette()
 	ret[4] = genShadow(128);
 	ret[5] = genBorderColor(getBorderStrength(elapsedTime), border);
 	ret[6] = addColors(genShadow(128), genBorderColor(getBorderStrength(elapsedTime), border));
-	ret[7] = addColors(genShadow(64),  genBorderColor(getBorderStrength(elapsedTime), border));
+	ret[7] = addColors(genShadow(64), genBorderColor(getBorderStrength(elapsedTime), border));
 
 	return ret;
 }
@@ -333,13 +326,13 @@ void CCreatureAnimation::nextFrameT(SDL_Surface * dest, bool rotate)
 
 	auto specialPalette = genSpecialPalette();
 
-	for (ui32 i=0; i<spriteHeight; i++)
+	for(ui32 i = 0; i < spriteHeight; i++)
 	{
 		//NOTE: if this loop will be optimized to skip empty lines - recheck this read access
 		ui8 * lineData = pixelData.get() + baseOffset + reader.readUInt32();
 
 		size_t destX = pos.x;
-		if (rotate)
+		if(rotate)
 			destX += rightMargin + spriteWidth - 1;
 		else
 			destX += leftMargin;
@@ -348,24 +341,24 @@ void CCreatureAnimation::nextFrameT(SDL_Surface * dest, bool rotate)
 		size_t currentOffset = 0;
 		size_t totalRowLength = 0;
 
-		while (totalRowLength < spriteWidth)
+		while(totalRowLength < spriteWidth)
 		{
 			ui8 type = lineData[currentOffset++];
 			ui32 length = lineData[currentOffset++] + 1;
 
-			if (type==0xFF)//Raw data
+			if(type == 0xFF) //Raw data
 			{
-				for (size_t j=0; j<length; j++)
-					putPixelAt<bpp>(dest, destX + (rotate?(-j):(j)), destY, lineData[currentOffset + j], specialPalette);
+				for(size_t j = 0; j < length; j++)
+					putPixelAt<bpp>(dest, destX + (rotate ? (-j) : (j)), destY, lineData[currentOffset + j], specialPalette);
 
 				currentOffset += length;
 			}
-			else// RLE
+			else // RLE
 			{
-				if (type != 0) // transparency row, handle it here for speed
+				if(type != 0) // transparency row, handle it here for speed
 				{
-					for (size_t j=0; j<length; j++)
-						putPixelAt<bpp>(dest, destX + (rotate?(-j):(j)), destY, type, specialPalette);
+					for(size_t j = 0; j < length; j++)
+						putPixelAt<bpp>(dest, destX + (rotate ? (-j) : (j)), destY, type, specialPalette);
 				}
 			}
 
@@ -375,15 +368,18 @@ void CCreatureAnimation::nextFrameT(SDL_Surface * dest, bool rotate)
 	}
 }
 
-void CCreatureAnimation::nextFrame(SDL_Surface *dest, bool attacker)
+void CCreatureAnimation::nextFrame(SDL_Surface * dest, bool attacker)
 {
 	// Note: please notice that attacker value is inversed when passed further.
 	// This is intended behavior because "attacker" actually does not needs rotation
 	switch(dest->format->BytesPerPixel)
 	{
-	case 2: return nextFrameT<2>(dest, !attacker);
-	case 3: return nextFrameT<3>(dest, !attacker);
-	case 4: return nextFrameT<4>(dest, !attacker);
+	case 2:
+		return nextFrameT<2>(dest, !attacker);
+	case 3:
+		return nextFrameT<3>(dest, !attacker);
+	case 4:
+		return nextFrameT<4>(dest, !attacker);
 	default:
 		logGlobal->errorStream() << (int)dest->format->BitsPerPixel << " bpp is not supported!!!";
 	}
@@ -399,20 +395,20 @@ int CCreatureAnimation::framesInGroup(CCreatureAnim::EAnimType group) const
 
 ui8 * CCreatureAnimation::getPixelAddr(SDL_Surface * dest, int X, int Y) const
 {
-	return (ui8*)dest->pixels + X * dest->format->BytesPerPixel + Y * dest->pitch;
+	return (ui8 *)dest->pixels + X * dest->format->BytesPerPixel + Y * dest->pitch;
 }
 
 template<int bpp>
 inline void CCreatureAnimation::putPixelAt(SDL_Surface * dest, int X, int Y, size_t index, const std::array<SDL_Color, 8> & special) const
 {
-	if ( X < pos.x + pos.w && Y < pos.y + pos.h && X >= 0 && Y >= 0)
+	if(X < pos.x + pos.w && Y < pos.y + pos.h && X >= 0 && Y >= 0)
 		putPixel<bpp>(getPixelAddr(dest, X, Y), palette[index], index, special);
 }
 
 template<int bpp>
 inline void CCreatureAnimation::putPixel(ui8 * dest, const SDL_Color & color, size_t index, const std::array<SDL_Color, 8> & special) const
 {
-	if (index < 8)
+	if(index < 8)
 	{
 		const SDL_Color & pal = special[index];
 		ColorPutter<bpp, 0>::PutColor(dest, pal.r, pal.g, pal.b, pal.a);
@@ -426,27 +422,27 @@ inline void CCreatureAnimation::putPixel(ui8 * dest, const SDL_Color & color, si
 bool CCreatureAnimation::isDead() const
 {
 	return getType() == CCreatureAnim::DEAD
-	    || getType() == CCreatureAnim::DEATH;
+	       || getType() == CCreatureAnim::DEATH;
 }
 
 bool CCreatureAnimation::isIdle() const
 {
 	return getType() == CCreatureAnim::HOLDING
-	    || getType() == CCreatureAnim::MOUSEON;
+	       || getType() == CCreatureAnim::MOUSEON;
 }
 
 bool CCreatureAnimation::isMoving() const
 {
 	return getType() == CCreatureAnim::MOVE_START
-	    || getType() == CCreatureAnim::MOVING
-	    || getType() == CCreatureAnim::MOVE_END;
+	       || getType() == CCreatureAnim::MOVING
+	       || getType() == CCreatureAnim::MOVE_END;
 }
 
 bool CCreatureAnimation::isShooting() const
 {
 	return getType() == CCreatureAnim::SHOOT_UP
-	    || getType() == CCreatureAnim::SHOOT_FRONT
-	    || getType() == CCreatureAnim::SHOOT_DOWN;
+	       || getType() == CCreatureAnim::SHOOT_FRONT
+	       || getType() == CCreatureAnim::SHOOT_DOWN;
 }
 
 void CCreatureAnimation::pause()
@@ -456,7 +452,7 @@ void CCreatureAnimation::pause()
 
 void CCreatureAnimation::play()
 {
-    speed = 0;
-    if (speedController(this, type) != 0)
-        speed = 1 / speedController(this, type);
+	speed = 0;
+	if(speedController(this, type) != 0)
+		speed = 1 / speedController(this, type);
 }

+ 20 - 19
client/battle/CCreatureAnimation.h

@@ -19,29 +19,29 @@ class CCreatureAnimation;
 /// Namespace for some common controls of animations
 namespace AnimationControls
 {
-	/// get SDL_Color for creature selection borders
-	SDL_Color getBlueBorder();
-	SDL_Color getGoldBorder();
-	SDL_Color getNoBorder();
+/// get SDL_Color for creature selection borders
+SDL_Color getBlueBorder();
+SDL_Color getGoldBorder();
+SDL_Color getNoBorder();
 
-	/// creates animation object with preset speed control
-	CCreatureAnimation * getAnimation(const CCreature * creature);
+/// creates animation object with preset speed control
+CCreatureAnimation * getAnimation(const CCreature * creature);
 
-	/// returns animation speed of specific group, taking in mind game setting (in frames per second)
-	float getCreatureAnimationSpeed(const CCreature * creature, const CCreatureAnimation * anim, size_t groupID);
+/// returns animation speed of specific group, taking in mind game setting (in frames per second)
+float getCreatureAnimationSpeed(const CCreature * creature, const CCreatureAnimation * anim, size_t groupID);
 
-	/// returns how far projectile should move each frame
-	/// TODO: make it time-based
-	float getProjectileSpeed();
+/// returns how far projectile should move each frame
+/// TODO: make it time-based
+float getProjectileSpeed();
 
-	/// returns speed of any spell effects, including any special effects like morale (in frames per second)
-	float getSpellEffectSpeed();
+/// returns speed of any spell effects, including any special effects like morale (in frames per second)
+float getSpellEffectSpeed();
 
-	/// returns duration of full movement animation, in seconds. Needed to move animation on screen
-	float getMovementDuration(const CCreature * creature);
+/// returns duration of full movement animation, in seconds. Needed to move animation on screen
+float getMovementDuration(const CCreature * creature);
 
-	/// Returns distance on which flying creatures should during one animation loop
-	float getFlightDistance(const CCreature * creature);
+/// Returns distance on which flying creatures should during one animation loop
+float getFlightDistance(const CCreature * creature);
 }
 
 /// Class which manages animations of creatures/units inside battles
@@ -49,7 +49,7 @@ namespace AnimationControls
 class CCreatureAnimation : public CIntObject
 {
 public:
-	typedef std::function<float(CCreatureAnimation *, size_t)> TSpeedController;
+	typedef std::function<float (CCreatureAnimation *, size_t)> TSpeedController;
 
 private:
 	std::string defName;
@@ -91,7 +91,7 @@ private:
 	void putPixelAt(SDL_Surface * dest, int X, int Y, size_t index, const std::array<SDL_Color, 8> & special) const;
 
 	template<int bpp>
-	void putPixel( ui8 * dest, const SDL_Color & color, size_t index, const std::array<SDL_Color, 8> & special) const;
+	void putPixel(ui8 * dest, const SDL_Color & color, size_t index, const std::array<SDL_Color, 8> & special) const;
 
 	template<int bpp>
 	void nextFrameT(SDL_Surface * dest, bool rotate);
@@ -100,6 +100,7 @@ private:
 
 	/// creates 8 special colors for current frame
 	std::array<SDL_Color, 8> genSpecialPalette();
+
 public:
 
 	// function(s) that will be called when animation ends, after reset to 1st frame

File diff suppressed because it is too large
+ 240 - 249
client/gui/CAnimation.cpp


+ 20 - 15
client/gui/CAnimation.h

@@ -23,10 +23,11 @@ class CDefFile;
 class IImage
 {
 	int refCount;
+
 public:
 
 	//draws image on surface "where" at position
-	virtual void draw(SDL_Surface * where, int posX = 0, int posY = 0, Rect * src = nullptr, ui8 alpha = 255) const=0;
+	virtual void draw(SDL_Surface * where, int posX = 0, int posY = 0, Rect * src = nullptr, ui8 alpha = 255) const = 0;
 	virtual void draw(SDL_Surface * where, SDL_Rect * dest, SDL_Rect * src, ui8 alpha = 255) const = 0;
 
 	virtual std::unique_ptr<IImage> scaleFast(float scale) const = 0;
@@ -38,13 +39,13 @@ public:
 	void increaseRef();
 
 	//Change palette to specific player
-	virtual void playerColored(PlayerColor player)=0;
+	virtual void playerColored(PlayerColor player) = 0;
 
 	//set special color for flag
-	virtual void setFlagColor(PlayerColor player)=0;
+	virtual void setFlagColor(PlayerColor player) = 0;
 
-	virtual int width() const=0;
-	virtual int height() const=0;
+	virtual int width() const = 0;
+	virtual int height() const = 0;
 
 	//only indexed bitmaps, 16 colors maximum
 	virtual void shiftPalette(int from, int howMany) = 0;
@@ -61,10 +62,10 @@ class CAnimation
 {
 private:
 	//source[group][position] - file with this frame, if string is empty - image located in def file
-	std::map<size_t, std::vector <JsonNode> > source;
+	std::map<size_t, std::vector<JsonNode>> source;
 
 	//bitmap[group][position], store objects with loaded bitmaps
-	std::map<size_t, std::map<size_t, IImage* > > images;
+	std::map<size_t, std::map<size_t, IImage *>> images;
 
 	//animation file name
 	std::string name;
@@ -105,28 +106,28 @@ public:
 	void duplicateImage(const size_t sourceGroup, const size_t sourceFrame, const size_t targetGroup);
 
 	//add custom surface to the selected position.
-	void setCustom(std::string filename, size_t frame, size_t group=0);
+	void setCustom(std::string filename, size_t frame, size_t group = 0);
 
 	//get pointer to image from specific group, nullptr if not found
-	IImage * getImage(size_t frame, size_t group=0, bool verbose=true) const;
+	IImage * getImage(size_t frame, size_t group = 0, bool verbose = true) const;
 
 	void exportBitmaps(const boost::filesystem::path & path) const;
 
 	//all available frames
-	void load  ();
+	void load();
 	void unload();
 	void preload();
 
 	//all frames from group
-	void loadGroup  (size_t group);
+	void loadGroup(size_t group);
 	void unloadGroup(size_t group);
 
 	//single image
-	void load  (size_t frame, size_t group=0);
-	void unload(size_t frame, size_t group=0);
+	void load(size_t frame, size_t group = 0);
+	void unload(size_t frame, size_t group = 0);
 
 	//total count of frames in group (including not loaded)
-	size_t size(size_t group=0) const;
+	size_t size(size_t group = 0) const;
 };
 
 const float DEFAULT_DELTA = 0.05f;
@@ -136,8 +137,11 @@ class CFadeAnimation
 public:
 	enum class EMode
 	{
-		NONE, IN, OUT
+		NONE,
+		IN,
+		OUT
 	};
+
 private:
 	float delta;
 	SDL_Surface * fadingSurface;
@@ -147,6 +151,7 @@ private:
 
 	float initialCounter() const;
 	bool isFinished() const;
+
 public:
 	EMode fadingMode;
 

+ 22 - 20
client/gui/CCursorHandler.cpp

@@ -25,9 +25,9 @@ void CCursorHandler::initCursor()
 	dndObject = nullptr;
 	currentCursor = nullptr;
 
-	help = CSDL_Ext::newSurface(40,40);
+	help = CSDL_Ext::newSurface(40, 40);
 	//No blending. Ensure, that we are copying pixels during "screen restore draw"
-	SDL_SetSurfaceBlendMode(help,SDL_BLENDMODE_NONE);	
+	SDL_SetSurfaceBlendMode(help, SDL_BLENDMODE_NONE);
 	SDL_ShowCursor(SDL_DISABLE);
 
 	changeGraphic(ECursor::ADVENTURE, 0);
@@ -37,7 +37,7 @@ void CCursorHandler::changeGraphic(ECursor::ECursorTypes type, int index)
 {
 	std::string cursorDefs[4] = { "CRADVNTR.DEF", "CRCOMBAT.DEF", "CRDEFLT.DEF", "CRSPELL.DEF" };
 
-	if (type != this->type)
+	if(type != this->type)
 	{
 		BLOCK_CAPTURING; // not used here
 
@@ -48,7 +48,7 @@ void CCursorHandler::changeGraphic(ECursor::ECursorTypes type, int index)
 		currentCursor = new CAnimImage(cursorDefs[int(type)], index);
 	}
 
-	if (frame != index)
+	if(frame != index)
 	{
 		frame = index;
 		currentCursor->setFrame(index);
@@ -57,7 +57,7 @@ void CCursorHandler::changeGraphic(ECursor::ECursorTypes type, int index)
 
 void CCursorHandler::dragAndDropCursor(CAnimImage * object)
 {
-	if (dndObject)
+	if(dndObject)
 		delete dndObject;
 
 	dndObject = object;
@@ -71,22 +71,23 @@ void CCursorHandler::cursorMove(const int & x, const int & y)
 
 void CCursorHandler::drawWithScreenRestore()
 {
-	if(!showing) return;
+	if(!showing)
+		return;
 	int x = xpos, y = ypos;
 	shiftPos(x, y);
 
-	SDL_Rect temp_rect1 = genRect(40,40,x,y);
-	SDL_Rect temp_rect2 = genRect(40,40,0,0);
+	SDL_Rect temp_rect1 = genRect(40, 40, x, y);
+	SDL_Rect temp_rect2 = genRect(40, 40, 0, 0);
 	SDL_BlitSurface(screen, &temp_rect1, help, &temp_rect2);
 
-	if (dndObject)
+	if(dndObject)
 	{
-		dndObject->moveTo(Point(x - dndObject->pos.w/2, y - dndObject->pos.h/2));
+		dndObject->moveTo(Point(x - dndObject->pos.w / 2, y - dndObject->pos.h / 2));
 		dndObject->showAll(screen);
 	}
 	else
 	{
-		currentCursor->moveTo(Point(x,y));
+		currentCursor->moveTo(Point(x, y));
 		currentCursor->showAll(screen);
 	}
 }
@@ -104,23 +105,23 @@ void CCursorHandler::drawRestored()
 	//blitAt(help,x,y);
 }
 
-void CCursorHandler::draw(SDL_Surface *to)
+void CCursorHandler::draw(SDL_Surface * to)
 {
 	currentCursor->moveTo(Point(xpos, ypos));
 	currentCursor->showAll(screen);
 }
 
-void CCursorHandler::shiftPos( int &x, int &y )
+void CCursorHandler::shiftPos(int & x, int & y)
 {
-	if(( type == ECursor::COMBAT && frame != ECursor::COMBAT_POINTER) || type == ECursor::SPELLBOOK)
+	if((type == ECursor::COMBAT && frame != ECursor::COMBAT_POINTER) || type == ECursor::SPELLBOOK)
 	{
-		x-=16;
-		y-=16;
+		x -= 16;
+		y -= 16;
 
 		// Properly align the melee attack cursors.
-		if (type == ECursor::COMBAT)
+		if(type == ECursor::COMBAT)
 		{
-			switch (frame)
+			switch(frame)
 			{
 			case 7: // Bottom left
 				x -= 6;
@@ -159,7 +160,8 @@ void CCursorHandler::shiftPos( int &x, int &y )
 	}
 	else if(type == ECursor::ADVENTURE)
 	{
-		if (frame == 0); //to exclude
+		if(frame == 0)
+			; //to exclude
 		else if(frame == 2)
 		{
 			x -= 12;
@@ -172,7 +174,7 @@ void CCursorHandler::shiftPos( int &x, int &y )
 		}
 		else if(frame < 27)
 		{
-			int hlpNum = (frame - 4)%6;
+			int hlpNum = (frame - 4) % 6;
 			if(hlpNum == 0)
 			{
 				x -= 15;

+ 31 - 14
client/gui/CCursorHandler.h

@@ -14,17 +14,34 @@ struct SDL_Surface;
 
 namespace ECursor
 {
-	enum ECursorTypes { ADVENTURE, COMBAT, DEFAULT, SPELLBOOK };
+enum ECursorTypes
+{
+	ADVENTURE,
+	COMBAT,
+	DEFAULT,
+	SPELLBOOK
+};
 
-	enum EBattleCursors { COMBAT_BLOCKED, COMBAT_MOVE, COMBAT_FLY, COMBAT_SHOOT,
-						COMBAT_HERO, COMBAT_QUERY, COMBAT_POINTER, 
-						//various attack frames
-						COMBAT_SHOOT_PENALTY = 15, COMBAT_SHOOT_CATAPULT, COMBAT_HEAL,
-						COMBAT_SACRIFICE, COMBAT_TELEPORT};
+enum EBattleCursors
+{
+	COMBAT_BLOCKED,
+	COMBAT_MOVE,
+	COMBAT_FLY,
+	COMBAT_SHOOT,
+	COMBAT_HERO,
+	COMBAT_QUERY,
+	COMBAT_POINTER,
+	//various attack frames
+	COMBAT_SHOOT_PENALTY = 15,
+	COMBAT_SHOOT_CATAPULT,
+	COMBAT_HEAL,
+	COMBAT_SACRIFICE,
+	COMBAT_TELEPORT
+};
 }
 
 /// handles mouse cursor
-class CCursorHandler 
+class CCursorHandler
 {
 	SDL_Surface * help;
 	CAnimImage * currentCursor;
@@ -36,8 +53,8 @@ class CCursorHandler
 	/// Restore original image below cursor
 	void drawRestored();
 	/// Simple draw cursor
-	void draw(SDL_Surface *to);
-	
+	void draw(SDL_Surface * to);
+
 public:
 	/// position of cursor
 	int xpos, ypos;
@@ -58,13 +75,13 @@ public:
 	 * @param image Image to replace cursor with or nullptr to use the normal
 	 * cursor. CursorHandler takes ownership of object
 	 */
-	void dragAndDropCursor (CAnimImage * image);
-	
+	void dragAndDropCursor(CAnimImage * image);
+
 	void render();
 
-	void shiftPos( int &x, int &y );
-	void hide() { showing=0; };
-	void show() { showing=1; };
+	void shiftPos(int & x, int & y);
+	void hide() { showing = 0; };
+	void show() { showing = 1; };
 
 	/// change cursor's positions to (x, y)
 	void cursorMove(const int & x, const int & y);

+ 62 - 55
client/gui/CGuiHandler.cpp

@@ -29,8 +29,8 @@ extern boost::mutex eventsM;
 CondSh<bool> CGuiHandler::terminate_cond(false);
 boost::thread_specific_ptr<bool> inGuiThread;
 
-SObjectConstruction::SObjectConstruction(CIntObject *obj)
-:myObj(obj)
+SObjectConstruction::SObjectConstruction(CIntObject * obj)
+	: myObj(obj)
 {
 	GH.createdObj.push_front(obj);
 	GH.captureChildren = true;
@@ -58,30 +58,30 @@ SSetCaptureState::~SSetCaptureState()
 	GH.defActionsDef = prevActions;
 }
 
-static inline void
-processList(const ui16 mask, const ui16 flag, std::list<CIntObject*> *lst, std::function<void (std::list<CIntObject*> *)> cb)
+static inline void processList(const ui16 mask, const ui16 flag, std::list<CIntObject *> * lst, std::function<void(std::list<CIntObject *> *)> cb)
 {
-	if (mask & flag)
+	if(mask & flag)
 		cb(lst);
 }
 
-void CGuiHandler::processLists(const ui16 activityFlag, std::function<void (std::list<CIntObject*> *)> cb)
+void CGuiHandler::processLists(const ui16 activityFlag, std::function<void(std::list<CIntObject *> *)> cb)
 {
-	processList(CIntObject::LCLICK,activityFlag,&lclickable,cb);
-	processList(CIntObject::RCLICK,activityFlag,&rclickable,cb);
-	processList(CIntObject::MCLICK,activityFlag,&mclickable,cb);
-	processList(CIntObject::HOVER,activityFlag,&hoverable,cb);
-	processList(CIntObject::MOVE,activityFlag,&motioninterested,cb);
-	processList(CIntObject::KEYBOARD,activityFlag,&keyinterested,cb);
-	processList(CIntObject::TIME,activityFlag,&timeinterested,cb);
-	processList(CIntObject::WHEEL,activityFlag,&wheelInterested,cb);
-	processList(CIntObject::DOUBLECLICK,activityFlag,&doubleClickInterested,cb);
-	processList(CIntObject::TEXTINPUT,activityFlag,&textInterested,cb);
+	processList(CIntObject::LCLICK, activityFlag, &lclickable, cb);
+	processList(CIntObject::RCLICK, activityFlag, &rclickable, cb);
+	processList(CIntObject::MCLICK, activityFlag, &mclickable, cb);
+	processList(CIntObject::HOVER, activityFlag, &hoverable, cb);
+	processList(CIntObject::MOVE, activityFlag, &motioninterested, cb);
+	processList(CIntObject::KEYBOARD, activityFlag, &keyinterested, cb);
+	processList(CIntObject::TIME, activityFlag, &timeinterested, cb);
+	processList(CIntObject::WHEEL, activityFlag, &wheelInterested, cb);
+	processList(CIntObject::DOUBLECLICK, activityFlag, &doubleClickInterested, cb);
+	processList(CIntObject::TEXTINPUT, activityFlag, &textInterested, cb);
 }
 
 void CGuiHandler::handleElementActivate(CIntObject * elem, ui16 activityFlag)
 {
-	processLists(activityFlag,[&](std::list<CIntObject*> * lst){
+	processLists(activityFlag, [&](std::list<CIntObject *> * lst)
+	{
 		lst->push_front(elem);
 	});
 	elem->active_m |= activityFlag;
@@ -89,15 +89,16 @@ void CGuiHandler::handleElementActivate(CIntObject * elem, ui16 activityFlag)
 
 void CGuiHandler::handleElementDeActivate(CIntObject * elem, ui16 activityFlag)
 {
-	processLists(activityFlag,[&](std::list<CIntObject*> * lst){
-		auto hlp = std::find(lst->begin(),lst->end(),elem);
+	processLists(activityFlag, [&](std::list<CIntObject *> * lst)
+	{
+		auto hlp = std::find(lst->begin(), lst->end(), elem);
 		assert(hlp != lst->end());
 		lst->erase(hlp);
 	});
 	elem->active_m &= ~activityFlag;
 }
 
-void CGuiHandler::popInt(IShowActivatable *top)
+void CGuiHandler::popInt(IShowActivatable * top)
 {
 	assert(listInt.front() == top);
 	top->deactivate();
@@ -108,7 +109,7 @@ void CGuiHandler::popInt(IShowActivatable *top)
 	totalRedraw();
 }
 
-void CGuiHandler::popIntTotally(IShowActivatable *top)
+void CGuiHandler::popIntTotally(IShowActivatable * top)
 {
 	assert(listInt.front() == top);
 	popInt(top);
@@ -116,7 +117,7 @@ void CGuiHandler::popIntTotally(IShowActivatable *top)
 	fakeMouseMove();
 }
 
-void CGuiHandler::pushInt(IShowActivatable *newInt)
+void CGuiHandler::pushInt(IShowActivatable * newInt)
 {
 	assert(newInt);
 	assert(boost::range::find(listInt, newInt) == listInt.end()); // do not add same object twice
@@ -134,11 +135,12 @@ void CGuiHandler::pushInt(IShowActivatable *newInt)
 
 void CGuiHandler::popInts(int howMany)
 {
-	if(!howMany) return; //senseless but who knows...
+	if(!howMany)
+		return; //senseless but who knows...
 
 	assert(listInt.size() >= howMany);
 	listInt.front()->deactivate();
-	for(int i=0; i < howMany; i++)
+	for(int i = 0; i < howMany; i++)
 	{
 		objsToBlit -= listInt.front();
 		delete listInt.front();
@@ -165,16 +167,17 @@ void CGuiHandler::totalRedraw()
 {
 	for(auto & elem : objsToBlit)
 		elem->showAll(screen2);
-	blitAt(screen2,0,0,screen);
+	blitAt(screen2, 0, 0, screen);
 }
 
 void CGuiHandler::updateTime()
 {
 	int ms = mainFPSmng->getElapsedMilliseconds();
-	std::list<CIntObject*> hlp = timeinterested;
-	for (auto & elem : hlp)
+	std::list<CIntObject *> hlp = timeinterested;
+	for(auto & elem : hlp)
 	{
-		if(!vstd::contains(timeinterested,elem)) continue;
+		if(!vstd::contains(timeinterested, elem))
+			continue;
 		(elem)->onTimer(ms);
 	}
 }
@@ -194,12 +197,12 @@ void CGuiHandler::handleEvents()
 	}
 }
 
-void CGuiHandler::handleEvent(SDL_Event *sEvent)
+void CGuiHandler::handleEvent(SDL_Event * sEvent)
 {
 	current = sEvent;
 	bool prev;
 
-	if (sEvent->type==SDL_KEYDOWN || sEvent->type==SDL_KEYUP)
+	if(sEvent->type == SDL_KEYDOWN || sEvent->type == SDL_KEYUP)
 	{
 		SDL_KeyboardEvent key = sEvent->key;
 		if(sEvent->type == SDL_KEYDOWN && key.keysym.sym >= SDLK_F1 && key.keysym.sym <= SDLK_F15 && settings["session"]["spectate"].Bool())
@@ -251,7 +254,7 @@ void CGuiHandler::handleEvent(SDL_Event *sEvent)
 		}
 
 		bool keysCaptured = false;
-		for(auto i=keyinterested.begin(); i != keyinterested.end() && current; i++)
+		for(auto i = keyinterested.begin(); i != keyinterested.end() && current; i++)
 		{
 			if((*i)->captureThisEvent(key))
 			{
@@ -260,12 +263,12 @@ void CGuiHandler::handleEvent(SDL_Event *sEvent)
 			}
 		}
 
-		std::list<CIntObject*> miCopy = keyinterested;
-		for(auto i=miCopy.begin(); i != miCopy.end() && current; i++)
-			if(vstd::contains(keyinterested,*i) && (!keysCaptured || (*i)->captureThisEvent(key)))
+		std::list<CIntObject *> miCopy = keyinterested;
+		for(auto i = miCopy.begin(); i != miCopy.end() && current; i++)
+			if(vstd::contains(keyinterested, *i) && (!keysCaptured || (*i)->captureThisEvent(key)))
 				(**i).keyPressed(key);
 	}
-	else if(sEvent->type==SDL_MOUSEMOTION)
+	else if(sEvent->type == SDL_MOUSEMOTION)
 	{
 		CCS->curh->cursorMove(sEvent->motion.x, sEvent->motion.y);
 		handleMouseMotion(sEvent);
@@ -277,10 +280,11 @@ void CGuiHandler::handleEvent(SDL_Event *sEvent)
 		case SDL_BUTTON_LEFT:
 			if(lastClick == sEvent->motion && (SDL_GetTicks() - lastClickTime) < 300)
 			{
-				std::list<CIntObject*> hlp = doubleClickInterested;
+				std::list<CIntObject *> hlp = doubleClickInterested;
 				for(auto i = hlp.begin(); i != hlp.end() && current; i++)
 				{
-					if(!vstd::contains(doubleClickInterested, *i)) continue;
+					if(!vstd::contains(doubleClickInterested, *i))
+						continue;
 					if(isItIn(&(*i)->pos, sEvent->motion.x, sEvent->motion.y))
 					{
 						(*i)->onDoubleClick();
@@ -304,12 +308,13 @@ void CGuiHandler::handleEvent(SDL_Event *sEvent)
 			break;
 		}
 	}
-	else if (sEvent->type == SDL_MOUSEWHEEL)
+	else if(sEvent->type == SDL_MOUSEWHEEL)
 	{
-		std::list<CIntObject*> hlp = wheelInterested;
-		for(auto i=hlp.begin(); i != hlp.end() && current; i++)
+		std::list<CIntObject *> hlp = wheelInterested;
+		for(auto i = hlp.begin(); i != hlp.end() && current; i++)
 		{
-			if(!vstd::contains(wheelInterested,*i)) continue;
+			if(!vstd::contains(wheelInterested, *i))
+				continue;
 			// SDL doesn't have the proper values for mouse positions on SDL_MOUSEWHEEL, refetch them
 			int x = 0, y = 0;
 			SDL_GetMouseState(&x, &y);
@@ -354,7 +359,8 @@ void CGuiHandler::handleMouseButtonClick(CIntObjectList & interestedObjs, EIntOb
 	auto hlp = interestedObjs;
 	for(auto i = hlp.begin(); i != hlp.end() && current; i++)
 	{
-		if(!vstd::contains(interestedObjs, *i)) continue;
+		if(!vstd::contains(interestedObjs, *i))
+			continue;
 
 		auto prev = (*i)->mouseState(btn);
 		if(!isPressed)
@@ -370,18 +376,18 @@ void CGuiHandler::handleMouseButtonClick(CIntObjectList & interestedObjs, EIntOb
 	}
 }
 
-void CGuiHandler::handleMouseMotion(SDL_Event *sEvent)
+void CGuiHandler::handleMouseMotion(SDL_Event * sEvent)
 {
 	//sending active, hovered hoverable objects hover() call
-	std::vector<CIntObject*> hlp;
+	std::vector<CIntObject *> hlp;
 	for(auto & elem : hoverable)
 	{
-		if (isItIn(&(elem)->pos,sEvent->motion.x,sEvent->motion.y))
+		if(isItIn(&(elem)->pos, sEvent->motion.x, sEvent->motion.y))
 		{
-			if (!(elem)->hovered)
+			if(!(elem)->hovered)
 				hlp.push_back((elem));
 		}
-		else if ((elem)->hovered)
+		else if((elem)->hovered)
 		{
 			(elem)->hover(false);
 			(elem)->hovered = false;
@@ -400,7 +406,7 @@ void CGuiHandler::simpleRedraw()
 {
 	//update only top interface and draw background
 	if(objsToBlit.size() > 1)
-		blitAt(screen2,0,0,screen); //blit background
+		blitAt(screen2, 0, 0, screen); //blit background
 	if(!objsToBlit.empty())
 		objsToBlit.back()->show(screen); //blit active interface/window
 }
@@ -408,7 +414,7 @@ void CGuiHandler::simpleRedraw()
 void CGuiHandler::handleMoveInterested(const SDL_MouseMotionEvent & motion)
 {
 	//sending active, MotionInterested objects mouseMoved() call
-	std::list<CIntObject*> miCopy = motioninterested;
+	std::list<CIntObject *> miCopy = motioninterested;
 	for(auto & elem : miCopy)
 	{
 		if(elem->strongInterest || isItInOrLowerBounds(&elem->pos, motion.x, motion.y)) //checking lower bounds fixes bug #2476
@@ -454,7 +460,7 @@ void CGuiHandler::renderFrame()
 		if(nullptr != curInt)
 			curInt->update();
 
-		if (settings["general"]["showfps"].Bool())
+		if(settings["general"]["showfps"].Bool())
 			drawFPSCounter();
 
 		// draw the mouse cursor and update the screen
@@ -471,7 +477,7 @@ void CGuiHandler::renderFrame()
 
 
 CGuiHandler::CGuiHandler()
-	: lastClick(-500, -500),lastClickTime(0), defActionsDef(0), captureChildren(false)
+	: lastClick(-500, -500), lastClickTime(0), defActionsDef(0), captureChildren(false)
 {
 	curInt = nullptr;
 	current = nullptr;
@@ -524,7 +530,8 @@ SDL_Keycode CGuiHandler::arrowToNum(SDL_Keycode key)
 SDL_Keycode CGuiHandler::numToDigit(SDL_Keycode key)
 {
 
-#define REMOVE_KP(keyName) case SDLK_KP_ ## keyName : return SDLK_ ## keyName;
+#define REMOVE_KP(keyName) case SDLK_KP_ ## keyName: \
+	return SDLK_ ## keyName;
 	switch(key)
 	{
 		REMOVE_KP(0)
@@ -576,7 +583,7 @@ void CGuiHandler::pushSDLEvent(int type, int usercode)
 {
 	SDL_Event event;
 	event.type = type;
-	event.user.code = usercode;	// not necessarily used
+	event.user.code = usercode; // not necessarily used
 	SDL_PushEvent(&event);
 }
 
@@ -602,7 +609,7 @@ void CFramerateManager::framerateDelay()
 	timeElapsed = currentTicks - lastticks;
 
 	// FPS is higher than it should be, then wait some time
-	if (timeElapsed < rateticks)
+	if(timeElapsed < rateticks)
 	{
 		SDL_Delay(ceil(this->rateticks) - timeElapsed);
 	}
@@ -613,7 +620,7 @@ void CFramerateManager::framerateDelay()
 	if(accumulatedFrames >= 100)
 	{
 		//about 2 second should be passed
-		fps = ceil(1000.0 / (accumulatedTime/accumulatedFrames));
+		fps = ceil(1000.0 / (accumulatedTime / accumulatedFrames));
 		accumulatedTime = 0;
 		accumulatedFrames = 0;
 	}

+ 28 - 26
client/gui/CGuiHandler.h

@@ -20,7 +20,7 @@ class IUpdateable;
 class IShowActivatable;
 class IShowable;
 enum class EIntObjMouseBtnType;
-template <typename T> struct CondSh;
+template<typename T> struct CondSh;
 
 // A fps manager which holds game updates at a constant rate
 class CFramerateManager
@@ -29,7 +29,8 @@ private:
 	double rateticks;
 	ui32 lastticks, timeElapsed;
 	int rate;
-	ui32 accumulatedTime,accumulatedFrames;
+	ui32 accumulatedTime, accumulatedFrames;
+
 public:
 	int fps; // the actual fps value
 
@@ -48,33 +49,34 @@ public:
 	CGStatusBar * statusbar;
 
 private:
-	typedef std::list<CIntObject*> CIntObjectList;
+	typedef std::list<CIntObject *> CIntObjectList;
 
 	//active GUI elements (listening for events
 	CIntObjectList lclickable,
-				   rclickable,
-				   mclickable,
-				   hoverable,
-				   keyinterested,
-				   motioninterested,
-	               timeinterested,
-	               wheelInterested,
-	               doubleClickInterested,
-	               textInterested;
+		       rclickable,
+		       mclickable,
+		       hoverable,
+		       keyinterested,
+		       motioninterested,
+		       timeinterested,
+		       wheelInterested,
+		       doubleClickInterested,
+		       textInterested;
 
 
 	void handleMouseButtonClick(CIntObjectList & interestedObjs, EIntObjMouseBtnType btn, bool isPressed);
-	void processLists(const ui16 activityFlag, std::function<void (std::list<CIntObject*> *)> cb);
+	void processLists(const ui16 activityFlag, std::function<void(std::list<CIntObject *> *)> cb);
+
 public:
 	void handleElementActivate(CIntObject * elem, ui16 activityFlag);
 	void handleElementDeActivate(CIntObject * elem, ui16 activityFlag);
 
 public:
 	//objs to blit
-	std::vector<IShowable*> objsToBlit;
+	std::vector<IShowable *> objsToBlit;
 
 	SDL_Event * current; //current event - can be set to nullptr to stop handling event
-	IUpdateable *curInt;
+	IUpdateable * curInt;
 
 	Point lastClick;
 	unsigned lastClickTime;
@@ -91,23 +93,23 @@ public:
 	void totalRedraw(); //forces total redraw (using showAll), sets a flag, method gets called at the end of the rendering
 	void simpleRedraw(); //update only top interface and draw background from buffer, sets a flag, method gets called at the end of the rendering
 
-	void popInt(IShowActivatable *top); //removes given interface from the top and activates next
-	void popIntTotally(IShowActivatable *top); //deactivates, deletes, removes given interface from the top and activates next
-	void pushInt(IShowActivatable *newInt); //deactivate old top interface, activates this one and pushes to the top
+	void popInt(IShowActivatable * top); //removes given interface from the top and activates next
+	void popIntTotally(IShowActivatable * top); //deactivates, deletes, removes given interface from the top and activates next
+	void pushInt(IShowActivatable * newInt); //deactivate old top interface, activates this one and pushes to the top
 	void popInts(int howMany); //pops one or more interfaces - deactivates top, deletes and removes given number of interfaces, activates new front
-	IShowActivatable *topInt(); //returns top interface
+	IShowActivatable * topInt(); //returns top interface
 
 	void updateTime(); //handles timeInterested
 	void handleEvents(); //takes events from queue and calls interested objects
-	void handleEvent(SDL_Event *sEvent);
-	void handleMouseMotion(SDL_Event *sEvent);
-	void handleMoveInterested( const SDL_MouseMotionEvent & motion );
+	void handleEvent(SDL_Event * sEvent);
+	void handleMouseMotion(SDL_Event * sEvent);
+	void handleMoveInterested(const SDL_MouseMotionEvent & motion);
 	void fakeMouseMove();
 	void breakEventHandling(); //current event won't be propagated anymore
 	void drawFPSCounter(); // draws the FPS to the upper left corner of the screen
 
 	static SDL_Keycode arrowToNum(SDL_Keycode key); //converts arrow key to according numpad key
-	static SDL_Keycode numToDigit(SDL_Keycode key);//converts numpad digit key to normal digit key
+	static SDL_Keycode numToDigit(SDL_Keycode key); //converts numpad digit key to normal digit key
 	static bool isNumKey(SDL_Keycode key, bool number = true); //checks if key is on numpad (numbers - check only for numpad digits)
 	static bool isArrowKey(SDL_Keycode key);
 	static bool amIGuiThread();
@@ -118,15 +120,15 @@ public:
 
 extern CGuiHandler GH; //global gui handler
 
-template <typename T> void pushIntT()
+template<typename T> void pushIntT()
 {
 	GH.pushInt(new T());
 }
 
 struct SObjectConstruction
 {
-	CIntObject *myObj;
-	SObjectConstruction(CIntObject *obj);
+	CIntObject * myObj;
+	SObjectConstruction(CIntObject * obj);
 	~SObjectConstruction();
 };
 

+ 41 - 44
client/gui/CIntObject.cpp

@@ -19,11 +19,8 @@ IShowActivatable::IShowActivatable()
 	type = 0;
 }
 
-CIntObject::CIntObject(int used_, Point pos_):
-	parent_m(nullptr),
-	active_m(0),
-	parent(parent_m),
-	active(active_m)
+CIntObject::CIntObject(int used_, Point pos_)
+	: parent_m(nullptr), active_m(0), parent(parent_m), active(active_m)
 {
 	hovered = captureAllKeys = strongInterest = false;
 	toNextTick = timerDelay = 0;
@@ -42,7 +39,7 @@ CIntObject::CIntObject(int used_, Point pos_):
 
 void CIntObject::setTimer(int msToTrigger)
 {
-	if (!(active & TIME))
+	if(!(active & TIME))
 		activate(TIME);
 	toNextTick = timerDelay = msToTrigger;
 	used |= TIME;
@@ -51,7 +48,7 @@ void CIntObject::setTimer(int msToTrigger)
 void CIntObject::onTimer(int timePassed)
 {
 	toNextTick -= timePassed;
-	if (toNextTick < 0)
+	if(toNextTick < 0)
 	{
 		toNextTick += timerDelay;
 		tick();
@@ -79,9 +76,9 @@ void CIntObject::showAll(SDL_Surface * to)
 
 void CIntObject::activate()
 {
-	if (active_m)
+	if(active_m)
 	{
-		if ((used | GENERAL) == active_m)
+		if((used | GENERAL) == active_m)
 			return;
 		else
 		{
@@ -106,10 +103,10 @@ void CIntObject::activate(ui16 what)
 
 void CIntObject::deactivate()
 {
-	if (!active_m)
+	if(!active_m)
 		return;
 
-	active_m &= ~ GENERAL;
+	active_m &= ~GENERAL;
 	deactivate(active_m);
 
 	assert(!active_m);
@@ -127,12 +124,12 @@ void CIntObject::deactivate(ui16 what)
 
 CIntObject::~CIntObject()
 {
-	if (active_m)
+	if(active_m)
 		deactivate();
 
 	if(defActions & DISPOSE)
 	{
-		while (!children.empty())
+		while(!children.empty())
 			if(children.front()->recActions & DISPOSE)
 				delete children.front();
 			else
@@ -172,44 +169,44 @@ void CIntObject::printAtRightLoc(const std::string & text, int x, int y, EFonts
 
 void CIntObject::printAtMiddleLoc(const std::string & text, int x, int y, EFonts font, SDL_Color kolor, SDL_Surface * dst)
 {
-	printAtMiddleLoc(text, Point(x,y), font, kolor, dst);
+	printAtMiddleLoc(text, Point(x, y), font, kolor, dst);
 }
 
-void CIntObject::printAtMiddleLoc(const std::string & text, const Point &p, EFonts font, SDL_Color kolor, SDL_Surface * dst)
+void CIntObject::printAtMiddleLoc(const std::string & text, const Point & p, EFonts font, SDL_Color kolor, SDL_Surface * dst)
 {
 	graphics->fonts[font]->renderTextCenter(dst, text, kolor, pos.topLeft() + p);
 }
 
-void CIntObject::blitAtLoc( SDL_Surface * src, int x, int y, SDL_Surface * dst )
+void CIntObject::blitAtLoc(SDL_Surface * src, int x, int y, SDL_Surface * dst)
 {
 	blitAt(src, pos.x + x, pos.y + y, dst);
 }
 
-void CIntObject::blitAtLoc(SDL_Surface * src, const Point &p, SDL_Surface * dst)
+void CIntObject::blitAtLoc(SDL_Surface * src, const Point & p, SDL_Surface * dst)
 {
 	blitAtLoc(src, p.x, p.y, dst);
 }
 
-void CIntObject::printAtMiddleWBLoc( const std::string & text, int x, int y, EFonts font, int charpr, SDL_Color kolor, SDL_Surface * dst)
+void CIntObject::printAtMiddleWBLoc(const std::string & text, int x, int y, EFonts font, int charpr, SDL_Color kolor, SDL_Surface * dst)
 {
 	graphics->fonts[font]->renderTextLinesCenter(dst, CMessage::breakText(text, charpr, font), kolor, Point(pos.x + x, pos.y + y));
 }
 
-void CIntObject::printToLoc( const std::string & text, int x, int y, EFonts font, SDL_Color kolor, SDL_Surface * dst )
+void CIntObject::printToLoc(const std::string & text, int x, int y, EFonts font, SDL_Color kolor, SDL_Surface * dst)
 {
 	graphics->fonts[font]->renderTextRight(dst, text, kolor, Point(pos.x + x, pos.y + y));
 }
 
 void CIntObject::addUsedEvents(ui16 newActions)
 {
-	if (active_m)
+	if(active_m)
 		activate(~used & newActions);
 	used |= newActions;
 }
 
 void CIntObject::removeUsedEvents(ui16 newActions)
 {
-	if (active_m)
+	if(active_m)
 		deactivate(used & newActions);
 	used &= ~newActions;
 }
@@ -230,12 +227,12 @@ void CIntObject::enable()
 	recActions = 255;
 }
 
-bool CIntObject::isItInLoc( const SDL_Rect &rect, int x, int y )
+bool CIntObject::isItInLoc(const SDL_Rect & rect, int x, int y)
 {
 	return isItIn(&rect, x - pos.x, y - pos.y);
 }
 
-bool CIntObject::isItInLoc( const SDL_Rect &rect, const Point &p )
+bool CIntObject::isItInLoc(const SDL_Rect & rect, const Point & p)
 {
 	return isItIn(&rect, p.x - pos.x, p.y - pos.y);
 }
@@ -247,7 +244,7 @@ void CIntObject::fitToScreen(int borderWidth, bool propagate)
 	vstd::amax(newPos.y, borderWidth);
 	vstd::amin(newPos.x, screen->w - borderWidth - pos.w);
 	vstd::amin(newPos.y, screen->h - borderWidth - pos.h);
-	if (newPos != pos.topLeft())
+	if(newPos != pos.topLeft())
 		moveTo(newPos, propagate);
 }
 
@@ -267,11 +264,11 @@ void CIntObject::moveTo(const Point & p, bool propagate)
 
 void CIntObject::addChild(CIntObject * child, bool adjustPosition)
 {
-	if (vstd::contains(children, child))
+	if(vstd::contains(children, child))
 	{
 		return;
 	}
-	if (child->parent_m)
+	if(child->parent_m)
 	{
 		child->parent_m->removeChild(child, adjustPosition);
 	}
@@ -280,15 +277,15 @@ void CIntObject::addChild(CIntObject * child, bool adjustPosition)
 	if(adjustPosition)
 		child->pos += pos;
 
-	if (!active && child->active)
+	if(!active && child->active)
 		child->deactivate();
-	if (active && !child->active)
+	if(active && !child->active)
 		child->activate();
 }
 
 void CIntObject::removeChild(CIntObject * child, bool adjustPosition)
 {
-	if (!child)
+	if(!child)
 		return;
 
 	assert(vstd::contains(children, child));
@@ -299,7 +296,7 @@ void CIntObject::removeChild(CIntObject * child, bool adjustPosition)
 		child->pos -= pos;
 }
 
-void CIntObject::drawBorderLoc(SDL_Surface * sur, const Rect &r, const int3 &color)
+void CIntObject::drawBorderLoc(SDL_Surface * sur, const Rect & r, const int3 & color)
 {
 	CSDL_Ext::drawBorder(sur, r + pos, color);
 }
@@ -308,9 +305,9 @@ void CIntObject::redraw()
 {
 	//currently most of calls come from active objects so this check won't affect them
 	//it should fix glitches when called by inactive elements located below active window
-	if (active)
+	if(active)
 	{
-		if (parent_m && (type & REDRAW_PARENT))
+		if(parent_m && (type & REDRAW_PARENT))
 		{
 			parent_m->redraw();
 		}
@@ -323,23 +320,23 @@ void CIntObject::redraw()
 	}
 }
 
-const Rect & CIntObject::center( const Rect &r, bool propagate )
+const Rect & CIntObject::center(const Rect & r, bool propagate)
 {
 	pos.w = r.w;
 	pos.h = r.h;
-	return center(Point(screen->w/2, screen->h/2), propagate);
+	return center(Point(screen->w / 2, screen->h / 2), propagate);
 }
 
-const Rect & CIntObject::center( bool propagate )
+const Rect & CIntObject::center(bool propagate)
 {
 	return center(pos, propagate);
 }
 
 const Rect & CIntObject::center(const Point & p, bool propagate)
 {
-	moveBy(Point(p.x - pos.w/2 - pos.x,
-		p.y - pos.h/2 - pos.y),
-		propagate);
+	moveBy(Point(p.x - pos.w / 2 - pos.x,
+		     p.y - pos.h / 2 - pos.y),
+	       propagate);
 	return pos;
 }
 
@@ -353,22 +350,22 @@ CKeyShortcut::CKeyShortcut()
 
 CKeyShortcut::CKeyShortcut(int key)
 {
-	if (key != SDLK_UNKNOWN)
+	if(key != SDLK_UNKNOWN)
 		assignedKeys.insert(key);
 }
 
 CKeyShortcut::CKeyShortcut(std::set<int> Keys)
-	:assignedKeys(Keys)
+	: assignedKeys(Keys)
 {}
 
 void CKeyShortcut::keyPressed(const SDL_KeyboardEvent & key)
 {
-	if(vstd::contains(assignedKeys,key.keysym.sym)
-	 || vstd::contains(assignedKeys, CGuiHandler::numToDigit(key.keysym.sym)))
+	if(vstd::contains(assignedKeys, key.keysym.sym)
+	   || vstd::contains(assignedKeys, CGuiHandler::numToDigit(key.keysym.sym)))
 	{
-		bool prev = mouseState(EIntObjMouseBtnType::LEFT);		
+		bool prev = mouseState(EIntObjMouseBtnType::LEFT);
 		updateMouseState(EIntObjMouseBtnType::LEFT, key.state == SDL_PRESSED);
 		clickLeft(key.state == SDL_PRESSED, prev);
-		
+
 	}
 }

+ 65 - 28
client/gui/CIntObject.h

@@ -25,15 +25,15 @@ using boost::logic::tribool;
 class IActivatable
 {
 public:
-	virtual void activate()=0;
-	virtual void deactivate()=0;
+	virtual void activate() = 0;
+	virtual void deactivate() = 0;
 	virtual ~IActivatable(){};
 };
 
 class IUpdateable
 {
 public:
-	virtual void update()=0;
+	virtual void update() = 0;
 	virtual ~IUpdateable(){};
 };
 
@@ -41,7 +41,7 @@ public:
 class IShowable
 {
 public:
-	virtual void redraw()=0;
+	virtual void redraw() = 0;
 	virtual void show(SDL_Surface * to) = 0;
 	virtual void showAll(SDL_Surface * to)
 	{
@@ -54,20 +54,29 @@ class IShowActivatable : public IShowable, public IActivatable
 {
 public:
 	//redraw parent flag - this int may be semi-transparent and require redraw of parent window
-	enum {BLOCK_ADV_HOTKEYS = 2, REDRAW_PARENT=8};
+	enum
+	{
+		BLOCK_ADV_HOTKEYS = 2,
+		REDRAW_PARENT=8
+	};
 	int type; //bin flags using etype
 	IShowActivatable();
 	virtual ~IShowActivatable(){};
 };
 
-enum class EIntObjMouseBtnType { LEFT, MIDDLE, RIGHT };
+enum class EIntObjMouseBtnType
+{
+	LEFT,
+	MIDDLE,
+	RIGHT
+};
 //typedef ui16 ActivityFlag;
 
 // Base UI element
 class CIntObject : public IShowActivatable //interface object
 {
 
-	ui16 used;//change via addUsed() or delUsed
+	ui16 used; //change via addUsed() or delUsed
 
 	//time handling
 	int toNextTick;
@@ -78,8 +87,9 @@ class CIntObject : public IShowActivatable //interface object
 	void onTimer(int timePassed);
 
 	//non-const versions of fields to allow changing them in CIntObject
-	CIntObject *parent_m; //parent object
+	CIntObject * parent_m; //parent object
 	ui16 active_m;
+
 protected:
 	//activate or deactivate specific action (LCLICK, RCLICK...)
 	void activate(ui16 what);
@@ -103,7 +113,7 @@ public:
 	/// position of object on the screen. Please do not modify this anywhere but in constructor - use moveBy\moveTo instead
 	/*const*/ Rect pos;
 
-	CIntObject(int used=0, Point offset=Point());
+	CIntObject(int used = 0, Point offset = Point());
 	virtual ~CIntObject();
 
 	void updateMouseState(EIntObjMouseBtnType btn, bool state) { currentMouseState[btn] = state; }
@@ -115,8 +125,8 @@ public:
 	virtual void clickMiddle(tribool down, bool previousState) {}
 
 	//hover handling
-	/*const*/ bool hovered;  //for determining if object is hovered
-	virtual void hover (bool on){}
+	/*const*/ bool hovered; //for determining if object is hovered
+	virtual void hover(bool on){}
 
 	//keyboard handling
 	bool captureAllKeys; //if true, only this object should get info about pressed keys
@@ -128,10 +138,10 @@ public:
 
 	//mouse movement handling
 	bool strongInterest; //if true - report all mouse movements, if not - only when hovered
-	virtual void mouseMoved (const SDL_MouseMotionEvent & sEvent){}
+	virtual void mouseMoved(const SDL_MouseMotionEvent & sEvent){}
 
 	//time handling
-	void setTimer(int msToTrigger);//set timer delay and activate timer if needed.
+	void setTimer(int msToTrigger); //set timer delay and activate timer if needed.
 	virtual void tick(){}
 
 	//mouse wheel
@@ -140,12 +150,34 @@ public:
 	//double click
 	virtual void onDoubleClick(){}
 
-	enum {LCLICK=1, RCLICK=2, HOVER=4, MOVE=8, KEYBOARD=16, TIME=32, GENERAL=64, WHEEL=128, DOUBLECLICK=256, TEXTINPUT=512, MCLICK=1024, ALL=0xffff};
+	enum
+	{
+		LCLICK=1,
+		RCLICK=2,
+		HOVER=4,
+		MOVE=8,
+		KEYBOARD=16,
+		TIME=32,
+		GENERAL=64,
+		WHEEL=128,
+		DOUBLECLICK=256,
+		TEXTINPUT=512,
+		MCLICK=1024,
+		ALL=0xffff
+	};
 	const ui16 & active;
 	void addUsedEvents(ui16 newActions);
 	void removeUsedEvents(ui16 newActions);
 
-	enum {ACTIVATE=1, DEACTIVATE=2, UPDATE=4, SHOWALL=8, DISPOSE=16, SHARE_POS=32};
+	enum
+	{
+		ACTIVATE=1,
+		DEACTIVATE=2,
+		UPDATE=4,
+		SHOWALL=8,
+		DISPOSE=16,
+		SHARE_POS=32
+	};
 	ui8 defActions; //which calls will be tried to be redirected to children
 	ui8 recActions; //which calls we allow to receive from parent
 
@@ -164,19 +196,24 @@ public:
 	//request complete redraw of this object
 	void redraw() override;
 
-	enum EAlignment {TOPLEFT, CENTER, BOTTOMRIGHT};
-
-	bool isItInLoc(const SDL_Rect &rect, int x, int y);
-	bool isItInLoc(const SDL_Rect &rect, const Point &p);
-	const Rect & center(const Rect &r, bool propagate = true); //sets pos so that r will be in the center of screen, assigns sizes of r to pos, returns new position
-	const Rect & center(const Point &p, bool propagate = true);  //moves object so that point p will be in its center
+	enum EAlignment
+	{
+		TOPLEFT,
+		CENTER,
+		BOTTOMRIGHT
+	};
+
+	bool isItInLoc(const SDL_Rect & rect, int x, int y);
+	bool isItInLoc(const SDL_Rect & rect, const Point & p);
+	const Rect & center(const Rect & r, bool propagate = true); //sets pos so that r will be in the center of screen, assigns sizes of r to pos, returns new position
+	const Rect & center(const Point & p, bool propagate = true); //moves object so that point p will be in its center
 	const Rect & center(bool propagate = true); //centers when pos.w and pos.h are set, returns new position
 	void fitToScreen(int borderWidth, bool propagate = true); //moves window to fit into screen
-	void moveBy(const Point &p, bool propagate = true);
-	void moveTo(const Point &p, bool propagate = true);//move this to new position, coordinates are absolute (0,0 is topleft screen corner)
+	void moveBy(const Point & p, bool propagate = true);
+	void moveTo(const Point & p, bool propagate = true); //move this to new position, coordinates are absolute (0,0 is topleft screen corner)
 
-	void addChild(CIntObject *child, bool adjustPosition = false);
-	void removeChild(CIntObject *child, bool adjustPosition = false);
+	void addChild(CIntObject * child, bool adjustPosition = false);
+	void removeChild(CIntObject * child, bool adjustPosition = false);
 	//delChild - not needed, use normal "delete child" instead
 	//delChildNull - not needed, use "vstd::clear_pointer(child)" instead
 
@@ -184,18 +221,18 @@ public:
  * Functions that should be used only by specific GUI elements. Don't use them unless you really know why they are here
  */
 	//wrappers for CSDL_Ext methods. This versions use coordinates relative to pos
-	void drawBorderLoc(SDL_Surface * sur, const Rect &r, const int3 &color);
+	void drawBorderLoc(SDL_Surface * sur, const Rect & r, const int3 & color);
 	//functions for printing text. Use CLabel where possible instead
 	void printAtLoc(const std::string & text, int x, int y, EFonts font, SDL_Color color, SDL_Surface * dst);
 	void printToLoc(const std::string & text, int x, int y, EFonts font, SDL_Color color, SDL_Surface * dst);
 	void printAtRightLoc(const std::string & text, int x, int y, EFonts font, SDL_Color color, SDL_Surface * dst);
 	void printAtMiddleLoc(const std::string & text, int x, int y, EFonts font, SDL_Color color, SDL_Surface * dst);
-	void printAtMiddleLoc(const std::string & text, const Point &p, EFonts font, SDL_Color color, SDL_Surface * dst);
+	void printAtMiddleLoc(const std::string & text, const Point & p, EFonts font, SDL_Color color, SDL_Surface * dst);
 	void printAtMiddleWBLoc(const std::string & text, int x, int y, EFonts font, int charsPerLine, SDL_Color color, SDL_Surface * dst);
 
 	//image blitting. If possible use CPicture or CAnimImage instead
 	void blitAtLoc(SDL_Surface * src, int x, int y, SDL_Surface * dst);
-	void blitAtLoc(SDL_Surface * src, const Point &p, SDL_Surface * dst);
+	void blitAtLoc(SDL_Surface * src, const Point & p, SDL_Surface * dst);
 
 	friend class CGuiHandler;
 };

+ 58 - 60
client/gui/Fonts.cpp

@@ -22,7 +22,7 @@ size_t IFont::getStringWidth(const std::string & data) const
 {
 	size_t width = 0;
 
-	for(size_t i=0; i<data.size(); i += Unicode::getCharacterSize(data[i]))
+	for(size_t i = 0; i < data.size(); i += Unicode::getCharacterSize(data[i]))
 	{
 		width += getGlyphWidth(data.data() + i);
 	}
@@ -72,7 +72,7 @@ void IFont::renderTextLinesRight(SDL_Surface * surface, const std::vector<std::s
 void IFont::renderTextLinesCenter(SDL_Surface * surface, const std::vector<std::string> & data, const SDL_Color & color, const Point & pos) const
 {
 	Point currPos = pos;
-	currPos.y -= data.size() * getLineHeight()/2;
+	currPos.y -= data.size() * getLineHeight() / 2;
 
 	for(const std::string & line : data)
 	{
@@ -87,16 +87,20 @@ std::array<CBitmapFont::BitmapChar, CBitmapFont::totalChars> CBitmapFont::loadCh
 
 	size_t offset = 32;
 
-	for (auto & elem : ret)
+	for(auto & elem : ret)
 	{
-		elem.leftOffset =  read_le_u32(data.first.get() + offset); offset+=4;
-		elem.width =       read_le_u32(data.first.get() + offset); offset+=4;
-		elem.rightOffset = read_le_u32(data.first.get() + offset); offset+=4;
+		elem.leftOffset = read_le_u32(data.first.get() + offset);
+		offset += 4;
+		elem.width = read_le_u32(data.first.get() + offset);
+		offset += 4;
+		elem.rightOffset = read_le_u32(data.first.get() + offset);
+		offset += 4;
 	}
 
-	for (auto & elem : ret)
+	for(auto & elem : ret)
 	{
-		int pixelOffset =  read_le_u32(data.first.get() + offset); offset+=4;
+		int pixelOffset = read_le_u32(data.first.get() + offset);
+		offset += 4;
 		elem.pixels = data.first.get() + 4128 + pixelOffset;
 
 		assert(pixelOffset + 4128 < data.second);
@@ -104,10 +108,8 @@ std::array<CBitmapFont::BitmapChar, CBitmapFont::totalChars> CBitmapFont::loadCh
 	return ret;
 }
 
-CBitmapFont::CBitmapFont(const std::string & filename):
-    data(CResourceHandler::get()->load(ResourceID("data/" + filename, EResType::BMP_FONT))->readAll()),
-    chars(loadChars()),
-    height(data.first.get()[5])
+CBitmapFont::CBitmapFont(const std::string & filename)
+	: data(CResourceHandler::get()->load(ResourceID("data/" + filename, EResType::BMP_FONT))->readAll()), chars(loadChars()), height(data.first.get()[5])
 {}
 
 size_t CBitmapFont::getLineHeight() const
@@ -119,7 +121,7 @@ size_t CBitmapFont::getGlyphWidth(const char * data) const
 {
 	std::string localChar = Unicode::fromUnicode(std::string(data, Unicode::getCharacterSize(data[0])));
 
-	if (localChar.size() == 1)
+	if(localChar.size() == 1)
 	{
 		const BitmapChar & ch = chars[ui8(localChar[0])];
 		return ch.leftOffset + ch.width + ch.rightOffset;
@@ -127,7 +129,7 @@ size_t CBitmapFont::getGlyphWidth(const char * data) const
 	return 0;
 }
 
-void CBitmapFont::renderCharacter(SDL_Surface * surface, const BitmapChar & character, const SDL_Color & color, int &posX, int &posY) const
+void CBitmapFont::renderCharacter(SDL_Surface * surface, const BitmapChar & character, const SDL_Color & color, int & posX, int & posY) const
 {
 	Rect clipRect;
 	SDL_GetClipRect(surface, &clipRect);
@@ -140,26 +142,26 @@ void CBitmapFont::renderCharacter(SDL_Surface * surface, const BitmapChar & char
 
 	// start of line, may differ from 0 due to end of surface or clipped surface
 	int lineBegin = std::max<int>(0, clipRect.y - posY);
-	int lineEnd   = std::min<int>(height, clipRect.y + clipRect.h - posY - 1);
+	int lineEnd = std::min<int>(height, clipRect.y + clipRect.h - posY - 1);
 
 	// start end end of each row, may differ from 0
 	int rowBegin = std::max<int>(0, clipRect.x - posX);
-	int rowEnd   = std::min<int>(character.width, clipRect.x + clipRect.w - posX - 1);
+	int rowEnd = std::min<int>(character.width, clipRect.x + clipRect.w - posX - 1);
 
 	//for each line in symbol
-	for(int dy = lineBegin; dy <lineEnd; dy++)
+	for(int dy = lineBegin; dy < lineEnd; dy++)
 	{
-		Uint8 *dstLine = (Uint8*)surface->pixels;
-		Uint8 *srcLine = character.pixels;
+		Uint8 * dstLine = (Uint8 *)surface->pixels;
+		Uint8 * srcLine = character.pixels;
 
 		// shift source\destination pixels to current position
-		dstLine += (posY+dy) * surface->pitch + posX * bpp;
+		dstLine += (posY + dy) * surface->pitch + posX * bpp;
 		srcLine += dy * character.width;
 
 		//for each column in line
 		for(int dx = rowBegin; dx < rowEnd; dx++)
 		{
-			Uint8* dstPixel = dstLine + dx*bpp;
+			Uint8 * dstPixel = dstLine + dx * bpp;
 			switch(srcLine[dx])
 			{
 			case 1: //black "shadow"
@@ -168,7 +170,7 @@ void CBitmapFont::renderCharacter(SDL_Surface * surface, const BitmapChar & char
 			case 255: //text colour
 				colorPutter(dstPixel, color.r, color.g, color.b);
 				break;
-			default :
+			default:
 				break; //transparency
 			}
 		}
@@ -179,7 +181,7 @@ void CBitmapFont::renderCharacter(SDL_Surface * surface, const BitmapChar & char
 
 void CBitmapFont::renderText(SDL_Surface * surface, const std::string & data, const SDL_Color & color, const Point & pos) const
 {
-	if (data.empty())
+	if(data.empty())
 		return;
 
 	assert(surface);
@@ -193,11 +195,11 @@ void CBitmapFont::renderText(SDL_Surface * surface, const std::string & data, co
 
 	SDL_LockSurface(surface);
 
-	for(size_t i=0; i<data.size(); i += Unicode::getCharacterSize(data[i]))
+	for(size_t i = 0; i < data.size(); i += Unicode::getCharacterSize(data[i]))
 	{
 		std::string localChar = Unicode::fromUnicode(data.substr(i, Unicode::getCharacterSize(data[i])));
 
-		if (localChar.size() == 1)
+		if(localChar.size() == 1)
 			renderCharacter(surface, chars[ui8(localChar[0])], color, posX, posY);
 	}
 	SDL_UnlockSurface(surface);
@@ -209,34 +211,32 @@ std::pair<std::unique_ptr<ui8[]>, ui64> CTrueTypeFont::loadData(const JsonNode &
 	return CResourceHandler::get()->load(ResourceID(filename, EResType::TTF_FONT))->readAll();
 }
 
-TTF_Font * CTrueTypeFont::loadFont(const JsonNode &config)
+TTF_Font * CTrueTypeFont::loadFont(const JsonNode & config)
 {
 	int pointSize = config["size"].Float();
 
-	if(!TTF_WasInit() && TTF_Init()==-1)
+	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);
 }
 
-int CTrueTypeFont::getFontStyle(const JsonNode &config)
+int CTrueTypeFont::getFontStyle(const JsonNode & config)
 {
 	const JsonVector & names = config["style"].Vector();
 	int ret = 0;
 	for(const JsonNode & node : names)
 	{
-		if (node.String() == "bold")
+		if(node.String() == "bold")
 			ret |= TTF_STYLE_BOLD;
-		else if (node.String() == "italic")
+		else if(node.String() == "italic")
 			ret |= TTF_STYLE_ITALIC;
 	}
 	return ret;
 }
 
-CTrueTypeFont::CTrueTypeFont(const JsonNode & fontConfig):
-    data(loadData(fontConfig)),
-    font(loadFont(fontConfig), TTF_CloseFont),
-    blended(fontConfig["blend"].Bool())
+CTrueTypeFont::CTrueTypeFont(const JsonNode & fontConfig)
+	: data(loadData(fontConfig)), font(loadFont(fontConfig), TTF_CloseFont), blended(fontConfig["blend"].Bool())
 {
 	assert(font);
 
@@ -248,7 +248,7 @@ size_t CTrueTypeFont::getLineHeight() const
 	return TTF_FontHeight(font.get());
 }
 
-size_t CTrueTypeFont::getGlyphWidth(const char *data) const
+size_t CTrueTypeFont::getGlyphWidth(const char * data) const
 {
 	return getStringWidth(std::string(data, Unicode::getCharacterSize(*data)));
 	/*
@@ -267,16 +267,16 @@ size_t CTrueTypeFont::getStringWidth(const std::string & data) const
 
 void CTrueTypeFont::renderText(SDL_Surface * surface, const std::string & data, const SDL_Color & color, const Point & pos) const
 {
-	if (color.r != 0 && color.g != 0 && color.b != 0) // not black - add shadow
+	if(color.r != 0 && color.g != 0 && color.b != 0) // not black - add shadow
 	{
 		SDL_Color black = { 0, 0, 0, SDL_ALPHA_OPAQUE};
 		renderText(surface, data, black, Point(pos.x + 1, pos.y + 1));
 	}
 
-	if (!data.empty())
+	if(!data.empty())
 	{
 		SDL_Surface * rendered;
-		if (blended)
+		if(blended)
 			rendered = TTF_RenderUTF8_Blended(font.get(), data.c_str(), color);
 		else
 			rendered = TTF_RenderUTF8_Solid(font.get(), data.c_str(), color);
@@ -291,20 +291,20 @@ void CTrueTypeFont::renderText(SDL_Surface * surface, const std::string & data,
 
 size_t CBitmapHanFont::getCharacterDataOffset(size_t index) const
 {
-	size_t rowSize  = (size + 7) / 8; // 1 bit per pixel, rounded up
+	size_t rowSize = (size + 7) / 8; // 1 bit per pixel, rounded up
 	size_t charSize = rowSize * size; // glyph contains "size" rows
 	return index * charSize;
 }
 
 size_t CBitmapHanFont::getCharacterIndex(ui8 first, ui8 second) const
 {
-	if (second > 0x7f )
+	if(second > 0x7f)
 		second--;
 
-	return (first - 0x81) * (12*16 - 2) + (second - 0x40);
+	return (first - 0x81) * (12 * 16 - 2) + (second - 0x40);
 }
 
-void CBitmapHanFont::renderCharacter(SDL_Surface * surface, int characterIndex, const SDL_Color & color, int &posX, int &posY) const
+void CBitmapHanFont::renderCharacter(SDL_Surface * surface, int characterIndex, const SDL_Color & color, int & posX, int & posY) const
 {
 	//TODO: somewhat duplicated with CBitmapFont::renderCharacter();
 	Rect clipRect;
@@ -315,20 +315,20 @@ void CBitmapHanFont::renderCharacter(SDL_Surface * surface, int characterIndex,
 
 	// start of line, may differ from 0 due to end of surface or clipped surface
 	int lineBegin = std::max<int>(0, clipRect.y - posY);
-	int lineEnd   = std::min<int>(size, clipRect.y + clipRect.h - posY);
+	int lineEnd = std::min<int>(size, clipRect.y + clipRect.h - posY);
 
 	// start end end of each row, may differ from 0
 	int rowBegin = std::max<int>(0, clipRect.x - posX);
-	int rowEnd   = std::min<int>(size, clipRect.x + clipRect.w - posX);
+	int rowEnd = std::min<int>(size, clipRect.x + clipRect.w - posX);
 
 	//for each line in symbol
-	for(int dy = lineBegin; dy <lineEnd; dy++)
+	for(int dy = lineBegin; dy < lineEnd; dy++)
 	{
-		Uint8 *dstLine = (Uint8*)surface->pixels;
-		Uint8 *source = data.first.get() + getCharacterDataOffset(characterIndex);
+		Uint8 * dstLine = (Uint8 *)surface->pixels;
+		Uint8 * source = data.first.get() + getCharacterDataOffset(characterIndex);
 
 		// shift source\destination pixels to current position
-		dstLine += (posY+dy) * surface->pitch + posX * bpp;
+		dstLine += (posY + dy) * surface->pitch + posX * bpp;
 		source += ((size + 7) / 8) * dy;
 
 		//for each column in line
@@ -337,8 +337,8 @@ void CBitmapHanFont::renderCharacter(SDL_Surface * surface, int characterIndex,
 			// select current bit in bitmap
 			int bit = (source[dx / 8] << (dx % 8)) & 0x80;
 
-			Uint8* dstPixel = dstLine + dx*bpp;
-			if (bit != 0)
+			Uint8 * dstPixel = dstLine + dx * bpp;
+			if(bit != 0)
 				colorPutter(dstPixel, color.r, color.g, color.b);
 		}
 	}
@@ -352,27 +352,25 @@ void CBitmapHanFont::renderText(SDL_Surface * surface, const std::string & data,
 
 	SDL_LockSurface(surface);
 
-	for(size_t i=0; i<data.size(); i += Unicode::getCharacterSize(data[i]))
+	for(size_t i = 0; i < data.size(); i += Unicode::getCharacterSize(data[i]))
 	{
 		std::string localChar = Unicode::fromUnicode(data.substr(i, Unicode::getCharacterSize(data[i])));
 
-		if (localChar.size() == 1)
+		if(localChar.size() == 1)
 			fallback->renderCharacter(surface, fallback->chars[ui8(localChar[0])], color, posX, posY);
 
-		if (localChar.size() == 2)
+		if(localChar.size() == 2)
 			renderCharacter(surface, getCharacterIndex(localChar[0], localChar[1]), color, posX, posY);
 	}
 	SDL_UnlockSurface(surface);
 }
 
-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())
+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())
 {
 	// basic tests to make sure that fonts are OK
 	// 1) fonts must contain 190 "sections", 126 symbols each.
-	assert(getCharacterIndex(0xfe, 0xff) == 190*126);
+	assert(getCharacterIndex(0xfe, 0xff) == 190 * 126);
 	// 2) ensure that font size is correct - enough to fit all possible symbols
 	assert(getCharacterDataOffset(getCharacterIndex(0xfe, 0xff)) == data.second);
 }
@@ -386,10 +384,10 @@ size_t CBitmapHanFont::getGlyphWidth(const char * data) const
 {
 	std::string localChar = Unicode::fromUnicode(std::string(data, Unicode::getCharacterSize(data[0])));
 
-	if (localChar.size() == 1)
+	if(localChar.size() == 1)
 		return fallback->getGlyphWidth(data);
 
-	if (localChar.size() == 2)
+	if(localChar.size() == 2)
 		return size + 1;
 
 	return 0;

+ 7 - 4
client/gui/Fonts.h

@@ -67,7 +67,7 @@ class CBitmapFont : public IFont
 		si32 leftOffset;
 		ui32 width;
 		si32 rightOffset;
-		ui8 *pixels; // pixels of this character, part of BitmapFont::data
+		ui8 * pixels; // pixels of this character, part of BitmapFont::data
 	};
 
 	const std::pair<std::unique_ptr<ui8[]>, ui64> data;
@@ -77,9 +77,10 @@ class CBitmapFont : public IFont
 
 	std::array<BitmapChar, totalChars> loadChars() const;
 
-	void renderCharacter(SDL_Surface * surface, const BitmapChar & character, const SDL_Color & color, int &posX, int &posY) const;
+	void renderCharacter(SDL_Surface * surface, const BitmapChar & character, const SDL_Color & color, int & posX, int & posY) const;
 
 	void renderText(SDL_Surface * surface, const std::string & data, const SDL_Color & color, const Point & pos) const override;
+
 public:
 	CBitmapFont(const std::string & filename);
 
@@ -102,8 +103,9 @@ class CBitmapHanFont : public IFont
 	size_t getCharacterDataOffset(size_t index) const;
 	size_t getCharacterIndex(ui8 first, ui8 second) const;
 
-	void renderCharacter(SDL_Surface * surface, int characterIndex, const SDL_Color & color, int &posX, int &posY) const;
+	void renderCharacter(SDL_Surface * surface, int characterIndex, const SDL_Color & color, int & posX, int & posY) const;
 	void renderText(SDL_Surface * surface, const std::string & data, const SDL_Color & color, const Point & pos) const override;
+
 public:
 	CBitmapHanFont(const JsonNode & config);
 
@@ -115,7 +117,7 @@ class CTrueTypeFont : public IFont
 {
 	const std::pair<std::unique_ptr<ui8[]>, ui64> data;
 
-	const std::unique_ptr<TTF_Font, void (*)(TTF_Font*)> font;
+	const std::unique_ptr<TTF_Font, void (*)(TTF_Font *)> font;
 	const bool blended;
 
 	std::pair<std::unique_ptr<ui8[]>, ui64> loadData(const JsonNode & config);
@@ -123,6 +125,7 @@ class CTrueTypeFont : public IFont
 	int getFontStyle(const JsonNode & config);
 
 	void renderText(SDL_Surface * surface, const std::string & data, const SDL_Color & color, const Point & pos) const override;
+
 public:
 	CTrueTypeFont(const JsonNode & fontConfig);
 

+ 6 - 6
client/gui/Geometries.cpp

@@ -12,21 +12,21 @@
 #include "../CMT.h"
 #include <SDL_events.h>
 
-Point::Point(const SDL_MouseMotionEvent &a)
-	:x(a.x),y(a.y)
+Point::Point(const SDL_MouseMotionEvent & a)
+	: x(a.x), y(a.y)
 {}
 
-Rect Rect::createCentered( int w, int h )
+Rect Rect::createCentered(int w, int h)
 {
-	return Rect(screen->w/2 - w/2, screen->h/2 - h/2, w, h);
+	return Rect(screen->w / 2 - w / 2, screen->h / 2 - h / 2, w, h);
 }
 
-Rect Rect::around(const Rect &r, int width) /*creates rect around another */
+Rect Rect::around(const Rect & r, int width) /*creates rect around another */
 {
 	return Rect(r.x - width, r.y - width, r.w + width * 2, r.h + width * 2);
 }
 
-Rect Rect::centerIn(const Rect &r)
+Rect Rect::centerIn(const Rect & r)
 {
 	return Rect(r.x + (r.w - w) / 2, r.y + (r.h - h) / 2, w, h);
 }

+ 52 - 52
client/gui/Geometries.h

@@ -25,33 +25,33 @@ struct Point
 		x = y = 0;
 	};
 	Point(int X, int Y)
-		:x(X),y(Y)
+		: x(X), y(Y)
 	{};
-	Point(const int3 &a)
-		:x(a.x),y(a.y)
+	Point(const int3 & a)
+		: x(a.x), y(a.y)
 	{}
-	Point(const SDL_MouseMotionEvent &a);
+	Point(const SDL_MouseMotionEvent & a);
 
 	template<typename T>
-	Point operator+(const T &b) const
+	Point operator+(const T & b) const
 	{
-		return Point(x+b.x,y+b.y);
+		return Point(x + b.x, y + b.y);
 	}
 
 	template<typename T>
-	Point operator/(const T &div) const
+	Point operator/(const T & div) const
 	{
-		return Point(x/div, y/div);
+		return Point(x / div, y / div);
 	}
 
 	template<typename T>
-	Point operator*(const T &mul) const
+	Point operator*(const T & mul) const
 	{
-		return Point(x*mul, y*mul);
+		return Point(x * mul, y * mul);
 	}
 
 	template<typename T>
-	Point& operator+=(const T &b)
+	Point & operator+=(const T & b)
 	{
 		x += b.x;
 		y += b.y;
@@ -59,33 +59,33 @@ struct Point
 	}
 
 	template<typename T>
-	Point operator-(const T &b) const
+	Point operator-(const T & b) const
 	{
 		return Point(x - b.x, y - b.y);
 	}
 
 	template<typename T>
-	Point& operator-=(const T &b)
+	Point & operator-=(const T & b)
 	{
 		x -= b.x;
 		y -= b.y;
 		return *this;
 	}
-	bool operator<(const Point &b) const //product order
+	bool operator<(const Point & b) const //product order
 	{
-		return x < b.x   &&   y < b.y;
+		return x < b.x && y < b.y;
 	}
-	template<typename T> Point& operator=(const T &t)
+	template<typename T> Point & operator=(const T & t)
 	{
 		x = t.x;
 		y = t.y;
 		return *this;
 	}
-	template<typename T> bool operator==(const T &t) const
+	template<typename T> bool operator==(const T & t) const
 	{
-		return x == t.x  &&  y == t.y;
+		return x == t.x && y == t.y;
 	}
-	template<typename T> bool operator!=(const T &t) const
+	template<typename T> bool operator!=(const T & t) const
 	{
 		return !(*this == t);
 	}
@@ -94,7 +94,7 @@ struct Point
 /// Rectangle class, which have a position and a size
 struct Rect : public SDL_Rect
 {
-	Rect()//default c-tor
+	Rect() //default c-tor
 	{
 		x = y = w = h = -1;
 	}
@@ -119,58 +119,58 @@ struct Rect : public SDL_Rect
 		w = r.w;
 		h = r.h;
 	}
-	explicit Rect(const SDL_Surface * const &surf)
+	explicit Rect(const SDL_Surface * const & surf)
 	{
 		x = y = 0;
 		w = surf->w;
 		h = surf->h;
 	}
 
-	Rect centerIn(const Rect &r);
+	Rect centerIn(const Rect & r);
 	static Rect createCentered(int w, int h);
-	static Rect around(const Rect &r, int width = 1); //creates rect around another
+	static Rect around(const Rect & r, int width = 1); //creates rect around another
 
 	bool isIn(int qx, int qy) const //determines if given point lies inside rect
 	{
-		if (qx > x   &&   qx<x+w   &&   qy>y   &&   qy<y+h)
+		if(qx > x && qx < x + w && qy > y && qy < y + h)
 			return true;
 		return false;
 	}
 	bool isIn(const Point & q) const //determines if given point lies inside rect
 	{
-		return isIn(q.x,q.y);
+		return isIn(q.x, q.y);
 	}
 	Point topLeft() const //top left corner of this rect
 	{
-		return Point(x,y);
+		return Point(x, y);
 	}
 	Point topRight() const //top right corner of this rect
 	{
-		return Point(x+w,y);
+		return Point(x + w, y);
 	}
 	Point bottomLeft() const //bottom left corner of this rect
 	{
-		return Point(x,y+h);
+		return Point(x, y + h);
 	}
 	Point bottomRight() const //bottom right corner of this rect
 	{
-		return Point(x+w,y+h);
+		return Point(x + w, y + h);
 	}
-	Rect operator+(const Rect &p) const //moves this rect by p's rect position
+	Rect operator+(const Rect & p) const //moves this rect by p's rect position
 	{
-		return Rect(x+p.x,y+p.y,w,h);
+		return Rect(x + p.x, y + p.y, w, h);
 	}
-	Rect operator+(const Point &p) const //moves this rect by p's point position
+	Rect operator+(const Point & p) const //moves this rect by p's point position
 	{
-		return Rect(x+p.x,y+p.y,w,h);
+		return Rect(x + p.x, y + p.y, w, h);
 	}
-	Rect& operator=(const Point &p) //assignment operator
+	Rect & operator=(const Point & p) //assignment operator
 	{
 		x = p.x;
 		y = p.y;
 		return *this;
 	}
-	Rect& operator=(const Rect &p) //assignment operator
+	Rect & operator=(const Rect & p) //assignment operator
 	{
 		x = p.x;
 		y = p.y;
@@ -178,35 +178,35 @@ struct Rect : public SDL_Rect
 		h = p.h;
 		return *this;
 	}
-	Rect& operator+=(const Rect &p) //works as operator+
+	Rect & operator+=(const Rect & p) //works as operator+
 	{
 		x += p.x;
 		y += p.y;
 		return *this;
 	}
-	Rect& operator+=(const Point &p) //works as operator+
+	Rect & operator+=(const Point & p) //works as operator+
 	{
 		x += p.x;
 		y += p.y;
 		return *this;
 	}
-	Rect& operator-=(const Rect &p) //works as operator+
+	Rect & operator-=(const Rect & p) //works as operator+
 	{
 		x -= p.x;
 		y -= p.y;
 		return *this;
 	}
-	Rect& operator-=(const Point &p) //works as operator+
+	Rect & operator-=(const Point & p) //works as operator+
 	{
 		x -= p.x;
 		y -= p.y;
 		return *this;
 	}
-	template<typename T> Rect operator-(const T &t)
+	template<typename T> Rect operator-(const T & t)
 	{
 		return Rect(x - t.x, y - t.y, w, h);
 	}
-	Rect operator&(const Rect &p) const //rect intersection
+	Rect operator&(const Rect & p) const //rect intersection
 	{
 		bool intersect = true;
 
@@ -214,11 +214,11 @@ struct Rect : public SDL_Rect
 		{
 			intersect = false;
 		}
-		else if(p.topLeft().y > y+h && p.bottomLeft().y > y+h) //rect p is below *this
+		else if(p.topLeft().y > y + h && p.bottomLeft().y > y + h) //rect p is below *this
 		{
 			intersect = false;
 		}
-		else if(p.topLeft().x > x+w && p.topRight().x > x+w) //rect p is on the right hand side of this
+		else if(p.topLeft().x > x + w && p.topRight().x > x + w) //rect p is on the right hand side of this
 		{
 			intersect = false;
 		}
@@ -233,8 +233,8 @@ struct Rect : public SDL_Rect
 			ret.x = std::max(this->x, p.x);
 			ret.y = std::max(this->y, p.y);
 			Point bR; //bottomRight point of returned rect
-			bR.x = std::min(this->w+this->x, p.w+p.x);
-			bR.y = std::min(this->h+this->y, p.h+p.y);
+			bR.x = std::min(this->w + this->x, p.w + p.x);
+			bR.y = std::min(this->h + this->y, p.h + p.y);
 			ret.w = bR.x - ret.x;
 			ret.h = bR.y - ret.y;
 			return ret;
@@ -244,15 +244,15 @@ struct Rect : public SDL_Rect
 			return Rect();
 		}
 	}
-	Rect operator|(const Rect &p) const //union of two rects
+	Rect operator|(const Rect & p) const //union of two rects
 	{
 		Rect ret;
-		ret.x =  std::min(p.x, this->x);
-		ret.y =  std::min(p.y, this->y);
-		int x2 = std::max(p.x+p.w, this->x+this->w);
-		int y2 = std::max(p.y+p.h, this->y+this->h);
-		ret.w = x2 -ret.x;
-		ret.h = y2 -ret.y;
+		ret.x = std::min(p.x, this->x);
+		ret.y = std::min(p.y, this->y);
+		int x2 = std::max(p.x + p.w, this->x + this->w);
+		int y2 = std::max(p.y + p.h, this->y + this->h);
+		ret.w = x2 - ret.x;
+		ret.h = y2 - ret.y;
 		return ret;
 	}
 };

+ 1 - 3
client/gui/SDL_Compat.h

@@ -8,7 +8,7 @@
  *
  */
 #pragma once
- 
+
 #include <SDL_version.h>
 
 #if (SDL_MAJOR_VERSION == 2)
@@ -21,5 +21,3 @@ typedef int SDLX_Size;
 #else
 #error "unknown or unsupported SDL version"
 #endif
- 
-

+ 235 - 203
client/gui/SDL_Extensions.cpp

@@ -22,23 +22,23 @@ const SDL_Color Colors::METALLIC_GOLD = { 173, 142, 66, 0 };
 const SDL_Color Colors::GREEN = { 0, 255, 0, 0 };
 const SDL_Color Colors::DEFAULT_KEY_COLOR = {0, 255, 255, 0};
 
-void SDL_UpdateRect(SDL_Surface *surface, int x, int y, int w, int h)
+void SDL_UpdateRect(SDL_Surface * surface, int x, int y, int w, int h)
 {
-	Rect rect(x,y,w,h);
-	if(0 !=SDL_UpdateTexture(screenTexture, &rect, surface->pixels, surface->pitch))
+	Rect rect(x, y, w, h);
+	if(0 != SDL_UpdateTexture(screenTexture, &rect, surface->pixels, surface->pitch))
 		logGlobal->errorStream() << __FUNCTION__ << "SDL_UpdateTexture " << SDL_GetError();
 
 	SDL_RenderClear(mainRenderer);
 	if(0 != SDL_RenderCopy(mainRenderer, screenTexture, NULL, NULL))
-		logGlobal->errorStream() << __FUNCTION__ << "SDL_RenderCopy " <<  SDL_GetError();
+		logGlobal->errorStream() << __FUNCTION__ << "SDL_RenderCopy " << SDL_GetError();
 	SDL_RenderPresent(mainRenderer);
 
 }
 
 SDL_Surface * CSDL_Ext::newSurface(int w, int h, SDL_Surface * mod) //creates new surface, with flags/format same as in surface given
 {
-	SDL_Surface * ret = SDL_CreateRGBSurface(mod->flags,w,h,mod->format->BitsPerPixel,mod->format->Rmask,mod->format->Gmask,mod->format->Bmask,mod->format->Amask);
-	if (mod->format->palette)
+	SDL_Surface * ret = SDL_CreateRGBSurface(mod->flags, w, h, mod->format->BitsPerPixel, mod->format->Rmask, mod->format->Gmask, mod->format->Bmask, mod->format->Amask);
+	if(mod->format->palette)
 	{
 		assert(ret->format->palette);
 		assert(ret->format->palette->ncolors == mod->format->palette->ncolors);
@@ -58,17 +58,17 @@ SDL_Surface * CSDL_Ext::createSurfaceWithBpp(int width, int height)
 {
 	Uint32 rMask = 0, gMask = 0, bMask = 0, aMask = 0;
 
-	Channels::px<bpp>::r.set((Uint8*)&rMask, 255);
-	Channels::px<bpp>::g.set((Uint8*)&gMask, 255);
-	Channels::px<bpp>::b.set((Uint8*)&bMask, 255);
-	Channels::px<bpp>::a.set((Uint8*)&aMask, 255);
+	Channels::px<bpp>::r.set((Uint8 *)&rMask, 255);
+	Channels::px<bpp>::g.set((Uint8 *)&gMask, 255);
+	Channels::px<bpp>::b.set((Uint8 *)&bMask, 255);
+	Channels::px<bpp>::a.set((Uint8 *)&aMask, 255);
 
-	return SDL_CreateRGBSurface( SDL_SWSURFACE, width, height, bpp * 8, rMask, gMask, bMask, aMask);
+	return SDL_CreateRGBSurface(SDL_SWSURFACE, width, height, bpp * 8, rMask, gMask, bMask, aMask);
 }
 
 bool isItIn(const SDL_Rect * rect, int x, int y)
 {
-	return (x>rect->x && x<rect->x+rect->w) && (y>rect->y && y<rect->y+rect->h);
+	return (x > rect->x && x < rect->x + rect->w) && (y > rect->y && y < rect->y + rect->h);
 }
 
 bool isItInOrLowerBounds(const SDL_Rect * rect, int x, int y)
@@ -78,15 +78,16 @@ bool isItInOrLowerBounds(const SDL_Rect * rect, int x, int y)
 
 void blitAt(SDL_Surface * src, int x, int y, SDL_Surface * dst)
 {
-	if(!dst) dst = screen;
-	SDL_Rect pom = genRect(src->h,src->w,x,y);
-	CSDL_Ext::blitSurface(src,nullptr,dst,&pom);
+	if(!dst)
+		dst = screen;
+	SDL_Rect pom = genRect(src->h, src->w, x, y);
+	CSDL_Ext::blitSurface(src, nullptr, dst, &pom);
 }
 
 void blitAt(SDL_Surface * src, const SDL_Rect & pos, SDL_Surface * dst)
 {
-	if (src)
-		blitAt(src,pos.x,pos.y,dst);
+	if(src)
+		blitAt(src, pos.x, pos.y, dst);
 }
 
 // Vertical flip
@@ -102,7 +103,7 @@ SDL_Surface * CSDL_Ext::verticalFlip(SDL_Surface * toRot)
 	char * src = reinterpret_cast<char *>(toRot->pixels);
 	char * dst = reinterpret_cast<char *>(ret->pixels);
 
-	for(int i=0; i<ret->h; i++)
+	for(int i = 0; i < ret->h; i++)
 	{
 		//FIXME: optimization bugged
 //		if (bpp == 1)
@@ -112,15 +113,15 @@ SDL_Surface * CSDL_Ext::verticalFlip(SDL_Surface * toRot)
 //		}
 //		else
 //		{
-			char * srcPxl = src;
-			char * dstPxl = dst + ret->w * bpp;
+		char * srcPxl = src;
+		char * dstPxl = dst + ret->w * bpp;
 
-			for(int j=0; j<ret->w; j++)
-			{
-				dstPxl -= bpp;
-				std::copy(srcPxl, srcPxl + bpp, dstPxl);
-				srcPxl += bpp;
-			}
+		for(int j = 0; j < ret->w; j++)
+		{
+			dstPxl -= bpp;
+			std::copy(srcPxl, srcPxl + bpp, dstPxl);
+			srcPxl += bpp;
+		}
 //		}
 		src += toRot->pitch;
 		dst += ret->pitch;
@@ -139,7 +140,7 @@ SDL_Surface * CSDL_Ext::horizontalFlip(SDL_Surface * toRot)
 	char * src = reinterpret_cast<char *>(toRot->pixels);
 	char * dst = reinterpret_cast<char *>(ret->pixels) + ret->h * ret->pitch;
 
-	for(int i=0; i<ret->h; i++)
+	for(int i = 0; i < ret->h; i++)
 	{
 		dst -= ret->pitch;
 		std::copy(src, src + toRot->pitch, dst);
@@ -150,17 +151,17 @@ SDL_Surface * CSDL_Ext::horizontalFlip(SDL_Surface * toRot)
 	return ret;
 }
 
-Uint32 CSDL_Ext::SDL_GetPixel(SDL_Surface *surface, const int & x, const int & y, bool colorByte)
+Uint32 CSDL_Ext::SDL_GetPixel(SDL_Surface * surface, const int & x, const int & y, bool colorByte)
 {
 	int bpp = surface->format->BytesPerPixel;
 	/* Here p is the address to the pixel we want to retrieve */
-	Uint8 *p = (Uint8 *)surface->pixels + y * surface->pitch + x * bpp;
+	Uint8 * p = (Uint8 *)surface->pixels + y * surface->pitch + x * bpp;
 
 	switch(bpp)
 	{
 	case 1:
 		if(colorByte)
-			return colorToUint32(surface->format->palette->colors+(*p));
+			return colorToUint32(surface->format->palette->colors + (*p));
 		else
 			return *p;
 
@@ -168,27 +169,27 @@ Uint32 CSDL_Ext::SDL_GetPixel(SDL_Surface *surface, const int & x, const int & y
 		return *(Uint16 *)p;
 
 	case 3:
-			return p[0] | p[1] << 8 | p[2] << 16;
+		return p[0] | p[1] << 8 | p[2] << 16;
 
 	case 4:
 		return *(Uint32 *)p;
 
 	default:
-		return 0;       // shouldn't happen, but avoids warnings
+		return 0; // shouldn't happen, but avoids warnings
 	}
 }
 
-void CSDL_Ext::alphaTransform(SDL_Surface *src)
+void CSDL_Ext::alphaTransform(SDL_Surface * src)
 {
 	assert(src->format->BitsPerPixel == 8);
 	SDL_Color colors[] =
 	{
-	    {  0,   0,  0,   0}, {  0,   0,   0,  32}, {  0,   0,   0,  64},
-	    {  0,   0,  0, 128}, {  0,   0,   0, 128}
+		{  0, 0, 0, 0}, {  0, 0, 0, 32}, {  0, 0, 0, 64},
+		{  0, 0, 0, 128}, {  0, 0, 0, 128}
 	};
 
 
-	for (size_t i=0; i< ARRAY_COUNT(colors); i++ )
+	for(size_t i = 0; i < ARRAY_COUNT(colors); i++)
 	{
 		SDL_Color & palColor = src->format->palette->colors[i];
 		palColor = colors[i];
@@ -200,25 +201,25 @@ template<int bpp>
 int CSDL_Ext::blit8bppAlphaTo24bppT(const SDL_Surface * src, const SDL_Rect * srcRect, SDL_Surface * dst, SDL_Rect * dstRect)
 {
 	/* Make sure the surfaces aren't locked */
-	if ( ! src || ! dst )
+	if(!src || !dst)
 	{
 		SDL_SetError("SDL_UpperBlit: passed a nullptr surface");
 		return -1;
 	}
 
-	if ( src->locked || dst->locked )
+	if(src->locked || dst->locked)
 	{
 		SDL_SetError("Surfaces must not be locked during blit");
 		return -1;
 	}
 
-	if (src->format->BytesPerPixel==1 && (bpp==3 || bpp==4 || bpp==2)) //everything's ok
+	if(src->format->BytesPerPixel == 1 && (bpp == 3 || bpp == 4 || bpp == 2)) //everything's ok
 	{
 		SDL_Rect fulldst;
 		int srcx, srcy, w, h;
 
 		/* If the destination rectangle is nullptr, use the entire dest surface */
-		if ( dstRect == nullptr )
+		if(dstRect == nullptr)
 		{
 			fulldst.x = fulldst.y = 0;
 			dstRect = &fulldst;
@@ -245,7 +246,7 @@ int CSDL_Ext::blit8bppAlphaTo24bppT(const SDL_Surface * src, const SDL_Rect * sr
 			h = srcRect->h;
 			if(srcy < 0)
 			{
-					h += srcy;
+				h += srcy;
 				dstRect->y -= srcy;
 				srcy = 0;
 			}
@@ -263,7 +264,7 @@ int CSDL_Ext::blit8bppAlphaTo24bppT(const SDL_Surface * src, const SDL_Rect * sr
 
 		/* clip the destination rectangle against the clip rectangle */
 		{
-			SDL_Rect *clip = &dst->clip_rect;
+			SDL_Rect * clip = &dst->clip_rect;
 			int dx, dy;
 
 			dx = clip->x - dstRect->x;
@@ -297,18 +298,18 @@ int CSDL_Ext::blit8bppAlphaTo24bppT(const SDL_Surface * src, const SDL_Rect * sr
 			if(SDL_LockSurface(dst))
 				return -1; //if we cannot lock the surface
 
-			const SDL_Color *colors = src->format->palette->colors;
-			Uint8 *colory = (Uint8*)src->pixels + srcy*src->pitch + srcx;
-			Uint8 *py = (Uint8*)dst->pixels + dstRect->y*dst->pitch + dstRect->x*bpp;
+			const SDL_Color * colors = src->format->palette->colors;
+			Uint8 * colory = (Uint8 *)src->pixels + srcy * src->pitch + srcx;
+			Uint8 * py = (Uint8 *)dst->pixels + dstRect->y * dst->pitch + dstRect->x * bpp;
 
-			for(int y=h; y; y--, colory+=src->pitch, py+=dst->pitch)
+			for(int y = h; y; y--, colory += src->pitch, py += dst->pitch)
 			{
-				Uint8 *color = colory;
-				Uint8 *p = py;
+				Uint8 * color = colory;
+				Uint8 * p = py;
 
 				for(int x = w; x; x--)
 				{
-					const SDL_Color &tbc = colors[*color++]; //color to blit
+					const SDL_Color & tbc = colors[*color++]; //color to blit
 					ColorPutter<bpp, +1>::PutColorAlphaSwitch(p, tbc.r, tbc.g, tbc.b, tbc.a);
 				}
 			}
@@ -322,9 +323,12 @@ int CSDL_Ext::blit8bppAlphaTo24bpp(const SDL_Surface * src, const SDL_Rect * src
 {
 	switch(dst->format->BytesPerPixel)
 	{
-	case 2: return blit8bppAlphaTo24bppT<2>(src, srcRect, dst, dstRect);
-	case 3: return blit8bppAlphaTo24bppT<3>(src, srcRect, dst, dstRect);
-	case 4: return blit8bppAlphaTo24bppT<4>(src, srcRect, dst, dstRect);
+	case 2:
+		return blit8bppAlphaTo24bppT<2>(src, srcRect, dst, dstRect);
+	case 3:
+		return blit8bppAlphaTo24bppT<3>(src, srcRect, dst, dstRect);
+	case 4:
+		return blit8bppAlphaTo24bppT<4>(src, srcRect, dst, dstRect);
 	default:
 		logGlobal->errorStream() << (int)dst->format->BitsPerPixel << " bpp is not supported!!!";
 		return -1;
@@ -334,13 +338,13 @@ int CSDL_Ext::blit8bppAlphaTo24bpp(const SDL_Surface * src, const SDL_Rect * src
 Uint32 CSDL_Ext::colorToUint32(const SDL_Color * color)
 {
 	Uint32 ret = 0;
-	ret+=color->a;
-	ret<<=8; //*=256
-	ret+=color->b;
-	ret<<=8; //*=256
-	ret+=color->g;
-	ret<<=8; //*=256
-	ret+=color->r;
+	ret += color->a;
+	ret <<= 8; //*=256
+	ret += color->b;
+	ret <<= 8; //*=256
+	ret += color->g;
+	ret <<= 8; //*=256
+	ret += color->r;
 	return ret;
 }
 
@@ -348,46 +352,46 @@ void CSDL_Ext::update(SDL_Surface * what)
 {
 	if(!what)
 		return;
-	if(0 !=SDL_UpdateTexture(screenTexture, nullptr, what->pixels, what->pitch))
+	if(0 != SDL_UpdateTexture(screenTexture, nullptr, what->pixels, what->pitch))
 		logGlobal->errorStream() << __FUNCTION__ << "SDL_UpdateTexture " << SDL_GetError();
 }
-void CSDL_Ext::drawBorder(SDL_Surface * sur, int x, int y, int w, int h, const int3 &color)
+void CSDL_Ext::drawBorder(SDL_Surface * sur, int x, int y, int w, int h, const int3 & color)
 {
 	for(int i = 0; i < w; i++)
 	{
-		SDL_PutPixelWithoutRefreshIfInSurf(sur,x+i,y,color.x,color.y,color.z);
-		SDL_PutPixelWithoutRefreshIfInSurf(sur,x+i,y+h-1,color.x,color.y,color.z);
+		SDL_PutPixelWithoutRefreshIfInSurf(sur, x + i, y, color.x, color.y, color.z);
+		SDL_PutPixelWithoutRefreshIfInSurf(sur, x + i, y + h - 1, color.x, color.y, color.z);
 	}
 	for(int i = 0; i < h; i++)
 	{
-		SDL_PutPixelWithoutRefreshIfInSurf(sur,x,y+i,color.x,color.y,color.z);
-		SDL_PutPixelWithoutRefreshIfInSurf(sur,x+w-1,y+i,color.x,color.y,color.z);
+		SDL_PutPixelWithoutRefreshIfInSurf(sur, x, y + i, color.x, color.y, color.z);
+		SDL_PutPixelWithoutRefreshIfInSurf(sur, x + w - 1, y + i, color.x, color.y, color.z);
 	}
 }
 
-void CSDL_Ext::drawBorder( SDL_Surface * sur, const SDL_Rect &r, const int3 &color )
+void CSDL_Ext::drawBorder(SDL_Surface * sur, const SDL_Rect & r, const int3 & color)
 {
 	drawBorder(sur, r.x, r.y, r.w, r.h, color);
 }
 
-void CSDL_Ext::drawDashedBorder(SDL_Surface * sur, const Rect &r, const int3 &color)
+void CSDL_Ext::drawDashedBorder(SDL_Surface * sur, const Rect & r, const int3 & color)
 {
-	const int y1 = r.y, y2 = r.y + r.h-1;
-	for (int i=0; i<r.w; i++)
+	const int y1 = r.y, y2 = r.y + r.h - 1;
+	for(int i = 0; i < r.w; i++)
 	{
 		const int x = r.x + i;
-		if (i%4 || (i==0))
+		if(i % 4 || (i == 0))
 		{
 			SDL_PutPixelWithoutRefreshIfInSurf(sur, x, y1, color.x, color.y, color.z);
 			SDL_PutPixelWithoutRefreshIfInSurf(sur, x, y2, color.x, color.y, color.z);
 		}
 	}
 
-	const int x1 = r.x, x2 = r.x + r.w-1;
-	for (int i=0; i<r.h; i++)
+	const int x1 = r.x, x2 = r.x + r.w - 1;
+	for(int i = 0; i < r.h; i++)
 	{
 		const int y = r.y + i;
-		if ((i%4) || (i==0))
+		if((i % 4) || (i == 0))
 		{
 			SDL_PutPixelWithoutRefreshIfInSurf(sur, x1, y, color.x, color.y, color.z);
 			SDL_PutPixelWithoutRefreshIfInSurf(sur, x2, y, color.x, color.y, color.z);
@@ -397,29 +401,27 @@ void CSDL_Ext::drawDashedBorder(SDL_Surface * sur, const Rect &r, const int3 &co
 
 void CSDL_Ext::setPlayerColor(SDL_Surface * sur, PlayerColor player)
 {
-	if(player==PlayerColor::UNFLAGGABLE)
+	if(player == PlayerColor::UNFLAGGABLE)
 		return;
-	if(sur->format->BitsPerPixel==8)
+	if(sur->format->BitsPerPixel == 8)
 	{
-		SDL_Color *color = (player == PlayerColor::NEUTRAL
-							? graphics->neutralColor
-							: &graphics->playerColors[player.getNum()]);
+		SDL_Color * color = (player == PlayerColor::NEUTRAL ? graphics->neutralColor : &graphics->playerColors[player.getNum()]);
 		SDL_SetColors(sur, color, 5, 1);
 	}
 	else
 		logGlobal->warnStream() << "Warning, setPlayerColor called on not 8bpp surface!";
 }
 
-TColorPutter CSDL_Ext::getPutterFor(SDL_Surface * const &dest, int incrementing)
+TColorPutter CSDL_Ext::getPutterFor(SDL_Surface * const & dest, int incrementing)
 {
-#define CASE_BPP(BytesPerPixel)							\
-case BytesPerPixel:									\
-	if(incrementing > 0)								\
-		return ColorPutter<BytesPerPixel, 1>::PutColor;	\
-	else if(incrementing == 0)							\
-		return ColorPutter<BytesPerPixel, 0>::PutColor;	\
-	else												\
-		return ColorPutter<BytesPerPixel, -1>::PutColor;\
+#define CASE_BPP(BytesPerPixel)                                                 \
+case BytesPerPixel:                                                                     \
+	if(incrementing > 0)                                                            \
+		return ColorPutter<BytesPerPixel, 1>::PutColor; \
+	else if(incrementing == 0)                                                      \
+		return ColorPutter<BytesPerPixel, 0>::PutColor; \
+	else                                                                                            \
+		return ColorPutter<BytesPerPixel, -1>::PutColor; \
 	break;
 
 	switch(dest->format->BytesPerPixel)
@@ -434,7 +436,7 @@ case BytesPerPixel:									\
 
 }
 
-TColorPutterAlpha CSDL_Ext::getPutterAlphaFor(SDL_Surface * const &dest, int incrementing)
+TColorPutterAlpha CSDL_Ext::getPutterAlphaFor(SDL_Surface * const & dest, int incrementing)
 {
 	switch(dest->format->BytesPerPixel)
 	{
@@ -448,23 +450,23 @@ TColorPutterAlpha CSDL_Ext::getPutterAlphaFor(SDL_Surface * const &dest, int inc
 #undef CASE_BPP
 }
 
-Uint8 * CSDL_Ext::getPxPtr(const SDL_Surface * const &srf, const int x, const int y)
+Uint8 * CSDL_Ext::getPxPtr(const SDL_Surface * const & srf, const int x, const int y)
 {
 	return (Uint8 *)srf->pixels + y * srf->pitch + x * srf->format->BytesPerPixel;
 }
 
 std::string CSDL_Ext::processStr(std::string str, std::vector<std::string> & tor)
 {
-	for (size_t i=0; (i<tor.size())&&(boost::find_first(str,"%s")); ++i)
+	for(size_t i = 0; (i < tor.size()) && (boost::find_first(str, "%s")); ++i)
 	{
-		boost::replace_first(str,"%s",tor[i]);
+		boost::replace_first(str, "%s", tor[i]);
 	}
 	return str;
 }
 
-bool CSDL_Ext::isTransparent( SDL_Surface * srf, int x, int y )
+bool CSDL_Ext::isTransparent(SDL_Surface * srf, int x, int y)
 {
-	if (x < 0 || y < 0 || x >= srf->w || y >= srf->h)
+	if(x < 0 || y < 0 || x >= srf->w || y >= srf->h)
 		return true;
 
 	SDL_Color color;
@@ -474,7 +476,7 @@ bool CSDL_Ext::isTransparent( SDL_Surface * srf, int x, int y )
 	// color is considered transparent here if
 	// a) image has aplha: less than 50% transparency
 	// b) no alpha: color is cyan
-	if (srf->format->Amask)
+	if(srf->format->Amask)
 		return color.a < 128; // almost transparent
 	else
 		return (color.r == 0 && color.g == 255 && color.b == 255);
@@ -484,123 +486,139 @@ void CSDL_Ext::VflipSurf(SDL_Surface * surf)
 {
 	char buf[4]; //buffer
 	int bpp = surf->format->BytesPerPixel;
-	for (int y=0; y<surf->h; ++y)
+	for(int y = 0; y < surf->h; ++y)
 	{
-		char * base = (char*)surf->pixels + y * surf->pitch;
-		for (int x=0; x<surf->w/2; ++x)
+		char * base = (char *)surf->pixels + y * surf->pitch;
+		for(int x = 0; x < surf->w / 2; ++x)
 		{
-			memcpy(buf, base  + x * bpp, bpp);
+			memcpy(buf, base + x * bpp, bpp);
 			memcpy(base + x * bpp, base + (surf->w - x - 1) * bpp, bpp);
 			memcpy(base + (surf->w - x - 1) * bpp, buf, bpp);
 		}
 	}
 }
 
-void CSDL_Ext::SDL_PutPixelWithoutRefresh(SDL_Surface *ekran, const int & x, const int & y, const Uint8 & R, const Uint8 & G, const Uint8 & B, Uint8 A)
+void CSDL_Ext::SDL_PutPixelWithoutRefresh(SDL_Surface * ekran, const int & x, const int & y, const Uint8 & R, const Uint8 & G, const Uint8 & B, Uint8 A)
 {
-	Uint8 *p = getPxPtr(ekran, x, y);
+	Uint8 * p = getPxPtr(ekran, x, y);
 	getPutterFor(ekran, false)(p, R, G, B);
 
 	switch(ekran->format->BytesPerPixel)
 	{
-	case 2: Channels::px<2>::a.set(p, A); break;
-	case 3: Channels::px<3>::a.set(p, A); break;
-	case 4: Channels::px<4>::a.set(p, A); break;
+	case 2:
+		Channels::px<2>::a.set(p, A);
+		break;
+	case 3:
+		Channels::px<3>::a.set(p, A);
+		break;
+	case 4:
+		Channels::px<4>::a.set(p, A);
+		break;
 	}
 }
 
-void CSDL_Ext::SDL_PutPixelWithoutRefreshIfInSurf(SDL_Surface *ekran, const int & x, const int & y, const Uint8 & R, const Uint8 & G, const Uint8 & B, Uint8 A)
+void CSDL_Ext::SDL_PutPixelWithoutRefreshIfInSurf(SDL_Surface * ekran, const int & x, const int & y, const Uint8 & R, const Uint8 & G, const Uint8 & B, Uint8 A)
 {
 	const SDL_Rect & rect = ekran->clip_rect;
 
-	if(x >= rect.x  &&  x < rect.w + rect.x
-	&& y >= rect.y  &&  y < rect.h + rect.y)
+	if(x >= rect.x && x < rect.w + rect.x
+	   && y >= rect.y && y < rect.h + rect.y)
 		SDL_PutPixelWithoutRefresh(ekran, x, y, R, G, B, A);
 }
 
 template<int bpp>
-void CSDL_Ext::applyEffectBpp( SDL_Surface * surf, const SDL_Rect * rect, int mode )
+void CSDL_Ext::applyEffectBpp(SDL_Surface * surf, const SDL_Rect * rect, int mode)
 {
 	switch(mode)
 	{
 	case 0: //sepia
-		{
-			const int sepiaDepth = 20;
-			const int sepiaIntensity = 30;
+	{
+		const int sepiaDepth = 20;
+		const int sepiaIntensity = 30;
 
-			for(int xp = rect->x; xp < rect->x + rect->w; ++xp)
+		for(int xp = rect->x; xp < rect->x + rect->w; ++xp)
+		{
+			for(int yp = rect->y; yp < rect->y + rect->h; ++yp)
 			{
-				for(int yp = rect->y; yp < rect->y + rect->h; ++yp)
-				{
-					Uint8 * pixel = (ui8*)surf->pixels + yp * surf->pitch + xp * surf->format->BytesPerPixel;
-					int r = Channels::px<bpp>::r.get(pixel);
-					int g = Channels::px<bpp>::g.get(pixel);
-					int b = Channels::px<bpp>::b.get(pixel);
-					int gray = 0.299 * r + 0.587 * g + 0.114 *b;
-
-					r = g = b = gray;
-					r = r + (sepiaDepth * 2);
-					g = g + sepiaDepth;
-
-					if (r>255) r=255;
-					if (g>255) g=255;
-					if (b>255) b=255;
-
-					// Darken blue color to increase sepia effect
-					b -= sepiaIntensity;
-
-					// normalize if out of bounds
-					if (b<0) b=0;
-
-					Channels::px<bpp>::r.set(pixel, r);
-					Channels::px<bpp>::g.set(pixel, g);
-					Channels::px<bpp>::b.set(pixel, b);
-				}
+				Uint8 * pixel = (ui8 *)surf->pixels + yp * surf->pitch + xp * surf->format->BytesPerPixel;
+				int r = Channels::px<bpp>::r.get(pixel);
+				int g = Channels::px<bpp>::g.get(pixel);
+				int b = Channels::px<bpp>::b.get(pixel);
+				int gray = 0.299 * r + 0.587 * g + 0.114 * b;
+
+				r = g = b = gray;
+				r = r + (sepiaDepth * 2);
+				g = g + sepiaDepth;
+
+				if(r > 255)
+					r = 255;
+				if(g > 255)
+					g = 255;
+				if(b > 255)
+					b = 255;
+
+				// Darken blue color to increase sepia effect
+				b -= sepiaIntensity;
+
+				// normalize if out of bounds
+				if(b < 0)
+					b = 0;
+
+				Channels::px<bpp>::r.set(pixel, r);
+				Channels::px<bpp>::g.set(pixel, g);
+				Channels::px<bpp>::b.set(pixel, b);
 			}
 		}
-		break;
+	}
+	break;
 	case 1: //grayscale
+	{
+		for(int xp = rect->x; xp < rect->x + rect->w; ++xp)
 		{
-			for(int xp = rect->x; xp < rect->x + rect->w; ++xp)
+			for(int yp = rect->y; yp < rect->y + rect->h; ++yp)
 			{
-				for(int yp = rect->y; yp < rect->y + rect->h; ++yp)
-				{
-					Uint8 * pixel = (ui8*)surf->pixels + yp * surf->pitch + xp * surf->format->BytesPerPixel;
+				Uint8 * pixel = (ui8 *)surf->pixels + yp * surf->pitch + xp * surf->format->BytesPerPixel;
 
-					int r = Channels::px<bpp>::r.get(pixel);
-					int g = Channels::px<bpp>::g.get(pixel);
-					int b = Channels::px<bpp>::b.get(pixel);
+				int r = Channels::px<bpp>::r.get(pixel);
+				int g = Channels::px<bpp>::g.get(pixel);
+				int b = Channels::px<bpp>::b.get(pixel);
 
-					int gray = 0.299 * r + 0.587 * g + 0.114 *b;
-					vstd::amax(gray, 255);
+				int gray = 0.299 * r + 0.587 * g + 0.114 * b;
+				vstd::amax(gray, 255);
 
-					Channels::px<bpp>::r.set(pixel, gray);
-					Channels::px<bpp>::g.set(pixel, gray);
-					Channels::px<bpp>::b.set(pixel, gray);
-				}
+				Channels::px<bpp>::r.set(pixel, gray);
+				Channels::px<bpp>::g.set(pixel, gray);
+				Channels::px<bpp>::b.set(pixel, gray);
 			}
 		}
-		break;
+	}
+	break;
 	default:
 		throw std::runtime_error("Unsupported effect!");
 	}
 }
 
-void CSDL_Ext::applyEffect( SDL_Surface * surf, const SDL_Rect * rect, int mode )
+void CSDL_Ext::applyEffect(SDL_Surface * surf, const SDL_Rect * rect, int mode)
 {
 	switch(surf->format->BytesPerPixel)
 	{
-		case 2: applyEffectBpp<2>(surf, rect, mode); break;
-		case 3: applyEffectBpp<3>(surf, rect, mode); break;
-		case 4: applyEffectBpp<4>(surf, rect, mode); break;
+	case 2:
+		applyEffectBpp<2>(surf, rect, mode);
+		break;
+	case 3:
+		applyEffectBpp<3>(surf, rect, mode);
+		break;
+	case 4:
+		applyEffectBpp<4>(surf, rect, mode);
+		break;
 	}
 }
 
 template<int bpp>
-void scaleSurfaceFastInternal(SDL_Surface *surf, SDL_Surface *ret)
+void scaleSurfaceFastInternal(SDL_Surface * surf, SDL_Surface * ret)
 {
 	const float factorX = float(surf->w) / float(ret->w),
-				factorY = float(surf->h) / float(ret->h);
+		    factorY = float(surf->h) / float(ret->h);
 
 	for(int y = 0; y < ret->h; y++)
 	{
@@ -608,43 +626,51 @@ void scaleSurfaceFastInternal(SDL_Surface *surf, SDL_Surface *ret)
 		{
 			//coordinates we want to calculate
 			int origX = floor(factorX * x),
-				origY = floor(factorY * y);
+			    origY = floor(factorY * y);
 
 			// Get pointers to source pixels
-			Uint8 *srcPtr = (Uint8*)surf->pixels + origY * surf->pitch + origX * bpp;
-			Uint8 *destPtr = (Uint8*)ret->pixels + y * ret->pitch + x * bpp;
+			Uint8 * srcPtr = (Uint8 *)surf->pixels + origY * surf->pitch + origX * bpp;
+			Uint8 * destPtr = (Uint8 *)ret->pixels + y * ret->pitch + x * bpp;
 
 			memcpy(destPtr, srcPtr, bpp);
 		}
 	}
 }
 
-SDL_Surface * CSDL_Ext::scaleSurfaceFast(SDL_Surface *surf, int width, int height)
+SDL_Surface * CSDL_Ext::scaleSurfaceFast(SDL_Surface * surf, int width, int height)
 {
-	if (!surf || !width || !height)
+	if(!surf || !width || !height)
 		return nullptr;
 
 	//Same size? return copy - this should more be faster
-	if (width == surf->w && height == surf->h)
+	if(width == surf->w && height == surf->h)
 		return copySurface(surf);
 
-	SDL_Surface *ret = newSurface(width, height, surf);
+	SDL_Surface * ret = newSurface(width, height, surf);
 
 	switch(surf->format->BytesPerPixel)
 	{
-		case 1: scaleSurfaceFastInternal<1>(surf, ret); break;
-		case 2: scaleSurfaceFastInternal<2>(surf, ret); break;
-		case 3: scaleSurfaceFastInternal<3>(surf, ret); break;
-		case 4: scaleSurfaceFastInternal<4>(surf, ret); break;
+	case 1:
+		scaleSurfaceFastInternal<1>(surf, ret);
+		break;
+	case 2:
+		scaleSurfaceFastInternal<2>(surf, ret);
+		break;
+	case 3:
+		scaleSurfaceFastInternal<3>(surf, ret);
+		break;
+	case 4:
+		scaleSurfaceFastInternal<4>(surf, ret);
+		break;
 	}
 	return ret;
 }
 
 template<int bpp>
-void scaleSurfaceInternal(SDL_Surface *surf, SDL_Surface *ret)
+void scaleSurfaceInternal(SDL_Surface * surf, SDL_Surface * ret)
 {
 	const float factorX = float(surf->w - 1) / float(ret->w),
-				factorY = float(surf->h - 1) / float(ret->h);
+		    factorY = float(surf->h - 1) / float(ret->h);
 
 	for(int y = 0; y < ret->h; y++)
 	{
@@ -652,10 +678,10 @@ void scaleSurfaceInternal(SDL_Surface *surf, SDL_Surface *ret)
 		{
 			//coordinates we want to interpolate
 			float origX = factorX * x,
-				  origY = factorY * y;
+			      origY = factorY * y;
 
-			float x1 = floor(origX), x2 = floor(origX+1),
-				  y1 = floor(origY), y2 = floor(origY+1);
+			float x1 = floor(origX), x2 = floor(origX + 1),
+			      y1 = floor(origY), y2 = floor(origY + 1);
 			//assert( x1 >= 0 && y1 >= 0 && x2 < surf->w && y2 < surf->h);//All pixels are in range
 
 			// Calculate weights of each source pixel
@@ -666,10 +692,10 @@ void scaleSurfaceInternal(SDL_Surface *surf, SDL_Surface *ret)
 			//assert( w11 + w12 + w21 + w22 > 0.99 && w11 + w12 + w21 + w22 < 1.01);//total weight is ~1.0
 
 			// Get pointers to source pixels
-			Uint8 *p11 = (Uint8*)surf->pixels + int(y1) * surf->pitch + int(x1) * bpp;
-			Uint8 *p12 = p11 + bpp;
-			Uint8 *p21 = p11 + surf->pitch;
-			Uint8 *p22 = p21 + bpp;
+			Uint8 * p11 = (Uint8 *)surf->pixels + int(y1) * surf->pitch + int(x1) * bpp;
+			Uint8 * p12 = p11 + bpp;
+			Uint8 * p21 = p11 + surf->pitch;
+			Uint8 * p22 = p21 + bpp;
 			// Calculate resulting channels
 #define PX(X, PTR) Channels::px<bpp>::X.get(PTR)
 			int resR = PX(r, p11) * w11 + PX(r, p12) * w12 + PX(r, p21) * w21 + PX(r, p22) * w22;
@@ -678,7 +704,7 @@ void scaleSurfaceInternal(SDL_Surface *surf, SDL_Surface *ret)
 			int resA = 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;
+			Uint8 * dest = (Uint8 *)ret->pixels + y * ret->pitch + x * bpp;
 			Channels::px<bpp>::r.set(dest, resR);
 			Channels::px<bpp>::g.set(dest, resG);
 			Channels::px<bpp>::b.set(dest, resB);
@@ -690,40 +716,46 @@ void scaleSurfaceInternal(SDL_Surface *surf, SDL_Surface *ret)
 // scaling via bilinear interpolation algorithm.
 // NOTE: best results are for scaling in range 50%...200%.
 // And upscaling looks awful right now - should be fixed somehow
-SDL_Surface * CSDL_Ext::scaleSurface(SDL_Surface *surf, int width, int height)
+SDL_Surface * CSDL_Ext::scaleSurface(SDL_Surface * surf, int width, int height)
 {
-	if (!surf || !width || !height)
+	if(!surf || !width || !height)
 		return nullptr;
 
-	if (surf->format->palette)
+	if(surf->format->palette)
 		return scaleSurfaceFast(surf, width, height);
 
 	//Same size? return copy - this should more be faster
-	if (width == surf->w && height == surf->h)
+	if(width == surf->w && height == surf->h)
 		return copySurface(surf);
 
-	SDL_Surface *ret = newSurface(width, height, surf);
+	SDL_Surface * ret = newSurface(width, height, surf);
 
 	switch(surf->format->BytesPerPixel)
 	{
-	case 2: scaleSurfaceInternal<2>(surf, ret); break;
-	case 3: scaleSurfaceInternal<3>(surf, ret); break;
-	case 4: scaleSurfaceInternal<4>(surf, ret); break;
+	case 2:
+		scaleSurfaceInternal<2>(surf, ret);
+		break;
+	case 3:
+		scaleSurfaceInternal<3>(surf, ret);
+		break;
+	case 4:
+		scaleSurfaceInternal<4>(surf, ret);
+		break;
 	}
 
 	return ret;
 }
 
-void CSDL_Ext::blitSurface( SDL_Surface * src, const SDL_Rect * srcRect, SDL_Surface * dst, SDL_Rect * dstRect )
+void CSDL_Ext::blitSurface(SDL_Surface * src, const SDL_Rect * srcRect, SDL_Surface * dst, SDL_Rect * dstRect)
 {
-	if (dst != screen)
+	if(dst != screen)
 	{
 		SDL_UpperBlit(src, srcRect, dst, dstRect);
 	}
 	else
 	{
 		SDL_Rect betterDst;
-		if (dstRect)
+		if(dstRect)
 		{
 			betterDst = *dstRect;
 		}
@@ -736,10 +768,10 @@ void CSDL_Ext::blitSurface( SDL_Surface * src, const SDL_Rect * srcRect, SDL_Sur
 	}
 }
 
-void CSDL_Ext::fillRect( SDL_Surface *dst, SDL_Rect *dstrect, Uint32 color )
+void CSDL_Ext::fillRect(SDL_Surface * dst, SDL_Rect * dstrect, Uint32 color)
 {
 	SDL_Rect newRect;
-	if (dstrect)
+	if(dstrect)
 	{
 		newRect = *dstrect;
 	}
@@ -750,13 +782,13 @@ void CSDL_Ext::fillRect( SDL_Surface *dst, SDL_Rect *dstrect, Uint32 color )
 	SDL_FillRect(dst, &newRect, color);
 }
 
-void CSDL_Ext::fillRectBlack( SDL_Surface *dst, SDL_Rect *dstrect)
+void CSDL_Ext::fillRectBlack(SDL_Surface * dst, SDL_Rect * dstrect)
 {
-	const Uint32 black = SDL_MapRGB(dst->format,0,0,0);
-	fillRect(dst,dstrect,black);
+	const Uint32 black = SDL_MapRGB(dst->format, 0, 0, 0);
+	fillRect(dst, dstrect, black);
 }
 
-void CSDL_Ext::fillTexture(SDL_Surface *dst, SDL_Surface * src)
+void CSDL_Ext::fillTexture(SDL_Surface * dst, SDL_Surface * src)
 {
 	SDL_Rect srcRect;
 	SDL_Rect dstRect;
@@ -764,9 +796,9 @@ void CSDL_Ext::fillTexture(SDL_Surface *dst, SDL_Surface * src)
 	SDL_GetClipRect(src, &srcRect);
 	SDL_GetClipRect(dst, &dstRect);
 
-	for (int y=dstRect.y; y < dstRect.y + dstRect.h; y+=srcRect.h)
+	for(int y = dstRect.y; y < dstRect.y + dstRect.h; y += srcRect.h)
 	{
-		for (int x=dstRect.x; x < dstRect.x + dstRect.w; x+=srcRect.w)
+		for(int x = dstRect.x; x < dstRect.x + dstRect.w; x += srcRect.w)
 		{
 			int xLeft = std::min<int>(srcRect.w, dstRect.x + dstRect.w - x);
 			int yLeft = std::min<int>(srcRect.h, dstRect.y + dstRect.h - y);
@@ -784,7 +816,7 @@ SDL_Color CSDL_Ext::makeColor(ui8 r, ui8 g, ui8 b, ui8 a)
 
 void CSDL_Ext::startTextInput(SDL_Rect * where)
 {
-	if (SDL_IsTextInputActive() == SDL_FALSE)
+	if(SDL_IsTextInputActive() == SDL_FALSE)
 	{
 		SDL_StartTextInput();
 	}
@@ -793,7 +825,7 @@ void CSDL_Ext::startTextInput(SDL_Rect * where)
 
 void CSDL_Ext::stopTextInput()
 {
-	if (SDL_IsTextInputActive() == SDL_TRUE)
+	if(SDL_IsTextInputActive() == SDL_TRUE)
 	{
 		SDL_StopTextInput();
 	}
@@ -806,7 +838,7 @@ STRONG_INLINE static uint32_t mapColor(SDL_Surface * surface, SDL_Color color)
 
 void CSDL_Ext::setColorKey(SDL_Surface * surface, SDL_Color color)
 {
-	uint32_t key = mapColor(surface,color);
+	uint32_t key = mapColor(surface, color);
 	SDL_SetColorKey(surface, SDL_TRUE, key);
 }
 
@@ -817,11 +849,11 @@ void CSDL_Ext::setDefaultColorKey(SDL_Surface * surface)
 
 void CSDL_Ext::setDefaultColorKeyPresize(SDL_Surface * surface)
 {
-	uint32_t key = mapColor(surface,Colors::DEFAULT_KEY_COLOR);
+	uint32_t key = mapColor(surface, Colors::DEFAULT_KEY_COLOR);
 	auto & color = surface->format->palette->colors[key];
 
 	// set color key only if exactly such color was found
-	if (color.r == Colors::DEFAULT_KEY_COLOR.r && color.g == Colors::DEFAULT_KEY_COLOR.g && color.b == Colors::DEFAULT_KEY_COLOR.b)
+	if(color.r == Colors::DEFAULT_KEY_COLOR.r && color.g == Colors::DEFAULT_KEY_COLOR.g && color.b == Colors::DEFAULT_KEY_COLOR.b)
 		SDL_SetColorKey(surface, SDL_TRUE, key);
 }
 

+ 109 - 108
client/gui/SDL_Extensions.h

@@ -21,17 +21,17 @@ extern SDL_Window * mainWindow;
 extern SDL_Renderer * mainRenderer;
 extern SDL_Texture * screenTexture;
 
-inline void SDL_SetColors(SDL_Surface *surface, SDL_Color *colors, int firstcolor, int ncolors)
+inline void SDL_SetColors(SDL_Surface * surface, SDL_Color * colors, int firstcolor, int ncolors)
 {
-	SDL_SetPaletteColors(surface->format->palette,colors,firstcolor,ncolors);
+	SDL_SetPaletteColors(surface->format->palette, colors, firstcolor, ncolors);
 }
 
 inline void SDL_WarpMouse(int x, int y)
 {
-	SDL_WarpMouseInWindow(mainWindow,x,y);
+	SDL_WarpMouseInWindow(mainWindow, x, y);
 }
 
-void SDL_UpdateRect(SDL_Surface *surface, int x, int y, int w, int h);
+void SDL_UpdateRect(SDL_Surface * surface, int x, int y, int w, int h);
 
 inline bool isCtrlKeyDown()
 {
@@ -49,25 +49,25 @@ inline bool isShiftKeyDown()
 }
 namespace CSDL_Ext
 {
-	//todo: should this better be assignment operator?
-	STRONG_INLINE void colorAssign(SDL_Color & dest, const SDL_Color & source)
-	{
-		dest.r = source.r;
-		dest.g = source.g;
-		dest.b = source.b;
-		dest.a = source.a;
-	}
+//todo: should this better be assignment operator?
+STRONG_INLINE void colorAssign(SDL_Color & dest, const SDL_Color & source)
+{
+	dest.r = source.r;
+	dest.g = source.g;
+	dest.b = source.b;
+	dest.a = source.a;
+}
 
-	inline void setAlpha(SDL_Surface * bg, int value)
-	{
-		SDL_SetSurfaceAlphaMod(bg, value);
-	}
+inline void setAlpha(SDL_Surface * bg, int value)
+{
+	SDL_SetSurfaceAlphaMod(bg, value);
+}
 }
 struct Rect;
 
-extern SDL_Surface * screen, *screen2, *screenBuf;
-void blitAt(SDL_Surface * src, int x, int y, SDL_Surface * dst=screen);
-void blitAt(SDL_Surface * src, const SDL_Rect & pos, SDL_Surface * dst=screen);
+extern SDL_Surface * screen, * screen2, * screenBuf;
+void blitAt(SDL_Surface * src, int x, int y, SDL_Surface * dst = screen);
+void blitAt(SDL_Surface * src, const SDL_Rect & pos, SDL_Surface * dst = screen);
 bool isItIn(const SDL_Rect * rect, int x, int y);
 bool isItInOrLowerBounds(const SDL_Rect * rect, int x, int y);
 
@@ -104,122 +104,123 @@ template<typename IntType>
 std::string makeNumberShort(IntType number, IntType maxLength = 3) //the output is a string containing at most 5 characters [4 if positive] (eg. intead 10000 it gives 10k)
 {
 	IntType max = pow(10, maxLength);
-	if (std::abs(number) < max)
+	if(std::abs(number) < max)
 		return boost::lexical_cast<std::string>(number);
 
 	std::string symbols = " kMGTPE";
 	auto iter = symbols.begin();
 
-	while (number >= max)
+	while(number >= max)
 	{
 		number /= 1000;
 		iter++;
 
-		assert(iter != symbols.end());//should be enough even for int64
+		assert(iter != symbols.end()); //should be enough even for int64
 	}
 	return boost::lexical_cast<std::string>(number) + *iter;
 }
 
-typedef void (*TColorPutter)(Uint8 *&ptr, const Uint8 & R, const Uint8 & G, const Uint8 & B);
-typedef void (*TColorPutterAlpha)(Uint8 *&ptr, const Uint8 & R, const Uint8 & G, const Uint8 & B, const Uint8 & A);
+typedef void (* TColorPutter)(Uint8 * & ptr, const Uint8 & R, const Uint8 & G, const Uint8 & B);
+typedef void (* TColorPutterAlpha)(Uint8 * & ptr, const Uint8 & R, const Uint8 & G, const Uint8 & B, const Uint8 & A);
 
 inline SDL_Rect genRect(const int & hh, const int & ww, const int & xx, const int & yy)
 {
 	SDL_Rect ret;
-	ret.h=hh;
-	ret.w=ww;
-	ret.x=xx;
-	ret.y=yy;
+	ret.h = hh;
+	ret.w = ww;
+	ret.x = xx;
+	ret.y = yy;
 	return ret;
 }
 
 template<int bpp, int incrementPtr>
 struct ColorPutter
 {
-	static STRONG_INLINE void PutColor(Uint8 *&ptr, const Uint8 & R, const Uint8 & G, const Uint8 & B);
-	static STRONG_INLINE void PutColor(Uint8 *&ptr, const Uint8 & R, const Uint8 & G, const Uint8 & B, const Uint8 & A);
-	static STRONG_INLINE void PutColorAlphaSwitch(Uint8 *&ptr, const Uint8 & R, const Uint8 & G, const Uint8 & B, const Uint8 & A);
-	static STRONG_INLINE void PutColor(Uint8 *&ptr, const SDL_Color & Color);
-	static STRONG_INLINE void PutColorAlpha(Uint8 *&ptr, const SDL_Color & Color);
-	static STRONG_INLINE void PutColorRow(Uint8 *&ptr, const SDL_Color & Color, size_t count);
+	static STRONG_INLINE void PutColor(Uint8 * & ptr, const Uint8 & R, const Uint8 & G, const Uint8 & B);
+	static STRONG_INLINE void PutColor(Uint8 * & ptr, const Uint8 & R, const Uint8 & G, const Uint8 & B, const Uint8 & A);
+	static STRONG_INLINE void PutColorAlphaSwitch(Uint8 * & ptr, const Uint8 & R, const Uint8 & G, const Uint8 & B, const Uint8 & A);
+	static STRONG_INLINE void PutColor(Uint8 * & ptr, const SDL_Color & Color);
+	static STRONG_INLINE void PutColorAlpha(Uint8 * & ptr, const SDL_Color & Color);
+	static STRONG_INLINE void PutColorRow(Uint8 * & ptr, const SDL_Color & Color, size_t count);
 };
 
-typedef void (*BlitterWithRotationVal)(SDL_Surface *src,SDL_Rect srcRect, SDL_Surface * dst, SDL_Rect dstRect, ui8 rotation);
+typedef void (* BlitterWithRotationVal)(SDL_Surface * src, SDL_Rect srcRect, SDL_Surface * dst, SDL_Rect dstRect, ui8 rotation);
 
 namespace CSDL_Ext
 {
-	/// helper that will safely set and un-set ClipRect for SDL_Surface
-	class CClipRectGuard
+/// helper that will safely set and un-set ClipRect for SDL_Surface
+class CClipRectGuard
+{
+	SDL_Surface * surf;
+	SDL_Rect oldRect;
+
+public:
+	CClipRectGuard(SDL_Surface * surface, const SDL_Rect & rect)
+		: surf(surface)
+	{
+		SDL_GetClipRect(surf, &oldRect);
+		SDL_SetClipRect(surf, &rect);
+	}
+
+	~CClipRectGuard()
 	{
-		SDL_Surface * surf;
-		SDL_Rect oldRect;
-	public:
-		CClipRectGuard(SDL_Surface * surface, const SDL_Rect & rect):
-			surf(surface)
-		{
-			SDL_GetClipRect(surf, &oldRect);
-			SDL_SetClipRect(surf, &rect);
-		}
-
-		~CClipRectGuard()
-		{
-			SDL_SetClipRect(surf, &oldRect);
-		}
-	};
-
-	void blitSurface(SDL_Surface * src, const SDL_Rect * srcRect, SDL_Surface * dst, SDL_Rect * dstRect);
-	void fillRect(SDL_Surface *dst, SDL_Rect *dstrect, Uint32 color);
-	void fillRectBlack(SDL_Surface * dst, SDL_Rect * dstrect);
-	//fill dest image with source texture.
-	void fillTexture(SDL_Surface *dst, SDL_Surface * sourceTexture);
-
-	void SDL_PutPixelWithoutRefresh(SDL_Surface *ekran, const int & x, const int & y, const Uint8 & R, const Uint8 & G, const Uint8 & B, Uint8 A = 255);
-	void SDL_PutPixelWithoutRefreshIfInSurf(SDL_Surface *ekran, const int & x, const int & y, const Uint8 & R, const Uint8 & G, const Uint8 & B, Uint8 A = 255);
-
-	SDL_Surface * verticalFlip(SDL_Surface * toRot); //vertical flip
-	SDL_Surface * horizontalFlip(SDL_Surface * toRot); //horizontal flip
-	Uint32 SDL_GetPixel(SDL_Surface *surface, const int & x, const int & y, bool colorByte = false);
-	void alphaTransform(SDL_Surface * src); //adds transparency and shadows (partial handling only; see examples of using for details)
-	bool isTransparent(SDL_Surface * srf, int x, int y); //checks if surface is transparent at given position
-
-	Uint8 *getPxPtr(const SDL_Surface * const &srf, const int x, const int y);
-	TColorPutter getPutterFor(SDL_Surface  * const &dest, int incrementing); //incrementing: -1, 0, 1
-	TColorPutterAlpha getPutterAlphaFor(SDL_Surface  * const &dest, int incrementing); //incrementing: -1, 0, 1
-
-	template<int bpp>
-	int blit8bppAlphaTo24bppT(const SDL_Surface * src, const SDL_Rect * srcRect, SDL_Surface * dst, SDL_Rect * dstRect); //blits 8 bpp surface with alpha channel to 24 bpp surface
-	int blit8bppAlphaTo24bpp(const SDL_Surface * src, const SDL_Rect * srcRect, SDL_Surface * dst, SDL_Rect * dstRect); //blits 8 bpp surface with alpha channel to 24 bpp surface
-	Uint32 colorToUint32(const SDL_Color * color); //little endian only
-	SDL_Color makeColor(ui8 r, ui8 g, ui8 b, ui8 a);
-
-	void update(SDL_Surface * what = screen); //updates whole surface (default - main screen)
-	void drawBorder(SDL_Surface * sur, int x, int y, int w, int h, const int3 &color);
-	void drawBorder(SDL_Surface * sur, const SDL_Rect &r, const int3 &color);
-	void drawDashedBorder(SDL_Surface * sur, const Rect &r, const int3 &color);
-	void setPlayerColor(SDL_Surface * sur, PlayerColor player); //sets correct color of flags; -1 for neutral
-	std::string processStr(std::string str, std::vector<std::string> & tor); //replaces %s in string
-	SDL_Surface * newSurface(int w, int h, SDL_Surface * mod=screen); //creates new surface, with flags/format same as in surface given
-	SDL_Surface * copySurface(SDL_Surface * mod); //returns copy of given surface
-	template<int bpp>
-	SDL_Surface * createSurfaceWithBpp(int width, int height); //create surface with give bits per pixels value
-	void VflipSurf(SDL_Surface * surf); //fluipis given surface by vertical axis
-
-	//scale surface to required size.
-	//nearest neighbour algorithm
-	SDL_Surface * scaleSurfaceFast(SDL_Surface *surf, int width, int height);
-	// bilinear filtering. Uses fallback to scaleSurfaceFast in case of indexed surfaces
-	SDL_Surface * scaleSurface(SDL_Surface *surf, int width, int height);
-
-	template<int bpp>
-	void applyEffectBpp( SDL_Surface * surf, const SDL_Rect * rect, int mode );
-	void applyEffect(SDL_Surface * surf, const SDL_Rect * rect, int mode); //mode: 0 - sepia, 1 - grayscale
-
-	void startTextInput(SDL_Rect * where);
-	void stopTextInput();
-
-	void setColorKey(SDL_Surface * surface, SDL_Color color);
-	///set key-color to 0,255,255
-	void setDefaultColorKey(SDL_Surface * surface);
-	///set key-color to 0,255,255 only if it exactly mapped
-	void setDefaultColorKeyPresize(SDL_Surface * surface);
+		SDL_SetClipRect(surf, &oldRect);
+	}
+};
+
+void blitSurface(SDL_Surface * src, const SDL_Rect * srcRect, SDL_Surface * dst, SDL_Rect * dstRect);
+void fillRect(SDL_Surface * dst, SDL_Rect * dstrect, Uint32 color);
+void fillRectBlack(SDL_Surface * dst, SDL_Rect * dstrect);
+//fill dest image with source texture.
+void fillTexture(SDL_Surface * dst, SDL_Surface * sourceTexture);
+
+void SDL_PutPixelWithoutRefresh(SDL_Surface * ekran, const int & x, const int & y, const Uint8 & R, const Uint8 & G, const Uint8 & B, Uint8 A = 255);
+void SDL_PutPixelWithoutRefreshIfInSurf(SDL_Surface * ekran, const int & x, const int & y, const Uint8 & R, const Uint8 & G, const Uint8 & B, Uint8 A = 255);
+
+SDL_Surface * verticalFlip(SDL_Surface * toRot); //vertical flip
+SDL_Surface * horizontalFlip(SDL_Surface * toRot); //horizontal flip
+Uint32 SDL_GetPixel(SDL_Surface * surface, const int & x, const int & y, bool colorByte = false);
+void alphaTransform(SDL_Surface * src); //adds transparency and shadows (partial handling only; see examples of using for details)
+bool isTransparent(SDL_Surface * srf, int x, int y); //checks if surface is transparent at given position
+
+Uint8 * getPxPtr(const SDL_Surface * const & srf, const int x, const int y);
+TColorPutter getPutterFor(SDL_Surface * const & dest, int incrementing); //incrementing: -1, 0, 1
+TColorPutterAlpha getPutterAlphaFor(SDL_Surface * const & dest, int incrementing); //incrementing: -1, 0, 1
+
+template<int bpp>
+int blit8bppAlphaTo24bppT(const SDL_Surface * src, const SDL_Rect * srcRect, SDL_Surface * dst, SDL_Rect * dstRect); //blits 8 bpp surface with alpha channel to 24 bpp surface
+int blit8bppAlphaTo24bpp(const SDL_Surface * src, const SDL_Rect * srcRect, SDL_Surface * dst, SDL_Rect * dstRect); //blits 8 bpp surface with alpha channel to 24 bpp surface
+Uint32 colorToUint32(const SDL_Color * color); //little endian only
+SDL_Color makeColor(ui8 r, ui8 g, ui8 b, ui8 a);
+
+void update(SDL_Surface * what = screen); //updates whole surface (default - main screen)
+void drawBorder(SDL_Surface * sur, int x, int y, int w, int h, const int3 & color);
+void drawBorder(SDL_Surface * sur, const SDL_Rect & r, const int3 & color);
+void drawDashedBorder(SDL_Surface * sur, const Rect & r, const int3 & color);
+void setPlayerColor(SDL_Surface * sur, PlayerColor player); //sets correct color of flags; -1 for neutral
+std::string processStr(std::string str, std::vector<std::string> & tor); //replaces %s in string
+SDL_Surface * newSurface(int w, int h, SDL_Surface * mod = screen); //creates new surface, with flags/format same as in surface given
+SDL_Surface * copySurface(SDL_Surface * mod); //returns copy of given surface
+template<int bpp>
+SDL_Surface * createSurfaceWithBpp(int width, int height); //create surface with give bits per pixels value
+void VflipSurf(SDL_Surface * surf); //fluipis given surface by vertical axis
+
+//scale surface to required size.
+//nearest neighbour algorithm
+SDL_Surface * scaleSurfaceFast(SDL_Surface * surf, int width, int height);
+// bilinear filtering. Uses fallback to scaleSurfaceFast in case of indexed surfaces
+SDL_Surface * scaleSurface(SDL_Surface * surf, int width, int height);
+
+template<int bpp>
+void applyEffectBpp(SDL_Surface * surf, const SDL_Rect * rect, int mode);
+void applyEffect(SDL_Surface * surf, const SDL_Rect * rect, int mode); //mode: 0 - sepia, 1 - grayscale
+
+void startTextInput(SDL_Rect * where);
+void stopTextInput();
+
+void setColorKey(SDL_Surface * surface, SDL_Color color);
+///set key-color to 0,255,255
+void setDefaultColorKey(SDL_Surface * surface);
+///set key-color to 0,255,255 only if it exactly mapped
+void setDefaultColorKeyPresize(SDL_Surface * surface);
 }

+ 134 - 134
client/gui/SDL_Pixels.h

@@ -17,136 +17,136 @@
 //should be as fast as accessing via pointer at least for 3-4 bytes per pixel
 namespace Channels
 {
-	// channel not present in this format
-	struct channel_empty
-	{
-		static STRONG_INLINE void set(Uint8*, Uint8) {}
-		static STRONG_INLINE Uint8 get(const Uint8 *) { return 255;}
-	};
+// channel not present in this format
+struct channel_empty
+{
+	static STRONG_INLINE void set(Uint8 *, Uint8) {}
+	static STRONG_INLINE Uint8 get(const Uint8 *) { return 255;}
+};
 
-	// channel which uses whole pixel
-	template<int offset>
-	struct channel_pixel
+// channel which uses whole pixel
+template<int offset>
+struct channel_pixel
+{
+	static STRONG_INLINE void set(Uint8 * ptr, Uint8 value)
 	{
-		static STRONG_INLINE void set(Uint8 *ptr, Uint8 value)
-		{
-			ptr[offset] = value;
-		}
-
-		static STRONG_INLINE Uint8 get(const Uint8 *ptr)
-		{
-			return ptr[offset];
-		}
-	};
+		ptr[offset] = value;
+	}
 
-	// channel which uses part of pixel
-	template <int bits, int mask, int shift>
-	struct channel_subpx
+	static STRONG_INLINE Uint8 get(const Uint8 * ptr)
 	{
+		return ptr[offset];
+	}
+};
 
-		static void STRONG_INLINE set(Uint8 *ptr, Uint8 value)
-		{
-			Uint16 * const pixel = (Uint16*)ptr;
-			Uint8 subpx = value >> (8 - bits);
-			*pixel = (*pixel & ~mask) | ((subpx << shift) & mask );
-		}
+// channel which uses part of pixel
+template<int bits, int mask, int shift>
+struct channel_subpx
+{
 
-		static Uint8 STRONG_INLINE get(const Uint8 *ptr)
-		{
-			Uint8 subpx = (*((Uint16 *)ptr) & mask) >> shift;
-			return (subpx << (8 - bits)) | (subpx >> (2*bits - 8));
-		}
-	};
+	static void STRONG_INLINE set(Uint8 * ptr, Uint8 value)
+	{
+		Uint16 * const pixel = (Uint16 *)ptr;
+		Uint8 subpx = value >> (8 - bits);
+		* pixel = (*pixel & ~mask) | ((subpx << shift) & mask);
+	}
 
-	template<int bpp>
-	struct px
+	static Uint8 STRONG_INLINE get(const Uint8 * ptr)
 	{
-		static channel_empty r;
-		static channel_empty g;
-		static channel_empty b;
-		static channel_empty a;
-	};
+		Uint8 subpx = (*((Uint16 *)ptr) & mask) >> shift;
+		return (subpx << (8 - bits)) | (subpx >> (2 * bits - 8));
+	}
+};
+
+template<int bpp>
+struct px
+{
+	static channel_empty r;
+	static channel_empty g;
+	static channel_empty b;
+	static channel_empty a;
+};
 
 #if (SDL_BYTEORDER == SDL_BIG_ENDIAN)
 
-	template<>
-	struct px<4>
-	{
-		static channel_pixel<1> r;
-		static channel_pixel<2> g;
-		static channel_pixel<3> b;
-		static channel_pixel<0> a;
-	};
-
-	template<>
-	struct px<3>
-	{
-		static channel_pixel<0> r;
-		static channel_pixel<1> g;
-		static channel_pixel<2> b;
-		static channel_empty a;
-	};
+template<>
+struct px<4>
+{
+	static channel_pixel<1> r;
+	static channel_pixel<2> g;
+	static channel_pixel<3> b;
+	static channel_pixel<0> a;
+};
+
+template<>
+struct px<3>
+{
+	static channel_pixel<0> r;
+	static channel_pixel<1> g;
+	static channel_pixel<2> b;
+	static channel_empty a;
+};
 
 #else
 
-	template<>
-	struct px<4>
-	{
-		static channel_pixel<2> r;
-		static channel_pixel<1> g;
-		static channel_pixel<0> b;
-		static channel_pixel<3> a;
-	};
-
-	template<>
-	struct px<3>
-	{
-		static channel_pixel<2> r;
-		static channel_pixel<1> g;
-		static channel_pixel<0> b;
-		static channel_empty a;
-	};
+template<>
+struct px<4>
+{
+	static channel_pixel<2> r;
+	static channel_pixel<1> g;
+	static channel_pixel<0> b;
+	static channel_pixel<3> a;
+};
+
+template<>
+struct px<3>
+{
+	static channel_pixel<2> r;
+	static channel_pixel<1> g;
+	static channel_pixel<0> b;
+	static channel_empty a;
+};
 
 #endif
 
-	template<>
-	struct px<2>
-	{
-		static channel_subpx<5, 0xF800, 11> r;
-		static channel_subpx<6, 0x07E0, 5 > g;
-		static channel_subpx<5, 0x001F, 0 > b;
-		static channel_empty a;
-	};
+template<>
+struct px<2>
+{
+	static channel_subpx<5, 0xF800, 11> r;
+	static channel_subpx<6, 0x07E0, 5> g;
+	static channel_subpx<5, 0x001F, 0> b;
+	static channel_empty a;
+};
 }
 
 
-template <int incrementPtr>
+template<int incrementPtr>
 struct ColorPutter<2, incrementPtr>
 {
-	static STRONG_INLINE void PutColor(Uint8 *&ptr, const Uint8 & R, const Uint8 & G, const Uint8 & B);
-	static STRONG_INLINE void PutColor(Uint8 *&ptr, const Uint8 & R, const Uint8 & G, const Uint8 & B, const Uint8 & A);
-	static STRONG_INLINE void PutColorAlphaSwitch(Uint8 *&ptr, const Uint8 & R, const Uint8 & G, const Uint8 & B, const Uint8 & A);
-	static STRONG_INLINE void PutColor(Uint8 *&ptr, const SDL_Color & Color);
-	static STRONG_INLINE void PutColorAlpha(Uint8 *&ptr, const SDL_Color & Color);
-	static STRONG_INLINE void PutColorRow(Uint8 *&ptr, const SDL_Color & Color, size_t count);
+	static STRONG_INLINE void PutColor(Uint8 * & ptr, const Uint8 & R, const Uint8 & G, const Uint8 & B);
+	static STRONG_INLINE void PutColor(Uint8 * & ptr, const Uint8 & R, const Uint8 & G, const Uint8 & B, const Uint8 & A);
+	static STRONG_INLINE void PutColorAlphaSwitch(Uint8 * & ptr, const Uint8 & R, const Uint8 & G, const Uint8 & B, const Uint8 & A);
+	static STRONG_INLINE void PutColor(Uint8 * & ptr, const SDL_Color & Color);
+	static STRONG_INLINE void PutColorAlpha(Uint8 * & ptr, const SDL_Color & Color);
+	static STRONG_INLINE void PutColorRow(Uint8 * & ptr, const SDL_Color & Color, size_t count);
 };
 
 template<int bpp, int incrementPtr>
-STRONG_INLINE void ColorPutter<bpp, incrementPtr>::PutColorAlpha(Uint8 *&ptr, const SDL_Color & Color)
+STRONG_INLINE void ColorPutter<bpp, incrementPtr>::PutColorAlpha(Uint8 * & ptr, const SDL_Color & Color)
 {
 	PutColor(ptr, Color.r, Color.g, Color.b, Color.a);
 }
 
 template<int bpp, int incrementPtr>
-STRONG_INLINE void ColorPutter<bpp, incrementPtr>::PutColor(Uint8 *&ptr, const SDL_Color & Color)
+STRONG_INLINE void ColorPutter<bpp, incrementPtr>::PutColor(Uint8 * & ptr, const SDL_Color & Color)
 {
 	PutColor(ptr, Color.r, Color.g, Color.b);
 }
 
 template<int bpp, int incrementPtr>
-STRONG_INLINE void ColorPutter<bpp, incrementPtr>::PutColorAlphaSwitch(Uint8 *&ptr, const Uint8 & R, const Uint8 & G, const Uint8 & B, const Uint8 & A)
+STRONG_INLINE void ColorPutter<bpp, incrementPtr>::PutColorAlphaSwitch(Uint8 * & ptr, const Uint8 & R, const Uint8 & G, const Uint8 & B, const Uint8 & A)
 {
-	switch (A)
+	switch(A)
 	{
 	case 0:
 		ptr += bpp * incrementPtr;
@@ -154,11 +154,11 @@ STRONG_INLINE void ColorPutter<bpp, incrementPtr>::PutColorAlphaSwitch(Uint8 *&p
 	case 255:
 		PutColor(ptr, R, G, B);
 		return;
-	case 128:  // optimized
+	case 128: // optimized
 		PutColor(ptr,
-				 ((Uint16)R + Channels::px<bpp>::r.get(ptr)) >> 1,
-				 ((Uint16)G + Channels::px<bpp>::g.get(ptr)) >> 1,
-				 ((Uint16)B + Channels::px<bpp>::b.get(ptr)) >> 1);
+			 ((Uint16)R + Channels::px<bpp>::r.get(ptr)) >> 1,
+			 ((Uint16)G + Channels::px<bpp>::g.get(ptr)) >> 1,
+			 ((Uint16)B + Channels::px<bpp>::b.get(ptr)) >> 1);
 		return;
 	default:
 		PutColor(ptr, R, G, B, A);
@@ -167,20 +167,20 @@ STRONG_INLINE void ColorPutter<bpp, incrementPtr>::PutColorAlphaSwitch(Uint8 *&p
 }
 
 template<int bpp, int incrementPtr>
-STRONG_INLINE void ColorPutter<bpp, incrementPtr>::PutColor(Uint8 *&ptr, const Uint8 & R, const Uint8 & G, const Uint8 & B, const Uint8 & A)
+STRONG_INLINE void ColorPutter<bpp, incrementPtr>::PutColor(Uint8 * & ptr, const Uint8 & R, const Uint8 & G, const Uint8 & B, const Uint8 & A)
 {
-	PutColor(ptr, ((((Uint32)R - (Uint32)Channels::px<bpp>::r.get(ptr))*(Uint32)A) >> 8 ) + (Uint32)Channels::px<bpp>::r.get(ptr),
-				  ((((Uint32)G - (Uint32)Channels::px<bpp>::g.get(ptr))*(Uint32)A) >> 8 ) + (Uint32)Channels::px<bpp>::g.get(ptr),
-				  ((((Uint32)B - (Uint32)Channels::px<bpp>::b.get(ptr))*(Uint32)A) >> 8 ) + (Uint32)Channels::px<bpp>::b.get(ptr));
+	PutColor(ptr, ((((Uint32)R - (Uint32)Channels::px<bpp>::r.get(ptr)) * (Uint32)A) >> 8) + (Uint32)Channels::px<bpp>::r.get(ptr),
+		 ((((Uint32)G - (Uint32)Channels::px<bpp>::g.get(ptr)) * (Uint32)A) >> 8) + (Uint32)Channels::px<bpp>::g.get(ptr),
+		 ((((Uint32)B - (Uint32)Channels::px<bpp>::b.get(ptr)) * (Uint32)A) >> 8) + (Uint32)Channels::px<bpp>::b.get(ptr));
 }
 
 
 template<int bpp, int incrementPtr>
-STRONG_INLINE void ColorPutter<bpp, incrementPtr>::PutColor(Uint8 *&ptr, const Uint8 & R, const Uint8 & G, const Uint8 & B)
+STRONG_INLINE void ColorPutter<bpp, incrementPtr>::PutColor(Uint8 * & ptr, const Uint8 & R, const Uint8 & G, const Uint8 & B)
 {
 	static_assert(incrementPtr >= -1 && incrementPtr <= +1, "Invalid incrementPtr value!");
 
-	if (incrementPtr < 0)
+	if(incrementPtr < 0)
 		ptr -= bpp;
 
 	Channels::px<bpp>::r.set(ptr, R);
@@ -188,20 +188,20 @@ STRONG_INLINE void ColorPutter<bpp, incrementPtr>::PutColor(Uint8 *&ptr, const U
 	Channels::px<bpp>::b.set(ptr, B);
 	Channels::px<bpp>::a.set(ptr, 255);
 
-	if (incrementPtr > 0)
+	if(incrementPtr > 0)
 		ptr += bpp;
 
 }
 
 template<int bpp, int incrementPtr>
-STRONG_INLINE void ColorPutter<bpp, incrementPtr>::PutColorRow(Uint8 *&ptr, const SDL_Color & Color, size_t count)
+STRONG_INLINE void ColorPutter<bpp, incrementPtr>::PutColorRow(Uint8 * & ptr, const SDL_Color & Color, size_t count)
 {
-	if (count)
+	if(count)
 	{
-		Uint8 *pixel = ptr;
+		Uint8 * pixel = ptr;
 		PutColor(ptr, Color.r, Color.g, Color.b);
 
-		for (size_t i=0; i<count-1; i++)
+		for(size_t i = 0; i < count - 1; i++)
 		{
 			memcpy(ptr, pixel, bpp);
 			ptr += bpp * incrementPtr;
@@ -209,23 +209,23 @@ STRONG_INLINE void ColorPutter<bpp, incrementPtr>::PutColorRow(Uint8 *&ptr, cons
 	}
 }
 
-template <int incrementPtr>
-STRONG_INLINE void ColorPutter<2, incrementPtr>::PutColor(Uint8 *&ptr, const Uint8 & R, const Uint8 & G, const Uint8 & B)
+template<int incrementPtr>
+STRONG_INLINE void ColorPutter<2, incrementPtr>::PutColor(Uint8 * & ptr, const Uint8 & R, const Uint8 & G, const Uint8 & B)
 {
 	if(incrementPtr == -1)
 		ptr -= 2;
 
-	Uint16 * const px = (Uint16*)ptr;
-	*px = (B>>3) + ((G>>2) << 5) + ((R>>3) << 11); //drop least significant bits of 24 bpp encoded color
+	Uint16 * const px = (Uint16 *)ptr;
+	*px = (B >> 3) + ((G >> 2) << 5) + ((R >> 3) << 11); //drop least significant bits of 24 bpp encoded color
 
 	if(incrementPtr == 1)
 		ptr += 2; //bpp
 }
 
-template <int incrementPtr>
-STRONG_INLINE void ColorPutter<2, incrementPtr>::PutColorAlphaSwitch(Uint8 *&ptr, const Uint8 & R, const Uint8 & G, const Uint8 & B, const Uint8 & A)
+template<int incrementPtr>
+STRONG_INLINE void ColorPutter<2, incrementPtr>::PutColorAlphaSwitch(Uint8 * & ptr, const Uint8 & R, const Uint8 & G, const Uint8 & B, const Uint8 & A)
 {
-	switch (A)
+	switch(A)
 	{
 	case 0:
 		ptr += 2 * incrementPtr;
@@ -239,46 +239,46 @@ STRONG_INLINE void ColorPutter<2, incrementPtr>::PutColorAlphaSwitch(Uint8 *&ptr
 	}
 }
 
-template <int incrementPtr>
-STRONG_INLINE void ColorPutter<2, incrementPtr>::PutColor(Uint8 *&ptr, const Uint8 & R, const Uint8 & G, const Uint8 & B, const Uint8 & A)
+template<int incrementPtr>
+STRONG_INLINE void ColorPutter<2, incrementPtr>::PutColor(Uint8 * & ptr, const Uint8 & R, const Uint8 & G, const Uint8 & B, const Uint8 & A)
 {
 	const int rbit = 5, gbit = 6, bbit = 5; //bits per color
 	const int rmask = 0xF800, gmask = 0x7E0, bmask = 0x1F;
 	const int rshift = 11, gshift = 5, bshift = 0;
 
 	const Uint8 r5 = (*((Uint16 *)ptr) & rmask) >> rshift,
-		b5 = (*((Uint16 *)ptr) & bmask) >> bshift,
-		g5 = (*((Uint16 *)ptr) & gmask) >> gshift;
+		    b5 = (*((Uint16 *)ptr) & bmask) >> bshift,
+		    g5 = (*((Uint16 *)ptr) & gmask) >> gshift;
 
-	const Uint32 r8 = (r5 << (8 - rbit)) | (r5 >> (2*rbit - 8)),
-		g8 = (g5 << (8 - gbit)) | (g5 >> (2*gbit - 8)),
-		b8 = (b5 << (8 - bbit)) | (b5 >> (2*bbit - 8));
+	const Uint32 r8 = (r5 << (8 - rbit)) | (r5 >> (2 * rbit - 8)),
+		     g8 = (g5 << (8 - gbit)) | (g5 >> (2 * gbit - 8)),
+		     b8 = (b5 << (8 - bbit)) | (b5 >> (2 * bbit - 8));
 
 	PutColor(ptr,
-		(((R-r8)*A) >> 8) + r8,
-		(((G-g8)*A) >> 8) + g8,
-		(((B-b8)*A) >> 8) + b8);
+		 (((R - r8) * A) >> 8) + r8,
+		 (((G - g8) * A) >> 8) + g8,
+		 (((B - b8) * A) >> 8) + b8);
 }
 
-template <int incrementPtr>
-STRONG_INLINE void ColorPutter<2, incrementPtr>::PutColorAlpha(Uint8 *&ptr, const SDL_Color & Color)
+template<int incrementPtr>
+STRONG_INLINE void ColorPutter<2, incrementPtr>::PutColorAlpha(Uint8 * & ptr, const SDL_Color & Color)
 {
 	PutColor(ptr, Color.r, Color.g, Color.b, Color.a);
 }
 
-template <int incrementPtr>
-STRONG_INLINE void ColorPutter<2, incrementPtr>::PutColor(Uint8 *&ptr, const SDL_Color & Color)
+template<int incrementPtr>
+STRONG_INLINE void ColorPutter<2, incrementPtr>::PutColor(Uint8 * & ptr, const SDL_Color & Color)
 {
 	PutColor(ptr, Color.r, Color.g, Color.b);
 }
 
-template <int incrementPtr>
-STRONG_INLINE void ColorPutter<2, incrementPtr>::PutColorRow(Uint8 *&ptr, const SDL_Color & Color, size_t count)
+template<int incrementPtr>
+STRONG_INLINE void ColorPutter<2, incrementPtr>::PutColorRow(Uint8 * & ptr, const SDL_Color & Color, size_t count)
 {
 	//drop least significant bits of 24 bpp encoded color
-	Uint16 pixel = (Color.b>>3) + ((Color.g>>2) << 5) + ((Color.r>>3) << 11);
+	Uint16 pixel = (Color.b >> 3) + ((Color.g >> 2) << 5) + ((Color.r >> 3) << 11);
 
-	for (size_t i=0; i<count; i++)
+	for(size_t i = 0; i < count; i++)
 	{
 		memcpy(ptr, &pixel, 2);
 		if(incrementPtr == -1)

File diff suppressed because it is too large
+ 234 - 233
client/mapHandler.cpp


+ 56 - 56
client/mapHandler.h

@@ -48,7 +48,6 @@ enum class EWorldViewIcon
 	RES_CRYSTAL,
 	RES_GEM,
 	RES_GOLD,
-
 };
 
 enum class EMapObjectFadingType
@@ -66,11 +65,11 @@ enum class EMapAnimRedrawStatus
 
 struct TerrainTileObject
 {
-	const CGObjectInstance *obj;
+	const CGObjectInstance * obj;
 	SDL_Rect rect;
 	int fadeAnimKey;
 
-	TerrainTileObject(const CGObjectInstance *obj_, SDL_Rect rect_);
+	TerrainTileObject(const CGObjectInstance * obj_, SDL_Rect rect_);
 	~TerrainTileObject();
 };
 
@@ -82,8 +81,8 @@ struct TerrainTile2
 struct MapDrawingInfo
 {
 	bool scaled;
-	int3 &topTile; // top-left tile in viewport [in tiles]
-	const std::vector< std::vector< std::vector<ui8> > > * visibilityMap;
+	int3 & topTile; // top-left tile in viewport [in tiles]
+	const std::vector<std::vector<std::vector<ui8>>> * visibilityMap;
 	SDL_Rect * drawBounds; // map rect drawing bounds on screen
 	std::shared_ptr<CAnimation> icons; // holds overlay icons for world view mode
 	float scale; // map scale for world view mode (only if scaled == true)
@@ -101,43 +100,31 @@ struct MapDrawingInfo
 
 	bool showAllTerrain; //for expert viewEarth
 
-	MapDrawingInfo(int3 &topTile_, const std::vector< std::vector< std::vector<ui8> > > * visibilityMap_, SDL_Rect * drawBounds_, std::shared_ptr<CAnimation> icons_ = nullptr)
-		: scaled(false),
-		  topTile(topTile_),
-		  visibilityMap(visibilityMap_),
-		  drawBounds(drawBounds_),
-		  icons(icons_),
-		  scale(1.0f),
-		  otherheroAnim(false),
-		  anim(0u),
-		  heroAnim(0u),
-		  movement(int3()),
-		  puzzleMode(false),
-		  grailPos(int3()),
-		  additionalIcons(nullptr),
-		  showAllTerrain(false)
+	MapDrawingInfo(int3 & topTile_, const std::vector<std::vector<std::vector<ui8>>> * visibilityMap_, SDL_Rect * drawBounds_, std::shared_ptr<CAnimation> icons_ = nullptr)
+		: scaled(false), topTile(topTile_), visibilityMap(visibilityMap_), drawBounds(drawBounds_), icons(icons_), scale(1.0f), otherheroAnim(false), anim(0u), heroAnim(0u), movement(int3()), puzzleMode(false), grailPos(int3()), additionalIcons(nullptr), showAllTerrain(false)
 	{}
 
 	ui8 getHeroAnim() const { return otherheroAnim ? anim : heroAnim; }
 };
 
 
-template <typename T> class PseudoV
+template<typename T> class PseudoV
 {
 public:
-	PseudoV() : offset(0) { }
+	PseudoV()
+		: offset(0) {}
 	inline T & operator[](const int & n)
 	{
-		return inver[n+offset];
+		return inver[n + offset];
 	}
 	inline const T & operator[](const int & n) const
 	{
-		return inver[n+offset];
+		return inver[n + offset];
 	}
 	void resize(int rest, int before, int after)
 	{
 		inver.resize(before + rest + after);
-		offset=before;
+		offset = before;
 	}
 	int size() const
 	{
@@ -148,19 +135,29 @@ private:
 	int offset;
 	std::vector<T> inver;
 };
+
 class CMapHandler
 {
 	enum class EMapCacheType : ui8
 	{
-		TERRAIN, OBJECTS, ROADS, RIVERS, FOW, HEROES, HERO_FLAGS, FRAME, AFTER_LAST
+		TERRAIN,
+		OBJECTS,
+		ROADS,
+		RIVERS,
+		FOW,
+		HEROES,
+		HERO_FLAGS,
+		FRAME,
+		AFTER_LAST
 	};
 
 	/// temporarily caches rescaled frames for map world view redrawing
 	class CMapCache
 	{
-		std::array< std::map<intptr_t, std::unique_ptr<IImage>>, (ui8)EMapCacheType::AFTER_LAST> data;
+		std::array<std::map<intptr_t, std::unique_ptr<IImage>>, (ui8)EMapCacheType::AFTER_LAST> data;
 		float worldViewCachedScale;
-	public:
+
+public:
 		CMapCache();
 		/// destroys all cached data (frees surfaces)
 		void discardWorldViewCache();
@@ -178,15 +175,13 @@ class CMapHandler
 		bool isMoving; // indicates if the object is moving (again, heroes/boats only)
 
 		AnimBitmapHolder(IImage * objBitmap_ = nullptr, IImage * flagBitmap_ = nullptr, bool moving = false)
-			: objBitmap(objBitmap_),
-			  flagBitmap(flagBitmap_),
-			  isMoving(moving)
+			: objBitmap(objBitmap_), flagBitmap(flagBitmap_), isMoving(moving)
 		{}
 	};
 
 	class CMapBlitter
 	{
-	protected:
+protected:
 		const int FRAMES_PER_MOVE_ANIM_GROUP = 8;
 		CMapHandler * parent; // ptr to enclosing map handler; generally for legacy reasons, probably could/should be refactored out of here
 		int tileSize; // size of a tile drawn on map [in pixels]
@@ -240,7 +235,7 @@ class CMapHandler
 		virtual SDL_Rect clip(SDL_Surface * targetSurf) const = 0;
 
 		virtual ui8 getHeroFrameGroup(ui8 dir, bool isMoving) const;
-		virtual ui8 getPhaseShift(const CGObjectInstance *object) const;
+		virtual ui8 getPhaseShift(const CGObjectInstance * object) const;
 
 		virtual bool canDrawObject(const CGObjectInstance * obj) const;
 		virtual bool canDrawCurrentTile() const;
@@ -253,7 +248,7 @@ class CMapHandler
 		IImage * findBoatFlagBitmap(const CGBoat * obj, int anim, const PlayerColor * color, int group, ui8 dir) const;
 		IImage * findFlagBitmapInternal(std::shared_ptr<CAnimation> animation, int anim, int group, ui8 dir, bool moving) const;
 
-	public:
+public:
 		CMapBlitter(CMapHandler * p);
 		virtual ~CMapBlitter();
 		void blit(SDL_Surface * targetSurf, const MapDrawingInfo * info);
@@ -263,21 +258,23 @@ class CMapHandler
 
 	class CMapNormalBlitter : public CMapBlitter
 	{
-	protected:
+protected:
 		void drawElement(EMapCacheType cacheType, const IImage * source, SDL_Rect * sourceRect, SDL_Surface * targetSurf, SDL_Rect * destRect) const override;
-		void drawTileOverlay(SDL_Surface * targetSurf,const TerrainTile2 & tile) const override {}
+		void drawTileOverlay(SDL_Surface * targetSurf, const TerrainTile2 & tile) const override {}
 		void init(const MapDrawingInfo * info) override;
 		SDL_Rect clip(SDL_Surface * targetSurf) const override;
-	public:
+
+public:
 		CMapNormalBlitter(CMapHandler * parent);
 		virtual ~CMapNormalBlitter(){}
 	};
 
 	class CMapWorldViewBlitter : public CMapBlitter
 	{
-	private:
+private:
 		IImage * objectToIcon(Obj id, si32 subId, PlayerColor owner) const;
-	protected:
+
+protected:
 		void drawElement(EMapCacheType cacheType, const IImage * source, SDL_Rect * sourceRect, SDL_Surface * targetSurf, SDL_Rect * destRect) const override;
 		void drawTileOverlay(SDL_Surface * targetSurf, const TerrainTile2 & tile) const override;
 		void drawHeroFlag(SDL_Surface * targetSurf, const IImage * source, SDL_Rect * sourceRect, SDL_Rect * destRect, bool moving) const override;
@@ -286,9 +283,10 @@ class CMapHandler
 		void drawOverlayEx(SDL_Surface * targetSurf) override;
 		void init(const MapDrawingInfo * info) override;
 		SDL_Rect clip(SDL_Surface * targetSurf) const override;
-		ui8 getPhaseShift(const CGObjectInstance *object) const override { return 0u; }
+		ui8 getPhaseShift(const CGObjectInstance * object) const override { return 0u; }
 		void calculateWorldViewCameraPos();
-	public:
+
+public:
 		CMapWorldViewBlitter(CMapHandler * parent);
 		virtual ~CMapWorldViewBlitter(){}
 	};
@@ -302,7 +300,8 @@ class CMapHandler
 		void postProcessing(SDL_Surface * targetSurf) const override;
 		bool canDrawObject(const CGObjectInstance * obj) const override;
 		bool canDrawCurrentTile() const override { return true; }
-	public:
+
+public:
 		CMapPuzzleViewBlitter(CMapHandler * parent);
 	};
 
@@ -311,7 +310,7 @@ class CMapHandler
 	CMapBlitter * worldViewBlitter;
 	CMapBlitter * puzzleViewBlitter;
 
-	std::map<int, std::pair<int3, CFadeAnimation*>> fadeAnims;
+	std::map<int, std::pair<int3, CFadeAnimation *>> fadeAnims;
 	int fadeAnimCounter;
 
 	CMapBlitter * resolveBlitter(const MapDrawingInfo * info) const;
@@ -322,8 +321,9 @@ class CMapHandler
 	void initBorderGraphics();
 	void initTerrainGraphics();
 	void prepareFOWDefs();
+
 public:
-	PseudoV< PseudoV< PseudoV<TerrainTile2> > > ttiles; //informations about map tiles
+	PseudoV<PseudoV<PseudoV<TerrainTile2>>> ttiles; //informations about map tiles
 	int3 sizes; //map size (x = width, y = height, z = number of levels)
 	const CMap * map;
 
@@ -346,34 +346,34 @@ public:
 
 	//FIXME: unique_ptr should be enough, but fails to compile in MSVS 2013
 	typedef std::vector<std::array<std::shared_ptr<CAnimation>, 4>> TFlippedAnimations; //[type, rotation]
-	typedef std::vector<std::vector<std::array<IImage *, 4>>> TFlippedCache;//[type, view type, rotation]
+	typedef std::vector<std::vector<std::array<IImage *, 4>>> TFlippedCache; //[type, view type, rotation]
 
-	TFlippedAnimations terrainAnimations;//[terrain type, rotation]
-	TFlippedCache terrainImages;//[terrain type, view type, rotation]
+	TFlippedAnimations terrainAnimations; //[terrain type, rotation]
+	TFlippedCache terrainImages; //[terrain type, view type, rotation]
 
-	TFlippedAnimations roadAnimations;//[road type, rotation]
-	TFlippedCache roadImages;//[road type, view type, rotation]
+	TFlippedAnimations roadAnimations; //[road type, rotation]
+	TFlippedCache roadImages; //[road type, view type, rotation]
 
-	TFlippedAnimations riverAnimations;//[river type, rotation]
-	TFlippedCache riverImages;//[river type, view type, rotation]
+	TFlippedAnimations riverAnimations; //[river type, rotation]
+	TFlippedCache riverImages; //[river type, view type, rotation]
 
 	//Fog of War cache (not owned)
 	std::vector<const IImage *> FoWfullHide;
-	std::vector<std::vector<std::vector<ui8> > > hideBitmap; //frame indexes (in FoWfullHide) of graphic that should be used to fully hide a tile
+	std::vector<std::vector<std::vector<ui8>>> hideBitmap; //frame indexes (in FoWfullHide) of graphic that should be used to fully hide a tile
 
 	std::vector<const IImage *> FoWpartialHide;
 
 	//edge graphics
 	std::unique_ptr<CAnimation> egdeAnimation;
-	std::vector<const IImage *> egdeImages;//cache of links to egdeAnimation (for faster access)
-	PseudoV< PseudoV< PseudoV <ui8> > > edgeFrames; //frame indexes (in egdeImages) of tile outside of map
+	std::vector<const IImage *> egdeImages; //cache of links to egdeAnimation (for faster access)
+	PseudoV<PseudoV<PseudoV<ui8>>> edgeFrames; //frame indexes (in egdeImages) of tile outside of map
 
-	mutable std::map<const CGObjectInstance*, ui8> animationPhase;
+	mutable std::map<const CGObjectInstance *, ui8> animationPhase;
 
 	CMapHandler();
 	~CMapHandler();
 
-	void getTerrainDescr(const int3 &pos, std::string & out, bool terName); //if tername == false => empty string when tile is clear
+	void getTerrainDescr(const int3 & pos, std::string & out, bool terName); //if tername == false => empty string when tile is clear
 	bool printObject(const CGObjectInstance * obj, bool fadein = false); //puts appropriate things to tiles, so obj will be visible on map
 	bool hideObject(const CGObjectInstance * obj, bool fadeout = false); //removes appropriate things from ttiles, so obj will be no longer visible on map (but still will exist)
 	void init();

+ 1 - 1
client/resource.h

@@ -5,7 +5,7 @@
 #define IDI_ICON1                       101
 
 // Next default values for new objects
-// 
+//
 #ifdef APSTUDIO_INVOKED
 #ifndef APSTUDIO_READONLY_SYMBOLS
 #define _APS_NEXT_RESOURCE_VALUE        102

File diff suppressed because it is too large
+ 209 - 221
client/widgets/AdventureMapClasses.cpp


+ 54 - 40
client/widgets/AdventureMapClasses.h

@@ -34,7 +34,8 @@ protected:
 	{
 		CList * parent;
 		CIntObject * selection;
-	public:
+
+public:
 		CListItem(CList * parent);
 		~CListItem();
 
@@ -44,16 +45,16 @@ protected:
 		void onSelect(bool on);
 
 		/// create object with selection rectangle
-		virtual CIntObject * genSelection()=0;
+		virtual CIntObject * genSelection() = 0;
 		/// reaction on item selection (e.g. enable selection border)
 		/// NOTE: item may be deleted in selected state
-		virtual void select(bool on)=0;
+		virtual void select(bool on) = 0;
 		/// open item (town or hero screen)
-		virtual void open()=0;
+		virtual void open() = 0;
 		/// show right-click tooltip
-		virtual void showTooltip()=0;
+		virtual void showTooltip() = 0;
 		/// get hover text for status bar
-		virtual std::string getHoverText()=0;
+		virtual std::string getHoverText() = 0;
 	};
 
 	CListBox * list;
@@ -71,11 +72,10 @@ protected:
 	 * @param create - function for creating items in listbox
 	 * @param destroy - function for deleting items in listbox
 	 */
-	CList(int size, Point position, std::string btnUp, std::string btnDown, size_t listAmount, int helpUp, int helpDown,
-		  CListBox::CreateFunc create, CListBox::DestroyFunc destroy = CListBox::DestroyFunc());
+	CList(int size, Point position, std::string btnUp, std::string btnDown, size_t listAmount, int helpUp, int helpDown, CListBox::CreateFunc create, CListBox::DestroyFunc destroy = CListBox::DestroyFunc());
 
 	//for selection\deselection
-	CListItem *selected;
+	CListItem * selected;
 	void select(CListItem * which);
 	friend class CListItem;
 
@@ -100,12 +100,12 @@ public:
 };
 
 /// List of heroes which is shown at the right of the adventure map screen
-class CHeroList	: public CList
+class CHeroList : public CList
 {
 	/// Empty hero item used as placeholder for unused entries in list
 	class CEmptyHeroItem : public CIntObject
 	{
-	public:
+public:
 		CEmptyHeroItem();
 	};
 
@@ -114,10 +114,11 @@ class CHeroList	: public CList
 		CAnimImage * movement;
 		CAnimImage * mana;
 		CAnimImage * portrait;
-	public:
+
+public:
 		const CGHeroInstance * const hero;
 
-		CHeroItem(CHeroList *parent, const CGHeroInstance * hero);
+		CHeroItem(CHeroList * parent, const CGHeroInstance * hero);
 
 		CIntObject * genSelection() override;
 		void update();
@@ -128,6 +129,7 @@ class CHeroList	: public CList
 	};
 
 	CIntObject * createHeroItem(size_t index);
+
 public:
 	/**
 	 * @brief CHeroList
@@ -143,15 +145,16 @@ public:
 };
 
 /// List of towns which is shown at the right of the adventure map screen or in the town screen
-class CTownList	: public CList
+class CTownList : public CList
 {
 	class CTownItem : public CListItem
 	{
 		CAnimImage * picture;
-	public:
+
+public:
 		const CGTownInstance * const town;
 
-		CTownItem(CTownList *parent, const CGTownInstance * town);
+		CTownItem(CTownList * parent, const CGTownInstance * town);
 
 		CIntObject * genSelection() override;
 		void update();
@@ -162,6 +165,7 @@ class CTownList	: public CList
 	};
 
 	CIntObject * createTownItem(size_t index);
+
 public:
 	/**
 	 * @brief CTownList
@@ -180,26 +184,27 @@ class CMinimap;
 
 class CMinimapInstance : public CIntObject
 {
-	CMinimap *parent;
+	CMinimap * parent;
 	SDL_Surface * minimap;
 	int level;
 
 	//get color of selected tile on minimap
 	const SDL_Color & getTileColor(const int3 & pos);
 
-	void blitTileWithColor(const SDL_Color & color, const int3 & pos, SDL_Surface *to, int x, int y);
+	void blitTileWithColor(const SDL_Color & color, const int3 & pos, SDL_Surface * to, int x, int y);
 
 	//draw minimap already scaled.
 	//result is not antialiased. Will result in "missing" pixels on huge maps (>144)
 	void drawScaled(int level);
+
 public:
 	CMinimapInstance(CMinimap * parent, int level);
 	~CMinimapInstance();
 
-	void showAll(SDL_Surface *to) override;
-	void tileToPixels (const int3 &tile, int &x, int &y,int toX = 0, int toY = 0);
+	void showAll(SDL_Surface * to) override;
+	void tileToPixels(const int3 & tile, int & x, int & y, int toX = 0, int toY = 0);
 
-	void refreshTile(const int3 &pos);
+	void refreshTile(const int3 & pos);
 };
 
 /// Minimap which is displayed at the right upper corner of adventure map
@@ -207,23 +212,23 @@ class CMinimap : public CIntObject
 {
 protected:
 
-	CPicture *aiShield; //the graphic displayed during AI turn
+	CPicture * aiShield; //the graphic displayed during AI turn
 	CMinimapInstance * minimap;
 	int level;
 
 	//to initialize colors
-	std::map<int, std::pair<SDL_Color, SDL_Color> > loadColors(std::string from);
+	std::map<int, std::pair<SDL_Color, SDL_Color>> loadColors(std::string from);
 
 	void clickLeft(tribool down, bool previousState) override;
 	void clickRight(tribool down, bool previousState) override;
-	void hover (bool on) override;
-	void mouseMoved (const SDL_MouseMotionEvent & sEvent) override;
+	void hover(bool on) override;
+	void mouseMoved(const SDL_MouseMotionEvent & sEvent) override;
 
 	void moveAdvMapSelection();
 
 public:
 	// terrainID -> (normal color, blocked color)
-	const std::map<int, std::pair<SDL_Color, SDL_Color> > colors;
+	const std::map<int, std::pair<SDL_Color, SDL_Color>> colors;
 
 	CMinimap(const Rect & position);
 
@@ -235,8 +240,8 @@ public:
 
 	void showAll(SDL_Surface * to) override;
 
-	void hideTile(const int3 &pos); //puts FoW
-	void showTile(const int3 &pos); //removes FoW
+	void hideTile(const int3 & pos); //puts FoW
+	void showTile(const int3 & pos); //removes FoW
 };
 
 /// Info box which shows next week/day information, hold the current date
@@ -249,15 +254,15 @@ class CInfoBar : public CIntObject
 		std::list<CIntObject *> forceRefresh;
 
 		//the only part of gui we need to know about for updating - AI progress
-		CAnimImage *aiProgress;
+		CAnimImage * aiProgress;
 
 		std::string getNewDayName();
 		void playNewDaySound();
 
-	public:
+public:
 		CVisibleInfo(Point position);
 
-		void show(SDL_Surface *to) override;
+		void show(SDL_Surface * to) override;
 
 		//functions that must be called only once
 		void loadHero(const CGHeroInstance * hero);
@@ -265,7 +270,7 @@ class CInfoBar : public CIntObject
 		void loadDay();
 		void loadEnemyTurn(PlayerColor player);
 		void loadGameStatus();
-		void loadComponent(const Component &comp, std::string message);
+		void loadComponent(const Component & comp, std::string message);
 
 		//can be called multiple times
 		void updateEnemyTurn(double progress);
@@ -273,7 +278,13 @@ class CInfoBar : public CIntObject
 
 	enum EState
 	{
-		EMPTY, HERO, TOWN, DATE, GAME, AITURN, COMPONENT
+		EMPTY,
+		HERO,
+		TOWN,
+		DATE,
+		GAME,
+		AITURN,
+		COMPONENT
 	};
 
 	CVisibleInfo * visibleInfo;
@@ -323,6 +334,7 @@ class CAdvMapPanel : public CIntObject
 	std::vector<CButton *> buttons;
 	/// the surface passed to this obj will be freed in dtor
 	SDL_Surface * background;
+
 public:
 	CAdvMapPanel(SDL_Surface * bg, Point position);
 	virtual ~CAdvMapPanel();
@@ -346,30 +358,32 @@ class CAdvMapWorldViewPanel : public CAdvMapPanel
 	SDL_Surface * tmpBackgroundFiller;
 	int fillerHeight;
 	std::shared_ptr<CAnimation> icons;
+
 public:
-	CAdvMapWorldViewPanel(std::shared_ptr<CAnimation> _icons, SDL_Surface * bg, Point position, int spaceBottom, const PlayerColor &color);
+	CAdvMapWorldViewPanel(std::shared_ptr<CAnimation> _icons, SDL_Surface * bg, Point position, int spaceBottom, const PlayerColor & color);
 	virtual ~CAdvMapWorldViewPanel();
 
 	void addChildIcon(std::pair<int, Point> data, int indexOffset);
 	/// recreates all pictures from given def to recolor them according to current player color
-	void recolorIcons(const PlayerColor &color, int indexOffset);
+	void recolorIcons(const PlayerColor & color, int indexOffset);
 	void showAll(SDL_Surface * to) override;
 };
 
 class CInGameConsole : public CIntObject
 {
 private:
-	std::list< std::pair< std::string, int > > texts; //list<text to show, time of add>
-	boost::mutex texts_mx;		// protects texts
-	std::vector< std::string > previouslyEntered; //previously entered texts, for up/down arrows to work
+	std::list<std::pair<std::string, int>> texts; //list<text to show, time of add>
+	boost::mutex texts_mx; // protects texts
+	std::vector<std::string> previouslyEntered; //previously entered texts, for up/down arrows to work
 	int prevEntDisp; //displayed entry from previouslyEntered - if none it's -1
 	int defaultTimeout; //timeout for new texts (in ms)
 	int maxDisplayedTexts; //hiw many texts can be displayed simultaneously
+
 public:
 	std::string enteredText;
 	void show(SDL_Surface * to) override;
-	void print(const std::string &txt);
-	void keyPressed (const SDL_KeyboardEvent & key) override; //call-in
+	void print(const std::string & txt);
+	void keyPressed(const SDL_KeyboardEvent & key) override; //call-in
 
 	void textInputed(const SDL_TextInputEvent & event) override;
 	void textEdited(const SDL_TextEditingEvent & event) override;

+ 96 - 105
client/widgets/Buttons.cpp

@@ -25,23 +25,23 @@
 
 void CButton::update()
 {
-	if (overlay)
+	if(overlay)
 	{
-		if (state == PRESSED)
-			overlay->moveTo(overlay->pos.centerIn(pos).topLeft() + Point(1,1));
+		if(state == PRESSED)
+			overlay->moveTo(overlay->pos.centerIn(pos).topLeft() + Point(1, 1));
 		else
 			overlay->moveTo(overlay->pos.centerIn(pos).topLeft());
 	}
 
 	int newPos = stateToIndex[int(state)];
-	if (newPos < 0)
+	if(newPos < 0)
 		newPos = 0;
 
-	if (state == HIGHLIGHTED && image->size() < 4)
-		newPos = image->size()-1;
+	if(state == HIGHLIGHTED && image->size() < 4)
+		newPos = image->size() - 1;
 	image->setFrame(newPos);
 
-	if (active)
+	if(active)
 		redraw();
 }
 
@@ -50,14 +50,14 @@ void CButton::addCallback(std::function<void()> callback)
 	this->callback += callback;
 }
 
-void CButton::addTextOverlay( const std::string &Text, EFonts font, SDL_Color color)
+void CButton::addTextOverlay(const std::string & Text, EFonts font, SDL_Color color)
 {
 	OBJ_CONSTRUCTION_CAPTURING_ALL;
-	addOverlay(new CLabel(pos.w/2, pos.h/2, font, CENTER, color, Text));
+	addOverlay(new CLabel(pos.w / 2, pos.h / 2, font, CENTER, color, Text));
 	update();
 }
 
-void CButton::addOverlay(CIntObject *newOverlay)
+void CButton::addOverlay(CIntObject * newOverlay)
 {
 	delete overlay;
 	overlay = newOverlay;
@@ -87,7 +87,7 @@ void CButton::setImageOrder(int state1, int state2, int state3, int state4)
 
 void CButton::setState(ButtonState newState)
 {
-	if (state == newState)
+	if(state == newState)
 		return;
 	state = newState;
 	update();
@@ -120,7 +120,7 @@ void CButton::onButtonClicked()
 	logAnim->traceStream() << "Button clicked at " << pos.x << "x" << pos.y;
 	CIntObject * parent = this->parent;
 	std::string prefix = "Parent is";
-	while (parent)
+	while(parent)
 	{
 		logAnim->traceStream() << prefix << typeid(*parent).name() << " at " << parent->pos.x << "x" << parent->pos.y;
 		parent = parent->parent;
@@ -134,9 +134,9 @@ void CButton::clickLeft(tribool down, bool previousState)
 	if(isBlocked())
 		return;
 
-	if (down)
+	if(down)
 	{
-		if (!soundDisabled)
+		if(!soundDisabled)
 			CCS->soundh->playSound(soundBase::button);
 		setState(PRESSED);
 	}
@@ -145,11 +145,11 @@ void CButton::clickLeft(tribool down, bool previousState)
 	else
 		setState(NORMAL);
 
-	if (actOnDown && down)
+	if(actOnDown && down)
 	{
 		onButtonClicked();
 	}
-	else if (!actOnDown && previousState && (down==false))
+	else if(!actOnDown && previousState && (down == false))
 	{
 		onButtonClicked();
 	}
@@ -161,7 +161,7 @@ void CButton::clickRight(tribool down, bool previousState)
 		CRClickPopup::createAndPush(helpBox);
 }
 
-void CButton::hover (bool on)
+void CButton::hover(bool on)
 {
 	if(hoverable && !isBlocked())
 	{
@@ -172,22 +172,20 @@ void CButton::hover (bool on)
 	}
 
 	/*if(pressedL && on) // WTF is this? When this is used?
-		setState(PRESSED);*/
+	        setState(PRESSED);*/
 
-	std::string name = hoverTexts[getState()].empty()
-		? hoverTexts[0]
-		: hoverTexts[getState()];
+	std::string name = hoverTexts[getState()].empty() ? hoverTexts[0] : hoverTexts[getState()];
 
 	if(!name.empty() && !isBlocked()) //if there is no name, there is nothing to display also
 	{
-		if (LOCPLINT && LOCPLINT->battleInt) //for battle buttons
+		if(LOCPLINT && LOCPLINT->battleInt) //for battle buttons
 		{
 			if(on && LOCPLINT->battleInt->console->alterTxt == "")
 			{
 				LOCPLINT->battleInt->console->alterTxt = name;
 				LOCPLINT->battleInt->console->whoSetAlter = 1;
 			}
-			else if (LOCPLINT->battleInt->console->alterTxt == name)
+			else if(LOCPLINT->battleInt->console->alterTxt == name)
 			{
 				LOCPLINT->battleInt->console->alterTxt = "";
 				LOCPLINT->battleInt->console->whoSetAlter = 0;
@@ -195,17 +193,16 @@ void CButton::hover (bool on)
 		}
 		else if(GH.statusbar) //for other buttons
 		{
-			if (on)
+			if(on)
 				GH.statusbar->setText(name);
-			else if ( GH.statusbar->getText()==(name) )
+			else if(GH.statusbar->getText() == (name))
 				GH.statusbar->clear();
 		}
 	}
 }
 
-CButton::CButton(Point position, const std::string &defName, const std::pair<std::string, std::string> &help, CFunctionList<void()> Callback, int key, bool playerColoredButton):
-    CKeyShortcut(key),
-    callback(Callback)
+CButton::CButton(Point position, const std::string & defName, const std::pair<std::string, std::string> & help, CFunctionList<void()> Callback, int key, bool playerColoredButton)
+	: CKeyShortcut(key), callback(Callback)
 {
 	addUsedEvents(LCLICK | RCLICK | HOVER | KEYBOARD);
 
@@ -214,19 +211,19 @@ CButton::CButton(Point position, const std::string &defName, const std::pair<std
 	stateToIndex[2] = 2;
 	stateToIndex[3] = 3;
 
-	state=NORMAL;
+	state = NORMAL;
 	image = nullptr;
 	overlay = nullptr;
 
 	currentImage = -1;
 	hoverable = actOnDown = soundDisabled = false;
 	hoverTexts[0] = help.first;
-	helpBox=help.second;
+	helpBox = help.second;
 
 	pos.x += position.x;
 	pos.y += position.y;
 
-	if (!defName.empty())
+	if(!defName.empty())
 	{
 		imageNames.push_back(defName);
 		setIndex(0, playerColoredButton);
@@ -235,7 +232,7 @@ CButton::CButton(Point position, const std::string &defName, const std::pair<std
 
 void CButton::setIndex(size_t index, bool playerColoredButton)
 {
-	if (index == currentImage || index>=imageNames.size())
+	if(index == currentImage || index >= imageNames.size())
 		return;
 	currentImage = index;
 	auto anim = std::make_shared<CAnimation>(imageNames[index]);
@@ -247,14 +244,14 @@ void CButton::setImage(std::shared_ptr<CAnimation> anim, bool playerColoredButto
 	OBJ_CONSTRUCTION_CAPTURING_ALL;
 
 	image = new CAnimImage(anim, getState(), 0, 0, 0, animFlags);
-	if (playerColoredButton)
+	if(playerColoredButton)
 		image->playerColored(LOCPLINT->playerID);
 	pos = image->pos;
 }
 
 void CButton::setPlayerColor(PlayerColor player)
 {
-	if (image)
+	if(image)
 		image->playerColored(player);
 }
 
@@ -262,8 +259,8 @@ void CButton::showAll(SDL_Surface * to)
 {
 	CIntObject::showAll(to);
 
-	if (borderColor && borderColor->a == 0)
-		CSDL_Ext::drawBorder(to, pos.x-1, pos.y-1, pos.w+2, pos.h+2, int3(borderColor->r, borderColor->g, borderColor->b));
+	if(borderColor && borderColor->a == 0)
+		CSDL_Ext::drawBorder(to, pos.x - 1, pos.y - 1, pos.w + 2, pos.h + 2, int3(borderColor->r, borderColor->g, borderColor->b));
 }
 
 std::pair<std::string, std::string> CButton::tooltip()
@@ -281,10 +278,8 @@ std::pair<std::string, std::string> CButton::tooltip(const std::string & hover,
 	return std::make_pair(hover, help);
 }
 
-CToggleBase::CToggleBase(CFunctionList<void (bool)> callback):
-    callback(callback),
-    selected(false),
-    allowDeselection(true)
+CToggleBase::CToggleBase(CFunctionList<void(bool)> callback)
+	: callback(callback), selected(false), allowDeselection(true)
 {
 }
 
@@ -302,13 +297,13 @@ void CToggleBase::setSelected(bool on)
 	bool changed = (on != selected);
 	selected = on;
 	doSelect(on);
-	if (changed)
+	if(changed)
 		callback(on);
 }
 
 bool CToggleBase::canActivate()
 {
-	if (selected && !allowDeselection)
+	if(selected && !allowDeselection)
 		return false;
 	return true;
 }
@@ -318,17 +313,15 @@ void CToggleBase::addCallback(std::function<void(bool)> function)
 	callback += function;
 }
 
-CToggleButton::CToggleButton(Point position, const std::string &defName, const std::pair<std::string, std::string> &help,
-                             CFunctionList<void(bool)> callback, int key, bool playerColoredButton):
-  CButton(position, defName, help, 0, key, playerColoredButton),
-  CToggleBase(callback)
+CToggleButton::CToggleButton(Point position, const std::string & defName, const std::pair<std::string, std::string> & help, CFunctionList<void(bool)> callback, int key, bool playerColoredButton)
+	: CButton(position, defName, help, 0, key, playerColoredButton), CToggleBase(callback)
 {
 	allowDeselection = true;
 }
 
 void CToggleButton::doSelect(bool on)
 {
-	if (on)
+	if(on)
 	{
 		setState(HIGHLIGHTED);
 	}
@@ -347,13 +340,13 @@ void CToggleButton::clickLeft(tribool down, bool previousState)
 	if(isBlocked())
 		return;
 
-	if (down && canActivate())
+	if(down && canActivate())
 	{
 		CCS->soundh->playSound(soundBase::button);
 		setState(PRESSED);
 	}
 
-	if(previousState)//mouse up
+	if(previousState) //mouse up
 	{
 		if(down == false && getState() == PRESSED && canActivate())
 		{
@@ -370,24 +363,28 @@ void CToggleGroup::addCallback(std::function<void(int)> callback)
 	onChange += callback;
 }
 
-void CToggleGroup::addToggle(int identifier, CToggleBase* bt)
+void CToggleGroup::addToggle(int identifier, CToggleBase * bt)
 {
-	if (auto intObj = dynamic_cast<CIntObject*>(bt)) // hack-ish workagound to avoid diamond problem with inheritance
+	if(auto intObj = dynamic_cast<CIntObject *>(bt)) // hack-ish workagound to avoid diamond problem with inheritance
 	{
-		if (intObj->parent)
+		if(intObj->parent)
 			intObj->parent->removeChild(intObj);
 		addChild(intObj);
 	}
 
-	bt->addCallback([=] (bool on) { if (on) selectionChanged(identifier);});
+	bt->addCallback([=](bool on)
+	{
+		if(on)
+			selectionChanged(identifier);
+	});
 	bt->allowDeselection = false;
 
 	assert(buttons[identifier] == nullptr);
 	buttons[identifier] = bt;
 }
 
-CToggleGroup::CToggleGroup(const CFunctionList<void(int)> &OnChange)
-: onChange(OnChange), selectedID(-2)
+CToggleGroup::CToggleGroup(const CFunctionList<void(int)> & OnChange)
+	: onChange(OnChange), selectedID(-2)
 {}
 
 void CToggleGroup::setSelected(int id)
@@ -397,27 +394,25 @@ void CToggleGroup::setSelected(int id)
 
 void CToggleGroup::selectionChanged(int to)
 {
-	if (to == selectedID)
+	if(to == selectedID)
 		return;
 
 	int oldSelection = selectedID;
 	selectedID = to;
 
-	if (buttons.count(oldSelection))
+	if(buttons.count(oldSelection))
 		buttons[oldSelection]->setSelected(false);
 
-	if (buttons.count(to))
+	if(buttons.count(to))
 		buttons[to]->setSelected(true);
 
 	onChange(to);
-	if (parent)
+	if(parent)
 		parent->redraw();
 }
 
-CVolumeSlider::CVolumeSlider(const Point &position, const std::string &defName, const int value,
-                             const std::pair<std::string, std::string> * const help) :
-	value(value),
-	helpHandlers(help)
+CVolumeSlider::CVolumeSlider(const Point & position, const std::string & defName, const int value, const std::pair<std::string, std::string> * const help)
+	: value(value), helpHandlers(help)
 {
 	OBJ_CONSTRUCTION_CAPTURING_ALL;
 	animImage = new CAnimImage(std::make_shared<CAnimation>(defName), 0, 0, position.x, position.y),
@@ -442,7 +437,7 @@ void CVolumeSlider::moveTo(int id)
 	vstd::abetween(id, 0, animImage->size() - 1);
 	animImage->setFrame(id);
 	animImage->moveTo(Point(pos.x + (animImage->pos.w + 1) * id, pos.y));
-	if (active)
+	if(active)
 		redraw();
 }
 
@@ -453,7 +448,7 @@ void CVolumeSlider::addCallback(std::function<void(int)> callback)
 
 void CVolumeSlider::clickLeft(tribool down, bool previousState)
 {
-	if (down)
+	if(down)
 	{
 		double px = GH.current->motion.x - pos.x;
 		double rx = px / static_cast<double>(pos.w);
@@ -472,7 +467,7 @@ void CVolumeSlider::clickLeft(tribool down, bool previousState)
 
 void CVolumeSlider::clickRight(tribool down, bool previousState)
 {
-	if (down)
+	if(down)
 	{
 		double px = GH.current->motion.x - pos.x;
 		int index = px / static_cast<double>(pos.w) * animImage->size();
@@ -487,7 +482,7 @@ void CVolumeSlider::clickRight(tribool down, bool previousState)
 
 void CVolumeSlider::wheelScrolled(bool down, bool in)
 {
-	if (in)
+	if(in)
 	{
 		int volume = value + 3 * (down ? 1 : -1);
 		vstd::abetween(volume, 0, 100);
@@ -502,12 +497,12 @@ void CSlider::sliderClicked()
 		addUsedEvents(MOVE);
 }
 
-void CSlider::mouseMoved (const SDL_MouseMotionEvent & sEvent)
+void CSlider::mouseMoved(const SDL_MouseMotionEvent & sEvent)
 {
 	double v = 0;
 	if(horizontal)
 	{
-		if(	std::abs(sEvent.y-(pos.y+pos.h/2)) > pos.h/2+40  ||  std::abs(sEvent.x-(pos.x+pos.w/2)) > pos.w/2  )
+		if(std::abs(sEvent.y - (pos.y + pos.h / 2)) > pos.h / 2 + 40 || std::abs(sEvent.x - (pos.x + pos.w / 2)) > pos.w / 2)
 			return;
 		v = sEvent.x - pos.x - 24;
 		v *= positions;
@@ -515,14 +510,14 @@ void CSlider::mouseMoved (const SDL_MouseMotionEvent & sEvent)
 	}
 	else
 	{
-		if(std::abs(sEvent.x-(pos.x+pos.w/2)) > pos.w/2+40  ||  std::abs(sEvent.y-(pos.y+pos.h/2)) > pos.h/2  )
+		if(std::abs(sEvent.x - (pos.x + pos.w / 2)) > pos.w / 2 + 40 || std::abs(sEvent.y - (pos.y + pos.h / 2)) > pos.h / 2)
 			return;
 		v = sEvent.y - pos.y - 24;
 		v *= positions;
 		v /= (pos.h - 48);
 	}
 	v += 0.5;
-	if(v!=value)
+	if(v != value)
 	{
 		moveTo(v);
 	}
@@ -545,12 +540,12 @@ int CSlider::getValue()
 
 void CSlider::moveLeft()
 {
-	moveTo(value-1);
+	moveTo(value - 1);
 }
 
 void CSlider::moveRight()
 {
-	moveTo(value+1);
+	moveTo(value + 1);
 }
 
 void CSlider::moveBy(int amount)
@@ -565,24 +560,24 @@ void CSlider::updateSliderPos()
 		if(positions)
 		{
 			double part = static_cast<double>(value) / positions;
-			part*=(pos.w-48);
+			part *= (pos.w - 48);
 			int newPos = part + pos.x + 16 - slider->pos.x;
 			slider->moveBy(Point(newPos, 0));
 		}
 		else
-			slider->moveTo(Point(pos.x+16, pos.y));
+			slider->moveTo(Point(pos.x + 16, pos.y));
 	}
 	else
 	{
 		if(positions)
 		{
 			double part = static_cast<double>(value) / positions;
-			part*=(pos.h-48);
+			part *= (pos.h - 48);
 			int newPos = part + pos.y + 16 - slider->pos.y;
 			slider->moveBy(Point(0, newPos));
 		}
 		else
-			slider->moveTo(Point(pos.x, pos.y+16));
+			slider->moveTo(Point(pos.x, pos.y + 16));
 	}
 }
 
@@ -609,20 +604,20 @@ void CSlider::clickLeft(tribool down, bool previousState)
 		double rw = 0;
 		if(horizontal)
 		{
-			pw = GH.current->motion.x-pos.x-25;
+			pw = GH.current->motion.x - pos.x - 25;
 			rw = pw / static_cast<double>(pos.w - 48);
 		}
 		else
 		{
-			pw = GH.current->motion.y-pos.y-24;
-			rw = pw / (pos.h-48);
+			pw = GH.current->motion.y - pos.y - 24;
+			rw = pw / (pos.h - 48);
 		}
-		if(pw < -8  ||  pw > (horizontal ? pos.w : pos.h) - 40)
+		if(pw < -8 || pw > (horizontal ? pos.w : pos.h) - 40)
 			return;
-		// 		if (rw>1) return;
-		// 		if (rw<0) return;
+		//              if (rw>1) return;
+		//              if (rw<0) return;
 		slider->clickLeft(true, slider->mouseState(EIntObjMouseBtnType::LEFT));
-		moveTo(rw * positions  +  0.5);
+		moveTo(rw * positions + 0.5);
 		return;
 	}
 	if(active & MOVE)
@@ -634,13 +629,8 @@ CSlider::~CSlider()
 
 }
 
-CSlider::CSlider(Point position, int totalw, std::function<void(int)> Moved, int Capacity, int Amount, int Value, bool Horizontal, CSlider::EStyle style):
-    capacity(Capacity),
-    horizontal(Horizontal),
-    amount(Amount),
-    value(Value),
-    scrollStep(1),
-    moved(Moved)
+CSlider::CSlider(Point position, int totalw, std::function<void(int)> Moved, int Capacity, int Amount, int Value, bool Horizontal, CSlider::EStyle style)
+	: capacity(Capacity), horizontal(Horizontal), amount(Amount), value(Value), scrollStep(1), moved(Moved)
 {
 	OBJ_CONSTRUCTION_CAPTURING_ALL;
 	setAmount(amount);
@@ -655,11 +645,11 @@ CSlider::CSlider(Point position, int totalw, std::function<void(int)> Moved, int
 
 	if(style == BROWN)
 	{
-		std::string name = horizontal?"IGPCRDIV.DEF":"OVBUTN2.DEF";
+		std::string name = horizontal ? "IGPCRDIV.DEF" : "OVBUTN2.DEF";
 		//NOTE: this images do not have "blocked" frames. They should be implemented somehow (e.g. palette transform or something...)
 
-		left =   new CButton(Point(), name, CButton::tooltip());
-		right =  new CButton(Point(), name, CButton::tooltip());
+		left = new CButton(Point(), name, CButton::tooltip());
+		right = new CButton(Point(), name, CButton::tooltip());
 		slider = new CButton(Point(), name, CButton::tooltip());
 
 		left->setImageOrder(0, 1, 1, 1);
@@ -677,14 +667,14 @@ CSlider::CSlider(Point position, int totalw, std::function<void(int)> Moved, int
 	left->soundDisabled = true;
 	right->soundDisabled = true;
 
-	if (horizontal)
+	if(horizontal)
 		right->moveBy(Point(totalw - right->pos.w, 0));
 	else
 		right->moveBy(Point(0, totalw - right->pos.h));
 
-	left->addCallback(std::bind(&CSlider::moveLeft,this));
-	right->addCallback(std::bind(&CSlider::moveRight,this));
-	slider->addCallback(std::bind(&CSlider::sliderClicked,this));
+	left->addCallback(std::bind(&CSlider::moveLeft, this));
+	right->addCallback(std::bind(&CSlider::moveRight, this));
+	slider->addCallback(std::bind(&CSlider::sliderClicked, this));
 
 	if(horizontal)
 	{
@@ -700,14 +690,14 @@ CSlider::CSlider(Point position, int totalw, std::function<void(int)> Moved, int
 	updateSliderPos();
 }
 
-void CSlider::block( bool on )
+void CSlider::block(bool on)
 {
 	left->block(on);
 	right->block(on);
 	slider->block(on);
 }
 
-void CSlider::setAmount( int to )
+void CSlider::setAmount(int to)
 {
 	amount = to;
 	positions = to - capacity;
@@ -727,25 +717,26 @@ void CSlider::wheelScrolled(bool down, bool in)
 
 void CSlider::keyPressed(const SDL_KeyboardEvent & key)
 {
-	if(key.state != SDL_PRESSED) return;
+	if(key.state != SDL_PRESSED)
+		return;
 
 	int moveDest = value;
 	switch(key.keysym.sym)
 	{
 	case SDLK_UP:
-		if (!horizontal)
+		if(!horizontal)
 			moveDest = value - scrollStep;
 		break;
 	case SDLK_LEFT:
-		if (horizontal)
+		if(horizontal)
 			moveDest = value - scrollStep;
 		break;
 	case SDLK_DOWN:
-		if (!horizontal)
+		if(!horizontal)
 			moveDest = value + scrollStep;
 		break;
 	case SDLK_RIGHT:
-		if (horizontal)
+		if(horizontal)
 			moveDest = value + scrollStep;
 		break;
 	case SDLK_PAGEUP:

+ 33 - 31
client/widgets/Buttons.h

@@ -22,7 +22,7 @@ class CAnimation;
 
 namespace config
 {
-	struct ButtonInfo;
+struct ButtonInfo;
 }
 
 /// Typical Heroes 3 button which can be inactive or active and can
@@ -39,31 +39,32 @@ public:
 		BLOCKED=2,
 		HIGHLIGHTED=3
 	};
+
 private:
-	std::vector<std::string> imageNames;//store list of images that can be used by this button
+	std::vector<std::string> imageNames; //store list of images that can be used by this button
 	size_t currentImage;
 
-	ButtonState state;//current state of button from enum
+	ButtonState state; //current state of button from enum
 
 	std::array<int, 4> stateToIndex; // mapping of button state to index of frame in animation
 	std::array<std::string, 4> hoverTexts; //texts for statusbar, if empty - first entry will be used
 	std::string helpBox; //for right-click help
 
 	CAnimImage * image; //image for this button
-	CIntObject * overlay;//object-overlay, can be null
+	CIntObject * overlay; //object-overlay, can be null
 
 protected:
 	void onButtonClicked(); // calls callback
-	void update();//to refresh button after image or text change
+	void update(); //to refresh button after image or text change
 
 	// internal method to change state. Public change can be done only via block()
 	void setState(ButtonState newState);
 	ButtonState getState();
 
 public:
-	bool actOnDown,//runs when mouse is pressed down over it, not when up
-		hoverable,//if true, button will be highlighted when hovered (e.g. main menu)
-		soundDisabled;
+	bool actOnDown, //runs when mouse is pressed down over it, not when up
+	     hoverable, //if true, button will be highlighted when hovered (e.g. main menu)
+	     soundDisabled;
 
 	// if set, button will have 1-px border around it with this color
 	boost::optional<SDL_Color> borderColor;
@@ -73,7 +74,7 @@ public:
 
 	/// adds overlay on top of button image. Only one overlay can be active at once
 	void addOverlay(CIntObject * newOverlay);
-	void addTextOverlay(const std::string &Text, EFonts font, SDL_Color color = Colors::WHITE);
+	void addTextOverlay(const std::string & Text, EFonts font, SDL_Color color = Colors::WHITE);
 
 	void addImage(std::string filename);
 	void addHoverText(ButtonState state, std::string text);
@@ -86,18 +87,17 @@ public:
 	bool isHighlighted();
 
 	/// Constructor
-	CButton(Point position, const std::string &defName, const std::pair<std::string, std::string> &help,
-	        CFunctionList<void()> Callback = 0, int key=0, bool playerColoredButton = false );
+	CButton(Point position, const std::string & defName, const std::pair<std::string, std::string> & help, CFunctionList<void()> Callback = 0, int key = 0, bool playerColoredButton = false);
 
 	/// Appearance modifiers
-	void setIndex(size_t index, bool playerColoredButton=false);
-	void setImage(std::shared_ptr<CAnimation> anim, bool playerColoredButton=false, int animFlags=0);
+	void setIndex(size_t index, bool playerColoredButton = false);
+	void setImage(std::shared_ptr<CAnimation> anim, bool playerColoredButton = false, int animFlags = 0);
 	void setPlayerColor(PlayerColor player);
 
 	/// CIntObject overrides
 	void clickRight(tribool down, bool previousState) override;
 	void clickLeft(tribool down, bool previousState) override;
-	void hover (bool on) override;
+	void hover(bool on) override;
 	void showAll(SDL_Surface * to) override;
 
 	/// generates tooltip that can be passed into constructor
@@ -109,6 +109,7 @@ public:
 class CToggleBase
 {
 	CFunctionList<void(bool)> callback;
+
 protected:
 
 	bool selected;
@@ -136,9 +137,9 @@ public:
 class CToggleButton : public CButton, public CToggleBase
 {
 	void doSelect(bool on) override;
+
 public:
-	CToggleButton(Point position, const std::string &defName, const std::pair<std::string, std::string> &help,
-	              CFunctionList<void(bool)> Callback = 0, int key=0, bool playerColoredButton = false );
+	CToggleButton(Point position, const std::string & defName, const std::pair<std::string, std::string> & help, CFunctionList<void(bool)> Callback = 0, int key = 0, bool playerColoredButton = false);
 	void clickLeft(tribool down, bool previousState) override;
 
 	// bring overrides into scope
@@ -152,8 +153,9 @@ class CToggleGroup : public CIntObject
 
 	int selectedID;
 	void selectionChanged(int to);
+
 public:
-	std::map<int, CToggleBase*> buttons;
+	std::map<int, CToggleBase *> buttons;
 
 	CToggleGroup(const CFunctionList<void(int)> & OnChange);
 
@@ -173,14 +175,14 @@ class CVolumeSlider : public CIntObject
 	CAnimImage * animImage;
 	const std::pair<std::string, std::string> * const helpHandlers;
 	void setVolume(const int v);
+
 public:
 
 	/// @param position coordinates of slider
 	/// @param defName name of def animation for slider
 	/// @param value initial value for volume
 	/// @param help pointer to first helptext of slider
-	CVolumeSlider(const Point &position, const std::string &defName, const int value,
-	              const std::pair<std::string, std::string> * const help);
+	CVolumeSlider(const Point & position, const std::string & defName, const int value, const std::pair<std::string, std::string> * const help);
 
 	void moveTo(int id);
 	void addCallback(std::function<void(int)> callback);
@@ -194,8 +196,8 @@ public:
 /// A typical slider which can be orientated horizontally/vertically.
 class CSlider : public CIntObject
 {
-	CButton *left, *right, *slider; //if vertical then left=up
-	int capacity;//how many elements can be active at same time (e.g. hero list = 5)
+	CButton * left, * right, * slider; //if vertical then left=up
+	int capacity; //how many elements can be active at same time (e.g. hero list = 5)
 	int positions; //number of highest position (0 if there is only one)
 	bool horizontal;
 	int amount; //total amount of elements (e.g. hero list = 0-8)
@@ -207,7 +209,8 @@ class CSlider : public CIntObject
 	void sliderClicked();
 
 public:
-	enum EStyle {
+	enum EStyle
+	{
 		BROWN,
 		BLUE
 	};
@@ -237,16 +240,15 @@ public:
 	void keyPressed(const SDL_KeyboardEvent & key) override;
 	void wheelScrolled(bool down, bool in) override;
 	void clickLeft(tribool down, bool previousState) override;
-	void mouseMoved (const SDL_MouseMotionEvent & sEvent) override;
+	void mouseMoved(const SDL_MouseMotionEvent & sEvent) override;
 	void showAll(SDL_Surface * to) override;
 
-	 /// @param position coordinates of slider
-	 /// @param length length of slider ribbon, including left/right buttons
-	 /// @param Moved function that will be called whenever slider moves
-	 /// @param Capacity maximal number of visible at once elements
-	 /// @param Amount total amount of elements, including not visible
-	 /// @param Value starting position
-	CSlider(Point position, int length, std::function<void(int)> Moved, int Capacity, int Amount,
-		int Value=0, bool Horizontal=true, EStyle style = BROWN);
+	/// @param position coordinates of slider
+	/// @param length length of slider ribbon, including left/right buttons
+	/// @param Moved function that will be called whenever slider moves
+	/// @param Capacity maximal number of visible at once elements
+	/// @param Amount total amount of elements, including not visible
+	/// @param Value starting position
+	CSlider(Point position, int length, std::function<void(int)> Moved, int Capacity, int Amount, int Value = 0, bool Horizontal = true, EStyle style = BROWN);
 	~CSlider();
 };

+ 142 - 146
client/widgets/CArtifactHolder.cpp

@@ -30,8 +30,8 @@
 
 #include "../../lib/mapObjects/CGHeroInstance.h"
 
-CHeroArtPlace::CHeroArtPlace(Point position, const CArtifactInstance * Art): CArtPlace(position, Art),
-	locked(false), picked(false), marked(false), ourOwner(nullptr)
+CHeroArtPlace::CHeroArtPlace(Point position, const CArtifactInstance * Art)
+	: CArtPlace(position, Art), locked(false), picked(false), marked(false), ourOwner(nullptr)
 {
 	createImage();
 }
@@ -41,13 +41,13 @@ void CHeroArtPlace::createImage()
 	OBJ_CONSTRUCTION_CAPTURING_ALL;
 
 	int imageIndex = 0;
-	if (ourArt)
+	if(ourArt)
 		imageIndex = ourArt->artType->iconIndex;
-	if (locked)
+	if(locked)
 		imageIndex = ArtifactID::ART_LOCK;
 
 	image = new CAnimImage("artifact", imageIndex);
-	if (!ourArt)
+	if(!ourArt)
 		image->disable();
 
 	selection = new CAnimImage("artifact", ArtifactID::ART_SELECTION);
@@ -56,14 +56,14 @@ void CHeroArtPlace::createImage()
 
 void CHeroArtPlace::lockSlot(bool on)
 {
-	if (locked == on)
+	if(locked == on)
 		return;
 
 	locked = on;
 
-	if (on)
+	if(on)
 		image->setFrame(ArtifactID::ART_LOCK);
-	else if (ourArt)
+	else if(ourArt)
 		image->setFrame(ourArt->artType->iconIndex);
 	else
 		image->setFrame(0);
@@ -71,11 +71,11 @@ void CHeroArtPlace::lockSlot(bool on)
 
 void CHeroArtPlace::pickSlot(bool on)
 {
-	if (picked == on)
+	if(picked == on)
 		return;
 
 	picked = on;
-	if (on)
+	if(on)
 		image->disable();
 	else
 		image->enable();
@@ -83,11 +83,11 @@ void CHeroArtPlace::pickSlot(bool on)
 
 void CHeroArtPlace::selectSlot(bool on)
 {
-	if (marked == on)
+	if(marked == on)
 		return;
 
 	marked = on;
-	if (on)
+	if(on)
 		selection->enable();
 	else
 		selection->disable();
@@ -97,8 +97,8 @@ void CHeroArtPlace::clickLeft(tribool down, bool previousState)
 {
 	//LRClickableAreaWTextComp::clickLeft(down);
 	bool inBackpack = slotID >= GameConstants::BACKPACK_START,
-		srcInBackpack = ourOwner->commonInfo->src.slotID >= GameConstants::BACKPACK_START,
-		srcInSameHero = ourOwner->commonInfo->src.AOH == ourOwner;
+	     srcInBackpack = ourOwner->commonInfo->src.slotID >= GameConstants::BACKPACK_START,
+	     srcInSameHero = ourOwner->commonInfo->src.AOH == ourOwner;
 
 	if(ourOwner->highlightModeCallback && ourArt)
 	{
@@ -125,15 +125,15 @@ void CHeroArtPlace::clickLeft(tribool down, bool previousState)
 			GH.pushInt(new CSpellWindow(ourOwner->curHero, LOCPLINT, LOCPLINT->battleInt));
 	}
 
-	if (!down && previousState)
+	if(!down && previousState)
 	{
 		if(ourArt && ourArt->artType->id == ArtifactID::SPELLBOOK)
 			return; //this is handled separately
 
 		if(!ourOwner->commonInfo->src.AOH) //nothing has been clicked
 		{
-			if(ourArt  //to prevent selecting empty slots (bugfix to what GrayFace reported)
-				&&  ourOwner->curHero->tempOwner == LOCPLINT->playerID)//can't take art from another player
+			if(ourArt //to prevent selecting empty slots (bugfix to what GrayFace reported)
+			   && ourOwner->curHero->tempOwner == LOCPLINT->playerID) //can't take art from another player
 			{
 				if(ourArt->artType->id == ArtifactID::CATAPULT) //catapult cannot be highlighted
 				{
@@ -174,11 +174,11 @@ void CHeroArtPlace::clickLeft(tribool down, bool previousState)
 					{
 						setMeAsDest();
 						vstd::amin(ourOwner->commonInfo->dst.slotID, ArtifactPosition(
-							ourOwner->curHero->artifactsInBackpack.size() + GameConstants::BACKPACK_START));
+								   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
-								|| ourOwner->commonInfo->src.slotID < ourOwner->commonInfo->dst.slotID) //rearranging arts in backpack after taking src artifact, the dest id will be shifted
+							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
+							   || ourOwner->commonInfo->src.slotID < ourOwner->commonInfo->dst.slotID) //rearranging arts in backpack after taking src artifact, the dest id will be shifted
 								vstd::advance(ourOwner->commonInfo->dst.slotID, -1);
 						}
 						if(srcInSameHero && ourOwner->commonInfo->dst.slotID == ourOwner->commonInfo->src.slotID) //we came to src == dst
@@ -189,21 +189,21 @@ void CHeroArtPlace::clickLeft(tribool down, bool previousState)
 				}
 			}
 			//check if swap is possible
-			else if (fitsHere(ourOwner->commonInfo->src.art) &&
+			else if(fitsHere(ourOwner->commonInfo->src.art) &&
 				(!ourArt || ourOwner->curHero->tempOwner == LOCPLINT->playerID))
 			{
 				setMeAsDest();
 //
-// 				// Special case when the dest artifact can't be fit into the src slot.
-// 				//CGI->arth->unequipArtifact(ourOwner->curHero->artifWorn, slotID);
-// 				const CArtifactsOfHero* srcAOH = ourOwner->commonInfo->src.AOH;
-// 				ui16 srcSlotID = ourOwner->commonInfo->src.slotID;
-// 				if (ourArt && srcSlotID < 19 && !ourArt->canBePutAt(ArtifactLocation(srcAOH->curHero, srcSlotID)))
-// 				{
-// 					// Put dest artifact into owner's backpack.
-// 					ourOwner->commonInfo->src.AOH = ourOwner;
-// 					ourOwner->commonInfo->src.slotID = ourOwner->curHero->artifacts.size() + 19;
-// 				}
+//                              // Special case when the dest artifact can't be fit into the src slot.
+//                              //CGI->arth->unequipArtifact(ourOwner->curHero->artifWorn, slotID);
+//                              const CArtifactsOfHero* srcAOH = ourOwner->commonInfo->src.AOH;
+//                              ui16 srcSlotID = ourOwner->commonInfo->src.slotID;
+//                              if (ourArt && srcSlotID < 19 && !ourArt->canBePutAt(ArtifactLocation(srcAOH->curHero, srcSlotID)))
+//                              {
+//                                      // Put dest artifact into owner's backpack.
+//                                      ourOwner->commonInfo->src.AOH = ourOwner;
+//                                      ourOwner->commonInfo->src.slotID = ourOwner->curHero->artifacts.size() + 19;
+//                              }
 
 				ourOwner->realizeCurrentTransaction();
 			}
@@ -211,15 +211,14 @@ void CHeroArtPlace::clickLeft(tribool down, bool previousState)
 	}
 }
 
-bool CHeroArtPlace::askToAssemble(const CArtifactInstance *art, ArtifactPosition slot,
-                              const CGHeroInstance *hero)
+bool CHeroArtPlace::askToAssemble(const CArtifactInstance * art, ArtifactPosition slot, const CGHeroInstance * hero)
 {
 	assert(art != nullptr);
 	assert(hero != nullptr);
 	std::vector<const CArtifact *> assemblyPossibilities = art->assemblyPossibilities(hero);
 
 	// If the artifact can be assembled, display dialog.
-	for(const CArtifact *combination : assemblyPossibilities)
+	for(const CArtifact * combination : assemblyPossibilities)
 	{
 		LOCPLINT->showArtifactAssemblyDialog(
 			art->artType->id,
@@ -232,7 +231,7 @@ bool CHeroArtPlace::askToAssemble(const CArtifactInstance *art, ArtifactPosition
 		{
 			logGlobal->warnStream() << boost::format(
 				"More than one possibility of assembling on %s... taking only first")
-				% art->artType->Name();
+			% art->artType->Name();
 		}
 		return true;
 	}
@@ -241,16 +240,16 @@ bool CHeroArtPlace::askToAssemble(const CArtifactInstance *art, ArtifactPosition
 
 void CHeroArtPlace::clickRight(tribool down, bool previousState)
 {
-	if(ourArt && down && ourArt && !locked && text.size() && !picked)  //if there is no description or it's a lock, do nothing ;]
+	if(ourArt && down && ourArt && !locked && text.size() && !picked) //if there is no description or it's a lock, do nothing ;]
 	{
-		if (slotID < GameConstants::BACKPACK_START)
+		if(slotID < GameConstants::BACKPACK_START)
 		{
 			if(ourOwner->allowedAssembling)
 			{
 				std::vector<const CArtifact *> assemblyPossibilities = ourArt->assemblyPossibilities(ourOwner->curHero);
 
 				// If the artifact can be assembled, display dialog.
-				if (askToAssemble(ourArt, slotID, ourOwner->curHero))
+				if(askToAssemble(ourArt, slotID, ourOwner->curHero))
 				{
 					return;
 				}
@@ -277,9 +276,9 @@ void CHeroArtPlace::clickRight(tribool down, bool previousState)
 /**
  * Selects artifact slot so that the containing artifact looks like it's picked up.
  */
-void CHeroArtPlace::select ()
+void CHeroArtPlace::select()
 {
-	if (locked)
+	if(locked)
 		return;
 
 	selectSlot(true);
@@ -289,7 +288,7 @@ void CHeroArtPlace::select ()
 		for(int i = 0; i < GameConstants::BACKPACK_START; i++)
 		{
 			CHeroArtPlace * ap = ourOwner->getArtPlace(i);
-			if(nullptr != ap)//getArtPlace may return null
+			if(nullptr != ap) //getArtPlace may return null
 				ap->pickSlot(ourArt->isPart(ap->ourArt));
 		}
 	}
@@ -308,7 +307,7 @@ void CHeroArtPlace::select ()
 /**
  * Deselects the artifact slot.
  */
-void CHeroArtPlace::deselect ()
+void CHeroArtPlace::deselect()
 {
 	pickSlot(false);
 	if(ourArt && ourArt->canBeDisassembled()) //combined art returned to its slot -> restore locks
@@ -317,7 +316,7 @@ void CHeroArtPlace::deselect ()
 		{
 			auto place = ourOwner->getArtPlace(i);
 
-			if(nullptr != place)//getArtPlace may return null
+			if(nullptr != place) //getArtPlace may return null
 				place->pickSlot(false);
 		}
 	}
@@ -335,7 +334,7 @@ void CHeroArtPlace::deselect ()
 
 void CHeroArtPlace::showAll(SDL_Surface * to)
 {
-	if (ourArt && !picked && ourArt == ourOwner->curHero->getArt(slotID, false)) //last condition is needed for disassembling -> artifact may be gone, but we don't know yet TODO: real, nice solution
+	if(ourArt && !picked && ourArt == ourOwner->curHero->getArt(slotID, false)) //last condition is needed for disassembling -> artifact may be gone, but we don't know yet TODO: real, nice solution
 	{
 		CIntObject::showAll(to);
 	}
@@ -343,16 +342,16 @@ void CHeroArtPlace::showAll(SDL_Surface * to)
 	if(marked && active)
 	{
 		// Draw vertical bars.
-		for (int i = 0; i < pos.h; ++i)
+		for(int i = 0; i < pos.h; ++i)
 		{
-			CSDL_Ext::SDL_PutPixelWithoutRefresh(to, pos.x,             pos.y + i, 240, 220, 120);
+			CSDL_Ext::SDL_PutPixelWithoutRefresh(to, pos.x, pos.y + i, 240, 220, 120);
 			CSDL_Ext::SDL_PutPixelWithoutRefresh(to, pos.x + pos.w - 1, pos.y + i, 240, 220, 120);
 		}
 
 		// Draw horizontal bars.
-		for (int i = 0; i < pos.w; ++i)
+		for(int i = 0; i < pos.w; ++i)
 		{
-			CSDL_Ext::SDL_PutPixelWithoutRefresh(to, pos.x + i, pos.y,             240, 220, 120);
+			CSDL_Ext::SDL_PutPixelWithoutRefresh(to, pos.x + i, pos.y, 240, 220, 120);
 			CSDL_Ext::SDL_PutPixelWithoutRefresh(to, pos.x + i, pos.y + pos.h - 1, 240, 220, 120);
 		}
 	}
@@ -365,7 +364,7 @@ bool CHeroArtPlace::fitsHere(const CArtifactInstance * art) const
 		return true;
 
 	// Anything but War Machines can be placed in backpack.
-	if (slotID >= GameConstants::BACKPACK_START)
+	if(slotID >= GameConstants::BACKPACK_START)
 		return !art->artType->isBig();
 
 	return art->canBePutAt(ArtifactLocation(ourOwner->curHero, slotID), true);
@@ -376,7 +375,7 @@ void CHeroArtPlace::setMeAsDest(bool backpackAsVoid)
 	ourOwner->commonInfo->dst.setTo(this, backpackAsVoid);
 }
 
-void CHeroArtPlace::setArtifact(const CArtifactInstance *art)
+void CHeroArtPlace::setArtifact(const CArtifactInstance * art)
 {
 	baseType = -1; //by default we don't store any component
 	ourArt = art;
@@ -411,7 +410,7 @@ void CHeroArtPlace::setArtifact(const CArtifactInstance *art)
 		bonusValue = 0;
 	}
 
-	if (locked) // Locks should appear as empty.
+	if(locked) // Locks should appear as empty.
 		hoverText = CGI->generaltexth->allTexts[507];
 	else
 		hoverText = boost::str(boost::format(CGI->generaltexth->heroscrn[1]) % ourArt->artType->Name());
@@ -427,7 +426,7 @@ void CArtifactsOfHero::SCommonPart::reset()
 void CArtifactsOfHero::setHero(const CGHeroInstance * hero)
 {
 	curHero = hero;
-	if (curHero->artifactsInBackpack.size() > 0)
+	if(curHero->artifactsInBackpack.size() > 0)
 		backpackPos %= curHero->artifactsInBackpack.size();
 	else
 		backpackPos = 0;
@@ -451,7 +450,7 @@ void CArtifactsOfHero::scrollBackpack(int dir)
 {
 	int artsInBackpack = curHero->artifactsInBackpack.size();
 	backpackPos += dir;
-	if(backpackPos < 0)// No guarantee of modulus behavior with negative operands -> we keep it positive
+	if(backpackPos < 0) // No guarantee of modulus behavior with negative operands -> we keep it positive
 		backpackPos += artsInBackpack;
 
 	if(artsInBackpack)
@@ -465,18 +464,18 @@ void CArtifactsOfHero::scrollBackpack(int dir)
 
 	//set new data
 	size_t s = 0;
-	for( ; s < artsInBackpack; ++s)
+	for(; s < artsInBackpack; ++s)
 	{
 
-		if (s < artsInBackpack)
+		if(s < artsInBackpack)
 		{
-			auto slotID = ArtifactPosition(GameConstants::BACKPACK_START + (s + backpackPos)%artsInBackpack);
-			const CArtifactInstance *art = curHero->getArt(slotID);
+			auto slotID = ArtifactPosition(GameConstants::BACKPACK_START + (s + backpackPos) % artsInBackpack);
+			const CArtifactInstance * art = curHero->getArt(slotID);
 			assert(art);
 			if(!vstd::contains(toOmit, art))
 			{
 				if(s - omitedSoFar < backpack.size())
-					setSlotData(backpack[s-omitedSoFar], slotID);
+					setSlotData(backpack[s - omitedSoFar], slotID);
 			}
 			else
 			{
@@ -486,8 +485,8 @@ void CArtifactsOfHero::scrollBackpack(int dir)
 			}
 		}
 	}
-	for( ; s - omitedSoFar < backpack.size(); s++)
-		eraseSlotData(backpack[s-omitedSoFar], ArtifactPosition(GameConstants::BACKPACK_START + s));
+	for(; s - omitedSoFar < backpack.size(); s++)
+		eraseSlotData(backpack[s - omitedSoFar], ArtifactPosition(GameConstants::BACKPACK_START + 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)
@@ -516,9 +515,9 @@ void CArtifactsOfHero::scrollBackpack(int dir)
  *
  * @param art Artifact checked against.
  */
-void CArtifactsOfHero::markPossibleSlots(const CArtifactInstance* art)
+void CArtifactsOfHero::markPossibleSlots(const CArtifactInstance * art)
 {
-	for(CArtifactsOfHero *aoh : commonInfo->participants)
+	for(CArtifactsOfHero * aoh : commonInfo->participants)
 		for(auto p : aoh->artWorn)
 			p.second->selectSlot(art->canBePutAt(ArtifactLocation(aoh->curHero, p.second->slotID), true));
 
@@ -531,10 +530,10 @@ void CArtifactsOfHero::markPossibleSlots(const CArtifactInstance* art)
 void CArtifactsOfHero::unmarkSlots(bool withRedraw)
 {
 	if(commonInfo)
-		for(CArtifactsOfHero *aoh : commonInfo->participants)
+		for(CArtifactsOfHero * aoh : commonInfo->participants)
 			aoh->unmarkLocalSlots(false);
 	else
-		unmarkLocalSlots(false);\
+		unmarkLocalSlots(false); \
 
 	if(withRedraw)
 		safeRedraw();
@@ -544,7 +543,7 @@ void CArtifactsOfHero::unmarkLocalSlots(bool withRedraw)
 {
 	for(auto p : artWorn)
 		p.second->selectSlot(false);
-	for(CHeroArtPlace *place : backpack)
+	for(CHeroArtPlace * place : backpack)
 		place->selectSlot(false);
 
 	if(withRedraw)
@@ -554,7 +553,7 @@ void CArtifactsOfHero::unmarkLocalSlots(bool withRedraw)
 /**
  * Assigns an artifacts to an artifact place depending on it's new slot ID.
  */
-void CArtifactsOfHero::setSlotData(CHeroArtPlace* artPlace, ArtifactPosition slotID)
+void CArtifactsOfHero::setSlotData(CHeroArtPlace * artPlace, ArtifactPosition slotID)
 {
 	if(!artPlace && slotID >= GameConstants::BACKPACK_START) //spurious call from artifactMoved in attempt to update hidden backpack slot
 	{
@@ -564,7 +563,7 @@ void CArtifactsOfHero::setSlotData(CHeroArtPlace* artPlace, ArtifactPosition slo
 	artPlace->pickSlot(false);
 	artPlace->slotID = slotID;
 
-	if(const ArtSlotInfo *asi = curHero->getSlot(slotID))
+	if(const ArtSlotInfo * asi = curHero->getSlot(slotID))
 	{
 		artPlace->lockSlot(asi->locked);
 		artPlace->setArtifact(asi->artifact);
@@ -576,21 +575,16 @@ void CArtifactsOfHero::setSlotData(CHeroArtPlace* artPlace, ArtifactPosition slo
 /**
  * Makes given artifact slot appear as empty with a certain slot ID.
  */
-void CArtifactsOfHero::eraseSlotData (CHeroArtPlace* artPlace, ArtifactPosition slotID)
+void CArtifactsOfHero::eraseSlotData(CHeroArtPlace * artPlace, ArtifactPosition slotID)
 {
 	artPlace->pickSlot(false);
 	artPlace->slotID = slotID;
 	artPlace->setArtifact(nullptr);
 }
 
-CArtifactsOfHero::CArtifactsOfHero(std::map<ArtifactPosition, CHeroArtPlace *> ArtWorn, std::vector<CHeroArtPlace *> Backpack,
-	CButton *leftScroll, CButton *rightScroll, bool createCommonPart):
+CArtifactsOfHero::CArtifactsOfHero(std::map<ArtifactPosition, CHeroArtPlace *> ArtWorn, std::vector<CHeroArtPlace *> Backpack, CButton * leftScroll, CButton * rightScroll, bool createCommonPart) :
 
-	curHero(nullptr),
-	artWorn(ArtWorn), backpack(Backpack),
-	backpackPos(0), commonInfo(nullptr), updateState(false),
-	leftArtRoll(leftScroll), rightArtRoll(rightScroll),
-	allowedAssembling(true), highlightModeCallback(nullptr)
+	curHero(nullptr), artWorn(ArtWorn), backpack(Backpack), backpackPos(0), commonInfo(nullptr), updateState(false), leftArtRoll(leftScroll), rightArtRoll(rightScroll), allowedAssembling(true), highlightModeCallback(nullptr)
 {
 	if(createCommonPart)
 	{
@@ -599,25 +593,25 @@ CArtifactsOfHero::CArtifactsOfHero(std::map<ArtifactPosition, CHeroArtPlace *> A
 	}
 
 	// Init slots for worn artifacts.
-	for (auto p : artWorn)
+	for(auto p : artWorn)
 	{
 		p.second->ourOwner = this;
 		eraseSlotData(p.second, p.first);
 	}
 
 	// Init slots for the backpack.
-	for(size_t s=0; s<backpack.size(); ++s)
+	for(size_t s = 0; s < backpack.size(); ++s)
 	{
 		backpack[s]->ourOwner = this;
 		eraseSlotData(backpack[s], ArtifactPosition(GameConstants::BACKPACK_START + s));
 	}
 
-	leftArtRoll->addCallback(std::bind(&CArtifactsOfHero::scrollBackpack,this,-1));
-	rightArtRoll->addCallback(std::bind(&CArtifactsOfHero::scrollBackpack,this,+1));
+	leftArtRoll->addCallback(std::bind(&CArtifactsOfHero::scrollBackpack, this, -1));
+	rightArtRoll->addCallback(std::bind(&CArtifactsOfHero::scrollBackpack, this, +1));
 }
 
-CArtifactsOfHero::CArtifactsOfHero(const Point& position, bool createCommonPart)
- : curHero(nullptr), backpackPos(0), commonInfo(nullptr), updateState(false), allowedAssembling(true), highlightModeCallback(nullptr)
+CArtifactsOfHero::CArtifactsOfHero(const Point & position, bool createCommonPart)
+	: curHero(nullptr), backpackPos(0), commonInfo(nullptr), updateState(false), allowedAssembling(true), highlightModeCallback(nullptr)
 {
 	if(createCommonPart)
 	{
@@ -630,17 +624,17 @@ CArtifactsOfHero::CArtifactsOfHero(const Point& position, bool createCommonPart)
 
 	std::vector<Point> slotPos =
 	{
-		Point(509,30),  Point(567,240), Point(509,80),  //0-2
-		Point(383,68),  Point(564,183), Point(509,130), //3-5
-		Point(431,68),  Point(610,183), Point(515,295), //6-8
-		Point(383,143), Point(399,194), Point(415,245), //9-11
-		Point(431,296), Point(564,30),  Point(610,30), //12-14
-		Point(610,76),  Point(610,122), Point(610,310), //15-17
-		Point(381,296) //18
+		Point(509, 30), Point(567, 240), Point(509, 80), //0-2
+		Point(383, 68), Point(564, 183), Point(509, 130), //3-5
+		Point(431, 68), Point(610, 183), Point(515, 295), //6-8
+		Point(383, 143), Point(399, 194), Point(415, 245), //9-11
+		Point(431, 296), Point(564, 30), Point(610, 30), //12-14
+		Point(610, 76), Point(610, 122), Point(610, 310), //15-17
+		Point(381, 296) //18
 	};
 
 	// Create slots for worn artifacts.
-	for (size_t g = 0; g < GameConstants::BACKPACK_START ; g++)
+	for(size_t g = 0; g < GameConstants::BACKPACK_START; g++)
 	{
 		artWorn[ArtifactPosition(g)] = new CHeroArtPlace(slotPos[g]);
 		artWorn[ArtifactPosition(g)]->ourOwner = this;
@@ -648,7 +642,7 @@ CArtifactsOfHero::CArtifactsOfHero(const Point& position, bool createCommonPart)
 	}
 
 	// Create slots for the backpack.
-	for(size_t s=0; s<5; ++s)
+	for(size_t s = 0; s < 5; ++s)
 	{
 		auto add = new CHeroArtPlace(Point(403 + 46 * s, 365));
 
@@ -658,7 +652,7 @@ CArtifactsOfHero::CArtifactsOfHero(const Point& position, bool createCommonPart)
 		backpack.push_back(add);
 	}
 
-	leftArtRoll =  new CButton(Point(379, 364), "hsbtns3.def", CButton::tooltip(), [&](){ scrollBackpack(-1);}, SDLK_LEFT);
+	leftArtRoll = new CButton(Point(379, 364), "hsbtns3.def", CButton::tooltip(), [&](){ scrollBackpack(-1);}, SDLK_LEFT);
 	rightArtRoll = new CButton(Point(632, 364), "hsbtns5.def", CButton::tooltip(), [&](){ scrollBackpack(+1);}, SDLK_RIGHT);
 }
 
@@ -669,14 +663,14 @@ CArtifactsOfHero::~CArtifactsOfHero()
 
 void CArtifactsOfHero::updateParentWindow()
 {
-	if (CHeroWindow* chw = dynamic_cast<CHeroWindow*>(GH.topInt()))
+	if(CHeroWindow * chw = dynamic_cast<CHeroWindow *>(GH.topInt()))
 	{
 		if(updateState)
 			chw->curHero = curHero;
 		else
 			chw->update(curHero, true);
 	}
-	else if(CExchangeWindow* cew = dynamic_cast<CExchangeWindow*>(GH.topInt()))
+	else if(CExchangeWindow * cew = dynamic_cast<CExchangeWindow *>(GH.topInt()))
 	{
 
 		//use our copy of hero to draw window
@@ -688,13 +682,13 @@ void CArtifactsOfHero::updateParentWindow()
 		if(!updateState)
 		{
 			cew->deactivate();
-// 			for(int g=0; g<ARRAY_COUNT(cew->heroInst); ++g)
-// 			{
-// 				if(cew->heroInst[g] == curHero)
-// 				{
-// 					cew->artifs[g]->setHero(curHero);
-// 				}
-// 			}
+//                      for(int g=0; g<ARRAY_COUNT(cew->heroInst); ++g)
+//                      {
+//                              if(cew->heroInst[g] == curHero)
+//                              {
+//                                      cew->artifs[g]->setHero(curHero);
+//                              }
+//                      }
 
 
 			cew->prepareBackground();
@@ -706,7 +700,7 @@ void CArtifactsOfHero::updateParentWindow()
 
 void CArtifactsOfHero::safeRedraw()
 {
-	if (active)
+	if(active)
 	{
 		if(parent)
 			parent->redraw();
@@ -720,28 +714,28 @@ void CArtifactsOfHero::realizeCurrentTransaction()
 	assert(commonInfo->src.AOH);
 	assert(commonInfo->dst.AOH);
 	LOCPLINT->cb->swapArtifacts(ArtifactLocation(commonInfo->src.AOH->curHero, commonInfo->src.slotID),
-								ArtifactLocation(commonInfo->dst.AOH->curHero, commonInfo->dst.slotID));
+				    ArtifactLocation(commonInfo->dst.AOH->curHero, commonInfo->dst.slotID));
 }
 
-void CArtifactsOfHero::artifactMoved(const ArtifactLocation &src, const ArtifactLocation &dst)
+void CArtifactsOfHero::artifactMoved(const ArtifactLocation & src, const ArtifactLocation & dst)
 {
 	bool isCurHeroSrc = src.isHolder(curHero),
-		isCurHeroDst = dst.isHolder(curHero);
+	     isCurHeroDst = dst.isHolder(curHero);
 	if(isCurHeroSrc && src.slot >= GameConstants::BACKPACK_START)
 		updateSlot(src.slot);
 	if(isCurHeroDst && dst.slot >= GameConstants::BACKPACK_START)
 		updateSlot(dst.slot);
-	if(isCurHeroSrc  ||  isCurHeroDst) //we need to update all slots, artifact might be combined and affect more slots
+	if(isCurHeroSrc || isCurHeroDst) //we need to update all slots, artifact might be combined and affect more slots
 		updateWornSlots(false);
 
-	if (!src.isHolder(curHero) && !isCurHeroDst)
+	if(!src.isHolder(curHero) && !isCurHeroDst)
 		return;
 
 	if(commonInfo->src == src) //artifact was taken from us
 	{
-		assert(commonInfo->dst == dst  //expected movement from slot ot slot
-			||  dst.slot == dst.getHolderArtSet()->artifactsInBackpack.size() + GameConstants::BACKPACK_START //artifact moved back to backpack (eg. to make place for art we are moving)
-			|| dst.getHolderArtSet()->bearerType() != ArtBearer::HERO);
+		assert(commonInfo->dst == dst //expected movement from slot ot slot
+		       || dst.slot == dst.getHolderArtSet()->artifactsInBackpack.size() + GameConstants::BACKPACK_START //artifact moved back to backpack (eg. to make place for art we are moving)
+		       || dst.getHolderArtSet()->bearerType() != ArtBearer::HERO);
 		commonInfo->reset();
 		unmarkSlots();
 	}
@@ -750,13 +744,13 @@ void CArtifactsOfHero::artifactMoved(const ArtifactLocation &src, const Artifact
 		assert(dst.slot >= GameConstants::BACKPACK_START);
 		commonInfo->reset();
 
-		CHeroArtPlace *ap = nullptr;
-		for(CArtifactsOfHero *aoh : commonInfo->participants)
+		CHeroArtPlace * ap = nullptr;
+		for(CArtifactsOfHero * aoh : commonInfo->participants)
 		{
 			if(dst.isHolder(aoh->curHero))
 			{
 				commonInfo->src.AOH = aoh;
-				if((ap = aoh->getArtPlace(dst.slot)))//getArtPlace may return null
+				if((ap = aoh->getArtPlace(dst.slot))) //getArtPlace may return null
 					break;
 			}
 		}
@@ -775,8 +769,8 @@ void CArtifactsOfHero::artifactMoved(const ArtifactLocation &src, const Artifact
 		}
 	}
 	else if(src.slot >= GameConstants::BACKPACK_START &&
-	        src.slot <  commonInfo->src.slotID &&
-			    src.isHolder(commonInfo->src.AOH->curHero)) //artifact taken from before currently picked one
+		src.slot < commonInfo->src.slotID &&
+		src.isHolder(commonInfo->src.AOH->curHero)) //artifact taken from before currently picked one
 	{
 		//int fixedSlot = src.hero->getArtPos(commonInfo->src.art);
 		vstd::advance(commonInfo->src.slotID, -1);
@@ -791,20 +785,20 @@ void CArtifactsOfHero::artifactMoved(const ArtifactLocation &src, const Artifact
 
 	updateParentWindow();
 	int shift = 0;
-// 	if(dst.slot >= Arts::BACKPACK_START && dst.slot - Arts::BACKPACK_START < backpackPos)
-// 		shift++;
+//      if(dst.slot >= Arts::BACKPACK_START && dst.slot - Arts::BACKPACK_START < backpackPos)
+//              shift++;
 //
-	if(src.slot < GameConstants::BACKPACK_START  &&  dst.slot - GameConstants::BACKPACK_START < backpackPos)
+	if(src.slot < GameConstants::BACKPACK_START && dst.slot - GameConstants::BACKPACK_START < backpackPos)
 		shift++;
-	if(dst.slot < GameConstants::BACKPACK_START  &&  src.slot - GameConstants::BACKPACK_START < backpackPos)
+	if(dst.slot < GameConstants::BACKPACK_START && src.slot - GameConstants::BACKPACK_START < backpackPos)
 		shift--;
 
-	if( (isCurHeroSrc && src.slot >= GameConstants::BACKPACK_START)
-	 || (isCurHeroDst && dst.slot >= GameConstants::BACKPACK_START) )
+	if((isCurHeroSrc && src.slot >= GameConstants::BACKPACK_START)
+	   || (isCurHeroDst && dst.slot >= GameConstants::BACKPACK_START))
 		scrollBackpack(shift); //update backpack slots
 }
 
-void CArtifactsOfHero::artifactRemoved(const ArtifactLocation &al)
+void CArtifactsOfHero::artifactRemoved(const ArtifactLocation & al)
 {
 	if(al.isHolder(curHero))
 	{
@@ -829,20 +823,20 @@ CHeroArtPlace * CArtifactsOfHero::getArtPlace(int slot)
 	}
 	else
 	{
-		for(CHeroArtPlace *ap : backpack)
+		for(CHeroArtPlace * ap : backpack)
 			if(ap->slotID == slot)
 				return ap;
 		return nullptr;
 	}
 }
 
-void CArtifactsOfHero::artifactAssembled(const ArtifactLocation &al)
+void CArtifactsOfHero::artifactAssembled(const ArtifactLocation & al)
 {
 	if(al.isHolder(curHero))
 		updateWornSlots();
 }
 
-void CArtifactsOfHero::artifactDisassembled(const ArtifactLocation &al)
+void CArtifactsOfHero::artifactDisassembled(const ArtifactLocation & al)
 {
 	if(al.isHolder(curHero))
 		updateWornSlots();
@@ -871,16 +865,16 @@ CArtifactHolder::CArtifactHolder()
 {
 }
 
-void CWindowWithArtifacts::artifactRemoved(const ArtifactLocation &artLoc)
+void CWindowWithArtifacts::artifactRemoved(const ArtifactLocation & artLoc)
 {
-	for(CArtifactsOfHero *aoh : artSets)
+	for(CArtifactsOfHero * aoh : artSets)
 		aoh->artifactRemoved(artLoc);
 }
 
-void CWindowWithArtifacts::artifactMoved(const ArtifactLocation &artLoc, const ArtifactLocation &destLoc)
+void CWindowWithArtifacts::artifactMoved(const ArtifactLocation & artLoc, const ArtifactLocation & destLoc)
 {
-	CArtifactsOfHero *destaoh = nullptr;
-	for(CArtifactsOfHero *aoh : artSets)
+	CArtifactsOfHero * destaoh = nullptr;
+	for(CArtifactsOfHero * aoh : artSets)
 	{
 		aoh->artifactMoved(artLoc, destLoc);
 		aoh->redraw();
@@ -895,15 +889,15 @@ void CWindowWithArtifacts::artifactMoved(const ArtifactLocation &artLoc, const A
 	}
 }
 
-void CWindowWithArtifacts::artifactDisassembled(const ArtifactLocation &artLoc)
+void CWindowWithArtifacts::artifactDisassembled(const ArtifactLocation & artLoc)
 {
-	for(CArtifactsOfHero *aoh : artSets)
+	for(CArtifactsOfHero * aoh : artSets)
 		aoh->artifactDisassembled(artLoc);
 }
 
-void CWindowWithArtifacts::artifactAssembled(const ArtifactLocation &artLoc)
+void CWindowWithArtifacts::artifactAssembled(const ArtifactLocation & artLoc)
 {
-	for(CArtifactsOfHero *aoh : artSets)
+	for(CArtifactsOfHero * aoh : artSets)
 		aoh->artifactAssembled(artLoc);
 }
 
@@ -919,7 +913,7 @@ CArtifactsOfHero::SCommonPart::Artpos::Artpos()
 	clear();
 }
 
-void CArtifactsOfHero::SCommonPart::Artpos::setTo(const CHeroArtPlace *place, bool dontTakeBackpack)
+void CArtifactsOfHero::SCommonPart::Artpos::setTo(const CHeroArtPlace * place, bool dontTakeBackpack)
 {
 	slotID = place->slotID;
 	AOH = place->ourOwner;
@@ -930,11 +924,11 @@ void CArtifactsOfHero::SCommonPart::Artpos::setTo(const CHeroArtPlace *place, bo
 		art = place->ourArt;
 }
 
-bool CArtifactsOfHero::SCommonPart::Artpos::operator==(const ArtifactLocation &al) const
+bool CArtifactsOfHero::SCommonPart::Artpos::operator==(const ArtifactLocation & al) const
 {
 	if(!AOH)
 		return false;
-	bool ret = al.isHolder(AOH->curHero)  &&  al.slot == slotID;
+	bool ret = al.isHolder(AOH->curHero) && al.slot == slotID;
 
 	//assert(al.getArt() == art);
 	return ret;
@@ -946,7 +940,8 @@ bool CArtifactsOfHero::SCommonPart::Artpos::valid()
 	return art == AOH->curHero->getArt(slotID);
 }
 
-CArtPlace::CArtPlace(Point position, const CArtifactInstance * Art) : ourArt(Art)
+CArtPlace::CArtPlace(Point position, const CArtifactInstance * Art)
+	: ourArt(Art)
 {
 	image = nullptr;
 	pos += position;
@@ -963,7 +958,8 @@ void CArtPlace::clickRight(tribool down, bool previousState)
 	LRClickableAreaWTextComp::clickRight(down, previousState);
 }
 
-CCommanderArtPlace::CCommanderArtPlace(Point position, const CGHeroInstance * commanderOwner, ArtifactPosition artSlot, const CArtifactInstance * Art) : CArtPlace(position, Art), commanderOwner(commanderOwner), commanderSlotID(artSlot.num)
+CCommanderArtPlace::CCommanderArtPlace(Point position, const CGHeroInstance * commanderOwner, ArtifactPosition artSlot, const CArtifactInstance * Art)
+	: CArtPlace(position, Art), commanderOwner(commanderOwner), commanderSlotID(artSlot.num)
 {
 	createImage();
 	setArtifact(Art);
@@ -971,13 +967,13 @@ CCommanderArtPlace::CCommanderArtPlace(Point position, const CGHeroInstance * co
 
 void CCommanderArtPlace::clickLeft(tribool down, bool previousState)
 {
-	if (ourArt && text.size() && down)
+	if(ourArt && text.size() && down)
 		LOCPLINT->showYesNoDialog(CGI->generaltexth->localizedTexts["commanderWindow"]["artifactMessage"].String(), [this](){ returnArtToHeroCallback(); }, [](){});
 }
 
 void CCommanderArtPlace::clickRight(tribool down, bool previousState)
 {
-	if (ourArt && text.size() && down)
+	if(ourArt && text.size() && down)
 		CArtPlace::clickRight(down, previousState);
 }
 
@@ -986,11 +982,11 @@ void CCommanderArtPlace::createImage()
 	OBJ_CONSTRUCTION_CAPTURING_ALL;
 
 	int imageIndex = 0;
-	if (ourArt)
+	if(ourArt)
 		imageIndex = ourArt->artType->iconIndex;
 
 	image = new CAnimImage("artifact", imageIndex);
-	if (!ourArt)
+	if(!ourArt)
 		image->disable();
 }
 
@@ -1002,7 +998,7 @@ void CCommanderArtPlace::returnArtToHeroCallback()
 	ArtifactLocation src(commanderOwner->commander.get(), artifactPos);
 	ArtifactLocation dst(commanderOwner, freeSlot);
 
-	if (ourArt->canBePutAt(dst, true))
+	if(ourArt->canBePutAt(dst, true))
 	{
 		LOCPLINT->cb->swapArtifacts(src, dst);
 		setArtifact(nullptr);
@@ -1014,7 +1010,7 @@ void CCommanderArtPlace::setArtifact(const CArtifactInstance * art)
 {
 	baseType = -1; //by default we don't store any component
 	ourArt = art;
-	if (!art)
+	if(!art)
 	{
 		image->disable();
 		text = std::string();
@@ -1026,10 +1022,10 @@ void CCommanderArtPlace::setArtifact(const CArtifactInstance * art)
 
 	text = art->getEffectiveDescription();
 
-	if (art->artType->id == ArtifactID::SPELL_SCROLL)
+	if(art->artType->id == ArtifactID::SPELL_SCROLL)
 	{
 		int spellID = art->getGivenSpellID();
-		if (spellID >= 0)
+		if(spellID >= 0)
 		{
 			//add spell component info (used to provide a pic in r-click popup)
 			baseType = CComponent::spell;

+ 36 - 36
client/widgets/CArtifactHolder.h

@@ -23,10 +23,10 @@ class CArtifactHolder
 public:
 	CArtifactHolder();
 
-	virtual void artifactRemoved(const ArtifactLocation &artLoc)=0;
-	virtual void artifactMoved(const ArtifactLocation &artLoc, const ArtifactLocation &destLoc)=0;
-	virtual void artifactDisassembled(const ArtifactLocation &artLoc)=0;
-	virtual void artifactAssembled(const ArtifactLocation &artLoc)=0;
+	virtual void artifactRemoved(const ArtifactLocation & artLoc) = 0;
+	virtual void artifactMoved(const ArtifactLocation & artLoc, const ArtifactLocation & destLoc) = 0;
+	virtual void artifactDisassembled(const ArtifactLocation & artLoc) = 0;
+	virtual void artifactAssembled(const ArtifactLocation & artLoc) = 0;
 };
 
 class CWindowWithArtifacts : public CArtifactHolder
@@ -34,17 +34,18 @@ class CWindowWithArtifacts : public CArtifactHolder
 public:
 	std::vector<CArtifactsOfHero *> artSets;
 
-	void artifactRemoved(const ArtifactLocation &artLoc) override;
-	void artifactMoved(const ArtifactLocation &artLoc, const ArtifactLocation &destLoc) override;
-	void artifactDisassembled(const ArtifactLocation &artLoc) override;
-	void artifactAssembled(const ArtifactLocation &artLoc) override;
+	void artifactRemoved(const ArtifactLocation & artLoc) override;
+	void artifactMoved(const ArtifactLocation & artLoc, const ArtifactLocation & destLoc) override;
+	void artifactDisassembled(const ArtifactLocation & artLoc) override;
+	void artifactAssembled(const ArtifactLocation & artLoc) override;
 };
 
 class CArtPlace : public LRClickableAreaWTextComp
 {
 protected:
-	CAnimImage *image;
-	virtual void createImage()=0;
+	CAnimImage * image;
+	virtual void createImage() = 0;
+
 public:
 	const CArtifactInstance * ourArt; // should be changed only with setArtifact()
 
@@ -52,7 +53,7 @@ public:
 	void clickLeft(tribool down, bool previousState) override;
 	void clickRight(tribool down, bool previousState) override;
 
-	virtual void setArtifact(const CArtifactInstance *art)=0;
+	virtual void setArtifact(const CArtifactInstance * art) = 0;
 };
 
 class CCommanderArtPlace : public CArtPlace
@@ -63,6 +64,7 @@ protected:
 
 	void createImage() override;
 	void returnArtToHeroCallback();
+
 public:
 	CCommanderArtPlace(Point position, const CGHeroInstance * commanderOwner, ArtifactPosition artSlot, const CArtifactInstance * Art = nullptr);
 	void clickLeft(tribool down, bool previousState) override;
@@ -73,9 +75,9 @@ public:
 };
 
 /// Artifacts can be placed there. Gets shown at the hero window
-class CHeroArtPlace: public CArtPlace
+class CHeroArtPlace : public CArtPlace
 {
-	CAnimImage *selection;
+	CAnimImage * selection;
 
 	void createImage() override;
 
@@ -100,12 +102,11 @@ public:
 	void select();
 	void deselect();
 	void showAll(SDL_Surface * to) override;
-	bool fitsHere (const CArtifactInstance * art) const; //returns true if given artifact can be placed here
+	bool fitsHere(const CArtifactInstance * art) const; //returns true if given artifact can be placed here
 
 	void setMeAsDest(bool backpackAsVoid = true);
-	void setArtifact(const CArtifactInstance *art) override;
-	static bool askToAssemble(const CArtifactInstance *art, ArtifactPosition slot,
-	                          const CGHeroInstance *hero);
+	void setArtifact(const CArtifactInstance * art) override;
+	static bool askToAssemble(const CArtifactInstance * art, ArtifactPosition slot, const CGHeroInstance * hero);
 };
 
 /// Contains artifacts of hero. Distincts which artifacts are worn or backpacked
@@ -124,14 +125,14 @@ public:
 		struct Artpos
 		{
 			ArtifactPosition slotID;
-			const CArtifactsOfHero *AOH;
-			const CArtifactInstance *art;
+			const CArtifactsOfHero * AOH;
+			const CArtifactInstance * art;
 
 			Artpos();
 			void clear();
-			void setTo(const CHeroArtPlace *place, bool dontTakeBackpack);
+			void setTo(const CHeroArtPlace * place, bool dontTakeBackpack);
 			bool valid();
-			bool operator==(const ArtifactLocation &al) const;
+			bool operator==(const ArtifactLocation & al) const;
 		} src, dst;
 
 		std::set<CArtifactsOfHero *> participants; // Needed to mark slots.
@@ -144,35 +145,34 @@ public:
 
 	CButton * leftArtRoll, * rightArtRoll;
 	bool allowedAssembling;
-	std::multiset<const CArtifactInstance*> artifactsOnAltar; //artifacts id that are technically present in backpack but in GUI are moved to the altar - they'll be omitted in backpack slots
-	std::function<void(CHeroArtPlace*)> highlightModeCallback; //if set, clicking on art place doesn't pick artifact but highlights the slot and calls this function
+	std::multiset<const CArtifactInstance *> artifactsOnAltar; //artifacts id that are technically present in backpack but in GUI are moved to the altar - they'll be omitted in backpack slots
+	std::function<void(CHeroArtPlace *)> highlightModeCallback; //if set, clicking on art place doesn't pick artifact but highlights the slot and calls this function
 
 	void realizeCurrentTransaction(); //calls callback with parameters stored in commonInfo
-	void artifactMoved(const ArtifactLocation &src, const ArtifactLocation &dst);
-	void artifactRemoved(const ArtifactLocation &al);
-	void artifactAssembled(const ArtifactLocation &al);
-	void artifactDisassembled(const ArtifactLocation &al);
-	CHeroArtPlace *getArtPlace(int slot);//may return null
+	void artifactMoved(const ArtifactLocation & src, const ArtifactLocation & dst);
+	void artifactRemoved(const ArtifactLocation & al);
+	void artifactAssembled(const ArtifactLocation & al);
+	void artifactDisassembled(const ArtifactLocation & al);
+	CHeroArtPlace * getArtPlace(int slot); //may return null
 
 	void setHero(const CGHeroInstance * hero);
-	const CGHeroInstance *getHero() const;
+	const CGHeroInstance * getHero() const;
 	void dispose(); //free resources not needed after closing windows and reset state
 	void scrollBackpack(int dir); //dir==-1 => to left; dir==1 => to right
 
 	void safeRedraw();
-	void markPossibleSlots(const CArtifactInstance* art);
+	void markPossibleSlots(const CArtifactInstance * art);
 	void unmarkSlots(bool withRedraw = true); //unmarks slots in all visible AOHs
 	void unmarkLocalSlots(bool withRedraw = true); //unmarks slots in that particular AOH
-	void setSlotData (CHeroArtPlace* artPlace, ArtifactPosition slotID);
-	void updateWornSlots (bool redrawParent = true);
+	void setSlotData(CHeroArtPlace * artPlace, ArtifactPosition slotID);
+	void updateWornSlots(bool redrawParent = true);
 
 	void updateSlot(ArtifactPosition i);
-	void eraseSlotData (CHeroArtPlace* artPlace, ArtifactPosition slotID);
+	void eraseSlotData(CHeroArtPlace * artPlace, ArtifactPosition slotID);
 
-	CArtifactsOfHero(const Point& position, bool createCommonPart = false);
+	CArtifactsOfHero(const Point & position, bool createCommonPart = false);
 	//Alternative constructor, used if custom artifacts positioning required (Kingdom interface)
-	CArtifactsOfHero(std::map<ArtifactPosition, CHeroArtPlace *> ArtWorn, std::vector<CHeroArtPlace *> Backpack,
-		CButton *leftScroll, CButton *rightScroll, bool createCommonPart = false);
+	CArtifactsOfHero(std::map<ArtifactPosition, CHeroArtPlace *> ArtWorn, std::vector<CHeroArtPlace *> Backpack, CButton * leftScroll, CButton * rightScroll, bool createCommonPart = false);
 	~CArtifactsOfHero();
 	void updateParentWindow();
 	friend class CHeroArtPlace;

+ 169 - 130
client/widgets/CComponent.cpp

@@ -26,24 +26,22 @@
 #include "../../lib/CGeneralTextHandler.h"
 #include "../../lib/NetPacksBase.h"
 
-CComponent::CComponent(Etype Type, int Subtype, int Val, ESize imageSize):
-	image(nullptr),
-	perDay(false)
+CComponent::CComponent(Etype Type, int Subtype, int Val, ESize imageSize)
+	: image(nullptr), perDay(false)
 {
 	addUsedEvents(RCLICK);
 	init(Type, Subtype, Val, imageSize);
 }
 
-CComponent::CComponent(const Component &c, ESize imageSize):
-	image(nullptr),
-	perDay(false)
+CComponent::CComponent(const Component & c, ESize imageSize)
+	: image(nullptr), perDay(false)
 {
 	addUsedEvents(RCLICK);
 
-	if(c.id == Component::RESOURCE && c.when==-1)
+	if(c.id == Component::RESOURCE && c.when == -1)
 		perDay = true;
 
-	init((Etype)c.id,c.subtype,c.val, imageSize);
+	init((Etype)c.id, c.subtype, c.val, imageSize);
 }
 
 void CComponent::init(Etype Type, int Subtype, int Val, ESize imageSize)
@@ -64,7 +62,7 @@ void CComponent::init(Etype Type, int Subtype, int Val, ESize imageSize)
 	pos.h = image->pos.h;
 
 	EFonts font = FONT_SMALL;
-	if (imageSize < small)
+	if(imageSize < small)
 		font = FONT_TINY; //other sizes?
 
 	pos.h += 4; //distance between text and image
@@ -73,12 +71,12 @@ void CComponent::init(Etype Type, int Subtype, int Val, ESize imageSize)
 	for(auto & line : textLines)
 	{
 		int height = graphics->fonts[font]->getLineHeight();
-		auto   label = new CLabel(pos.w/2, pos.h + height/2, font, CENTER, Colors::WHITE, line);
+		auto label = new CLabel(pos.w / 2, pos.h + height / 2, font, CENTER, Colors::WHITE, line);
 
 		pos.h += height;
-		if (label->pos.w > pos.w)
+		if(label->pos.w > pos.w)
 		{
-			pos.x -= (label->pos.w - pos.w)/2;
+			pos.x -= (label->pos.w - pos.w) / 2;
 			pos.w = label->pos.w;
 		}
 	}
@@ -86,36 +84,48 @@ void CComponent::init(Etype Type, int Subtype, int Val, ESize imageSize)
 
 const std::vector<std::string> CComponent::getFileName()
 {
-	static const std::string  primSkillsArr [] = {"PSKIL32",        "PSKIL32",        "PSKIL42",        "PSKILL"};
-	static const std::string  secSkillsArr [] =  {"SECSK32",        "SECSK32",        "SECSKILL",       "SECSK82"};
-	static const std::string  resourceArr [] =   {"SMALRES",        "RESOURCE",       "RESOUR82",       "RESOUR82"};
-	static const std::string  creatureArr [] =   {"CPRSMALL",       "CPRSMALL",       "TWCRPORT",       "TWCRPORT"};
-	static const std::string  artifactArr[]  =   {"Artifact",       "Artifact",       "Artifact",       "Artifact"};
-	static const std::string  spellsArr [] =     {"SpellInt",       "SpellInt",       "SPELLSCR",       "SPELLSCR"};
-	static const std::string  moraleArr [] =     {"IMRL22",         "IMRL30",         "IMRL42",         "imrl82"};
-	static const std::string  luckArr [] =       {"ILCK22",         "ILCK30",         "ILCK42",         "ilck82"};
-	static const std::string  heroArr [] =       {"PortraitsSmall", "PortraitsSmall", "PortraitsLarge", "PortraitsLarge"};
-	static const std::string  flagArr [] =       {"CREST58",        "CREST58",        "CREST58",        "CREST58"};
+	static const std::string primSkillsArr[] = {"PSKIL32", "PSKIL32", "PSKIL42", "PSKILL"};
+	static const std::string secSkillsArr[] = {"SECSK32", "SECSK32", "SECSKILL", "SECSK82"};
+	static const std::string resourceArr[] = {"SMALRES", "RESOURCE", "RESOUR82", "RESOUR82"};
+	static const std::string creatureArr[] = {"CPRSMALL", "CPRSMALL", "TWCRPORT", "TWCRPORT"};
+	static const std::string artifactArr[] = {"Artifact", "Artifact", "Artifact", "Artifact"};
+	static const std::string spellsArr[] = {"SpellInt", "SpellInt", "SPELLSCR", "SPELLSCR"};
+	static const std::string moraleArr[] = {"IMRL22", "IMRL30", "IMRL42", "imrl82"};
+	static const std::string luckArr[] = {"ILCK22", "ILCK30", "ILCK42", "ilck82"};
+	static const std::string heroArr[] = {"PortraitsSmall", "PortraitsSmall", "PortraitsLarge", "PortraitsLarge"};
+	static const std::string flagArr[] = {"CREST58", "CREST58", "CREST58", "CREST58"};
 
 	auto gen = [](const std::string * arr)
-	{
-		return std::vector<std::string>(arr, arr + 4);
-	};
+		{
+			return std::vector<std::string>(arr, arr + 4);
+		};
 
 	switch(compType)
 	{
-	case primskill:  return gen(primSkillsArr);
-	case secskill:   return gen(secSkillsArr);
-	case resource:   return gen(resourceArr);
-	case creature:   return gen(creatureArr);
-	case artifact:   return gen(artifactArr);
-	case experience: return gen(primSkillsArr);
-	case spell:      return gen(spellsArr);
-	case morale:     return gen(moraleArr);
-	case luck:       return gen(luckArr);
-	case building:   return std::vector<std::string>(4, CGI->townh->factions[subtype]->town->clientInfo.buildingsIcons);
-	case hero:       return gen(heroArr);
-	case flag:       return gen(flagArr);
+	case primskill:
+		return gen(primSkillsArr);
+	case secskill:
+		return gen(secSkillsArr);
+	case resource:
+		return gen(resourceArr);
+	case creature:
+		return gen(creatureArr);
+	case artifact:
+		return gen(artifactArr);
+	case experience:
+		return gen(primSkillsArr);
+	case spell:
+		return gen(spellsArr);
+	case morale:
+		return gen(moraleArr);
+	case luck:
+		return gen(luckArr);
+	case building:
+		return std::vector<std::string>(4, CGI->townh->factions[subtype]->town->clientInfo.buildingsIcons);
+	case hero:
+		return gen(heroArr);
+	case flag:
+		return gen(flagArr);
 	}
 	assert(0);
 	return std::vector<std::string>();
@@ -125,18 +135,30 @@ size_t CComponent::getIndex()
 {
 	switch(compType)
 	{
-	case primskill:  return subtype;
-	case secskill:   return subtype*3 + 3 + val - 1;
-	case resource:   return subtype;
-	case creature:   return CGI->creh->creatures[subtype]->iconIndex;
-	case artifact:   return CGI->arth->artifacts[subtype]->iconIndex;
-	case experience: return 4;
-	case spell:      return subtype;
-	case morale:     return val+3;
-	case luck:       return val+3;
-	case building:   return val;
-	case hero:       return subtype;
-	case flag:       return subtype;
+	case primskill:
+		return subtype;
+	case secskill:
+		return subtype * 3 + 3 + val - 1;
+	case resource:
+		return subtype;
+	case creature:
+		return CGI->creh->creatures[subtype]->iconIndex;
+	case artifact:
+		return CGI->arth->artifacts[subtype]->iconIndex;
+	case experience:
+		return 4;
+	case spell:
+		return subtype;
+	case morale:
+		return val + 3;
+	case luck:
+		return val + 3;
+	case building:
+		return val;
+	case hero:
+		return subtype;
+	case flag:
+		return subtype;
 	}
 	assert(0);
 	return 0;
@@ -146,15 +168,19 @@ std::string CComponent::getDescription()
 {
 	switch(compType)
 	{
-	case primskill:  return (subtype < 4)? CGI->generaltexth->arraytxt[2+subtype] //Primary skill
-										 : CGI->generaltexth->allTexts[149]; //mana
-	case secskill:   return CGI->generaltexth->skillInfoTexts[subtype][val-1];
-	case resource:   return CGI->generaltexth->allTexts[242];
-	case creature:   return "";
+	case primskill:
+		return (subtype < 4) ? CGI->generaltexth->arraytxt[2 + subtype] //Primary skill
+		       : CGI->generaltexth->allTexts[149]; //mana
+	case secskill:
+		return CGI->generaltexth->skillInfoTexts[subtype][val - 1];
+	case resource:
+		return CGI->generaltexth->allTexts[242];
+	case creature:
+		return "";
 	case artifact:
 	{
 		std::unique_ptr<CArtifactInstance> art;
-		if (subtype != ArtifactID::SPELL_SCROLL)
+		if(subtype != ArtifactID::SPELL_SCROLL)
 		{
 			art.reset(CArtifactInstance::createNewArtifactInstance(subtype));
 		}
@@ -164,13 +190,20 @@ std::string CComponent::getDescription()
 		}
 		return art->getEffectiveDescription();
 	}
-	case experience: return CGI->generaltexth->allTexts[241];
-	case spell:      return CGI->spellh->objects[subtype]->getLevelInfo(val).description;
-	case morale:     return CGI->generaltexth->heroscrn[ 4 - (val>0) + (val<0)];
-	case luck:       return CGI->generaltexth->heroscrn[ 7 - (val>0) + (val<0)];
-	case building:   return CGI->townh->factions[subtype]->town->buildings[BuildingID(val)]->Description();
-	case hero:       return "";
-	case flag:       return "";
+	case experience:
+		return CGI->generaltexth->allTexts[241];
+	case spell:
+		return CGI->spellh->objects[subtype]->getLevelInfo(val).description;
+	case morale:
+		return CGI->generaltexth->heroscrn[4 - (val > 0) + (val < 0)];
+	case luck:
+		return CGI->generaltexth->heroscrn[7 - (val > 0) + (val < 0)];
+	case building:
+		return CGI->townh->factions[subtype]->town->buildings[BuildingID(val)]->Description();
+	case hero:
+		return "";
+	case flag:
+		return "";
 	}
 	assert(0);
 	return "";
@@ -191,40 +224,50 @@ std::string CComponent::getSubtitleInternal()
 	//FIXME: some of these are horrible (e.g creature)
 	switch(compType)
 	{
-	case primskill:  return boost::str(boost::format("%+d %s") % val % (subtype < 4 ? CGI->generaltexth->primarySkillNames[subtype] : CGI->generaltexth->allTexts[387]));
-	case secskill:   return CGI->generaltexth->levels[val-1] + "\n" + CGI->generaltexth->skillName[subtype];
-	case resource:   return boost::lexical_cast<std::string>(val);
-	case creature:   return (val? boost::lexical_cast<std::string>(val) + " " : "") + CGI->creh->creatures[subtype]->*(val != 1 ? &CCreature::namePl : &CCreature::nameSing);
-	case artifact:   return CGI->arth->artifacts[subtype]->Name();
+	case primskill:
+		return boost::str(boost::format("%+d %s") % val % (subtype < 4 ? CGI->generaltexth->primarySkillNames[subtype] : CGI->generaltexth->allTexts[387]));
+	case secskill:
+		return CGI->generaltexth->levels[val - 1] + "\n" + CGI->generaltexth->skillName[subtype];
+	case resource:
+		return boost::lexical_cast<std::string>(val);
+	case creature:
+		return (val ? boost::lexical_cast<std::string>(val) + " " : "") + CGI->creh->creatures[subtype]->*(val != 1 ? &CCreature::namePl : &CCreature::nameSing);
+	case artifact:
+		return CGI->arth->artifacts[subtype]->Name();
 	case experience:
+	{
+		if(subtype == 1) //+1 level - tree of knowledge
 		{
-			if(subtype == 1) //+1 level - tree of knowledge
-			{
-				std::string level = CGI->generaltexth->allTexts[442];
-				boost::replace_first(level, "1", boost::lexical_cast<std::string>(val));
-				return level;
-			}
-			else
-			{
-				return boost::lexical_cast<std::string>(val); //amount of experience OR level required for seer hut;
-			}
+			std::string level = CGI->generaltexth->allTexts[442];
+			boost::replace_first(level, "1", boost::lexical_cast<std::string>(val));
+			return level;
 		}
-	case spell:      return CGI->spellh->objects[subtype]->name;
-	case morale:     return "";
-	case luck:       return "";
+		else
+		{
+			return boost::lexical_cast<std::string>(val); //amount of experience OR level required for seer hut;
+		}
+	}
+	case spell:
+		return CGI->spellh->objects[subtype]->name;
+	case morale:
+		return "";
+	case luck:
+		return "";
 	case building:
+	{
+		auto building = CGI->townh->factions[subtype]->town->buildings[BuildingID(val)];
+		if(!building)
 		{
-			auto building = CGI->townh->factions[subtype]->town->buildings[BuildingID(val)];
-			if(!building)
-			{
-				logGlobal->errorStream() << boost::format("Town of faction %s has no building #%d")
-					% CGI->townh->factions[subtype]->town->faction->name % val;
-				return (boost::format("Missing building #%d") % val).str();
-			}
-			return building->Name();
+			logGlobal->errorStream() << boost::format("Town of faction %s has no building #%d")
+			% CGI->townh->factions[subtype]->town->faction->name % val;
+			return (boost::format("Missing building #%d") % val).str();
 		}
-	case hero:       return "";
-	case flag:       return CGI->generaltexth->capColors[subtype];
+		return building->Name();
+	}
+	case hero:
+		return "";
+	case flag:
+		return CGI->generaltexth->capColors[subtype];
 	}
 	assert(0);
 	return "";
@@ -245,7 +288,7 @@ void CComponent::clickRight(tribool down, bool previousState)
 
 void CSelectableComponent::clickLeft(tribool down, bool previousState)
 {
-	if (down)
+	if(down)
 	{
 		if(onSelect)
 			onSelect();
@@ -257,16 +300,16 @@ void CSelectableComponent::init()
 	selected = false;
 }
 
-CSelectableComponent::CSelectableComponent(const Component &c, std::function<void()> OnSelect):
-	CComponent(c),onSelect(OnSelect)
+CSelectableComponent::CSelectableComponent(const Component & c, std::function<void()> OnSelect)
+	: CComponent(c), onSelect(OnSelect)
 {
 	type |= REDRAW_PARENT;
 	addUsedEvents(LCLICK | KEYBOARD);
 	init();
 }
 
-CSelectableComponent::CSelectableComponent(Etype Type, int Sub, int Val, ESize imageSize, std::function<void()> OnSelect):
-	CComponent(Type,Sub,Val, imageSize),onSelect(OnSelect)
+CSelectableComponent::CSelectableComponent(Etype Type, int Sub, int Val, ESize imageSize, std::function<void()> OnSelect)
+	: CComponent(Type, Sub, Val, imageSize), onSelect(OnSelect)
 {
 	type |= REDRAW_PARENT;
 	addUsedEvents(LCLICK | KEYBOARD);
@@ -287,48 +330,48 @@ void CSelectableComponent::showAll(SDL_Surface * to)
 	CComponent::showAll(to);
 	if(selected)
 	{
-		CSDL_Ext::drawBorder(to, Rect::around(image->pos), int3(239,215,123));
+		CSDL_Ext::drawBorder(to, Rect::around(image->pos), int3(239, 215, 123));
 	}
 }
 
 void CComponentBox::selectionChanged(CSelectableComponent * newSelection)
 {
-	if (newSelection == selected)
+	if(newSelection == selected)
 		return;
 
-	if (selected)
+	if(selected)
 		selected->select(false);
 
 	selected = newSelection;
-	if (onSelect)
+	if(onSelect)
 		onSelect(selectedIndex());
 
-	if (selected)
+	if(selected)
 		selected->select(true);
 }
 
 int CComponentBox::selectedIndex()
 {
-	if (selected)
+	if(selected)
 		return std::find(components.begin(), components.end(), selected) - components.begin();
 	return -1;
 }
 
-Point CComponentBox::getOrTextPos(CComponent *left, CComponent *right)
+Point CComponentBox::getOrTextPos(CComponent * left, CComponent * right)
 {
-	int leftSubtitle  = ( left->pos.w -  left->image->pos.w) / 2;
+	int leftSubtitle = (left->pos.w - left->image->pos.w) / 2;
 	int rightSubtitle = (right->pos.w - right->image->pos.w) / 2;
 	int fullDistance = getDistance(left, right) + leftSubtitle + rightSubtitle;
 
-	return Point(fullDistance/2 - leftSubtitle, (left->image->pos.h + right->image->pos.h) / 4);
+	return Point(fullDistance / 2 - leftSubtitle, (left->image->pos.h + right->image->pos.h) / 4);
 }
 
-int CComponentBox::getDistance(CComponent *left, CComponent *right)
+int CComponentBox::getDistance(CComponent * left, CComponent * right)
 {
 	static const int betweenImagesMin = 20;
 	static const int betweenSubtitlesMin = 10;
 
-	int leftSubtitle  = ( left->pos.w -  left->image->pos.w) / 2;
+	int leftSubtitle = (left->pos.w - left->image->pos.w) / 2;
 	int rightSubtitle = (right->pos.w - right->image->pos.w) / 2;
 	int subtitlesOffset = leftSubtitle + rightSubtitle;
 
@@ -340,7 +383,7 @@ void CComponentBox::placeComponents(bool selectable)
 	static const int betweenRows = 22;
 
 	OBJ_CONSTRUCTION_CAPTURING_ALL;
-	if (components.empty())
+	if(components.empty())
 		return;
 
 	//prepare components
@@ -355,11 +398,11 @@ void CComponentBox::placeComponents(bool selectable)
 		size_t comps;
 		int width;
 		int height;
-		RowData (size_t Comps, int Width, int Height):
-		comps(Comps), width (Width), height (Height){};
+		RowData(size_t Comps, int Width, int Height)
+			: comps(Comps), width(Width), height(Height){};
 	};
 	std::vector<RowData> rows;
-	rows.push_back (RowData (0,0,0));
+	rows.push_back(RowData(0, 0, 0));
 
 	//split components in rows
 	CComponent * prevComp = nullptr;
@@ -372,14 +415,14 @@ void CComponentBox::placeComponents(bool selectable)
 		const int distance = prevComp ? getDistance(prevComp, comp) : 0;
 
 		//start next row
-		if ((pos.w != 0 && rows.back().width + comp->pos.w + distance > pos.w) // row is full
-			|| rows.back().comps >= 4) // no more than 4 comps per row
+		if((pos.w != 0 && rows.back().width + comp->pos.w + distance > pos.w) // row is full
+		   || rows.back().comps >= 4) // no more than 4 comps per row
 		{
 			prevComp = nullptr;
-			rows.push_back (RowData (0,0,0));
+			rows.push_back(RowData(0, 0, 0));
 		}
 
-		if (prevComp)
+		if(prevComp)
 			rows.back().width += distance;
 
 		rows.back().comps++;
@@ -389,7 +432,7 @@ void CComponentBox::placeComponents(bool selectable)
 		prevComp = comp;
 	}
 
-	if (pos.w == 0)
+	if(pos.w == 0)
 	{
 		for(auto & row : rows)
 			vstd::amax(pos.w, row.width);
@@ -400,26 +443,26 @@ void CComponentBox::placeComponents(bool selectable)
 		height += row.height;
 
 	//assert(pos.h == 0 || pos.h < height);
-	if (pos.h == 0)
+	if(pos.h == 0)
 		pos.h = height;
 
 	auto iter = components.begin();
 	int currentY = (pos.h - height) / 2;
 
 	//move components to their positions
-	for (auto & rows_row : rows)
+	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);
 		prevComp = nullptr;
 
 		int currentX = 0;
-		for (size_t col = 0; col < rows_row.comps; col++)
+		for(size_t col = 0; col < rows_row.comps; col++)
 		{
 			currentX += freeSpace;
-			if (prevComp)
+			if(prevComp)
 			{
-				if (selectable)
+				if(selectable)
 				{
 					Point orPos = Point(currentX - freeSpace, currentY) + getOrTextPos(prevComp, *iter);
 
@@ -438,28 +481,24 @@ void CComponentBox::placeComponents(bool selectable)
 	}
 }
 
-CComponentBox::CComponentBox(CComponent * _components, Rect position):
-	components(1, _components),
-	selected(nullptr)
+CComponentBox::CComponentBox(CComponent * _components, Rect position)
+	: components(1, _components), selected(nullptr)
 {
 	type |= REDRAW_PARENT;
 	pos = position + pos;
 	placeComponents(false);
 }
 
-CComponentBox::CComponentBox(std::vector<CComponent *> _components, Rect position):
-	components(_components),
-	selected(nullptr)
+CComponentBox::CComponentBox(std::vector<CComponent *> _components, Rect position)
+	: components(_components), selected(nullptr)
 {
 	type |= REDRAW_PARENT;
 	pos = position + pos;
 	placeComponents(false);
 }
 
-CComponentBox::CComponentBox(std::vector<CSelectableComponent *> _components, Rect position, std::function<void(int newID)> _onSelect):
-	components(_components.begin(), _components.end()),
-	selected(nullptr),
-	onSelect(_onSelect)
+CComponentBox::CComponentBox(std::vector<CSelectableComponent *> _components, Rect position, std::function<void(int newID)> _onSelect)
+	: components(_components.begin(), _components.end()), selected(nullptr), onSelect(_onSelect)
 {
 	type |= REDRAW_PARENT;
 	pos = position + pos;

+ 29 - 12
client/widgets/CComponent.h

@@ -20,16 +20,32 @@ class CComponent : public virtual CIntObject
 public:
 	enum Etype
 	{
-		primskill, secskill, resource, creature, artifact, experience, spell, morale, luck, building, hero, flag, typeInvalid
+		primskill,
+		secskill,
+		resource,
+		creature,
+		artifact,
+		experience,
+		spell,
+		morale,
+		luck,
+		building,
+		hero,
+		flag,
+		typeInvalid
 	};
 
 	//NOTE: not all types have exact these sizes or have less than 4 of them. In such cases closest one will be used
 	enum ESize
 	{
-		tiny,  // ~22-24px
-		small, // ~30px
-		medium,// ~42px
-		large,  // ~82px
+		tiny,
+		// ~22-24px
+		small,
+		// ~30px
+		medium,
+		// ~42px
+		large,
+		// ~82px
 		sizeInvalid
 	};
 
@@ -42,7 +58,7 @@ private:
 	void init(Etype Type, int Subtype, int Val, ESize imageSize);
 
 public:
-	CAnimImage *image; //our image
+	CAnimImage * image; //our image
 
 	Etype compType; //component type
 	ESize size; //component size.
@@ -53,8 +69,8 @@ public:
 	std::string getDescription();
 	std::string getSubtitle();
 
-	CComponent(Etype Type, int Subtype, int Val = 0, ESize imageSize=large);
-	CComponent(const Component &c, ESize imageSize=large);
+	CComponent(Etype Type, int Subtype, int Val = 0, ESize imageSize = large);
+	CComponent(const Component & c, ESize imageSize = large);
 
 	void clickRight(tribool down, bool previousState) override; //call-in
 };
@@ -63,6 +79,7 @@ public:
 class CSelectableComponent : public CComponent, public CKeyShortcut
 {
 	void init();
+
 public:
 	bool selected; //if true, this component is selected
 	std::function<void()> onSelect; //function called on selection change
@@ -71,8 +88,8 @@ public:
 	void select(bool on);
 
 	void clickLeft(tribool down, bool previousState) override; //call-in
-	CSelectableComponent(Etype Type, int Sub, int Val, ESize imageSize=large, std::function<void()> OnSelect = nullptr);
-	CSelectableComponent(const Component &c, std::function<void()> OnSelect = nullptr);
+	CSelectableComponent(Etype Type, int Sub, int Val, ESize imageSize = large, std::function<void()> OnSelect = nullptr);
+	CSelectableComponent(const Component & c, std::function<void()> OnSelect = nullptr);
 };
 
 /// box with multiple components (up to 8?)
@@ -88,10 +105,10 @@ class CComponentBox : public CIntObject
 
 	//get position of "or" text between these comps
 	//it will place "or" equidistant to both images
-	Point getOrTextPos(CComponent *left, CComponent * right);
+	Point getOrTextPos(CComponent * left, CComponent * right);
 
 	//get distance between these copmonents
-	int getDistance(CComponent *left, CComponent * right);
+	int getDistance(CComponent * left, CComponent * right);
 	void placeComponents(bool selectable);
 
 public:

+ 84 - 90
client/widgets/CGarrisonInt.cpp

@@ -29,13 +29,13 @@
 
 void CGarrisonSlot::setHighlight(bool on)
 {
-	if (on)
+	if(on)
 		selectionImage->enable(); //show
 	else
 		selectionImage->disable(); //hide
 }
 
-void CGarrisonSlot::hover (bool on)
+void CGarrisonSlot::hover(bool on)
 {
 	////Hoverable::hover(on);
 	if(on)
@@ -48,22 +48,22 @@ void CGarrisonSlot::hover (bool on)
 				if(owner->getSelection() == this)
 				{
 					temp = CGI->generaltexth->tcommands[4]; //View %s
-					boost::algorithm::replace_first(temp,"%s",creature->nameSing);
+					boost::algorithm::replace_first(temp, "%s", creature->nameSing);
 				}
-				else if (owner->getSelection()->creature == creature)
+				else if(owner->getSelection()->creature == creature)
 				{
 					temp = CGI->generaltexth->tcommands[2]; //Combine %s armies
-					boost::algorithm::replace_first(temp,"%s",creature->nameSing);
+					boost::algorithm::replace_first(temp, "%s", creature->nameSing);
 				}
-				else if (owner->getSelection()->creature)
+				else if(owner->getSelection()->creature)
 				{
 					temp = CGI->generaltexth->tcommands[7]; //Exchange %s with %s
-					boost::algorithm::replace_first(temp,"%s",owner->getSelection()->creature->nameSing);
-					boost::algorithm::replace_first(temp,"%s",creature->nameSing);
+					boost::algorithm::replace_first(temp, "%s", owner->getSelection()->creature->nameSing);
+					boost::algorithm::replace_first(temp, "%s", creature->nameSing);
 				}
 				else
 				{
-					logGlobal->warnStream() << "Warning - shouldn't be - highlighted void slot "<<owner->getSelection();
+					logGlobal->warnStream() << "Warning - shouldn't be - highlighted void slot " << owner->getSelection();
 					logGlobal->warnStream() << "Highlighted set to nullptr";
 					owner->selectSlot(nullptr);
 				}
@@ -82,25 +82,25 @@ void CGarrisonSlot::hover (bool on)
 				{
 					temp = CGI->generaltexth->allTexts[481]; //Select %s
 				}
-				boost::algorithm::replace_first(temp,"%s",creature->nameSing);
+				boost::algorithm::replace_first(temp, "%s", creature->nameSing);
 			}
 		}
 		else
 		{
 			if(owner->getSelection())
 			{
-				const CArmedInstance *highl = owner->getSelection()->getObj();
-				if(  highl->needsLastStack()		//we are moving stack from hero's
-				  && highl->stacksCount() == 1	//it's only stack
-				  && owner->getSelection()->upg != upg	//we're moving it to the other garrison
-				  )
+				const CArmedInstance * highl = owner->getSelection()->getObj();
+				if(highl->needsLastStack() //we are moving stack from hero's
+				   && highl->stacksCount() == 1 //it's only stack
+				   && owner->getSelection()->upg != upg //we're moving it to the other garrison
+				   )
 				{
 					temp = CGI->generaltexth->tcommands[5]; //Cannot move last army to garrison
 				}
 				else
 				{
 					temp = CGI->generaltexth->tcommands[6]; //Move %s
-					boost::algorithm::replace_first(temp,"%s",owner->getSelection()->creature->nameSing);
+					boost::algorithm::replace_first(temp, "%s", owner->getSelection()->creature->nameSing);
 				}
 			}
 			else
@@ -118,7 +118,7 @@ void CGarrisonSlot::hover (bool on)
 
 const CArmedInstance * CGarrisonSlot::getObj() const
 {
-	return 	owner->armedObjs[upg];
+	return owner->armedObjs[upg];
 }
 
 /// @return Whether the unit in the slot belongs to the current player.
@@ -143,12 +143,20 @@ bool CGarrisonSlot::viewInfo()
 	UpgradeInfo pom;
 	LOCPLINT->cb->getUpgradeInfo(getObj(), ID, pom);
 
-	bool canUpgrade = getObj()->tempOwner == LOCPLINT->playerID && pom.oldID>=0; //upgrade is possible
-	bool canDismiss = getObj()->tempOwner == LOCPLINT->playerID && (getObj()->stacksCount()>1  || !getObj()->needsLastStack());
+	bool canUpgrade = getObj()->tempOwner == LOCPLINT->playerID && pom.oldID >= 0; //upgrade is possible
+	bool canDismiss = getObj()->tempOwner == LOCPLINT->playerID && (getObj()->stacksCount() > 1 || !getObj()->needsLastStack());
 	std::function<void(CreatureID)> upgr = nullptr;
 	std::function<void()> dism = nullptr;
-	if(canUpgrade) upgr = [=] (CreatureID newID) { LOCPLINT->cb->upgradeCreature(getObj(), ID, newID); };
-	if(canDismiss) dism = [=](){ LOCPLINT->cb->dismissCreature(getObj(), ID); };
+	if(canUpgrade)
+		upgr = [=](CreatureID newID)
+			{
+				LOCPLINT->cb->upgradeCreature(getObj(), ID, newID);
+			};
+	if(canDismiss)
+		dism = [=]()
+			{
+				LOCPLINT->cb->dismissCreature(getObj(), ID);
+			};
 
 	owner->selectSlot(nullptr);
 	owner->setSplittingMode(false);
@@ -166,19 +174,19 @@ bool CGarrisonSlot::viewInfo()
 bool CGarrisonSlot::highlightOrDropArtifact()
 {
 	bool artSelected = false;
-	if (CWindowWithArtifacts* chw = dynamic_cast<CWindowWithArtifacts*>(GH.topInt())) //dirty solution
+	if(CWindowWithArtifacts * chw = dynamic_cast<CWindowWithArtifacts *>(GH.topInt())) //dirty solution
 	{
 		const std::shared_ptr<CArtifactsOfHero::SCommonPart> commonInfo = chw->artSets.front()->commonInfo;
-		if (const CArtifactInstance *art = commonInfo->src.art)
+		if(const CArtifactInstance * art = commonInfo->src.art)
 		{
-			const CGHeroInstance *srcHero = commonInfo->src.AOH->getHero();
+			const CGHeroInstance * srcHero = commonInfo->src.AOH->getHero();
 			artSelected = true;
-			if (myStack) // try dropping the artifact only if the slot isn't empty
+			if(myStack) // try dropping the artifact only if the slot isn't empty
 			{
 				ArtifactLocation src(srcHero, commonInfo->src.slotID);
 				ArtifactLocation dst(myStack, ArtifactPosition::CREATURE_SLOT);
-				if (art->canBePutAt(dst, true))
-				{	//equip clicked stack
+				if(art->canBePutAt(dst, true))
+				{ //equip clicked stack
 					if(dst.getArt())
 					{
 						//creature can wear only one active artifact
@@ -190,7 +198,7 @@ bool CGarrisonSlot::highlightOrDropArtifact()
 			}
 		}
 	}
-	if (!artSelected && creature)
+	if(!artSelected && creature)
 	{
 		owner->selectSlot(this);
 		if(creature)
@@ -208,23 +216,23 @@ bool CGarrisonSlot::highlightOrDropArtifact()
 bool CGarrisonSlot::split()
 {
 	const CGarrisonSlot * selection = owner->getSelection();
-	owner->p2 = ID;   // store the second stack pos
-	owner->pb = upg;  // store the second stack owner (up or down army)
+	owner->p2 = ID; // store the second stack pos
+	owner->pb = upg; // store the second stack owner (up or down army)
 	owner->setSplittingMode(false);
 
-	int minLeft=0, minRight=0;
+	int minLeft = 0, minRight = 0;
 
 	if(upg != selection->upg) // not splitting within same army
 	{
 		if(selection->getObj()->stacksCount() == 1 // we're splitting away the last stack
-			&& selection->getObj()->needsLastStack() )
+		   && selection->getObj()->needsLastStack())
 		{
 			minLeft = 1;
 		}
 		// destination army can't be emptied, unless we're rebalancing two stacks of same creature
 		if(getObj()->stacksCount() == 1
-			&& selection->creature == creature
-			&& getObj()->needsLastStack() )
+		   && selection->creature == creature
+		   && getObj()->needsLastStack())
 		{
 			minRight = 1;
 		}
@@ -234,7 +242,7 @@ bool CGarrisonSlot::split()
 	int countRight = myStack ? myStack->count : 0;
 
 	GH.pushInt(new CSplitWindow(selection->creature, std::bind(&CGarrisonInt::splitStacks, owner, _1, _2),
-	                            minLeft, minRight, countLeft, countRight));
+				    minLeft, minRight, countLeft, countRight));
 	return true;
 }
 
@@ -248,17 +256,17 @@ bool CGarrisonSlot::mustForceReselection() const
 {
 	const CGarrisonSlot * selection = owner->getSelection();
 	bool withAlly = selection->our() ^ our();
-	if (!creature || !selection->creature)
+	if(!creature || !selection->creature)
 		return false;
 	// Attempt to take creatures from ally (select theirs first)
-	if (!selection->our())
+	if(!selection->our())
 		return true;
 	// Attempt to swap creatures with ally (select ours first)
-	if (selection->creature != creature && withAlly)
+	if(selection->creature != creature && withAlly)
 		return true;
-	if (!owner->removableUnits)
+	if(!owner->removableUnits)
 	{
-		if (selection->upg == EGarrisonType::UP)
+		if(selection->upg == EGarrisonType::UP)
 			return true;
 		else
 			return creature || upg == EGarrisonType::UP;
@@ -285,7 +293,7 @@ void CGarrisonSlot::clickLeft(tribool down, bool previousState)
 		else if(selection == this)
 			refr = viewInfo();
 		// Re-highlight if troops aren't removable or not ours.
-		else if (mustForceReselection())
+		else if(mustForceReselection())
 		{
 			if(creature)
 				owner->selectSlot(this);
@@ -297,14 +305,14 @@ void CGarrisonSlot::clickLeft(tribool down, bool previousState)
 			const CArmedInstance * selectedObj = owner->armedObjs[selection->upg];
 			bool lastHeroStackSelected = false;
 			if(selectedObj->stacksCount() == 1
-				&& owner->getSelection()->upg != upg
-				&& dynamic_cast<const CGHeroInstance*>(selectedObj))
+			   && owner->getSelection()->upg != upg
+			   && dynamic_cast<const CGHeroInstance *>(selectedObj))
 			{
 				lastHeroStackSelected = true;
 			}
 
 			if((owner->getSplittingMode() || LOCPLINT->shiftPressed()) // split window
-				&& (!creature || creature == selection->creature))
+			   && (!creature || creature == selection->creature))
 			{
 				refr = split();
 			}
@@ -328,7 +336,7 @@ void CGarrisonSlot::clickLeft(tribool down, bool previousState)
 
 void CGarrisonSlot::update()
 {
-	if (getObj() != nullptr)
+	if(getObj() != nullptr)
 	{
 		addUsedEvents(LCLICK | RCLICK | HOVER);
 		myStack = getObj()->getStackPtr(ID);
@@ -341,7 +349,7 @@ void CGarrisonSlot::update()
 		creature = nullptr;
 	}
 
-	if (creature)
+	if(creature)
 	{
 		creatureImage->enable();
 		creatureImage->setFrame(creature->iconIndex);
@@ -356,15 +364,11 @@ void CGarrisonSlot::update()
 	}
 }
 
-CGarrisonSlot::CGarrisonSlot(CGarrisonInt *Owner, int x, int y, SlotID IID, CGarrisonSlot::EGarrisonType Upg, const CStackInstance * Creature):
-    ID(IID),
-    owner(Owner),
-    myStack(Creature),
-    creature(Creature ? Creature->type : nullptr),
-    upg(Upg)
+CGarrisonSlot::CGarrisonSlot(CGarrisonInt * Owner, int x, int y, SlotID IID, CGarrisonSlot::EGarrisonType Upg, const CStackInstance * Creature)
+	: ID(IID), owner(Owner), myStack(Creature), creature(Creature ? Creature->type : nullptr), upg(Upg)
 {
 	OBJ_CONSTRUCTION_CAPTURING_ALL;
-	if (getObj())
+	if(getObj())
 		addUsedEvents(LCLICK | RCLICK | HOVER);
 	pos.x += x;
 	pos.y += y;
@@ -372,7 +376,7 @@ CGarrisonSlot::CGarrisonSlot(CGarrisonInt *Owner, int x, int y, SlotID IID, CGar
 	std::string imgName = owner->smallIcons ? "cprsmall" : "TWCRPORT";
 
 	creatureImage = new CAnimImage(imgName, creature ? creature->iconIndex : 0);
-	if (!creature)
+	if(!creature)
 		creatureImage->disable();
 
 	selectionImage = new CAnimImage(imgName, 1);
@@ -390,7 +394,7 @@ CGarrisonSlot::CGarrisonSlot(CGarrisonInt *Owner, int x, int y, SlotID IID, CGar
 	}
 
 	stackCount = new CLabel(pos.w, pos.h, owner->smallIcons ? FONT_TINY : FONT_MEDIUM, BOTTOMRIGHT, Colors::WHITE);
-	if (!creature)
+	if(!creature)
 		stackCount->disable();
 	else
 		stackCount->setText(boost::lexical_cast<std::string>(myStack->count));
@@ -407,23 +411,23 @@ void CGarrisonInt::addSplitBtn(CButton * button)
 void CGarrisonInt::createSlots()
 {
 	OBJ_CONSTRUCTION_CAPTURING_ALL;
-	int distance = interx + (smallIcons? 32 : 58);
-	for(int i=0; i<2; i++)
+	int distance = interx + (smallIcons ? 32 : 58);
+	for(int i = 0; i < 2; i++)
 	{
-		std::vector<CGarrisonSlot*> garrisonSlots;
+		std::vector<CGarrisonSlot *> garrisonSlots;
 		garrisonSlots.resize(7);
-		if (armedObjs[i])
+		if(armedObjs[i])
 		{
 			for(auto & elem : armedObjs[i]->Slots())
 			{
-				garrisonSlots[elem.first.getNum()] = new CGarrisonSlot(this, i*garOffset.x + (elem.first.getNum()*distance), i*garOffset.y, elem.first, static_cast<CGarrisonSlot::EGarrisonType>(i), elem.second);
+				garrisonSlots[elem.first.getNum()] = new CGarrisonSlot(this, i * garOffset.x + (elem.first.getNum() * distance), i * garOffset.y, elem.first, static_cast<CGarrisonSlot::EGarrisonType>(i), elem.second);
 			}
 		}
-		for(int j=0; j<7; j++)
+		for(int j = 0; j < 7; j++)
 		{
 			if(!garrisonSlots[j])
-				garrisonSlots[j] = new CGarrisonSlot(this, i*garOffset.x + (j*distance), i*garOffset.y, SlotID(j), static_cast<CGarrisonSlot::EGarrisonType>(i), nullptr);
-			if (twoRows && j>=4)
+				garrisonSlots[j] = new CGarrisonSlot(this, i * garOffset.x + (j * distance), i * garOffset.y, SlotID(j), static_cast<CGarrisonSlot::EGarrisonType>(i), nullptr);
+			if(twoRows && j >= 4)
 			{
 				garrisonSlots[j]->moveBy(Point(-126, 37));
 			}
@@ -458,18 +462,8 @@ void CGarrisonInt::splitStacks(int, int amountRight)
 	LOCPLINT->cb->splitStack(armedObjs[getSelection()->upg], armedObjs[pb], getSelection()->ID, p2, amountRight);
 }
 
-CGarrisonInt::CGarrisonInt(int x, int y, int inx, const Point &garsOffset,
-                           SDL_Surface *pomsur, const Point& SurOffset,
-                           const CArmedInstance *s1, const CArmedInstance *s2,
-                           bool _removableUnits, bool smallImgs, bool _twoRows ) :
-    highlighted(nullptr),
-    inSplittingMode(false),
-    interx(inx),
-    garOffset(garsOffset),
-    pb(false),
-    smallIcons(smallImgs),
-    removableUnits(_removableUnits),
-    twoRows(_twoRows)
+CGarrisonInt::CGarrisonInt(int x, int y, int inx, const Point & garsOffset, SDL_Surface * pomsur, const Point & SurOffset, const CArmedInstance * s1, const CArmedInstance * s2, bool _removableUnits, bool smallImgs, bool _twoRows)
+	: highlighted(nullptr), inSplittingMode(false), interx(inx), garOffset(garsOffset), pb(false), smallIcons(smallImgs), removableUnits(_removableUnits), twoRows(_twoRows)
 {
 	setArmy(s1, false);
 	setArmy(s2, true);
@@ -483,18 +477,18 @@ const CGarrisonSlot * CGarrisonInt::getSelection()
 	return highlighted;
 }
 
-void CGarrisonInt::selectSlot(CGarrisonSlot *slot)
+void CGarrisonInt::selectSlot(CGarrisonSlot * slot)
 {
-	if (slot != highlighted)
+	if(slot != highlighted)
 	{
-		if (highlighted)
+		if(highlighted)
 			highlighted->setHighlight(false);
 
 		highlighted = slot;
-		for (auto button : splitButtons)
+		for(auto button : splitButtons)
 			button->block(highlighted == nullptr || !slot->our());
 
-		if (highlighted)
+		if(highlighted)
 			highlighted->setHighlight(true);
 	}
 }
@@ -503,12 +497,12 @@ void CGarrisonInt::setSplittingMode(bool on)
 {
 	assert(on == false || highlighted != nullptr); //can't be in splitting mode without selection
 
-	if (inSplittingMode || on)
+	if(inSplittingMode || on)
 	{
 		for(CGarrisonSlot * slot : availableSlots)
 		{
-			if(slot!=getSelection())
-				slot->setHighlight( ( on && (slot->our() || slot->ally()) && (slot->creature == nullptr || slot->creature == getSelection()->creature)));
+			if(slot != getSelection())
+				slot->setHighlight((on && (slot->our() || slot->ally()) && (slot->creature == nullptr || slot->creature == getSelection()->creature)));
 		}
 		inSplittingMode = on;
 	}
@@ -519,27 +513,27 @@ bool CGarrisonInt::getSplittingMode()
 	return inSplittingMode;
 }
 
-void CGarrisonInt::setArmy(const CArmedInstance *army, bool bottomGarrison)
+void CGarrisonInt::setArmy(const CArmedInstance * army, bool bottomGarrison)
 {
-	owned[bottomGarrison] =  army ? (army->tempOwner == LOCPLINT->playerID || army->tempOwner == PlayerColor::UNFLAGGABLE) : false;
+	owned[bottomGarrison] = army ? (army->tempOwner == LOCPLINT->playerID || army->tempOwner == PlayerColor::UNFLAGGABLE) : false;
 	armedObjs[bottomGarrison] = army;
 }
 
-CGarrisonWindow::CGarrisonWindow( const CArmedInstance *up, const CGHeroInstance *down, bool removableUnits ):
-	CWindowObject(PLAYER_COLORED, "GARRISON")
+CGarrisonWindow::CGarrisonWindow(const CArmedInstance * up, const CGHeroInstance * down, bool removableUnits)
+	: CWindowObject(PLAYER_COLORED, "GARRISON")
 {
 	OBJ_CONSTRUCTION_CAPTURING_ALL;
 
-	garr = new CGarrisonInt(92, 127, 4, Point(0,96), background->bg, Point(93,127), up, down, removableUnits);
+	garr = new CGarrisonInt(92, 127, 4, Point(0, 96), background->bg, Point(93, 127), up, down, removableUnits);
 	{
-		CButton *split = new CButton(Point(88, 314), "IDV6432.DEF", CButton::tooltip(CGI->generaltexth->tcommands[3], ""), [&](){ garr->splitClick(); } );
+		CButton * split = new CButton(Point(88, 314), "IDV6432.DEF", CButton::tooltip(CGI->generaltexth->tcommands[3], ""), [&](){ garr->splitClick(); });
 		removeChild(split);
 		garr->addSplitBtn(split);
 	}
 	quit = new CButton(Point(399, 314), "IOK6432.DEF", CButton::tooltip(CGI->generaltexth->tcommands[8], ""), [&](){ close(); }, SDLK_RETURN);
 
 	std::string titleText;
-	if (down->tempOwner == up->tempOwner)
+	if(down->tempOwner == up->tempOwner)
 		titleText = CGI->generaltexth->allTexts[709];
 	else
 	{

+ 28 - 32
client/widgets/CGarrisonInt.h

@@ -24,15 +24,17 @@ class CLabel;
 class CGarrisonSlot : public CIntObject
 {
 	SlotID ID; //for identification
-	CGarrisonInt *owner;
-	const CStackInstance *myStack; //nullptr if slot is empty
-	const CCreature *creature;
+	CGarrisonInt * owner;
+	const CStackInstance * myStack; //nullptr if slot is empty
+	const CCreature * creature;
 
 	/// Type of Garrison for slot (up or down)
 	enum EGarrisonType
 	{
-		UP=0,  ///< 0 - up garrison (Garrisoned)
-		DOWN,  ///< 1 - down garrison (Visiting)
+		UP=0,
+		///< 0 - up garrison (Garrisoned)
+		DOWN,
+		///< 1 - down garrison (Visiting)
 	} upg; ///< Flag indicating if it is the up or down garrison
 
 	CAnimImage * creatureImage;
@@ -45,24 +47,25 @@ class CGarrisonSlot : public CIntObject
 	bool mustForceReselection() const;
 
 	void setHighlight(bool on);
+
 public:
-	virtual void hover (bool on) override; //call-in
+	virtual void hover(bool on) override; //call-in
 	const CArmedInstance * getObj() const;
 	bool our() const;
 	bool ally() const;
 	void clickRight(tribool down, bool previousState) override;
 	void clickLeft(tribool down, bool previousState) override;
 	void update();
-	CGarrisonSlot(CGarrisonInt *Owner, int x, int y, SlotID IID, EGarrisonType Upg=EGarrisonType::UP, const CStackInstance * Creature=nullptr);
+	CGarrisonSlot(CGarrisonInt * Owner, int x, int y, SlotID IID, EGarrisonType Upg = EGarrisonType::UP, const CStackInstance * Creature = nullptr);
 
 	friend class CGarrisonInt;
 };
 
 /// Class which manages slots of upper and lower garrison, splitting of units
-class CGarrisonInt :public CIntObject
+class CGarrisonInt : public CIntObject
 {
 	/// Chosen slot. Should be changed only via selectSlot.
-	CGarrisonSlot *highlighted;
+	CGarrisonSlot * highlighted;
 	bool inSplittingMode;
 
 public:
@@ -72,29 +75,29 @@ public:
 	void setSplittingMode(bool on);
 	bool getSplittingMode();
 
-	int interx;  ///< Space between slots
-	Point garOffset;  ///< Offset between garrisons (not used if only one hero)
-	std::vector<CButton *> splitButtons;  ///< May be empty if no buttons
+	int interx; ///< Space between slots
+	Point garOffset; ///< Offset between garrisons (not used if only one hero)
+	std::vector<CButton *> splitButtons; ///< May be empty if no buttons
 
 	SlotID p2; ///< TODO: comment me
 	bool pb,
-		 smallIcons,      ///< true - 32x32 imgs, false - 58x64
-		 removableUnits,  ///< player Can remove units from up
-		 twoRows,         ///< slots Will be placed in 2 rows
-		 owned[2];        ///< player Owns up or down army ([0] upper, [1] lower)
+	     smallIcons, ///< true - 32x32 imgs, false - 58x64
+	     removableUnits, ///< player Can remove units from up
+	     twoRows, ///< slots Will be placed in 2 rows
+	     owned[2]; ///< player Owns up or down army ([0] upper, [1] lower)
 
-	std::vector<CGarrisonSlot*> availableSlots;  ///< Slots of upper and lower garrison
+	std::vector<CGarrisonSlot *> availableSlots; ///< Slots of upper and lower garrison
 
-	const CArmedInstance *armedObjs[2];  ///< [0] is upper, [1] is down
+	const CArmedInstance * armedObjs[2]; ///< [0] is upper, [1] is down
 
-	void setArmy(const CArmedInstance *army, bool bottomGarrison);
+	void setArmy(const CArmedInstance * army, bool bottomGarrison);
 	void addSplitBtn(CButton * button);
 
 	void createSlots();
 	void recreateSlots();
 
-	void splitClick();  ///< handles click on split button
-	void splitStacks(int amountLeft, int amountRight);  ///< TODO: comment me
+	void splitClick(); ///< handles click on split button
+	void splitStacks(int amountLeft, int amountRight); ///< TODO: comment me
 
 	/// Constructor
 	/// @param x, y Position
@@ -105,27 +108,20 @@ public:
 	/// @param _removableUnits You can take units from top
 	/// @param smallImgs Units images size 64x58 or 32x32
 	/// @param _twoRows Display slots in 2 row (1st row = 4 slots, 2nd = 3 slots)
-	CGarrisonInt(int x, int y,
-	             int inx,
-	             const Point &garsOffset,
-	             SDL_Surface *pomsur, const Point &SurOffset,
-	             const CArmedInstance *s1, const CArmedInstance *s2=nullptr,
-	             bool _removableUnits = true,
-	             bool smallImgs = false,
-	             bool _twoRows=false);
+	CGarrisonInt(int x, int y, int inx, const Point & garsOffset, SDL_Surface * pomsur, const Point & SurOffset, const CArmedInstance * s1, const CArmedInstance * s2 = nullptr, bool _removableUnits = true, bool smallImgs = false, bool _twoRows = false);
 };
 
 class CGarrisonHolder
 {
 public:
 	CGarrisonHolder();
-	virtual void updateGarrisons()=0;
+	virtual void updateGarrisons() = 0;
 };
 
 class CWindowWithGarrison : public virtual CGarrisonHolder
 {
 public:
-	CGarrisonInt *garr;
+	CGarrisonInt * garr;
 	virtual void updateGarrisons() override;
 };
 
@@ -135,5 +131,5 @@ class CGarrisonWindow : public CWindowObject, public CWindowWithGarrison
 public:
 	CButton * quit;
 
-	CGarrisonWindow(const CArmedInstance *up, const CGHeroInstance *down, bool removableUnits);
+	CGarrisonWindow(const CArmedInstance * up, const CGHeroInstance * down, bool removableUnits);
 };

+ 81 - 98
client/widgets/Images.cpp

@@ -34,7 +34,7 @@
 #include "../../lib/CGeneralTextHandler.h" //for Unicode related stuff
 #include "../../lib/CRandomGenerator.h"
 
-CPicture::CPicture( SDL_Surface *BG, int x, int y, bool Free )
+CPicture::CPicture(SDL_Surface * BG, int x, int y, bool Free)
 {
 	init();
 	bg = BG;
@@ -45,7 +45,7 @@ CPicture::CPicture( SDL_Surface *BG, int x, int y, bool Free )
 	pos.h = BG->h;
 }
 
-CPicture::CPicture( const std::string &bmpname, int x, int y )
+CPicture::CPicture(const std::string & bmpname, int x, int y)
 {
 	init();
 	bg = BitmapHandler::loadBitmap(bmpname);
@@ -63,19 +63,19 @@ CPicture::CPicture( const std::string &bmpname, int x, int y )
 	}
 }
 
-CPicture::CPicture(const Rect &r, const SDL_Color &color, bool screenFormat)
+CPicture::CPicture(const Rect & r, const SDL_Color & color, bool screenFormat)
 {
 	init();
-	createSimpleRect(r, screenFormat, SDL_MapRGB(bg->format, color.r, color.g,color.b));
+	createSimpleRect(r, screenFormat, SDL_MapRGB(bg->format, color.r, color.g, color.b));
 }
 
-CPicture::CPicture(const Rect &r, ui32 color, bool screenFormat)
+CPicture::CPicture(const Rect & r, ui32 color, bool screenFormat)
 {
 	init();
 	createSimpleRect(r, screenFormat, color);
 }
 
-CPicture::CPicture(SDL_Surface * BG, const Rect &SrcRect, int x, int y, bool free)
+CPicture::CPicture(SDL_Surface * BG, const Rect & SrcRect, int x, int y, bool free)
 {
 	visible = true;
 	needRefresh = false;
@@ -88,10 +88,10 @@ CPicture::CPicture(SDL_Surface * BG, const Rect &SrcRect, int x, int y, bool fre
 	freeSurf = free;
 }
 
-void CPicture::setSurface(SDL_Surface *to)
+void CPicture::setSurface(SDL_Surface * to)
 {
 	bg = to;
-	if (srcRect)
+	if(srcRect)
 	{
 		pos.w = srcRect->w;
 		pos.h = srcRect->h;
@@ -119,7 +119,7 @@ void CPicture::init()
 
 void CPicture::show(SDL_Surface * to)
 {
-	if (visible && needRefresh)
+	if(visible && needRefresh)
 		showAll(to);
 }
 
@@ -143,15 +143,15 @@ void CPicture::showAll(SDL_Surface * to)
 
 void CPicture::convertToScreenBPP()
 {
-	SDL_Surface *hlp = bg;
-	bg = SDL_ConvertSurface(hlp,screen->format,0);
+	SDL_Surface * hlp = bg;
+	bg = SDL_ConvertSurface(hlp, screen->format, 0);
 	CSDL_Ext::setDefaultColorKey(bg);
 	SDL_FreeSurface(hlp);
 }
 
 void CPicture::setAlpha(int value)
 {
-	CSDL_Ext::setAlpha (bg, value);
+	CSDL_Ext::setAlpha(bg, value);
 }
 
 void CPicture::scaleTo(Point size)
@@ -165,7 +165,7 @@ void CPicture::scaleTo(Point size)
 	freeSurf = false;
 }
 
-void CPicture::createSimpleRect(const Rect &r, bool screenFormat, ui32 color)
+void CPicture::createSimpleRect(const Rect & r, bool screenFormat, ui32 color)
 {
 	pos += r;
 	pos.w = r.w;
@@ -192,9 +192,8 @@ void CPicture::colorize(PlayerColor player)
 	graphics->blueToPlayersAdv(bg, player);
 }
 
-CFilledTexture::CFilledTexture(std::string imageName, Rect position):
-    CIntObject(0, position.topLeft()),
-    texture(BitmapHandler::loadBitmap(imageName))
+CFilledTexture::CFilledTexture(std::string imageName, Rect position)
+	: CIntObject(0, position.topLeft()), texture(BitmapHandler::loadBitmap(imageName))
 {
 	pos.w = position.w;
 	pos.h = position.h;
@@ -205,17 +204,14 @@ CFilledTexture::~CFilledTexture()
 	SDL_FreeSurface(texture);
 }
 
-void CFilledTexture::showAll(SDL_Surface *to)
+void CFilledTexture::showAll(SDL_Surface * to)
 {
 	CSDL_Ext::CClipRectGuard guard(to, pos);
 	CSDL_Ext::fillTexture(to, texture);
 }
 
-CAnimImage::CAnimImage(const std::string & name, size_t Frame, size_t Group, int x, int y, ui8 Flags):
-	frame(Frame),
-	group(Group),
-	player(-1),
-	flags(Flags)
+CAnimImage::CAnimImage(const std::string & name, size_t Frame, size_t Group, int x, int y, ui8 Flags)
+	: frame(Frame), group(Group), player(-1), flags(Flags)
 {
 	pos.x += x;
 	pos.y += y;
@@ -223,12 +219,8 @@ CAnimImage::CAnimImage(const std::string & name, size_t Frame, size_t Group, int
 	init();
 }
 
-CAnimImage::CAnimImage(std::shared_ptr<CAnimation> Anim, size_t Frame, size_t Group, int x, int y, ui8 Flags):
-	anim(Anim),
-	frame(Frame),
-	group(Group),
-	player(-1),
-	flags(Flags)
+CAnimImage::CAnimImage(std::shared_ptr<CAnimation> Anim, size_t Frame, size_t Group, int x, int y, ui8 Flags)
+	: anim(Anim), frame(Frame), group(Group), player(-1), flags(Flags)
 {
 	pos.x += x;
 	pos.y += y;
@@ -244,11 +236,11 @@ void CAnimImage::init()
 {
 	visible = true;
 	anim->load(frame, group);
-	if (flags & CShowableAnim::BASE)
-		anim->load(0,group);
+	if(flags & CShowableAnim::BASE)
+		anim->load(0, group);
 
-	IImage *img = anim->getImage(frame, group);
-	if (img)
+	IImage * img = anim->getImage(frame, group);
+	if(img)
 	{
 		pos.w = img->width();
 		pos.h = img->height();
@@ -258,8 +250,8 @@ void CAnimImage::init()
 CAnimImage::~CAnimImage()
 {
 	anim->unload(frame, group);
-	if (flags & CShowableAnim::BASE)
-		anim->unload(0,group);
+	if(flags & CShowableAnim::BASE)
+		anim->unload(0, group);
 }
 
 void CAnimImage::showAll(SDL_Surface * to)
@@ -267,30 +259,30 @@ void CAnimImage::showAll(SDL_Surface * to)
 	if(!visible)
 		return;
 
-	IImage *img;
+	IImage * img;
 
-	if ( flags & CShowableAnim::BASE && frame != 0)
-		if ((img = anim->getImage(0, group)))
+	if(flags & CShowableAnim::BASE && frame != 0)
+		if((img = anim->getImage(0, group)))
 			img->draw(to, pos.x, pos.y);
 
-	if ((img = anim->getImage(frame, group)))
+	if((img = anim->getImage(frame, group)))
 		img->draw(to, pos.x, pos.y);
 }
 
 void CAnimImage::setFrame(size_t Frame, size_t Group)
 {
-	if (frame == Frame && group==Group)
+	if(frame == Frame && group == Group)
 		return;
-	if (anim->size(Group) > Frame)
+	if(anim->size(Group) > Frame)
 	{
 		anim->load(Frame, Group);
 		anim->unload(frame, group);
 		frame = Frame;
 		group = Group;
-		IImage *img = anim->getImage(frame, group);
-		if (img)
+		IImage * img = anim->getImage(frame, group);
+		if(img)
 		{
-			if (flags & CShowableAnim::PLAYER_COLORED)
+			if(flags & CShowableAnim::PLAYER_COLORED)
 				img->playerColored(player);
 			pos.w = img->width();
 			pos.h = img->height();
@@ -305,29 +297,20 @@ void CAnimImage::playerColored(PlayerColor currPlayer)
 	player = currPlayer;
 	flags |= CShowableAnim::PLAYER_COLORED;
 	anim->getImage(frame, group)->playerColored(player);
-	if (flags & CShowableAnim::BASE)
-			anim->getImage(0, group)->playerColored(player);
-}
-
-CShowableAnim::CShowableAnim(int x, int y, std::string name, ui8 Flags, ui32 Delay, size_t Group):
-	anim(new CAnimation(name, Flags & USE_RLE)),
-	group(Group),
-	frame(0),
-	first(0),
-	frameDelay(Delay),
-	value(0),
-	flags(Flags),
-	xOffset(0),
-	yOffset(0),
-	alpha(255)
+	if(flags & CShowableAnim::BASE)
+		anim->getImage(0, group)->playerColored(player);
+}
+
+CShowableAnim::CShowableAnim(int x, int y, std::string name, ui8 Flags, ui32 Delay, size_t Group)
+	: anim(new CAnimation(name, Flags & USE_RLE)), group(Group), frame(0), first(0), frameDelay(Delay), value(0), flags(Flags), xOffset(0), yOffset(0), alpha(255)
 {
 	anim->loadGroup(group);
 	last = anim->size(group);
 
 	pos.w = anim->getImage(0, group)->width();
 	pos.h = anim->getImage(0, group)->height();
-	pos.x+= x;
-	pos.y+= y;
+	pos.x += x;
+	pos.y += y;
 }
 
 CShowableAnim::~CShowableAnim()
@@ -345,10 +328,10 @@ bool CShowableAnim::set(size_t Group, size_t from, size_t to)
 {
 	size_t max = anim->size(Group);
 
-	if (to < max)
+	if(to < max)
 		max = to;
 
-	if (max < from || max == 0)
+	if(max < from || max == 0)
 		return false;
 
 	anim->load(Group);
@@ -362,9 +345,9 @@ bool CShowableAnim::set(size_t Group, size_t from, size_t to)
 
 bool CShowableAnim::set(size_t Group)
 {
-	if (anim->size(Group)== 0)
+	if(anim->size(Group) == 0)
 		return false;
-	if (group != Group)
+	if(group != Group)
 	{
 		anim->loadGroup(Group);
 		anim->unloadGroup(group);
@@ -381,7 +364,7 @@ void CShowableAnim::reset()
 	value = 0;
 	frame = first;
 
-	if (callback)
+	if(callback)
 		callback();
 }
 
@@ -395,54 +378,54 @@ void CShowableAnim::clipRect(int posX, int posY, int width, int height)
 
 void CShowableAnim::show(SDL_Surface * to)
 {
-	if ( flags & BASE )// && frame != first) // FIXME: results in graphical glytch in Fortress, upgraded hydra's dwelling
+	if(flags & BASE) // && frame != first) // FIXME: results in graphical glytch in Fortress, upgraded hydra's dwelling
 		blitImage(first, group, to);
 	blitImage(frame, group, to);
 
-	if ((flags & PLAY_ONCE) && frame + 1 == last)
+	if((flags & PLAY_ONCE) && frame + 1 == last)
 		return;
 
-	if ( ++value == frameDelay )
+	if(++value == frameDelay)
 	{
 		value = 0;
-		if ( ++frame >= last)
+		if(++frame >= last)
 			reset();
 	}
 }
 
 void CShowableAnim::showAll(SDL_Surface * to)
 {
-	if ( flags & BASE )// && frame != first)
+	if(flags & BASE) // && frame != first)
 		blitImage(first, group, to);
 	blitImage(frame, group, to);
 }
 
-void CShowableAnim::blitImage(size_t frame, size_t group, SDL_Surface *to)
+void CShowableAnim::blitImage(size_t frame, size_t group, SDL_Surface * to)
 {
 	assert(to);
-	Rect src( xOffset, yOffset, pos.w, pos.h);
+	Rect src(xOffset, yOffset, pos.w, pos.h);
 	IImage * img = anim->getImage(frame, group);
-	if (img)
-		img->draw(to, pos.x-xOffset, pos.y-yOffset, &src, alpha);
+	if(img)
+		img->draw(to, pos.x - xOffset, pos.y - yOffset, &src, alpha);
 }
 
 void CShowableAnim::rotate(bool on, bool vertical)
 {
-	ui8 flag = vertical? VERTICAL_FLIP:HORIZONTAL_FLIP;
-	if (on)
+	ui8 flag = vertical ? VERTICAL_FLIP : HORIZONTAL_FLIP;
+	if(on)
 		flags |= flag;
 	else
 		flags &= ~flag;
 }
 
-CCreatureAnim::CCreatureAnim(int x, int y, std::string name, Rect picPos, ui8 flags, EAnimType type):
-	CShowableAnim(x,y,name,flags,4,type)
+CCreatureAnim::CCreatureAnim(int x, int y, std::string name, Rect picPos, ui8 flags, EAnimType type)
+	: CShowableAnim(x, y, name, flags, 4, type)
 {
 	xOffset = picPos.x;
 	yOffset = picPos.y;
-	if (picPos.w)
+	if(picPos.w)
 		pos.w = picPos.w;
-	if (picPos.h)
+	if(picPos.h)
 		pos.h = picPos.h;
 }
 
@@ -454,22 +437,22 @@ void CCreatureAnim::loopPreview(bool warMachine)
 	static const EAnimType machPreviewList[] = {HOLDING, MOVING, SHOOT_UP, SHOOT_FRONT, SHOOT_DOWN};
 	auto & previewList = warMachine ? machPreviewList : creaPreviewList;
 
-	for (auto & elem : previewList)
-		if (anim->size(elem))
+	for(auto & elem : previewList)
+		if(anim->size(elem))
 			available.push_back(elem);
 
 	size_t rnd = CRandomGenerator::getDefault().nextInt(available.size() * 2 - 1);
 
-	if (rnd >= available.size())
+	if(rnd >= available.size())
 	{
 		EAnimType type;
-		if ( anim->size(MOVING) == 0 )//no moving animation present
+		if(anim->size(MOVING) == 0) //no moving animation present
 			type = HOLDING;
 		else
 			type = MOVING;
 
 		//display this anim for ~1 second (time is random, but it looks good)
-		for (size_t i=0; i< 12/anim->size(type) + 1; i++)
+		for(size_t i = 0; i < 12 / anim->size(type) + 1; i++)
 			addLast(type);
 	}
 	else
@@ -478,15 +461,15 @@ void CCreatureAnim::loopPreview(bool warMachine)
 
 void CCreatureAnim::addLast(EAnimType newType)
 {
-	if (type != MOVING && newType == MOVING)//starting moving - play init sequence
+	if(type != MOVING && newType == MOVING) //starting moving - play init sequence
 	{
-		queue.push( MOVE_START );
+		queue.push(MOVE_START);
 	}
-	else if (type == MOVING && newType != MOVING )//previous anim was moving - finish it
+	else if(type == MOVING && newType != MOVING) //previous anim was moving - finish it
 	{
-		queue.push( MOVE_END );
+		queue.push(MOVE_END);
 	}
-	if (newType == TURN_L || newType == TURN_R)
+	if(newType == TURN_L || newType == TURN_R)
 		queue.push(newType);
 
 	queue.push(newType);
@@ -495,25 +478,25 @@ void CCreatureAnim::addLast(EAnimType newType)
 void CCreatureAnim::reset()
 {
 	//if we are in the middle of rotation - set flag
-	if (type == TURN_L && !queue.empty() && queue.front() == TURN_L)
+	if(type == TURN_L && !queue.empty() && queue.front() == TURN_L)
 		rotate(true);
-	if (type == TURN_R && !queue.empty() && queue.front() == TURN_R)
+	if(type == TURN_R && !queue.empty() && queue.front() == TURN_R)
 		rotate(false);
 
-	while (!queue.empty())
+	while(!queue.empty())
 	{
 		EAnimType at = queue.front();
 		queue.pop();
-		if (set(at))
+		if(set(at))
 			return;
 	}
-	if  (callback)
+	if(callback)
 		callback();
-	while (!queue.empty())
+	while(!queue.empty())
 	{
 		EAnimType at = queue.front();
 		queue.pop();
-		if (set(at))
+		if(set(at))
 			return;
 	}
 	set(HOLDING);
@@ -526,7 +509,7 @@ void CCreatureAnim::startPreview(bool warMachine)
 
 void CCreatureAnim::clearAndSet(EAnimType type)
 {
-	while (!queue.empty())
+	while(!queue.empty())
 		queue.pop();
 	set(type);
 }

+ 44 - 34
client/widgets/Images.h

@@ -21,23 +21,24 @@ class CAnimation;
 // Image class
 class CPicture : public CIntObject
 {
-	void setSurface(SDL_Surface *to);
+	void setSurface(SDL_Surface * to);
+
 public:
 	SDL_Surface * bg;
 	Rect * srcRect; //if nullptr then whole surface will be used
 	bool freeSurf; //whether surface will be freed upon CPicture destruction
-	bool needRefresh;//Surface needs to be displayed each frame
+	bool needRefresh; //Surface needs to be displayed each frame
 	bool visible;
-	operator SDL_Surface*()
+	operator SDL_Surface *()
 	{
 		return bg;
 	}
 
 	CPicture(const Rect & r, const SDL_Color & color, bool screenFormat = false); //rect filled with given color
 	CPicture(const Rect & r, ui32 color, bool screenFormat = false); //rect filled with given color
-	CPicture(SDL_Surface * BG, int x = 0, int y=0, bool Free = true); //wrap existing SDL_Surface
-	CPicture(const std::string &bmpname, int x=0, int y=0);
-	CPicture(SDL_Surface *BG, const Rect &SrcRext, int x = 0, int y = 0, bool free = false); //wrap subrect of given surface
+	CPicture(SDL_Surface * BG, int x = 0, int y = 0, bool Free = true); //wrap existing SDL_Surface
+	CPicture(const std::string & bmpname, int x = 0, int y = 0);
+	CPicture(SDL_Surface * BG, const Rect & SrcRext, int x = 0, int y = 0, bool free = false); //wrap subrect of given surface
 	~CPicture();
 	void init();
 
@@ -46,7 +47,7 @@ public:
 	void setAlpha(int value);
 
 	void scaleTo(Point size);
-	void createSimpleRect(const Rect &r, bool screenFormat, ui32 color);
+	void createSimpleRect(const Rect & r, bool screenFormat, ui32 color);
 	void show(SDL_Surface * to) override;
 	void showAll(SDL_Surface * to) override;
 	void convertToScreenBPP();
@@ -62,11 +63,11 @@ class CFilledTexture : CIntObject
 public:
 	CFilledTexture(std::string imageName, Rect position);
 	~CFilledTexture();
-	void showAll(SDL_Surface *to) override;
+	void showAll(SDL_Surface * to) override;
 };
 
 /// Class for displaying one image from animation
-class CAnimImage: public CIntObject
+class CAnimImage : public CIntObject
 {
 private:
 	std::shared_ptr<CAnimation> anim;
@@ -81,15 +82,15 @@ private:
 public:
 	bool visible;
 
-	CAnimImage(const std::string & name, size_t Frame, size_t Group=0, int x=0, int y=0, ui8 Flags=0);
-	CAnimImage(std::shared_ptr<CAnimation> Anim, size_t Frame, size_t Group=0, int x=0, int y=0, ui8 Flags=0);
+	CAnimImage(const std::string & name, size_t Frame, size_t Group = 0, int x = 0, int y = 0, ui8 Flags = 0);
+	CAnimImage(std::shared_ptr<CAnimation> Anim, size_t Frame, size_t Group = 0, int x = 0, int y = 0, ui8 Flags = 0);
 	~CAnimImage();
 
 	//size of animation
 	size_t size();
 
 	//change displayed frame on this one
-	void setFrame(size_t Frame, size_t Group=0);
+	void setFrame(size_t Frame, size_t Group = 0);
 
 	//makes image player-colored
 	void playerColored(PlayerColor player);
@@ -98,33 +99,39 @@ public:
 };
 
 /// Base class for displaying animation, used as superclass for different animations
-class CShowableAnim: public CIntObject
+class CShowableAnim : public CIntObject
 {
 public:
 	enum EFlags
 	{
-		BASE=1,            //base frame will be blitted before current one
-		HORIZONTAL_FLIP=2, //TODO: will be displayed rotated
-		VERTICAL_FLIP=4,   //TODO: will be displayed rotated
-		USE_RLE=8,         //RLE-d version, support full alpha-channel for 8-bit images
-		PLAYER_COLORED=16, //TODO: all loaded images will be player-colored
-		PLAY_ONCE=32       //play animation only once and stop at last frame
+		BASE=1,
+		//base frame will be blitted before current one
+		HORIZONTAL_FLIP=2,
+		//TODO: will be displayed rotated
+		VERTICAL_FLIP=4,
+		//TODO: will be displayed rotated
+		USE_RLE=8,
+		//RLE-d version, support full alpha-channel for 8-bit images
+		PLAYER_COLORED=16,
+		//TODO: all loaded images will be player-colored
+		PLAY_ONCE=32 //play animation only once and stop at last frame
 	};
+
 protected:
 	CAnimation * anim;
 
-	size_t group, frame;//current frame
+	size_t group, frame; //current frame
 
 	size_t first, last; //animation range
 
 	//TODO: replace with time delay(needed for battles)
-	ui32 frameDelay;//delay in frames of each image
-	ui32 value;//how many times current frame was showed
+	ui32 frameDelay; //delay in frames of each image
+	ui32 value; //how many times current frame was showed
 
-	ui8 flags;//Flags from EFlags enum
+	ui8 flags; //Flags from EFlags enum
 
 	//blit image with optional rotation, fitting into rect, etc
-	void blitImage(size_t frame, size_t group, SDL_Surface *to);
+	void blitImage(size_t frame, size_t group, SDL_Surface * to);
 
 	//For clipping in rect, offsets of picture coordinates
 	int xOffset, yOffset;
@@ -138,15 +145,15 @@ public:
 	//Set per-surface alpha, 0 = transparent, 255 = opaque
 	void setAlpha(ui32 alphaValue);
 
-	CShowableAnim(int x, int y, std::string name, ui8 flags=0, ui32 Delay=4, size_t Group=0);
+	CShowableAnim(int x, int y, std::string name, ui8 flags = 0, ui32 Delay = 4, size_t Group = 0);
 	~CShowableAnim();
 
 	//set animation to group or part of group
 	bool set(size_t Group);
-	bool set(size_t Group, size_t from, size_t to=-1);
+	bool set(size_t Group, size_t from, size_t to = -1);
 
 	//set rotation flags
-	void rotate(bool on, bool vertical=false);
+	void rotate(bool on, bool vertical = false);
 
 	//move displayed part of picture (if picture is clipped to rect)
 	void clipRect(int posX, int posY, int width, int height);
@@ -160,16 +167,19 @@ public:
 };
 
 /// Creature-dependend animations like attacking, moving,...
-class CCreatureAnim: public CShowableAnim
+class CCreatureAnim : public CShowableAnim
 {
 public:
 
 	enum EHeroAnimType
 	{
 		HERO_HOLDING = 0,
-		HERO_IDLE = 1, // idling movement that happens from time to time
-		HERO_DEFEAT = 2, // played when army loses stack or on friendly fire
-		HERO_VICTORY = 3, // when enemy stack killed or huge damage is dealt
+		HERO_IDLE = 1,
+		// idling movement that happens from time to time
+		HERO_DEFEAT = 2,
+		// played when army loses stack or on friendly fire
+		HERO_VICTORY = 3,
+		// when enemy stack killed or huge damage is dealt
 		HERO_CAST_SPELL = 4 // spellcasting
 	};
 
@@ -183,7 +193,8 @@ public:
 		DEATH=5,
 		//DEATH2=6, //unused?
 		TURN_L=7,
-		TURN_R=8, //same
+		TURN_R=8,
+		//same
 		//TURN_L2=9, //identical to previous?
 		//TURN_R2=10,
 		ATTACK_UP=11,
@@ -220,7 +231,6 @@ public:
 	//clear queue and set animation to this sequence
 	void clearAndSet(EAnimType type);
 
-	CCreatureAnim(int x, int y, std::string name, Rect picPos,
-				  ui8 flags= USE_RLE, EAnimType = HOLDING );
+	CCreatureAnim(int x, int y, std::string name, Rect picPos, ui8 flags = USE_RLE, EAnimType = HOLDING);
 
 };

+ 79 - 78
client/widgets/MiscWidgets.cpp

@@ -31,11 +31,11 @@
 #include "../../lib/CModHandler.h"
 #include "../../lib/CGameState.h"
 
-void CHoverableArea::hover (bool on)
+void CHoverableArea::hover(bool on)
 {
-	if (on)
+	if(on)
 		GH.statusbar->setText(hoverText);
-	else if (GH.statusbar->getText()==hoverText)
+	else if(GH.statusbar->getText() == hoverText)
 		GH.statusbar->clear();
 }
 
@@ -57,7 +57,7 @@ void LRClickableAreaWText::clickLeft(tribool down, bool previousState)
 }
 void LRClickableAreaWText::clickRight(tribool down, bool previousState)
 {
-	if (!text.empty())
+	if(!text.empty())
 		adventureInt->handleRightClick(text, down);
 }
 
@@ -66,7 +66,7 @@ LRClickableAreaWText::LRClickableAreaWText()
 	init();
 }
 
-LRClickableAreaWText::LRClickableAreaWText(const Rect &Pos, const std::string &HoverText, const std::string &ClickText)
+LRClickableAreaWText::LRClickableAreaWText(const Rect & Pos, const std::string & HoverText, const std::string & ClickText)
 {
 	init();
 	pos = Pos + pos;
@@ -87,12 +87,12 @@ void LRClickableAreaWTextComp::clickLeft(tribool down, bool previousState)
 {
 	if((!down) && previousState)
 	{
-		std::vector<CComponent*> comp(1, createComponent());
+		std::vector<CComponent *> comp(1, createComponent());
 		LOCPLINT->showInfoDialog(text, comp);
 	}
 }
 
-LRClickableAreaWTextComp::LRClickableAreaWTextComp(const Rect &Pos, int BaseType)
+LRClickableAreaWTextComp::LRClickableAreaWTextComp(const Rect & Pos, int BaseType)
 	: LRClickableAreaWText(Pos), baseType(BaseType), bonusValue(-1), type(-1)
 {
 }
@@ -109,7 +109,7 @@ void LRClickableAreaWTextComp::clickRight(tribool down, bool previousState)
 {
 	if(down)
 	{
-		if(CComponent *comp = createComponent())
+		if(CComponent * comp = createComponent())
 		{
 			CRClickPopup::createAndPush(text, CInfoWindow::TCompsInfo(1, comp));
 			return;
@@ -119,15 +119,18 @@ void LRClickableAreaWTextComp::clickRight(tribool down, bool previousState)
 	LRClickableAreaWText::clickRight(down, previousState); //only if with-component variant not occurred
 }
 
-CHeroArea::CHeroArea(int x, int y, const CGHeroInstance * _hero):hero(_hero)
+CHeroArea::CHeroArea(int x, int y, const CGHeroInstance * _hero)
+	: hero(_hero)
 {
 	OBJ_CONSTRUCTION_CAPTURING_ALL;
 
 	addUsedEvents(LCLICK | RCLICK | HOVER);
-	pos.x += x;	pos.w = 58;
-	pos.y += y;	pos.h = 64;
+	pos.x += x;
+	pos.w = 58;
+	pos.y += y;
+	pos.h = 64;
 
-	if (hero)
+	if(hero)
 		new CAnimImage("PortraitsLarge", hero->portrait);
 }
 
@@ -145,7 +148,7 @@ void CHeroArea::clickRight(tribool down, bool previousState)
 
 void CHeroArea::hover(bool on)
 {
-	if (on && hero)
+	if(on && hero)
 		GH.statusbar->setText(hero->getObjectName());
 	else
 		GH.statusbar->clear();
@@ -156,9 +159,9 @@ void LRClickableAreaOpenTown::clickLeft(tribool down, bool previousState)
 	if(town && (!down) && previousState)
 	{
 		LOCPLINT->openTownWindow(town);
-		if ( type == 2 )
+		if(type == 2)
 			LOCPLINT->castleInt->builds->buildingClicked(BuildingID::VILLAGE_HALL);
-		else if ( type == 3 && town->fortLevel() )
+		else if(type == 3 && town->fortLevel())
 			LOCPLINT->castleInt->builds->buildingClicked(BuildingID::FORT);
 	}
 }
@@ -166,7 +169,7 @@ void LRClickableAreaOpenTown::clickLeft(tribool down, bool previousState)
 void LRClickableAreaOpenTown::clickRight(tribool down, bool previousState)
 {
 	if(town && (!down) && previousState)
-		LOCPLINT->openTownWindow(town);//TODO: popup?
+		LOCPLINT->openTownWindow(town); //TODO: popup?
 }
 
 LRClickableAreaOpenTown::LRClickableAreaOpenTown(const Rect & Pos, const CGTownInstance * Town)
@@ -180,12 +183,12 @@ void CMinorResDataBar::show(SDL_Surface * to)
 
 void CMinorResDataBar::showAll(SDL_Surface * to)
 {
-	blitAt(bg,pos.x,pos.y,to);
-	for (Res::ERes i=Res::WOOD; i<=Res::GOLD; vstd::advance(i, 1))
+	blitAt(bg, pos.x, pos.y, to);
+	for(Res::ERes i = Res::WOOD; i <= Res::GOLD; vstd::advance(i, 1))
 	{
 		std::string text = boost::lexical_cast<std::string>(LOCPLINT->cb->getResourceAmount(i));
 
-		graphics->fonts[FONT_SMALL]->renderTextCenter(to, text, Colors::WHITE, Point(pos.x + 50 + 76 * i, pos.y + pos.h/2));
+		graphics->fonts[FONT_SMALL]->renderTextCenter(to, text, Colors::WHITE, Point(pos.x + 50 + 76 * i, pos.y + pos.h / 2));
 	}
 	std::vector<std::string> temp;
 
@@ -193,17 +196,17 @@ void CMinorResDataBar::showAll(SDL_Surface * to)
 	temp.push_back(boost::lexical_cast<std::string>(LOCPLINT->cb->getDate(Date::WEEK)));
 	temp.push_back(boost::lexical_cast<std::string>(LOCPLINT->cb->getDate(Date::DAY_OF_WEEK)));
 
-	std::string datetext =  CGI->generaltexth->allTexts[62]+": %s, " + CGI->generaltexth->allTexts[63]
-							+ ": %s, " + CGI->generaltexth->allTexts[64] + ": %s";
+	std::string datetext = CGI->generaltexth->allTexts[62] + ": %s, " + CGI->generaltexth->allTexts[63]
+		+ ": %s, " + CGI->generaltexth->allTexts[64] + ": %s";
 
-	graphics->fonts[FONT_SMALL]->renderTextCenter(to, CSDL_Ext::processStr(datetext,temp), Colors::WHITE, Point(pos.x+545+(pos.w-545)/2,pos.y+pos.h/2));
+	graphics->fonts[FONT_SMALL]->renderTextCenter(to, CSDL_Ext::processStr(datetext, temp), Colors::WHITE, Point(pos.x + 545 + (pos.w - 545) / 2, pos.y + pos.h / 2));
 }
 
 CMinorResDataBar::CMinorResDataBar()
 {
 	bg = BitmapHandler::loadBitmap("KRESBAR.bmp");
 	CSDL_Ext::setDefaultColorKey(bg);
-	graphics->blueToPlayersAdv(bg,LOCPLINT->playerID);
+	graphics->blueToPlayersAdv(bg, LOCPLINT->playerID);
 	pos.x = 7;
 	pos.y = 575;
 	pos.w = bg->w;
@@ -215,20 +218,20 @@ CMinorResDataBar::~CMinorResDataBar()
 	SDL_FreeSurface(bg);
 }
 
-void CArmyTooltip::init(const InfoAboutArmy &army)
+void CArmyTooltip::init(const InfoAboutArmy & army)
 {
 	OBJ_CONSTRUCTION_CAPTURING_ALL;
 
 	new CLabel(66, 2, FONT_SMALL, TOPLEFT, Colors::WHITE, army.name);
 
 	std::vector<Point> slotsPos;
-	slotsPos.push_back(Point(36,73));
-	slotsPos.push_back(Point(72,73));
-	slotsPos.push_back(Point(108,73));
-	slotsPos.push_back(Point(18,122));
-	slotsPos.push_back(Point(54,122));
-	slotsPos.push_back(Point(90,122));
-	slotsPos.push_back(Point(126,122));
+	slotsPos.push_back(Point(36, 73));
+	slotsPos.push_back(Point(72, 73));
+	slotsPos.push_back(Point(108, 73));
+	slotsPos.push_back(Point(18, 122));
+	slotsPos.push_back(Point(54, 122));
+	slotsPos.push_back(Point(90, 122));
+	slotsPos.push_back(Point(126, 122));
 
 	for(auto & slot : army.army)
 	{
@@ -246,8 +249,8 @@ void CArmyTooltip::init(const InfoAboutArmy &army)
 		else
 		{
 			//if =0 - we have no information about stack size at all
-			if (slot.second.count)
-				subtitle = CGI->generaltexth->arraytxt[171 + 3*(slot.second.count)];
+			if(slot.second.count)
+				subtitle = CGI->generaltexth->arraytxt[171 + 3 * (slot.second.count)];
 		}
 
 		new CLabel(slotsPos[slot.first.getNum()].x + 17, slotsPos[slot.first.getNum()].y + 41, FONT_TINY, CENTER, Colors::WHITE, subtitle);
@@ -255,50 +258,50 @@ void CArmyTooltip::init(const InfoAboutArmy &army)
 
 }
 
-CArmyTooltip::CArmyTooltip(Point pos, const InfoAboutArmy &army):
-	CIntObject(0, pos)
+CArmyTooltip::CArmyTooltip(Point pos, const InfoAboutArmy & army)
+	: CIntObject(0, pos)
 {
 	init(army);
 }
 
-CArmyTooltip::CArmyTooltip(Point pos, const CArmedInstance * army):
-	CIntObject(0, pos)
+CArmyTooltip::CArmyTooltip(Point pos, const CArmedInstance * army)
+	: CIntObject(0, pos)
 {
 	init(InfoAboutArmy(army, true));
 }
 
-void CHeroTooltip::init(const InfoAboutHero &hero)
+void CHeroTooltip::init(const InfoAboutHero & hero)
 {
 	OBJ_CONSTRUCTION_CAPTURING_ALL;
 	new CAnimImage("PortraitsLarge", hero.portrait, 0, 3, 2);
 
 	if(hero.details)
 	{
-		for (size_t i = 0; i < hero.details->primskills.size(); i++)
+		for(size_t i = 0; i < hero.details->primskills.size(); i++)
 			new CLabel(75 + 28 * i, 58, FONT_SMALL, CENTER, Colors::WHITE,
-					   boost::lexical_cast<std::string>(hero.details->primskills[i]));
+				   boost::lexical_cast<std::string>(hero.details->primskills[i]));
 
 		new CLabel(158, 98, FONT_TINY, CENTER, Colors::WHITE,
-				   boost::lexical_cast<std::string>(hero.details->mana));
+			   boost::lexical_cast<std::string>(hero.details->mana));
 
 		new CAnimImage("IMRL22", hero.details->morale + 3, 0, 5, 74);
 		new CAnimImage("ILCK22", hero.details->luck + 3, 0, 5, 91);
 	}
 }
 
-CHeroTooltip::CHeroTooltip(Point pos, const InfoAboutHero &hero):
-	CArmyTooltip(pos, hero)
+CHeroTooltip::CHeroTooltip(Point pos, const InfoAboutHero & hero)
+	: CArmyTooltip(pos, hero)
 {
 	init(hero);
 }
 
-CHeroTooltip::CHeroTooltip(Point pos, const CGHeroInstance * hero):
-	CArmyTooltip(pos, InfoAboutHero(hero, InfoAboutHero::EInfoLevel::DETAILED))
+CHeroTooltip::CHeroTooltip(Point pos, const CGHeroInstance * hero)
+	: CArmyTooltip(pos, InfoAboutHero(hero, InfoAboutHero::EInfoLevel::DETAILED))
 {
 	init(InfoAboutHero(hero, InfoAboutHero::EInfoLevel::DETAILED));
 }
 
-void CTownTooltip::init(const InfoAboutTown &town)
+void CTownTooltip::init(const InfoAboutTown & town)
 {
 	OBJ_CONSTRUCTION_CAPTURING_ALL;
 
@@ -317,19 +320,19 @@ void CTownTooltip::init(const InfoAboutTown &town)
 	{
 		new CAnimImage("ITMTLS", town.details->hallLevel, 0, 67, 31);
 
-		if (town.details->goldIncome)
+		if(town.details->goldIncome)
 			new CLabel(157, 58, FONT_TINY, CENTER, Colors::WHITE,
-					   boost::lexical_cast<std::string>(town.details->goldIncome));
+				   boost::lexical_cast<std::string>(town.details->goldIncome));
 
 		if(town.details->garrisonedHero) //garrisoned hero icon
 			new CPicture("TOWNQKGH", 149, 76);
 
-		if(town.details->customRes)//silo is built
+		if(town.details->customRes) //silo is built
 		{
-			if (town.tType->primaryRes == Res::WOOD_AND_ORE )// wood & ore
+			if(town.tType->primaryRes == Res::WOOD_AND_ORE) // wood & ore
 			{
 				new CAnimImage("SMALRES", Res::WOOD, 0, 7, 75);
-				new CAnimImage("SMALRES", Res::ORE , 0, 7, 88);
+				new CAnimImage("SMALRES", Res::ORE, 0, 7, 88);
 			}
 			else
 				new CAnimImage("SMALRES", town.tType->primaryRes, 0, 7, 81);
@@ -337,20 +340,20 @@ void CTownTooltip::init(const InfoAboutTown &town)
 	}
 }
 
-CTownTooltip::CTownTooltip(Point pos, const InfoAboutTown &town):
-	CArmyTooltip(pos, town)
+CTownTooltip::CTownTooltip(Point pos, const InfoAboutTown & town)
+	: CArmyTooltip(pos, town)
 {
 	init(town);
 }
 
-CTownTooltip::CTownTooltip(Point pos, const CGTownInstance * town):
-	CArmyTooltip(pos, InfoAboutTown(town, true))
+CTownTooltip::CTownTooltip(Point pos, const CGTownInstance * town)
+	: CArmyTooltip(pos, InfoAboutTown(town, true))
 {
 	init(InfoAboutTown(town, true));
 }
 
 
-void MoraleLuckBox::set(const IBonusBearer *node)
+void MoraleLuckBox::set(const IBonusBearer * node)
 {
 	OBJ_CONSTRUCTION_CAPTURING_ALL;
 	const int textId[] = {62, 88}; //eg %s \n\n\n {Current Luck Modifiers:}
@@ -359,10 +362,10 @@ void MoraleLuckBox::set(const IBonusBearer *node)
 	const int componentType[] = {CComponent::luck, CComponent::morale};
 	const int hoverTextBase[] = {7, 4};
 	const Bonus::BonusType bonusType[] = {Bonus::LUCK, Bonus::MORALE};
-	int (IBonusBearer::*getValue[])() const = {&IBonusBearer::LuckVal, &IBonusBearer::MoraleVal};
+	int (IBonusBearer::* getValue[])() const = {&IBonusBearer::LuckVal, &IBonusBearer::MoraleVal};
 	TBonusListPtr modifierList(new BonusList());
 
-	if (node)
+	if(node)
 	{
 		modifierList = node->getBonuses(Selector::type(bonusType[morale]));
 		bonusValue = (node->*getValue[morale])();
@@ -370,15 +373,15 @@ void MoraleLuckBox::set(const IBonusBearer *node)
 	else
 		bonusValue = 0;
 
-	int mrlt = (bonusValue>0)-(bonusValue<0); //signum: -1 - bad luck / morale, 0 - neutral, 1 - good
+	int mrlt = (bonusValue > 0) - (bonusValue < 0); //signum: -1 - bad luck / morale, 0 - neutral, 1 - good
 	hoverText = CGI->generaltexth->heroscrn[hoverTextBase[morale] - mrlt];
 	baseType = componentType[morale];
 	text = CGI->generaltexth->arraytxt[textId[morale]];
-	boost::algorithm::replace_first(text,"%s",CGI->generaltexth->arraytxt[neutralDescr[morale]-mrlt]);
+	boost::algorithm::replace_first(text, "%s", CGI->generaltexth->arraytxt[neutralDescr[morale] - mrlt]);
 
-	if (morale && node && (node->hasBonusOfType(Bonus::UNDEAD)
-			|| node->hasBonusOfType(Bonus::BLOCK_MORALE)
-			|| node->hasBonusOfType(Bonus::NON_LIVING)))
+	if(morale && node && (node->hasBonusOfType(Bonus::UNDEAD)
+			      || node->hasBonusOfType(Bonus::BLOCK_MORALE)
+			      || node->hasBonusOfType(Bonus::NON_LIVING)))
 	{
 		text += CGI->generaltexth->arraytxt[113]; //unaffected by morale
 		bonusValue = 0;
@@ -390,10 +393,10 @@ void MoraleLuckBox::set(const IBonusBearer *node)
 		bonusValue = 0;
 	}
 	else if(modifierList->empty())
-		text += CGI->generaltexth->arraytxt[noneTxtId];//no modifiers
+		text += CGI->generaltexth->arraytxt[noneTxtId]; //no modifiers
 	else
 	{
-		for(auto& elem : *modifierList)
+		for(auto & elem : *modifierList)
 		{
 			if(elem->val != 0)
 				//no bonuses with value 0
@@ -402,30 +405,28 @@ void MoraleLuckBox::set(const IBonusBearer *node)
 	}
 
 	std::string imageName;
-	if (small)
-		imageName = morale ? "IMRL30": "ILCK30";
+	if(small)
+		imageName = morale ? "IMRL30" : "ILCK30";
 	else
 		imageName = morale ? "IMRL42" : "ILCK42";
 
 	delete image;
 	image = new CAnimImage(imageName, bonusValue + 3);
-	image->moveBy(Point(pos.w/2 - image->pos.w/2, pos.h/2 - image->pos.h/2));//center icon
+	image->moveBy(Point(pos.w / 2 - image->pos.w / 2, pos.h / 2 - image->pos.h / 2)); //center icon
 }
 
-MoraleLuckBox::MoraleLuckBox(bool Morale, const Rect &r, bool Small):
-	image(nullptr),
-	morale(Morale),
-	small(Small)
+MoraleLuckBox::MoraleLuckBox(bool Morale, const Rect & r, bool Small)
+	: image(nullptr), morale(Morale), small(Small)
 {
 	bonusValue = 0;
 	pos = r + pos;
 }
 
-CCreaturePic::CCreaturePic(int x, int y, const CCreature *cre, bool Big, bool Animated)
+CCreaturePic::CCreaturePic(int x, int y, const CCreature * cre, bool Big, bool Animated)
 {
 	OBJ_CONSTRUCTION_CAPTURING_ALL;
-	pos.x+=x;
-	pos.y+=y;
+	pos.x += x;
+	pos.y += y;
 
 	TFaction faction = cre->faction;
 
@@ -436,7 +437,7 @@ CCreaturePic::CCreaturePic(int x, int y, const CCreature *cre, bool Big, bool An
 	else
 		bg = new CPicture(CGI->townh->factions[faction]->creatureBg120);
 	anim = new CCreatureAnim(0, 0, cre->animDefName, Rect());
-	anim->clipRect(cre->isDoubleWide()?170:150, 155, bg->pos.w, bg->pos.h);
+	anim->clipRect(cre->isDoubleWide() ? 170 : 150, 155, bg->pos.w, bg->pos.h);
 	anim->startPreview(cre->hasBonusOfType(Bonus::SIEGE_WEAPON));
 
 	amount = new CLabel(bg->pos.w, bg->pos.h, FONT_MEDIUM, BOTTOMRIGHT, Colors::WHITE);
@@ -445,7 +446,7 @@ CCreaturePic::CCreaturePic(int x, int y, const CCreature *cre, bool Big, bool An
 	pos.h = bg->pos.h;
 }
 
-void CCreaturePic::show(SDL_Surface *to)
+void CCreaturePic::show(SDL_Surface * to)
 {
 	// redraw everything in a proper order
 	bg->showAll(to);
@@ -455,7 +456,7 @@ void CCreaturePic::show(SDL_Surface *to)
 
 void CCreaturePic::setAmount(int newAmount)
 {
-	if (newAmount != 0)
+	if(newAmount != 0)
 		amount->setText(boost::lexical_cast<std::string>(newAmount));
 	else
 		amount->setText("");

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