Browse Source

Merge remote-tracking branch 'upstream/develop' into interface-builder

# Conflicts:
#	client/lobby/RandomMapTab.cpp
nordsoft 3 years ago
parent
commit
2fe951f819
93 changed files with 8116 additions and 6623 deletions
  1. 6 2
      CMakeLists.txt
  2. 6 6
      Global.h
  3. 21 1
      client/CBitmapHandler.cpp
  4. 28 8
      client/CMakeLists.txt
  5. 36 58
      client/CPlayerInterface.cpp
  6. 2 3
      client/CPlayerInterface.h
  7. 3 3
      client/Client.cpp
  8. 2 2
      client/CreatureCostBox.cpp
  9. 0 1
      client/Graphics.cpp
  10. 1 1
      client/Graphics.h
  11. 1 1
      client/NetPacksClient.cpp
  12. 775 0
      client/battle/BattleActionsController.cpp
  13. 96 0
      client/battle/BattleActionsController.h
  14. 1222 0
      client/battle/BattleAnimationClasses.cpp
  15. 350 0
      client/battle/BattleAnimationClasses.h
  16. 328 0
      client/battle/BattleControlPanel.cpp
  17. 76 0
      client/battle/BattleControlPanel.h
  18. 140 0
      client/battle/BattleEffectsController.cpp
  19. 84 0
      client/battle/BattleEffectsController.h
  20. 634 0
      client/battle/BattleFieldController.cpp
  21. 91 0
      client/battle/BattleFieldController.h
  22. 964 0
      client/battle/BattleInterface.cpp
  23. 209 0
      client/battle/BattleInterface.h
  24. 171 231
      client/battle/BattleInterfaceClasses.cpp
  25. 47 38
      client/battle/BattleInterfaceClasses.h
  26. 190 0
      client/battle/BattleObstacleController.cpp
  27. 58 0
      client/battle/BattleObstacleController.h
  28. 373 0
      client/battle/BattleProjectileController.cpp
  29. 118 0
      client/battle/BattleProjectileController.h
  30. 71 0
      client/battle/BattleRenderer.cpp
  31. 54 0
      client/battle/BattleRenderer.h
  32. 368 0
      client/battle/BattleSiegeController.cpp
  33. 110 0
      client/battle/BattleSiegeController.h
  34. 589 0
      client/battle/BattleStacksController.cpp
  35. 121 0
      client/battle/BattleStacksController.h
  36. 0 1229
      client/battle/CBattleAnimations.cpp
  37. 0 262
      client/battle/CBattleAnimations.h
  38. 0 3806
      client/battle/CBattleInterface.cpp
  39. 0 414
      client/battle/CBattleInterface.h
  40. 50 31
      client/battle/CreatureAnimation.cpp
  41. 45 25
      client/battle/CreatureAnimation.h
  42. 24 10
      client/gui/CAnimation.cpp
  43. 11 4
      client/gui/CAnimation.h
  44. 1 1
      client/gui/CGuiHandler.cpp
  45. 2 2
      client/gui/CGuiHandler.h
  46. 3 0
      client/gui/CIntObject.cpp
  47. 22 2
      client/gui/CIntObject.h
  48. 84 0
      client/gui/Canvas.cpp
  49. 55 0
      client/gui/Canvas.h
  50. 2 0
      client/gui/Geometries.h
  51. 10 34
      client/gui/SDL_Extensions.cpp
  52. 39 20
      client/gui/SDL_Extensions.h
  53. 8 9
      client/lobby/CBonusSelection.cpp
  54. 22 23
      client/lobby/CSelectionBase.cpp
  55. 24 25
      client/lobby/OptionsTab.cpp
  56. 6 7
      client/lobby/SelectionTab.cpp
  57. 1 2
      client/mainmenu/CCampaignScreen.cpp
  58. 12 12
      client/mainmenu/CMainMenu.cpp
  59. 1 0
      client/mainmenu/CMainMenu.h
  60. 1 1
      client/mainmenu/CPrologEpilogVideo.cpp
  61. 1 1
      client/mainmenu/CreditsScreen.cpp
  62. 15 49
      client/widgets/AdventureMapClasses.cpp
  63. 8 24
      client/widgets/Buttons.cpp
  64. 2 2
      client/widgets/CComponent.cpp
  65. 2 2
      client/widgets/CGarrisonInt.cpp
  66. 2 2
      client/widgets/Images.cpp
  67. 2 1
      client/widgets/Images.h
  68. 10 11
      client/widgets/MiscWidgets.cpp
  69. 62 31
      client/widgets/TextControls.cpp
  70. 22 15
      client/widgets/TextControls.h
  71. 5 5
      client/windows/CAdvmapInterface.cpp
  72. 38 38
      client/windows/CCastleInterface.cpp
  73. 6 6
      client/windows/CCreatureWindow.cpp
  74. 15 16
      client/windows/CHeroWindow.cpp
  75. 17 17
      client/windows/CKingdomInterface.cpp
  76. 3 4
      client/windows/CQuestLog.cpp
  77. 2 2
      client/windows/CQuestLog.h
  78. 5 5
      client/windows/CSpellWindow.cpp
  79. 21 21
      client/windows/CTradeWindow.cpp
  80. 3 3
      client/windows/CWindowObject.cpp
  81. 2 2
      client/windows/CreaturePurchaseCard.cpp
  82. 64 65
      client/windows/GUIClasses.cpp
  83. 9 10
      client/windows/InfoWindows.cpp
  84. 2 2
      client/windows/InfoWindows.h
  85. 1 1
      config/factions/necropolis.json
  86. 1 1
      config/spells/ability.json
  87. 2 2
      config/spells/other.json
  88. 9 0
      lib/battle/BattleHex.h
  89. 3 3
      lib/battle/BattleInfo.cpp
  90. 2 0
      lib/battle/CObstacleInstance.cpp
  91. 6 6
      lib/battle/CObstacleInstance.h
  92. 1 1
      lib/spells/CSpellHandler.cpp
  93. 5 1
      lib/spells/effects/RemoveObstacle.cpp

+ 6 - 2
CMakeLists.txt

@@ -243,13 +243,17 @@ endif(MINGW OR MSVC)
 
 if(CMAKE_COMPILER_IS_GNUCXX OR NOT WIN32) #so far all *nix compilers support such parameters
 	set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -Wpointer-arith -Wuninitialized")
+	if (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 10.0 OR CMAKE_CXX_COMPILER_ID STREQUAL "Clang" )
+		set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wmismatched-tags")
+	endif()
+
 	set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-strict-aliasing -Wno-switch -Wno-sign-compare -Wno-unused-local-typedefs")
 	set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unused-parameter -Wno-overloaded-virtual -Wno-type-limits -Wno-unknown-pragmas")
 	set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-reorder")
 	set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-varargs") # fuzzylite - Operation.h
 
-	if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang")
-		set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-mismatched-tags -Wno-unknown-warning-option -Wno-missing-braces")
+	if(CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
+		set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unknown-warning-option")
 	endif()
 
 	if(UNIX)

+ 6 - 6
Global.h

@@ -543,6 +543,12 @@ namespace vstd
 		return *itr;
 	}
 
+	template <typename Container, typename Item>
+	void erase(Container &c, const Item &item)
+	{
+		c.erase(boost::remove(c, item), c.end());
+	}
+
 	template<typename Range, typename Predicate>
 	void erase_if(Range &vec, Predicate pred)
 	{
@@ -704,12 +710,6 @@ namespace vstd
 		return false;
 	}
 
-	template <typename Container, typename Pred>
-	void erase(Container &c, Pred pred)
-	{
-		c.erase(boost::remove_if(c, pred), c.end());
-	}
-
 	template<typename T>
 	void removeDuplicates(std::vector<T> &vec)
 	{

+ 21 - 1
client/CBitmapHandler.cpp

@@ -161,7 +161,26 @@ 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)
+	// 4) special case - there are 2 .bmp images that have semi-transparency (CCELLGRD.BMP & CCELLSHD.BMP)
+	if (ret->format->palette &&
+		ret->format->palette->colors[0].r == 255 &&
+		ret->format->palette->colors[0].g ==   0 &&
+		ret->format->palette->colors[0].b == 255 )
+	{
+		static SDL_Color shadow[3] =
+		{
+			{   0,   0,   0,   0},// 100% - transparency
+			{   0,   0,   0,  32},//  75% - shadow border,
+			{   0,   0,   0, 128},//  50% - shadow body
+		};
+
+		CSDL_Ext::setColorKey(ret, ret->format->palette->colors[0]);
+
+		ret->format->palette->colors[0] = shadow[0];
+		ret->format->palette->colors[1] = shadow[1];
+		ret->format->palette->colors[4] = shadow[2];
+	}
+	else if (ret->format->palette)
 	{
 		CSDL_Ext::setDefaultColorKeyPresize(ret);
 	}
@@ -173,6 +192,7 @@ SDL_Surface * BitmapHandler::loadBitmapFromDir(std::string path, std::string fna
 	{
 		CSDL_Ext::setDefaultColorKey(ret);
 	}
+
 	return ret;
 }
 

+ 28 - 8
client/CMakeLists.txt

@@ -2,12 +2,22 @@ set(client_SRCS
 		StdInc.cpp
 		../CCallback.cpp
 
-		battle/CBattleAnimations.cpp
-		battle/CBattleInterfaceClasses.cpp
-		battle/CBattleInterface.cpp
-		battle/CCreatureAnimation.cpp
+		battle/BattleActionsController.cpp
+		battle/BattleAnimationClasses.cpp
+		battle/BattleControlPanel.cpp
+		battle/BattleEffectsController.cpp
+		battle/BattleFieldController.cpp
+		battle/BattleInterfaceClasses.cpp
+		battle/BattleInterface.cpp
+		battle/BattleObstacleController.cpp
+		battle/BattleProjectileController.cpp
+		battle/BattleRenderer.cpp
+		battle/BattleSiegeController.cpp
+		battle/BattleStacksController.cpp
+		battle/CreatureAnimation.cpp
 
 		gui/CAnimation.cpp
+		gui/Canvas.cpp
 		gui/CCursorHandler.cpp
 		gui/CGuiHandler.cpp
 		gui/CIntObject.cpp
@@ -76,12 +86,22 @@ set(client_SRCS
 set(client_HEADERS
 		StdInc.h
 
-		battle/CBattleAnimations.h
-		battle/CBattleInterfaceClasses.h
-		battle/CBattleInterface.h
-		battle/CCreatureAnimation.h
+		battle/BattleActionsController.h
+		battle/BattleAnimationClasses.h
+		battle/BattleControlPanel.h
+		battle/BattleEffectsController.h
+		battle/BattleFieldController.h
+		battle/BattleInterfaceClasses.h
+		battle/BattleInterface.h
+		battle/BattleObstacleController.h
+		battle/BattleProjectileController.h
+		battle/BattleRenderer.h
+		battle/BattleSiegeController.h
+		battle/BattleStacksController.h
+		battle/CreatureAnimation.h
 
 		gui/CAnimation.h
+		gui/Canvas.h
 		gui/CCursorHandler.h
 		gui/CGuiHandler.h
 		gui/CIntObject.h

+ 36 - 58
client/CPlayerInterface.cpp

@@ -12,8 +12,11 @@
 #include <vcmi/Artifact.h>
 
 #include "windows/CAdvmapInterface.h"
-#include "battle/CBattleInterface.h"
-#include "battle/CBattleInterfaceClasses.h"
+#include "battle/BattleInterface.h"
+#include "battle/BattleEffectsController.h"
+#include "battle/BattleFieldController.h"
+#include "battle/BattleInterfaceClasses.h"
+#include "battle/BattleControlPanel.h"
 #include "../CCallback.h"
 #include "windows/CCastleInterface.h"
 #include "gui/CCursorHandler.h"
@@ -29,7 +32,6 @@
 #include "windows/CTradeWindow.h"
 #include "windows/CSpellWindow.h"
 #include "../lib/CConfigHandler.h"
-#include "battle/CCreatureAnimation.h"
 #include "Graphics.h"
 #include "windows/GUIClasses.h"
 #include "../lib/CArtHandler.h"
@@ -55,6 +57,7 @@
 #include "../lib/CPlayerState.h"
 #include "../lib/GameConstants.h"
 #include "gui/CGuiHandler.h"
+#include "gui/CAnimation.h"
 #include "windows/InfoWindows.h"
 #include "../lib/UnlockGuard.h"
 #include "../lib/CPathfinder.h"
@@ -90,7 +93,7 @@ boost::recursive_mutex * CPlayerInterface::pim = new boost::recursive_mutex;
 
 CPlayerInterface * LOCPLINT;
 
-CBattleInterface * CPlayerInterface::battleInt;
+BattleInterface * CPlayerInterface::battleInt;
 
 enum  EMoveState {STOP_MOVE, WAITING_MOVE, CONTINUE_MOVE, DURING_MOVE};
 CondSh<EMoveState> stillMoveHero(STOP_MOVE); //used during hero movement
@@ -715,34 +718,14 @@ void CPlayerInterface::battleUnitsChanged(const std::vector<UnitChanges> & units
 		{
 		case UnitChanges::EOperation::RESET_STATE:
 			{
-				const battle::Unit * unit = cb->battleGetUnitByID(info.id);
+				const CStack * stack = cb->battleGetStackByID(info.id );
 
-				if(!unit)
+				if(!stack)
 				{
 					logGlobal->error("Invalid unit ID %d", info.id);
 					continue;
 				}
-
-				auto iter = battleInt->creAnims.find(info.id);
-
-				if(iter == battleInt->creAnims.end())
-				{
-					logGlobal->error("Unit %d have no animation", info.id);
-					continue;
-				}
-
-				auto animation = iter->second;
-
-				if(unit->alive() && animation->isDead())
-					animation->setType(CCreatureAnim::HOLDING);
-
-				if (unit->isClone())
-				{
-					std::unique_ptr<ColorShifterDeepBlue> shifter(new ColorShifterDeepBlue());
-					animation->shiftColor(shifter.get());
-				}
-
-				//TODO: handle more cases
+				battleInt->stackReset(stack);
 			}
 			break;
 		case UnitChanges::EOperation::REMOVE:
@@ -756,7 +739,7 @@ void CPlayerInterface::battleUnitsChanged(const std::vector<UnitChanges> & units
 					logGlobal->error("Invalid unit ID %d", info.id);
 					continue;
 				}
-				battleInt->unitAdded(unit);
+				battleInt->stackAdded(unit);
 			}
 			break;
 		default:
@@ -765,7 +748,7 @@ void CPlayerInterface::battleUnitsChanged(const std::vector<UnitChanges> & units
 		}
 	}
 
-	battleInt->displayCustomEffects(customEffects);
+	battleInt->effectsController->displayCustomEffects(customEffects);
 }
 
 void CPlayerInterface::battleObstaclesChanged(const std::vector<ObstacleChanges> & obstacles)
@@ -773,7 +756,7 @@ void CPlayerInterface::battleObstaclesChanged(const std::vector<ObstacleChanges>
 	EVENT_HANDLER_CALLED_BY_CLIENT;
 	BATTLE_EVENT_POSSIBLE_RETURN;
 
-	bool needUpdate = false;
+	std::vector<std::shared_ptr<const CObstacleInstance>> newObstacles;
 
 	for(auto & change : obstacles)
 	{
@@ -781,19 +764,16 @@ void CPlayerInterface::battleObstaclesChanged(const std::vector<ObstacleChanges>
 		{
 			auto instance = cb->battleGetObstacleByID(change.id);
 			if(instance)
-				battleInt->obstaclePlaced(*instance);
+				newObstacles.push_back(instance);
 			else
 				logNetwork->error("Invalid obstacle instance %d", change.id);
 		}
-		else
-		{
-			needUpdate = true;
-		}
 	}
 
-	if(needUpdate)
-		//update accessible hexes
-		battleInt->redrawBackgroundWithHexes(battleInt->activeStack);
+	if (!newObstacles.empty())
+		battleInt->obstaclePlaced(newObstacles);
+
+	battleInt->fieldController->redrawBackgroundWithHexes();
 }
 
 void CPlayerInterface::battleCatapultAttacked(const CatapultAttack & ca)
@@ -858,17 +838,17 @@ BattleAction CPlayerInterface::activeStack(const CStack * stack) //called when i
 		autofightingAI.reset();
 	}
 
-	CBattleInterface *b = battleInt;
+	BattleInterface *b = battleInt;
 
 	if(!b)
 	{
 		return BattleAction::makeDefend(stack); // probably battle is finished already
 	}
 
-	if(CBattleInterface::givenCommand.get())
+	if(BattleInterface::givenCommand.get())
 	{
 		logGlobal->error("Command buffer must be clean! (we don't want to use old command)");
-		vstd::clear_pointer(CBattleInterface::givenCommand.data);
+		vstd::clear_pointer(BattleInterface::givenCommand.data);
 	}
 
 	{
@@ -877,17 +857,17 @@ BattleAction CPlayerInterface::activeStack(const CStack * stack) //called when i
 		//Regeneration & mana drain go there
 	}
 	//wait till BattleInterface sets its command
-	boost::unique_lock<boost::mutex> lock(CBattleInterface::givenCommand.mx);
-	while(!CBattleInterface::givenCommand.data)
+	boost::unique_lock<boost::mutex> lock(BattleInterface::givenCommand.mx);
+	while(!BattleInterface::givenCommand.data)
 	{
-		CBattleInterface::givenCommand.cond.wait(lock);
+		BattleInterface::givenCommand.cond.wait(lock);
 		if (!battleInt) //battle ended while we were waiting for movement (eg. because of spell)
 			throw boost::thread_interrupted(); //will shut the thread peacefully
 	}
 
 	//tidy up
-	BattleAction ret = *(CBattleInterface::givenCommand.data);
-	vstd::clear_pointer(CBattleInterface::givenCommand.data);
+	BattleAction ret = *(BattleInterface::givenCommand.data);
+	vstd::clear_pointer(BattleInterface::givenCommand.data);
 
 	if(ret.actionType == EActionType::CANCEL)
 	{
@@ -912,7 +892,7 @@ void CPlayerInterface::battleEnd(const BattleResult *br)
 
 		if(!battleInt)
 		{
-			GH.pushIntT<CBattleResultWindow>(*br, *this);
+			GH.pushIntT<BattleResultWindow>(*br, *this);
 			// #1490 - during AI turn when quick combat is on, we need to display the message and wait for user to close it.
 			// Otherwise NewTurn causes freeze.
 			waitWhileDialog();
@@ -962,7 +942,7 @@ void CPlayerInterface::battleTriggerEffect (const BattleTriggerEffect & bte)
 	//TODO why is this different (no return on LOPLINT != this) ?
 
 	RETURN_IF_QUICK_COMBAT;
-	battleInt->battleTriggerEffect(bte);
+	battleInt->effectsController->battleTriggerEffect(bte);
 }
 void CPlayerInterface::battleStacksAttacked(const std::vector<BattleStackAttacked> & bsa)
 {
@@ -977,7 +957,7 @@ void CPlayerInterface::battleStacksAttacked(const std::vector<BattleStackAttacke
 		if(elem.isEffect())
 		{
 			if(defender && !elem.isSecondary())
-				battleInt->displayEffect(elem.effect, defender->getPosition());
+				battleInt->effectsController->displayEffect(EBattleEffect::EBattleEffect(elem.effect), defender->getPosition());
 		}
 		if(elem.isSpell())
 		{
@@ -1012,28 +992,26 @@ void CPlayerInterface::battleAttack(const BattleAttack * ba)
 
 	if(ba->lucky()) //lucky hit
 	{
-		battleInt->console->addText(attacker->formatGeneralMessage(-45));
-		battleInt->displayEffect(18, attacker->getPosition());
-		CCS->soundh->playSound(soundBase::GOODLUCK);
+		battleInt->controlPanel->console->addText(attacker->formatGeneralMessage(-45));
+		battleInt->effectsController->displayEffect(EBattleEffect::GOOD_LUCK, soundBase::GOODLUCK, attacker->getPosition());
 	}
 	if(ba->unlucky()) //unlucky hit
 	{
-		battleInt->console->addText(attacker->formatGeneralMessage(-44));
-		battleInt->displayEffect(48, attacker->getPosition());
-		CCS->soundh->playSound(soundBase::BADLUCK);
+		battleInt->controlPanel->console->addText(attacker->formatGeneralMessage(-44));
+		battleInt->effectsController->displayEffect(EBattleEffect::BAD_LUCK, soundBase::BADLUCK, attacker->getPosition());
 	}
 	if(ba->deathBlow())
 	{
-		battleInt->console->addText(attacker->formatGeneralMessage(365));
+		battleInt->controlPanel->console->addText(attacker->formatGeneralMessage(365));
 		for(auto & elem : ba->bsa)
 		{
 			const CStack * attacked = cb->battleGetStackByID(elem.stackAttacked);
-			battleInt->displayEffect(73, attacked->getPosition());
+			battleInt->effectsController->displayEffect(EBattleEffect::DEATH_BLOW, attacked->getPosition());
 		}
 		CCS->soundh->playSound(soundBase::deathBlow);
 	}
 
-	battleInt->displayCustomEffects(ba->customEffects);
+	battleInt->effectsController->displayCustomEffects(ba->customEffects);
 
 	battleInt->waitForAnims();
 

+ 2 - 3
client/CPlayerInterface.h

@@ -40,9 +40,8 @@ class CButton;
 class CToggleGroup;
 class CAdvMapInt;
 class CCastleInterface;
-class CBattleInterface;
+class BattleInterface;
 class CComponent;
-class CCreatureAnimation;
 class CSelectableComponent;
 class CSlider;
 class CInGameConsole;
@@ -85,7 +84,7 @@ public:
 	static const int SAVES_COUNT = 5;
 
 	CCastleInterface * castleInt; //nullptr if castle window isn't opened
-	static CBattleInterface * battleInt; //nullptr if no battle
+	static BattleInterface * battleInt; //nullptr if no battle
 	CInGameConsole * cingconsole;
 
 	std::shared_ptr<CCallback> cb; //to communicate with engine

+ 3 - 3
client/Client.cpp

@@ -42,7 +42,7 @@
 #include "mainmenu/CMainMenu.h"
 #include "mainmenu/CCampaignScreen.h"
 #include "lobby/CBonusSelection.h"
-#include "battle/CBattleInterface.h"
+#include "battle/BattleInterface.h"
 #include "../lib/CThreadHelper.h"
 #include "../lib/registerTypes/RegisterTypes.h"
 #include "gui/CGuiHandler.h"
@@ -598,7 +598,7 @@ void CClient::battleStarted(const BattleInfo * info)
 		if(!!att || !!def)
 		{
 			boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
-			GH.pushIntT<CBattleInterface>(leftSide.armyObject, rightSide.armyObject, leftSide.hero, rightSide.hero, battleIntRect, att, def);
+			GH.pushIntT<BattleInterface>(leftSide.armyObject, rightSide.armyObject, leftSide.hero, rightSide.hero, battleIntRect, att, def);
 		}
 		else if(settings["session"]["spectate"].Bool() && !settings["session"]["spectate-skip-battle"].Bool())
 		{
@@ -606,7 +606,7 @@ void CClient::battleStarted(const BattleInfo * info)
 			auto spectratorInt = std::dynamic_pointer_cast<CPlayerInterface>(playerint[PlayerColor::SPECTATOR]);
 			spectratorInt->cb->setBattle(info);
 			boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
-			GH.pushIntT<CBattleInterface>(leftSide.armyObject, rightSide.armyObject, leftSide.hero, rightSide.hero, battleIntRect, att, def, spectratorInt);
+			GH.pushIntT<BattleInterface>(leftSide.armyObject, rightSide.armyObject, leftSide.hero, rightSide.hero, battleIntRect, att, def, spectratorInt);
 		}
 	}
 

+ 2 - 2
client/CreatureCostBox.cpp

@@ -20,7 +20,7 @@ CreatureCostBox::CreatureCostBox(Rect position, std::string titleText)
 	type |= REDRAW_PARENT;
 	pos = position + pos;
 
-	title = std::make_shared<CLabel>(pos.w/2, 10, FONT_SMALL, CENTER, Colors::WHITE, titleText);
+	title = std::make_shared<CLabel>(pos.w/2, 10, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, titleText);
 }
 
 void CreatureCostBox::set(TResources res)
@@ -39,7 +39,7 @@ void CreatureCostBox::createItems(TResources res)
 	while(iter.valid())
 	{
 		ImagePtr image = std::make_shared<CAnimImage>("RESOURCE", iter->resType);
-		LabelPtr text = std::make_shared<CLabel>(15, 43, FONT_SMALL, CENTER, Colors::WHITE, "0");
+		LabelPtr text = std::make_shared<CLabel>(15, 43, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, "0");
 
 		resources.insert(std::make_pair(iter->resType, std::make_pair(text, image)));
 		iter++;

+ 0 - 1
client/Graphics.cpp

@@ -29,7 +29,6 @@
 #include "../lib/VCMI_Lib.h"
 #include "../CCallback.h"
 #include "../lib/CGeneralTextHandler.h"
-#include "CBitmapHandler.h"
 #include "../lib/CGameState.h"
 #include "../lib/JsonNode.h"
 #include "../lib/vcmi_endian.h"

+ 1 - 1
client/Graphics.h

@@ -30,7 +30,7 @@ struct SDL_Surface;
 struct SDL_Color;
 class CAnimation;
 
-enum EFonts
+enum EFonts : int
 {
 	FONT_BIG, FONT_CALLI, FONT_CREDITS, FONT_HIGH_SCORE, FONT_MEDIUM, FONT_SMALL, FONT_TIMES, FONT_TINY, FONT_VERD
 };

+ 1 - 1
client/NetPacksClient.cpp

@@ -30,7 +30,7 @@
 #include "windows/GUIClasses.h"
 #include "../lib/CConfigHandler.h"
 #include "gui/SDL_Extensions.h"
-#include "battle/CBattleInterface.h"
+#include "battle/BattleInterface.h"
 #include "../lib/mapping/CCampaignHandler.h"
 #include "../lib/CGameState.h"
 #include "../lib/CStack.h"

+ 775 - 0
client/battle/BattleActionsController.cpp

@@ -0,0 +1,775 @@
+/*
+ * BattleActionsController.cpp, part of VCMI engine
+ *
+ * Authors: listed in file AUTHORS in main folder
+ *
+ * License: GNU General Public License v2.0 or later
+ * Full text of license available in license.txt file, in main folder
+ *
+ */
+#include "StdInc.h"
+#include "BattleActionsController.h"
+
+#include "BattleControlPanel.h"
+#include "BattleStacksController.h"
+#include "BattleInterface.h"
+#include "BattleFieldController.h"
+#include "BattleSiegeController.h"
+#include "BattleInterfaceClasses.h"
+
+#include "../CGameInfo.h"
+#include "../CPlayerInterface.h"
+#include "../gui/CCursorHandler.h"
+#include "../gui/CGuiHandler.h"
+#include "../gui/CIntObject.h"
+#include "../windows/CCreatureWindow.h"
+
+#include "../../CCallback.h"
+#include "../../lib/CStack.h"
+#include "../../lib/battle/BattleAction.h"
+#include "../../lib/spells/CSpellHandler.h"
+#include "../../lib/spells/ISpellMechanics.h"
+#include "../../lib/spells/Problem.h"
+#include "../../lib/CGeneralTextHandler.h"
+
+static std::string formatDmgRange(std::pair<ui32, ui32> dmgRange)
+{
+	if (dmgRange.first != dmgRange.second)
+		return (boost::format("%d - %d") % dmgRange.first % dmgRange.second).str();
+	else
+		return (boost::format("%d") % dmgRange.first).str();
+}
+
+
+BattleActionsController::BattleActionsController(BattleInterface & owner):
+	owner(owner),
+	creatureCasting(false),
+	spellDestSelectMode(false),
+	spellToCast(nullptr),
+	currentSpell(nullptr)
+{
+	currentAction = PossiblePlayerBattleAction::INVALID;
+	selectedAction = PossiblePlayerBattleAction::INVALID;
+}
+
+void BattleActionsController::endCastingSpell()
+{
+	if(spellDestSelectMode)
+	{
+		spellToCast.reset();
+
+		currentSpell = nullptr;
+		spellDestSelectMode = false;
+		CCS->curh->changeGraphic(ECursor::COMBAT, ECursor::COMBAT_POINTER);
+
+		if(owner.stacksController->getActiveStack())
+		{
+			possibleActions = getPossibleActionsForStack(owner.stacksController->getActiveStack()); //restore actions after they were cleared
+			owner.myTurn = true;
+		}
+	}
+	else
+	{
+		if(owner.stacksController->getActiveStack())
+		{
+			possibleActions = getPossibleActionsForStack(owner.stacksController->getActiveStack());
+			GH.fakeMouseMove();
+		}
+	}
+}
+
+void BattleActionsController::enterCreatureCastingMode()
+{
+	//silently check for possible errors
+	if (!owner.myTurn)
+		return;
+
+	if (owner.tacticsMode)
+		return;
+
+	//hero is casting a spell
+	if (spellDestSelectMode)
+		return;
+
+	if (!owner.stacksController->getActiveStack())
+		return;
+
+	if (!owner.stacksController->activeStackSpellcaster())
+		return;
+
+	//random spellcaster
+	if (owner.stacksController->activeStackSpellToCast() == SpellID::NONE)
+		return;
+
+	if (vstd::contains(possibleActions, PossiblePlayerBattleAction::NO_LOCATION))
+	{
+		const spells::Caster * caster = owner.stacksController->getActiveStack();
+		const CSpell * spell = owner.stacksController->activeStackSpellToCast().toSpell();
+
+		spells::Target target;
+		target.emplace_back();
+
+		spells::BattleCast cast(owner.curInt->cb.get(), caster, spells::Mode::CREATURE_ACTIVE, spell);
+
+		auto m = spell->battleMechanics(&cast);
+		spells::detail::ProblemImpl ignored;
+
+		const bool isCastingPossible = m->canBeCastAt(target, ignored);
+
+		if (isCastingPossible)
+		{
+			owner.myTurn = false;
+			owner.giveCommand(EActionType::MONSTER_SPELL, BattleHex::INVALID, owner.stacksController->activeStackSpellToCast());
+			owner.stacksController->setSelectedStack(nullptr);
+
+			CCS->curh->changeGraphic(ECursor::COMBAT, ECursor::COMBAT_POINTER);
+		}
+	}
+	else
+	{
+		possibleActions = getPossibleActionsForStack(owner.stacksController->getActiveStack());
+
+		auto actionFilterPredicate = [](const PossiblePlayerBattleAction x)
+		{
+			return (x != PossiblePlayerBattleAction::ANY_LOCATION) && (x != PossiblePlayerBattleAction::NO_LOCATION) &&
+				(x != PossiblePlayerBattleAction::FREE_LOCATION) && (x != PossiblePlayerBattleAction::AIMED_SPELL_CREATURE) &&
+				(x != PossiblePlayerBattleAction::OBSTACLE);
+		};
+
+		vstd::erase_if(possibleActions, actionFilterPredicate);
+		GH.fakeMouseMove();
+	}
+}
+
+std::vector<PossiblePlayerBattleAction> BattleActionsController::getPossibleActionsForStack(const CStack *stack) const
+{
+	BattleClientInterfaceData data; //hard to get rid of these things so for now they're required data to pass
+	data.creatureSpellToCast = owner.stacksController->activeStackSpellToCast();
+	data.tacticsMode = owner.tacticsMode;
+	auto allActions = owner.curInt->cb->getClientActionsForStack(stack, data);
+
+	return std::vector<PossiblePlayerBattleAction>(allActions);
+}
+
+void BattleActionsController::reorderPossibleActionsPriority(const CStack * stack, MouseHoveredHexContext context)
+{
+	if(owner.tacticsMode || possibleActions.empty()) return; //this function is not supposed to be called in tactics mode or before getPossibleActionsForStack
+
+	auto assignPriority = [&](PossiblePlayerBattleAction const & item) -> uint8_t //large lambda assigning priority which would have to be part of possibleActions without it
+	{
+		switch(item)
+		{
+		case PossiblePlayerBattleAction::AIMED_SPELL_CREATURE:
+		case PossiblePlayerBattleAction::ANY_LOCATION:
+		case PossiblePlayerBattleAction::NO_LOCATION:
+		case PossiblePlayerBattleAction::FREE_LOCATION:
+		case PossiblePlayerBattleAction::OBSTACLE:
+			if(!stack->hasBonusOfType(Bonus::NO_SPELLCAST_BY_DEFAULT) && context == MouseHoveredHexContext::OCCUPIED_HEX)
+				return 1;
+			else
+				return 100;//bottom priority
+			break;
+		case PossiblePlayerBattleAction::RANDOM_GENIE_SPELL:
+			return 2; break;
+		case PossiblePlayerBattleAction::RISE_DEMONS:
+			return 3; break;
+		case PossiblePlayerBattleAction::SHOOT:
+			return 4; break;
+		case PossiblePlayerBattleAction::ATTACK_AND_RETURN:
+			return 5; break;
+		case PossiblePlayerBattleAction::ATTACK:
+			return 6; break;
+		case PossiblePlayerBattleAction::WALK_AND_ATTACK:
+			return 7; break;
+		case PossiblePlayerBattleAction::MOVE_STACK:
+			return 8; break;
+		case PossiblePlayerBattleAction::CATAPULT:
+			return 9; break;
+		case PossiblePlayerBattleAction::HEAL:
+			return 10; break;
+		default:
+			return 200; break;
+		}
+	};
+
+	auto comparer = [&](PossiblePlayerBattleAction const & lhs, PossiblePlayerBattleAction const & rhs)
+	{
+		return assignPriority(lhs) > assignPriority(rhs);
+	};
+
+	std::make_heap(possibleActions.begin(), possibleActions.end(), comparer);
+}
+
+void BattleActionsController::castThisSpell(SpellID spellID)
+{
+	spellToCast = std::make_shared<BattleAction>();
+	spellToCast->actionType = EActionType::HERO_SPELL;
+	spellToCast->actionSubtype = spellID; //spell number
+	spellToCast->stackNumber = (owner.attackingHeroInstance->tempOwner == owner.curInt->playerID) ? -1 : -2;
+	spellToCast->side = owner.defendingHeroInstance ? (owner.curInt->playerID == owner.defendingHeroInstance->tempOwner) : false;
+	spellDestSelectMode = true;
+	creatureCasting = false;
+
+	//choosing possible targets
+	const CGHeroInstance *castingHero = (owner.attackingHeroInstance->tempOwner == owner.curInt->playerID) ? owner.attackingHeroInstance : owner.defendingHeroInstance;
+	assert(castingHero); // code below assumes non-null hero
+	currentSpell = spellID.toSpell();
+	PossiblePlayerBattleAction spellSelMode = owner.curInt->cb->getCasterAction(currentSpell, castingHero, spells::Mode::HERO);
+
+	if (spellSelMode == PossiblePlayerBattleAction::NO_LOCATION) //user does not have to select location
+	{
+		spellToCast->aimToHex(BattleHex::INVALID);
+		owner.curInt->cb->battleMakeAction(spellToCast.get());
+		endCastingSpell();
+	}
+	else
+	{
+		possibleActions.clear();
+		possibleActions.push_back (spellSelMode); //only this one action can be performed at the moment
+		GH.fakeMouseMove();//update cursor
+	}
+}
+
+
+void BattleActionsController::handleHex(BattleHex myNumber, int eventType)
+{
+	if (!owner.myTurn || !owner.battleActionsStarted) //we are not permit to do anything
+		return;
+
+	// This function handles mouse move over hexes and l-clicking on them.
+	// First we decide what happens if player clicks on this hex and set appropriately
+	// consoleMsg, cursorFrame/Type and prepare lambda realizeAction.
+	//
+	// Then, depending whether it was hover/click we either call the action or set tooltip/cursor.
+
+	std::string newConsoleMsg;
+	//used when hovering -> tooltip message and cursor to be set
+	bool setCursor = true; //if we want to suppress setting cursor
+	ECursor::ECursorTypes cursorType = ECursor::COMBAT;
+	int cursorFrame = ECursor::COMBAT_POINTER; //TODO: is this line used?
+
+	//used when l-clicking -> action to be called upon the click
+	std::function<void()> realizeAction;
+
+	//Get stack on the hex - first try to grab the alive one, if not found -> allow dead stacks.
+	const CStack * shere = owner.curInt->cb->battleGetStackByPos(myNumber, true);
+	if(!shere)
+		shere = owner.curInt->cb->battleGetStackByPos(myNumber, false);
+
+	if(!owner.stacksController->getActiveStack())
+		return;
+
+	bool ourStack = false;
+	if (shere)
+		ourStack = shere->owner == owner.curInt->playerID;
+
+	//stack may have changed, update selection border
+	owner.stacksController->setHoveredStack(shere);
+
+	localActions.clear();
+	illegalActions.clear();
+
+	reorderPossibleActionsPriority(owner.stacksController->getActiveStack(), shere ? MouseHoveredHexContext::OCCUPIED_HEX : MouseHoveredHexContext::UNOCCUPIED_HEX);
+	const bool forcedAction = possibleActions.size() == 1;
+
+	for (PossiblePlayerBattleAction action : possibleActions)
+	{
+		bool legalAction = false; //this action is legal and can be performed
+		bool notLegal = false; //this action is not legal and should display message
+
+		switch (action)
+		{
+			case PossiblePlayerBattleAction::CHOOSE_TACTICS_STACK:
+				if (shere && ourStack)
+					legalAction = true;
+				break;
+			case PossiblePlayerBattleAction::MOVE_TACTICS:
+			case PossiblePlayerBattleAction::MOVE_STACK:
+			{
+				if (!(shere && shere->alive())) //we can walk on dead stacks
+				{
+					if(canStackMoveHere(owner.stacksController->getActiveStack(), myNumber))
+						legalAction = true;
+				}
+				break;
+			}
+			case PossiblePlayerBattleAction::ATTACK:
+			case PossiblePlayerBattleAction::WALK_AND_ATTACK:
+			case PossiblePlayerBattleAction::ATTACK_AND_RETURN:
+			{
+				if(owner.curInt->cb->battleCanAttack(owner.stacksController->getActiveStack(), shere, myNumber))
+				{
+					if (owner.fieldController->isTileAttackable(myNumber)) // move isTileAttackable to be part of battleCanAttack?
+					{
+						owner.fieldController->setBattleCursor(myNumber); // temporary - needed for following function :(
+						BattleHex attackFromHex = owner.fieldController->fromWhichHexAttack(myNumber);
+
+						if (attackFromHex >= 0) //we can be in this line when unreachable creature is L - clicked (as of revision 1308)
+							legalAction = true;
+					}
+				}
+			}
+				break;
+			case PossiblePlayerBattleAction::SHOOT:
+				if(owner.curInt->cb->battleCanShoot(owner.stacksController->getActiveStack(), myNumber))
+					legalAction = true;
+				break;
+			case PossiblePlayerBattleAction::ANY_LOCATION:
+				if (myNumber > -1) //TODO: this should be checked for all actions
+				{
+					if(isCastingPossibleHere(owner.stacksController->getActiveStack(), shere, myNumber))
+						legalAction = true;
+				}
+				break;
+			case PossiblePlayerBattleAction::AIMED_SPELL_CREATURE:
+				if(shere && isCastingPossibleHere(owner.stacksController->getActiveStack(), shere, myNumber))
+					legalAction = true;
+				break;
+			case PossiblePlayerBattleAction::RANDOM_GENIE_SPELL:
+			{
+				if(shere && ourStack && shere != owner.stacksController->getActiveStack() && shere->alive()) //only positive spells for other allied creatures
+				{
+					int spellID = owner.curInt->cb->battleGetRandomStackSpell(CRandomGenerator::getDefault(), shere, CBattleInfoCallback::RANDOM_GENIE);
+					if(spellID > -1)
+					{
+						legalAction = true;
+					}
+				}
+			}
+				break;
+			case PossiblePlayerBattleAction::OBSTACLE:
+				if(isCastingPossibleHere(owner.stacksController->getActiveStack(), shere, myNumber))
+					legalAction = true;
+				break;
+			case PossiblePlayerBattleAction::TELEPORT:
+			{
+				//todo: move to mechanics
+				ui8 skill = 0;
+				if (creatureCasting)
+					skill = owner.stacksController->getActiveStack()->getEffectLevel(SpellID(SpellID::TELEPORT).toSpell());
+				else
+					skill = owner.getActiveHero()->getEffectLevel(SpellID(SpellID::TELEPORT).toSpell());
+				//TODO: explicitely save power, skill
+				if (owner.curInt->cb->battleCanTeleportTo(owner.stacksController->getSelectedStack(), myNumber, skill))
+					legalAction = true;
+				else
+					notLegal = true;
+			}
+				break;
+			case PossiblePlayerBattleAction::SACRIFICE: //choose our living stack to sacrifice
+				if (shere && shere != owner.stacksController->getSelectedStack() && ourStack && shere->alive())
+					legalAction = true;
+				else
+					notLegal = true;
+				break;
+			case PossiblePlayerBattleAction::FREE_LOCATION:
+				legalAction = true;
+				if(!isCastingPossibleHere(owner.stacksController->getActiveStack(), shere, myNumber))
+				{
+					legalAction = false;
+					notLegal = true;
+				}
+				break;
+			case PossiblePlayerBattleAction::CATAPULT:
+				if (owner.siegeController && owner.siegeController->isAttackableByCatapult(myNumber))
+					legalAction = true;
+				break;
+			case PossiblePlayerBattleAction::HEAL:
+				if (shere && ourStack && shere->canBeHealed())
+					legalAction = true;
+				break;
+			case PossiblePlayerBattleAction::RISE_DEMONS:
+				if (shere && ourStack && !shere->alive())
+				{
+					if (!(shere->hasBonusOfType(Bonus::UNDEAD)
+						|| shere->hasBonusOfType(Bonus::NON_LIVING)
+						|| shere->hasBonusOfType(Bonus::GARGOYLE)
+						|| shere->summoned
+						|| shere->isClone()
+						|| shere->hasBonusOfType(Bonus::SIEGE_WEAPON)
+						))
+						legalAction = true;
+				}
+				break;
+		}
+		if (legalAction)
+			localActions.push_back (action);
+		else if (notLegal || forcedAction)
+			illegalActions.push_back (action);
+	}
+	illegalAction = PossiblePlayerBattleAction::INVALID; //clear it in first place
+
+	if (vstd::contains(localActions, selectedAction)) //try to use last selected action by default
+		currentAction = selectedAction;
+	else if (localActions.size()) //if not possible, select first available action (they are sorted by suggested priority)
+		currentAction = localActions.front();
+	else //no legal action possible
+	{
+		currentAction = PossiblePlayerBattleAction::INVALID; //don't allow to do anything
+
+		if (vstd::contains(illegalActions, selectedAction))
+			illegalAction = selectedAction;
+		else if (illegalActions.size())
+			illegalAction = illegalActions.front();
+		else if (shere && ourStack && shere->alive()) //last possibility - display info about our creature
+		{
+			currentAction = PossiblePlayerBattleAction::CREATURE_INFO;
+		}
+		else
+			illegalAction = PossiblePlayerBattleAction::INVALID; //we should never be here
+	}
+
+	bool isCastingPossible = false;
+	bool secondaryTarget = false;
+
+	if (currentAction > PossiblePlayerBattleAction::INVALID)
+	{
+		switch (currentAction) //display console message, realize selected action
+		{
+			case PossiblePlayerBattleAction::CHOOSE_TACTICS_STACK:
+				newConsoleMsg = (boost::format(CGI->generaltexth->allTexts[481]) % shere->getName()).str(); //Select %s
+				realizeAction = [=](){ owner.stackActivated(shere); };
+				break;
+			case PossiblePlayerBattleAction::MOVE_TACTICS:
+			case PossiblePlayerBattleAction::MOVE_STACK:
+				if (owner.stacksController->getActiveStack()->hasBonusOfType(Bonus::FLYING))
+				{
+					cursorFrame = ECursor::COMBAT_FLY;
+					newConsoleMsg = (boost::format(CGI->generaltexth->allTexts[295]) % owner.stacksController->getActiveStack()->getName()).str(); //Fly %s here
+				}
+				else
+				{
+					cursorFrame = ECursor::COMBAT_MOVE;
+					newConsoleMsg = (boost::format(CGI->generaltexth->allTexts[294]) % owner.stacksController->getActiveStack()->getName()).str(); //Move %s here
+				}
+
+				realizeAction = [=]()
+				{
+					if(owner.stacksController->getActiveStack()->doubleWide())
+					{
+						std::vector<BattleHex> acc = owner.curInt->cb->battleGetAvailableHexes(owner.stacksController->getActiveStack());
+						BattleHex shiftedDest = myNumber.cloneInDirection(owner.stacksController->getActiveStack()->destShiftDir(), false);
+						if(vstd::contains(acc, myNumber))
+							owner.giveCommand(EActionType::WALK, myNumber);
+						else if(vstd::contains(acc, shiftedDest))
+							owner.giveCommand(EActionType::WALK, shiftedDest);
+					}
+					else
+					{
+						owner.giveCommand(EActionType::WALK, myNumber);
+					}
+				};
+				break;
+			case PossiblePlayerBattleAction::ATTACK:
+			case PossiblePlayerBattleAction::WALK_AND_ATTACK:
+			case PossiblePlayerBattleAction::ATTACK_AND_RETURN: //TODO: allow to disable return
+				{
+					owner.fieldController->setBattleCursor(myNumber); //handle direction of cursor and attackable tile
+					setCursor = false; //don't overwrite settings from the call above //TODO: what does it mean?
+
+					bool returnAfterAttack = currentAction == PossiblePlayerBattleAction::ATTACK_AND_RETURN;
+
+					realizeAction = [=]()
+					{
+						BattleHex attackFromHex = owner.fieldController->fromWhichHexAttack(myNumber);
+						if(attackFromHex.isValid()) //we can be in this line when unreachable creature is L - clicked (as of revision 1308)
+						{
+							auto command = new BattleAction(BattleAction::makeMeleeAttack(owner.stacksController->getActiveStack(), myNumber, attackFromHex, returnAfterAttack));
+							owner.sendCommand(command, owner.stacksController->getActiveStack());
+						}
+					};
+
+					TDmgRange damage = owner.curInt->cb->battleEstimateDamage(owner.stacksController->getActiveStack(), shere);
+					std::string estDmgText = formatDmgRange(std::make_pair((ui32)damage.first, (ui32)damage.second)); //calculating estimated dmg
+					newConsoleMsg = (boost::format(CGI->generaltexth->allTexts[36]) % shere->getName() % estDmgText).str(); //Attack %s (%s damage)
+				}
+				break;
+			case PossiblePlayerBattleAction::SHOOT:
+			{
+				if (owner.curInt->cb->battleHasShootingPenalty(owner.stacksController->getActiveStack(), myNumber))
+					cursorFrame = ECursor::COMBAT_SHOOT_PENALTY;
+				else
+					cursorFrame = ECursor::COMBAT_SHOOT;
+
+				realizeAction = [=](){owner.giveCommand(EActionType::SHOOT, myNumber);};
+				TDmgRange damage = owner.curInt->cb->battleEstimateDamage(owner.stacksController->getActiveStack(), shere);
+				std::string estDmgText = formatDmgRange(std::make_pair((ui32)damage.first, (ui32)damage.second)); //calculating estimated dmg
+				//printing - Shoot %s (%d shots left, %s damage)
+				newConsoleMsg = (boost::format(CGI->generaltexth->allTexts[296]) % shere->getName() % owner.stacksController->getActiveStack()->shots.available() % estDmgText).str();
+			}
+				break;
+			case PossiblePlayerBattleAction::AIMED_SPELL_CREATURE:
+				currentSpell = CGI->spellh->objects[creatureCasting ? owner.stacksController->activeStackSpellToCast() : spellToCast->actionSubtype]; //necessary if creature has random Genie spell at same time
+				newConsoleMsg = boost::str(boost::format(CGI->generaltexth->allTexts[27]) % currentSpell->name % shere->getName()); //Cast %s on %s
+				switch (currentSpell->id)
+				{
+					case SpellID::SACRIFICE:
+					case SpellID::TELEPORT:
+						owner.stacksController->setSelectedStack(shere); //remember first target
+						secondaryTarget = true;
+						break;
+				}
+				isCastingPossible = true;
+				break;
+			case PossiblePlayerBattleAction::ANY_LOCATION:
+				currentSpell = CGI->spellh->objects[creatureCasting ? owner.stacksController->activeStackSpellToCast() : spellToCast->actionSubtype]; //necessary if creature has random Genie spell at same time
+				newConsoleMsg = boost::str(boost::format(CGI->generaltexth->allTexts[26]) % currentSpell->name); //Cast %s
+				isCastingPossible = true;
+				break;
+			case PossiblePlayerBattleAction::RANDOM_GENIE_SPELL: //we assume that teleport / sacrifice will never be available as random spell
+				currentSpell = nullptr;
+				newConsoleMsg = boost::str(boost::format(CGI->generaltexth->allTexts[301]) % shere->getName()); //Cast a spell on %
+				creatureCasting = true;
+				isCastingPossible = true;
+				break;
+			case PossiblePlayerBattleAction::TELEPORT:
+				newConsoleMsg = CGI->generaltexth->allTexts[25]; //Teleport Here
+				cursorFrame = ECursor::COMBAT_TELEPORT;
+				isCastingPossible = true;
+				break;
+			case PossiblePlayerBattleAction::OBSTACLE:
+				newConsoleMsg = CGI->generaltexth->allTexts[550];
+				//TODO: remove obstacle cursor
+				isCastingPossible = true;
+				break;
+			case PossiblePlayerBattleAction::SACRIFICE:
+				newConsoleMsg = (boost::format(CGI->generaltexth->allTexts[549]) % shere->getName()).str(); //sacrifice the %s
+				cursorFrame = ECursor::COMBAT_SACRIFICE;
+				isCastingPossible = true;
+				break;
+			case PossiblePlayerBattleAction::FREE_LOCATION:
+				newConsoleMsg = boost::str(boost::format(CGI->generaltexth->allTexts[26]) % currentSpell->name); //Cast %s
+				isCastingPossible = true;
+				break;
+			case PossiblePlayerBattleAction::HEAL:
+				cursorFrame = ECursor::COMBAT_HEAL;
+				newConsoleMsg = (boost::format(CGI->generaltexth->allTexts[419]) % shere->getName()).str(); //Apply first aid to the %s
+				realizeAction = [=](){ owner.giveCommand(EActionType::STACK_HEAL, myNumber); }; //command healing
+				break;
+			case PossiblePlayerBattleAction::RISE_DEMONS:
+				cursorType = ECursor::SPELLBOOK;
+				realizeAction = [=]()
+				{
+					owner.giveCommand(EActionType::DAEMON_SUMMONING, myNumber);
+				};
+				break;
+			case PossiblePlayerBattleAction::CATAPULT:
+				cursorFrame = ECursor::COMBAT_SHOOT_CATAPULT;
+				realizeAction = [=](){ owner.giveCommand(EActionType::CATAPULT, myNumber); };
+				break;
+			case PossiblePlayerBattleAction::CREATURE_INFO:
+			{
+				cursorFrame = ECursor::COMBAT_QUERY;
+				newConsoleMsg = (boost::format(CGI->generaltexth->allTexts[297]) % shere->getName()).str();
+				realizeAction = [=](){ GH.pushIntT<CStackWindow>(shere, false); };
+				break;
+			}
+		}
+	}
+	else //no possible valid action, display message
+	{
+		switch (illegalAction)
+		{
+			case PossiblePlayerBattleAction::AIMED_SPELL_CREATURE:
+			case PossiblePlayerBattleAction::RANDOM_GENIE_SPELL:
+				cursorFrame = ECursor::COMBAT_BLOCKED;
+				newConsoleMsg = CGI->generaltexth->allTexts[23];
+				break;
+			case PossiblePlayerBattleAction::TELEPORT:
+				cursorFrame = ECursor::COMBAT_BLOCKED;
+				newConsoleMsg = CGI->generaltexth->allTexts[24]; //Invalid Teleport Destination
+				break;
+			case PossiblePlayerBattleAction::SACRIFICE:
+				newConsoleMsg = CGI->generaltexth->allTexts[543]; //choose army to sacrifice
+				break;
+			case PossiblePlayerBattleAction::FREE_LOCATION:
+				cursorFrame = ECursor::COMBAT_BLOCKED;
+				newConsoleMsg = boost::str(boost::format(CGI->generaltexth->allTexts[181]) % currentSpell->name); //No room to place %s here
+				break;
+			default:
+				if (myNumber == -1)
+					CCS->curh->changeGraphic(ECursor::COMBAT, ECursor::COMBAT_POINTER); //set neutral cursor over menu etc.
+				else
+					cursorFrame = ECursor::COMBAT_BLOCKED;
+				break;
+		}
+	}
+
+	if (isCastingPossible) //common part
+	{
+		switch (currentAction) //don't use that with teleport / sacrifice
+		{
+			case PossiblePlayerBattleAction::TELEPORT: //FIXME: more generic solution?
+			case PossiblePlayerBattleAction::SACRIFICE:
+				break;
+			default:
+				cursorType = ECursor::SPELLBOOK;
+				cursorFrame = 0;
+				if (newConsoleMsg.empty() && currentSpell)
+					newConsoleMsg = boost::str(boost::format(CGI->generaltexth->allTexts[26]) % currentSpell->name); //Cast %s
+				break;
+		}
+
+		realizeAction = [=]()
+		{
+			if(secondaryTarget) //select that target now
+			{
+
+				possibleActions.clear();
+				switch (currentSpell->id.toEnum())
+				{
+					case SpellID::TELEPORT: //don't cast spell yet, only select target
+						spellToCast->aimToUnit(shere);
+						possibleActions.push_back(PossiblePlayerBattleAction::TELEPORT);
+						break;
+					case SpellID::SACRIFICE:
+						spellToCast->aimToHex(myNumber);
+						possibleActions.push_back(PossiblePlayerBattleAction::SACRIFICE);
+						break;
+				}
+			}
+			else
+			{
+				if (creatureCasting)
+				{
+					if (currentSpell)
+					{
+						owner.giveCommand(EActionType::MONSTER_SPELL, myNumber, owner.stacksController->activeStackSpellToCast());
+					}
+					else //unknown random spell
+					{
+						owner.giveCommand(EActionType::MONSTER_SPELL, myNumber);
+					}
+				}
+				else
+				{
+					assert(currentSpell);
+					switch (currentSpell->id.toEnum())
+					{
+					case SpellID::SACRIFICE:
+						spellToCast->aimToUnit(shere);//victim
+						break;
+					default:
+						spellToCast->aimToHex(myNumber);
+						break;
+					}
+					owner.curInt->cb->battleMakeAction(spellToCast.get());
+					endCastingSpell();
+				}
+				owner.stacksController->setSelectedStack(nullptr);
+			}
+		};
+	}
+
+	{
+		if (eventType == CIntObject::MOVE)
+		{
+			if (setCursor)
+				CCS->curh->changeGraphic(cursorType, cursorFrame);
+
+			if (!currentConsoleMsg.empty())
+				owner.controlPanel->console->clearIfMatching(currentConsoleMsg);
+			if (!newConsoleMsg.empty())
+				owner.controlPanel->console->write(newConsoleMsg);
+
+			currentConsoleMsg = newConsoleMsg;
+		}
+		if (eventType == CIntObject::LCLICK && realizeAction)
+		{
+			//opening creature window shouldn't affect myTurn...
+			if ((currentAction != PossiblePlayerBattleAction::CREATURE_INFO) && !secondaryTarget)
+			{
+				owner.myTurn = false; //tends to crash with empty calls
+			}
+			realizeAction();
+			if (!secondaryTarget) //do not replace teleport or sacrifice cursor
+				CCS->curh->changeGraphic(ECursor::COMBAT, ECursor::COMBAT_POINTER);
+			owner.controlPanel->console->clear();
+		}
+	}
+}
+
+
+bool BattleActionsController::isCastingPossibleHere(const CStack *sactive, const CStack *shere, BattleHex myNumber)
+{
+	creatureCasting = owner.stacksController->activeStackSpellcaster() && !spellDestSelectMode; //TODO: allow creatures to cast aimed spells
+
+	bool isCastingPossible = true;
+
+	int spellID = -1;
+	if (creatureCasting)
+	{
+		if (owner.stacksController->activeStackSpellToCast() != SpellID::NONE && (shere != sactive)) //can't cast on itself
+			spellID = owner.stacksController->activeStackSpellToCast(); //TODO: merge with SpellTocast?
+	}
+	else //hero casting
+	{
+		spellID = spellToCast->actionSubtype;
+	}
+
+
+	currentSpell = nullptr;
+	if (spellID >= 0)
+		currentSpell = CGI->spellh->objects[spellID];
+
+	if (currentSpell)
+	{
+		const spells::Caster *caster = creatureCasting ? static_cast<const spells::Caster *>(sactive) : static_cast<const spells::Caster *>(owner.curInt->cb->battleGetMyHero());
+		if (caster == nullptr)
+		{
+			isCastingPossible = false;//just in case
+		}
+		else
+		{
+			const spells::Mode mode = creatureCasting ? spells::Mode::CREATURE_ACTIVE : spells::Mode::HERO;
+
+			spells::Target target;
+			target.emplace_back(myNumber);
+
+			spells::BattleCast cast(owner.curInt->cb.get(), caster, mode, currentSpell);
+
+			auto m = currentSpell->battleMechanics(&cast);
+			spells::detail::ProblemImpl problem; //todo: display problem in status bar
+
+			isCastingPossible = m->canBeCastAt(target, problem);
+		}
+	}
+	else
+		isCastingPossible = false;
+	if (!myNumber.isAvailable() && !shere) //empty tile outside battlefield (or in the unavailable border column)
+			isCastingPossible = false;
+
+	return isCastingPossible;
+}
+
+bool BattleActionsController::canStackMoveHere(const CStack * stackToMove, BattleHex myNumber) const
+{
+	std::vector<BattleHex> acc = owner.curInt->cb->battleGetAvailableHexes(stackToMove);
+	BattleHex shiftedDest = myNumber.cloneInDirection(stackToMove->destShiftDir(), false);
+
+	if (vstd::contains(acc, myNumber))
+		return true;
+	else if (stackToMove->doubleWide() && vstd::contains(acc, shiftedDest))
+		return true;
+	else
+		return false;
+}
+
+void BattleActionsController::activateStack()
+{
+	const CStack * s = owner.stacksController->getActiveStack();
+	if(s)
+		possibleActions = getPossibleActionsForStack(s);
+}
+
+bool BattleActionsController::spellcastingModeActive() const
+{
+	return spellDestSelectMode;
+}
+
+SpellID BattleActionsController::selectedSpell() const
+{
+	if (!spellToCast)
+		return SpellID::NONE;
+	return SpellID(spellToCast->actionSubtype);
+}

+ 96 - 0
client/battle/BattleActionsController.h

@@ -0,0 +1,96 @@
+/*
+ * BattleActionsController.h, part of VCMI engine
+ *
+ * Authors: listed in file AUTHORS in main folder
+ *
+ * License: GNU General Public License v2.0 or later
+ * Full text of license available in license.txt file, in main folder
+ *
+ */
+#pragma once
+
+#include "../../lib/battle/CBattleInfoCallback.h"
+
+VCMI_LIB_NAMESPACE_BEGIN
+
+class BattleAction;
+
+VCMI_LIB_NAMESPACE_END
+
+class BattleInterface;
+
+enum class MouseHoveredHexContext
+{
+	UNOCCUPIED_HEX,
+	OCCUPIED_HEX
+};
+
+/// Class that controls actions that can be performed by player, e.g. moving stacks, attacking, etc
+/// As well as all relevant feedback for these actions in user interface
+class BattleActionsController
+{
+	BattleInterface & owner;
+
+	/// all actions possible to call at the moment by player
+	std::vector<PossiblePlayerBattleAction> possibleActions;
+
+	/// actions possible to take on hovered hex
+	std::vector<PossiblePlayerBattleAction> localActions;
+
+	/// these actions display message in case of illegal target
+	std::vector<PossiblePlayerBattleAction> illegalActions;
+
+	/// action that will be performed on l-click
+	PossiblePlayerBattleAction currentAction;
+
+	/// last action chosen (and saved) by player
+	PossiblePlayerBattleAction selectedAction;
+
+	/// if there are not possible actions to choose from, this action should be show as "illegal" in UI
+	PossiblePlayerBattleAction illegalAction;
+
+	/// if true, stack currently aims to cats a spell
+	bool creatureCasting;
+
+	/// if true, player is choosing destination for his spell - only for GUI / console
+	bool spellDestSelectMode;
+
+	/// spell for which player is choosing destination
+	std::shared_ptr<BattleAction> spellToCast;
+
+	/// spell for which player is choosing destination, pointer for convenience
+	const CSpell *currentSpell;
+
+	/// cached message that was set by this class in status bar
+	std::string currentConsoleMsg;
+
+	bool isCastingPossibleHere (const CStack *sactive, const CStack *shere, BattleHex myNumber);
+	bool canStackMoveHere (const CStack *sactive, BattleHex MyNumber) const; //TODO: move to BattleState / callback
+	std::vector<PossiblePlayerBattleAction> getPossibleActionsForStack (const CStack *stack) const; //called when stack gets its turn
+	void reorderPossibleActionsPriority(const CStack * stack, MouseHoveredHexContext context);
+
+public:
+	BattleActionsController(BattleInterface & owner);
+
+	/// initialize list of potential actions for new active stack
+	void activateStack();
+
+	/// initialize potential actions for spells that can be cast by active stack
+	void enterCreatureCastingMode();
+
+	/// initialize potential actions for selected spell
+	void castThisSpell(SpellID spellID);
+
+	/// ends casting spell (eg. when spell has been cast or canceled)
+	void endCastingSpell();
+
+	/// update UI (e.g. status bar/cursor) according to new active hex
+	void handleHex(BattleHex myNumber, int eventType);
+
+	/// returns currently selected spell or SpellID::NONE on error
+	SpellID selectedSpell() const;
+
+	/// returns true if UI is currently in target selection mode
+	bool spellcastingModeActive() const;
+
+};

+ 1222 - 0
client/battle/BattleAnimationClasses.cpp

@@ -0,0 +1,1222 @@
+/*
+ * BattleAnimationClasses.cpp, part of VCMI engine
+ *
+ * Authors: listed in file AUTHORS in main folder
+ *
+ * License: GNU General Public License v2.0 or later
+ * Full text of license available in license.txt file, in main folder
+ *
+ */
+#include "StdInc.h"
+#include "BattleAnimationClasses.h"
+
+#include <boost/math/constants/constants.hpp>
+
+#include "BattleInterfaceClasses.h"
+#include "BattleInterface.h"
+#include "BattleProjectileController.h"
+#include "BattleSiegeController.h"
+#include "BattleFieldController.h"
+#include "BattleEffectsController.h"
+#include "BattleStacksController.h"
+#include "CreatureAnimation.h"
+
+#include "../CGameInfo.h"
+#include "../CMusicHandler.h"
+#include "../CPlayerInterface.h"
+#include "../Graphics.h"
+#include "../gui/CAnimation.h"
+#include "../gui/CCursorHandler.h"
+#include "../gui/CGuiHandler.h"
+
+#include "../../CCallback.h"
+#include "../../lib/CStack.h"
+#include "../../lib/CTownHandler.h"
+#include "../../lib/mapObjects/CGTownInstance.h"
+
+CBattleAnimation::CBattleAnimation(BattleInterface & owner)
+	: owner(owner),
+	  ID(owner.stacksController->animIDhelper++),
+	  initialized(false)
+{
+	logAnim->trace("Animation #%d created", ID);
+}
+
+bool CBattleAnimation::tryInitialize()
+{
+	assert(!initialized);
+
+	if ( init() )
+	{
+		initialized = true;
+		return true;
+	}
+	return false;
+}
+
+bool CBattleAnimation::isInitialized()
+{
+	return initialized;
+}
+
+CBattleAnimation::~CBattleAnimation()
+{
+	logAnim->trace("Animation #%d ended, type is %s", ID, typeid(this).name());
+	for(auto & elem : pendingAnimations())
+	{
+		if(elem == this)
+			elem = nullptr;
+	}
+	logAnim->trace("Animation #%d deleted", ID);
+}
+
+std::vector<CBattleAnimation *> & CBattleAnimation::pendingAnimations()
+{
+	return owner.stacksController->currentAnimations;
+}
+
+std::shared_ptr<CreatureAnimation> CBattleAnimation::stackAnimation(const CStack * stack) const
+{
+	return owner.stacksController->stackAnimation[stack->ID];
+}
+
+bool CBattleAnimation::stackFacingRight(const CStack * stack)
+{
+	return owner.stacksController->stackFacingRight[stack->ID];
+}
+
+void CBattleAnimation::setStackFacingRight(const CStack * stack, bool facingRight)
+{
+	owner.stacksController->stackFacingRight[stack->ID] = facingRight;
+}
+
+bool CBattleAnimation::checkInitialConditions()
+{
+	int lowestMoveID = ID;
+	auto * thAnim = dynamic_cast<CBattleStackAnimation *>(this);
+	auto * thSen = dynamic_cast<CPointEffectAnimation *>(this);
+
+	for(auto & elem : pendingAnimations())
+	{
+		auto * sen = dynamic_cast<CPointEffectAnimation *>(elem);
+
+		// all effect animations can play concurrently with each other
+		if(sen && thSen && sen != thSen)
+			continue;
+
+		auto * revAnim = dynamic_cast<CReverseAnimation *>(elem);
+
+		// if there is high-priority reverse animation affecting our stack then this animation will wait
+		if(revAnim && thAnim && revAnim && revAnim->stack->ID == thAnim->stack->ID && revAnim->priority)
+			return false;
+
+		if(elem)
+			vstd::amin(lowestMoveID, elem->ID);
+	}
+	return ID == lowestMoveID;
+}
+
+CBattleStackAnimation::CBattleStackAnimation(BattleInterface & owner, const CStack * stack)
+	: CBattleAnimation(owner),
+	  myAnim(stackAnimation(stack)),
+	  stack(stack)
+{
+	assert(myAnim);
+}
+
+void CBattleStackAnimation::shiftColor(const ColorShifter * shifter)
+{
+	assert(myAnim);
+	myAnim->shiftColor(shifter);
+}
+
+void CAttackAnimation::nextFrame()
+{
+	if(myAnim->getType() != group)
+	{
+		myAnim->setType(group);
+		myAnim->onAnimationReset += [&](){ delete this; };
+	}
+
+	if(!soundPlayed)
+	{
+		if(shooting)
+			CCS->soundh->playSound(battle_sound(getCreature(), shoot));
+		else
+			CCS->soundh->playSound(battle_sound(getCreature(), attack));
+		soundPlayed = true;
+	}
+}
+
+CAttackAnimation::~CAttackAnimation()
+{
+	myAnim->setType(CCreatureAnim::HOLDING);
+}
+
+bool CAttackAnimation::checkInitialConditions()
+{
+	for(auto & elem : pendingAnimations())
+	{
+		CBattleStackAnimation * stAnim = dynamic_cast<CBattleStackAnimation *>(elem);
+		CReverseAnimation * revAnim = dynamic_cast<CReverseAnimation *>(stAnim);
+
+		if(revAnim && attackedStack) // enemy must be fully reversed
+		{
+			if (revAnim->stack->ID == attackedStack->ID)
+				return false;
+		}
+	}
+	return CBattleAnimation::checkInitialConditions();
+}
+
+const CCreature * CAttackAnimation::getCreature() const
+{
+	if (attackingStack->getCreature()->idNumber == CreatureID::ARROW_TOWERS)
+		return owner.siegeController->getTurretCreature();
+	else
+		return attackingStack->getCreature();
+}
+
+CAttackAnimation::CAttackAnimation(BattleInterface & 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");
+	attackingStackPosBeforeReturn = attackingStack->getPosition();
+}
+
+CDefenceAnimation::CDefenceAnimation(StackAttackedInfo _attackedInfo, BattleInterface & owner)
+	: CBattleStackAnimation(owner, _attackedInfo.defender),
+	  attacker(_attackedInfo.attacker),
+	  rangedAttack(_attackedInfo.indirectAttack),
+	  killed(_attackedInfo.killed),
+	  timeToWait(0)
+{
+	logAnim->debug("Created defence anim for %s", _attackedInfo.defender->getName());
+}
+
+bool CDefenceAnimation::init()
+{
+	ui32 lowestMoveID = ID;
+	for(auto & elem : pendingAnimations())
+	{
+
+		auto * defAnim = dynamic_cast<CDefenceAnimation *>(elem);
+		if(defAnim && defAnim->stack->ID != stack->ID)
+			continue;
+
+		auto * attAnim = dynamic_cast<CAttackAnimation *>(elem);
+		if(attAnim && attAnim->stack->ID != stack->ID)
+			continue;
+
+		auto * sen = dynamic_cast<CPointEffectAnimation *>(elem);
+		if (sen && attacker == nullptr)
+			return false;
+
+		if (sen)
+			continue;
+
+		CReverseAnimation * animAsRev = dynamic_cast<CReverseAnimation *>(elem);
+
+		if(animAsRev)
+			return false;
+
+		if(elem)
+			vstd::amin(lowestMoveID, elem->ID);
+	}
+
+	if(ID > lowestMoveID)
+		return false;
+
+
+	//reverse unit if necessary
+	if(attacker && owner.getCurrentPlayerInterface()->cb->isToReverse(stack->getPosition(), attacker->getPosition(), stackFacingRight(stack), attacker->doubleWide(), stackFacingRight(attacker)))
+	{
+		owner.stacksController->addNewAnim(new CReverseAnimation(owner, stack, stack->getPosition(), true));
+		return false;
+	}
+	//unit reversed
+
+	if(rangedAttack && attacker != nullptr && owner.projectilesController->hasActiveProjectile(attacker)) //delay hit animation
+	{
+		return false;
+	}
+
+	// synchronize animation with attacker, unless defending or attacked by shooter:
+	// wait for 1/2 of attack animation
+	if (!rangedAttack && getMyAnimType() != CCreatureAnim::DEFENCE)
+	{
+		float frameLength = AnimationControls::getCreatureAnimationSpeed(
+								  stack->getCreature(), stackAnimation(stack).get(), getMyAnimType());
+
+		timeToWait = myAnim->framesInGroup(getMyAnimType()) * frameLength / 2;
+
+		myAnim->setType(CCreatureAnim::HOLDING);
+	}
+	else
+	{
+		timeToWait = 0;
+		startAnimation();
+	}
+
+	return true; //initialized successfuly
+}
+
+std::string CDefenceAnimation::getMySound()
+{
+	if(killed)
+		return battle_sound(stack->getCreature(), killed);
+	else if(stack->defendingAnim)
+		return battle_sound(stack->getCreature(), defend);
+	else
+		return battle_sound(stack->getCreature(), wince);
+}
+
+CCreatureAnim::EAnimType CDefenceAnimation::getMyAnimType()
+{
+	if(killed)
+	{
+		if(rangedAttack && myAnim->framesInGroup(CCreatureAnim::DEATH_RANGED) > 0)
+			return CCreatureAnim::DEATH_RANGED;
+		else
+			return CCreatureAnim::DEATH;
+	}
+
+	if(stack->defendingAnim)
+		return CCreatureAnim::DEFENCE;
+	else
+		return CCreatureAnim::HITTED;
+}
+
+void CDefenceAnimation::startAnimation()
+{
+	CCS->soundh->playSound(getMySound());
+	myAnim->setType(getMyAnimType());
+	myAnim->onAnimationReset += [&](){ delete this; };
+}
+
+void CDefenceAnimation::nextFrame()
+{
+	if (timeToWait > 0)
+	{
+		timeToWait -= float(GH.mainFPSmng->getElapsedMilliseconds()) / 1000;
+		if (timeToWait <= 0)
+			startAnimation();
+	}
+
+	CBattleAnimation::nextFrame();
+}
+
+CDefenceAnimation::~CDefenceAnimation()
+{
+	if(killed)
+	{
+		if(rangedAttack && myAnim->framesInGroup(CCreatureAnim::DEAD_RANGED) > 0)
+			myAnim->setType(CCreatureAnim::DEAD_RANGED);
+		else
+			myAnim->setType(CCreatureAnim::DEAD);
+	}
+	else
+	{
+		myAnim->setType(CCreatureAnim::HOLDING);
+	}
+}
+
+CDummyAnimation::CDummyAnimation(BattleInterface & owner, int howManyFrames)
+	: CBattleAnimation(owner),
+	  counter(0),
+	  howMany(howManyFrames)
+{
+	logAnim->debug("Created dummy animation for %d frames", howManyFrames);
+}
+
+bool CDummyAnimation::init()
+{
+	return true;
+}
+
+void CDummyAnimation::nextFrame()
+{
+	counter++;
+	if(counter > howMany)
+		delete this;
+}
+
+bool CMeleeAttackAnimation::init()
+{
+	if(!CAttackAnimation::checkInitialConditions())
+		return false;
+
+	if(!attackingStack || myAnim->isDeadOrDying())
+	{
+		delete this;
+		return false;
+	}
+
+	bool toReverse = owner.getCurrentPlayerInterface()->cb->isToReverse(attackingStackPosBeforeReturn, attackedStack->getPosition(), stackFacingRight(stack), attackedStack->doubleWide(), stackFacingRight(attackedStack));
+
+	if(toReverse)
+	{
+		owner.stacksController->addNewAnim(new CReverseAnimation(owner, stack, attackingStackPosBeforeReturn, true));
+		return false;
+	}
+
+	// opponent must face attacker ( = different directions) before he can be attacked
+	if(attackingStack && attackedStack &&
+		stackFacingRight(attackingStack) == stackFacingRight(attackedStack))
+		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 mutPosToGroup2H[] =
+	{
+		CCreatureAnim::VCMI_2HEX_UP,
+		CCreatureAnim::VCMI_2HEX_UP,
+		CCreatureAnim::VCMI_2HEX_FRONT,
+		CCreatureAnim::VCMI_2HEX_DOWN,
+		CCreatureAnim::VCMI_2HEX_DOWN,
+		CCreatureAnim::VCMI_2HEX_FRONT
+	};
+
+	int revShiftattacker = (attackingStack->side == BattleSide::ATTACKER ? -1 : 1);
+
+	int mutPos = BattleHex::mutualPosition(attackingStackPosBeforeReturn, dest);
+	if(mutPos == -1 && attackingStack->doubleWide())
+	{
+		mutPos = BattleHex::mutualPosition(attackingStackPosBeforeReturn + revShiftattacker, attackedStack->getPosition());
+	}
+	if (mutPos == -1 && attackedStack->doubleWide())
+	{
+		mutPos = BattleHex::mutualPosition(attackingStackPosBeforeReturn, attackedStack->occupiedHex());
+	}
+	if (mutPos == -1 && attackedStack->doubleWide() && attackingStack->doubleWide())
+	{
+		mutPos = BattleHex::mutualPosition(attackingStackPosBeforeReturn + revShiftattacker, attackedStack->occupiedHex());
+	}
+
+
+	switch(mutPos) //attack direction
+	{
+	case 0:
+	case 1:
+	case 2:
+	case 3:
+	case 4:
+	case 5:
+		group = mutPosToGroup[mutPos];
+		if(attackingStack->hasBonusOfType(Bonus::TWO_HEX_ATTACK_BREATH))
+		{
+			CCreatureAnim::EAnimType group2H = mutPosToGroup2H[mutPos];
+			if(myAnim->framesInGroup(group2H)>0)
+				group = group2H;
+		}
+
+		break;
+	default:
+		logGlobal->error("Critical Error! Wrong dest in stackAttacking! dest: %d; attacking stack pos: %d; mutual pos: %d", dest.hex, attackingStackPosBeforeReturn, mutPos);
+		group = CCreatureAnim::ATTACK_FRONT;
+		break;
+	}
+
+	return true;
+}
+
+CMeleeAttackAnimation::CMeleeAttackAnimation(BattleInterface & owner, const CStack * attacker, BattleHex _dest, const CStack * _attacked)
+	: CAttackAnimation(owner, attacker, _dest, _attacked)
+{
+	logAnim->debug("Created melee attack anim for %s", attacker->getName());
+}
+
+CStackMoveAnimation::CStackMoveAnimation(BattleInterface & owner, const CStack * _stack, BattleHex _currentHex):
+	CBattleStackAnimation(owner, _stack),
+	currentHex(_currentHex)
+{
+
+}
+
+bool CMovementAnimation::init()
+{
+	if( !CBattleAnimation::checkInitialConditions() )
+		return false;
+
+	if(!stack || myAnim->isDeadOrDying())
+	{
+		delete this;
+		return false;
+	}
+
+	if(stackAnimation(stack)->framesInGroup(CCreatureAnim::MOVING) == 0 ||
+	   stack->hasBonus(Selector::typeSubtype(Bonus::FLYING, 1)))
+	{
+		//no movement or teleport, end immediately
+		delete this;
+		return false;
+	}
+
+	//reverse unit if necessary
+	if(owner.stacksController->shouldRotate(stack, oldPos, currentHex))
+	{
+		// 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.
+		{
+			owner.stacksController->addNewAnim(new CReverseAnimation(owner, stack, oldPos, true));
+			return false;
+		}
+		else
+		{
+			rotateStack(oldPos);
+		}
+	}
+
+	if(myAnim->getType() != CCreatureAnim::MOVING)
+	{
+		myAnim->setType(CCreatureAnim::MOVING);
+	}
+
+	if (owner.moveSoundHander == -1)
+	{
+		owner.moveSoundHander = CCS->soundh->playSound(battle_sound(stack->getCreature(), move), -1);
+	}
+
+	Point begPosition = owner.stacksController->getStackPositionAtHex(oldPos, stack);
+	Point endPosition = owner.stacksController->getStackPositionAtHex(currentHex, stack);
+
+	timeToMove = AnimationControls::getMovementDuration(stack->getCreature());
+
+	begX = begPosition.x;
+	begY = begPosition.y;
+	progress = 0;
+	distanceX = endPosition.x - begPosition.x;
+	distanceY = endPosition.y - begPosition.y;
+
+	if (stack->hasBonus(Selector::type()(Bonus::FLYING)))
+	{
+		float distance = static_cast<float>(sqrt(distanceX * distanceX + distanceY * distanceY));
+
+		timeToMove *= AnimationControls::getFlightDistance(stack->getCreature()) / distance;
+	}
+
+	return true;
+}
+
+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 );
+
+	CBattleAnimation::nextFrame();
+
+	if(progress >= 1.0)
+	{
+		// Sets the position of the creature animation sprites
+		Point coords = owner.stacksController->getStackPositionAtHex(currentHex, stack);
+		myAnim->pos = coords;
+
+		// true if creature haven't reached the final destination hex
+		if ((curentMoveIndex + 1) < destTiles.size())
+		{
+			// update the next hex field which has to be reached by the stack
+			curentMoveIndex++;
+			oldPos = currentHex;
+			currentHex = destTiles[curentMoveIndex];
+
+			// request re-initialization
+			initialized = false;
+		}
+		else
+			delete this;
+	}
+}
+
+CMovementAnimation::~CMovementAnimation()
+{
+	assert(stack);
+
+	myAnim->pos = owner.stacksController->getStackPositionAtHex(currentHex, stack);
+	owner.stacksController->addNewAnim(new CMovementEndAnimation(owner, stack, currentHex));
+
+	if(owner.moveSoundHander != -1)
+	{
+		CCS->soundh->stopSound(owner.moveSoundHander);
+		owner.moveSoundHander = -1;
+	}
+}
+
+CMovementAnimation::CMovementAnimation(BattleInterface & owner, const CStack *_stack, std::vector<BattleHex> _destTiles, int _distance)
+	: CStackMoveAnimation(owner, _stack, _destTiles.front()),
+	  destTiles(_destTiles),
+	  curentMoveIndex(0),
+	  oldPos(stack->getPosition()),
+	  begX(0), begY(0),
+	  distanceX(0), distanceY(0),
+	  timeToMove(0.0),
+	  progress(0.0)
+{
+	logAnim->debug("Created movement anim for %s", stack->getName());
+}
+
+CMovementEndAnimation::CMovementEndAnimation(BattleInterface & owner, const CStack * _stack, BattleHex destTile)
+: CStackMoveAnimation(owner, _stack, destTile)
+{
+	logAnim->debug("Created movement end anim for %s", stack->getName());
+}
+
+bool CMovementEndAnimation::init()
+{
+	//if( !isEarliest(true) )
+	//	return false;
+
+	if(!stack || myAnim->framesInGroup(CCreatureAnim::MOVE_END) == 0 ||
+		myAnim->isDeadOrDying())
+	{
+		delete this;
+		return false;
+	}
+
+	CCS->soundh->playSound(battle_sound(stack->getCreature(), endMoving));
+
+	myAnim->setType(CCreatureAnim::MOVE_END);
+
+	myAnim->onAnimationReset += [&](){ delete this; };
+
+	return true;
+}
+
+CMovementEndAnimation::~CMovementEndAnimation()
+{
+	if(myAnim->getType() != CCreatureAnim::DEAD)
+		myAnim->setType(CCreatureAnim::HOLDING); //resetting to default
+
+	CCS->curh->show();
+}
+
+CMovementStartAnimation::CMovementStartAnimation(BattleInterface & owner, const CStack * _stack)
+	: CStackMoveAnimation(owner, _stack, _stack->getPosition())
+{
+	logAnim->debug("Created movement start anim for %s", stack->getName());
+}
+
+bool CMovementStartAnimation::init()
+{
+	if( !CBattleAnimation::checkInitialConditions() )
+		return false;
+
+
+	if(!stack || myAnim->isDeadOrDying())
+	{
+		delete this;
+		return false;
+	}
+
+	CCS->soundh->playSound(battle_sound(stack->getCreature(), startMoving));
+	myAnim->setType(CCreatureAnim::MOVE_START);
+	myAnim->onAnimationReset += [&](){ delete this; };
+
+	return true;
+}
+
+CReverseAnimation::CReverseAnimation(BattleInterface & owner, const CStack * stack, BattleHex dest, bool _priority)
+	: CStackMoveAnimation(owner, stack, dest),
+	  priority(_priority)
+{
+	logAnim->debug("Created reverse anim for %s", stack->getName());
+}
+
+bool CReverseAnimation::init()
+{
+	if(myAnim == nullptr || myAnim->isDeadOrDying())
+	{
+		delete this;
+		return false; //there is no such creature
+	}
+
+	if(!priority && !CBattleAnimation::checkInitialConditions())
+		return false;
+
+	if(myAnim->framesInGroup(CCreatureAnim::TURN_L))
+	{
+		myAnim->setType(CCreatureAnim::TURN_L);
+		myAnim->onAnimationReset += std::bind(&CReverseAnimation::setupSecondPart, this);
+	}
+	else
+	{
+		setupSecondPart();
+	}
+	return true;
+}
+
+CReverseAnimation::~CReverseAnimation()
+{
+	if( stack && stack->alive() )//don't do that if stack is dead
+		myAnim->setType(CCreatureAnim::HOLDING);
+}
+
+void CBattleStackAnimation::rotateStack(BattleHex hex)
+{
+	setStackFacingRight(stack, !stackFacingRight(stack));
+
+	stackAnimation(stack)->pos = owner.stacksController->getStackPositionAtHex(hex, stack);
+}
+
+void CReverseAnimation::setupSecondPart()
+{
+	if(!stack)
+	{
+		delete this;
+		return;
+	}
+
+	rotateStack(currentHex);
+
+	if(myAnim->framesInGroup(CCreatureAnim::TURN_R))
+	{
+		myAnim->setType(CCreatureAnim::TURN_R);
+		myAnim->onAnimationReset += [&](){ delete this; };
+	}
+	else
+		delete this;
+}
+
+CRangedAttackAnimation::CRangedAttackAnimation(BattleInterface & owner, const CStack * attacker, BattleHex dest_, const CStack * defender)
+	: CAttackAnimation(owner, attacker, dest_, defender),
+	  projectileEmitted(false)
+{
+	logAnim->info("Ranged attack animation created");
+}
+
+bool CRangedAttackAnimation::init()
+{
+	if( !CAttackAnimation::checkInitialConditions() )
+		return false;
+
+	assert(attackingStack);
+	assert(!myAnim->isDeadOrDying());
+
+	if(!attackingStack || myAnim->isDeadOrDying())
+	{
+		//FIXME: how is this possible?
+		logAnim->warn("Shooting animation has not started yet but attacker is dead! Aborting...");
+		delete this;
+		return false;
+	}
+
+	//reverse unit if necessary
+	if (attackingStack && attackedStack && owner.getCurrentPlayerInterface()->cb->isToReverse(attackingStack->getPosition(), attackedStack->getPosition(), stackFacingRight(attackingStack), attackingStack->doubleWide(), stackFacingRight(attackedStack)))
+	{
+		owner.stacksController->addNewAnim(new CReverseAnimation(owner, attackingStack, attackingStack->getPosition(), true));
+		return false;
+	}
+
+	logAnim->info("Ranged attack animation initialized");
+	setAnimationGroup();
+	initializeProjectile();
+	shooting = true;
+	return true;
+}
+
+void CRangedAttackAnimation::setAnimationGroup()
+{
+	Point shooterPos = stackAnimation(attackingStack)->pos.topLeft();
+	Point shotTarget = owner.stacksController->getStackPositionAtHex(dest, attackedStack);
+
+	//maximal angle in radians between straight horizontal line and shooting line for which shot is considered to be straight (absoulte value)
+	static const double straightAngle = 0.2;
+
+	double projectileAngle = -atan2(shotTarget.y - shooterPos.y, std::abs(shotTarget.x - shooterPos.x));
+
+	// Calculate projectile start position. Offsets are read out of the CRANIM.TXT.
+	if (projectileAngle > straightAngle)
+		group = getUpwardsGroup();
+	else if (projectileAngle < -straightAngle)
+		group = getDownwardsGroup();
+	else
+		group = getForwardGroup();
+}
+
+void CRangedAttackAnimation::initializeProjectile()
+{
+	const CCreature *shooterInfo = getCreature();
+	Point shotTarget = owner.stacksController->getStackPositionAtHex(dest, attackedStack) + Point(225, 225);
+	Point shotOrigin = stackAnimation(attackingStack)->pos.topLeft() + Point(222, 265);
+	int multiplier = stackFacingRight(attackingStack) ? 1 : -1;
+
+	if (group == getUpwardsGroup())
+	{
+		shotOrigin.x += ( -25 + shooterInfo->animation.upperRightMissleOffsetX ) * multiplier;
+		shotOrigin.y += shooterInfo->animation.upperRightMissleOffsetY;
+	}
+	else if (group == getDownwardsGroup())
+	{
+		shotOrigin.x += ( -25 + shooterInfo->animation.lowerRightMissleOffsetX ) * multiplier;
+		shotOrigin.y += shooterInfo->animation.lowerRightMissleOffsetY;
+	}
+	else if (group == getForwardGroup())
+	{
+		shotOrigin.x += ( -25 + shooterInfo->animation.rightMissleOffsetX ) * multiplier;
+		shotOrigin.y += shooterInfo->animation.rightMissleOffsetY;
+	}
+	else
+	{
+		assert(0);
+	}
+
+	createProjectile(shotOrigin, shotTarget);
+}
+
+void CRangedAttackAnimation::emitProjectile()
+{
+	logAnim->info("Ranged attack projectile emitted");
+	owner.projectilesController->emitStackProjectile(attackingStack);
+	projectileEmitted = true;
+}
+
+void CRangedAttackAnimation::nextFrame()
+{
+	for(auto & it : pendingAnimations())
+	{
+		CMovementStartAnimation * anim = dynamic_cast<CMovementStartAnimation *>(it);
+		CReverseAnimation * anim2 = dynamic_cast<CReverseAnimation *>(it);
+		if( (anim && anim->stack->ID == stack->ID) || (anim2 && anim2->stack->ID == stack->ID && anim2->priority ) )
+		{
+			assert(0); // FIXME: our stack started to move even though we are playing shooting animation? How?
+			return;
+		}
+	}
+
+	// animation should be paused if there is an active projectile
+	if (projectileEmitted)
+	{
+		if (owner.projectilesController->hasActiveProjectile(attackingStack))
+			stackAnimation(attackingStack)->pause();
+		else
+			stackAnimation(attackingStack)->play();
+	}
+
+	CAttackAnimation::nextFrame();
+
+	if (!projectileEmitted)
+	{
+		logAnim->info("Ranged attack executing, %d / %d / %d",
+					  stackAnimation(attackingStack)->getCurrentFrame(),
+					  getAttackClimaxFrame(),
+					  stackAnimation(attackingStack)->framesInGroup(group));
+
+		// emit projectile once animation playback reached "climax" frame
+		if ( stackAnimation(attackingStack)->getCurrentFrame() >= getAttackClimaxFrame() )
+		{
+			emitProjectile();
+			stackAnimation(attackingStack)->pause();
+			return;
+		}
+	}
+}
+
+CRangedAttackAnimation::~CRangedAttackAnimation()
+{
+	logAnim->info("Ranged attack animation is over");
+	//FIXME: this assert triggers under some unclear, rare conditions. Possibly - if game window is inactive and/or in foreground/minimized?
+	assert(!owner.projectilesController->hasActiveProjectile(attackingStack));
+	assert(projectileEmitted);
+
+	// FIXME: is this possible? Animation is over but we're yet to fire projectile?
+	if (!projectileEmitted)
+	{
+		logAnim->warn("Shooting animation has finished but projectile was not emitted! Emitting it now...");
+		emitProjectile();
+	}
+}
+
+CShootingAnimation::CShootingAnimation(BattleInterface & owner, const CStack * attacker, BattleHex _dest, const CStack * _attacked)
+	: CRangedAttackAnimation(owner, attacker, _dest, _attacked)
+{
+	logAnim->debug("Created shooting anim for %s", stack->getName());
+}
+
+void CShootingAnimation::createProjectile(const Point & from, const Point & dest) const
+{
+	owner.projectilesController->createProjectile(attackingStack, from, dest);
+}
+
+uint32_t CShootingAnimation::getAttackClimaxFrame() const
+{
+	const CCreature *shooterInfo = getCreature();
+	return shooterInfo->animation.attackClimaxFrame;
+}
+
+CCreatureAnim::EAnimType CShootingAnimation::getUpwardsGroup() const
+{
+	return CCreatureAnim::SHOOT_UP;
+}
+
+CCreatureAnim::EAnimType CShootingAnimation::getForwardGroup() const
+{
+	return CCreatureAnim::SHOOT_FRONT;
+}
+
+CCreatureAnim::EAnimType CShootingAnimation::getDownwardsGroup() const
+{
+	return CCreatureAnim::SHOOT_DOWN;
+}
+
+CCatapultAnimation::CCatapultAnimation(BattleInterface & owner, const CStack * attacker, BattleHex _dest, const CStack * _attacked, int _catapultDmg)
+	: CShootingAnimation(owner, attacker, _dest, _attacked),
+	catapultDamage(_catapultDmg),
+	explosionEmitted(false)
+{
+	logAnim->debug("Created shooting anim for %s", stack->getName());
+}
+
+void CCatapultAnimation::nextFrame()
+{
+	CShootingAnimation::nextFrame();
+
+	if ( explosionEmitted)
+		return;
+
+	if ( !projectileEmitted)
+		return;
+
+	if (owner.projectilesController->hasActiveProjectile(attackingStack))
+		return;
+
+	explosionEmitted = true;
+	Point shotTarget = owner.stacksController->getStackPositionAtHex(dest, attackedStack) + Point(225, 225) - Point(126, 105);
+
+	if(catapultDamage > 0)
+		owner.stacksController->addNewAnim( new CPointEffectAnimation(owner, soundBase::WALLHIT, "SGEXPL.DEF", shotTarget));
+	else
+		owner.stacksController->addNewAnim( new CPointEffectAnimation(owner, soundBase::WALLMISS, "CSGRCK.DEF", shotTarget));
+}
+
+void CCatapultAnimation::createProjectile(const Point & from, const Point & dest) const
+{
+	owner.projectilesController->createCatapultProjectile(attackingStack, from, dest);
+}
+
+
+CCastAnimation::CCastAnimation(BattleInterface & owner, const CStack * attacker, BattleHex dest_, const CStack * defender, const CSpell * spell)
+	: CRangedAttackAnimation(owner, attacker, dest_, defender),
+	  spell(spell)
+{
+	assert(dest.isValid());// FIXME: when?
+
+	if(!dest_.isValid() && defender)
+		dest = defender->getPosition();
+}
+
+CCreatureAnim::EAnimType CCastAnimation::findValidGroup( const std::vector<CCreatureAnim::EAnimType> candidates ) const
+{
+	for ( auto group : candidates)
+	{
+		if(myAnim->framesInGroup(group) > 0)
+			return group;
+	}
+
+	assert(0);
+	return CCreatureAnim::HOLDING;
+}
+
+CCreatureAnim::EAnimType CCastAnimation::getUpwardsGroup() const
+{
+	return findValidGroup({
+		CCreatureAnim::VCMI_CAST_UP,
+		CCreatureAnim::CAST_UP,
+		CCreatureAnim::SHOOT_UP,
+		CCreatureAnim::ATTACK_UP
+	});
+}
+
+CCreatureAnim::EAnimType CCastAnimation::getForwardGroup() const
+{
+	return findValidGroup({
+		CCreatureAnim::VCMI_CAST_FRONT,
+		CCreatureAnim::CAST_FRONT,
+		CCreatureAnim::SHOOT_FRONT,
+		CCreatureAnim::ATTACK_FRONT
+	});
+}
+
+CCreatureAnim::EAnimType CCastAnimation::getDownwardsGroup() const
+{
+	return findValidGroup({
+		CCreatureAnim::VCMI_CAST_DOWN,
+		CCreatureAnim::CAST_DOWN,
+		CCreatureAnim::SHOOT_DOWN,
+		CCreatureAnim::ATTACK_DOWN
+	});
+}
+
+void CCastAnimation::createProjectile(const Point & from, const Point & dest) const
+{
+	if (!spell->animationInfo.projectile.empty())
+		owner.projectilesController->createSpellProjectile(attackingStack, from, dest, spell);
+}
+
+uint32_t CCastAnimation::getAttackClimaxFrame() const
+{
+	//FIXME: allow defining this parameter in config file, separately from attackClimaxFrame of missile attacks
+	uint32_t maxFrames = stackAnimation(attackingStack)->framesInGroup(group);
+
+	if (maxFrames > 2)
+		return maxFrames - 2;
+	return 0;
+}
+
+CPointEffectAnimation::CPointEffectAnimation(BattleInterface & owner, soundBase::soundID sound, std::string animationName, int effects):
+	CBattleAnimation(owner),
+	animation(std::make_shared<CAnimation>(animationName)),
+	sound(sound),
+	effectFlags(effects),
+	soundPlayed(false),
+	soundFinished(false),
+	effectFinished(false)
+{
+}
+
+CPointEffectAnimation::CPointEffectAnimation(BattleInterface & owner, soundBase::soundID sound, std::string animationName, std::vector<BattleHex> hex, int effects):
+	CPointEffectAnimation(owner, sound, animationName, effects)
+{
+	battlehexes = hex;
+}
+
+CPointEffectAnimation::CPointEffectAnimation(BattleInterface & owner, soundBase::soundID sound, std::string animationName, BattleHex hex, int effects):
+	CPointEffectAnimation(owner, sound, animationName, effects)
+{
+	assert(hex.isValid());
+	battlehexes.push_back(hex);
+}
+
+CPointEffectAnimation::CPointEffectAnimation(BattleInterface & owner, soundBase::soundID sound, std::string animationName, std::vector<Point> pos, int effects):
+	CPointEffectAnimation(owner, sound, animationName, effects)
+{
+	positions = pos;
+}
+
+CPointEffectAnimation::CPointEffectAnimation(BattleInterface & owner, soundBase::soundID sound, std::string animationName, Point pos, int effects):
+	CPointEffectAnimation(owner, sound, animationName, effects)
+{
+	positions.push_back(pos);
+}
+
+CPointEffectAnimation::CPointEffectAnimation(BattleInterface & owner, soundBase::soundID sound, std::string animationName, Point pos, BattleHex hex,   int effects):
+	CPointEffectAnimation(owner, sound, animationName, effects)
+{
+	assert(hex.isValid());
+	battlehexes.push_back(hex);
+	positions.push_back(pos);
+}
+
+bool CPointEffectAnimation::init()
+{
+	if(!CBattleAnimation::checkInitialConditions())
+		return false;
+
+	animation->preload();
+
+	auto first = animation->getImage(0, 0, true);
+	if(!first)
+	{
+		delete this;
+		return false;
+	}
+
+	if (screenFill())
+	{
+		for(int i=0; i * first->width() < owner.pos.w ; ++i)
+			for(int j=0; j * first->height() < owner.pos.h ; ++j)
+				positions.push_back(Point( owner.pos.x + i * first->width(), owner.pos.y + j * first->height()));
+	}
+
+	BattleEffect be;
+	be.effectID = ID;
+	be.animation = animation;
+	be.currentFrame = 0;
+
+	for (size_t i = 0; i < std::max(battlehexes.size(), positions.size()); ++i)
+	{
+		bool hasTile = i < battlehexes.size();
+		bool hasPosition = i < positions.size();
+
+		if (hasTile && !forceOnTop())
+			be.position = battlehexes[i];
+		else
+			be.position = BattleHex::INVALID;
+
+		if (hasPosition)
+		{
+			be.x = positions[i].x;
+			be.y = positions[i].y;
+		}
+		else
+		{
+			const CStack * destStack = owner.getCurrentPlayerInterface()->cb->battleGetStackByPos(battlehexes[i], false);
+			Rect tilePos = owner.fieldController->hexPositionAbsolute(battlehexes[i]);
+
+			be.x = tilePos.x + tilePos.w/2 - first->width()/2;
+
+			if(destStack && destStack->doubleWide()) // Correction for 2-hex creatures.
+				be.x += (destStack->side == BattleSide::ATTACKER ? -1 : 1)*tilePos.w/2;
+
+			if (alignToBottom())
+				be.y = tilePos.y + tilePos.h - first->height();
+			else
+				be.y = tilePos.y - first->height()/2;
+		}
+		owner.effectsController->battleEffects.push_back(be);
+	}
+	return true;
+}
+
+void CPointEffectAnimation::nextFrame()
+{
+	playSound();
+	playEffect();
+
+	if (soundFinished && effectFinished)
+	{
+		//remove visual effect itself only if sound has finished as well - necessary for obstacles like force field
+		clearEffect();
+		delete this;
+	}
+}
+
+bool CPointEffectAnimation::alignToBottom() const
+{
+	return effectFlags & ALIGN_TO_BOTTOM;
+}
+
+bool CPointEffectAnimation::waitForSound() const
+{
+	return effectFlags & WAIT_FOR_SOUND;
+}
+
+bool CPointEffectAnimation::forceOnTop() const
+{
+	return effectFlags & FORCE_ON_TOP;
+}
+
+bool CPointEffectAnimation::screenFill() const
+{
+	return effectFlags & SCREEN_FILL;
+}
+
+void CPointEffectAnimation::onEffectFinished()
+{
+	effectFinished = true;
+}
+
+void CPointEffectAnimation::onSoundFinished()
+{
+	soundFinished = true;
+}
+
+void CPointEffectAnimation::playSound()
+{
+	if (soundPlayed)
+		return;
+
+	soundPlayed = true;
+	if (sound == soundBase::invalid)
+	{
+		onSoundFinished();
+		return;
+	}
+
+	int channel = CCS->soundh->playSound(sound);
+
+	if (!waitForSound() || channel == -1)
+		onSoundFinished();
+	else
+		CCS->soundh->setCallback(channel, [&](){ onSoundFinished(); });
+}
+
+void CPointEffectAnimation::playEffect()
+{
+	if ( effectFinished )
+		return;
+
+	for(auto & elem : owner.effectsController->battleEffects)
+	{
+		if(elem.effectID == ID)
+		{
+			elem.currentFrame += AnimationControls::getSpellEffectSpeed() * GH.mainFPSmng->getElapsedMilliseconds() / 1000;
+
+			if(elem.currentFrame >= elem.animation->size())
+			{
+				elem.currentFrame = elem.animation->size() - 1;
+				onEffectFinished();
+				break;
+			}
+		}
+	}
+}
+
+void CPointEffectAnimation::clearEffect()
+{
+	auto & effects = owner.effectsController->battleEffects;
+
+	vstd::erase_if(effects, [&](const BattleEffect & effect){
+		return effect.effectID == ID;
+	});
+}
+
+CPointEffectAnimation::~CPointEffectAnimation()
+{
+	assert(effectFinished);
+	assert(soundFinished);
+}
+
+CWaitingAnimation::CWaitingAnimation(BattleInterface & owner):
+	CBattleAnimation(owner)
+{}
+
+void CWaitingAnimation::nextFrame()
+{
+	// initialization conditions fulfilled, delay is over
+	delete this;
+}
+
+CWaitingProjectileAnimation::CWaitingProjectileAnimation(BattleInterface & owner, const CStack * shooter):
+	CWaitingAnimation(owner),
+	shooter(shooter)
+{}
+
+bool CWaitingProjectileAnimation::init()
+{
+	for(auto & elem : pendingAnimations())
+	{
+		auto * attackAnim = dynamic_cast<CRangedAttackAnimation *>(elem);
+
+		if( attackAnim && shooter && attackAnim->stack->ID == shooter->ID && !attackAnim->isInitialized() )
+		{
+			// there is ongoing ranged attack that involves our stack, but projectile was not created yet
+			return false;
+		}
+	}
+
+	if(owner.projectilesController->hasActiveProjectile(shooter))
+		return false;
+
+	return true;
+}

+ 350 - 0
client/battle/BattleAnimationClasses.h

@@ -0,0 +1,350 @@
+/*
+ * BattleAnimations.h, part of VCMI engine
+ *
+ * Authors: listed in file AUTHORS in main folder
+ *
+ * License: GNU General Public License v2.0 or later
+ * Full text of license available in license.txt file, in main folder
+ *
+ */
+#pragma once
+
+#include "../../lib/battle/BattleHex.h"
+#include "../../lib/CSoundBase.h"
+#include "../widgets/Images.h"
+
+VCMI_LIB_NAMESPACE_BEGIN
+
+class CStack;
+
+VCMI_LIB_NAMESPACE_END
+
+class BattleInterface;
+class CreatureAnimation;
+class CBattleAnimation;
+struct CatapultProjectileInfo;
+struct StackAttackedInfo;
+
+/// Base class of battle animations
+class CBattleAnimation
+{
+
+protected:
+	BattleInterface & owner;
+	bool initialized;
+
+	std::vector<CBattleAnimation *> & pendingAnimations();
+	std::shared_ptr<CreatureAnimation> stackAnimation(const CStack * stack) const;
+	bool stackFacingRight(const CStack * stack);
+	void setStackFacingRight(const CStack * stack, bool facingRight);
+
+	virtual bool init() = 0; //to be called - if returned false, call again until returns true
+	bool checkInitialConditions(); //determines if this animation is earliest of all
+
+public:
+	ui32 ID; //unique identifier
+
+	bool isInitialized();
+	bool tryInitialize();
+	virtual void nextFrame() {} //call every new frame
+	virtual ~CBattleAnimation();
+
+	CBattleAnimation(BattleInterface & owner);
+};
+
+/// Sub-class which is responsible for managing the battle stack animation.
+class CBattleStackAnimation : public CBattleAnimation
+{
+public:
+	std::shared_ptr<CreatureAnimation> myAnim; //animation for our stack, managed by CBattleInterface
+	const CStack * stack; //id of stack whose animation it is
+
+	CBattleStackAnimation(BattleInterface & owner, const CStack * _stack);
+
+	void shiftColor(const ColorShifter * shifter);
+	void rotateStack(BattleHex hex);
+};
+
+/// This class is responsible for managing the battle attack animation
+class CAttackAnimation : public CBattleStackAnimation
+{
+	bool soundPlayed;
+
+protected:
+	BattleHex dest; //attacked hex
+	bool shooting;
+	CCreatureAnim::EAnimType group; //if shooting is true, print this animation group
+	const CStack *attackedStack;
+	const CStack *attackingStack;
+	int attackingStackPosBeforeReturn; //for stacks with return_after_strike feature
+
+	const CCreature * getCreature() const;
+public:
+	void nextFrame() override;
+	bool checkInitialConditions();
+
+	CAttackAnimation(BattleInterface & owner, const CStack *attacker, BattleHex _dest, const CStack *defender);
+	~CAttackAnimation();
+};
+
+/// Animation of a defending unit
+class CDefenceAnimation : public CBattleStackAnimation
+{
+	CCreatureAnim::EAnimType getMyAnimType();
+	std::string getMySound();
+
+	void startAnimation();
+
+	const CStack * attacker; //attacking stack
+	bool rangedAttack; //if true, stack has been attacked by shooting
+	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;
+
+	CDefenceAnimation(StackAttackedInfo _attackedInfo, BattleInterface & owner);
+	~CDefenceAnimation();
+};
+
+class CDummyAnimation : public CBattleAnimation
+{
+private:
+	int counter;
+	int howMany;
+public:
+	bool init() override;
+	void nextFrame() override;
+
+	CDummyAnimation(BattleInterface & owner, int howManyFrames);
+};
+
+/// Hand-to-hand attack
+class CMeleeAttackAnimation : public CAttackAnimation
+{
+public:
+	bool init() override;
+
+	CMeleeAttackAnimation(BattleInterface & owner, const CStack * attacker, BattleHex _dest, const CStack * _attacked);
+};
+
+/// Base class for all animations that play during stack movement
+class CStackMoveAnimation : public CBattleStackAnimation
+{
+public:
+	BattleHex currentHex;
+
+protected:
+	CStackMoveAnimation(BattleInterface & owner, const CStack * _stack, BattleHex _currentHex);
+};
+
+/// Move animation of a creature
+class CMovementAnimation : public CStackMoveAnimation
+{
+private:
+	std::vector<BattleHex> destTiles; //full path, includes already passed hexes
+	ui32 curentMoveIndex; // index of nextHex in destTiles
+
+	BattleHex oldPos; //position of stack before move
+
+	double begX, begY; // starting position
+	double distanceX, distanceY; // full movement distance, may be negative if creture moves topleft
+
+	double timeToMove; // full length of movement animation
+	double progress; // range 0 -> 1, indicates move progrees. 0 = movement starts, 1 = move ends
+
+public:
+	bool init() override;
+	void nextFrame() override;
+
+	CMovementAnimation(BattleInterface & owner, const CStack *_stack, std::vector<BattleHex> _destTiles, int _distance);
+	~CMovementAnimation();
+};
+
+/// Move end animation of a creature
+class CMovementEndAnimation : public CStackMoveAnimation
+{
+public:
+	bool init() override;
+
+	CMovementEndAnimation(BattleInterface & owner, const CStack * _stack, BattleHex destTile);
+	~CMovementEndAnimation();
+};
+
+/// Move start animation of a creature
+class CMovementStartAnimation : public CStackMoveAnimation
+{
+public:
+	bool init() override;
+
+	CMovementStartAnimation(BattleInterface & owner, const CStack * _stack);
+};
+
+/// Class responsible for animation of stack chaning direction (left <-> right)
+class CReverseAnimation : public CStackMoveAnimation
+{
+public:
+	bool priority; //true - high, false - low
+	bool init() override;
+
+	void setupSecondPart();
+
+	CReverseAnimation(BattleInterface & owner, const CStack * stack, BattleHex dest, bool _priority);
+	~CReverseAnimation();
+};
+
+class CRangedAttackAnimation : public CAttackAnimation
+{
+
+	void setAnimationGroup();
+	void initializeProjectile();
+	void emitProjectile();
+	void emitExplosion();
+
+protected:
+	bool projectileEmitted;
+
+	virtual CCreatureAnim::EAnimType getUpwardsGroup() const = 0;
+	virtual CCreatureAnim::EAnimType getForwardGroup() const = 0;
+	virtual CCreatureAnim::EAnimType getDownwardsGroup() const = 0;
+
+	virtual void createProjectile(const Point & from, const Point & dest) const = 0;
+	virtual uint32_t getAttackClimaxFrame() const = 0;
+
+public:
+	CRangedAttackAnimation(BattleInterface & owner, const CStack * attacker, BattleHex dest, const CStack * defender);
+	~CRangedAttackAnimation();
+
+	bool init() override;
+	void nextFrame() override;
+};
+
+/// Shooting attack
+class CShootingAnimation : public CRangedAttackAnimation
+{
+	CCreatureAnim::EAnimType getUpwardsGroup() const override;
+	CCreatureAnim::EAnimType getForwardGroup() const override;
+	CCreatureAnim::EAnimType getDownwardsGroup() const override;
+
+	void createProjectile(const Point & from, const Point & dest) const override;
+	uint32_t getAttackClimaxFrame() const override;
+
+public:
+	CShootingAnimation(BattleInterface & owner, const CStack * attacker, BattleHex dest, const CStack * defender);
+
+};
+
+/// Catapult attack
+class CCatapultAnimation : public CShootingAnimation
+{
+private:
+	bool explosionEmitted;
+	int catapultDamage;
+
+public:
+	CCatapultAnimation(BattleInterface & owner, const CStack * attacker, BattleHex dest, const CStack * defender, int _catapultDmg = 0);
+
+	void createProjectile(const Point & from, const Point & dest) const override;
+	void nextFrame() override;
+};
+
+class CCastAnimation : public CRangedAttackAnimation
+{
+	const CSpell * spell;
+
+	CCreatureAnim::EAnimType findValidGroup( const std::vector<CCreatureAnim::EAnimType> candidates ) const;
+	CCreatureAnim::EAnimType getUpwardsGroup() const override;
+	CCreatureAnim::EAnimType getForwardGroup() const override;
+	CCreatureAnim::EAnimType getDownwardsGroup() const override;
+
+	void createProjectile(const Point & from, const Point & dest) const override;
+	uint32_t getAttackClimaxFrame() const override;
+
+public:
+	CCastAnimation(BattleInterface & owner, const CStack * attacker, BattleHex dest_, const CStack * defender, const CSpell * spell);
+};
+
+struct CPointEffectParameters
+{
+	std::vector<Point> positions;
+	std::vector<BattleHex> tiles;
+	std::string animation;
+
+	soundBase::soundID sound = soundBase::invalid;
+	BattleHex boundHex = BattleHex::INVALID;
+	bool aligntoBottom = false;
+	bool waitForSound = false;
+	bool screenFill = false;
+};
+
+/// Class that plays effect at one or more positions along with (single) sound effect
+class CPointEffectAnimation : public CBattleAnimation
+{
+	soundBase::soundID sound;
+	bool soundPlayed;
+	bool soundFinished;
+	bool effectFinished;
+	int effectFlags;
+
+	std::shared_ptr<CAnimation>	animation;
+	std::vector<Point> positions;
+	std::vector<BattleHex> battlehexes;
+
+	bool alignToBottom() const;
+	bool waitForSound() const;
+	bool forceOnTop() const;
+	bool screenFill() const;
+
+	void onEffectFinished();
+	void onSoundFinished();
+	void clearEffect();
+
+	void playSound();
+	void playEffect();
+
+public:
+	enum EEffectFlags
+	{
+		ALIGN_TO_BOTTOM = 1,
+		WAIT_FOR_SOUND  = 2,
+		FORCE_ON_TOP    = 4,
+		SCREEN_FILL     = 8,
+	};
+
+	/// Create animation with screen-wide effect
+	CPointEffectAnimation(BattleInterface & owner, soundBase::soundID sound, std::string animationName, int effects = 0);
+
+	/// Create animation positioned at point(s). Note that positions must be are absolute, including battleint position offset
+	CPointEffectAnimation(BattleInterface & owner, soundBase::soundID sound, std::string animationName, Point pos                 , int effects = 0);
+	CPointEffectAnimation(BattleInterface & owner, soundBase::soundID sound, std::string animationName, std::vector<Point> pos    , int effects = 0);
+
+	/// Create animation positioned at certain hex(es)
+	CPointEffectAnimation(BattleInterface & owner, soundBase::soundID sound, std::string animationName, BattleHex hex             , int effects = 0);
+	CPointEffectAnimation(BattleInterface & owner, soundBase::soundID sound, std::string animationName, std::vector<BattleHex> hex, int effects = 0);
+
+	CPointEffectAnimation(BattleInterface & owner, soundBase::soundID sound, std::string animationName, Point pos, BattleHex hex,   int effects = 0);
+	 ~CPointEffectAnimation();
+
+	bool init() override;
+	void nextFrame() override;
+};
+
+/// Base class (e.g. for use in dynamic_cast's) for "animations" that wait for certain event
+class CWaitingAnimation : public CBattleAnimation
+{
+protected:
+	CWaitingAnimation(BattleInterface & owner);
+public:
+	void nextFrame() override;
+};
+
+/// Class that waits till projectile of certain shooter hits a target
+class CWaitingProjectileAnimation : public CWaitingAnimation
+{
+	const CStack * shooter;
+public:
+	CWaitingProjectileAnimation(BattleInterface & owner, const CStack * shooter);
+
+	bool init() override;
+};

+ 328 - 0
client/battle/BattleControlPanel.cpp

@@ -0,0 +1,328 @@
+/*
+ * BattleControlPanel.cpp, part of VCMI engine
+ *
+ * Authors: listed in file AUTHORS in main folder
+ *
+ * License: GNU General Public License v2.0 or later
+ * Full text of license available in license.txt file, in main folder
+ *
+ */
+#include "StdInc.h"
+#include "BattleControlPanel.h"
+
+#include "BattleInterface.h"
+#include "BattleInterfaceClasses.h"
+#include "BattleStacksController.h"
+#include "BattleActionsController.h"
+
+#include "../CGameInfo.h"
+#include "../CPlayerInterface.h"
+#include "../gui/CCursorHandler.h"
+#include "../gui/CGuiHandler.h"
+#include "../windows/CSpellWindow.h"
+#include "../widgets/Buttons.h"
+#include "../widgets/Images.h"
+
+#include "../../CCallback.h"
+#include "../../lib/CGeneralTextHandler.h"
+#include "../../lib/mapObjects/CGHeroInstance.h"
+#include "../../lib/CStack.h"
+#include "../../lib/CConfigHandler.h"
+
+BattleControlPanel::BattleControlPanel(BattleInterface & owner, const Point & position):
+	owner(owner)
+{
+	OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
+	pos += position;
+
+	//preparing buttons and console
+	bOptions = std::make_shared<CButton>    (Point(  3,  5), "icm003.def", CGI->generaltexth->zelp[381], std::bind(&BattleControlPanel::bOptionsf,this), SDLK_o);
+	bSurrender = std::make_shared<CButton>  (Point( 54,  5), "icm001.def", CGI->generaltexth->zelp[379], std::bind(&BattleControlPanel::bSurrenderf,this), SDLK_s);
+	bFlee = std::make_shared<CButton>       (Point(105,  5), "icm002.def", CGI->generaltexth->zelp[380], std::bind(&BattleControlPanel::bFleef,this), SDLK_r);
+	bAutofight = std::make_shared<CButton>  (Point(157,  5), "icm004.def", CGI->generaltexth->zelp[382], std::bind(&BattleControlPanel::bAutofightf,this), SDLK_a);
+	bSpell = std::make_shared<CButton>      (Point(645,  5), "icm005.def", CGI->generaltexth->zelp[385], std::bind(&BattleControlPanel::bSpellf,this), SDLK_c);
+	bWait = std::make_shared<CButton>       (Point(696,  5), "icm006.def", CGI->generaltexth->zelp[386], std::bind(&BattleControlPanel::bWaitf,this), SDLK_w);
+	bDefence = std::make_shared<CButton>    (Point(747,  5), "icm007.def", CGI->generaltexth->zelp[387], std::bind(&BattleControlPanel::bDefencef,this), SDLK_d);
+	bConsoleUp = std::make_shared<CButton>  (Point(624,  5), "ComSlide.def", std::make_pair("", ""),     std::bind(&BattleControlPanel::bConsoleUpf,this), SDLK_UP);
+	bConsoleDown = std::make_shared<CButton>(Point(624, 24), "ComSlide.def", std::make_pair("", ""),     std::bind(&BattleControlPanel::bConsoleDownf,this), SDLK_DOWN);
+
+	bDefence->assignedKeys.insert(SDLK_SPACE);
+	bConsoleUp->setImageOrder(0, 1, 0, 0);
+	bConsoleDown->setImageOrder(2, 3, 2, 2);
+
+	console = std::make_shared<BattleConsole>(Rect(211, 4, 406,38));
+	GH.statusbar = console;
+
+	if ( owner.tacticsMode )
+		tacticPhaseStarted();
+	else
+		tacticPhaseEnded();
+}
+
+void BattleControlPanel::show(SDL_Surface * to)
+{
+	//show menu before all other elements to keep it in background
+	menu->show(to);
+	CIntObject::show(to);
+}
+
+void BattleControlPanel::showAll(SDL_Surface * to)
+{
+	//show menu before all other elements to keep it in background
+	menu->showAll(to);
+	CIntObject::showAll(to);
+}
+
+
+void BattleControlPanel::tacticPhaseStarted()
+{
+	OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
+
+	btactNext = std::make_shared<CButton>(Point(213, 4), "icm011.def", std::make_pair("", ""), [&]() { bTacticNextStack();}, SDLK_SPACE);
+	btactEnd = std::make_shared<CButton>(Point(419,  4), "icm012.def", std::make_pair("", ""),  [&](){ bTacticPhaseEnd();}, SDLK_RETURN);
+	menu = std::make_shared<CPicture>("COPLACBR.BMP", 0, 0);
+	menu->colorize(owner.curInt->playerID);
+	menu->recActions &= ~(SHOWALL | UPDATE);
+}
+void BattleControlPanel::tacticPhaseEnded()
+{
+	OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
+
+	btactNext.reset();
+	btactEnd.reset();
+
+	menu = std::make_shared<CPicture>("CBAR.BMP", 0, 0);
+	menu->colorize(owner.curInt->playerID);
+	menu->recActions &= ~(SHOWALL | UPDATE);
+}
+
+void BattleControlPanel::bOptionsf()
+{
+	if (owner.actionsController->spellcastingModeActive())
+		return;
+
+	CCS->curh->changeGraphic(ECursor::ADVENTURE,0);
+
+	GH.pushIntT<BattleOptionsWindow>(owner);
+}
+
+void BattleControlPanel::bSurrenderf()
+{
+	if (owner.actionsController->spellcastingModeActive())
+		return;
+
+	int cost = owner.curInt->cb->battleGetSurrenderCost();
+	if(cost >= 0)
+	{
+		std::string enemyHeroName = owner.curInt->cb->battleGetEnemyHero().name;
+		if(enemyHeroName.empty())
+		{
+			logGlobal->warn("Surrender performed without enemy hero, should not happen!");
+			enemyHeroName = "#ENEMY#";
+		}
+
+		std::string surrenderMessage = boost::str(boost::format(CGI->generaltexth->allTexts[32]) % enemyHeroName % cost); //%s states: "I will accept your surrender and grant you and your troops safe passage for the price of %d gold."
+		owner.curInt->showYesNoDialog(surrenderMessage, [this](){ reallySurrender(); }, nullptr);
+	}
+}
+
+void BattleControlPanel::bFleef()
+{
+	if (owner.actionsController->spellcastingModeActive())
+		return;
+
+	if ( owner.curInt->cb->battleCanFlee() )
+	{
+		CFunctionList<void()> ony = std::bind(&BattleControlPanel::reallyFlee,this);
+		owner.curInt->showYesNoDialog(CGI->generaltexth->allTexts[28], ony, nullptr); //Are you sure you want to retreat?
+	}
+	else
+	{
+		std::vector<std::shared_ptr<CComponent>> comps;
+		std::string heroName;
+		//calculating fleeing hero's name
+		if (owner.attackingHeroInstance)
+			if (owner.attackingHeroInstance->tempOwner == owner.curInt->cb->getMyColor())
+				heroName = owner.attackingHeroInstance->name;
+		if (owner.defendingHeroInstance)
+			if (owner.defendingHeroInstance->tempOwner == owner.curInt->cb->getMyColor())
+				heroName = owner.defendingHeroInstance->name;
+		//calculating text
+		auto txt = boost::format(CGI->generaltexth->allTexts[340]) % heroName; //The Shackles of War are present.  %s can not retreat!
+
+		//printing message
+		owner.curInt->showInfoDialog(boost::to_string(txt), comps);
+	}
+}
+
+void BattleControlPanel::reallyFlee()
+{
+	owner.giveCommand(EActionType::RETREAT);
+	CCS->curh->changeGraphic(ECursor::ADVENTURE, 0);
+}
+
+void BattleControlPanel::reallySurrender()
+{
+	if (owner.curInt->cb->getResourceAmount(Res::GOLD) < owner.curInt->cb->battleGetSurrenderCost())
+	{
+		owner.curInt->showInfoDialog(CGI->generaltexth->allTexts[29]); //You don't have enough gold!
+	}
+	else
+	{
+		owner.giveCommand(EActionType::SURRENDER);
+		CCS->curh->changeGraphic(ECursor::ADVENTURE, 0);
+	}
+}
+
+void BattleControlPanel::bAutofightf()
+{
+	if (owner.actionsController->spellcastingModeActive())
+		return;
+
+	//Stop auto-fight mode
+	if(owner.curInt->isAutoFightOn)
+	{
+		assert(owner.curInt->autofightingAI);
+		owner.curInt->isAutoFightOn = false;
+		logGlobal->trace("Stopping the autofight...");
+	}
+	else if(!owner.curInt->autofightingAI)
+	{
+		owner.curInt->isAutoFightOn = true;
+		blockUI(true);
+
+		auto ai = CDynLibHandler::getNewBattleAI(settings["server"]["friendlyAI"].String());
+		ai->init(owner.curInt->env, owner.curInt->cb);
+		ai->battleStart(owner.army1, owner.army2, int3(0,0,0), owner.attackingHeroInstance, owner.defendingHeroInstance, owner.curInt->cb->battleGetMySide());
+		owner.curInt->autofightingAI = ai;
+		owner.curInt->cb->registerBattleInterface(ai);
+
+		owner.requestAutofightingAIToTakeAction();
+	}
+}
+
+void BattleControlPanel::bSpellf()
+{
+	if (owner.actionsController->spellcastingModeActive())
+		return;
+
+	if (!owner.myTurn)
+		return;
+
+	auto myHero = owner.currentHero();
+	if(!myHero)
+		return;
+
+	CCS->curh->changeGraphic(ECursor::ADVENTURE,0);
+
+	ESpellCastProblem::ESpellCastProblem spellCastProblem = owner.curInt->cb->battleCanCastSpell(myHero, spells::Mode::HERO);
+
+	if(spellCastProblem == ESpellCastProblem::OK)
+	{
+		GH.pushIntT<CSpellWindow>(myHero, owner.curInt.get());
+	}
+	else if (spellCastProblem == ESpellCastProblem::MAGIC_IS_BLOCKED)
+	{
+		//TODO: move to spell mechanics, add more information to spell cast problem
+		//Handle Orb of Inhibition-like effects -> we want to display dialog with info, why casting is impossible
+		auto blockingBonus = owner.currentHero()->getBonusLocalFirst(Selector::type()(Bonus::BLOCK_ALL_MAGIC));
+		if (!blockingBonus)
+			return;
+
+		if (blockingBonus->source == Bonus::ARTIFACT)
+		{
+			const auto artID = ArtifactID(blockingBonus->sid);
+			//If we have artifact, put name of our hero. Otherwise assume it's the enemy.
+			//TODO check who *really* is source of bonus
+			std::string heroName = myHero->hasArt(artID) ? myHero->name : owner.enemyHero().name;
+
+			//%s wields the %s, an ancient artifact which creates a p dead to all magic.
+			LOCPLINT->showInfoDialog(boost::str(boost::format(CGI->generaltexth->allTexts[683])
+										% heroName % CGI->artifacts()->getByIndex(artID)->getName()));
+		}
+	}
+}
+
+void BattleControlPanel::bWaitf()
+{
+	if (owner.actionsController->spellcastingModeActive())
+		return;
+
+	if (owner.stacksController->getActiveStack() != nullptr)
+		owner.giveCommand(EActionType::WAIT);
+}
+
+void BattleControlPanel::bDefencef()
+{
+	if (owner.actionsController->spellcastingModeActive())
+		return;
+
+	if (owner.stacksController->getActiveStack() != nullptr)
+		owner.giveCommand(EActionType::DEFEND);
+}
+
+void BattleControlPanel::bConsoleUpf()
+{
+	if (owner.actionsController->spellcastingModeActive())
+		return;
+
+	console->scrollUp();
+}
+
+void BattleControlPanel::bConsoleDownf()
+{
+	if (owner.actionsController->spellcastingModeActive())
+		return;
+
+	console->scrollDown();
+}
+
+void BattleControlPanel::bTacticNextStack()
+{
+	owner.tacticNextStack(nullptr);
+}
+
+void BattleControlPanel::bTacticPhaseEnd()
+{
+	owner.tacticPhaseEnd();
+}
+
+void BattleControlPanel::blockUI(bool on)
+{
+	bool canCastSpells = false;
+	auto hero = owner.curInt->cb->battleGetMyHero();
+
+	if(hero)
+	{
+		ESpellCastProblem::ESpellCastProblem spellcastingProblem = owner.curInt->cb->battleCanCastSpell(hero, spells::Mode::HERO);
+
+		//if magic is blocked, we leave button active, so the message can be displayed after button click
+		canCastSpells = spellcastingProblem == ESpellCastProblem::OK || spellcastingProblem == ESpellCastProblem::MAGIC_IS_BLOCKED;
+	}
+
+	bool canWait = owner.stacksController->getActiveStack() ? !owner.stacksController->getActiveStack()->waitedThisTurn : false;
+
+	bOptions->block(on);
+	bFlee->block(on || !owner.curInt->cb->battleCanFlee());
+	bSurrender->block(on || owner.curInt->cb->battleGetSurrenderCost() < 0);
+
+	// block only if during enemy turn and auto-fight is off
+	// otherwise - crash on accessing non-exisiting active stack
+	bAutofight->block(!owner.curInt->isAutoFightOn && !owner.stacksController->getActiveStack());
+
+	if (owner.tacticsMode && btactEnd && btactNext)
+	{
+		btactNext->block(on);
+		btactEnd->block(on);
+	}
+	else
+	{
+		bConsoleUp->block(on);
+		bConsoleDown->block(on);
+	}
+
+
+	bSpell->block(on || owner.tacticsMode || !canCastSpells);
+	bWait->block(on || owner.tacticsMode || !canWait);
+	bDefence->block(on || owner.tacticsMode);
+}

+ 76 - 0
client/battle/BattleControlPanel.h

@@ -0,0 +1,76 @@
+/*
+ * BattleControlPanel.h, part of VCMI engine
+ *
+ * Authors: listed in file AUTHORS in main folder
+ *
+ * License: GNU General Public License v2.0 or later
+ * Full text of license available in license.txt file, in main folder
+ *
+ */
+#pragma once
+
+#include "../gui/CIntObject.h"
+
+VCMI_LIB_NAMESPACE_BEGIN
+class CStack;
+
+VCMI_LIB_NAMESPACE_END
+
+class CButton;
+class BattleInterface;
+class BattleConsole;
+
+/// GUI object that handles functionality of panel at the bottom of combat screen
+class BattleControlPanel : public CIntObject
+{
+	BattleInterface & owner;
+
+	std::shared_ptr<CPicture> menu;
+
+	std::shared_ptr<CButton> bOptions;
+	std::shared_ptr<CButton> bSurrender;
+	std::shared_ptr<CButton> bFlee;
+	std::shared_ptr<CButton> bAutofight;
+	std::shared_ptr<CButton> bSpell;
+	std::shared_ptr<CButton> bWait;
+	std::shared_ptr<CButton> bDefence;
+	std::shared_ptr<CButton> bConsoleUp;
+	std::shared_ptr<CButton> bConsoleDown;
+	std::shared_ptr<CButton> btactNext;
+	std::shared_ptr<CButton> btactEnd;
+
+	/// button press handling functions
+	void bOptionsf();
+	void bSurrenderf();
+	void bFleef();
+	void bAutofightf();
+	void bSpellf();
+	void bWaitf();
+	void bDefencef();
+	void bConsoleUpf();
+	void bConsoleDownf();
+	void bTacticNextStack();
+	void bTacticPhaseEnd();
+
+	/// functions for handling actions after they were confirmed by popup window
+	void reallyFlee();
+	void reallySurrender();
+
+public:
+	std::shared_ptr<BattleConsole> console;
+
+	/// block all UI elements when player is not allowed to act, e.g. during enemy turn
+	void blockUI(bool on);
+
+	void show(SDL_Surface * to) override;
+	void showAll(SDL_Surface * to) override;
+
+	/// Toggle UI to displaying tactics phase
+	void tacticPhaseStarted();
+
+	/// Toggle UI to displaying battle log in place of tactics UI
+	void tacticPhaseEnded();
+
+	BattleControlPanel(BattleInterface & owner, const Point & position);
+};
+

+ 140 - 0
client/battle/BattleEffectsController.cpp

@@ -0,0 +1,140 @@
+/*
+ * BattleEffectsController.cpp, part of VCMI engine
+ *
+ * Authors: listed in file AUTHORS in main folder
+ *
+ * License: GNU General Public License v2.0 or later
+ * Full text of license available in license.txt file, in main folder
+ *
+ */
+#include "StdInc.h"
+#include "BattleEffectsController.h"
+
+#include "BattleAnimationClasses.h"
+#include "BattleControlPanel.h"
+#include "BattleInterface.h"
+#include "BattleInterfaceClasses.h"
+#include "BattleFieldController.h"
+#include "BattleStacksController.h"
+#include "BattleRenderer.h"
+
+#include "../CMusicHandler.h"
+#include "../CGameInfo.h"
+#include "../CPlayerInterface.h"
+#include "../gui/CAnimation.h"
+#include "../gui/Canvas.h"
+
+#include "../../CCallback.h"
+#include "../../lib/battle/BattleAction.h"
+#include "../../lib/NetPacks.h"
+#include "../../lib/CStack.h"
+#include "../../lib/IGameEventsReceiver.h"
+#include "../../lib/CGeneralTextHandler.h"
+
+BattleEffectsController::BattleEffectsController(BattleInterface & owner):
+	owner(owner)
+{}
+
+void BattleEffectsController::displayEffect(EBattleEffect::EBattleEffect effect, const BattleHex & destTile)
+{
+	displayEffect(effect, soundBase::invalid, destTile);
+}
+
+void BattleEffectsController::displayEffect(EBattleEffect::EBattleEffect effect, uint32_t soundID, const BattleHex & destTile)
+{
+	std::string customAnim = graphics->battleACToDef[effect][0];
+
+	owner.stacksController->addNewAnim(new CPointEffectAnimation(owner, soundBase::soundID(soundID), customAnim, destTile));
+}
+
+void BattleEffectsController::displayCustomEffects(const std::vector<CustomEffectInfo> & customEffects)
+{
+	for(const CustomEffectInfo & one : customEffects)
+	{
+		const CStack * s = owner.curInt->cb->battleGetStackByID(one.stack, false);
+
+		assert(s);
+		assert(one.effect != 0);
+
+		displayEffect(EBattleEffect::EBattleEffect(one.effect), soundBase::soundID(one.sound), s->getPosition());
+	}
+}
+
+void BattleEffectsController::battleTriggerEffect(const BattleTriggerEffect & bte)
+{
+	const CStack * stack = owner.curInt->cb->battleGetStackByID(bte.stackID);
+	if(!stack)
+	{
+		logGlobal->error("Invalid stack ID %d", bte.stackID);
+		return;
+	}
+	//don't show animation when no HP is regenerated
+	switch(bte.effect)
+	{
+		//TODO: move to bonus type handler
+		case Bonus::HP_REGENERATION:
+			displayEffect(EBattleEffect::REGENERATION, soundBase::REGENER, stack->getPosition());
+			break;
+		case Bonus::MANA_DRAIN:
+			displayEffect(EBattleEffect::MANA_DRAIN, soundBase::MANADRAI, stack->getPosition());
+			break;
+		case Bonus::POISON:
+			displayEffect(EBattleEffect::POISON, soundBase::POISON, stack->getPosition());
+			break;
+		case Bonus::FEAR:
+			displayEffect(EBattleEffect::FEAR, soundBase::FEAR, stack->getPosition());
+			break;
+		case Bonus::MORALE:
+		{
+			std::string hlp = CGI->generaltexth->allTexts[33];
+			boost::algorithm::replace_first(hlp,"%s",(stack->getName()));
+			displayEffect(EBattleEffect::GOOD_MORALE, soundBase::GOODMRLE, stack->getPosition());
+			owner.controlPanel->console->addText(hlp);
+			break;
+		}
+		default:
+			return;
+	}
+	//waitForAnims(); //fixme: freezes game :?
+}
+
+void BattleEffectsController::startAction(const BattleAction* action)
+{
+	const CStack *stack = owner.curInt->cb->battleGetStackByID(action->stackNumber);
+
+	switch(action->actionType)
+	{
+	case EActionType::WAIT:
+		owner.controlPanel->console->addText(stack->formatGeneralMessage(136));
+		break;
+	case EActionType::BAD_MORALE:
+		owner.controlPanel->console->addText(stack->formatGeneralMessage(-34));
+		displayEffect(EBattleEffect::BAD_MORALE, soundBase::BADMRLE, stack->getPosition());
+		break;
+	}
+
+	//displaying special abilities
+	auto actionTarget = action->getTarget(owner.curInt->cb.get());
+	switch(action->actionType)
+	{
+		case EActionType::STACK_HEAL:
+			displayEffect(EBattleEffect::REGENERATION, soundBase::REGENER, actionTarget.at(0).hexValue);
+			break;
+	}
+}
+
+void BattleEffectsController::collectRenderableObjects(BattleRenderer & renderer)
+{
+	for (auto & elem : battleEffects)
+	{
+		renderer.insert( EBattleFieldLayer::EFFECTS, elem.position, [&elem](BattleRenderer::RendererRef canvas)
+		{
+			int currentFrame = static_cast<int>(floor(elem.currentFrame));
+			currentFrame %= elem.animation->size();
+
+			auto img = elem.animation->getImage(currentFrame);
+
+			canvas.draw(img, Point(elem.x, elem.y));
+		});
+	}
+}

+ 84 - 0
client/battle/BattleEffectsController.h

@@ -0,0 +1,84 @@
+/*
+ * BattleEffectsController.h, part of VCMI engine
+ *
+ * Authors: listed in file AUTHORS in main folder
+ *
+ * License: GNU General Public License v2.0 or later
+ * Full text of license available in license.txt file, in main folder
+ *
+ */
+#pragma once
+
+#include "../../lib/battle/BattleHex.h"
+
+VCMI_LIB_NAMESPACE_BEGIN
+
+class BattleAction;
+struct CustomEffectInfo;
+struct BattleTriggerEffect;
+
+VCMI_LIB_NAMESPACE_END
+
+class CAnimation;
+class Canvas;
+class BattleInterface;
+class BattleRenderer;
+class CPointEffectAnimation;
+
+namespace EBattleEffect
+{
+	enum EBattleEffect
+	{
+		// list of battle effects that have hardcoded triggers
+		FEAR         = 15,
+		GOOD_LUCK    = 18,
+		GOOD_MORALE  = 20,
+		BAD_MORALE   = 30,
+		BAD_LUCK     = 48,
+		RESURRECT    = 50,
+		DRAIN_LIFE   = 52, // hardcoded constant in CGameHandler
+		POISON       = 67,
+		DEATH_BLOW   = 73,
+		REGENERATION = 74,
+		MANA_DRAIN   = 77,
+
+		INVALID      = -1,
+	};
+}
+
+/// Struct for battle effect animation e.g. morale, prayer, armageddon, bless,...
+struct BattleEffect
+{
+	int x, y; //position on the screen
+	float currentFrame;
+	std::shared_ptr<CAnimation> animation;
+	int effectID; //uniqueID equal ot ID of appropriate CSpellEffectAnim
+	BattleHex position; //Indicates if effect which hex the effect is drawn on
+};
+
+/// Controls rendering of effects in battle, e.g. from spells, abilities and various other actions like morale
+class BattleEffectsController
+{
+	BattleInterface & owner;
+
+	/// list of current effects that are being displayed on screen (spells & creature abilities)
+	std::vector<BattleEffect> battleEffects;
+
+public:
+	BattleEffectsController(BattleInterface & owner);
+
+	void startAction(const BattleAction* action);
+
+	void displayCustomEffects(const std::vector<CustomEffectInfo> & customEffects);
+
+	//displays custom effect on the battlefield
+	void displayEffect(EBattleEffect::EBattleEffect effect, const BattleHex & destTile);
+	void displayEffect(EBattleEffect::EBattleEffect effect, uint32_t soundID, const BattleHex & destTile);
+	//void displayEffects(EBattleEffect::EBattleEffect effect, uint32_t soundID, const std::vector<BattleHex> & destTiles);
+
+	void battleTriggerEffect(const BattleTriggerEffect & bte);
+
+	void collectRenderableObjects(BattleRenderer & renderer);
+
+	friend class CPointEffectAnimation;
+};

+ 634 - 0
client/battle/BattleFieldController.cpp

@@ -0,0 +1,634 @@
+/*
+ * BattleFieldController.cpp, part of VCMI engine
+ *
+ * Authors: listed in file AUTHORS in main folder
+ *
+ * License: GNU General Public License v2.0 or later
+ * Full text of license available in license.txt file, in main folder
+ *
+ */
+#include "StdInc.h"
+#include "BattleFieldController.h"
+
+#include "BattleInterface.h"
+#include "BattleActionsController.h"
+#include "BattleInterfaceClasses.h"
+#include "BattleEffectsController.h"
+#include "BattleSiegeController.h"
+#include "BattleStacksController.h"
+#include "BattleObstacleController.h"
+#include "BattleProjectileController.h"
+#include "BattleRenderer.h"
+
+#include "../CGameInfo.h"
+#include "../CPlayerInterface.h"
+#include "../gui/CAnimation.h"
+#include "../gui/Canvas.h"
+#include "../gui/CGuiHandler.h"
+#include "../gui/CCursorHandler.h"
+
+#include "../../CCallback.h"
+#include "../../lib/BattleFieldHandler.h"
+#include "../../lib/CConfigHandler.h"
+#include "../../lib/CStack.h"
+#include "../../lib/spells/ISpellMechanics.h"
+
+BattleFieldController::BattleFieldController(BattleInterface & owner):
+	owner(owner),
+	attackingHex(BattleHex::INVALID)
+{
+	OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
+	pos.w = owner.pos.w;
+	pos.h = owner.pos.h;
+
+	//preparing cells and hexes
+	cellBorder = IImage::createFromFile("CCELLGRD.BMP");
+	cellShade = IImage::createFromFile("CCELLSHD.BMP");
+
+	if(!owner.siegeController)
+	{
+		auto bfieldType = owner.curInt->cb->battleGetBattlefieldType();
+
+		if(bfieldType == BattleField::NONE)
+			logGlobal->error("Invalid battlefield returned for current battle");
+		else
+			background = IImage::createFromFile(bfieldType.getInfo()->graphics);
+	}
+	else
+	{
+		std::string backgroundName = owner.siegeController->getBattleBackgroundName();
+		background = IImage::createFromFile(backgroundName);
+	}
+
+	//preparing graphic with cell borders
+	cellBorders = std::make_unique<Canvas>(Point(background->width(), background->height()));
+
+	for (int i=0; i<GameConstants::BFIELD_SIZE; ++i)
+	{
+		if ( i % GameConstants::BFIELD_WIDTH == 0)
+			continue;
+		if ( i % GameConstants::BFIELD_WIDTH == GameConstants::BFIELD_WIDTH - 1)
+			continue;
+
+		cellBorders->draw(cellBorder, hexPositionLocal(i).topLeft());
+	}
+
+	backgroundWithHexes = std::make_unique<Canvas>(Point(background->width(), background->height()));
+
+	for (int h = 0; h < GameConstants::BFIELD_SIZE; ++h)
+	{
+		auto hex = std::make_shared<ClickableHex>();
+		hex->myNumber = h;
+		hex->pos = hexPositionAbsolute(h);
+		hex->myInterface = &owner;
+		bfield.push_back(hex);
+	}
+
+	auto accessibility = owner.curInt->cb->getAccesibility();
+	for(int i = 0; i < accessibility.size(); i++)
+		stackCountOutsideHexes[i] = (accessibility[i] == EAccessibility::ACCESSIBLE);
+}
+
+void BattleFieldController::renderBattlefield(Canvas & canvas)
+{
+	showBackground(canvas);
+
+	BattleRenderer renderer(owner);
+
+	renderer.execute(canvas);
+
+	owner.projectilesController->showProjectiles(canvas);
+}
+
+void BattleFieldController::showBackground(Canvas & canvas)
+{
+	if (owner.stacksController->getActiveStack() != nullptr ) //&& creAnims[stacksController->getActiveStack()->ID]->isIdle() //show everything with range
+		showBackgroundImageWithHexes(canvas);
+	else
+		showBackgroundImage(canvas);
+
+	showHighlightedHexes(canvas);
+
+}
+
+void BattleFieldController::showBackgroundImage(Canvas & canvas)
+{
+	canvas.draw(background, owner.pos.topLeft());
+
+	owner.obstacleController->showAbsoluteObstacles(canvas, pos.topLeft());
+	if ( owner.siegeController )
+		owner.siegeController->showAbsoluteObstacles(canvas, pos.topLeft());
+
+	if (settings["battle"]["cellBorders"].Bool())
+		canvas.draw(*cellBorders, owner.pos.topLeft());
+}
+
+void BattleFieldController::showBackgroundImageWithHexes(Canvas & canvas)
+{
+	canvas.draw(*backgroundWithHexes.get(), owner.pos.topLeft());
+}
+
+void BattleFieldController::redrawBackgroundWithHexes()
+{
+	const CStack *activeStack = owner.stacksController->getActiveStack();
+	std::vector<BattleHex> attackableHexes;
+	if (activeStack)
+		occupyableHexes = owner.curInt->cb->battleGetAvailableHexes(activeStack, true, &attackableHexes);
+
+	auto accessibility = owner.curInt->cb->getAccesibility();
+
+	for(int i = 0; i < accessibility.size(); i++)
+		stackCountOutsideHexes[i] = (accessibility[i] == EAccessibility::ACCESSIBLE);
+
+	//prepare background graphic with hexes and shaded hexes
+	backgroundWithHexes->draw(background, Point(0,0));
+	owner.obstacleController->showAbsoluteObstacles(*backgroundWithHexes, Point(0,0));
+	if ( owner.siegeController )
+		owner.siegeController->showAbsoluteObstacles(*backgroundWithHexes, Point(0,0));
+
+	if (settings["battle"]["stackRange"].Bool())
+	{
+		std::vector<BattleHex> hexesToShade = occupyableHexes;
+		hexesToShade.insert(hexesToShade.end(), attackableHexes.begin(), attackableHexes.end());
+		for (BattleHex hex : hexesToShade)
+		{
+			backgroundWithHexes->draw(cellShade, hexPositionLocal(hex).topLeft());
+		}
+	}
+
+	if(settings["battle"]["cellBorders"].Bool())
+		backgroundWithHexes->draw(*cellBorders, Point(0, 0));
+}
+
+void BattleFieldController::showHighlightedHex(Canvas & canvas, BattleHex hex, bool darkBorder)
+{
+	Point hexPos = hexPositionAbsolute(hex).topLeft();
+
+	canvas.draw(cellShade, hexPos);
+	if(!darkBorder && settings["battle"]["cellBorders"].Bool())
+		canvas.draw(cellBorder, hexPos);
+}
+
+std::set<BattleHex> BattleFieldController::getHighlightedHexesStackRange()
+{
+	std::set<BattleHex> result;
+
+	if ( !owner.stacksController->getActiveStack())
+		return result;
+
+	if ( !settings["battle"]["stackRange"].Bool())
+		return result;
+
+	auto hoveredHex = getHoveredHex();
+
+	std::set<BattleHex> set = owner.curInt->cb->battleGetAttackedHexes(owner.stacksController->getActiveStack(), hoveredHex, attackingHex);
+	for(BattleHex hex : set)
+		result.insert(hex);
+
+	// display the movement shadow of the stack at b (i.e. stack under mouse)
+	const CStack * const shere = owner.curInt->cb->battleGetStackByPos(hoveredHex, false);
+	if(shere && shere != owner.stacksController->getActiveStack() && shere->alive())
+	{
+		std::vector<BattleHex> v = owner.curInt->cb->battleGetAvailableHexes(shere, true, nullptr);
+		for(BattleHex hex : v)
+			result.insert(hex);
+	}
+	return result;
+}
+
+std::set<BattleHex> BattleFieldController::getHighlightedHexesSpellRange()
+{
+	std::set<BattleHex> result;
+	auto hoveredHex = getHoveredHex();
+
+	if(!settings["battle"]["mouseShadow"].Bool())
+		return result;
+
+	const spells::Caster *caster = nullptr;
+	const CSpell *spell = nullptr;
+
+	spells::Mode mode = spells::Mode::HERO;
+
+	if(owner.actionsController->spellcastingModeActive())//hero casts spell
+	{
+		spell = owner.actionsController->selectedSpell().toSpell();
+		caster = owner.getActiveHero();
+	}
+	else if(owner.stacksController->activeStackSpellToCast() != SpellID::NONE)//stack casts spell
+	{
+		spell = SpellID(owner.stacksController->activeStackSpellToCast()).toSpell();
+		caster = owner.stacksController->getActiveStack();
+		mode = spells::Mode::CREATURE_ACTIVE;
+	}
+
+	if(caster && spell) //when casting spell
+	{
+		// printing shaded hex(es)
+		spells::BattleCast event(owner.curInt->cb.get(), caster, mode, spell);
+		auto shaded = spell->battleMechanics(&event)->rangeInHexes(hoveredHex);
+
+		for(BattleHex shadedHex : shaded)
+		{
+			if((shadedHex.getX() != 0) && (shadedHex.getX() != GameConstants::BFIELD_WIDTH - 1))
+				result.insert(shadedHex);
+		}
+	}
+	else if(owner.active) //always highlight pointed hex
+	{
+		if(hoveredHex.getX() != 0 && hoveredHex.getX() != GameConstants::BFIELD_WIDTH - 1)
+			result.insert(hoveredHex);
+	}
+
+	return result;
+}
+
+void BattleFieldController::showHighlightedHexes(Canvas & canvas)
+{
+	std::set<BattleHex> hoveredStack = getHighlightedHexesStackRange();
+	std::set<BattleHex> hoveredMouse = getHighlightedHexesSpellRange();
+
+	for(int b=0; b<GameConstants::BFIELD_SIZE; ++b)
+	{
+		bool stack = hoveredStack.count(b);
+		bool mouse = hoveredMouse.count(b);
+
+		if ( stack && mouse )
+		{
+			// area where enemy stack can move AND affected by mouse cursor - create darker highlight by blitting twice
+			showHighlightedHex(canvas, b, true);
+			showHighlightedHex(canvas, b, true);
+		}
+		if ( !stack && mouse )
+		{
+			showHighlightedHex(canvas, b, true);
+		}
+		if ( stack && !mouse )
+		{
+			showHighlightedHex(canvas, b, false);
+		}
+	}
+}
+
+Rect BattleFieldController::hexPositionLocal(BattleHex hex) const
+{
+	int x = 14 + ((hex.getY())%2==0 ? 22 : 0) + 44*hex.getX();
+	int y = 86 + 42 *hex.getY();
+	int w = cellShade->width();
+	int h = cellShade->height();
+	return Rect(x, y, w, h);
+}
+
+Rect BattleFieldController::hexPositionAbsolute(BattleHex hex) const
+{
+	return hexPositionLocal(hex) + owner.pos.topLeft();
+}
+
+bool BattleFieldController::isPixelInHex(Point const & position)
+{
+	return !cellShade->isTransparent(position);
+}
+
+BattleHex BattleFieldController::getHoveredHex()
+{
+	for ( auto const & hex : bfield)
+		if (hex->hovered && hex->strictHovered)
+			return hex->myNumber;
+
+	return BattleHex::INVALID;
+}
+
+void BattleFieldController::setBattleCursor(BattleHex myNumber)
+{
+	Rect hoveredHexPos = hexPositionAbsolute(myNumber);
+	CCursorHandler *cursor = CCS->curh;
+
+	const double subdividingAngle = 2.0*M_PI/6.0; // Divide a hex into six sectors.
+	const double hexMidX = hoveredHexPos.x + hoveredHexPos.w/2.0;
+	const double hexMidY = hoveredHexPos.y + hoveredHexPos.h/2.0;
+	const double cursorHexAngle = M_PI - atan2(hexMidY - cursor->ypos, cursor->xpos - hexMidX) + subdividingAngle/2; //TODO: refactor this nightmare
+	const double sector = fmod(cursorHexAngle/subdividingAngle, 6.0);
+	const int zigzagCorrection = !((myNumber/GameConstants::BFIELD_WIDTH)%2); // Off-by-one correction needed to deal with the odd battlefield rows.
+
+	std::vector<int> sectorCursor; // From left to bottom left.
+	sectorCursor.push_back(8);
+	sectorCursor.push_back(9);
+	sectorCursor.push_back(10);
+	sectorCursor.push_back(11);
+	sectorCursor.push_back(12);
+	sectorCursor.push_back(7);
+
+	const bool doubleWide = owner.stacksController->getActiveStack()->doubleWide();
+	bool aboveAttackable = true, belowAttackable = true;
+
+	// Exclude directions which cannot be attacked from.
+	// Check to the left.
+	if (myNumber%GameConstants::BFIELD_WIDTH <= 1 || !vstd::contains(occupyableHexes, myNumber - 1))
+	{
+		sectorCursor[0] = -1;
+	}
+	// Check top left, top right as well as above for 2-hex creatures.
+	if (myNumber/GameConstants::BFIELD_WIDTH == 0)
+	{
+			sectorCursor[1] = -1;
+			sectorCursor[2] = -1;
+			aboveAttackable = false;
+	}
+	else
+	{
+		if (doubleWide)
+		{
+			bool attackRow[4] = {true, true, true, true};
+
+			if (myNumber%GameConstants::BFIELD_WIDTH <= 1 || !vstd::contains(occupyableHexes, myNumber - GameConstants::BFIELD_WIDTH - 2 + zigzagCorrection))
+				attackRow[0] = false;
+			if (!vstd::contains(occupyableHexes, myNumber - GameConstants::BFIELD_WIDTH - 1 + zigzagCorrection))
+				attackRow[1] = false;
+			if (!vstd::contains(occupyableHexes, myNumber - GameConstants::BFIELD_WIDTH + zigzagCorrection))
+				attackRow[2] = false;
+			if (myNumber%GameConstants::BFIELD_WIDTH >= GameConstants::BFIELD_WIDTH - 2 || !vstd::contains(occupyableHexes, myNumber - GameConstants::BFIELD_WIDTH + 1 + zigzagCorrection))
+				attackRow[3] = false;
+
+			if (!(attackRow[0] && attackRow[1]))
+				sectorCursor[1] = -1;
+			if (!(attackRow[1] && attackRow[2]))
+				aboveAttackable = false;
+			if (!(attackRow[2] && attackRow[3]))
+				sectorCursor[2] = -1;
+		}
+		else
+		{
+			if (!vstd::contains(occupyableHexes, myNumber - GameConstants::BFIELD_WIDTH - 1 + zigzagCorrection))
+				sectorCursor[1] = -1;
+			if (!vstd::contains(occupyableHexes, myNumber - GameConstants::BFIELD_WIDTH + zigzagCorrection))
+				sectorCursor[2] = -1;
+		}
+	}
+	// Check to the right.
+	if (myNumber%GameConstants::BFIELD_WIDTH >= GameConstants::BFIELD_WIDTH - 2 || !vstd::contains(occupyableHexes, myNumber + 1))
+	{
+		sectorCursor[3] = -1;
+	}
+	// Check bottom right, bottom left as well as below for 2-hex creatures.
+	if (myNumber/GameConstants::BFIELD_WIDTH == GameConstants::BFIELD_HEIGHT - 1)
+	{
+		sectorCursor[4] = -1;
+		sectorCursor[5] = -1;
+		belowAttackable = false;
+	}
+	else
+	{
+		if (doubleWide)
+		{
+			bool attackRow[4] = {true, true, true, true};
+
+			if (myNumber%GameConstants::BFIELD_WIDTH <= 1 || !vstd::contains(occupyableHexes, myNumber + GameConstants::BFIELD_WIDTH - 2 + zigzagCorrection))
+				attackRow[0] = false;
+			if (!vstd::contains(occupyableHexes, myNumber + GameConstants::BFIELD_WIDTH - 1 + zigzagCorrection))
+				attackRow[1] = false;
+			if (!vstd::contains(occupyableHexes, myNumber + GameConstants::BFIELD_WIDTH + zigzagCorrection))
+				attackRow[2] = false;
+			if (myNumber%GameConstants::BFIELD_WIDTH >= GameConstants::BFIELD_WIDTH - 2 || !vstd::contains(occupyableHexes, myNumber + GameConstants::BFIELD_WIDTH + 1 + zigzagCorrection))
+				attackRow[3] = false;
+
+			if (!(attackRow[0] && attackRow[1]))
+				sectorCursor[5] = -1;
+			if (!(attackRow[1] && attackRow[2]))
+				belowAttackable = false;
+			if (!(attackRow[2] && attackRow[3]))
+				sectorCursor[4] = -1;
+		}
+		else
+		{
+			if (!vstd::contains(occupyableHexes, myNumber + GameConstants::BFIELD_WIDTH + zigzagCorrection))
+				sectorCursor[4] = -1;
+			if (!vstd::contains(occupyableHexes, myNumber + GameConstants::BFIELD_WIDTH - 1 + zigzagCorrection))
+				sectorCursor[5] = -1;
+		}
+	}
+
+	// Determine index from sector.
+	int cursorIndex;
+	if (doubleWide)
+	{
+		sectorCursor.insert(sectorCursor.begin() + 5, belowAttackable ? 13 : -1);
+		sectorCursor.insert(sectorCursor.begin() + 2, aboveAttackable ? 14 : -1);
+
+		if (sector < 1.5)
+			cursorIndex = static_cast<int>(sector);
+		else if (sector >= 1.5 && sector < 2.5)
+			cursorIndex = 2;
+		else if (sector >= 2.5 && sector < 4.5)
+			cursorIndex = (int) sector + 1;
+		else if (sector >= 4.5 && sector < 5.5)
+			cursorIndex = 6;
+		else
+			cursorIndex = (int) sector + 2;
+	}
+	else
+	{
+		cursorIndex = static_cast<int>(sector);
+	}
+
+	// Generally should NEVER happen, but to avoid the possibility of having endless loop below... [#1016]
+	if (!vstd::contains_if (sectorCursor, [](int sc) { return sc != -1; }))
+	{
+		logGlobal->error("Error: for hex %d cannot find a hex to attack from!", myNumber);
+		attackingHex = -1;
+		return;
+	}
+
+	// Find the closest direction attackable, starting with the right one.
+	// FIXME: Is this really how the original H3 client does it?
+	int i = 0;
+	while (sectorCursor[(cursorIndex + i)%sectorCursor.size()] == -1) //Why hast thou forsaken me?
+		i = i <= 0 ? 1 - i : -i; // 0, 1, -1, 2, -2, 3, -3 etc..
+	int index = (cursorIndex + i)%sectorCursor.size(); //hopefully we get elements from sectorCursor
+	cursor->changeGraphic(ECursor::COMBAT, sectorCursor[index]);
+	switch (index)
+	{
+		case 0:
+			attackingHex = myNumber - 1; //left
+			break;
+		case 1:
+			attackingHex = myNumber - GameConstants::BFIELD_WIDTH - 1 + zigzagCorrection; //top left
+			break;
+		case 2:
+			attackingHex = myNumber - GameConstants::BFIELD_WIDTH + zigzagCorrection; //top right
+			break;
+		case 3:
+			attackingHex = myNumber + 1; //right
+			break;
+		case 4:
+			attackingHex = myNumber + GameConstants::BFIELD_WIDTH + zigzagCorrection; //bottom right
+			break;
+		case 5:
+			attackingHex = myNumber + GameConstants::BFIELD_WIDTH - 1 + zigzagCorrection; //bottom left
+			break;
+	}
+	BattleHex hex(attackingHex);
+	if (!hex.isValid())
+		attackingHex = -1;
+}
+
+BattleHex BattleFieldController::fromWhichHexAttack(BattleHex myNumber)
+{
+	//TODO far too much repeating code
+	BattleHex destHex;
+	switch(CCS->curh->frame)
+	{
+	case 12: //from bottom right
+		{
+			bool doubleWide = owner.stacksController->getActiveStack()->doubleWide();
+			destHex = myNumber + ( (myNumber/GameConstants::BFIELD_WIDTH)%2 ? GameConstants::BFIELD_WIDTH : GameConstants::BFIELD_WIDTH+1 ) +
+				(owner.stacksController->getActiveStack()->side == BattleSide::ATTACKER && doubleWide ? 1 : 0);
+			if(vstd::contains(occupyableHexes, destHex))
+				return destHex;
+			else if(owner.stacksController->getActiveStack()->side == BattleSide::ATTACKER)
+			{
+				if (vstd::contains(occupyableHexes, destHex+1))
+					return destHex+1;
+			}
+			else //if we are defender
+			{
+				if(vstd::contains(occupyableHexes, destHex-1))
+					return destHex-1;
+			}
+			break;
+		}
+	case 7: //from bottom left
+		{
+			destHex = myNumber + ( (myNumber/GameConstants::BFIELD_WIDTH)%2 ? GameConstants::BFIELD_WIDTH-1 : GameConstants::BFIELD_WIDTH );
+			if (vstd::contains(occupyableHexes, destHex))
+				return destHex;
+			else if(owner.stacksController->getActiveStack()->side == BattleSide::ATTACKER)
+			{
+				if(vstd::contains(occupyableHexes, destHex+1))
+					return destHex+1;
+			}
+			else //we are defender
+			{
+				if(vstd::contains(occupyableHexes, destHex-1))
+					return destHex-1;
+			}
+			break;
+		}
+	case 8: //from left
+		{
+			if(owner.stacksController->getActiveStack()->doubleWide() && owner.stacksController->getActiveStack()->side == BattleSide::DEFENDER)
+			{
+				std::vector<BattleHex> acc = owner.curInt->cb->battleGetAvailableHexes(owner.stacksController->getActiveStack());
+				if (vstd::contains(acc, myNumber))
+					return myNumber - 1;
+				else
+					return myNumber - 2;
+			}
+			else
+			{
+				return myNumber - 1;
+			}
+			break;
+		}
+	case 9: //from top left
+		{
+			destHex = myNumber - ((myNumber/GameConstants::BFIELD_WIDTH) % 2 ? GameConstants::BFIELD_WIDTH + 1 : GameConstants::BFIELD_WIDTH);
+			if(vstd::contains(occupyableHexes, destHex))
+				return destHex;
+			else if(owner.stacksController->getActiveStack()->side == BattleSide::ATTACKER)
+			{
+				if(vstd::contains(occupyableHexes, destHex+1))
+					return destHex+1;
+			}
+			else //if we are defender
+			{
+				if(vstd::contains(occupyableHexes, destHex-1))
+					return destHex-1;
+			}
+			break;
+		}
+	case 10: //from top right
+		{
+			bool doubleWide = owner.stacksController->getActiveStack()->doubleWide();
+			destHex = myNumber - ( (myNumber/GameConstants::BFIELD_WIDTH)%2 ? GameConstants::BFIELD_WIDTH : GameConstants::BFIELD_WIDTH-1 ) +
+				(owner.stacksController->getActiveStack()->side == BattleSide::ATTACKER && doubleWide ? 1 : 0);
+			if(vstd::contains(occupyableHexes, destHex))
+				return destHex;
+			else if(owner.stacksController->getActiveStack()->side == BattleSide::ATTACKER)
+			{
+				if(vstd::contains(occupyableHexes, destHex+1))
+					return destHex+1;
+			}
+			else //if we are defender
+			{
+				if(vstd::contains(occupyableHexes, destHex-1))
+					return destHex-1;
+			}
+			break;
+		}
+	case 11: //from right
+		{
+			if(owner.stacksController->getActiveStack()->doubleWide() && owner.stacksController->getActiveStack()->side == BattleSide::ATTACKER)
+			{
+				std::vector<BattleHex> acc = owner.curInt->cb->battleGetAvailableHexes(owner.stacksController->getActiveStack());
+				if(vstd::contains(acc, myNumber))
+					return myNumber + 1;
+				else
+					return myNumber + 2;
+			}
+			else
+			{
+				return myNumber + 1;
+			}
+			break;
+		}
+	case 13: //from bottom
+		{
+			destHex = myNumber + ( (myNumber/GameConstants::BFIELD_WIDTH)%2 ? GameConstants::BFIELD_WIDTH : GameConstants::BFIELD_WIDTH+1 );
+			if(vstd::contains(occupyableHexes, destHex))
+				return destHex;
+			else if(owner.stacksController->getActiveStack()->side == BattleSide::ATTACKER)
+			{
+				if(vstd::contains(occupyableHexes, destHex+1))
+					return destHex+1;
+			}
+			else //if we are defender
+			{
+				if(vstd::contains(occupyableHexes, destHex-1))
+					return destHex-1;
+			}
+			break;
+		}
+	case 14: //from top
+		{
+			destHex = myNumber - ( (myNumber/GameConstants::BFIELD_WIDTH)%2 ? GameConstants::BFIELD_WIDTH : GameConstants::BFIELD_WIDTH-1 );
+			if (vstd::contains(occupyableHexes, destHex))
+				return destHex;
+			else if(owner.stacksController->getActiveStack()->side == BattleSide::ATTACKER)
+			{
+				if(vstd::contains(occupyableHexes, destHex+1))
+					return destHex+1;
+			}
+			else //if we are defender
+			{
+				if(vstd::contains(occupyableHexes, destHex-1))
+					return destHex-1;
+			}
+			break;
+		}
+	}
+	return -1;
+}
+
+bool BattleFieldController::isTileAttackable(const BattleHex & number) const
+{
+	for (auto & elem : occupyableHexes)
+	{
+		if (BattleHex::mutualPosition(elem, number) != -1 || elem == number)
+			return true;
+	}
+	return false;
+}
+
+bool BattleFieldController::stackCountOutsideHex(const BattleHex & number) const
+{
+	return stackCountOutsideHexes[number];
+}

+ 91 - 0
client/battle/BattleFieldController.h

@@ -0,0 +1,91 @@
+/*
+ * BattleFieldController.h, part of VCMI engine
+ *
+ * Authors: listed in file AUTHORS in main folder
+ *
+ * License: GNU General Public License v2.0 or later
+ * Full text of license available in license.txt file, in main folder
+ *
+ */
+#pragma once
+
+#include "../../lib/battle/BattleHex.h"
+#include "../gui/CIntObject.h"
+
+VCMI_LIB_NAMESPACE_BEGIN
+
+class CStack;
+
+VCMI_LIB_NAMESPACE_END
+
+struct Rect;
+struct Point;
+
+class ClickableHex;
+class Canvas;
+class IImage;
+class BattleInterface;
+
+/// Handles battlefield grid as well as rendering of background layer of battle interface
+class BattleFieldController : public CIntObject
+{
+	BattleInterface & owner;
+
+	std::shared_ptr<IImage> background;
+	std::shared_ptr<IImage> cellBorder;
+	std::shared_ptr<IImage> cellShade;
+
+	/// Canvas that contains background, hex grid (if enabled), absolute obstacles and movement range of active stack
+	std::unique_ptr<Canvas> backgroundWithHexes;
+
+	/// Canvas that contains cell borders of all tiles in the battlefield
+	std::unique_ptr<Canvas> cellBorders;
+
+	/// hex from which the stack would perform attack with current cursor
+	BattleHex attackingHex;
+
+	/// hexes to which currently active stack can move
+	std::vector<BattleHex> occupyableHexes;
+
+	/// hexes that when in front of a unit cause it's amount box to move back
+	std::array<bool, GameConstants::BFIELD_SIZE> stackCountOutsideHexes;
+
+	std::vector<std::shared_ptr<ClickableHex>> bfield;
+
+	void showHighlightedHex(Canvas & to, BattleHex hex, bool darkBorder);
+
+	std::set<BattleHex> getHighlightedHexesStackRange();
+	std::set<BattleHex> getHighlightedHexesSpellRange();
+
+	void showBackground(Canvas & canvas);
+	void showBackgroundImage(Canvas & canvas);
+	void showBackgroundImageWithHexes(Canvas & canvas);
+	void showHighlightedHexes(Canvas & canvas);
+
+public:
+	BattleFieldController(BattleInterface & owner);
+
+	void redrawBackgroundWithHexes();
+	void renderBattlefield(Canvas & canvas);
+
+	/// Returns position of hex relative to owner (BattleInterface)
+	Rect hexPositionLocal(BattleHex hex) const;
+
+	/// Returns position of hex relative to game window
+	Rect hexPositionAbsolute(BattleHex hex) const;
+
+	/// Checks whether selected pixel is transparent, uses local coordinates of a hex
+	bool isPixelInHex(Point const & position);
+
+	/// Returns ID of currently hovered hex or BattleHex::INVALID if none
+	BattleHex getHoveredHex();
+
+	/// returns true if selected tile can be attacked in melee by current stack
+	bool isTileAttackable(const BattleHex & number) const;
+
+	/// returns true if stack should render its stack count image in default position - outside own hex
+	bool stackCountOutsideHex(const BattleHex & number) const;
+
+	void setBattleCursor(BattleHex myNumber);
+	BattleHex fromWhichHexAttack(BattleHex myNumber);
+};

+ 964 - 0
client/battle/BattleInterface.cpp

@@ -0,0 +1,964 @@
+/*
+ * BattleInterface.cpp, part of VCMI engine
+ *
+ * Authors: listed in file AUTHORS in main folder
+ *
+ * License: GNU General Public License v2.0 or later
+ * Full text of license available in license.txt file, in main folder
+ *
+ */
+#include "StdInc.h"
+#include "BattleInterface.h"
+
+#include "BattleAnimationClasses.h"
+#include "BattleActionsController.h"
+#include "BattleInterfaceClasses.h"
+#include "CreatureAnimation.h"
+#include "BattleProjectileController.h"
+#include "BattleEffectsController.h"
+#include "BattleObstacleController.h"
+#include "BattleSiegeController.h"
+#include "BattleFieldController.h"
+#include "BattleControlPanel.h"
+#include "BattleStacksController.h"
+#include "BattleRenderer.h"
+
+#include "../CGameInfo.h"
+#include "../CMessage.h"
+#include "../CMusicHandler.h"
+#include "../CPlayerInterface.h"
+#include "../gui/Canvas.h"
+#include "../gui/CCursorHandler.h"
+#include "../gui/CGuiHandler.h"
+#include "../windows/CAdvmapInterface.h"
+
+#include "../../CCallback.h"
+#include "../../lib/CStack.h"
+#include "../../lib/CConfigHandler.h"
+#include "../../lib/CGeneralTextHandler.h"
+#include "../../lib/CHeroHandler.h"
+#include "../../lib/CondSh.h"
+#include "../../lib/mapObjects/CGTownInstance.h"
+#include "../../lib/NetPacks.h"
+#include "../../lib/UnlockGuard.h"
+
+CondSh<bool> BattleInterface::animsAreDisplayed(false);
+CondSh<BattleAction *> BattleInterface::givenCommand(nullptr);
+
+BattleInterface::BattleInterface(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)
+	: attackingHeroInstance(hero1), defendingHeroInstance(hero2), animCount(0),
+	attackerInt(att), defenderInt(defen), curInt(att),
+	myTurn(false), moveStarted(false), moveSoundHander(-1), bresult(nullptr), battleActionsStarted(false)
+{
+	OBJ_CONSTRUCTION;
+
+	if(spectatorInt)
+	{
+		curInt = spectatorInt;
+	}
+	else if(!curInt)
+	{
+		//May happen when we are defending during network MP game -> attacker interface is just not present
+		curInt = defenderInt;
+	}
+
+	animsAreDisplayed.setn(false);
+	pos = myRect;
+	strongInterest = true;
+	givenCommand.setn(nullptr);
+
+	//hot-seat -> check tactics for both players (defender may be local human)
+	if(attackerInt && attackerInt->cb->battleGetTacticDist())
+		tacticianInterface = attackerInt;
+	else if(defenderInt && defenderInt->cb->battleGetTacticDist())
+		tacticianInterface = defenderInt;
+
+	//if we found interface of player with tactics, then enter tactics mode
+	tacticsMode = static_cast<bool>(tacticianInterface);
+
+	//create stack queue
+	bool embedQueue;
+	std::string queueSize = settings["battle"]["queueSize"].String();
+
+	if(queueSize == "auto")
+		embedQueue = screen->h < 700;
+	else
+		embedQueue = screen->h < 700 || queueSize == "small";
+
+	queue = std::make_shared<StackQueue>(embedQueue, *this);
+	if(!embedQueue)
+	{
+		if (settings["battle"]["showQueue"].Bool())
+			pos.y += queue->pos.h / 2; //center whole window
+
+		queue->moveTo(Point(pos.x, pos.y - queue->pos.h));
+	}
+
+
+	CPlayerInterface::battleInt = this;
+
+	//initializing armies
+	this->army1 = army1;
+	this->army2 = army2;
+
+	const CGTownInstance *town = curInt->cb->battleGetDefendedTown();
+	if(town && town->hasFort())
+		siegeController.reset(new BattleSiegeController(*this, town));
+
+	controlPanel = std::make_shared<BattleControlPanel>(*this, Point(0, 556));
+	projectilesController.reset(new BattleProjectileController(*this));
+	fieldController.reset( new BattleFieldController(*this));
+	stacksController.reset( new BattleStacksController(*this));
+	actionsController.reset( new BattleActionsController(*this));
+	effectsController.reset(new BattleEffectsController(*this));
+
+	//loading hero animations
+	if(hero1) // attacking hero
+	{
+		std::string battleImage;
+		if(!hero1->type->battleImage.empty())
+		{
+			battleImage = hero1->type->battleImage;
+		}
+		else
+		{
+			if(hero1->sex)
+				battleImage = hero1->type->heroClass->imageBattleFemale;
+			else
+				battleImage = hero1->type->heroClass->imageBattleMale;
+		}
+
+		attackingHero = std::make_shared<BattleHero>(battleImage, false, hero1->tempOwner, hero1->tempOwner == curInt->playerID ? hero1 : nullptr, *this);
+
+		auto img = attackingHero->animation->getImage(0, 0, true);
+		if(img)
+			attackingHero->pos = genRect(img->height(), img->width(), pos.x - 43, pos.y - 19);
+	}
+
+
+	if(hero2) // defending hero
+	{
+		std::string battleImage;
+
+		if(!hero2->type->battleImage.empty())
+		{
+			battleImage = hero2->type->battleImage;
+		}
+		else
+		{
+			if(hero2->sex)
+				battleImage = hero2->type->heroClass->imageBattleFemale;
+			else
+				battleImage = hero2->type->heroClass->imageBattleMale;
+		}
+
+		defendingHero = std::make_shared<BattleHero>(battleImage, true, hero2->tempOwner, hero2->tempOwner == curInt->playerID ? hero2 : nullptr, *this);
+
+		auto img = defendingHero->animation->getImage(0, 0, true);
+		if(img)
+			defendingHero->pos = genRect(img->height(), img->width(), pos.x + 693, pos.y - 19);
+	}
+
+	obstacleController.reset(new BattleObstacleController(*this));
+
+	if(tacticsMode)
+		tacticNextStack(nullptr);
+
+	CCS->musich->stopMusic();
+	battleIntroSoundChannel = CCS->soundh->playSoundFromSet(CCS->soundh->battleIntroSounds);
+	auto onIntroPlayed = [&]()
+	{
+		if(LOCPLINT->battleInt)
+		{
+			CCS->musich->playMusicFromSet("battle", true, true);
+			battleActionsStarted = true;
+			activateStack();
+			controlPanel->blockUI(settings["session"]["spectate"].Bool() || stacksController->getActiveStack() == nullptr);
+			battleIntroSoundChannel = -1;
+		}
+	};
+
+	CCS->soundh->setCallback(battleIntroSoundChannel, onIntroPlayed);
+
+	addUsedEvents(RCLICK | MOVE | KEYBOARD);
+	controlPanel->blockUI(true);
+	queue->update();
+}
+
+BattleInterface::~BattleInterface()
+{
+	CPlayerInterface::battleInt = nullptr;
+	givenCommand.cond.notify_all(); //that two lines should make any stacksController->getActiveStack() waiting thread to finish
+
+	if (active) //dirty fix for #485
+	{
+		deactivate();
+	}
+
+	if (adventureInt && adventureInt->selection)
+	{
+		//FIXME: this should be moved to adventureInt which should restore correct track based on selection/active player
+		const auto & terrain = *(LOCPLINT->cb->getTile(adventureInt->selection->visitablePos())->terType);
+		CCS->musich->playMusicFromSet("terrain", terrain.name, true, false);
+	}
+	animsAreDisplayed.setn(false);
+}
+
+void BattleInterface::setPrintCellBorders(bool set)
+{
+	Settings cellBorders = settings.write["battle"]["cellBorders"];
+	cellBorders->Bool() = set;
+
+	fieldController->redrawBackgroundWithHexes();
+	GH.totalRedraw();
+}
+
+void BattleInterface::setPrintStackRange(bool set)
+{
+	Settings stackRange = settings.write["battle"]["stackRange"];
+	stackRange->Bool() = set;
+
+	fieldController->redrawBackgroundWithHexes();
+	GH.totalRedraw();
+}
+
+void BattleInterface::setPrintMouseShadow(bool set)
+{
+	Settings shadow = settings.write["battle"]["mouseShadow"];
+	shadow->Bool() = set;
+}
+
+void BattleInterface::activate()
+{
+	controlPanel->activate();
+
+	if (curInt->isAutoFightOn)
+		return;
+
+	CIntObject::activate();
+
+	if (attackingHero)
+		attackingHero->activate();
+	if (defendingHero)
+		defendingHero->activate();
+
+	fieldController->activate();
+
+	if (settings["battle"]["showQueue"].Bool())
+		queue->activate();
+
+	LOCPLINT->cingconsole->activate();
+}
+
+void BattleInterface::deactivate()
+{
+	controlPanel->deactivate();
+	CIntObject::deactivate();
+
+	fieldController->deactivate();
+
+	if (attackingHero)
+		attackingHero->deactivate();
+	if (defendingHero)
+		defendingHero->deactivate();
+	if (settings["battle"]["showQueue"].Bool())
+		queue->deactivate();
+
+	LOCPLINT->cingconsole->deactivate();
+}
+
+void BattleInterface::keyPressed(const SDL_KeyboardEvent & key)
+{
+	if(key.keysym.sym == SDLK_q && key.state == SDL_PRESSED)
+	{
+		if(settings["battle"]["showQueue"].Bool()) //hide queue
+			hideQueue();
+		else
+			showQueue();
+
+	}
+	else if(key.keysym.sym == SDLK_f && key.state == SDL_PRESSED)
+	{
+		actionsController->enterCreatureCastingMode();
+	}
+	else if(key.keysym.sym == SDLK_ESCAPE)
+	{
+		if(!battleActionsStarted)
+			CCS->soundh->stopSound(battleIntroSoundChannel);
+		else
+			actionsController->endCastingSpell();
+	}
+}
+void BattleInterface::mouseMoved(const SDL_MouseMotionEvent &event)
+{
+	BattleHex selectedHex = fieldController->getHoveredHex();
+
+	actionsController->handleHex(selectedHex, MOVE);
+
+	controlPanel->mouseMoved(event);
+}
+
+void BattleInterface::clickRight(tribool down, bool previousState)
+{
+	if (!down)
+	{
+		actionsController->endCastingSpell();
+	}
+}
+
+void BattleInterface::stackReset(const CStack * stack)
+{
+	stacksController->stackReset(stack);
+}
+
+void BattleInterface::stackAdded(const CStack * stack)
+{
+	stacksController->stackAdded(stack);
+}
+
+void BattleInterface::stackRemoved(uint32_t stackID)
+{
+	stacksController->stackRemoved(stackID);
+	fieldController->redrawBackgroundWithHexes();
+	queue->update();
+}
+
+void BattleInterface::stackActivated(const CStack *stack) //TODO: check it all before game state is changed due to abilities
+{
+	stacksController->stackActivated(stack);
+}
+
+void BattleInterface::stackMoved(const CStack *stack, std::vector<BattleHex> destHex, int distance)
+{
+	stacksController->stackMoved(stack, destHex, distance);
+}
+
+void BattleInterface::stacksAreAttacked(std::vector<StackAttackedInfo> attackedInfos)
+{
+	stacksController->stacksAreAttacked(attackedInfos);
+
+	std::array<int, 2> killedBySide = {0, 0};
+
+	int targets = 0;
+	for(const StackAttackedInfo & attackedInfo : attackedInfos)
+	{
+		++targets;
+
+		ui8 side = attackedInfo.defender->side;
+		killedBySide.at(side) += attackedInfo.amountKilled;
+	}
+
+	for(ui8 side = 0; side < 2; side++)
+	{
+		if(killedBySide.at(side) > killedBySide.at(1-side))
+			setHeroAnimation(side, CCreatureAnim::HERO_DEFEAT);
+		else if(killedBySide.at(side) < killedBySide.at(1-side))
+			setHeroAnimation(side, CCreatureAnim::HERO_VICTORY);
+	}
+}
+
+void BattleInterface::stackAttacking( const CStack *attacker, BattleHex dest, const CStack *attacked, bool shooting )
+{
+	stacksController->stackAttacking(attacker, dest, attacked, shooting);
+}
+
+void BattleInterface::newRoundFirst( int round )
+{
+	waitForAnims();
+}
+
+void BattleInterface::newRound(int number)
+{
+	controlPanel->console->addText(CGI->generaltexth->allTexts[412]);
+}
+
+void BattleInterface::giveCommand(EActionType action, BattleHex tile, si32 additional)
+{
+	const CStack * actor = nullptr;
+	if(action != EActionType::HERO_SPELL && action != EActionType::RETREAT && action != EActionType::SURRENDER)
+	{
+		actor = stacksController->getActiveStack();
+	}
+
+	auto side = curInt->cb->playerToSide(curInt->playerID);
+	if(!side)
+	{
+		logGlobal->error("Player %s is not in battle", curInt->playerID.getStr());
+		return;
+	}
+
+	auto ba = new BattleAction(); //is deleted in CPlayerInterface::stacksController->getActiveStack()()
+	ba->side = side.get();
+	ba->actionType = action;
+	ba->aimToHex(tile);
+	ba->actionSubtype = additional;
+
+	sendCommand(ba, actor);
+}
+
+void BattleInterface::sendCommand(BattleAction *& command, const CStack * actor)
+{
+	command->stackNumber = actor ? actor->unitId() : ((command->side == BattleSide::ATTACKER) ? -1 : -2);
+
+	if(!tacticsMode)
+	{
+		logGlobal->trace("Setting command for %s", (actor ? actor->nodeName() : "hero"));
+		myTurn = false;
+		stacksController->setActiveStack(nullptr);
+		givenCommand.setn(command);
+	}
+	else
+	{
+		curInt->cb->battleMakeTacticAction(command);
+		vstd::clear_pointer(command);
+		stacksController->setActiveStack(nullptr);
+		//next stack will be activated when action ends
+	}
+}
+
+const CGHeroInstance * BattleInterface::getActiveHero()
+{
+	const CStack *attacker = stacksController->getActiveStack();
+	if(!attacker)
+	{
+		return nullptr;
+	}
+
+	if(attacker->side == BattleSide::ATTACKER)
+	{
+		return attackingHeroInstance;
+	}
+
+	return defendingHeroInstance;
+}
+
+void BattleInterface::hexLclicked(int whichOne)
+{
+	actionsController->handleHex(whichOne, LCLICK);
+}
+
+void BattleInterface::stackIsCatapulting(const CatapultAttack & ca)
+{
+	if (siegeController)
+		siegeController->stackIsCatapulting(ca);
+}
+
+void BattleInterface::gateStateChanged(const EGateState state)
+{
+	if (siegeController)
+		siegeController->gateStateChanged(state);
+}
+
+void BattleInterface::battleFinished(const BattleResult& br)
+{
+	bresult = &br;
+	{
+		auto unlockPim = vstd::makeUnlockGuard(*CPlayerInterface::pim);
+		animsAreDisplayed.waitUntil(false);
+	}
+	stacksController->setActiveStack(nullptr);
+	displayBattleFinished();
+}
+
+void BattleInterface::displayBattleFinished()
+{
+	CCS->curh->changeGraphic(ECursor::ADVENTURE,0);
+	if(settings["session"]["spectate"].Bool() && settings["session"]["spectate-skip-battle-result"].Bool())
+	{
+		close();
+		return;
+	}
+
+	GH.pushInt(std::make_shared<BattleResultWindow>(*bresult, *(this->curInt)));
+	curInt->waitWhileDialog(); // Avoid freeze when AI end turn after battle. Check bug #1897
+	CPlayerInterface::battleInt = nullptr;
+}
+
+void BattleInterface::spellCast(const BattleSpellCast * sc)
+{
+	const SpellID spellID = sc->spellID;
+	const CSpell * spell = spellID.toSpell();
+
+	assert(spell);
+	if(!spell)
+		return;
+
+	const std::string & castSoundPath = spell->getCastSound();
+
+	if (!castSoundPath.empty())
+		CCS->soundh->playSound(castSoundPath);
+
+	if ( sc->activeCast )
+	{
+		const CStack * casterStack = curInt->cb->battleGetStackByID(sc->casterStack);
+
+		if(casterStack != nullptr )
+		{
+			displaySpellCast(spellID, casterStack->getPosition());
+
+			stacksController->addNewAnim(new CCastAnimation(*this, casterStack, sc->tile, curInt->cb->battleGetStackByPos(sc->tile), spell));
+		}
+		else
+		if (sc->tile.isValid() && !spell->animationInfo.projectile.empty())
+		{
+			// this is spell cast by hero with valid destination & valid projectile -> play animation
+
+			const CStack * target = curInt->cb->battleGetStackByPos(sc->tile);
+			Point srccoord = (sc->side ? Point(770, 60) : Point(30, 60)) + pos;	//hero position
+			Point destcoord = stacksController->getStackPositionAtHex(sc->tile, target); //position attacked by projectile
+			destcoord += Point(250, 240); // FIXME: what are these constants?
+
+			projectilesController->createSpellProjectile( nullptr, srccoord, destcoord, spell);
+			projectilesController->emitStackProjectile( nullptr );
+
+			// wait fo projectile to end
+			stacksController->addNewAnim(new CWaitingProjectileAnimation(*this, nullptr));
+		}
+	}
+
+	waitForAnims(); //wait for projectile animation
+
+	displaySpellHit(spellID, sc->tile);
+
+	//queuing affect animation
+	for(auto & elem : sc->affectedCres)
+	{
+		auto stack = curInt->cb->battleGetStackByID(elem, false);
+		if(stack)
+			displaySpellEffect(spellID, stack->getPosition());
+	}
+
+	//queuing additional animation
+	for(auto & elem : sc->customEffects)
+	{
+		auto stack = curInt->cb->battleGetStackByID(elem.stack, false);
+		if(stack)
+			effectsController->displayEffect(EBattleEffect::EBattleEffect(elem.effect), stack->getPosition());
+	}
+
+	waitForAnims();
+	//mana absorption
+	if (sc->manaGained > 0)
+	{
+		Point leftHero = Point(15, 30) + pos;
+		Point rightHero = Point(755, 30) + pos;
+		stacksController->addNewAnim(new CPointEffectAnimation(*this, soundBase::invalid, sc->side ? "SP07_A.DEF" : "SP07_B.DEF", leftHero));
+		stacksController->addNewAnim(new CPointEffectAnimation(*this, soundBase::invalid, sc->side ? "SP07_B.DEF" : "SP07_A.DEF", rightHero));
+	}
+}
+
+void BattleInterface::battleStacksEffectsSet(const SetStackEffect & sse)
+{
+	if(stacksController->getActiveStack() != nullptr)
+		fieldController->redrawBackgroundWithHexes();
+}
+
+void BattleInterface::setHeroAnimation(ui8 side, int phase)
+{
+	if(side == BattleSide::ATTACKER)
+	{
+		if(attackingHero)
+			attackingHero->setPhase(phase);
+	}
+	else
+	{
+		if(defendingHero)
+			defendingHero->setPhase(phase);
+	}
+}
+
+void BattleInterface::displayBattleLog(const std::vector<MetaString> & battleLog)
+{
+	for(const auto & line : battleLog)
+	{
+		std::string formatted = line.toString();
+		boost::algorithm::trim(formatted);
+		if(!controlPanel->console->addText(formatted))
+			logGlobal->warn("Too long battle log line");
+	}
+}
+
+void BattleInterface::displaySpellAnimationQueue(const CSpell::TAnimationQueue & q, BattleHex destinationTile, bool isHit)
+{
+	for(const CSpell::TAnimation & animation : q)
+	{
+		if(animation.pause > 0)
+			stacksController->addNewAnim(new CDummyAnimation(*this, animation.pause));
+		else
+		{
+			int flags = 0;
+
+			if (isHit)
+				flags |= CPointEffectAnimation::FORCE_ON_TOP;
+
+			if (animation.verticalPosition == VerticalPosition::BOTTOM)
+				flags |= CPointEffectAnimation::ALIGN_TO_BOTTOM;
+
+			if (!destinationTile.isValid())
+				flags |= CPointEffectAnimation::SCREEN_FILL;
+
+			if (!destinationTile.isValid())
+				stacksController->addNewAnim(new CPointEffectAnimation(*this, soundBase::invalid, animation.resourceName, flags));
+			else
+				stacksController->addNewAnim(new CPointEffectAnimation(*this, soundBase::invalid, animation.resourceName, destinationTile, flags));
+		}
+	}
+}
+
+void BattleInterface::displaySpellCast(SpellID spellID, BattleHex destinationTile)
+{
+	const CSpell * spell = spellID.toSpell();
+
+	if(spell)
+		displaySpellAnimationQueue(spell->animationInfo.cast, destinationTile, false);
+}
+
+void BattleInterface::displaySpellEffect(SpellID spellID, BattleHex destinationTile)
+{
+	const CSpell *spell = spellID.toSpell();
+
+	if(spell)
+		displaySpellAnimationQueue(spell->animationInfo.affect, destinationTile, false);
+}
+
+void BattleInterface::displaySpellHit(SpellID spellID, BattleHex destinationTile)
+{
+	const CSpell * spell = spellID.toSpell();
+
+	if(spell)
+		displaySpellAnimationQueue(spell->animationInfo.hit, destinationTile, true);
+}
+
+void BattleInterface::setAnimSpeed(int set)
+{
+	Settings speed = settings.write["battle"]["animationSpeed"];
+	speed->Float() = float(set) / 100;
+}
+
+int BattleInterface::getAnimSpeed() const
+{
+	if(settings["session"]["spectate"].Bool() && !settings["session"]["spectate-battle-speed"].isNull())
+		return static_cast<int>(vstd::round(settings["session"]["spectate-battle-speed"].Float() *100));
+
+	return static_cast<int>(vstd::round(settings["battle"]["animationSpeed"].Float() *100));
+}
+
+CPlayerInterface *BattleInterface::getCurrentPlayerInterface() const
+{
+	return curInt.get();
+}
+
+void BattleInterface::trySetActivePlayer( PlayerColor player )
+{
+	if ( attackerInt && attackerInt->playerID == player )
+		curInt = attackerInt;
+
+	if ( defenderInt && defenderInt->playerID == player )
+		curInt = defenderInt;
+}
+
+void BattleInterface::activateStack()
+{
+	if(!battleActionsStarted)
+		return; //"show" function should re-call this function
+
+	stacksController->activateStack();
+
+	const CStack * s = stacksController->getActiveStack();
+	if(!s)
+		return;
+
+	myTurn = true;
+	queue->update();
+	fieldController->redrawBackgroundWithHexes();
+	actionsController->activateStack();
+	GH.fakeMouseMove();
+}
+
+void BattleInterface::endAction(const BattleAction* action)
+{
+	const CStack *stack = curInt->cb->battleGetStackByID(action->stackNumber);
+
+	if(action->actionType == EActionType::HERO_SPELL)
+		setHeroAnimation(action->side, CCreatureAnim::HERO_HOLDING);
+
+	stacksController->endAction(action);
+
+	queue->update();
+
+	if (tacticsMode) //stack ended movement in tactics phase -> select the next one
+		tacticNextStack(stack);
+
+	if(action->actionType == EActionType::HERO_SPELL) //we have activated next stack after sending request that has been just realized -> blockmap due to movement has changed
+		fieldController->redrawBackgroundWithHexes();
+
+//	if (stacksController->getActiveStack() && !animsAreDisplayed.get() && pendingAnims.empty() && !active)
+//	{
+//		logGlobal->warn("Something wrong... interface was deactivated but there is no animation. Reactivating...");
+//		controlPanel->blockUI(false);
+//	}
+//	else
+//	{
+		// block UI if no active stack (e.g. enemy turn);
+	controlPanel->blockUI(stacksController->getActiveStack() == nullptr);
+//	}
+}
+
+void BattleInterface::hideQueue()
+{
+	Settings showQueue = settings.write["battle"]["showQueue"];
+	showQueue->Bool() = false;
+
+	queue->deactivate();
+
+	if (!queue->embedded)
+	{
+		moveBy(Point(0, -queue->pos.h / 2));
+		GH.totalRedraw();
+	}
+}
+
+void BattleInterface::showQueue()
+{
+	Settings showQueue = settings.write["battle"]["showQueue"];
+	showQueue->Bool() = true;
+
+	queue->activate();
+
+	if (!queue->embedded)
+	{
+		moveBy(Point(0, +queue->pos.h / 2));
+		GH.totalRedraw();
+	}
+}
+
+void BattleInterface::startAction(const BattleAction* action)
+{
+	controlPanel->blockUI(true);
+
+	if(action->actionType == EActionType::END_TACTIC_PHASE)
+	{
+		controlPanel->tacticPhaseEnded();
+		return;
+	}
+
+	const CStack *stack = curInt->cb->battleGetStackByID(action->stackNumber);
+
+	if (stack)
+	{
+		queue->update();
+	}
+	else
+	{
+		assert(action->actionType == EActionType::HERO_SPELL); //only cast spell is valid action without acting stack number
+	}
+
+	stacksController->startAction(action);
+
+	redraw(); // redraw after deactivation, including proper handling of hovered hexes
+
+	if(action->actionType == EActionType::HERO_SPELL) //when hero casts spell
+	{
+		setHeroAnimation(action->side, CCreatureAnim::HERO_CAST_SPELL);
+		return;
+	}
+
+	if (!stack)
+	{
+		logGlobal->error("Something wrong with stackNumber in actionStarted. Stack number: %d", action->stackNumber);
+		return;
+	}
+
+	effectsController->startAction(action);
+}
+
+void BattleInterface::waitForAnims()
+{
+	auto unlockPim = vstd::makeUnlockGuard(*CPlayerInterface::pim);
+	animsAreDisplayed.waitWhileTrue();
+}
+
+void BattleInterface::tacticPhaseEnd()
+{
+	stacksController->setActiveStack(nullptr);
+	controlPanel->blockUI(true);
+	tacticsMode = false;
+}
+
+static bool immobile(const CStack *s)
+{
+	return !s->Speed(0, true); //should bound stacks be immobile?
+}
+
+void BattleInterface::tacticNextStack(const CStack * current)
+{
+	if (!current)
+		current = stacksController->getActiveStack();
+
+	//no switching stacks when the current one is moving
+	waitForAnims();
+
+	TStacks stacksOfMine = tacticianInterface->cb->battleGetStacks(CBattleCallback::ONLY_MINE);
+	vstd::erase_if (stacksOfMine, &immobile);
+	if (stacksOfMine.empty())
+	{
+		tacticPhaseEnd();
+		return;
+	}
+
+	auto it = vstd::find(stacksOfMine, current);
+	if (it != stacksOfMine.end() && ++it != stacksOfMine.end())
+		stackActivated(*it);
+	else
+		stackActivated(stacksOfMine.front());
+
+}
+
+void BattleInterface::obstaclePlaced(const std::vector<std::shared_ptr<const CObstacleInstance>> oi)
+{
+	obstacleController->obstaclePlaced(oi);
+}
+
+const CGHeroInstance *BattleInterface::currentHero() const
+{
+	if (attackingHeroInstance && attackingHeroInstance->tempOwner == curInt->playerID)
+		return attackingHeroInstance;
+
+	if (defendingHeroInstance && defendingHeroInstance->tempOwner == curInt->playerID)
+		return defendingHeroInstance;
+
+	return nullptr;
+}
+
+InfoAboutHero BattleInterface::enemyHero() const
+{
+	InfoAboutHero ret;
+	if (attackingHeroInstance->tempOwner == curInt->playerID)
+		curInt->cb->getHeroInfo(defendingHeroInstance, ret);
+	else
+		curInt->cb->getHeroInfo(attackingHeroInstance, ret);
+
+	return ret;
+}
+
+void BattleInterface::requestAutofightingAIToTakeAction()
+{
+	assert(curInt->isAutoFightOn);
+
+	boost::thread aiThread([&]()
+	{
+		auto ba = make_unique<BattleAction>(curInt->autofightingAI->activeStack(stacksController->getActiveStack()));
+
+		if(curInt->cb->battleIsFinished())
+		{
+			return; // battle finished with spellcast
+		}
+
+		if (curInt->isAutoFightOn)
+		{
+			if (tacticsMode)
+			{
+				// Always end tactics mode. Player interface is blocked currently, so it's not possible that
+				// the AI can take any action except end tactics phase (AI actions won't be triggered)
+				//TODO implement the possibility that the AI will be triggered for further actions
+				//TODO any solution to merge tactics phase & normal phase in the way it is handled by the player and battle interface?
+				stacksController->setActiveStack(nullptr);
+				controlPanel->blockUI(true);
+				tacticsMode = false;
+			}
+			else
+			{
+				givenCommand.setn(ba.release());
+			}
+		}
+		else
+		{
+			boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
+			activateStack();
+		}
+	});
+
+	aiThread.detach();
+}
+
+void BattleInterface::showAll(SDL_Surface *to)
+{
+	show(to);
+}
+
+void BattleInterface::show(SDL_Surface *to)
+{
+	Canvas canvas(to);
+	assert(to);
+
+	SDL_Rect buf;
+	SDL_GetClipRect(to, &buf);
+	SDL_SetClipRect(to, &pos);
+
+	++animCount;
+
+	fieldController->renderBattlefield(canvas);
+
+	if(battleActionsStarted)
+		stacksController->updateBattleAnimations();
+
+	SDL_SetClipRect(to, &buf); //restoring previous clip_rect
+
+	showInterface(to);
+
+	//activation of next stack, if any
+	//TODO: should be moved to the very start of this method?
+	//activateStack();
+}
+
+void BattleInterface::collectRenderableObjects(BattleRenderer & renderer)
+{
+	if (attackingHero)
+	{
+		renderer.insert(EBattleFieldLayer::HEROES, BattleHex(0),[this](BattleRenderer::RendererRef canvas)
+		{
+			attackingHero->render(canvas);
+		});
+	}
+	if (defendingHero)
+	{
+		renderer.insert(EBattleFieldLayer::HEROES, BattleHex(GameConstants::BFIELD_WIDTH-1),[this](BattleRenderer::RendererRef canvas)
+		{
+			defendingHero->render(canvas);
+		});
+	}
+}
+
+void BattleInterface::showInterface(SDL_Surface * to)
+{
+	//showing in-game console
+	LOCPLINT->cingconsole->show(to);
+	controlPanel->showAll(to);
+
+	Rect posWithQueue = Rect(pos.x, pos.y, 800, 600);
+
+	if (settings["battle"]["showQueue"].Bool())
+	{
+		if (!queue->embedded)
+		{
+			posWithQueue.y -= queue->pos.h;
+			posWithQueue.h += queue->pos.h;
+		}
+
+		queue->showAll(to);
+	}
+
+	//printing border around interface
+	if (screen->w != 800 || screen->h !=600)
+	{
+		CMessage::drawBorder(curInt->playerID,to,posWithQueue.w + 28, posWithQueue.h + 28, posWithQueue.x-14, posWithQueue.y-15);
+	}
+}
+
+void BattleInterface::castThisSpell(SpellID spellID)
+{
+	actionsController->castThisSpell(spellID);
+}

+ 209 - 0
client/battle/BattleInterface.h

@@ -0,0 +1,209 @@
+/*
+ * BattleInterface.h, part of VCMI engine
+ *
+ * Authors: listed in file AUTHORS in main folder
+ *
+ * License: GNU General Public License v2.0 or later
+ * Full text of license available in license.txt file, in main folder
+ *
+ */
+#pragma once
+
+#include "../gui/CIntObject.h"
+#include "../../lib/spells/CSpellHandler.h" //CSpell::TAnimation
+
+VCMI_LIB_NAMESPACE_BEGIN
+
+class CCreatureSet;
+class CGHeroInstance;
+class CStack;
+struct BattleResult;
+struct BattleSpellCast;
+struct CObstacleInstance;
+template <typename T> struct CondSh;
+struct SetStackEffect;
+class BattleAction;
+class CGTownInstance;
+struct CatapultAttack;
+struct BattleTriggerEffect;
+struct BattleHex;
+struct InfoAboutHero;
+struct CustomEffectInfo;
+
+VCMI_LIB_NAMESPACE_END
+
+class BattleHero;
+class Canvas;
+class BattleResultWindow;
+class StackQueue;
+class CPlayerInterface;
+class ClickableHex;
+class CAnimation;
+struct BattleEffect;
+class IImage;
+class StackQueue;
+
+class BattleProjectileController;
+class BattleSiegeController;
+class BattleObstacleController;
+class BattleFieldController;
+class BattleRenderer;
+class BattleControlPanel;
+class BattleStacksController;
+class BattleActionsController;
+class BattleEffectsController;
+
+/// Small struct which contains information about the id of the attacked stack, the damage dealt,...
+struct StackAttackedInfo
+{
+	const CStack *defender; //attacked stack
+	int64_t dmg; //damage dealt
+	unsigned int amountKilled; //how many creatures in stack has been killed
+	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
+	bool cloneKilled;
+};
+
+/// Big class which handles the overall battle interface actions and it is also responsible for
+/// drawing everything correctly.
+class BattleInterface : public WindowBase
+{
+private:
+	std::shared_ptr<BattleHero> attackingHero;
+	std::shared_ptr<BattleHero> defendingHero;
+	std::shared_ptr<StackQueue> queue;
+	std::shared_ptr<BattleControlPanel> controlPanel;
+
+	std::shared_ptr<CPlayerInterface> tacticianInterface; //used during tactics mode, points to the interface of player with higher tactics (can be either attacker or defender in hot-seat), valid onloy for human players
+	std::shared_ptr<CPlayerInterface> attackerInt, defenderInt; //because LOCPLINT is not enough in hotSeat
+	std::shared_ptr<CPlayerInterface> curInt; //current player interface
+
+	const CCreatureSet *army1, *army2; //copy of initial armies (for result window)
+	const CGHeroInstance *attackingHeroInstance, *defendingHeroInstance;
+
+	ui8 animCount;
+
+	bool tacticsMode;
+	bool battleActionsStarted; //used for delaying battle actions until intro sound stops
+	int battleIntroSoundChannel; //required as variable for disabling it via ESC key
+
+	void trySetActivePlayer( PlayerColor player ); // if in hotseat, will activate interface of chosen player
+	void activateStack(); //sets activeStack to stackToActivate etc. //FIXME: No, it's not clear at all
+	void requestAutofightingAIToTakeAction();
+
+	void giveCommand(EActionType action, BattleHex tile = BattleHex(), si32 additional = -1);
+	void sendCommand(BattleAction *& command, const CStack * actor = nullptr);
+
+	const CGHeroInstance *getActiveHero(); //returns hero that can currently cast a spell
+
+	void showInterface(SDL_Surface * to);
+
+	void setHeroAnimation(ui8 side, int phase);
+public:
+	std::unique_ptr<BattleProjectileController> projectilesController;
+	std::unique_ptr<BattleSiegeController> siegeController;
+	std::unique_ptr<BattleObstacleController> obstacleController;
+	std::unique_ptr<BattleFieldController> fieldController;
+	std::unique_ptr<BattleStacksController> stacksController;
+	std::unique_ptr<BattleActionsController> actionsController;
+	std::unique_ptr<BattleEffectsController> effectsController;
+
+	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
+
+	bool myTurn; //if true, interface is active (commands can be ordered)
+	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
+
+	BattleInterface(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 ~BattleInterface();
+
+	void setPrintCellBorders(bool set); //if true, cell borders will be printed
+	void setPrintStackRange(bool set); //if true,range of active stack will be printed
+	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;
+
+	void tacticNextStack(const CStack *current);
+	void tacticPhaseEnd();
+	void waitForAnims();
+
+	//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 clickRight(tribool down, bool previousState) override;
+
+	void show(SDL_Surface *to) override;
+	void showAll(SDL_Surface *to) override;
+
+	void collectRenderableObjects(BattleRenderer & renderer);
+
+	//call-ins
+	void startAction(const BattleAction* action);
+	void stackReset(const CStack * stack);
+	void stackAdded(const CStack * stack); //new stack appeared on battlefield
+	void stackRemoved(uint32_t 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 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 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 displayBattleFinished(); //displays battle result
+	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 displayBattleLog(const std::vector<MetaString> & battleLog);
+
+	void displaySpellAnimationQueue(const CSpell::TAnimationQueue & q, BattleHex destinationTile, bool isHit);
+	void displaySpellCast(SpellID spellID, BattleHex destinationTile); //displays spell`s cast animation
+	void displaySpellEffect(SpellID spellID, BattleHex destinationTile); //displays spell`s affected animation
+	void displaySpellHit(SpellID spellID, BattleHex destinationTile); //displays spell`s affected animation
+
+	void endAction(const BattleAction* action);
+	void hideQueue();
+	void showQueue();
+
+	void obstaclePlaced(const std::vector<std::shared_ptr<const CObstacleInstance>> oi);
+
+	void gateStateChanged(const EGateState state);
+
+	const CGHeroInstance *currentHero() const;
+	InfoAboutHero enemyHero() const;
+
+	// TODO: cleanup this list
+	friend class CPlayerInterface;
+	friend class CInGameConsole;
+	friend class StackQueue;
+	friend class BattleResultWindow;
+	friend class BattleHero;
+	friend class CBattleStackAnimation;
+	friend class CReverseAnimation;
+	friend class CDefenceAnimation;
+	friend class CMovementAnimation;
+	friend class CMovementStartAnimation;
+	friend class CAttackAnimation;
+	friend class CMeleeAttackAnimation;
+	friend class CShootingAnimation;
+	friend class CCastAnimation;
+	friend class ClickableHex;
+	friend class BattleProjectileController;
+	friend class BattleSiegeController;
+	friend class BattleObstacleController;
+	friend class BattleFieldController;
+	friend class BattleControlPanel;
+	friend class BattleStacksController;
+	friend class BattleActionsController;
+	friend class BattleEffectsController;
+};

+ 171 - 231
client/battle/CBattleInterfaceClasses.cpp → client/battle/BattleInterfaceClasses.cpp

@@ -1,5 +1,5 @@
 /*
- * CBattleInterfaceClasses.cpp, part of VCMI engine
+ * BattleInterfaceClasses.cpp, part of VCMI engine
  *
  * Authors: listed in file AUTHORS in main folder
  *
@@ -8,11 +8,15 @@
  *
  */
 #include "StdInc.h"
-#include "CBattleInterfaceClasses.h"
+#include "BattleInterfaceClasses.h"
 
-#include "CBattleInterface.h"
+#include "BattleInterface.h"
+#include "BattleActionsController.h"
+#include "BattleSiegeController.h"
+#include "BattleFieldController.h"
+#include "BattleStacksController.h"
+#include "BattleControlPanel.h"
 
-#include "../CBitmapHandler.h"
 #include "../CGameInfo.h"
 #include "../CMessage.h"
 #include "../CMusicHandler.h"
@@ -20,10 +24,11 @@
 #include "../CVideoHandler.h"
 #include "../Graphics.h"
 #include "../gui/CAnimation.h"
+#include "../gui/Canvas.h"
 #include "../gui/CCursorHandler.h"
 #include "../gui/CGuiHandler.h"
-#include "../gui/SDL_Extensions.h"
 #include "../widgets/Buttons.h"
+#include "../widgets/Images.h"
 #include "../widgets/TextControls.h"
 #include "../windows/CCreatureWindow.h"
 #include "../windows/CSpellWindow.h"
@@ -40,34 +45,35 @@
 #include "../../lib/CondSh.h"
 #include "../../lib/mapObjects/CGTownInstance.h"
 
-void CBattleConsole::showAll(SDL_Surface * to)
+void BattleConsole::showAll(SDL_Surface * to)
 {
-	Point textPos(pos.x + pos.w/2, pos.y + 17);
+	Point consolePos(pos.x + 10,      pos.y + 17);
+	Point textPos   (pos.x + pos.w/2, pos.y + 17);
 
-	if(ingcAlter.size())
+	if (!consoleText.empty())
 	{
-		graphics->fonts[FONT_SMALL]->renderTextLinesCenter(to, CMessage::breakText(ingcAlter, pos.w, FONT_SMALL), Colors::WHITE, textPos);
+		graphics->fonts[FONT_SMALL]->renderTextLinesLeft(to, CMessage::breakText(consoleText, pos.w, FONT_SMALL), Colors::WHITE, consolePos);
 	}
-	else if(alterTxt.size())
+	else if(!hoverText.empty())
 	{
-		graphics->fonts[FONT_SMALL]->renderTextLinesCenter(to, CMessage::breakText(alterTxt, pos.w, FONT_SMALL), Colors::WHITE, textPos);
+		graphics->fonts[FONT_SMALL]->renderTextLinesCenter(to, CMessage::breakText(hoverText, pos.w, FONT_SMALL), Colors::WHITE, textPos);
 	}
-	else if(texts.size())
+	else if(logEntries.size())
 	{
-		if(texts.size()==1)
+		if(logEntries.size()==1)
 		{
-			graphics->fonts[FONT_SMALL]->renderTextLinesCenter(to, CMessage::breakText(texts[0], pos.w, FONT_SMALL), Colors::WHITE, textPos);
+			graphics->fonts[FONT_SMALL]->renderTextLinesCenter(to, CMessage::breakText(logEntries[0], pos.w, FONT_SMALL), Colors::WHITE, textPos);
 		}
 		else
 		{
-			graphics->fonts[FONT_SMALL]->renderTextLinesCenter(to, CMessage::breakText(texts[lastShown - 1], pos.w, FONT_SMALL), Colors::WHITE, textPos);
+			graphics->fonts[FONT_SMALL]->renderTextLinesCenter(to, CMessage::breakText(logEntries[scrollPosition - 1], pos.w, FONT_SMALL), Colors::WHITE, textPos);
 			textPos.y += 16;
-			graphics->fonts[FONT_SMALL]->renderTextLinesCenter(to, CMessage::breakText(texts[lastShown], pos.w, FONT_SMALL), Colors::WHITE, textPos);
+			graphics->fonts[FONT_SMALL]->renderTextLinesCenter(to, CMessage::breakText(logEntries[scrollPosition], pos.w, FONT_SMALL), Colors::WHITE, textPos);
 		}
 	}
 }
 
-bool CBattleConsole::addText(const std::string & text)
+bool BattleConsole::addText(const std::string & text)
 {
 	logGlobal->trace("CBattleConsole message: %s", text);
 	if(text.size()>70)
@@ -77,57 +83,82 @@ bool CBattleConsole::addText(const std::string & text)
 	{
 		if(text[i] == 10)
 		{
-			texts.push_back( text.substr(firstInToken, i-firstInToken) );
+			logEntries.push_back( text.substr(firstInToken, i-firstInToken) );
 			firstInToken = (int)i+1;
 		}
 	}
 
-	texts.push_back( text.substr(firstInToken, text.size()) );
-	lastShown = (int)texts.size()-1;
+	logEntries.push_back( text.substr(firstInToken, text.size()) );
+	scrollPosition = (int)logEntries.size()-1;
 	return true;
 }
+void BattleConsole::scrollUp(ui32 by)
+{
+	if(scrollPosition > static_cast<int>(by))
+		scrollPosition -= by;
+}
+
+void BattleConsole::scrollDown(ui32 by)
+{
+	if(scrollPosition + by < logEntries.size())
+		scrollPosition += by;
+}
+
+BattleConsole::BattleConsole(const Rect & position)
+	: scrollPosition(-1)
+	, enteringText(false)
+{
+	pos += position.topLeft();
+	pos.w = position.w;
+	pos.h = position.h;
+}
 
-void CBattleConsole::alterText(const std::string &text)
+BattleConsole::~BattleConsole()
 {
-	//char buf[500];
-	//sprintf(buf, text.c_str());
-	//alterTxt = buf;
-	alterTxt = text;
+	if (enteringText)
+		setEnteringMode(false);
 }
 
-void CBattleConsole::eraseText(ui32 pos)
+void BattleConsole::setEnteringMode(bool on)
 {
-	if(pos < texts.size())
+	consoleText.clear();
+
+	if (on)
 	{
-		texts.erase(texts.begin() + pos);
-		if(lastShown == texts.size())
-			--lastShown;
+		assert(enteringText == false);
+		CSDL_Ext::startTextInput(&pos);
 	}
+	else
+	{
+		assert(enteringText == true);
+		CSDL_Ext::stopTextInput();
+	}
+	enteringText = on;
 }
 
-void CBattleConsole::changeTextAt(const std::string & text, ui32 pos)
+void BattleConsole::setEnteredText(const std::string & text)
 {
-	if(pos >= texts.size()) //no such pos
-		return;
-	texts[pos] = text;
+	assert(enteringText == true);
+	consoleText = text;
 }
 
-void CBattleConsole::scrollUp(ui32 by)
+void BattleConsole::write(const std::string & Text)
 {
-	if(lastShown > static_cast<int>(by))
-		lastShown -= by;
+	hoverText = Text;
 }
 
-void CBattleConsole::scrollDown(ui32 by)
+void BattleConsole::clearIfMatching(const std::string & Text)
 {
-	if(lastShown + by < texts.size())
-		lastShown += by;
+	if (hoverText == Text)
+		clear();
 }
 
-CBattleConsole::CBattleConsole() : lastShown(-1), alterTxt(""), whoSetAlter(0)
-{}
+void BattleConsole::clear()
+{
+	write({});
+}
 
-void CBattleHero::show(SDL_Surface * to)
+void BattleHero::render(Canvas & canvas)
 {
 	auto flagFrame = flagAnimation->getImage(flagAnim, 0, true);
 
@@ -135,35 +166,18 @@ void CBattleHero::show(SDL_Surface * to)
 		return;
 
 	//animation of flag
-	SDL_Rect temp_rect;
-	if(flip)
-	{
-		temp_rect = genRect(
-			flagFrame->height(),
-			flagFrame->width(),
-			pos.x + 61,
-			pos.y + 39);
+	Point flagPosition = pos.topLeft();
 
-	}
+	if(flip)
+		flagPosition += Point(61, 39);
 	else
-	{
-		temp_rect = genRect(
-			flagFrame->height(),
-			flagFrame->width(),
-			pos.x + 72,
-			pos.y + 39);
-	}
-
-	flagFrame->draw(screen, &temp_rect, nullptr); //FIXME: why screen?
+		flagPosition += Point(72, 39);
 
-	//animation of hero
-	SDL_Rect rect = pos;
 
 	auto heroFrame = animation->getImage(currentFrame, phase, true);
-	if(!heroFrame)
-		return;
 
-	heroFrame->draw(to, &rect, nullptr);
+	canvas.draw(flagFrame, flagPosition);
+	canvas.draw(heroFrame, pos.topLeft());
 
 	if(++animCount >= 4)
 	{
@@ -176,14 +190,14 @@ void CBattleHero::show(SDL_Surface * to)
 	}
 }
 
-void CBattleHero::setPhase(int newPhase)
+void BattleHero::setPhase(int newPhase)
 {
 	nextPhase = newPhase;
 	switchToNextPhase(); //immediately switch to next phase and then restore idling phase
 	nextPhase = 0;
 }
 
-void CBattleHero::hover(bool on)
+void BattleHero::hover(bool on)
 {
 	//TODO: Make lines below work properly
 	if (on)
@@ -192,9 +206,9 @@ void CBattleHero::hover(bool on)
 		CCS->curh->changeGraphic(ECursor::COMBAT, 0);
 }
 
-void CBattleHero::clickLeft(tribool down, bool previousState)
+void BattleHero::clickLeft(tribool down, bool previousState)
 {
-	if(myOwner->spellDestSelectMode) //we are casting a spell
+	if(myOwner->actionsController->spellcastingModeActive()) //we are casting a spell
 		return;
 
 	if(boost::logic::indeterminate(down))
@@ -205,18 +219,18 @@ void CBattleHero::clickLeft(tribool down, bool previousState)
 
 	if(myOwner->getCurrentPlayerInterface()->cb->battleCanCastSpell(myHero, spells::Mode::HERO) == 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
-		{
-			if(myOwner->bfield[it]->hovered && myOwner->bfield[it]->strictHovered)
-				return;
-		}
+		BattleHex hoveredHex = myOwner->fieldController->getHoveredHex();
+		//do nothing when any hex is hovered - hero's animation overlaps battlefield
+		if ( hoveredHex != BattleHex::INVALID )
+			return;
+
 		CCS->curh->changeGraphic(ECursor::ADVENTURE, 0);
 
 		GH.pushIntT<CSpellWindow>(myHero, myOwner->getCurrentPlayerInterface());
 	}
 }
 
-void CBattleHero::clickRight(tribool down, bool previousState)
+void BattleHero::clickRight(tribool down, bool previousState)
 {
 	if(boost::logic::indeterminate(down))
 		return;
@@ -230,11 +244,11 @@ void CBattleHero::clickRight(tribool down, bool previousState)
 	{
 		auto h = flip ? myOwner->defendingHeroInstance : myOwner->attackingHeroInstance;
 		targetHero.initFromHero(h, InfoAboutHero::EInfoLevel::INBATTLE);
-		GH.pushIntT<CHeroInfoWindow>(targetHero, &windowPosition);
+		GH.pushIntT<HeroInfoWindow>(targetHero, &windowPosition);
 	}
 }
 
-void CBattleHero::switchToNextPhase()
+void BattleHero::switchToNextPhase()
 {
 	if(phase != nextPhase)
 	{
@@ -248,10 +262,10 @@ void CBattleHero::switchToNextPhase()
 	currentFrame = firstFrame;
 }
 
-CBattleHero::CBattleHero(const std::string & animationPath, bool flipG, PlayerColor player, const CGHeroInstance * hero, const CBattleInterface * owner):
+BattleHero::BattleHero(const std::string & animationPath, bool flipG, PlayerColor player, const CGHeroInstance * hero, const BattleInterface & owner):
     flip(flipG),
     myHero(hero),
-    myOwner(owner),
+	myOwner(&owner),
     phase(1),
     nextPhase(0),
     flagAnim(0),
@@ -275,9 +289,7 @@ CBattleHero::CBattleHero(const std::string & animationPath, bool flipG, PlayerCo
 	switchToNextPhase();
 }
 
-CBattleHero::~CBattleHero() = default;
-
-CHeroInfoWindow::CHeroInfoWindow(const InfoAboutHero & hero, Point * position)
+HeroInfoWindow::HeroInfoWindow(const InfoAboutHero & hero, Point * position)
 	: CWindowObject(RCLICK_POPUP | SHADOW_DISABLED, "CHRPOP")
 {
 	OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
@@ -297,49 +309,46 @@ CHeroInfoWindow::CHeroInfoWindow(const InfoAboutHero & hero, Point * position)
 	icons.push_back(std::make_shared<CAnimImage>("PortraitsLarge", hero.portrait, 0, 10, 6));
 
 	//primary stats
-	labels.push_back(std::make_shared<CLabel>(9, 75, EFonts::FONT_TINY, EAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[380] + ":"));
-	labels.push_back(std::make_shared<CLabel>(9, 87, EFonts::FONT_TINY, EAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[381] + ":"));
-	labels.push_back(std::make_shared<CLabel>(9, 99, EFonts::FONT_TINY, EAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[382] + ":"));
-	labels.push_back(std::make_shared<CLabel>(9, 111, EFonts::FONT_TINY, EAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[383] + ":"));
+	labels.push_back(std::make_shared<CLabel>(9, 75, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[380] + ":"));
+	labels.push_back(std::make_shared<CLabel>(9, 87, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[381] + ":"));
+	labels.push_back(std::make_shared<CLabel>(9, 99, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[382] + ":"));
+	labels.push_back(std::make_shared<CLabel>(9, 111, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[383] + ":"));
 
-	labels.push_back(std::make_shared<CLabel>(69, 87, EFonts::FONT_TINY, EAlignment::BOTTOMRIGHT, Colors::WHITE, std::to_string(attack)));
-	labels.push_back(std::make_shared<CLabel>(69, 99, EFonts::FONT_TINY, EAlignment::BOTTOMRIGHT, Colors::WHITE, std::to_string(defense)));
-	labels.push_back(std::make_shared<CLabel>(69, 111, EFonts::FONT_TINY, EAlignment::BOTTOMRIGHT, Colors::WHITE, std::to_string(power)));
-	labels.push_back(std::make_shared<CLabel>(69, 123, EFonts::FONT_TINY, EAlignment::BOTTOMRIGHT, Colors::WHITE, std::to_string(knowledge)));
+	labels.push_back(std::make_shared<CLabel>(69, 87, EFonts::FONT_TINY, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, std::to_string(attack)));
+	labels.push_back(std::make_shared<CLabel>(69, 99, EFonts::FONT_TINY, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, std::to_string(defense)));
+	labels.push_back(std::make_shared<CLabel>(69, 111, EFonts::FONT_TINY, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, std::to_string(power)));
+	labels.push_back(std::make_shared<CLabel>(69, 123, EFonts::FONT_TINY, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, std::to_string(knowledge)));
 
 	//morale+luck
-	labels.push_back(std::make_shared<CLabel>(9, 131, EFonts::FONT_TINY, EAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[384] + ":"));
-	labels.push_back(std::make_shared<CLabel>(9, 143, EFonts::FONT_TINY, EAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[385] + ":"));
+	labels.push_back(std::make_shared<CLabel>(9, 131, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[384] + ":"));
+	labels.push_back(std::make_shared<CLabel>(9, 143, EFonts::FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[385] + ":"));
 
 	icons.push_back(std::make_shared<CAnimImage>("IMRL22", morale + 3, 0, 47, 131));
 	icons.push_back(std::make_shared<CAnimImage>("ILCK22", luck + 3, 0, 47, 143));
 
 	//spell points
-	labels.push_back(std::make_shared<CLabel>(39, 174, EFonts::FONT_TINY, EAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[387]));
-	labels.push_back(std::make_shared<CLabel>(39, 186, EFonts::FONT_TINY, EAlignment::CENTER, Colors::WHITE, std::to_string(currentSpellPoints) + "/" + std::to_string(maxSpellPoints)));
+	labels.push_back(std::make_shared<CLabel>(39, 174, EFonts::FONT_TINY, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[387]));
+	labels.push_back(std::make_shared<CLabel>(39, 186, EFonts::FONT_TINY, ETextAlignment::CENTER, Colors::WHITE, std::to_string(currentSpellPoints) + "/" + std::to_string(maxSpellPoints)));
 }
 
-CBattleOptionsWindow::CBattleOptionsWindow(const SDL_Rect & position, CBattleInterface *owner)
+BattleOptionsWindow::BattleOptionsWindow(BattleInterface & owner):
+	CWindowObject(PLAYER_COLORED, "comopbck.bmp")
 {
 	OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
-	pos = position;
-
-	background = std::make_shared<CPicture>("comopbck.bmp");
-	background->colorize(owner->getCurrentPlayerInterface()->playerID);
 
-	auto viewGrid = std::make_shared<CToggleButton>(Point(25, 56), "sysopchk.def", CGI->generaltexth->zelp[427], [=](bool on){owner->setPrintCellBorders(on);} );
+	auto viewGrid = std::make_shared<CToggleButton>(Point(25, 56), "sysopchk.def", CGI->generaltexth->zelp[427], [&](bool on){owner.setPrintCellBorders(on);} );
 	viewGrid->setSelected(settings["battle"]["cellBorders"].Bool());
 	toggles.push_back(viewGrid);
 
-	auto movementShadow = std::make_shared<CToggleButton>(Point(25, 89), "sysopchk.def", CGI->generaltexth->zelp[428], [=](bool on){owner->setPrintStackRange(on);});
+	auto movementShadow = std::make_shared<CToggleButton>(Point(25, 89), "sysopchk.def", CGI->generaltexth->zelp[428], [&](bool on){owner.setPrintStackRange(on);});
 	movementShadow->setSelected(settings["battle"]["stackRange"].Bool());
 	toggles.push_back(movementShadow);
 
-	auto mouseShadow = std::make_shared<CToggleButton>(Point(25, 122), "sysopchk.def", CGI->generaltexth->zelp[429], [=](bool on){owner->setPrintMouseShadow(on);});
+	auto mouseShadow = std::make_shared<CToggleButton>(Point(25, 122), "sysopchk.def", CGI->generaltexth->zelp[429], [&](bool on){owner.setPrintMouseShadow(on);});
 	mouseShadow->setSelected(settings["battle"]["mouseShadow"].Bool());
 	toggles.push_back(mouseShadow);
 
-	animSpeeds = std::make_shared<CToggleGroup>([=](int value){ owner->setAnimSpeed(value);});
+	animSpeeds = std::make_shared<CToggleGroup>([&](int value){ owner.setAnimSpeed(value);});
 
 	std::shared_ptr<CToggleButton> toggle;
 	toggle = std::make_shared<CToggleButton>(Point( 28, 225), "sysopb9.def", CGI->generaltexth->zelp[422]);
@@ -351,7 +360,7 @@ CBattleOptionsWindow::CBattleOptionsWindow(const SDL_Rect & position, CBattleInt
 	toggle = std::make_shared<CToggleButton>(Point(156, 225), "sysob11.def", CGI->generaltexth->zelp[424]);
 	animSpeeds->addToggle(100, toggle);
 
-	animSpeeds->setSelected(owner->getAnimSpeed());
+	animSpeeds->setSelected(owner.getAnimSpeed());
 
 	setToDefault = std::make_shared<CButton>(Point(246, 359), "codefaul.def", CGI->generaltexth->zelp[393], [&](){ bDefaultf(); });
 	setToDefault->setImageOrder(1, 0, 2, 3);
@@ -359,42 +368,42 @@ CBattleOptionsWindow::CBattleOptionsWindow(const SDL_Rect & position, CBattleInt
 	exit->setImageOrder(1, 0, 2, 3);
 
 	//creating labels
-	labels.push_back(std::make_shared<CLabel>(242,  32, FONT_BIG,    CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[392]));//window title
-	labels.push_back(std::make_shared<CLabel>(122, 214, FONT_MEDIUM, CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[393]));//animation speed
-	labels.push_back(std::make_shared<CLabel>(122, 293, FONT_MEDIUM, CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[394]));//music volume
-	labels.push_back(std::make_shared<CLabel>(122, 359, FONT_MEDIUM, CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[395]));//effects' volume
-	labels.push_back(std::make_shared<CLabel>(353,  66, FONT_MEDIUM, CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[396]));//auto - combat options
-	labels.push_back(std::make_shared<CLabel>(353, 265, FONT_MEDIUM, CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[397]));//creature info
+	labels.push_back(std::make_shared<CLabel>(242,  32, FONT_BIG,    ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[392]));//window title
+	labels.push_back(std::make_shared<CLabel>(122, 214, FONT_MEDIUM, ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[393]));//animation speed
+	labels.push_back(std::make_shared<CLabel>(122, 293, FONT_MEDIUM, ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[394]));//music volume
+	labels.push_back(std::make_shared<CLabel>(122, 359, FONT_MEDIUM, ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[395]));//effects' volume
+	labels.push_back(std::make_shared<CLabel>(353,  66, FONT_MEDIUM, ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[396]));//auto - combat options
+	labels.push_back(std::make_shared<CLabel>(353, 265, FONT_MEDIUM, ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[397]));//creature info
 
 	//auto - combat options
-	labels.push_back(std::make_shared<CLabel>(283,  86, FONT_MEDIUM, TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[398]));//creatures
-	labels.push_back(std::make_shared<CLabel>(283, 116, FONT_MEDIUM, TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[399]));//spells
-	labels.push_back(std::make_shared<CLabel>(283, 146, FONT_MEDIUM, TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[400]));//catapult
-	labels.push_back(std::make_shared<CLabel>(283, 176, FONT_MEDIUM, TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[151]));//ballista
-	labels.push_back(std::make_shared<CLabel>(283, 206, FONT_MEDIUM, TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[401]));//first aid tent
+	labels.push_back(std::make_shared<CLabel>(283,  86, FONT_MEDIUM, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[398]));//creatures
+	labels.push_back(std::make_shared<CLabel>(283, 116, FONT_MEDIUM, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[399]));//spells
+	labels.push_back(std::make_shared<CLabel>(283, 146, FONT_MEDIUM, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[400]));//catapult
+	labels.push_back(std::make_shared<CLabel>(283, 176, FONT_MEDIUM, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[151]));//ballista
+	labels.push_back(std::make_shared<CLabel>(283, 206, FONT_MEDIUM, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[401]));//first aid tent
 
 	//creature info
-	labels.push_back(std::make_shared<CLabel>(283, 285, FONT_MEDIUM, TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[402]));//all stats
-	labels.push_back(std::make_shared<CLabel>(283, 315, FONT_MEDIUM, TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[403]));//spells only
+	labels.push_back(std::make_shared<CLabel>(283, 285, FONT_MEDIUM, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[402]));//all stats
+	labels.push_back(std::make_shared<CLabel>(283, 315, FONT_MEDIUM, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[403]));//spells only
 
 	//general options
-	labels.push_back(std::make_shared<CLabel>(61,  57, FONT_MEDIUM, TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[404]));
-	labels.push_back(std::make_shared<CLabel>(61,  90, FONT_MEDIUM, TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[405]));
-	labels.push_back(std::make_shared<CLabel>(61, 123, FONT_MEDIUM, TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[406]));
-	labels.push_back(std::make_shared<CLabel>(61, 156, FONT_MEDIUM, TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[407]));
+	labels.push_back(std::make_shared<CLabel>(61,  57, FONT_MEDIUM, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[404]));
+	labels.push_back(std::make_shared<CLabel>(61,  90, FONT_MEDIUM, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[405]));
+	labels.push_back(std::make_shared<CLabel>(61, 123, FONT_MEDIUM, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[406]));
+	labels.push_back(std::make_shared<CLabel>(61, 156, FONT_MEDIUM, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[407]));
 }
 
-void CBattleOptionsWindow::bDefaultf()
+void BattleOptionsWindow::bDefaultf()
 {
 	//TODO: implement
 }
 
-void CBattleOptionsWindow::bExitf()
+void BattleOptionsWindow::bExitf()
 {
 	close();
 }
 
-CBattleResultWindow::CBattleResultWindow(const BattleResult & br, CPlayerInterface & _owner)
+BattleResultWindow::BattleResultWindow(const BattleResult & br, CPlayerInterface & _owner)
 	: owner(_owner)
 {
 	OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
@@ -408,25 +417,25 @@ CBattleResultWindow::CBattleResultWindow(const BattleResult & br, CPlayerInterfa
 
 	if(br.winner == 0) //attacker won
 	{
-		labels.push_back(std::make_shared<CLabel>(59, 124, FONT_SMALL, CENTER, Colors::WHITE, CGI->generaltexth->allTexts[410]));
+		labels.push_back(std::make_shared<CLabel>(59, 124, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[410]));
 	}
 	else
 	{
-		labels.push_back(std::make_shared<CLabel>(59, 124, FONT_SMALL, CENTER, Colors::WHITE, CGI->generaltexth->allTexts[411]));
+		labels.push_back(std::make_shared<CLabel>(59, 124, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[411]));
 	}
 
 	if(br.winner == 1)
 	{
-		labels.push_back(std::make_shared<CLabel>(412, 124, FONT_SMALL, CENTER, Colors::WHITE, CGI->generaltexth->allTexts[410]));
+		labels.push_back(std::make_shared<CLabel>(412, 124, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[410]));
 	}
 	else
 	{
-		labels.push_back(std::make_shared<CLabel>(408, 124, FONT_SMALL, CENTER, Colors::WHITE, CGI->generaltexth->allTexts[411]));
+		labels.push_back(std::make_shared<CLabel>(408, 124, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[411]));
 	}
 
-	labels.push_back(std::make_shared<CLabel>(232, 302, FONT_BIG, CENTER, Colors::YELLOW,  CGI->generaltexth->allTexts[407]));
-	labels.push_back(std::make_shared<CLabel>(232, 332, FONT_SMALL, CENTER, Colors::WHITE, CGI->generaltexth->allTexts[408]));
-	labels.push_back(std::make_shared<CLabel>(232, 428, FONT_SMALL, CENTER, Colors::WHITE, CGI->generaltexth->allTexts[409]));
+	labels.push_back(std::make_shared<CLabel>(232, 302, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW,  CGI->generaltexth->allTexts[407]));
+	labels.push_back(std::make_shared<CLabel>(232, 332, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[408]));
+	labels.push_back(std::make_shared<CLabel>(232, 428, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[409]));
 
 	std::string sideNames[2] = {"N/A", "N/A"};
 
@@ -462,15 +471,15 @@ CBattleResultWindow::CBattleResultWindow(const BattleResult & br, CPlayerInterfa
 	}
 
 	//printing attacker and defender's names
-	labels.push_back(std::make_shared<CLabel>(89, 37, FONT_SMALL, TOPLEFT, Colors::WHITE, sideNames[0]));
-	labels.push_back(std::make_shared<CLabel>(381, 53, FONT_SMALL, BOTTOMRIGHT, Colors::WHITE, sideNames[1]));
+	labels.push_back(std::make_shared<CLabel>(89, 37, FONT_SMALL, ETextAlignment::TOPLEFT, Colors::WHITE, sideNames[0]));
+	labels.push_back(std::make_shared<CLabel>(381, 53, FONT_SMALL, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, sideNames[1]));
 
 	//printing casualties
 	for(int step = 0; step < 2; ++step)
 	{
 		if(br.casualties[step].size()==0)
 		{
-			labels.push_back(std::make_shared<CLabel>(235, 360 + 97 * step, FONT_SMALL, CENTER, Colors::WHITE, CGI->generaltexth->allTexts[523]));
+			labels.push_back(std::make_shared<CLabel>(235, 360 + 97 * step, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[523]));
 		}
 		else
 		{
@@ -481,7 +490,7 @@ CBattleResultWindow::CBattleResultWindow(const BattleResult & br, CPlayerInterfa
 				icons.push_back(std::make_shared<CAnimImage>("CPRSMALL", CGI->creatures()->getByIndex(elem.first)->getIconIndex(), 0, xPos, yPos));
 				std::ostringstream amount;
 				amount<<elem.second;
-				labels.push_back(std::make_shared<CLabel>(xPos + 16, yPos + 42, FONT_SMALL, CENTER, Colors::WHITE, amount.str()));
+				labels.push_back(std::make_shared<CLabel>(xPos + 16, yPos + 42, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, amount.str()));
 				xPos += 42;
 			}
 		}
@@ -518,7 +527,7 @@ CBattleResultWindow::CBattleResultWindow(const BattleResult & br, CPlayerInterfa
 			boost::algorithm::replace_first(str, "%d", boost::lexical_cast<std::string>(br.exp[weAreAttacker ? 0 : 1]));
 		}
 
-		description = std::make_shared<CTextBox>(str, Rect(69, 203, 330, 68), 0, FONT_SMALL, CENTER, Colors::WHITE);
+		description = std::make_shared<CTextBox>(str, Rect(69, 203, 330, 68), 0, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
 	}
 	else // we lose
 	{
@@ -546,31 +555,29 @@ CBattleResultWindow::CBattleResultWindow(const BattleResult & br, CPlayerInterfa
 		CCS->musich->playMusic(musicName, false, true);
 		CCS->videoh->open(videoName);
 
-		labels.push_back(std::make_shared<CLabel>(235, 235, FONT_SMALL, CENTER, Colors::WHITE, CGI->generaltexth->allTexts[text]));
+		labels.push_back(std::make_shared<CLabel>(235, 235, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[text]));
 	}
 }
 
-CBattleResultWindow::~CBattleResultWindow() = default;
-
-void CBattleResultWindow::activate()
+void BattleResultWindow::activate()
 {
 	owner.showingDialog->set(true);
 	CIntObject::activate();
 }
 
-void CBattleResultWindow::show(SDL_Surface * to)
+void BattleResultWindow::show(SDL_Surface * to)
 {
 	CIntObject::show(to);
 	CCS->videoh->update(pos.x + 107, pos.y + 70, screen, true, false);
 }
 
-void CBattleResultWindow::bExitf()
+void BattleResultWindow::bExitf()
 {
 	CPlayerInterface &intTmp = owner; //copy reference because "this" will be destructed soon
 
 	close();
 
-	if(dynamic_cast<CBattleInterface*>(GH.topInt().get()))
+	if(dynamic_cast<BattleInterface*>(GH.topInt().get()))
 		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,
@@ -579,113 +586,48 @@ void CBattleResultWindow::bExitf()
 	CCS->videoh->close();
 }
 
-Point CClickableHex::getXYUnitAnim(BattleHex hexNum, const CStack * stack, CBattleInterface * cbi)
-{
-	assert(cbi);
-
-	Point ret(-500, -500); //returned value
-	if(stack && stack->initialPosition < 0) //creatures in turrets
-	{
-		switch(stack->initialPosition)
-		{
-		case -2: //keep
-			ret = cbi->siegeH->town->town->clientInfo.siegePositions[18];
-			break;
-		case -3: //lower turret
-			ret = cbi->siegeH->town->town->clientInfo.siegePositions[19];
-			break;
-		case -4: //upper turret
-			ret = cbi->siegeH->town->town->clientInfo.siegePositions[20];
-			break;
-		}
-	}
-	else
-	{
-		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.y = basePos.y + 42 * hexNum.getY();
-
-		if (stack)
-		{
-			if(cbi->creDir[stack->ID])
-				ret.x += imageShiftX;
-			else
-				ret.x -= imageShiftX;
-
-			//shifting position for double - hex creatures
-			if(stack->doubleWide())
-			{
-				if(stack->side == BattleSide::ATTACKER)
-				{
-					if(cbi->creDir[stack->ID])
-						ret.x -= 44;
-				}
-				else
-				{
-					if(!cbi->creDir[stack->ID])
-						ret.x += 44;
-				}
-			}
-		}
-	}
-	//returning
-	return ret + CPlayerInterface::battleInt->pos;
-}
-
-void CClickableHex::hover(bool on)
+void ClickableHex::hover(bool on)
 {
 	hovered = on;
 	//Hoverable::hover(on);
 	if(!on && setAlterText)
 	{
-		myInterface->console->alterTxt = std::string();
+		myInterface->controlPanel->console->clear();
 		setAlterText = false;
 	}
 }
 
-CClickableHex::CClickableHex() : setAlterText(false), myNumber(-1), accessible(true), strictHovered(false), myInterface(nullptr)
+ClickableHex::ClickableHex() : setAlterText(false), myNumber(-1), strictHovered(false), myInterface(nullptr)
 {
 	addUsedEvents(LCLICK | RCLICK | HOVER | MOVE);
 }
 
-void CClickableHex::mouseMoved(const SDL_MouseMotionEvent &sEvent)
+void ClickableHex::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
-		{
-			strictHovered = false;
-		}
-		else //hovered pixel is inside hex
-		{
-			strictHovered = true;
-		}
-	}
+	strictHovered = myInterface->fieldController->isPixelInHex(Point(sEvent.x-pos.x, sEvent.y-pos.y));
 
 	if(hovered && strictHovered) //print attacked creature to console
 	{
 		const CStack * attackedStack = myInterface->getCurrentPlayerInterface()->cb->battleGetStackByPos(myNumber);
-		if(myInterface->console->alterTxt.size() == 0 &&attackedStack != nullptr &&
+		if( attackedStack != nullptr &&
 			attackedStack->owner != myInterface->getCurrentPlayerInterface()->playerID &&
 			attackedStack->alive())
 		{
 			MetaString text;
 			text.addTxt(MetaString::GENERAL_TXT, 220);
 			attackedStack->addNameReplacement(text);
-			myInterface->console->alterTxt = text.toString();
+			myInterface->controlPanel->console->write(text.toString());
 			setAlterText = true;
 		}
 	}
 	else if(setAlterText)
 	{
-		myInterface->console->alterTxt = std::string();
+		myInterface->controlPanel->console->clear();
 		setAlterText = false;
 	}
 }
 
-void CClickableHex::clickLeft(tribool down, bool previousState)
+void ClickableHex::clickLeft(tribool down, bool previousState)
 {
 	if(!down && hovered && strictHovered) //we've been really clicked!
 	{
@@ -693,7 +635,7 @@ void CClickableHex::clickLeft(tribool down, bool previousState)
 	}
 }
 
-void CClickableHex::clickRight(tribool down, bool previousState)
+void ClickableHex::clickRight(tribool down, bool previousState)
 {
 	const CStack * myst = myInterface->getCurrentPlayerInterface()->cb->battleGetStackByPos(myNumber); //stack info
 	if(hovered && strictHovered && myst!=nullptr)
@@ -706,9 +648,9 @@ void CClickableHex::clickRight(tribool down, bool previousState)
 	}
 }
 
-CStackQueue::CStackQueue(bool Embedded, CBattleInterface * _owner)
+StackQueue::StackQueue(bool Embedded, BattleInterface & owner)
 	: embedded(Embedded),
-	owner(_owner)
+	owner(owner)
 {
 	OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
 	if(embedded)
@@ -743,13 +685,11 @@ CStackQueue::CStackQueue(bool Embedded, CBattleInterface * _owner)
 	}
 }
 
-CStackQueue::~CStackQueue() = default;
-
-void CStackQueue::update()
+void StackQueue::update()
 {
 	std::vector<battle::Units> queueData;
 
-	owner->getCurrentPlayerInterface()->cb->battleGetTurnOrder(queueData, stackBoxes.size(), 0);
+	owner.getCurrentPlayerInterface()->cb->battleGetTurnOrder(queueData, stackBoxes.size(), 0);
 
 	size_t boxIndex = 0;
 
@@ -763,12 +703,12 @@ void CStackQueue::update()
 		stackBoxes[boxIndex]->setUnit(nullptr);
 }
 
-int32_t CStackQueue::getSiegeShooterIconID()
+int32_t StackQueue::getSiegeShooterIconID()
 {
-	return owner->siegeH->town->town->faction->index;
+	return owner.siegeController->getSiegedTown()->town->faction->index;
 }
 
-CStackQueue::StackBox::StackBox(CStackQueue * owner):
+StackQueue::StackBox::StackBox(StackQueue * owner):
 	owner(owner)
 {
 	OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
@@ -780,12 +720,12 @@ CStackQueue::StackBox::StackBox(CStackQueue * owner):
 	if(owner->embedded)
 	{
 		icon = std::make_shared<CAnimImage>(owner->icons, 0, 0, 5, 2);
-		amount = std::make_shared<CLabel>(pos.w/2, pos.h - 7, FONT_SMALL, CENTER, Colors::WHITE);
+		amount = std::make_shared<CLabel>(pos.w/2, pos.h - 7, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
 	}
 	else
 	{
 		icon = std::make_shared<CAnimImage>(owner->icons, 0, 0, 9, 1);
-		amount = std::make_shared<CLabel>(pos.w/2, pos.h - 8, FONT_MEDIUM, CENTER, Colors::WHITE);
+		amount = std::make_shared<CLabel>(pos.w/2, pos.h - 8, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE);
 
 		int icon_x = pos.w - 17;
 		int icon_y = pos.h - 18;
@@ -795,7 +735,7 @@ CStackQueue::StackBox::StackBox(CStackQueue * owner):
 	}
 }
 
-void CStackQueue::StackBox::setUnit(const battle::Unit * unit, size_t turn)
+void StackQueue::StackBox::setUnit(const battle::Unit * unit, size_t turn)
 {
 	if(unit)
 	{

+ 47 - 38
client/battle/CBattleInterfaceClasses.h → client/battle/BattleInterfaceClasses.h

@@ -1,5 +1,5 @@
 /*
- * CBattleInterfaceClasses.h, part of VCMI engine
+ * BattleInterfaceClasses.h, part of VCMI engine
  *
  * Authors: listed in file AUTHORS in main folder
  *
@@ -26,8 +26,9 @@ class Unit;
 
 VCMI_LIB_NAMESPACE_END
 
+class Canvas;
 struct SDL_Surface;
-class CBattleInterface;
+class BattleInterface;
 class CPicture;
 class CFilledTexture;
 class CButton;
@@ -39,27 +40,42 @@ class CAnimImage;
 class CPlayerInterface;
 
 /// Class which shows the console at the bottom of the battle screen and manages the text of the console
-class CBattleConsole : public CIntObject
+class BattleConsole : public CIntObject, public IStatusBar
 {
 private:
-	std::vector< std::string > texts; //a place where texts are stored
-	int lastShown; //last shown line of text
+	/// List of all texts added during battle, essentially - log of entire battle
+	std::vector< std::string > logEntries;
+
+	/// Current scrolling position, to allow showing older entries via scroll buttons
+	int scrollPosition;
+
+	/// current hover text set on mouse move, takes priority over log entries
+	std::string hoverText;
+
+	/// current text entered via in-game console, takes priority over both log entries and hover text
+	std::string consoleText;
+
+	/// if true then we are currently entering console text
+	bool enteringText;
 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;
+	BattleConsole(const Rect & position);
+	~BattleConsole();
+	void showAll(SDL_Surface * to) 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
-	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 scrollUp(ui32 by = 1); //scrolls console up by 'by' positions
 	void scrollDown(ui32 by = 1); //scrolls console up by 'by' positions
+
+	// IStatusBar interface
+	void write(const std::string & Text) override;
+	void clearIfMatching(const std::string & Text) override;
+	void clear() override;
+	void setEnteringMode(bool on) override;
+	void setEnteredText(const std::string & text) override;
 };
 
 /// Hero battle animation
-class CBattleHero : public CIntObject
+class BattleHero : public CIntObject
 {
 	void switchToNextPhase();
 public:
@@ -69,50 +85,48 @@ public:
 	std::shared_ptr<CAnimation> flagAnimation;
 
 	const CGHeroInstance * myHero; //this animation's hero instance
-	const CBattleInterface * myOwner; //battle interface to which this animation is assigned
+	const BattleInterface * myOwner; //battle interface to which this animation is assigned
 	int phase; //stage of animation
 	int nextPhase; //stage of animation to be set after current phase is fully displayed
 	int currentFrame, firstFrame, lastFrame; //frame of animation
 
 	size_t flagAnim;
 	ui8 animCount; //for flag animation
-	void show(SDL_Surface * to) override; //prints next frame of animation to to
+	void render(Canvas & canvas); //prints next frame of animation to to
 	void setPhase(int newPhase); //sets phase of hero animation
 	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 & animationPath, bool filpG, PlayerColor player, const CGHeroInstance * hero, const CBattleInterface * owner);
-	~CBattleHero();
+	BattleHero(const std::string & animationPath, bool filpG, PlayerColor player, const CGHeroInstance * hero, const BattleInterface & owner);
 };
 
-class CHeroInfoWindow : public CWindowObject
+class HeroInfoWindow : public CWindowObject
 {
 private:
 	std::vector<std::shared_ptr<CLabel>> labels;
 	std::vector<std::shared_ptr<CAnimImage>> icons;
 public:
-	CHeroInfoWindow(const InfoAboutHero & hero, Point * position);
+	HeroInfoWindow(const InfoAboutHero & hero, Point * position);
 };
 
 /// Class which manages the battle options window
-class CBattleOptionsWindow : public WindowBase
+class BattleOptionsWindow : public CWindowObject
 {
 private:
-	std::shared_ptr<CPicture> background;
 	std::shared_ptr<CButton> setToDefault;
 	std::shared_ptr<CButton> exit;
 	std::shared_ptr<CToggleGroup> animSpeeds;
 	std::vector<std::shared_ptr<CLabel>> labels;
 	std::vector<std::shared_ptr<CToggleButton>> toggles;
 public:
-	CBattleOptionsWindow(const SDL_Rect & position, CBattleInterface * owner);
+	BattleOptionsWindow(BattleInterface & owner);
 
 	void bDefaultf(); //default button callback
 	void bExitf(); //exit button callback
 };
 
 /// Class which is responsible for showing the battle result window
-class CBattleResultWindow : public WindowBase
+class BattleResultWindow : public WindowBase
 {
 private:
 	std::shared_ptr<CPicture> background;
@@ -122,8 +136,7 @@ private:
 	std::shared_ptr<CTextBox> description;
 	CPlayerInterface & owner;
 public:
-	CBattleResultWindow(const BattleResult & br, CPlayerInterface & _owner);
-	~CBattleResultWindow();
+	BattleResultWindow(const BattleResult & br, CPlayerInterface & _owner);
 
 	void bExitf(); //exit button callback
 
@@ -132,32 +145,29 @@ public:
 };
 
 /// Class which stands for a single hex field on a battlefield
-class CClickableHex : public CIntObject
+class ClickableHex : 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
-	//CStack * ourStack;
 	bool strictHovered; //for determining if hex is hovered by mouse (this is different problem than hex's graphic hovering)
-	CBattleInterface * myInterface; //interface that owns me
-	static Point getXYUnitAnim(BattleHex hexNum, const CStack * creature, CBattleInterface * cbi); //returns (x, y) of left top corner of animation
+	BattleInterface * myInterface; //interface that owns me
 
 	//for user interactions
 	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();
+	ClickableHex();
 };
 
 /// Shows the stack queue
-class CStackQueue : public CIntObject
+class StackQueue : public CIntObject
 {
 	class StackBox : public CIntObject
 	{
-		CStackQueue * owner;
+		StackQueue * owner;
 	public:
 		std::shared_ptr<CPicture> background;
 		std::shared_ptr<CAnimImage> icon;
@@ -165,13 +175,13 @@ class CStackQueue : public CIntObject
 		std::shared_ptr<CAnimImage> stateIcon;
 
 		void setUnit(const battle::Unit * unit, size_t turn = 0);
-		StackBox(CStackQueue * owner);
+		StackBox(StackQueue * owner);
 	};
 
 	static const int QUEUE_SIZE = 10;
 	std::shared_ptr<CFilledTexture> background;
 	std::vector<std::shared_ptr<StackBox>> stackBoxes;
-	CBattleInterface * owner;
+	BattleInterface & owner;
 
 	std::shared_ptr<CAnimation> icons;
 	std::shared_ptr<CAnimation> stateIcons;
@@ -180,7 +190,6 @@ class CStackQueue : public CIntObject
 public:
 	const bool embedded;
 
-	CStackQueue(bool Embedded, CBattleInterface * _owner);
-	~CStackQueue();
+	StackQueue(bool Embedded, BattleInterface & owner);
 	void update();
 };

+ 190 - 0
client/battle/BattleObstacleController.cpp

@@ -0,0 +1,190 @@
+/*
+ * BattleObstacleController.cpp, part of VCMI engine
+ *
+ * Authors: listed in file AUTHORS in main folder
+ *
+ * License: GNU General Public License v2.0 or later
+ * Full text of license available in license.txt file, in main folder
+ *
+ */
+#include "StdInc.h"
+#include "BattleObstacleController.h"
+
+#include "BattleInterface.h"
+#include "BattleFieldController.h"
+#include "BattleAnimationClasses.h"
+#include "BattleStacksController.h"
+#include "BattleRenderer.h"
+
+#include "../CPlayerInterface.h"
+#include "../gui/CAnimation.h"
+#include "../gui/Canvas.h"
+
+#include "../../CCallback.h"
+#include "../../lib/battle/CObstacleInstance.h"
+#include "../../lib/ObstacleHandler.h"
+
+BattleObstacleController::BattleObstacleController(BattleInterface & owner):
+	owner(owner)
+{
+	auto obst = owner.curInt->cb->battleGetAllObstacles();
+	for(auto & elem : obst)
+	{
+		if ( elem->obstacleType == CObstacleInstance::MOAT )
+			continue; // handled by siege controller;
+		loadObstacleImage(*elem);
+	}
+}
+
+void BattleObstacleController::loadObstacleImage(const CObstacleInstance & oi)
+{
+	std::string animationName;
+
+	if (auto spellObstacle = dynamic_cast<const SpellCreatedObstacle*>(&oi))
+	{
+		animationName = spellObstacle->animation;
+	}
+	else
+	{
+		assert( oi.obstacleType == CObstacleInstance::USUAL || oi.obstacleType == CObstacleInstance::ABSOLUTE_OBSTACLE);
+		animationName = oi.getInfo().animation;
+	}
+
+	if (animationsCache.count(animationName) == 0)
+	{
+		if (oi.obstacleType == CObstacleInstance::ABSOLUTE_OBSTACLE)
+		{
+			// obstacle uses single bitmap image for animations
+			auto animation = std::make_shared<CAnimation>();
+			animation->setCustom(animationName, 0, 0);
+			animationsCache[animationName] = animation;
+			animation->preload();
+		}
+		else
+		{
+			auto animation = std::make_shared<CAnimation>(animationName);
+			animationsCache[animationName] = animation;
+			animation->preload();
+		}
+	}
+	obstacleAnimations[oi.uniqueID] = animationsCache[animationName];
+}
+
+void BattleObstacleController::obstaclePlaced(const std::vector<std::shared_ptr<const CObstacleInstance>> & obstacles)
+{
+	assert(obstaclesBeingPlaced.empty());
+	for (auto const & oi : obstacles)
+		obstaclesBeingPlaced.push_back(oi->uniqueID);
+
+	for (auto const & oi : obstacles)
+	{
+		auto spellObstacle = dynamic_cast<const SpellCreatedObstacle*>(oi.get());
+
+		if (!spellObstacle)
+		{
+			logGlobal->error("I don't know how to animate appearing obstacle of type %d", (int)oi->obstacleType);
+			obstaclesBeingPlaced.erase(obstaclesBeingPlaced.begin());
+			continue;
+		}
+
+		auto animation = std::make_shared<CAnimation>(spellObstacle->appearAnimation);
+		animation->preload();
+
+		auto first = animation->getImage(0, 0);
+		if(!first)
+		{
+			obstaclesBeingPlaced.erase(obstaclesBeingPlaced.begin());
+			continue;
+		}
+
+		//TODO: sound
+		//soundBase::QUIKSAND
+		//soundBase::LANDMINE
+
+		//we assume here that effect graphics have the same size as the usual obstacle image
+		// -> if we know how to blit obstacle, let's blit the effect in the same place
+		Point whereTo = getObstaclePosition(first, *oi);
+		owner.stacksController->addNewAnim(new CPointEffectAnimation(owner, soundBase::invalid, spellObstacle->appearAnimation, whereTo, oi->pos, CPointEffectAnimation::WAIT_FOR_SOUND));
+
+		//so when multiple obstacles are added, they show up one after another
+		owner.waitForAnims();
+
+		obstaclesBeingPlaced.erase(obstaclesBeingPlaced.begin());
+		loadObstacleImage(*spellObstacle);
+	}
+}
+
+void BattleObstacleController::showAbsoluteObstacles(Canvas & canvas, const Point & offset)
+{
+	//Blit absolute obstacles
+	for(auto & oi : owner.curInt->cb->battleGetAllObstacles())
+	{
+		if(oi->obstacleType == CObstacleInstance::ABSOLUTE_OBSTACLE)
+		{
+			auto img = getObstacleImage(*oi);
+			if(img)
+				canvas.draw(img, Point(offset.x + oi->getInfo().width, offset.y + oi->getInfo().height));
+		}
+	}
+}
+
+void BattleObstacleController::collectRenderableObjects(BattleRenderer & renderer)
+{
+	for (auto obstacle : owner.curInt->cb->battleGetAllObstacles())
+	{
+		if (obstacle->obstacleType == CObstacleInstance::ABSOLUTE_OBSTACLE)
+			continue;
+
+		if (obstacle->obstacleType == CObstacleInstance::MOAT)
+			continue;
+
+		renderer.insert(EBattleFieldLayer::OBSTACLES, obstacle->pos, [this, obstacle]( BattleRenderer::RendererRef canvas ){
+			auto img = getObstacleImage(*obstacle);
+			if(img)
+			{
+				Point p = getObstaclePosition(img, *obstacle);
+				canvas.draw(img, p);
+			}
+		});
+	}
+}
+
+std::shared_ptr<IImage> BattleObstacleController::getObstacleImage(const CObstacleInstance & oi)
+{
+	int frameIndex = (owner.animCount+1) *25 / owner.getAnimSpeed();
+	std::shared_ptr<CAnimation> animation;
+
+	if (obstacleAnimations.count(oi.uniqueID) == 0)
+	{
+		if (boost::range::find(obstaclesBeingPlaced, oi.uniqueID) != obstaclesBeingPlaced.end())
+		{
+			// obstacle is not loaded yet, don't show anything
+			return nullptr;
+		}
+		else
+		{
+			assert(0); // how?
+			loadObstacleImage(oi);
+		}
+	}
+
+	animation = obstacleAnimations[oi.uniqueID];
+	assert(animation);
+
+	if(animation)
+	{
+		frameIndex %= animation->size(0);
+		return animation->getImage(frameIndex, 0);
+	}
+	return nullptr;
+}
+
+Point BattleObstacleController::getObstaclePosition(std::shared_ptr<IImage> image, const CObstacleInstance & obstacle)
+{
+	int offset = obstacle.getAnimationYOffset(image->height());
+
+	Rect r = owner.fieldController->hexPositionAbsolute(obstacle.pos);
+	r.y += 42 - image->height() + offset;
+
+	return r.topLeft();
+}

+ 58 - 0
client/battle/BattleObstacleController.h

@@ -0,0 +1,58 @@
+/*
+ * BattleObstacleController.h, part of VCMI engine
+ *
+ * Authors: listed in file AUTHORS in main folder
+ *
+ * License: GNU General Public License v2.0 or later
+ * Full text of license available in license.txt file, in main folder
+ *
+ */
+#pragma once
+
+VCMI_LIB_NAMESPACE_BEGIN
+
+struct BattleHex;
+struct CObstacleInstance;
+
+VCMI_LIB_NAMESPACE_END
+
+class IImage;
+class Canvas;
+class CAnimation;
+class BattleInterface;
+class BattleRenderer;
+struct Point;
+
+/// Controls all currently active projectiles on the battlefield
+/// (with exception of moat, which is apparently handled by siege controller)
+class BattleObstacleController
+{
+	BattleInterface & owner;
+
+	/// cached animations of all obstacles in current battle
+	std::map<std::string, std::shared_ptr<CAnimation>> animationsCache;
+
+	/// list of all obstacles that are currently being rendered
+	std::map<si32, std::shared_ptr<CAnimation>> obstacleAnimations;
+
+	/// semi-debug member, contains obstacles that should not yet be visible due to ongoing placement animation
+	/// used only for sanity checks to ensure that there are no invisible obstacles
+	std::vector<si32> obstaclesBeingPlaced;
+
+	void loadObstacleImage(const CObstacleInstance & oi);
+
+	std::shared_ptr<IImage> getObstacleImage(const CObstacleInstance & oi);
+	Point getObstaclePosition(std::shared_ptr<IImage> image, const CObstacleInstance & obstacle);
+
+public:
+	BattleObstacleController(BattleInterface & owner);
+
+	/// call-in from network pack, add newly placed obstacles with any required animations
+	void obstaclePlaced(const std::vector<std::shared_ptr<const CObstacleInstance>> & oi);
+
+	/// renders all "absolute" obstacles
+	void showAbsoluteObstacles(Canvas & canvas, const Point & offset);
+
+	/// adds all non-"absolute" visible obstacles for rendering
+	void collectRenderableObjects(BattleRenderer & renderer);
+};

+ 373 - 0
client/battle/BattleProjectileController.cpp

@@ -0,0 +1,373 @@
+/*
+ * BattleProjectileController.cpp, part of VCMI engine
+ *
+ * Authors: listed in file AUTHORS in main folder
+ *
+ * License: GNU General Public License v2.0 or later
+ * Full text of license available in license.txt file, in main folder
+ *
+ */
+#include "StdInc.h"
+#include "BattleProjectileController.h"
+
+#include "BattleInterface.h"
+#include "BattleSiegeController.h"
+#include "BattleStacksController.h"
+#include "CreatureAnimation.h"
+
+#include "../gui/Geometries.h"
+#include "../gui/CAnimation.h"
+#include "../gui/Canvas.h"
+#include "../gui/CGuiHandler.h"
+#include "../CGameInfo.h"
+
+#include "../../lib/CStack.h"
+#include "../../lib/mapObjects/CGTownInstance.h"
+
+static double calculateCatapultParabolaY(const Point & from, const Point & dest, int x)
+{
+	double facA = 0.005; // seems to be constant
+
+	// system of 2 linear equations, solutions of which are missing coefficients
+	// for quadratic equation a*x*x + b*x + c
+	double eq[2][3] = {
+		{ static_cast<double>(from.x), 1.0, from.y - facA*from.x*from.x },
+		{ static_cast<double>(dest.x), 1.0, dest.y - facA*dest.x*dest.x }
+	};
+
+	// solve system via determinants
+	double det  = eq[0][0] *eq[1][1] - eq[1][0] *eq[0][1];
+	double detB = eq[0][2] *eq[1][1] - eq[1][2] *eq[0][1];
+	double detC = eq[0][0] *eq[1][2] - eq[1][0] *eq[0][2];
+
+	double facB = detB / det;
+	double facC = detC / det;
+
+	return facA *pow(x, 2.0) + facB *x + facC;
+}
+
+void ProjectileMissile::show(Canvas & canvas)
+{
+	logAnim->info("Projectile rendering, %d / %d", step, steps);
+	size_t group = reverse ? 1 : 0;
+	auto image = animation->getImage(frameNum, group, true);
+
+	if(image)
+	{
+		float progress = float(step) / steps;
+
+		Point pos {
+			CSDL_Ext::lerp(from.x, dest.x, progress) - image->width() / 2,
+			CSDL_Ext::lerp(from.y, dest.y, progress) - image->height() / 2,
+		};
+
+		canvas.draw(image, pos);
+	}
+	++step;
+}
+
+void ProjectileAnimatedMissile::show(Canvas & canvas)
+{
+	ProjectileMissile::show(canvas);
+	frameProgress += AnimationControls::getSpellEffectSpeed() * GH.mainFPSmng->getElapsedMilliseconds() / 1000;
+	size_t animationSize = animation->size(reverse ? 1 : 0);
+	while (frameProgress > animationSize)
+		frameProgress -= animationSize;
+
+	frameNum = std::floor(frameProgress);
+}
+
+void ProjectileCatapult::show(Canvas & canvas)
+{
+	auto image = animation->getImage(frameNum, 0, true);
+
+	if(image)
+	{
+		float progress = float(step) / steps;
+
+		int posX = CSDL_Ext::lerp(from.x, dest.x, progress);
+		int posY = calculateCatapultParabolaY(from, dest, posX);
+		Point pos(posX, posY);
+
+		canvas.draw(image, pos);
+
+		frameNum = (frameNum + 1) % animation->size(0);
+	}
+	++step;
+}
+
+void ProjectileRay::show(Canvas & canvas)
+{
+	float progress = float(step) / steps;
+
+	Point curr {
+		CSDL_Ext::lerp(from.x, dest.x, progress),
+		CSDL_Ext::lerp(from.y, dest.y, progress),
+	};
+
+	Point length = curr - from;
+
+	//select axis to draw ray on, we want angle to be less than 45 degrees so individual sub-rays won't overlap each other
+
+	if (std::abs(length.x) > std::abs(length.y)) // draw in horizontal axis
+	{
+		int y1 =  from.y - rayConfig.size() / 2;
+		int y2 =  curr.y - rayConfig.size() / 2;
+
+		int x1 = from.x;
+		int x2 = curr.x;
+
+		for (size_t i = 0; i < rayConfig.size(); ++i)
+		{
+			auto ray = rayConfig[i];
+			SDL_Color beginColor{ ray.r1, ray.g1, ray.b1, ray.a1};
+			SDL_Color endColor  { ray.r2, ray.g2, ray.b2, ray.a2};
+
+			canvas.drawLine(Point(x1, y1 + i), Point(x2, y2+i), beginColor, endColor);
+		}
+	}
+	else // draw in vertical axis
+	{
+		int x1 = from.x - rayConfig.size() / 2;
+		int x2 = curr.x - rayConfig.size() / 2;
+
+		int y1 = from.y;
+		int y2 = curr.y;
+
+		for (size_t i = 0; i < rayConfig.size(); ++i)
+		{
+			auto ray = rayConfig[i];
+			SDL_Color beginColor{ ray.r1, ray.g1, ray.b1, ray.a1};
+			SDL_Color endColor  { ray.r2, ray.g2, ray.b2, ray.a2};
+
+			canvas.drawLine(Point(x1 + i, y1), Point(x2 + i, y2), beginColor, endColor);
+		}
+	}
+	++step;
+}
+
+BattleProjectileController::BattleProjectileController(BattleInterface & owner):
+	owner(owner)
+{}
+
+const CCreature & BattleProjectileController::getShooter(const CStack * stack) const
+{
+	const CCreature * creature = stack->getCreature();
+
+	if(creature->idNumber == CreatureID::ARROW_TOWERS)
+		creature = owner.siegeController->getTurretCreature();
+
+	if(creature->animation.missleFrameAngles.empty())
+	{
+		logAnim->error("Mod error: Creature '%s' on the Archer's tower is not a shooter. Mod should be fixed. Trying to use archer's data instead...", creature->nameSing);
+		creature = CGI->creh->objects[CreatureID::ARCHER];
+	}
+
+	return *creature;
+}
+
+bool BattleProjectileController::stackUsesRayProjectile(const CStack * stack) const
+{
+	return !getShooter(stack).animation.projectileRay.empty();
+}
+
+bool BattleProjectileController::stackUsesMissileProjectile(const CStack * stack) const
+{
+	return !getShooter(stack).animation.projectileImageName.empty();
+}
+
+void BattleProjectileController::initStackProjectile(const CStack * stack)
+{
+	if (!stackUsesMissileProjectile(stack))
+		return;
+
+	const CCreature & creature = getShooter(stack);
+	projectilesCache[creature.animation.projectileImageName] = createProjectileImage(creature.animation.projectileImageName);
+}
+
+std::shared_ptr<CAnimation> BattleProjectileController::createProjectileImage(const std::string & path )
+{
+	std::shared_ptr<CAnimation> projectile = std::make_shared<CAnimation>(path);
+	projectile->preload();
+
+	if(projectile->size(1) != 0)
+		logAnim->error("Expected empty group 1 in stack projectile");
+	else
+		projectile->createFlippedGroup(0, 1);
+
+	return projectile;
+}
+
+std::shared_ptr<CAnimation> BattleProjectileController::getProjectileImage(const CStack * stack)
+{
+	const CCreature & creature = getShooter(stack);
+	std::string imageName = creature.animation.projectileImageName;
+
+	if (!projectilesCache.count(imageName))
+		initStackProjectile(stack);
+
+	return projectilesCache[imageName];
+}
+
+void BattleProjectileController::emitStackProjectile(const CStack * stack)
+{
+	int stackID = stack ? stack->ID : -1;
+
+	for (auto projectile : projectiles)
+	{
+		if ( !projectile->playing && projectile->shooterID == stackID)
+		{
+			projectile->playing = true;
+			return;
+		}
+	}
+}
+
+void BattleProjectileController::showProjectiles(Canvas & canvas)
+{
+	for ( auto projectile: projectiles)
+	{
+		if ( projectile->playing )
+			projectile->show(canvas);
+	}
+
+	vstd::erase_if(projectiles, [&](const std::shared_ptr<ProjectileBase> & projectile){
+		return projectile->step > projectile->steps;
+	});
+}
+
+bool BattleProjectileController::hasActiveProjectile(const CStack * stack) const
+{
+	int stackID = stack ? stack->ID : -1;
+
+	for(auto const & instance : projectiles)
+	{
+		if(instance->shooterID == stackID)
+		{
+			return true;
+		}
+	}
+	return false;
+}
+
+int BattleProjectileController::computeProjectileFlightTime( Point from, Point dest, double animSpeed)
+{
+	double distanceSquared = (dest.x - from.x) * (dest.x - from.x) + (dest.y - from.y) * (dest.y - from.y);
+	double distance = sqrt(distanceSquared);
+	int steps = std::round(distance / animSpeed);
+
+	if (steps > 0)
+		return steps;
+	return 1;
+}
+
+int BattleProjectileController::computeProjectileFrameID( Point from, Point dest, const CStack * stack)
+{
+	const CCreature & creature = getShooter(stack);
+
+	auto & angles = creature.animation.missleFrameAngles;
+	auto animation = getProjectileImage(stack);
+
+	// only frames below maxFrame are usable: anything  higher is either no present or we don't know when it should be used
+	size_t maxFrame = std::min<size_t>(angles.size(), animation->size(0));
+
+	assert(maxFrame > 0);
+	double projectileAngle = -atan2(dest.y - from.y, std::abs(dest.x - from.x));
+
+	// values in angles array indicate position from which this frame was rendered, in degrees.
+	// possible range is 90 ... -90, where projectile for +90 will be used for shooting upwards, +0 for shots towards right and -90 for downwards shots
+	// find frame that has closest angle to one that we need for this shot
+	int bestID = 0;
+	double bestDiff = fabs( angles[0] / 180 * M_PI - projectileAngle );
+
+	for (int i=1; i<maxFrame; i++)
+	{
+		double currentDiff = fabs( angles[i] / 180 * M_PI - projectileAngle );
+		if (currentDiff < bestDiff)
+		{
+			bestID = i;
+			bestDiff = currentDiff;
+		}
+	}
+	return bestID;
+}
+
+void BattleProjectileController::createCatapultProjectile(const CStack * shooter, Point from, Point dest)
+{
+	auto catapultProjectile       = new ProjectileCatapult();
+
+	catapultProjectile->animation = getProjectileImage(shooter);
+	catapultProjectile->frameNum  = 0;
+	catapultProjectile->step      = 0;
+	catapultProjectile->steps     = computeProjectileFlightTime(from, dest, AnimationControls::getCatapultSpeed());
+	catapultProjectile->from      = from;
+	catapultProjectile->dest      = dest;
+	catapultProjectile->shooterID = shooter->ID;
+	catapultProjectile->step      = 0;
+	catapultProjectile->playing   = false;
+
+	projectiles.push_back(std::shared_ptr<ProjectileBase>(catapultProjectile));
+}
+
+void BattleProjectileController::createProjectile(const CStack * shooter, Point from, Point dest)
+{
+	const CCreature & shooterInfo = getShooter(shooter);
+
+	std::shared_ptr<ProjectileBase> projectile;
+	if (stackUsesRayProjectile(shooter) && stackUsesMissileProjectile(shooter))
+	{
+		logAnim->error("Mod error: Creature '%s' has both missile and ray projectiles configured. Mod should be fixed. Using ray projectile configuration...", shooterInfo.nameSing);
+	}
+
+	if (stackUsesRayProjectile(shooter))
+	{
+		auto rayProjectile = new ProjectileRay();
+		projectile.reset(rayProjectile);
+
+		rayProjectile->rayConfig = shooterInfo.animation.projectileRay;
+	}
+	else if (stackUsesMissileProjectile(shooter))
+	{
+		auto missileProjectile = new ProjectileMissile();
+		projectile.reset(missileProjectile);
+
+		missileProjectile->animation = getProjectileImage(shooter);
+		missileProjectile->reverse  = !owner.stacksController->facingRight(shooter);
+		missileProjectile->frameNum = computeProjectileFrameID(from, dest, shooter);
+	}
+
+	projectile->steps     = computeProjectileFlightTime(from, dest, AnimationControls::getProjectileSpeed());
+	projectile->from      = from;
+	projectile->dest      = dest;
+	projectile->shooterID = shooter->ID;
+	projectile->step      = 0;
+	projectile->playing   = false;
+
+	projectiles.push_back(projectile);
+}
+
+void BattleProjectileController::createSpellProjectile(const CStack * shooter, Point from, Point dest, const CSpell * spell)
+{
+	double projectileAngle = std::abs(atan2(dest.x - from.x, dest.y - from.y));
+	std::string animToDisplay = spell->animationInfo.selectProjectile(projectileAngle);
+
+	assert(!animToDisplay.empty());
+
+	if(!animToDisplay.empty())
+	{
+		auto projectile = new ProjectileAnimatedMissile();
+
+		projectile->animation     = createProjectileImage(animToDisplay);
+		projectile->frameProgress = 0;
+		projectile->frameNum      = 0;
+		projectile->reverse       = from.x > dest.x;
+		projectile->from          = from;
+		projectile->dest          = dest;
+		projectile->shooterID     = shooter ? shooter->ID : -1;
+		projectile->step          = 0;
+		projectile->steps         = computeProjectileFlightTime(from, dest, AnimationControls::getSpellEffectSpeed());
+		projectile->playing       = false;
+
+		projectiles.push_back(std::shared_ptr<ProjectileBase>(projectile));
+	}
+}

+ 118 - 0
client/battle/BattleProjectileController.h

@@ -0,0 +1,118 @@
+/*
+ * BattleSiegeController.h, part of VCMI engine
+ *
+ * Authors: listed in file AUTHORS in main folder
+ *
+ * License: GNU General Public License v2.0 or later
+ * Full text of license available in license.txt file, in main folder
+ *
+ */
+#pragma once
+
+#include "../../lib/CCreatureHandler.h"
+#include "../gui/Geometries.h"
+
+VCMI_LIB_NAMESPACE_BEGIN
+
+class CStack;
+class CSpell;
+
+VCMI_LIB_NAMESPACE_END
+
+struct Point;
+class CAnimation;
+class Canvas;
+class BattleInterface;
+
+/// Base class for projectiles
+struct ProjectileBase
+{
+	virtual ~ProjectileBase() = default;
+	virtual void show(Canvas & canvas) =  0;
+
+	Point from; // initial position on the screen
+	Point dest; // target position on the screen
+
+	int step;      // current step counter
+	int steps;     // total number of steps/frames to show
+	int shooterID; // ID of shooter stack
+	bool playing;  // if set to true, projectile animation is playing, e.g. flying to target
+};
+
+/// Projectile for most shooters - render pre-selected frame moving in straight line from origin to destination
+struct ProjectileMissile : ProjectileBase
+{
+	void show(Canvas & canvas) override;
+
+	std::shared_ptr<CAnimation> animation;
+	int frameNum;  // frame to display from projectile animation
+	bool reverse;  // if true, projectile will be flipped by vertical axis
+};
+
+/// Projectile for spell - render animation moving in straight line from origin to destination
+struct ProjectileAnimatedMissile : ProjectileMissile
+{
+	void show(Canvas & canvas) override;
+	float frameProgress;
+};
+
+/// Projectile for catapult - render spinning projectile moving at parabolic trajectory to its destination
+struct ProjectileCatapult : ProjectileBase
+{
+	void show(Canvas & canvas) override;
+
+	std::shared_ptr<CAnimation> animation;
+	int frameNum;  // frame to display from projectile animation
+};
+
+/// Projectile for mages/evil eye - render ray expanding from origin position to destination
+struct ProjectileRay : ProjectileBase
+{
+	void show(Canvas & canvas) override;
+
+	std::vector<CCreature::CreatureAnimation::RayColor> rayConfig;
+};
+
+/// Class that manages all ongoing projectiles in the game
+/// ... even though in H3 only 1 projectile can be on screen at any point of time
+class BattleProjectileController
+{
+	BattleInterface & owner;
+
+	/// all projectiles loaded during current battle
+	std::map<std::string, std::shared_ptr<CAnimation>> projectilesCache;
+
+	/// projectiles currently flying on battlefield
+	std::vector<std::shared_ptr<ProjectileBase>> projectiles;
+
+	std::shared_ptr<CAnimation> getProjectileImage(const CStack * stack);
+	std::shared_ptr<CAnimation> createProjectileImage(const std::string & path );
+	void initStackProjectile(const CStack * stack);
+
+	bool stackUsesRayProjectile(const CStack * stack) const;
+	bool stackUsesMissileProjectile(const CStack * stack) const;
+
+	void showProjectile(Canvas & canvas, std::shared_ptr<ProjectileBase> projectile);
+
+	const CCreature & getShooter(const CStack * stack) const;
+
+	int computeProjectileFrameID( Point from, Point dest, const CStack * stack);
+	int computeProjectileFlightTime( Point from, Point dest, double speed);
+
+public:
+	BattleProjectileController(BattleInterface & owner);
+
+	/// renders all currently active projectiles
+	void showProjectiles(Canvas & canvas);
+
+	/// returns true if stack has projectile that is yet to hit target
+	bool hasActiveProjectile(const CStack * stack) const;
+
+	/// starts rendering previously created projectile
+	void emitStackProjectile(const CStack * stack);
+
+	/// creates (but not emits!) projectile and initializes it based on parameters
+	void createProjectile(const CStack * shooter, Point from, Point dest);
+	void createSpellProjectile(const CStack * shooter, Point from, Point dest, const CSpell * spell);
+	void createCatapultProjectile(const CStack * shooter, Point from, Point dest);
+};

+ 71 - 0
client/battle/BattleRenderer.cpp

@@ -0,0 +1,71 @@
+/*
+ * BattleFieldController.cpp, part of VCMI engine
+ *
+ * Authors: listed in file AUTHORS in main folder
+ *
+ * License: GNU General Public License v2.0 or later
+ * Full text of license available in license.txt file, in main folder
+ *
+ */
+#include "StdInc.h"
+#include "BattleRenderer.h"
+
+#include "BattleInterface.h"
+#include "BattleEffectsController.h"
+#include "BattleSiegeController.h"
+#include "BattleStacksController.h"
+#include "BattleObstacleController.h"
+
+void BattleRenderer::collectObjects()
+{
+	owner.collectRenderableObjects(*this);
+	owner.effectsController->collectRenderableObjects(*this);
+	owner.obstacleController->collectRenderableObjects(*this);
+	owner.stacksController->collectRenderableObjects(*this);
+	if (owner.siegeController)
+		owner.siegeController->collectRenderableObjects(*this);
+}
+
+void BattleRenderer::sortObjects()
+{
+	auto getRow = [](const RenderableInstance & object) -> int
+	{
+		if (object.tile.isValid())
+			return object.tile.getY();
+
+		if ( object.tile == BattleHex::HEX_BEFORE_ALL )
+			return -1;
+
+		assert( object.tile == BattleHex::HEX_AFTER_ALL || object.tile == BattleHex::INVALID);
+		return GameConstants::BFIELD_HEIGHT;
+	};
+
+	std::stable_sort(objects.begin(), objects.end(), [&](const RenderableInstance & left, const RenderableInstance & right){
+		if ( getRow(left) != getRow(right))
+			return getRow(left) < getRow(right);
+		return left.layer < right.layer;
+	});
+}
+
+void BattleRenderer::renderObjects(BattleRenderer::RendererRef targetCanvas)
+{
+	for (auto const & object : objects)
+		object.functor(targetCanvas);
+}
+
+BattleRenderer::BattleRenderer(BattleInterface & owner):
+	owner(owner)
+{
+}
+
+void BattleRenderer::insert(EBattleFieldLayer layer, BattleHex tile, BattleRenderer::RenderFunctor functor)
+{
+	objects.push_back({functor, layer, tile});
+}
+
+void BattleRenderer::execute(BattleRenderer::RendererRef targetCanvas)
+{
+	collectObjects();
+	sortObjects();
+	renderObjects(targetCanvas);
+}

+ 54 - 0
client/battle/BattleRenderer.h

@@ -0,0 +1,54 @@
+/*
+ * BattleFieldController.h, part of VCMI engine
+ *
+ * Authors: listed in file AUTHORS in main folder
+ *
+ * License: GNU General Public License v2.0 or later
+ * Full text of license available in license.txt file, in main folder
+ *
+ */
+#pragma once
+
+#include "../../lib/battle/BattleHex.h"
+
+class Canvas;
+class BattleInterface;
+
+enum class EBattleFieldLayer {
+					   // confirmed ordering requirements:
+	OBSTACLES     = 0,
+	CORPSES       = 0,
+	WALLS         = 1,
+	HEROES        = 1,
+	STACKS        = 1, // after corpses, obstacles
+	BATTLEMENTS   = 2, // after stacks
+	STACK_AMOUNTS = 2, // after stacks, obstacles, corpses
+	EFFECTS       = 3, // after obstacles, battlements
+};
+
+class BattleRenderer
+{
+public:
+	using RendererRef = Canvas &;
+	using RenderFunctor = std::function<void(RendererRef)>;
+
+private:
+	BattleInterface & owner;
+
+	struct RenderableInstance
+	{
+		RenderFunctor functor;
+		EBattleFieldLayer layer;
+		BattleHex tile;
+	};
+	std::vector<RenderableInstance> objects;
+
+	void collectObjects();
+	void sortObjects();
+	void renderObjects(RendererRef targetCanvas);
+public:
+	BattleRenderer(BattleInterface & owner);
+
+	void insert(EBattleFieldLayer layer, BattleHex tile, RenderFunctor functor);
+	void execute(RendererRef targetCanvas);
+};

+ 368 - 0
client/battle/BattleSiegeController.cpp

@@ -0,0 +1,368 @@
+/*
+ * BattleSiegeController.cpp, part of VCMI engine
+ *
+ * Authors: listed in file AUTHORS in main folder
+ *
+ * License: GNU General Public License v2.0 or later
+ * Full text of license available in license.txt file, in main folder
+ *
+ */
+#include "StdInc.h"
+#include "BattleSiegeController.h"
+
+#include "BattleAnimationClasses.h"
+#include "BattleInterface.h"
+#include "BattleInterfaceClasses.h"
+#include "BattleStacksController.h"
+#include "BattleFieldController.h"
+#include "BattleRenderer.h"
+
+#include "../CMusicHandler.h"
+#include "../CGameInfo.h"
+#include "../CPlayerInterface.h"
+#include "../gui/CAnimation.h"
+#include "../gui/Canvas.h"
+
+#include "../../CCallback.h"
+#include "../../lib/NetPacks.h"
+#include "../../lib/CStack.h"
+#include "../../lib/mapObjects/CGTownInstance.h"
+
+std::string BattleSiegeController::getWallPieceImageName(EWallVisual::EWallVisual what, EWallState::EWallState state) const
+{
+	auto getImageIndex = [&]() -> int
+	{
+		switch (state)
+		{
+		case EWallState::INTACT :
+			return 1;
+		case EWallState::DAMAGED :
+			// towers don't have separate image here - INTACT and DAMAGED is 1, DESTROYED is 2
+			if(what == EWallVisual::KEEP || what == EWallVisual::BOTTOM_TOWER || what == EWallVisual::UPPER_TOWER)
+				return 1;
+			else
+				return 2;
+		case EWallState::DESTROYED :
+			if (what == EWallVisual::KEEP || what == EWallVisual::BOTTOM_TOWER || what == EWallVisual::UPPER_TOWER)
+				return 2;
+			else
+				return 3;
+		}
+		return 1;
+	};
+
+	const std::string & prefix = town->town->clientInfo.siegePrefix;
+	std::string addit = boost::lexical_cast<std::string>(getImageIndex());
+
+	switch(what)
+	{
+	case EWallVisual::BACKGROUND_WALL:
+		{
+			switch(town->town->faction->index)
+			{
+			case ETownType::RAMPART:
+			case ETownType::NECROPOLIS:
+			case ETownType::DUNGEON:
+			case ETownType::STRONGHOLD:
+				return prefix + "TPW1.BMP";
+			default:
+				return prefix + "TPWL.BMP";
+			}
+		}
+	case EWallVisual::KEEP:
+		return prefix + "MAN" + addit + ".BMP";
+	case EWallVisual::BOTTOM_TOWER:
+		return prefix + "TW1" + addit + ".BMP";
+	case EWallVisual::BOTTOM_WALL:
+		return prefix + "WA1" + addit + ".BMP";
+	case EWallVisual::WALL_BELLOW_GATE:
+		return prefix + "WA3" + addit + ".BMP";
+	case EWallVisual::WALL_OVER_GATE:
+		return prefix + "WA4" + addit + ".BMP";
+	case EWallVisual::UPPER_WALL:
+		return prefix + "WA6" + addit + ".BMP";
+	case EWallVisual::UPPER_TOWER:
+		return prefix + "TW2" + addit + ".BMP";
+	case EWallVisual::GATE:
+		return prefix + "DRW" + addit + ".BMP";
+	case EWallVisual::GATE_ARCH:
+		return prefix + "ARCH.BMP";
+	case EWallVisual::BOTTOM_STATIC_WALL:
+		return prefix + "WA2.BMP";
+	case EWallVisual::UPPER_STATIC_WALL:
+		return prefix + "WA5.BMP";
+	case EWallVisual::MOAT:
+		return prefix + "MOAT.BMP";
+	case EWallVisual::MOAT_BANK:
+		return prefix + "MLIP.BMP";
+	case EWallVisual::KEEP_BATTLEMENT:
+		return prefix + "MANC.BMP";
+	case EWallVisual::BOTTOM_BATTLEMENT:
+		return prefix + "TW1C.BMP";
+	case EWallVisual::UPPER_BATTLEMENT:
+		return prefix + "TW2C.BMP";
+	default:
+		return "";
+	}
+}
+
+void BattleSiegeController::showWallPiece(Canvas & canvas, EWallVisual::EWallVisual what, const Point & offset)
+{
+	auto & ci = town->town->clientInfo;
+	auto const & pos = ci.siegePositions[what];
+
+	if ( wallPieceImages[what])
+		canvas.draw(wallPieceImages[what], offset + Point(pos.x, pos.y));
+}
+
+std::string BattleSiegeController::getBattleBackgroundName() const
+{
+	const std::string & prefix = town->town->clientInfo.siegePrefix;
+	return prefix + "BACK.BMP";
+}
+
+bool BattleSiegeController::getWallPieceExistance(EWallVisual::EWallVisual what) const
+{
+	//FIXME: use this instead of buildings test?
+	//ui8 siegeLevel = owner.curInt->cb->battleGetSiegeLevel();
+
+	switch (what)
+	{
+	case EWallVisual::MOAT:              return town->hasBuilt(BuildingID::CITADEL) && town->town->faction->index != ETownType::TOWER;
+	case EWallVisual::MOAT_BANK:         return town->hasBuilt(BuildingID::CITADEL) && town->town->faction->index != ETownType::TOWER && town->town->faction->index != ETownType::NECROPOLIS;
+	case EWallVisual::KEEP_BATTLEMENT:   return town->hasBuilt(BuildingID::CITADEL) && EWallState::EWallState(owner.curInt->cb->battleGetWallState(EWallPart::KEEP)) != EWallState::DESTROYED;
+	case EWallVisual::UPPER_BATTLEMENT:  return town->hasBuilt(BuildingID::CASTLE) && EWallState::EWallState(owner.curInt->cb->battleGetWallState(EWallPart::UPPER_TOWER)) != EWallState::DESTROYED;
+	case EWallVisual::BOTTOM_BATTLEMENT: return town->hasBuilt(BuildingID::CASTLE) && EWallState::EWallState(owner.curInt->cb->battleGetWallState(EWallPart::BOTTOM_TOWER)) != EWallState::DESTROYED;
+	default:                             return true;
+	}
+}
+
+BattleHex BattleSiegeController::getWallPiecePosition(EWallVisual::EWallVisual what) const
+{
+	static const std::array<BattleHex, 18> wallsPositions = {
+		BattleHex::INVALID,        // BACKGROUND,         // handled separately
+		BattleHex::HEX_BEFORE_ALL, // BACKGROUND_WALL,
+		135,                       // KEEP,
+		BattleHex::HEX_AFTER_ALL,  // BOTTOM_TOWER,
+		182,                       // BOTTOM_WALL,
+		130,                       // WALL_BELLOW_GATE,
+		78,                        // WALL_OVER_GATE,
+		12,                        // UPPER_WALL,
+		BattleHex::HEX_BEFORE_ALL, // UPPER_TOWER,
+		BattleHex::HEX_BEFORE_ALL, // GATE,               // 94
+		112,                       // GATE_ARCH,
+		165,                       // BOTTOM_STATIC_WALL,
+		45,                        // UPPER_STATIC_WALL,
+		BattleHex::INVALID,        // MOAT,               // printed as absolute obstacle
+		BattleHex::INVALID,        // MOAT_BANK,          // printed as absolute obstacle
+		135,                       // KEEP_BATTLEMENT,
+		BattleHex::HEX_AFTER_ALL,  // BOTTOM_BATTLEMENT,
+		BattleHex::HEX_BEFORE_ALL, // UPPER_BATTLEMENT,
+	};
+
+	return wallsPositions[what];
+}
+
+BattleSiegeController::BattleSiegeController(BattleInterface & owner, const CGTownInstance *siegeTown):
+	owner(owner),
+	town(siegeTown)
+{
+	assert(owner.fieldController.get() == nullptr); // must be created after this
+
+	for (int g = 0; g < wallPieceImages.size(); ++g)
+	{
+		if ( g == EWallVisual::GATE ) // gate is initially closed and has no image to display in this state
+			continue;
+
+		if ( !getWallPieceExistance(EWallVisual::EWallVisual(g)) )
+			continue;
+
+		wallPieceImages[g] = IImage::createFromFile(getWallPieceImageName(EWallVisual::EWallVisual(g), EWallState::INTACT));
+	}
+}
+
+const CCreature *BattleSiegeController::getTurretCreature() const
+{
+	return CGI->creh->objects[town->town->clientInfo.siegeShooter];
+}
+
+Point BattleSiegeController::getTurretCreaturePosition( BattleHex position ) const
+{
+	// Turret positions are read out of the config/wall_pos.txt
+	int posID = 0;
+	switch (position)
+	{
+	case BattleHex::CASTLE_CENTRAL_TOWER: // keep creature
+		posID = EWallVisual::CREATURE_KEEP;
+		break;
+	case BattleHex::CASTLE_BOTTOM_TOWER: // bottom creature
+		posID = EWallVisual::CREATURE_BOTTOM_TOWER;
+		break;
+	case BattleHex::CASTLE_UPPER_TOWER: // upper creature
+		posID = EWallVisual::CREATURE_UPPER_TOWER;
+		break;
+	}
+
+	if (posID != 0)
+	{
+		Point result = owner.pos.topLeft();
+		result.x += town->town->clientInfo.siegePositions[posID].x;
+		result.y += town->town->clientInfo.siegePositions[posID].y;
+		return result;
+	}
+
+	assert(0);
+	return Point(0,0);
+}
+
+void BattleSiegeController::gateStateChanged(const EGateState state)
+{
+	auto oldState = owner.curInt->cb->battleGetGateState();
+	bool playSound = false;
+	auto stateId = EWallState::NONE;
+	switch(state)
+	{
+	case EGateState::CLOSED:
+		if (oldState != EGateState::BLOCKED)
+			playSound = true;
+		break;
+	case EGateState::BLOCKED:
+		if (oldState != EGateState::CLOSED)
+			playSound = true;
+		break;
+	case EGateState::OPENED:
+		playSound = true;
+		stateId = EWallState::DAMAGED;
+		break;
+	case EGateState::DESTROYED:
+		stateId = EWallState::DESTROYED;
+		break;
+	}
+
+	if (oldState != EGateState::NONE && oldState != EGateState::CLOSED && oldState != EGateState::BLOCKED)
+		wallPieceImages[EWallVisual::GATE] = nullptr;
+
+	if (stateId != EWallState::NONE)
+		wallPieceImages[EWallVisual::GATE] = IImage::createFromFile(getWallPieceImageName(EWallVisual::GATE,  stateId));
+
+	if (playSound)
+		CCS->soundh->playSound(soundBase::DRAWBRG);
+}
+
+void BattleSiegeController::showAbsoluteObstacles(Canvas & canvas, const Point & offset)
+{
+	if (getWallPieceExistance(EWallVisual::MOAT))
+		showWallPiece(canvas, EWallVisual::MOAT, offset);
+
+	if (getWallPieceExistance(EWallVisual::MOAT_BANK))
+		showWallPiece(canvas, EWallVisual::MOAT_BANK, offset);
+}
+
+BattleHex BattleSiegeController::getTurretBattleHex(EWallVisual::EWallVisual wallPiece) const
+{
+	switch(wallPiece)
+	{
+	case EWallVisual::KEEP_BATTLEMENT:   return BattleHex::CASTLE_CENTRAL_TOWER;
+	case EWallVisual::BOTTOM_BATTLEMENT: return BattleHex::CASTLE_BOTTOM_TOWER;
+	case EWallVisual::UPPER_BATTLEMENT:  return BattleHex::CASTLE_UPPER_TOWER;
+	}
+	assert(0);
+	return BattleHex::INVALID;
+}
+
+const CStack * BattleSiegeController::getTurretStack(EWallVisual::EWallVisual wallPiece) const
+{
+	for (auto & stack : owner.curInt->cb->battleGetAllStacks(true))
+	{
+		if ( stack->initialPosition == getTurretBattleHex(wallPiece))
+			return stack;
+	}
+	assert(0);
+	return nullptr;
+}
+
+void BattleSiegeController::collectRenderableObjects(BattleRenderer & renderer)
+{
+	for (int i = EWallVisual::WALL_FIRST; i <= EWallVisual::WALL_LAST; ++i)
+	{
+		auto wallPiece = EWallVisual::EWallVisual(i);
+
+		if ( !getWallPieceExistance(wallPiece))
+			continue;
+
+		if ( getWallPiecePosition(wallPiece) == BattleHex::INVALID)
+			continue;
+
+		if (wallPiece == EWallVisual::KEEP_BATTLEMENT ||
+			wallPiece == EWallVisual::BOTTOM_BATTLEMENT ||
+			wallPiece == EWallVisual::UPPER_BATTLEMENT)
+		{
+			renderer.insert( EBattleFieldLayer::STACKS, getWallPiecePosition(wallPiece), [this, wallPiece](BattleRenderer::RendererRef canvas){
+				owner.stacksController->showStack(canvas, getTurretStack(wallPiece));
+			});
+			renderer.insert( EBattleFieldLayer::BATTLEMENTS, getWallPiecePosition(wallPiece), [this, wallPiece](BattleRenderer::RendererRef canvas){
+				showWallPiece(canvas, wallPiece, owner.pos.topLeft());
+			});
+		}
+		renderer.insert( EBattleFieldLayer::WALLS, getWallPiecePosition(wallPiece), [this, wallPiece](BattleRenderer::RendererRef canvas){
+			showWallPiece(canvas, wallPiece, owner.pos.topLeft());
+		});
+
+
+	}
+}
+
+bool BattleSiegeController::isAttackableByCatapult(BattleHex hex) const
+{
+	if (owner.tacticsMode)
+		return false;
+
+	auto wallPart = owner.curInt->cb->battleHexToWallPart(hex);
+	if (!owner.curInt->cb->isWallPartPotentiallyAttackable(wallPart))
+		return false;
+
+	auto state = owner.curInt->cb->battleGetWallState(static_cast<int>(wallPart));
+	return state != EWallState::DESTROYED && state != EWallState::NONE;
+}
+
+void BattleSiegeController::stackIsCatapulting(const CatapultAttack & ca)
+{
+	if (ca.attacker != -1)
+	{
+		const CStack *stack = owner.curInt->cb->battleGetStackByID(ca.attacker);
+		for (auto attackInfo : ca.attackedParts)
+		{
+			owner.stacksController->addNewAnim(new CCatapultAnimation(owner, stack, attackInfo.destinationTile, nullptr, attackInfo.damageDealt));
+		}
+	}
+	else
+	{
+		std::vector<Point> positions;
+
+		//no attacker stack, assume spell-related (earthquake) - only hit animation
+		for (auto attackInfo : ca.attackedParts)
+			positions.push_back(owner.stacksController->getStackPositionAtHex(attackInfo.destinationTile, nullptr) + Point(99, 120));
+
+
+		owner.stacksController->addNewAnim(new CPointEffectAnimation(owner, soundBase::WALLHIT, "SGEXPL.DEF", positions));
+	}
+
+	owner.waitForAnims();
+
+	for (auto attackInfo : ca.attackedParts)
+	{
+		int wallId = attackInfo.attackedPart + EWallVisual::DESTRUCTIBLE_FIRST;
+		//gate state changing handled separately
+		if (wallId == EWallVisual::GATE)
+			continue;
+
+		auto wallState = EWallState::EWallState(owner.curInt->cb->battleGetWallState(attackInfo.attackedPart));
+
+		wallPieceImages[wallId] = IImage::createFromFile(getWallPieceImageName(EWallVisual::EWallVisual(wallId), wallState));
+	}
+}
+
+const CGTownInstance *BattleSiegeController::getSiegedTown() const
+{
+	return town;
+}

+ 110 - 0
client/battle/BattleSiegeController.h

@@ -0,0 +1,110 @@
+/*
+ * BattleObstacleController.h, part of VCMI engine
+ *
+ * Authors: listed in file AUTHORS in main folder
+ *
+ * License: GNU General Public License v2.0 or later
+ * Full text of license available in license.txt file, in main folder
+ *
+ */
+#pragma once
+
+#include "../../lib/GameConstants.h"
+#include "../../lib/battle/BattleHex.h"
+
+VCMI_LIB_NAMESPACE_BEGIN
+
+struct CatapultAttack;
+class CCreature;
+class CStack;
+class CGTownInstance;
+
+VCMI_LIB_NAMESPACE_END
+
+struct Point;
+class Canvas;
+class BattleInterface;
+class BattleRenderer;
+class IImage;
+
+namespace EWallVisual
+{
+	enum EWallVisual
+	{
+		BACKGROUND,
+		BACKGROUND_WALL,
+
+		KEEP,
+		BOTTOM_TOWER,
+		BOTTOM_WALL,
+		WALL_BELLOW_GATE,
+		WALL_OVER_GATE,
+		UPPER_WALL,
+		UPPER_TOWER,
+		GATE,
+
+		GATE_ARCH,
+		BOTTOM_STATIC_WALL,
+		UPPER_STATIC_WALL,
+		MOAT,
+		MOAT_BANK,
+		KEEP_BATTLEMENT,
+		BOTTOM_BATTLEMENT,
+		UPPER_BATTLEMENT,
+
+		CREATURE_KEEP,
+		CREATURE_BOTTOM_TOWER,
+		CREATURE_UPPER_TOWER,
+
+		WALL_FIRST = BACKGROUND_WALL,
+		WALL_LAST  = UPPER_BATTLEMENT,
+
+		// these entries are mapped to EWallPart enum
+		DESTRUCTIBLE_FIRST = KEEP,
+		DESTRUCTIBLE_LAST = GATE,
+	};
+}
+
+class BattleSiegeController
+{
+	BattleInterface & owner;
+
+	/// besieged town
+	const CGTownInstance *town;
+
+	/// sections of castle walls, in their currently visible state
+	std::array<std::shared_ptr<IImage>, EWallVisual::WALL_LAST + 1> wallPieceImages;
+
+	/// return URI for image for a wall piece
+	std::string getWallPieceImageName(EWallVisual::EWallVisual what, EWallState::EWallState state) const;
+
+	/// returns BattleHex to which chosen wall piece is bound
+	BattleHex getWallPiecePosition(EWallVisual::EWallVisual what) const;
+
+	/// returns true if chosen wall piece should be present in current battle
+	bool getWallPieceExistance(EWallVisual::EWallVisual what) const;
+
+	void showWallPiece(Canvas & canvas, EWallVisual::EWallVisual what, const Point & offset);
+
+	BattleHex getTurretBattleHex(EWallVisual::EWallVisual wallPiece) const;
+	const CStack * getTurretStack(EWallVisual::EWallVisual wallPiece) const;
+
+public:
+	BattleSiegeController(BattleInterface & owner, const CGTownInstance *siegeTown);
+
+	/// call-ins from server
+	void gateStateChanged(const EGateState state);
+	void stackIsCatapulting(const CatapultAttack & ca);
+
+	/// call-ins from other battle controllers
+	void showAbsoluteObstacles(Canvas & canvas, const Point & offset);
+	void collectRenderableObjects(BattleRenderer & renderer);
+
+	/// queries from other battle controllers
+	bool isAttackableByCatapult(BattleHex hex) const;
+	std::string getBattleBackgroundName() const;
+	const CCreature *getTurretCreature() const;
+	Point getTurretCreaturePosition( BattleHex position ) const;
+
+	const CGTownInstance *getSiegedTown() const;
+};

+ 589 - 0
client/battle/BattleStacksController.cpp

@@ -0,0 +1,589 @@
+/*
+ * BattleStacksController.cpp, part of VCMI engine
+ *
+ * Authors: listed in file AUTHORS in main folder
+ *
+ * License: GNU General Public License v2.0 or later
+ * Full text of license available in license.txt file, in main folder
+ *
+ */
+#include "StdInc.h"
+#include "BattleStacksController.h"
+
+#include "BattleSiegeController.h"
+#include "BattleInterfaceClasses.h"
+#include "BattleInterface.h"
+#include "BattleAnimationClasses.h"
+#include "BattleFieldController.h"
+#include "BattleEffectsController.h"
+#include "BattleProjectileController.h"
+#include "BattleControlPanel.h"
+#include "BattleRenderer.h"
+#include "CreatureAnimation.h"
+
+#include "../CPlayerInterface.h"
+#include "../CMusicHandler.h"
+#include "../CGameInfo.h"
+#include "../gui/CAnimation.h"
+#include "../gui/CGuiHandler.h"
+#include "../gui/Canvas.h"
+
+#include "../../CCallback.h"
+#include "../../lib/battle/BattleHex.h"
+#include "../../lib/CGameState.h"
+#include "../../lib/CStack.h"
+#include "../../lib/CondSh.h"
+
+static void onAnimationFinished(const CStack *stack, std::weak_ptr<CreatureAnimation> anim)
+{
+	std::shared_ptr<CreatureAnimation> animation = anim.lock();
+	if(!animation)
+		return;
+
+	if (animation->isIdle())
+	{
+		const CCreature *creature = stack->getCreature();
+
+		if (animation->framesInGroup(CCreatureAnim::MOUSEON) > 0)
+		{
+			if (CRandomGenerator::getDefault().nextDouble(99.0) < creature->animation.timeBetweenFidgets *10)
+				animation->playOnce(CCreatureAnim::MOUSEON);
+			else
+				animation->setType(CCreatureAnim::HOLDING);
+		}
+		else
+		{
+			animation->setType(CCreatureAnim::HOLDING);
+		}
+	}
+	// always reset callback
+	animation->onAnimationReset += std::bind(&onAnimationFinished, stack, anim);
+}
+
+BattleStacksController::BattleStacksController(BattleInterface & owner):
+	owner(owner),
+	activeStack(nullptr),
+	mouseHoveredStack(nullptr),
+	stackToActivate(nullptr),
+	selectedStack(nullptr),
+	stackCanCastSpell(false),
+	creatureSpellToCast(uint32_t(-1)),
+	animIDhelper(0)
+{
+	//preparing graphics for displaying amounts of creatures
+	amountNormal     = IImage::createFromFile("CMNUMWIN.BMP");
+	amountPositive   = IImage::createFromFile("CMNUMWIN.BMP");
+	amountNegative   = IImage::createFromFile("CMNUMWIN.BMP");
+	amountEffNeutral = IImage::createFromFile("CMNUMWIN.BMP");
+
+	static const ColorShifterMultiplyAndAddExcept shifterNormal  ({150,  50, 255, 255}, {0,0,0,0}, {255, 231, 132, 255});
+	static const ColorShifterMultiplyAndAddExcept shifterPositive({ 50, 255,  50, 255}, {0,0,0,0}, {255, 231, 132, 255});
+	static const ColorShifterMultiplyAndAddExcept shifterNegative({255,  50,  50, 255}, {0,0,0,0}, {255, 231, 132, 255});
+	static const ColorShifterMultiplyAndAddExcept shifterNeutral ({255, 255,  50, 255}, {0,0,0,0}, {255, 231, 132, 255});
+
+	amountNormal->adjustPalette(&shifterNormal);
+	amountPositive->adjustPalette(&shifterPositive);
+	amountNegative->adjustPalette(&shifterNegative);
+	amountEffNeutral->adjustPalette(&shifterNeutral);
+
+	std::vector<const CStack*> stacks = owner.curInt->cb->battleGetAllStacks(true);
+	for(const CStack * s : stacks)
+	{
+		stackAdded(s);
+	}
+}
+
+BattleHex BattleStacksController::getStackCurrentPosition(const CStack * stack) const
+{
+	if ( !stackAnimation.at(stack->ID)->isMoving())
+		return stack->getPosition();
+
+	if (stack->hasBonusOfType(Bonus::FLYING))
+		return BattleHex::HEX_AFTER_ALL;
+
+	for (auto & anim : currentAnimations)
+	{
+		// certainly ugly workaround but fixes quite annoying bug
+		// stack position will be updated only *after* movement is finished
+		// before this - stack is always at its initial position. Thus we need to find
+		// its current position. Which can be found only in this class
+		if (CStackMoveAnimation *move = dynamic_cast<CStackMoveAnimation*>(anim))
+		{
+			if (move->stack == stack)
+				return move->currentHex;
+		}
+	}
+	return stack->getPosition();
+}
+
+void BattleStacksController::collectRenderableObjects(BattleRenderer & renderer)
+{
+	auto stacks = owner.curInt->cb->battleGetAllStacks(false);
+
+	for (auto stack : stacks)
+	{
+		if (stackAnimation.find(stack->ID) == stackAnimation.end()) //e.g. for summoned but not yet handled stacks
+			continue;
+
+		//FIXME: hack to ignore ghost stacks
+		if ((stackAnimation[stack->ID]->getType() == CCreatureAnim::DEAD || stackAnimation[stack->ID]->getType() == CCreatureAnim::HOLDING) && stack->isGhost())
+			continue;
+
+		auto layer = stackAnimation[stack->ID]->isDead() ? EBattleFieldLayer::CORPSES : EBattleFieldLayer::STACKS;
+		auto location = getStackCurrentPosition(stack);
+
+		renderer.insert(layer, location, [this, stack]( BattleRenderer::RendererRef renderer ){
+			showStack(renderer, stack);
+		});
+
+		if (stackNeedsAmountBox(stack))
+		{
+			renderer.insert(EBattleFieldLayer::STACK_AMOUNTS, location, [this, stack]( BattleRenderer::RendererRef renderer ){
+				showStackAmountBox(renderer, stack);
+			});
+		}
+	}
+}
+
+void BattleStacksController::stackReset(const CStack * stack)
+{
+	auto iter = stackAnimation.find(stack->ID);
+
+	if(iter == stackAnimation.end())
+	{
+		logGlobal->error("Unit %d have no animation", stack->ID);
+		return;
+	}
+
+	auto animation = iter->second;
+
+	if(stack->alive() && animation->isDeadOrDying())
+		animation->setType(CCreatureAnim::HOLDING);
+
+	static const ColorShifterMultiplyAndAdd shifterClone ({255, 255, 0, 255}, {0, 0, 255, 0});
+
+	if (stack->isClone())
+	{
+		animation->shiftColor(&shifterClone);
+	}
+
+	//TODO: handle more cases
+}
+
+void BattleStacksController::stackAdded(const CStack * stack)
+{
+	// Tower shooters have only their upper half visible
+	static const int turretCreatureAnimationHeight = 235;
+
+	stackFacingRight[stack->ID] = stack->side == BattleSide::ATTACKER; // must be set before getting stack position
+
+	Point coords = getStackPositionAtHex(stack->getPosition(), stack);
+
+	if(stack->initialPosition < 0) //turret
+	{
+		assert(owner.siegeController);
+
+		const CCreature *turretCreature = owner.siegeController->getTurretCreature();
+
+		stackAnimation[stack->ID] = AnimationControls::getAnimation(turretCreature);
+		stackAnimation[stack->ID]->pos.h = turretCreatureAnimationHeight;
+
+		coords = owner.siegeController->getTurretCreaturePosition(stack->initialPosition);
+	}
+	else
+	{
+		stackAnimation[stack->ID] = AnimationControls::getAnimation(stack->getCreature());
+		stackAnimation[stack->ID]->onAnimationReset += std::bind(&onAnimationFinished, stack, stackAnimation[stack->ID]);
+		stackAnimation[stack->ID]->pos.h = stackAnimation[stack->ID]->getHeight();
+	}
+	stackAnimation[stack->ID]->pos.x = coords.x;
+	stackAnimation[stack->ID]->pos.y = coords.y;
+	stackAnimation[stack->ID]->pos.w = stackAnimation[stack->ID]->getWidth();
+	stackAnimation[stack->ID]->setType(CCreatureAnim::HOLDING);
+}
+
+void BattleStacksController::setActiveStack(const CStack *stack)
+{
+	if (activeStack) // update UI
+		stackAnimation[activeStack->ID]->setBorderColor(AnimationControls::getNoBorder());
+
+	activeStack = stack;
+
+	if (activeStack) // update UI
+		stackAnimation[activeStack->ID]->setBorderColor(AnimationControls::getGoldBorder());
+
+	owner.controlPanel->blockUI(activeStack == nullptr);
+}
+
+void BattleStacksController::setHoveredStack(const CStack *stack)
+{
+	if ( stack == mouseHoveredStack )
+		 return;
+
+	if (mouseHoveredStack)
+		stackAnimation[mouseHoveredStack->ID]->setBorderColor(AnimationControls::getNoBorder());
+
+	// stack must be alive and not active (which uses gold border instead)
+	if (stack && stack->alive() && stack != activeStack)
+	{
+		mouseHoveredStack = stack;
+
+		if (mouseHoveredStack)
+		{
+			stackAnimation[mouseHoveredStack->ID]->setBorderColor(AnimationControls::getBlueBorder());
+			if (stackAnimation[mouseHoveredStack->ID]->framesInGroup(CCreatureAnim::MOUSEON) > 0)
+				stackAnimation[mouseHoveredStack->ID]->playOnce(CCreatureAnim::MOUSEON);
+		}
+	}
+	else
+		mouseHoveredStack = nullptr;
+}
+
+bool BattleStacksController::stackNeedsAmountBox(const CStack * stack) const
+{
+	BattleHex currentActionTarget;
+	if(owner.curInt->curAction)
+	{
+		auto target = owner.curInt->curAction->getTarget(owner.curInt->cb.get());
+		if(!target.empty())
+			currentActionTarget = target.at(0).hexValue;
+	}
+
+	if(stack->hasBonusOfType(Bonus::SIEGE_WEAPON) && stack->getCount() == 1) //do not show box for singular war machines, stacked war machines with box shown are supported as extension feature
+		return false;
+
+	if (!owner.battleActionsStarted) // do not perform any further checks since they are related to actions that will only occur after intro music
+		return true;
+
+	if(!stack->alive())
+		return false;
+
+	if(stack->getCount() == 0) //hide box when target is going to die anyway - do not display "0 creatures"
+		return false;
+
+	for(auto anim : currentAnimations) //no matter what other conditions below are, hide box when creature is playing hit animation
+	{
+		auto hitAnimation = dynamic_cast<CDefenceAnimation*>(anim);
+		if(hitAnimation && (hitAnimation->stack->ID == stack->ID))
+			return false;
+	}
+
+	if(owner.curInt->curAction)
+	{
+		if(owner.curInt->curAction->stackNumber == stack->ID) //stack is currently taking action (is not a target of another creature's action etc)
+		{
+			if(owner.curInt->curAction->actionType == EActionType::WALK || owner.curInt->curAction->actionType == EActionType::SHOOT) //hide when stack walks or shoots
+				return false;
+
+			else if(owner.curInt->curAction->actionType == EActionType::WALK_AND_ATTACK && currentActionTarget != stack->getPosition()) //when attacking, hide until walk phase finished
+				return false;
+		}
+
+		if(owner.curInt->curAction->actionType == EActionType::SHOOT && currentActionTarget == stack->getPosition()) //hide if we are ranged attack target
+			return false;
+	}
+	return true;
+}
+
+std::shared_ptr<IImage> BattleStacksController::getStackAmountBox(const CStack * stack)
+{
+	std::vector<si32> activeSpells = stack->activeSpells();
+
+	if ( activeSpells.empty())
+		return amountNormal;
+
+	int effectsPositivness = 0;
+
+	for ( auto const & spellID : activeSpells)
+		effectsPositivness += CGI->spellh->objects.at(spellID)->positiveness;
+
+	if (effectsPositivness > 0)
+		return amountPositive;
+
+	if (effectsPositivness < 0)
+		return amountNegative;
+
+	return amountEffNeutral;
+}
+
+void BattleStacksController::showStackAmountBox(Canvas & canvas, const CStack * stack)
+{
+	//blitting amount background box
+	auto amountBG = getStackAmountBox(stack);
+
+	const int sideShift = stack->side == BattleSide::ATTACKER ? 1 : -1;
+	const int reverseSideShift = stack->side == BattleSide::ATTACKER ? -1 : 1;
+	const BattleHex nextPos = stack->getPosition() + sideShift;
+	const bool edge = stack->getPosition() % GameConstants::BFIELD_WIDTH == (stack->side == BattleSide::ATTACKER ? GameConstants::BFIELD_WIDTH - 2 : 1);
+	const bool moveInside = !edge && !owner.fieldController->stackCountOutsideHex(nextPos);
+
+	int xAdd = (stack->side == BattleSide::ATTACKER ? 220 : 202) +
+			(stack->doubleWide() ? 44 : 0) * sideShift +
+			(moveInside ? amountBG->width() + 10 : 0) * reverseSideShift;
+	int yAdd = 260 + ((stack->side == BattleSide::ATTACKER || moveInside) ? 0 : -15);
+
+	canvas.draw(amountBG, stackAnimation[stack->ID]->pos.topLeft() + Point(xAdd, yAdd));
+
+	//blitting amount
+	Point textPos = stackAnimation[stack->ID]->pos.topLeft() + amountBG->dimensions()/2 + Point(xAdd, yAdd);
+
+	canvas.drawText(textPos, EFonts::FONT_TINY, Colors::WHITE, ETextAlignment::CENTER, makeNumberShort(stack->getCount()));
+}
+
+void BattleStacksController::showStack(Canvas & canvas, const CStack * stack)
+{
+	stackAnimation[stack->ID]->nextFrame(canvas, facingRight(stack)); // do actual blit
+	stackAnimation[stack->ID]->incrementFrame(float(GH.mainFPSmng->getElapsedMilliseconds()) / 1000);
+}
+
+void BattleStacksController::updateBattleAnimations()
+{
+	for (auto & elem : currentAnimations)
+	{
+		if (!elem)
+			continue;
+
+		if (elem->isInitialized())
+			elem->nextFrame();
+		else
+			elem->tryInitialize();
+	}
+
+	bool hadAnimations = !currentAnimations.empty();
+	vstd::erase(currentAnimations, nullptr);
+
+	if (hadAnimations && currentAnimations.empty())
+	{
+		//anims ended
+		owner.controlPanel->blockUI(activeStack == nullptr);
+		owner.animsAreDisplayed.setn(false);
+	}
+}
+
+void BattleStacksController::addNewAnim(CBattleAnimation *anim)
+{
+	currentAnimations.push_back(anim);
+	owner.animsAreDisplayed.setn(true);
+}
+
+void BattleStacksController::stackActivated(const CStack *stack) //TODO: check it all before game state is changed due to abilities
+{
+	stackToActivate = stack;
+	owner.waitForAnims();
+	if (stackToActivate) //during waiting stack may have gotten activated through show
+		owner.activateStack();
+}
+
+void BattleStacksController::stackRemoved(uint32_t stackID)
+{
+	if (getActiveStack() && getActiveStack()->ID == stackID)
+	{
+		BattleAction *action = new BattleAction();
+		action->side = owner.defendingHeroInstance ? (owner.curInt->playerID == owner.defendingHeroInstance->tempOwner) : false;
+		action->actionType = EActionType::CANCEL;
+		action->stackNumber = getActiveStack()->ID;
+		owner.givenCommand.setn(action);
+		setActiveStack(nullptr);
+	}
+}
+
+void BattleStacksController::stacksAreAttacked(std::vector<StackAttackedInfo> attackedInfos)
+{
+	for(auto & attackedInfo : attackedInfos)
+	{
+		//if (!attackedInfo.cloneKilled) //FIXME: play dead animation for cloned creature before it vanishes
+			addNewAnim(new CDefenceAnimation(attackedInfo, owner));
+
+		if(attackedInfo.rebirth)
+		{
+			owner.effectsController->displayEffect(EBattleEffect::RESURRECT, soundBase::RESURECT, attackedInfo.defender->getPosition()); //TODO: play reverse death animation
+		}
+	}
+	owner.waitForAnims();
+
+	for (auto & attackedInfo : attackedInfos)
+	{
+		if (attackedInfo.rebirth)
+			stackAnimation[attackedInfo.defender->ID]->setType(CCreatureAnim::HOLDING);
+		if (attackedInfo.cloneKilled)
+			stackRemoved(attackedInfo.defender->ID);
+	}
+}
+
+void BattleStacksController::stackMoved(const CStack *stack, std::vector<BattleHex> destHex, int distance)
+{
+	addNewAnim(new CMovementAnimation(owner, stack, destHex, distance));
+	owner.waitForAnims();
+}
+
+void BattleStacksController::stackAttacking( const CStack *attacker, BattleHex dest, const CStack *attacked, bool shooting )
+{
+	if (shooting)
+	{
+		addNewAnim(new CShootingAnimation(owner, attacker, dest, attacked));
+	}
+	else
+	{
+		addNewAnim(new CMeleeAttackAnimation(owner, attacker, dest, attacked));
+	}
+	//waitForAnims();
+}
+
+bool BattleStacksController::shouldRotate(const CStack * stack, const BattleHex & oldPos, const BattleHex & nextHex) const
+{
+	Point begPosition = getStackPositionAtHex(oldPos,stack);
+	Point endPosition = getStackPositionAtHex(nextHex, stack);
+
+	if((begPosition.x > endPosition.x) && facingRight(stack))
+		return true;
+	else if((begPosition.x < endPosition.x) && !facingRight(stack))
+		return true;
+
+	return false;
+}
+
+
+void BattleStacksController::endAction(const BattleAction* action)
+{
+	//check if we should reverse stacks
+	//for some strange reason, it's not enough
+	TStacks stacks = owner.curInt->cb->battleGetStacks(CBattleCallback::MINE_AND_ENEMY);
+
+	for (const CStack *s : stacks)
+	{
+		bool shouldFaceRight  = s && s->side == BattleSide::ATTACKER;
+
+		if (s && facingRight(s) != shouldFaceRight && s->alive() && stackAnimation[s->ID]->isIdle())
+		{
+			addNewAnim(new CReverseAnimation(owner, s, s->getPosition(), false));
+		}
+	}
+}
+
+void BattleStacksController::startAction(const BattleAction* action)
+{
+	const CStack *stack = owner.curInt->cb->battleGetStackByID(action->stackNumber);
+	setHoveredStack(nullptr);
+
+	auto actionTarget = action->getTarget(owner.curInt->cb.get());
+
+	if(action->actionType == EActionType::WALK
+		|| (action->actionType == EActionType::WALK_AND_ATTACK && actionTarget.at(0).hexValue != stack->getPosition()))
+	{
+		assert(stack);
+		owner.moveStarted = true;
+		if (stackAnimation[action->stackNumber]->framesInGroup(CCreatureAnim::MOVE_START))
+			addNewAnim(new CMovementStartAnimation(owner, stack));
+
+		//if(shouldRotate(stack, stack->getPosition(), actionTarget.at(0).hexValue))
+		//	addNewAnim(new CReverseAnimation(owner, stack, stack->getPosition(), true));
+	}
+}
+
+void BattleStacksController::activateStack()
+{
+	if ( !currentAnimations.empty())
+		return;
+
+	if ( !stackToActivate)
+		return;
+
+	owner.trySetActivePlayer(stackToActivate->owner);
+
+	setActiveStack(stackToActivate);
+	stackToActivate = nullptr;
+
+	const CStack * s = getActiveStack();
+	if(!s)
+		return;
+
+	//set casting flag to true if creature can use it to not check it every time
+	const auto spellcaster = s->getBonusLocalFirst(Selector::type()(Bonus::SPELLCASTER));
+	const auto randomSpellcaster = s->getBonusLocalFirst(Selector::type()(Bonus::RANDOM_SPELLCASTER));
+	if(s->canCast() && (spellcaster || randomSpellcaster))
+	{
+		stackCanCastSpell = true;
+		if(randomSpellcaster)
+			creatureSpellToCast = -1; //spell will be set later on cast
+		else
+			creatureSpellToCast = owner.curInt->cb->battleGetRandomStackSpell(CRandomGenerator::getDefault(), s, CBattleInfoCallback::RANDOM_AIMED); //faerie dragon can cast only one spell until their next move
+		//TODO: what if creature can cast BOTH random genie spell and aimed spell?
+		//TODO: faerie dragon type spell should be selected by server
+	}
+	else
+	{
+		stackCanCastSpell = false;
+		creatureSpellToCast = -1;
+	}
+}
+
+void BattleStacksController::setSelectedStack(const CStack *stack)
+{
+	selectedStack = stack;
+}
+
+const CStack* BattleStacksController::getSelectedStack() const
+{
+	return selectedStack;
+}
+
+const CStack* BattleStacksController::getActiveStack() const
+{
+	return activeStack;
+}
+
+bool BattleStacksController::facingRight(const CStack * stack) const
+{
+	return stackFacingRight.at(stack->ID);
+}
+
+bool BattleStacksController::activeStackSpellcaster()
+{
+	return stackCanCastSpell;
+}
+
+SpellID BattleStacksController::activeStackSpellToCast()
+{
+	if (!stackCanCastSpell)
+		return SpellID::NONE;
+	return SpellID(creatureSpellToCast);
+}
+
+Point BattleStacksController::getStackPositionAtHex(BattleHex hexNum, const CStack * stack) const
+{
+	Point ret(-500, -500); //returned value
+	if(stack && stack->initialPosition < 0) //creatures in turrets
+		return owner.siegeController->getTurretCreaturePosition(stack->initialPosition);
+
+	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.y = basePos.y + 42 * hexNum.getY();
+
+	if (stack)
+	{
+		if(facingRight(stack))
+			ret.x += imageShiftX;
+		else
+			ret.x -= imageShiftX;
+
+		//shifting position for double - hex creatures
+		if(stack->doubleWide())
+		{
+			if(stack->side == BattleSide::ATTACKER)
+			{
+				if(facingRight(stack))
+					ret.x -= 44;
+			}
+			else
+			{
+				if(!facingRight(stack))
+					ret.x += 44;
+			}
+		}
+	}
+	//returning
+	return ret + owner.pos.topLeft();
+
+}

+ 121 - 0
client/battle/BattleStacksController.h

@@ -0,0 +1,121 @@
+/*
+ * BattleStacksController.h, part of VCMI engine
+ *
+ * Authors: listed in file AUTHORS in main folder
+ *
+ * License: GNU General Public License v2.0 or later
+ * Full text of license available in license.txt file, in main folder
+ *
+ */
+#pragma once
+
+#include "../gui/Geometries.h"
+
+VCMI_LIB_NAMESPACE_BEGIN
+
+struct BattleHex;
+class BattleAction;
+class CStack;
+class SpellID;
+
+VCMI_LIB_NAMESPACE_END
+
+struct StackAttackedInfo;
+
+class Canvas;
+class BattleInterface;
+class CBattleAnimation;
+class CreatureAnimation;
+class CBattleAnimation;
+class BattleRenderer;
+class IImage;
+
+/// Class responsible for handling stacks in battle
+/// Handles ordering of stacks animation
+/// As well as rendering of stacks, their amount boxes
+/// And any other effect applied to stacks
+class BattleStacksController
+{
+	BattleInterface & owner;
+
+	std::shared_ptr<IImage> amountNormal;
+	std::shared_ptr<IImage> amountNegative;
+	std::shared_ptr<IImage> amountPositive;
+	std::shared_ptr<IImage> amountEffNeutral;
+
+	/// currently displayed animations <anim, initialized>
+	std::vector<CBattleAnimation *> currentAnimations;
+
+	/// animations of creatures from fighting armies (order by BattleInfo's stacks' ID)
+	std::map<int32_t, std::shared_ptr<CreatureAnimation>> stackAnimation;
+
+	/// <creatureID, if false reverse creature's animation> //TODO: move it to battle callback
+	std::map<int, bool> stackFacingRight;
+
+	/// number of active stack; nullptr - no one
+	const CStack *activeStack;
+
+	/// stack below mouse pointer, used for border animation
+	const CStack *mouseHoveredStack;
+
+	///when animation is playing, we should wait till the end to make the next stack active; nullptr of none
+	const CStack *stackToActivate;
+
+	/// stack that was selected for multi-target spells - Teleport / Sacrifice
+	const CStack *selectedStack;
+
+	/// if true, active stack could possibly cast some target spell
+	bool stackCanCastSpell;
+	si32 creatureSpellToCast;
+
+	/// for giving IDs for animations
+	ui32 animIDhelper;
+
+	bool stackNeedsAmountBox(const CStack * stack) const;
+	void showStackAmountBox(Canvas & canvas, const CStack * stack);
+	BattleHex getStackCurrentPosition(const CStack * stack) const;
+
+	std::shared_ptr<IImage> getStackAmountBox(const CStack * stack);
+
+public:
+	BattleStacksController(BattleInterface & owner);
+
+	bool shouldRotate(const CStack * stack, const BattleHex & oldPos, const BattleHex & nextHex) const;
+	bool facingRight(const CStack * stack) const;
+
+	void stackReset(const CStack * stack);
+	void stackAdded(const CStack * stack); //new stack appeared on battlefield
+	void stackRemoved(uint32_t 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 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 startAction(const BattleAction* action);
+	void endAction(const BattleAction* action);
+
+	bool activeStackSpellcaster();
+	SpellID activeStackSpellToCast();
+
+	void activateStack(); //sets activeStack to stackToActivate etc. //FIXME: No, it's not clear at all
+
+	void setActiveStack(const CStack *stack);
+	void setHoveredStack(const CStack *stack);
+	void setSelectedStack(const CStack *stack);
+
+	void showAliveStack(Canvas & canvas, const CStack * stack);
+	void showStack(Canvas & canvas, const CStack * stack);
+
+	void collectRenderableObjects(BattleRenderer & renderer);
+
+	void addNewAnim(CBattleAnimation *anim); //adds new anim to pendingAnims
+	void updateBattleAnimations();
+
+	const CStack* getActiveStack() const;
+	const CStack* getSelectedStack() const;
+
+	/// returns position of animation needed to place stack in specific hex
+	Point getStackPositionAtHex(BattleHex hexNum, const CStack * creature) const;
+
+	friend class CBattleAnimation; // for exposing pendingAnims/creAnims/creDir to animations
+};

+ 0 - 1229
client/battle/CBattleAnimations.cpp

@@ -1,1229 +0,0 @@
-/*
- * CBattleAnimations.cpp, part of VCMI engine
- *
- * Authors: listed in file AUTHORS in main folder
- *
- * License: GNU General Public License v2.0 or later
- * Full text of license available in license.txt file, in main folder
- *
- */
-#include "StdInc.h"
-#include "CBattleAnimations.h"
-
-#include <boost/math/constants/constants.hpp>
-
-#include "CBattleInterfaceClasses.h"
-#include "CBattleInterface.h"
-#include "CCreatureAnimation.h"
-
-#include "../CGameInfo.h"
-#include "../CMusicHandler.h"
-#include "../CPlayerInterface.h"
-#include "../Graphics.h"
-#include "../gui/CAnimation.h"
-#include "../gui/CCursorHandler.h"
-#include "../gui/CGuiHandler.h"
-#include "../gui/SDL_Extensions.h"
-
-#include "../../CCallback.h"
-#include "../../lib/CStack.h"
-#include "../../lib/CTownHandler.h"
-#include "../../lib/mapObjects/CGTownInstance.h"
-
-CBattleAnimation::CBattleAnimation(CBattleInterface * _owner)
-	: owner(_owner), ID(_owner->animIDhelper++)
-{
-	logAnim->trace("Animation #%d created", ID);
-}
-
-CBattleAnimation::~CBattleAnimation()
-{
-	logAnim->trace("Animation #%d deleted", ID);
-}
-
-void CBattleAnimation::endAnim()
-{
-	logAnim->trace("Animation #%d ended, type is %s", ID, typeid(this).name());
-	for(auto & elem : owner->pendingAnims)
-	{
-		if(elem.first == this)
-		{
-			elem.first = nullptr;
-		}
-	}
-}
-
-bool CBattleAnimation::isEarliest(bool perStackConcurrency)
-{
-	int lowestMoveID = owner->animIDhelper + 5;
-	CBattleStackAnimation * thAnim = dynamic_cast<CBattleStackAnimation *>(this);
-	CEffectAnimation * thSen = dynamic_cast<CEffectAnimation *>(this);
-
-	for(auto & elem : owner->pendingAnims)
-	{
-
-		CBattleStackAnimation * stAnim = dynamic_cast<CBattleStackAnimation *>(elem.first);
-		CEffectAnimation * sen = dynamic_cast<CEffectAnimation *>(elem.first);
-		if(perStackConcurrency && stAnim && thAnim && stAnim->stack->ID != thAnim->stack->ID)
-			continue;
-
-		if(perStackConcurrency && sen && thSen && sen != thSen)
-			continue;
-
-		CReverseAnimation * revAnim = dynamic_cast<CReverseAnimation *>(stAnim);
-
-		if(revAnim && thAnim && stAnim && stAnim->stack->ID == thAnim->stack->ID && revAnim->priority)
-			return false;
-
-		if(elem.first)
-			vstd::amin(lowestMoveID, elem.first->ID);
-	}
-	return (ID == lowestMoveID) || (lowestMoveID == (owner->animIDhelper + 5));
-}
-
-CBattleStackAnimation::CBattleStackAnimation(CBattleInterface * owner, const CStack * stack)
-	: CBattleAnimation(owner),
-	  myAnim(owner->creAnims[stack->ID]),
-	  stack(stack)
-{
-	assert(myAnim);
-}
-
-void CBattleStackAnimation::shiftColor(const ColorShifter * shifter)
-{
-	assert(myAnim);
-	myAnim->shiftColor(shifter);
-}
-
-void CAttackAnimation::nextFrame()
-{
-	if(myAnim->getType() != group)
-	{
-		myAnim->setType(group);
-		myAnim->onAnimationReset += std::bind(&CAttackAnimation::endAnim, this);
-	}
-
-	if(!soundPlayed)
-	{
-		if(shooting)
-			CCS->soundh->playSound(battle_sound(attackingStack->getCreature(), shoot));
-		else
-			CCS->soundh->playSound(battle_sound(attackingStack->getCreature(), attack));
-		soundPlayed = true;
-	}
-	CBattleAnimation::nextFrame();
-}
-
-void CAttackAnimation::endAnim()
-{
-	myAnim->setType(CCreatureAnim::HOLDING);
-	CBattleStackAnimation::endAnim();
-}
-
-bool CAttackAnimation::checkInitialConditions()
-{
-	for(auto & elem : owner->pendingAnims)
-	{
-		CBattleStackAnimation * stAnim = dynamic_cast<CBattleStackAnimation *>(elem.first);
-		CReverseAnimation * revAnim = dynamic_cast<CReverseAnimation *>(stAnim);
-
-		if(revAnim && attackedStack) // enemy must be fully reversed
-		{
-			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)
-{
-	assert(attackingStack && "attackingStack is nullptr in CBattleAttack::CBattleAttack !\n");
-	attackingStackPosBeforeReturn = attackingStack->getPosition();
-}
-
-CDefenceAnimation::CDefenceAnimation(StackAttackedInfo _attackedInfo, CBattleInterface * _owner)
-: CBattleStackAnimation(_owner, _attackedInfo.defender),
-attacker(_attackedInfo.attacker), rangedAttack(_attackedInfo.indirectAttack),
-killed(_attackedInfo.killed), timeToWait(0)
-{
-	logAnim->debug("Created defence anim for %s", _attackedInfo.defender->getName());
-}
-
-bool CDefenceAnimation::init()
-{
-	if(attacker == nullptr && owner->battleEffects.size() > 0)
-		return false;
-
-	ui32 lowestMoveID = owner->animIDhelper + 5;
-	for(auto & elem : owner->pendingAnims)
-	{
-
-		CDefenceAnimation * defAnim = dynamic_cast<CDefenceAnimation *>(elem.first);
-		if(defAnim && defAnim->stack->ID != stack->ID)
-			continue;
-
-		CAttackAnimation * attAnim = dynamic_cast<CAttackAnimation *>(elem.first);
-		if(attAnim && attAnim->stack->ID != stack->ID)
-			continue;
-
-		CEffectAnimation * sen = dynamic_cast<CEffectAnimation *>(elem.first);
-		if (sen)
-			continue;
-
-		CReverseAnimation * animAsRev = dynamic_cast<CReverseAnimation *>(elem.first);
-
-		if(animAsRev)
-			return false;
-
-		if(elem.first)
-			vstd::amin(lowestMoveID, elem.first->ID);
-	}
-
-	if(ID > lowestMoveID)
-		return false;
-
-
-	//reverse unit if necessary
-	if(attacker && owner->getCurrentPlayerInterface()->cb->isToReverse(stack->getPosition(), attacker->getPosition(), owner->creDir[stack->ID], attacker->doubleWide(), owner->creDir[attacker->ID]))
-	{
-		owner->addNewAnim(new CReverseAnimation(owner, stack, stack->getPosition(), true));
-		return false;
-	}
-	//unit reversed
-
-	if(rangedAttack && attacker != nullptr) //delay hit animation
-	{
-		for(std::list<ProjectileInfo>::const_iterator it = owner->projectiles.begin(); it != owner->projectiles.end(); ++it)
-		{
-			if(it->creID == attacker->getCreature()->idNumber)
-			{
-				return false;
-			}
-		}
-	}
-
-	// synchronize animation with attacker, unless defending or attacked by shooter:
-	// wait for 1/2 of attack animation
-	if (!rangedAttack && getMyAnimType() != CCreatureAnim::DEFENCE)
-	{
-		float frameLength = AnimationControls::getCreatureAnimationSpeed(
-								  stack->getCreature(), owner->creAnims[stack->ID].get(), getMyAnimType());
-
-		timeToWait = myAnim->framesInGroup(getMyAnimType()) * frameLength / 2;
-
-		myAnim->setType(CCreatureAnim::HOLDING);
-	}
-	else
-	{
-		timeToWait = 0;
-		startAnimation();
-	}
-
-	return true; //initialized successfuly
-}
-
-std::string CDefenceAnimation::getMySound()
-{
-	if(killed)
-		return battle_sound(stack->getCreature(), killed);
-	else if(stack->defendingAnim)
-		return battle_sound(stack->getCreature(), defend);
-	else
-		return battle_sound(stack->getCreature(), wince);
-}
-
-CCreatureAnim::EAnimType CDefenceAnimation::getMyAnimType()
-{
-	if(killed)
-	{
-		if(rangedAttack && myAnim->framesInGroup(CCreatureAnim::DEATH_RANGED) > 0)
-			return CCreatureAnim::DEATH_RANGED;
-		else
-			return CCreatureAnim::DEATH;
-	}
-
-	if(stack->defendingAnim)
-		return CCreatureAnim::DEFENCE;
-	else
-		return CCreatureAnim::HITTED;
-}
-
-void CDefenceAnimation::startAnimation()
-{
-	CCS->soundh->playSound(getMySound());
-	myAnim->setType(getMyAnimType());
-	myAnim->onAnimationReset += std::bind(&CDefenceAnimation::endAnim, this);
-}
-
-void CDefenceAnimation::nextFrame()
-{
-	if (timeToWait > 0)
-	{
-		timeToWait -= float(GH.mainFPSmng->getElapsedMilliseconds()) / 1000;
-		if (timeToWait <= 0)
-			startAnimation();
-	}
-
-	CBattleAnimation::nextFrame();
-}
-
-void CDefenceAnimation::endAnim()
-{
-	if(killed)
-	{
-		if(rangedAttack && myAnim->framesInGroup(CCreatureAnim::DEAD_RANGED) > 0)
-			myAnim->setType(CCreatureAnim::DEAD_RANGED);
-		else
-			myAnim->setType(CCreatureAnim::DEAD);
-	}
-	else
-	{
-		myAnim->setType(CCreatureAnim::HOLDING);
-	}
-
-
-	CBattleAnimation::endAnim();
-
-	delete this;
-}
-
-CDummyAnimation::CDummyAnimation(CBattleInterface * _owner, int howManyFrames)
-: CBattleAnimation(_owner), counter(0), howMany(howManyFrames)
-{
-	logAnim->debug("Created dummy animation for %d frames", howManyFrames);
-}
-
-bool CDummyAnimation::init()
-{
-	return true;
-}
-
-void CDummyAnimation::nextFrame()
-{
-	counter++;
-	if(counter > howMany)
-		endAnim();
-}
-
-void CDummyAnimation::endAnim()
-{
-	CBattleAnimation::endAnim();
-
-	delete this;
-}
-
-bool CMeleeAttackAnimation::init()
-{
-	if(!CAttackAnimation::checkInitialConditions())
-		return false;
-
-	if(!attackingStack || myAnim->isDead())
-	{
-		endAnim();
-		return false;
-	}
-
-	bool toReverse = owner->getCurrentPlayerInterface()->cb->isToReverse(attackingStackPosBeforeReturn, attackedStack->getPosition(), owner->creDir[stack->ID], attackedStack->doubleWide(), owner->creDir[attackedStack->ID]);
-
-	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])
-		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 mutPosToGroup2H[] =
-	{
-		CCreatureAnim::VCMI_2HEX_UP,
-		CCreatureAnim::VCMI_2HEX_UP,
-		CCreatureAnim::VCMI_2HEX_FRONT,
-		CCreatureAnim::VCMI_2HEX_DOWN,
-		CCreatureAnim::VCMI_2HEX_DOWN,
-		CCreatureAnim::VCMI_2HEX_FRONT
-	};
-
-	int revShiftattacker = (attackingStack->side == BattleSide::ATTACKER ? -1 : 1);
-
-	int mutPos = BattleHex::mutualPosition(attackingStackPosBeforeReturn, dest);
-	if(mutPos == -1 && attackingStack->doubleWide())
-	{
-		mutPos = BattleHex::mutualPosition(attackingStackPosBeforeReturn + revShiftattacker, attackedStack->getPosition());
-	}
-	if (mutPos == -1 && attackedStack->doubleWide())
-	{
-		mutPos = BattleHex::mutualPosition(attackingStackPosBeforeReturn, attackedStack->occupiedHex());
-	}
-	if (mutPos == -1 && attackedStack->doubleWide() && attackingStack->doubleWide())
-	{
-		mutPos = BattleHex::mutualPosition(attackingStackPosBeforeReturn + revShiftattacker, attackedStack->occupiedHex());
-	}
-
-
-	switch(mutPos) //attack direction
-	{
-	case 0:
-	case 1:
-	case 2:
-	case 3:
-	case 4:
-	case 5:
-		group = mutPosToGroup[mutPos];
-		if(attackingStack->hasBonusOfType(Bonus::TWO_HEX_ATTACK_BREATH))
-		{
-			CCreatureAnim::EAnimType group2H = mutPosToGroup2H[mutPos];
-			if(myAnim->framesInGroup(group2H)>0)
-				group = group2H;
-		}
-
-		break;
-	default:
-		logGlobal->error("Critical Error! Wrong dest in stackAttacking! dest: %d; attacking stack pos: %d; mutual pos: %d", dest.hex, attackingStackPosBeforeReturn, mutPos);
-		group = CCreatureAnim::ATTACK_FRONT;
-		break;
-	}
-
-	return true;
-}
-
-CMeleeAttackAnimation::CMeleeAttackAnimation(CBattleInterface * _owner, const CStack * attacker, BattleHex _dest, const CStack * _attacked)
-: CAttackAnimation(_owner, attacker, _dest, _attacked)
-{
-	logAnim->debug("Created melee attack anim for %s", attacker->getName());
-}
-
-void CMeleeAttackAnimation::endAnim()
-{
-	CAttackAnimation::endAnim();
-	delete this;
-}
-
-bool CMovementAnimation::init()
-{
-	if( !isEarliest(false) )
-		return false;
-
-	if(!stack || myAnim->isDead())
-	{
-		endAnim();
-		return false;
-	}
-
-	if(owner->creAnims[stack->ID]->framesInGroup(CCreatureAnim::MOVING) == 0 ||
-	   stack->hasBonus(Selector::typeSubtype(Bonus::FLYING, 1)))
-	{
-		//no movement or teleport, end immediately
-		endAnim();
-		return false;
-	}
-
-	//reverse unit if necessary
-	if(owner->shouldRotate(stack, oldPos, nextHex))
-	{
-		// 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.
-		{
-			owner->addNewAnim(new CReverseAnimation(owner, stack, oldPos, true));
-			return false;
-		}
-		else
-		{
-			CReverseAnimation::rotateStack(owner, stack, oldPos);
-		}
-	}
-
-	if(myAnim->getType() != CCreatureAnim::MOVING)
-	{
-		myAnim->setType(CCreatureAnim::MOVING);
-	}
-
-	if (owner->moveSoundHander == -1)
-	{
-		owner->moveSoundHander = CCS->soundh->playSound(battle_sound(stack->getCreature(), move), -1);
-	}
-
-	Point begPosition = CClickableHex::getXYUnitAnim(oldPos, stack, owner);
-	Point endPosition = CClickableHex::getXYUnitAnim(nextHex, stack, owner);
-
-	timeToMove = AnimationControls::getMovementDuration(stack->getCreature());
-
-	begX = begPosition.x;
-	begY = begPosition.y;
-	progress = 0;
-	distanceX = endPosition.x - begPosition.x;
-	distanceY = endPosition.y - begPosition.y;
-
-	if (stack->hasBonus(Selector::type()(Bonus::FLYING)))
-	{
-		float distance = static_cast<float>(sqrt(distanceX * distanceX + distanceY * distanceY));
-
-		timeToMove *= AnimationControls::getFlightDistance(stack->getCreature()) / distance;
-	}
-
-	return true;
-}
-
-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 );
-
-	CBattleAnimation::nextFrame();
-
-	if(progress >= 1.0)
-	{
-		// Sets the position of the creature animation sprites
-		Point coords = CClickableHex::getXYUnitAnim(nextHex, stack, owner);
-		myAnim->pos = coords;
-
-		// true if creature haven't reached the final destination hex
-		if ((curentMoveIndex + 1) < destTiles.size())
-		{
-			// update the next hex field which has to be reached by the stack
-			curentMoveIndex++;
-			oldPos = nextHex;
-			nextHex = destTiles[curentMoveIndex];
-
-			// re-init animation
-			for(auto & elem : owner->pendingAnims)
-			{
-				if (elem.first == this)
-				{
-					elem.second = false;
-					break;
-				}
-			}
-		}
-		else
-			endAnim();
-	}
-}
-
-void CMovementAnimation::endAnim()
-{
-	assert(stack);
-
-	myAnim->pos = CClickableHex::getXYUnitAnim(nextHex, stack, owner);
-	CBattleAnimation::endAnim();
-
-	owner->addNewAnim(new CMovementEndAnimation(owner, stack, nextHex));
-
-	if(owner->moveSoundHander != -1)
-	{
-		CCS->soundh->stopSound(owner->moveSoundHander);
-		owner->moveSoundHander = -1;
-	}
-	delete this;
-}
-
-CMovementAnimation::CMovementAnimation(CBattleInterface *_owner, const CStack *_stack, std::vector<BattleHex> _destTiles, int _distance)
-	: CBattleStackAnimation(_owner, _stack),
-	  destTiles(_destTiles),
-	  curentMoveIndex(0),
-	  oldPos(stack->getPosition()),
-	  begX(0), begY(0),
-	  distanceX(0), distanceY(0),
-	  timeToMove(0.0),
-	  progress(0.0),
-	  nextHex(destTiles.front())
-{
-	logAnim->debug("Created movement anim for %s", stack->getName());
-}
-
-CMovementEndAnimation::CMovementEndAnimation(CBattleInterface * _owner, const CStack * _stack, BattleHex destTile)
-: CBattleStackAnimation(_owner, _stack), destinationTile(destTile)
-{
-	logAnim->debug("Created movement end anim for %s", stack->getName());
-}
-
-bool CMovementEndAnimation::init()
-{
-	if( !isEarliest(true) )
-		return false;
-
-	if(!stack || myAnim->framesInGroup(CCreatureAnim::MOVE_END) == 0 ||
-		myAnim->isDead())
-	{
-		endAnim();
-
-		return false;
-	}
-
-	CCS->soundh->playSound(battle_sound(stack->getCreature(), endMoving));
-
-	myAnim->setType(CCreatureAnim::MOVE_END);
-
-	myAnim->onAnimationReset += std::bind(&CMovementEndAnimation::endAnim, this);
-
-	return true;
-}
-
-void CMovementEndAnimation::endAnim()
-{
-	CBattleAnimation::endAnim();
-
-	if(myAnim->getType() != CCreatureAnim::DEAD)
-		myAnim->setType(CCreatureAnim::HOLDING); //resetting to default
-
-	CCS->curh->show();
-	delete this;
-}
-
-CMovementStartAnimation::CMovementStartAnimation(CBattleInterface * _owner, const CStack * _stack)
-: CBattleStackAnimation(_owner, _stack)
-{
-	logAnim->debug("Created movement start anim for %s", stack->getName());
-}
-
-bool CMovementStartAnimation::init()
-{
-	if( !isEarliest(false) )
-		return false;
-
-
-	if(!stack || myAnim->isDead())
-	{
-		CMovementStartAnimation::endAnim();
-		return false;
-	}
-
-	CCS->soundh->playSound(battle_sound(stack->getCreature(), startMoving));
-	myAnim->setType(CCreatureAnim::MOVE_START);
-	myAnim->onAnimationReset += std::bind(&CMovementStartAnimation::endAnim, this);
-
-	return true;
-}
-
-void CMovementStartAnimation::endAnim()
-{
-	CBattleAnimation::endAnim();
-
-	delete this;
-}
-
-CReverseAnimation::CReverseAnimation(CBattleInterface * _owner, const CStack * stack, BattleHex dest, bool _priority)
-: CBattleStackAnimation(_owner, stack), hex(dest), priority(_priority)
-{
-	logAnim->debug("Created reverse anim for %s", stack->getName());
-}
-
-bool CReverseAnimation::init()
-{
-	if(myAnim == nullptr || myAnim->isDead())
-	{
-		endAnim();
-		return false; //there is no such creature
-	}
-
-	if(!priority && !isEarliest(false))
-		return false;
-
-	if(myAnim->framesInGroup(CCreatureAnim::TURN_L))
-	{
-		myAnim->setType(CCreatureAnim::TURN_L);
-		myAnim->onAnimationReset += std::bind(&CReverseAnimation::setupSecondPart, this);
-	}
-	else
-	{
-		setupSecondPart();
-	}
-	return true;
-}
-
-void CReverseAnimation::endAnim()
-{
-	CBattleAnimation::endAnim();
-	if( stack->alive() )//don't do that if stack is dead
-		myAnim->setType(CCreatureAnim::HOLDING);
-
-	delete this;
-}
-
-void CReverseAnimation::rotateStack(CBattleInterface * owner, const CStack * stack, BattleHex hex)
-{
-	owner->creDir[stack->ID] = !owner->creDir[stack->ID];
-
-	owner->creAnims[stack->ID]->pos = CClickableHex::getXYUnitAnim(hex, stack, owner);
-}
-
-void CReverseAnimation::setupSecondPart()
-{
-	if(!stack)
-	{
-		endAnim();
-		return;
-	}
-
-	rotateStack(owner, stack, hex);
-
-	if(myAnim->framesInGroup(CCreatureAnim::TURN_R))
-	{
-		myAnim->setType(CCreatureAnim::TURN_R);
-		myAnim->onAnimationReset += std::bind(&CReverseAnimation::endAnim, this);
-	}
-	else
-		endAnim();
-}
-
-CRangedAttackAnimation::CRangedAttackAnimation(CBattleInterface * owner_, const CStack * attacker, BattleHex dest_, const CStack * defender)
-	: CAttackAnimation(owner_, attacker, dest_, defender)
-{
-
-}
-
-
-CShootingAnimation::CShootingAnimation(CBattleInterface * _owner, const CStack * attacker, BattleHex _dest, const CStack * _attacked, bool _catapult, int _catapultDmg)
-	: CRangedAttackAnimation(_owner, attacker, _dest, _attacked),
-	catapultDamage(_catapultDmg)
-{
-	logAnim->debug("Created shooting anim for %s", stack->getName());
-}
-
-bool CShootingAnimation::init()
-{
-	if( !CAttackAnimation::checkInitialConditions() )
-		return false;
-
-	const CStack * shooter = attackingStack;
-
-	if(!shooter || myAnim->isDead())
-	{
-		endAnim();
-		return false;
-	}
-
-	//reverse unit if necessary
-	if (attackingStack && attackedStack && owner->getCurrentPlayerInterface()->cb->isToReverse(attackingStack->getPosition(), attackedStack->getPosition(), owner->creDir[attackingStack->ID], attackingStack->doubleWide(), owner->creDir[attackedStack->ID]))
-	{
-		owner->addNewAnim(new CReverseAnimation(owner, attackingStack, attackingStack->getPosition(), true));
-		return false;
-	}
-
-	// opponent must face attacker ( = different directions) before he can be attacked
-	//FIXME: this cause freeze
-
-//	if (attackingStack && attackedStack &&
-//	    owner->creDir[attackingStack->ID] == owner->creDir[attackedStack->ID])
-//		return false;
-
-	// Create the projectile animation
-
-	//maximal angle in radians between straight horizontal line and shooting line for which shot is considered to be straight (absoulte value)
-	static const double straightAngle = 0.2;
-
-	// 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)
-	{
-		int creID = owner->siegeH->town->town->clientInfo.siegeShooter;
-		shooterInfo = CGI->creh->operator[](creID);
-	}
-	if(!shooterInfo->animation.missleFrameAngles.size())
-		logAnim->error("Mod error: Creature '%s' on the Archer's tower is not a shooter. Mod should be fixed. Trying to use archer's data instead..."
-			, shooterInfo->nameSing);
-
-	auto & angles = shooterInfo->animation.missleFrameAngles.size()
-		? shooterInfo->animation.missleFrameAngles
-		: CGI->creh->operator[](CreatureID::ARCHER)->animation.missleFrameAngles;
-
-	ProjectileInfo spi;
-	spi.shotDone = false;
-	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.step = 0;
-	spi.frameNum = 0;
-
-	Point fromPos;
-	Point destPos;
-
-	// NOTE: two lines below return different positions (very notable with 2-hex creatures). Obtaining via creanims seems to be more precise
-	fromPos = owner->creAnims[spi.stackID]->pos.topLeft();
-	//xycoord = CClickableHex::getXYUnitAnim(shooter->position, true, shooter, owner);
-
-	destPos = CClickableHex::getXYUnitAnim(dest, attackedStack, owner);
-
-	// to properly translate coordinates when shooter is rotated
-	int multiplier = spi.reverse ? -1 : 1;
-
-	double projectileAngle = atan2(fabs((double)destPos.y - fromPos.y), fabs((double)destPos.x - fromPos.x));
-	if(shooter->getPosition() < dest)
-		projectileAngle = -projectileAngle;
-
-	// Calculate projectile start position. Offsets are read out of the CRANIM.TXT.
-	if (projectileAngle > straightAngle)
-	{
-		//upper shot
-		spi.x0 = fromPos.x + 222 + ( -25 + shooterInfo->animation.upperRightMissleOffsetX ) * multiplier;
-		spi.y0 = fromPos.y + 265 + shooterInfo->animation.upperRightMissleOffsetY;
-	}
-	else if (projectileAngle < -straightAngle)
-	{
-		//lower shot
-		spi.x0 = fromPos.x + 222 + ( -25 + shooterInfo->animation.lowerRightMissleOffsetX ) * multiplier;
-		spi.y0 = fromPos.y + 265 + shooterInfo->animation.lowerRightMissleOffsetY;
-	}
-	else
-	{
-		//straight shot
-		spi.x0 = fromPos.x + 222 + ( -25 + shooterInfo->animation.rightMissleOffsetX ) * multiplier;
-		spi.y0 = fromPos.y + 265 + shooterInfo->animation.rightMissleOffsetY;
-	}
-
-	spi.x = spi.x0;
-	spi.y = spi.y0;
-
-	destPos += Point(225, 225);
-
-	// recalculate angle taking in account offsets
-	//projectileAngle = atan2(fabs(destPos.y - spi.y), fabs(destPos.x - spi.x));
-	//if(shooter->position < dest)
-	//	projectileAngle = -projectileAngle;
-
-	if (attackedStack)
-	{
-		double animSpeed = AnimationControls::getProjectileSpeed(); // flight speed of projectile
-		double distanceSquared = (destPos.x - spi.x) * (destPos.x - spi.x) + (destPos.y - spi.y) * (destPos.y - spi.y);
-		double distance = sqrt(distanceSquared);
-		spi.lastStep = std::round(distance / animSpeed);
-		if(spi.lastStep == 0)
-			spi.lastStep = 1;
-		spi.dx = (destPos.x - spi.x) / spi.lastStep;
-		spi.dy = (destPos.y - spi.y) / spi.lastStep;
-	}
-	else
-	{
-		// Catapult attack
-		spi.catapultInfo.reset(new CatapultProjectileInfo(Point((int)spi.x, (int)spi.y), destPos));
-
-		double animSpeed = AnimationControls::getProjectileSpeed() / 10;
-		spi.lastStep = static_cast<int>(std::abs((destPos.x - spi.x) / animSpeed));
-		spi.dx = animSpeed;
-		spi.dy = 0;
-
-		auto img = owner->idToProjectile[spi.creID]->getImage(0);
-
-		// Add explosion anim
-		Point animPos(destPos.x - 126 + img->width() / 2,
-					  destPos.y - 105 + img->height() / 2);
-
-		owner->addNewAnim( new CEffectAnimation(owner, catapultDamage ? "SGEXPL.DEF" : "CSGRCK.DEF", animPos.x, animPos.y));
-	}
-	double pi = boost::math::constants::pi<double>();
-
-	//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) && !owner->idToRay.count(spi.creID))
-		owner->initStackProjectile(shooter);
-
-	if (owner->idToProjectile.count(spi.creID))
-	{
-		// only frames below maxFrame are usable: anything  higher is either no present or we don't know when it should be used
-		size_t maxFrame = std::min<size_t>(angles.size(), owner->idToProjectile.at(spi.creID)->size(0));
-
-		assert(maxFrame > 0);
-
-		// 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 );
-
-		for (size_t i=1; i<maxFrame; i++)
-		{
-			double currentDiff = fabs( angles[i] / 180 * pi - projectileAngle );
-			if (currentDiff < bestDiff)
-			{
-				bestID = i;
-				bestDiff = currentDiff;
-			}
-		}
-
-		spi.frameNum = static_cast<int>(bestID);
-	}
-	else if (owner->idToRay.count(spi.creID))
-	{
-		// no-op
-	}
-	else
-	{
-		logGlobal->error("Unable to find valid projectile for shooter %d", spi.creID);
-	}
-
-	// Set projectile animation start delay which is specified in frames
-	spi.animStartDelay = shooterInfo->animation.attackClimaxFrame;
-	owner->projectiles.push_back(spi);
-
-	//attack animation
-
-	shooting = true;
-
-	if(projectileAngle > straightAngle)
-		group = CCreatureAnim::SHOOT_UP;
-	else if(projectileAngle < -straightAngle)
-		group = CCreatureAnim::SHOOT_DOWN;
-	else //straight shot
-		group = CCreatureAnim::SHOOT_FRONT;
-
-	return true;
-}
-
-void CShootingAnimation::nextFrame()
-{
-	for(auto & it : owner->pendingAnims)
-	{
-		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 ) )
-			return;
-	}
-
-	CAttackAnimation::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");
-		}
-	}
-
-	CAttackAnimation::endAnim();
-	delete this;
-}
-
-CCastAnimation::CCastAnimation(CBattleInterface * owner_, const CStack * attacker, BattleHex dest_, const CStack * defender)
-	: CRangedAttackAnimation(owner_, attacker, dest_, defender)
-{
-	if(!dest_.isValid() && defender)
-		dest = defender->getPosition();
-}
-
-bool CCastAnimation::init()
-{
-	if(!CAttackAnimation::checkInitialConditions())
-		return false;
-
-	if(!attackingStack || myAnim->isDead())
-	{
-		endAnim();
-		return false;
-	}
-
-	//reverse unit if necessary
-	if(attackedStack)
-	{
-		if(owner->getCurrentPlayerInterface()->cb->isToReverse(attackingStack->getPosition(), attackedStack->getPosition(), owner->creDir[attackingStack->ID], attackingStack->doubleWide(), owner->creDir[attackedStack->ID]))
-		{
-			owner->addNewAnim(new CReverseAnimation(owner, attackingStack, attackingStack->getPosition(), true));
-			return false;
-		}
-	}
-	else
-	{
-		if(dest.isValid() && owner->getCurrentPlayerInterface()->cb->isToReverse(attackingStack->getPosition(), dest, owner->creDir[attackingStack->ID], false, false))
-		{
-			owner->addNewAnim(new CReverseAnimation(owner, attackingStack, attackingStack->getPosition(), true));
-			return false;
-		}
-	}
-
-	//TODO: display spell projectile here
-
-	static const double straightAngle = 0.2;
-
-
-	Point fromPos;
-	Point destPos;
-
-	// NOTE: two lines below return different positions (very notable with 2-hex creatures). Obtaining via creanims seems to be more precise
-	fromPos = owner->creAnims[attackingStack->ID]->pos.topLeft();
-	//xycoord = CClickableHex::getXYUnitAnim(shooter->getPosition(), true, shooter, owner);
-
-	destPos = CClickableHex::getXYUnitAnim(dest, attackedStack, owner);
-
-
-	double projectileAngle = atan2(fabs((double)destPos.y - fromPos.y), fabs((double)destPos.x - fromPos.x));
-	if(attackingStack->getPosition() < dest)
-		projectileAngle = -projectileAngle;
-
-
-	if(projectileAngle > straightAngle)
-		group = CCreatureAnim::VCMI_CAST_UP;
-	else if(projectileAngle < -straightAngle)
-		group = CCreatureAnim::VCMI_CAST_DOWN;
-	else
-		group = CCreatureAnim::VCMI_CAST_FRONT;
-
-	//fall back to H3 cast/2hex
-	//even if creature have 2hex attack instead of cast it is ok since we fall back to attack anyway
-	if(myAnim->framesInGroup(group) == 0)
-	{
-		if(projectileAngle > straightAngle)
-			group = CCreatureAnim::CAST_UP;
-		else if(projectileAngle < -straightAngle)
-			group = CCreatureAnim::CAST_DOWN;
-		else
-			group = CCreatureAnim::CAST_FRONT;
-	}
-
-	//fall back to ranged attack
-	if(myAnim->framesInGroup(group) == 0)
-	{
-		if(projectileAngle > straightAngle)
-			group = CCreatureAnim::SHOOT_UP;
-		else if(projectileAngle < -straightAngle)
-			group = CCreatureAnim::SHOOT_DOWN;
-		else
-			group = CCreatureAnim::SHOOT_FRONT;
-	}
-
-	//fall back to normal attack
-	if(myAnim->framesInGroup(group) == 0)
-	{
-		if(projectileAngle > straightAngle)
-			group = CCreatureAnim::ATTACK_UP;
-		else if(projectileAngle < -straightAngle)
-			group = CCreatureAnim::ATTACK_DOWN;
-		else
-			group = CCreatureAnim::ATTACK_FRONT;
-	}
-
-	return true;
-}
-
-void CCastAnimation::nextFrame()
-{
-	for(auto & it : owner->pendingAnims)
-	{
-		CReverseAnimation * anim = dynamic_cast<CReverseAnimation *>(it.first);
-		if(anim && anim->stack->ID == stack->ID && anim->priority)
-			return;
-	}
-
-	if(myAnim->getType() != group)
-	{
-		myAnim->setType(group);
-		myAnim->onAnimationReset += std::bind(&CAttackAnimation::endAnim, this);
-	}
-
-	CBattleAnimation::nextFrame();
-}
-
-
-void CCastAnimation::endAnim()
-{
-	CAttackAnimation::endAnim();
-	delete this;
-}
-
-
-CEffectAnimation::CEffectAnimation(CBattleInterface * _owner, std::string _customAnim, int _x, int _y, int _dx, int _dy, bool _Vflip, bool _alignToBottom)
-	: CBattleAnimation(_owner),
-	destTile(BattleHex::INVALID),
-	x(_x),
-	y(_y),
-	dx(_dx),
-	dy(_dy),
-	Vflip(_Vflip),
-	alignToBottom(_alignToBottom)
-{
-	logAnim->debug("Created effect animation %s", _customAnim);
-
-	customAnim = std::make_shared<CAnimation>(_customAnim);
-}
-
-CEffectAnimation::CEffectAnimation(CBattleInterface * _owner, std::shared_ptr<CAnimation> _customAnim, int _x, int _y, int _dx, int _dy)
-	: CBattleAnimation(_owner),
-	destTile(BattleHex::INVALID),
-	customAnim(_customAnim),
-	x(_x),
-	y(_y),
-	dx(_dx),
-	dy(_dy),
-	Vflip(false),
-	alignToBottom(false)
-{
-	logAnim->debug("Created custom effect animation");
-}
-
-
-CEffectAnimation::CEffectAnimation(CBattleInterface * _owner, std::string _customAnim, BattleHex _destTile, bool _Vflip, bool _alignToBottom)
-	: CBattleAnimation(_owner),
-	destTile(_destTile),
-	x(-1),
-	y(-1),
-	dx(0),
-	dy(0),
-	Vflip(_Vflip),
-	alignToBottom(_alignToBottom)
-{
-	logAnim->debug("Created effect animation %s", _customAnim);
-	customAnim = std::make_shared<CAnimation>(_customAnim);
-}
-
-bool CEffectAnimation::init()
-{
-	if(!isEarliest(true))
-		return false;
-
-	const bool areaEffect = (!destTile.isValid() && x == -1 && y == -1);
-
-	std::shared_ptr<CAnimation> animation = customAnim;
-
-	animation->preload();
-	if(Vflip)
-		animation->verticalFlip();
-
-	auto first = animation->getImage(0, 0, true);
-	if(!first)
-	{
-		endAnim();
-		return false;
-	}
-
-	if(areaEffect) //f.e. armageddon
-	{
-		for(int i=0; i * first->width() < owner->pos.w ; ++i)
-		{
-			for(int j=0; j * first->height() < owner->pos.h ; ++j)
-			{
-				BattleEffect be;
-				be.effectID = ID;
-				be.animation = animation;
-				be.currentFrame = 0;
-
-				be.x = i * first->width() + owner->pos.x;
-				be.y = j * first->height() + owner->pos.y;
-				be.position = BattleHex::INVALID;
-
-				owner->battleEffects.push_back(be);
-			}
-		}
-	}
-	else // Effects targeted at a specific creature/hex.
-	{
-		const CStack * destStack = owner->getCurrentPlayerInterface()->cb->battleGetStackByPos(destTile, false);
-		BattleEffect be;
-		be.effectID = ID;
-		be.animation = animation;
-		be.currentFrame = 0;
-
-
-		//todo: lightning anim frame count override
-
-//			if(effect == 1)
-//				be.maxFrame = 3;
-
-		be.x = x;
-		be.y = y;
-		if(destTile.isValid())
-		{
-			Rect & tilePos = owner->bfield[destTile]->pos;
-			if(x == -1)
-				be.x = tilePos.x + tilePos.w/2 - first->width()/2;
-			if(y == -1)
-			{
-				if(alignToBottom)
-					be.y = tilePos.y + tilePos.h - first->height();
-				else
-					be.y = tilePos.y - first->height()/2;
-			}
-
-			// Correction for 2-hex creatures.
-			if(destStack != nullptr && destStack->doubleWide())
-				be.x += (destStack->side == BattleSide::ATTACKER ? -1 : 1)*tilePos.w/2;
-		}
-
-		assert(be.x != -1 && be.y != -1);
-
-		//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);
-	}
-	//battleEffects
-	return true;
-}
-
-void CEffectAnimation::nextFrame()
-{
-	//notice: there may be more than one effect in owner->battleEffects correcponding to this animation (ie. armageddon)
-	for(auto & elem : owner->battleEffects)
-	{
-		if(elem.effectID == ID)
-		{
-			elem.currentFrame += AnimationControls::getSpellEffectSpeed() * GH.mainFPSmng->getElapsedMilliseconds() / 1000;
-
-			if(elem.currentFrame >= elem.animation->size())
-			{
-				endAnim();
-				break;
-			}
-			else
-			{
-				elem.x += dx;
-				elem.y += dy;
-			}
-		}
-	}
-}
-
-void CEffectAnimation::endAnim()
-{
-	CBattleAnimation::endAnim();
-
-	std::vector<std::list<BattleEffect>::iterator> toDel;
-
-	for(auto it = owner->battleEffects.begin(); it != owner->battleEffects.end(); ++it)
-	{
-		if(it->effectID == ID)
-		{
-			toDel.push_back(it);
-		}
-	}
-
-	for(auto & elem : toDel)
-	{
-		owner->battleEffects.erase(elem);
-	}
-
-	delete this;
-}

+ 0 - 262
client/battle/CBattleAnimations.h

@@ -1,262 +0,0 @@
-/*
- * CBattleAnimations.h, part of VCMI engine
- *
- * Authors: listed in file AUTHORS in main folder
- *
- * License: GNU General Public License v2.0 or later
- * Full text of license available in license.txt file, in main folder
- *
- */
-#pragma once
-
-#include "../../lib/battle/BattleHex.h"
-#include "../widgets/Images.h"
-
-VCMI_LIB_NAMESPACE_BEGIN
-
-class CStack;
-
-VCMI_LIB_NAMESPACE_END
-
-class CBattleInterface;
-class CCreatureAnimation;
-struct CatapultProjectileInfo;
-struct StackAttackedInfo;
-
-/// Base class of battle animations
-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
-	virtual void endAnim(); //to be called mostly internally; in this class it removes animation from pendingAnims list
-	virtual ~CBattleAnimation();
-
-	bool isEarliest(bool perStackConcurrency); //determines if this animation is earliest of all
-
-	ui32 ID; //unique identifier
-	CBattleAnimation(CBattleInterface * _owner);
-};
-
-/// Sub-class which is responsible for managing the battle stack animation.
-class CBattleStackAnimation : public CBattleAnimation
-{
-public:
-	std::shared_ptr<CCreatureAnimation> myAnim; //animation for our stack, managed by CBattleInterface
-	const CStack * stack; //id of stack whose animation it is
-
-	CBattleStackAnimation(CBattleInterface * _owner, const CStack * _stack);
-
-	void shiftColor(const ColorShifter * shifter);
-};
-
-/// This class is responsible for managing the battle attack animation
-class CAttackAnimation : public CBattleStackAnimation
-{
-	bool soundPlayed;
-
-protected:
-	BattleHex dest; //attacked hex
-	bool shooting;
-	CCreatureAnim::EAnimType group; //if shooting is true, print this animation group
-	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);
-};
-
-/// Animation of a defending unit
-class CDefenceAnimation : public CBattleStackAnimation
-{
-	CCreatureAnim::EAnimType getMyAnimType();
-	std::string getMySound();
-
-	void startAnimation();
-
-	const CStack * attacker; //attacking stack
-	bool rangedAttack; //if true, stack has been attacked by shooting
-	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;
-	void endAnim() override;
-
-	CDefenceAnimation(StackAttackedInfo _attackedInfo, CBattleInterface * _owner);
-	virtual ~CDefenceAnimation(){};
-};
-
-class CDummyAnimation : public CBattleAnimation
-{
-private:
-	int counter;
-	int howMany;
-public:
-	bool init() override;
-	void nextFrame() override;
-	void endAnim() override;
-
-	CDummyAnimation(CBattleInterface * _owner, int howManyFrames);
-	virtual ~CDummyAnimation(){}
-};
-
-/// Hand-to-hand attack
-class CMeleeAttackAnimation : public CAttackAnimation
-{
-public:
-	bool init() override;
-	void endAnim() override;
-
-	CMeleeAttackAnimation(CBattleInterface * _owner, const CStack * attacker, BattleHex _dest, const CStack * _attacked);
-	virtual ~CMeleeAttackAnimation(){};
-};
-
-/// Move animation of a creature
-class CMovementAnimation : public CBattleStackAnimation
-{
-private:
-	std::vector<BattleHex> destTiles; //full path, includes already passed hexes
-	ui32 curentMoveIndex; // index of nextHex in destTiles
-
-	BattleHex oldPos; //position of stack before move
-
-	double begX, begY; // starting position
-	double distanceX, distanceY; // full movement distance, may be negative if creture moves topleft
-
-	double timeToMove; // full length of movement animation
-	double progress; // range 0 -> 1, indicates move progrees. 0 = movement starts, 1 = move ends
-
-public:
-	BattleHex nextHex; // next hex, to which creature move right now
-
-	bool init() override;
-	void nextFrame() override;
-	void endAnim() override;
-
-	CMovementAnimation(CBattleInterface *_owner, const CStack *_stack, std::vector<BattleHex> _destTiles, int _distance);
-	virtual ~CMovementAnimation(){};
-};
-
-/// Move end animation of a creature
-class CMovementEndAnimation : public CBattleStackAnimation
-{
-private:
-	BattleHex destinationTile;
-public:
-	bool init() override;
-	void endAnim() override;
-
-	CMovementEndAnimation(CBattleInterface * _owner, const CStack * _stack, BattleHex destTile);
-	virtual ~CMovementEndAnimation(){};
-};
-
-/// Move start animation of a creature
-class CMovementStartAnimation : public CBattleStackAnimation
-{
-public:
-	bool init() override;
-	void endAnim() override;
-
-	CMovementStartAnimation(CBattleInterface * _owner, const CStack * _stack);
-	virtual ~CMovementStartAnimation(){};
-};
-
-/// Class responsible for animation of stack chaning direction (left <-> right)
-class CReverseAnimation : public CBattleStackAnimation
-{
-	BattleHex hex;
-public:
-	bool priority; //true - high, false - low
-	bool init() override;
-
-	static void rotateStack(CBattleInterface * owner, const CStack * stack, BattleHex hex);
-
-	void setupSecondPart();
-	void endAnim() override;
-
-	CReverseAnimation(CBattleInterface * _owner, const CStack * stack, BattleHex dest, bool _priority);
-	virtual ~CReverseAnimation(){};
-};
-
-/// Small struct which contains information about the position and the velocity of a projectile
-struct ProjectileInfo
-{
-	double x0, y0; //initial position on the screen
-	double x, y; //position on the screen
-	double dx, dy; //change in position in one step
-	int step, lastStep; //to know when finish showing this projectile
-	int creID; //ID of creature that shot this projectile
-	int stackID; //ID of stack
-	int frameNum; //frame to display form projectile animation
-	//bool spin; //if true, frameNum will be increased
-	int animStartDelay; //frame of shooter animation when projectile should appear
-	bool shotDone; // actual shot already done, projectile is flying
-	bool reverse; //if true, projectile will be flipped by vertical asix
-	std::shared_ptr<CatapultProjectileInfo> catapultInfo; // holds info about the parabolic trajectory of the cannon
-};
-
-class CRangedAttackAnimation : public CAttackAnimation
-{
-public:
-	CRangedAttackAnimation(CBattleInterface * owner_, const CStack * attacker, BattleHex dest_, const CStack * defender);
-protected:
-
-};
-
-/// Shooting attack
-class CShootingAnimation : public CRangedAttackAnimation
-{
-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);
-	virtual ~CShootingAnimation(){};
-};
-
-class CCastAnimation : public CRangedAttackAnimation
-{
-public:
-	CCastAnimation(CBattleInterface * owner_, const CStack * attacker, BattleHex dest_, const CStack * defender);
-
-	bool init() override;
-	void nextFrame() override;
-	void endAnim() override;
-
-};
-
-
-/// This class manages effect animation
-class CEffectAnimation : public CBattleAnimation
-{
-private:
-	BattleHex destTile;
-	std::shared_ptr<CAnimation>	customAnim;
-	int	x, y, dx, dy;
-	bool Vflip;
-	bool alignToBottom;
-public:
-	bool init() override;
-	void nextFrame() override;
-	void endAnim() override;
-
-	CEffectAnimation(CBattleInterface * _owner, std::string _customAnim, int _x, int _y, int _dx = 0, int _dy = 0, bool _Vflip = false, bool _alignToBottom = false);
-
-	CEffectAnimation(CBattleInterface * _owner, std::shared_ptr<CAnimation> _customAnim, int _x, int _y, int _dx = 0, int _dy = 0);
-
-	CEffectAnimation(CBattleInterface * _owner, std::string _customAnim, BattleHex _destTile, bool _Vflip = false, bool _alignToBottom = false);
-	virtual ~CEffectAnimation(){};
-};

+ 0 - 3806
client/battle/CBattleInterface.cpp

@@ -1,3806 +0,0 @@
-/*
- * CBattleInterface.cpp, part of VCMI engine
- *
- * Authors: listed in file AUTHORS in main folder
- *
- * License: GNU General Public License v2.0 or later
- * Full text of license available in license.txt file, in main folder
- *
- */
-#include "StdInc.h"
-#include "CBattleInterface.h"
-
-#include "CBattleAnimations.h"
-#include "CBattleInterfaceClasses.h"
-#include "CCreatureAnimation.h"
-
-#include "../CBitmapHandler.h"
-#include "../CGameInfo.h"
-#include "../CMessage.h"
-#include "../CMT.h"
-#include "../CMusicHandler.h"
-#include "../CPlayerInterface.h"
-#include "../CVideoHandler.h"
-#include "../Graphics.h"
-#include "../gui/CAnimation.h"
-#include "../gui/CCursorHandler.h"
-#include "../gui/CGuiHandler.h"
-#include "../gui/SDL_Extensions.h"
-#include "../windows/CAdvmapInterface.h"
-#include "../windows/CCreatureWindow.h"
-#include "../windows/CSpellWindow.h"
-
-#include "../../CCallback.h"
-#include "../../lib/CStack.h"
-#include "../../lib/CConfigHandler.h"
-#include "../../lib/CGeneralTextHandler.h"
-#include "../../lib/CHeroHandler.h"
-#include "../../lib/CondSh.h"
-#include "../../lib/CRandomGenerator.h"
-#include "../../lib/spells/CSpellHandler.h"
-#include "../../lib/spells/ISpellMechanics.h"
-#include "../../lib/spells/Problem.h"
-#include "../../lib/CTownHandler.h"
-#include "../../lib/BattleFieldHandler.h"
-#include "../../lib/ObstacleHandler.h"
-#include "../../lib/CGameState.h"
-#include "../../lib/mapping/CMap.h"
-#include "../../lib/NetPacks.h"
-#include "../../lib/UnlockGuard.h"
-
-CondSh<bool> CBattleInterface::animsAreDisplayed(false);
-CondSh<BattleAction *> CBattleInterface::givenCommand(nullptr);
-
-static void onAnimationFinished(const CStack *stack, std::weak_ptr<CCreatureAnimation> anim)
-{
-	std::shared_ptr<CCreatureAnimation> animation = anim.lock();
-	if(!animation)
-		return;
-
-	if (animation->isIdle())
-	{
-		const CCreature *creature = stack->getCreature();
-
-		if (animation->framesInGroup(CCreatureAnim::MOUSEON) > 0)
-		{
-			if (CRandomGenerator::getDefault().nextDouble(99.0) < creature->animation.timeBetweenFidgets *10)
-				animation->playOnce(CCreatureAnim::MOUSEON);
-			else
-				animation->setType(CCreatureAnim::HOLDING);
-		}
-		else
-		{
-			animation->setType(CCreatureAnim::HOLDING);
-		}
-	}
-	// always reset callback
-	animation->onAnimationReset += std::bind(&onAnimationFinished, stack, anim);
-}
-
-static void transformPalette(SDL_Surface *surf, double rCor, double gCor, double bCor)
-{
-	SDL_Color *colorsToChange = surf->format->palette->colors;
-	for (int g=0; g<surf->format->palette->ncolors; ++g)
-	{
-		SDL_Color *color = &colorsToChange[g];
-		if (color->b != 132 &&
-			color->g != 231 &&
-			color->r != 255) //it's not yellow border
-		{
-			color->r = static_cast<Uint8>(color->r * rCor);
-			color->g = static_cast<Uint8>(color->g * gCor);
-			color->b = static_cast<Uint8>(color->b * bCor);
-		}
-	}
-}
-
-void CBattleInterface::addNewAnim(CBattleAnimation *anim)
-{
-	pendingAnims.push_back( std::make_pair(anim, false) );
-	animsAreDisplayed.setn(true);
-}
-
-CBattleInterface::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)
-	: background(nullptr), attackingHeroInstance(hero1), defendingHeroInstance(hero2), animCount(0),
-	activeStack(nullptr), mouseHoveredStack(nullptr), stackToActivate(nullptr), selectedStack(nullptr), previouslyHoveredHex(-1),
-	currentlyHoveredHex(-1), attackingHex(-1), stackCanCastSpell(false), creatureCasting(false), spellDestSelectMode(false), spellToCast(nullptr), sp(nullptr),
-	creatureSpellToCast(-1),
-	siegeH(nullptr), attackerInt(att), defenderInt(defen), curInt(att), animIDhelper(0),
-	myTurn(false), moveStarted(false), moveSoundHander(-1), bresult(nullptr), battleActionsStarted(false)
-{
-	OBJ_CONSTRUCTION;
-
-	if(spectatorInt)
-	{
-		curInt = spectatorInt;
-	}
-	else if(!curInt)
-	{
-		//May happen when we are defending during network MP game -> attacker interface is just not present
-		curInt = defenderInt;
-	}
-
-	animsAreDisplayed.setn(false);
-	pos = myRect;
-	strongInterest = true;
-	givenCommand.setn(nullptr);
-
-	//hot-seat -> check tactics for both players (defender may be local human)
-	if(attackerInt && attackerInt->cb->battleGetTacticDist())
-		tacticianInterface = attackerInt;
-	else if(defenderInt && defenderInt->cb->battleGetTacticDist())
-		tacticianInterface = defenderInt;
-
-	//if we found interface of player with tactics, then enter tactics mode
-	tacticsMode = static_cast<bool>(tacticianInterface);
-
-	//create stack queue
-
-	bool embedQueue;
-
-	std::string queueSize = settings["battle"]["queueSize"].String();
-
-	if(queueSize == "auto")
-		embedQueue = screen->h < 700;
-	else
-		embedQueue = screen->h < 700 || queueSize == "small";
-
-	queue = std::make_shared<CStackQueue>(embedQueue, this);
-	if(!embedQueue)
-	{
-		if (settings["battle"]["showQueue"].Bool())
-			pos.y += queue->pos.h / 2; //center whole window
-
-		queue->moveTo(Point(pos.x, pos.y - queue->pos.h));
-	}
-
-	//preparing siege info
-	const CGTownInstance *town = curInt->cb->battleGetDefendedTown();
-	if(town && town->hasFort())
-	{
-		siegeH = new SiegeHelper(town, this);
-	}
-
-	CPlayerInterface::battleInt = this;
-
-	//initializing armies
-	this->army1 = army1;
-	this->army2 = army2;
-	std::vector<const CStack*> stacks = curInt->cb->battleGetAllStacks(true);
-	for(const CStack * s : stacks)
-	{
-		unitAdded(s);
-	}
-
-	//preparing menu background and terrain
-	if(siegeH)
-	{
-		background = BitmapHandler::loadBitmap( siegeH->getSiegeName(0), false );
-		ui8 siegeLevel = curInt->cb->battleGetSiegeLevel();
-		if (siegeLevel >= 2) //citadel or castle
-		{
-			//print moat/mlip
-			SDL_Surface *moat = BitmapHandler::loadBitmap( siegeH->getSiegeName(13) ),
-				* mlip = BitmapHandler::loadBitmap( siegeH->getSiegeName(14) );
-
-			auto & info = siegeH->town->town->clientInfo;
-			Point moatPos(info.siegePositions[13].x, info.siegePositions[13].y);
-			Point mlipPos(info.siegePositions[14].x, info.siegePositions[14].y);
-
-			if (moat) //eg. tower has no moat
-				blitAt(moat, moatPos.x,moatPos.y, background);
-			if (mlip) //eg. tower has no mlip
-				blitAt(mlip, mlipPos.x, mlipPos.y, background);
-
-			SDL_FreeSurface(moat);
-			SDL_FreeSurface(mlip);
-		}
-	}
-	else
-	{
-		auto bfieldType = curInt->cb->battleGetBattlefieldType();
-
-		if(bfieldType == BattleField::NONE)
-		{
-			logGlobal->error("Invalid battlefield returned for current battle");
-		}
-		else
-		{
-			background = BitmapHandler::loadBitmap(bfieldType.getInfo()->graphics, false);
-		}
-	}
-
-	//preparing graphics for displaying amounts of creatures
-	amountNormal = BitmapHandler::loadBitmap("CMNUMWIN.BMP");
-	CSDL_Ext::alphaTransform(amountNormal);
-	transformPalette(amountNormal, 0.59, 0.19, 0.93);
-
-	amountPositive = BitmapHandler::loadBitmap("CMNUMWIN.BMP");
-	CSDL_Ext::alphaTransform(amountPositive);
-	transformPalette(amountPositive, 0.18, 1.00, 0.18);
-
-	amountNegative = BitmapHandler::loadBitmap("CMNUMWIN.BMP");
-	CSDL_Ext::alphaTransform(amountNegative);
-	transformPalette(amountNegative, 1.00, 0.18, 0.18);
-
-	amountEffNeutral = BitmapHandler::loadBitmap("CMNUMWIN.BMP");
-	CSDL_Ext::alphaTransform(amountEffNeutral);
-	transformPalette(amountEffNeutral, 1.00, 1.00, 0.18);
-
-	//preparing buttons and console
-	bOptions = std::make_shared<CButton>(Point(  3, 561), "icm003.def", CGI->generaltexth->zelp[381], std::bind(&CBattleInterface::bOptionsf,this), SDLK_o);
-	bSurrender = std::make_shared<CButton>(Point( 54, 561), "icm001.def", CGI->generaltexth->zelp[379], std::bind(&CBattleInterface::bSurrenderf,this), SDLK_s);
-	bFlee = std::make_shared<CButton>(Point(105, 561), "icm002.def", CGI->generaltexth->zelp[380], std::bind(&CBattleInterface::bFleef,this), SDLK_r);
-	bAutofight = std::make_shared<CButton>(Point(157, 561), "icm004.def", CGI->generaltexth->zelp[382], std::bind(&CBattleInterface::bAutofightf,this), SDLK_a);
-	bSpell = std::make_shared<CButton>(Point(645, 561), "icm005.def", CGI->generaltexth->zelp[385], std::bind(&CBattleInterface::bSpellf,this), SDLK_c);
-	bWait = std::make_shared<CButton>(Point(696, 561), "icm006.def", CGI->generaltexth->zelp[386], std::bind(&CBattleInterface::bWaitf,this), SDLK_w);
-	bDefence = std::make_shared<CButton>(Point(747, 561), "icm007.def", CGI->generaltexth->zelp[387], std::bind(&CBattleInterface::bDefencef,this), SDLK_d);
-	bDefence->assignedKeys.insert(SDLK_SPACE);
-	bConsoleUp = std::make_shared<CButton>(Point(624, 561), "ComSlide.def", std::make_pair("", ""), std::bind(&CBattleInterface::bConsoleUpf,this), SDLK_UP);
-	bConsoleDown = std::make_shared<CButton>(Point(624, 580), "ComSlide.def", std::make_pair("", ""), std::bind(&CBattleInterface::bConsoleDownf,this), SDLK_DOWN);
-	bConsoleUp->setImageOrder(0, 1, 0, 0);
-	bConsoleDown->setImageOrder(2, 3, 2, 2);
-
-	console = std::make_shared<CBattleConsole>();
-	console->pos.x += 211;
-	console->pos.y += 560;
-	console->pos.w = 406;
-	console->pos.h = 38;
-	if(tacticsMode)
-	{
-		btactNext = std::make_shared<CButton>(Point(213, 560), "icm011.def", std::make_pair("", ""), [&](){ bTacticNextStack(nullptr);}, SDLK_SPACE);
-		btactEnd = std::make_shared<CButton>(Point(419, 560), "icm012.def", std::make_pair("", ""), [&](){ bEndTacticPhase();}, SDLK_RETURN);
-		menu = BitmapHandler::loadBitmap("COPLACBR.BMP");
-	}
-	else
-	{
-		menu = BitmapHandler::loadBitmap("CBAR.BMP");
-	}
-	graphics->blueToPlayersAdv(menu, curInt->playerID);
-
-	//loading hero animations
-	if(hero1) // attacking hero
-	{
-		std::string battleImage;
-		if(!hero1->type->battleImage.empty())
-		{
-			battleImage = hero1->type->battleImage;
-		}
-		else
-		{
-			if(hero1->sex)
-				battleImage = hero1->type->heroClass->imageBattleFemale;
-			else
-				battleImage = hero1->type->heroClass->imageBattleMale;
-		}
-
-		attackingHero = std::make_shared<CBattleHero>(battleImage, false, hero1->tempOwner, hero1->tempOwner == curInt->playerID ? hero1 : nullptr, this);
-
-		auto img = attackingHero->animation->getImage(0, 0, true);
-		if(img)
-			attackingHero->pos = genRect(img->height(), img->width(), pos.x - 43, pos.y - 19);
-	}
-
-
-	if(hero2) // defending hero
-	{
-		std::string battleImage;
-
-		if(!hero2->type->battleImage.empty())
-		{
-			battleImage = hero2->type->battleImage;
-		}
-		else
-		{
-			if(hero2->sex)
-				battleImage = hero2->type->heroClass->imageBattleFemale;
-			else
-				battleImage = hero2->type->heroClass->imageBattleMale;
-		}
-
-		defendingHero = std::make_shared<CBattleHero>(battleImage, true, hero2->tempOwner, hero2->tempOwner == curInt->playerID ? hero2 : nullptr, this);
-
-		auto img = defendingHero->animation->getImage(0, 0, true);
-		if(img)
-			defendingHero->pos = genRect(img->height(), img->width(), pos.x + 693, pos.y - 19);
-	}
-
-
-	//preparing cells and hexes
-	cellBorder = BitmapHandler::loadBitmap("CCELLGRD.BMP");
-	CSDL_Ext::alphaTransform(cellBorder);
-	cellShade = BitmapHandler::loadBitmap("CCELLSHD.BMP");
-	CSDL_Ext::alphaTransform(cellShade);
-	for (int h = 0; h < GameConstants::BFIELD_SIZE; ++h)
-	{
-		auto hex = std::make_shared<CClickableHex>();
-		hex->myNumber = h;
-		hex->pos = hexPosition(h);
-		hex->accessible = true;
-		hex->myInterface = this;
-		bfield.push_back(hex);
-	}
-	//locking occupied positions on batlefield
-	for(const CStack * s : stacks)  //stacks gained at top of this function
-		if(s->initialPosition >= 0) //turrets have position < 0
-			bfield[s->getPosition()]->accessible = false;
-
-	//preparing graphic with cell borders
-	cellBorders = CSDL_Ext::newSurface(background->w, background->h, cellBorder);
-	//copying palette
-	for (int g=0; g<cellBorder->format->palette->ncolors; ++g) //we assume that cellBorders->format->palette->ncolors == 256
-	{
-		cellBorders->format->palette->colors[g] = cellBorder->format->palette->colors[g];
-	}
-	//palette copied
-	for (int i=0; i<GameConstants::BFIELD_HEIGHT; ++i) //rows
-	{
-		for (int j=0; j<GameConstants::BFIELD_WIDTH-2; ++j) //columns
-		{
-			int x = 58 + (i%2==0 ? 22 : 0) + 44*j;
-			int y = 86 + 42 *i;
-			for (int cellX = 0; cellX < cellBorder->w; ++cellX)
-			{
-				for (int cellY = 0; cellY < cellBorder->h; ++cellY)
-				{
-					if (y+cellY < cellBorders->h && x+cellX < cellBorders->w)
-						* ((Uint8*)cellBorders->pixels + (y+cellY) *cellBorders->pitch + (x+cellX)) |= *((Uint8*)cellBorder->pixels + cellY *cellBorder->pitch + cellX);
-				}
-			}
-		}
-	}
-
-	backgroundWithHexes = CSDL_Ext::newSurface(background->w, background->h, screen);
-
-	//preparing obstacle defs
-	auto obst = curInt->cb->battleGetAllObstacles();
-	for(auto & elem : obst)
-	{
-		if(elem->obstacleType == CObstacleInstance::USUAL)
-		{
-			std::string animationName = elem->getInfo().animation;
-
-			auto cached = animationsCache.find(animationName);
-
-			if(cached == animationsCache.end())
-			{
-				auto animation = std::make_shared<CAnimation>(animationName);
-				animationsCache[animationName] = animation;
-				obstacleAnimations[elem->uniqueID] = animation;
-				animation->preload();
-			}
-			else
-			{
-				obstacleAnimations[elem->uniqueID] = cached->second;
-			}
-		}
-		else if (elem->obstacleType == CObstacleInstance::ABSOLUTE_OBSTACLE)
-		{
-			std::string animationName = elem->getInfo().animation;
-
-			auto cached = animationsCache.find(animationName);
-
-			if(cached == animationsCache.end())
-			{
-				auto animation = std::make_shared<CAnimation>();
-				animation->setCustom(animationName, 0, 0);
-				animationsCache[animationName] = animation;
-				obstacleAnimations[elem->uniqueID] = animation;
-				animation->preload();
-			}
-			else
-			{
-				obstacleAnimations[elem->uniqueID] = cached->second;
-			}
-		}
-	}
-
-	for(auto hex : bfield)
-		addChild(hex.get());
-
-	if(tacticsMode)
-		bTacticNextStack();
-
-	CCS->musich->stopMusic();
-	battleIntroSoundChannel = CCS->soundh->playSoundFromSet(CCS->soundh->battleIntroSounds);
-	auto onIntroPlayed = [&]()
-	{
-		if(LOCPLINT->battleInt)
-		{
-			CCS->musich->playMusicFromSet("battle", true, true);
-			battleActionsStarted = true;
-			blockUI(settings["session"]["spectate"].Bool());
-			battleIntroSoundChannel = -1;
-		}
-	};
-
-	CCS->soundh->setCallback(battleIntroSoundChannel, onIntroPlayed);
-
-	currentAction = PossiblePlayerBattleAction::INVALID;
-	selectedAction = PossiblePlayerBattleAction::INVALID;
-	addUsedEvents(RCLICK | MOVE | KEYBOARD);
-	queue->update();
-	blockUI(true);
-}
-
-CBattleInterface::~CBattleInterface()
-{
-	CPlayerInterface::battleInt = nullptr;
-	givenCommand.cond.notify_all(); //that two lines should make any activeStack waiting thread to finish
-
-	if (active) //dirty fix for #485
-	{
-		deactivate();
-	}
-	SDL_FreeSurface(background);
-	SDL_FreeSurface(menu);
-	SDL_FreeSurface(amountNormal);
-	SDL_FreeSurface(amountNegative);
-	SDL_FreeSurface(amountPositive);
-	SDL_FreeSurface(amountEffNeutral);
-	SDL_FreeSurface(cellBorders);
-	SDL_FreeSurface(backgroundWithHexes);
-
-
-	SDL_FreeSurface(cellBorder);
-	SDL_FreeSurface(cellShade);
-
-	delete siegeH;
-
-	//TODO: play AI tracks if battle was during AI turn
-	//if (!curInt->makingTurn)
-	//CCS->musich->playMusicFromSet(CCS->musich->aiMusics, -1);
-
-	if (adventureInt && adventureInt->selection)
-	{
-		const auto & terrain = *(LOCPLINT->cb->getTile(adventureInt->selection->visitablePos())->terType);
-		CCS->musich->playMusicFromSet("terrain", terrain.name, true, false);
-	}
-	animsAreDisplayed.setn(false);
-}
-
-void CBattleInterface::setPrintCellBorders(bool set)
-{
-	Settings cellBorders = settings.write["battle"]["cellBorders"];
-	cellBorders->Bool() = set;
-
-	redrawBackgroundWithHexes(activeStack);
-	GH.totalRedraw();
-}
-
-void CBattleInterface::setPrintStackRange(bool set)
-{
-	Settings stackRange = settings.write["battle"]["stackRange"];
-	stackRange->Bool() = set;
-
-	redrawBackgroundWithHexes(activeStack);
-	GH.totalRedraw();
-}
-
-void CBattleInterface::setPrintMouseShadow(bool set)
-{
-	Settings shadow = settings.write["battle"]["mouseShadow"];
-	shadow->Bool() = set;
-}
-
-void CBattleInterface::activate()
-{
-	if (curInt->isAutoFightOn)
-	{
-		bAutofight->activate();
-		return;
-	}
-
-	CIntObject::activate();
-	bOptions->activate();
-	bSurrender->activate();
-	bFlee->activate();
-	bAutofight->activate();
-	bSpell->activate();
-	bWait->activate();
-	bDefence->activate();
-
-	if (attackingHero)
-		attackingHero->activate();
-	if (defendingHero)
-		defendingHero->activate();
-
-	for (auto hex : bfield)
-		hex->activate();
-
-	if (settings["battle"]["showQueue"].Bool())
-		queue->activate();
-
-	if (tacticsMode)
-	{
-		btactNext->activate();
-		btactEnd->activate();
-	}
-	else
-	{
-		bConsoleUp->activate();
-		bConsoleDown->activate();
-	}
-
-	LOCPLINT->cingconsole->activate();
-}
-
-void CBattleInterface::deactivate()
-{
-	CIntObject::deactivate();
-
-	bOptions->deactivate();
-	bSurrender->deactivate();
-	bFlee->deactivate();
-	bAutofight->deactivate();
-	bSpell->deactivate();
-	bWait->deactivate();
-	bDefence->deactivate();
-
-	for (auto hex : bfield)
-		hex->deactivate();
-
-	if (attackingHero)
-		attackingHero->deactivate();
-	if (defendingHero)
-		defendingHero->deactivate();
-	if (settings["battle"]["showQueue"].Bool())
-		queue->deactivate();
-
-	if (tacticsMode)
-	{
-		btactNext->deactivate();
-		btactEnd->deactivate();
-	}
-	else
-	{
-		bConsoleUp->deactivate();
-		bConsoleDown->deactivate();
-	}
-
-	LOCPLINT->cingconsole->deactivate();
-}
-
-void CBattleInterface::keyPressed(const SDL_KeyboardEvent & key)
-{
-	if(key.keysym.sym == SDLK_q && key.state == SDL_PRESSED)
-	{
-		if(settings["battle"]["showQueue"].Bool()) //hide queue
-			hideQueue();
-		else
-			showQueue();
-
-	}
-	else if(key.keysym.sym == SDLK_f && key.state == SDL_PRESSED)
-	{
-		enterCreatureCastingMode();
-	}
-	else if(key.keysym.sym == SDLK_ESCAPE)
-	{
-		if(!battleActionsStarted)
-			CCS->soundh->stopSound(battleIntroSoundChannel);
-		else
-			endCastingSpell();
-	}
-}
-void CBattleInterface::mouseMoved(const SDL_MouseMotionEvent &sEvent)
-{
-	auto hexItr = std::find_if(bfield.begin(), bfield.end(), [](std::shared_ptr<CClickableHex> hex)
-	{
-		return hex->hovered && hex->strictHovered;
-	});
-
-	handleHex(hexItr == bfield.end() ? -1 : (*hexItr)->myNumber, MOVE);
-}
-
-void CBattleInterface::setBattleCursor(const int myNumber)
-{
-	const CClickableHex & hoveredHex = *bfield[myNumber];
-	CCursorHandler *cursor = CCS->curh;
-
-	const double subdividingAngle = 2.0*M_PI/6.0; // Divide a hex into six sectors.
-	const double hexMidX = hoveredHex.pos.x + hoveredHex.pos.w/2.0;
-	const double hexMidY = hoveredHex.pos.y + hoveredHex.pos.h/2.0;
-	const double cursorHexAngle = M_PI - atan2(hexMidY - cursor->ypos, cursor->xpos - hexMidX) + subdividingAngle/2; //TODO: refactor this nightmare
-	const double sector = fmod(cursorHexAngle/subdividingAngle, 6.0);
-	const int zigzagCorrection = !((myNumber/GameConstants::BFIELD_WIDTH)%2); // Off-by-one correction needed to deal with the odd battlefield rows.
-
-	std::vector<int> sectorCursor; // From left to bottom left.
-	sectorCursor.push_back(8);
-	sectorCursor.push_back(9);
-	sectorCursor.push_back(10);
-	sectorCursor.push_back(11);
-	sectorCursor.push_back(12);
-	sectorCursor.push_back(7);
-
-	const bool doubleWide = activeStack->doubleWide();
-	bool aboveAttackable = true, belowAttackable = true;
-
-	// Exclude directions which cannot be attacked from.
-	// Check to the left.
-	if (myNumber%GameConstants::BFIELD_WIDTH <= 1 || !vstd::contains(occupyableHexes, myNumber - 1))
-	{
-		sectorCursor[0] = -1;
-	}
-	// Check top left, top right as well as above for 2-hex creatures.
-	if (myNumber/GameConstants::BFIELD_WIDTH == 0)
-	{
-			sectorCursor[1] = -1;
-			sectorCursor[2] = -1;
-			aboveAttackable = false;
-	}
-	else
-	{
-		if (doubleWide)
-		{
-			bool attackRow[4] = {true, true, true, true};
-
-			if (myNumber%GameConstants::BFIELD_WIDTH <= 1 || !vstd::contains(occupyableHexes, myNumber - GameConstants::BFIELD_WIDTH - 2 + zigzagCorrection))
-				attackRow[0] = false;
-			if (!vstd::contains(occupyableHexes, myNumber - GameConstants::BFIELD_WIDTH - 1 + zigzagCorrection))
-				attackRow[1] = false;
-			if (!vstd::contains(occupyableHexes, myNumber - GameConstants::BFIELD_WIDTH + zigzagCorrection))
-				attackRow[2] = false;
-			if (myNumber%GameConstants::BFIELD_WIDTH >= GameConstants::BFIELD_WIDTH - 2 || !vstd::contains(occupyableHexes, myNumber - GameConstants::BFIELD_WIDTH + 1 + zigzagCorrection))
-				attackRow[3] = false;
-
-			if (!(attackRow[0] && attackRow[1]))
-				sectorCursor[1] = -1;
-			if (!(attackRow[1] && attackRow[2]))
-				aboveAttackable = false;
-			if (!(attackRow[2] && attackRow[3]))
-				sectorCursor[2] = -1;
-		}
-		else
-		{
-			if (!vstd::contains(occupyableHexes, myNumber - GameConstants::BFIELD_WIDTH - 1 + zigzagCorrection))
-				sectorCursor[1] = -1;
-			if (!vstd::contains(occupyableHexes, myNumber - GameConstants::BFIELD_WIDTH + zigzagCorrection))
-				sectorCursor[2] = -1;
-		}
-	}
-	// Check to the right.
-	if (myNumber%GameConstants::BFIELD_WIDTH >= GameConstants::BFIELD_WIDTH - 2 || !vstd::contains(occupyableHexes, myNumber + 1))
-	{
-		sectorCursor[3] = -1;
-	}
-	// Check bottom right, bottom left as well as below for 2-hex creatures.
-	if (myNumber/GameConstants::BFIELD_WIDTH == GameConstants::BFIELD_HEIGHT - 1)
-	{
-		sectorCursor[4] = -1;
-		sectorCursor[5] = -1;
-		belowAttackable = false;
-	}
-	else
-	{
-		if (doubleWide)
-		{
-			bool attackRow[4] = {true, true, true, true};
-
-			if (myNumber%GameConstants::BFIELD_WIDTH <= 1 || !vstd::contains(occupyableHexes, myNumber + GameConstants::BFIELD_WIDTH - 2 + zigzagCorrection))
-				attackRow[0] = false;
-			if (!vstd::contains(occupyableHexes, myNumber + GameConstants::BFIELD_WIDTH - 1 + zigzagCorrection))
-				attackRow[1] = false;
-			if (!vstd::contains(occupyableHexes, myNumber + GameConstants::BFIELD_WIDTH + zigzagCorrection))
-				attackRow[2] = false;
-			if (myNumber%GameConstants::BFIELD_WIDTH >= GameConstants::BFIELD_WIDTH - 2 || !vstd::contains(occupyableHexes, myNumber + GameConstants::BFIELD_WIDTH + 1 + zigzagCorrection))
-				attackRow[3] = false;
-
-			if (!(attackRow[0] && attackRow[1]))
-				sectorCursor[5] = -1;
-			if (!(attackRow[1] && attackRow[2]))
-				belowAttackable = false;
-			if (!(attackRow[2] && attackRow[3]))
-				sectorCursor[4] = -1;
-		}
-		else
-		{
-			if (!vstd::contains(occupyableHexes, myNumber + GameConstants::BFIELD_WIDTH + zigzagCorrection))
-				sectorCursor[4] = -1;
-			if (!vstd::contains(occupyableHexes, myNumber + GameConstants::BFIELD_WIDTH - 1 + zigzagCorrection))
-				sectorCursor[5] = -1;
-		}
-	}
-
-	// Determine index from sector.
-	int cursorIndex;
-	if (doubleWide)
-	{
-		sectorCursor.insert(sectorCursor.begin() + 5, belowAttackable ? 13 : -1);
-		sectorCursor.insert(sectorCursor.begin() + 2, aboveAttackable ? 14 : -1);
-
-		if (sector < 1.5)
-			cursorIndex = static_cast<int>(sector);
-		else if (sector >= 1.5 && sector < 2.5)
-			cursorIndex = 2;
-		else if (sector >= 2.5 && sector < 4.5)
-			cursorIndex = (int) sector + 1;
-		else if (sector >= 4.5 && sector < 5.5)
-			cursorIndex = 6;
-		else
-			cursorIndex = (int) sector + 2;
-	}
-	else
-	{
-		cursorIndex = static_cast<int>(sector);
-	}
-
-	// Generally should NEVER happen, but to avoid the possibility of having endless loop below... [#1016]
-	if (!vstd::contains_if (sectorCursor, [](int sc) { return sc != -1; }))
-	{
-		logGlobal->error("Error: for hex %d cannot find a hex to attack from!", myNumber);
-		attackingHex = -1;
-		return;
-	}
-
-	// Find the closest direction attackable, starting with the right one.
-	// FIXME: Is this really how the original H3 client does it?
-	int i = 0;
-	while (sectorCursor[(cursorIndex + i)%sectorCursor.size()] == -1) //Why hast thou forsaken me?
-		i = i <= 0 ? 1 - i : -i; // 0, 1, -1, 2, -2, 3, -3 etc..
-	int index = (cursorIndex + i)%sectorCursor.size(); //hopefully we get elements from sectorCursor
-	cursor->changeGraphic(ECursor::COMBAT, sectorCursor[index]);
-	switch (index)
-	{
-		case 0:
-			attackingHex = myNumber - 1; //left
-			break;
-		case 1:
-			attackingHex = myNumber - GameConstants::BFIELD_WIDTH - 1 + zigzagCorrection; //top left
-			break;
-		case 2:
-			attackingHex = myNumber - GameConstants::BFIELD_WIDTH + zigzagCorrection; //top right
-			break;
-		case 3:
-			attackingHex = myNumber + 1; //right
-			break;
-		case 4:
-			attackingHex = myNumber + GameConstants::BFIELD_WIDTH + zigzagCorrection; //bottom right
-			break;
-		case 5:
-			attackingHex = myNumber + GameConstants::BFIELD_WIDTH - 1 + zigzagCorrection; //bottom left
-			break;
-	}
-	BattleHex hex(attackingHex);
-	if (!hex.isValid())
-		attackingHex = -1;
-}
-
-void CBattleInterface::clickRight(tribool down, bool previousState)
-{
-	if (!down)
-	{
-		endCastingSpell();
-	}
-}
-
-void CBattleInterface::bOptionsf()
-{
-	if (spellDestSelectMode) //we are casting a spell
-		return;
-
-	CCS->curh->changeGraphic(ECursor::ADVENTURE,0);
-
-	Rect tempRect = genRect(431, 481, 160, 84);
-	tempRect += pos.topLeft();
-	GH.pushIntT<CBattleOptionsWindow>(tempRect, this);
-}
-
-void CBattleInterface::bSurrenderf()
-{
-	if(spellDestSelectMode) //we are casting a spell
-		return;
-
-	int cost = curInt->cb->battleGetSurrenderCost();
-	if(cost >= 0)
-	{
-		std::string enemyHeroName = curInt->cb->battleGetEnemyHero().name;
-		if(enemyHeroName.empty())
-		{
-			logGlobal->warn("Surrender performed without enemy hero, should not happen!");
-			enemyHeroName = "#ENEMY#";
-		}
-
-		std::string surrenderMessage = boost::str(boost::format(CGI->generaltexth->allTexts[32]) % enemyHeroName % cost); //%s states: "I will accept your surrender and grant you and your troops safe passage for the price of %d gold."
-		curInt->showYesNoDialog(surrenderMessage, [this](){ reallySurrender(); }, nullptr);
-	}
-}
-
-void CBattleInterface::bFleef()
-{
-	if (spellDestSelectMode) //we are casting a spell
-		return;
-
-	if ( curInt->cb->battleCanFlee() )
-	{
-		CFunctionList<void()> ony = std::bind(&CBattleInterface::reallyFlee,this);
-		curInt->showYesNoDialog(CGI->generaltexth->allTexts[28], ony, nullptr); //Are you sure you want to retreat?
-	}
-	else
-	{
-		std::vector<std::shared_ptr<CComponent>> comps;
-		std::string heroName;
-		//calculating fleeing hero's name
-		if (attackingHeroInstance)
-			if (attackingHeroInstance->tempOwner == curInt->cb->getMyColor())
-				heroName = attackingHeroInstance->name;
-		if (defendingHeroInstance)
-			if (defendingHeroInstance->tempOwner == curInt->cb->getMyColor())
-				heroName = defendingHeroInstance->name;
-		//calculating text
-		auto txt = boost::format(CGI->generaltexth->allTexts[340]) % heroName; //The Shackles of War are present.  %s can not retreat!
-
-		//printing message
-		curInt->showInfoDialog(boost::to_string(txt), comps);
-	}
-}
-
-void CBattleInterface::reallyFlee()
-{
-	giveCommand(EActionType::RETREAT);
-	CCS->curh->changeGraphic(ECursor::ADVENTURE, 0);
-}
-
-void CBattleInterface::reallySurrender()
-{
-	if (curInt->cb->getResourceAmount(Res::GOLD) < curInt->cb->battleGetSurrenderCost())
-	{
-		curInt->showInfoDialog(CGI->generaltexth->allTexts[29]); //You don't have enough gold!
-	}
-	else
-	{
-		giveCommand(EActionType::SURRENDER);
-		CCS->curh->changeGraphic(ECursor::ADVENTURE, 0);
-	}
-}
-
-void CBattleInterface::bAutofightf()
-{
-	if(spellDestSelectMode) //we are casting a spell
-		return;
-
-	//Stop auto-fight mode
-	if(curInt->isAutoFightOn)
-	{
-		assert(curInt->autofightingAI);
-		curInt->isAutoFightOn = false;
-		logGlobal->trace("Stopping the autofight...");
-	}
-	else if(!curInt->autofightingAI)
-	{
-		curInt->isAutoFightOn = true;
-		blockUI(true);
-
-		auto ai = CDynLibHandler::getNewBattleAI(settings["server"]["friendlyAI"].String());
-		ai->init(curInt->env, curInt->cb);
-		ai->battleStart(army1, army2, int3(0,0,0), attackingHeroInstance, defendingHeroInstance, curInt->cb->battleGetMySide());
-		curInt->autofightingAI = ai;
-		curInt->cb->registerBattleInterface(ai);
-
-		requestAutofightingAIToTakeAction();
-	}
-}
-
-void CBattleInterface::bSpellf()
-{
-	if (spellDestSelectMode) //we are casting a spell
-		return;
-
-	if (!myTurn)
-		return;
-
-	auto myHero = currentHero();
-	if(!myHero)
-		return;
-
-	CCS->curh->changeGraphic(ECursor::ADVENTURE,0);
-
-	ESpellCastProblem::ESpellCastProblem spellCastProblem = curInt->cb->battleCanCastSpell(myHero, spells::Mode::HERO);
-
-	if(spellCastProblem == ESpellCastProblem::OK)
-	{
-		GH.pushIntT<CSpellWindow>(myHero, curInt.get());
-	}
-	else if (spellCastProblem == ESpellCastProblem::MAGIC_IS_BLOCKED)
-	{
-		//TODO: move to spell mechanics, add more information to spell cast problem
-		//Handle Orb of Inhibition-like effects -> we want to display dialog with info, why casting is impossible
-		auto blockingBonus = currentHero()->getBonusLocalFirst(Selector::type()(Bonus::BLOCK_ALL_MAGIC));
-		if (!blockingBonus)
-			return;
-
-		if (blockingBonus->source == Bonus::ARTIFACT)
-		{
-			const auto artID = ArtifactID(blockingBonus->sid);
-			//If we have artifact, put name of our hero. Otherwise assume it's the enemy.
-			//TODO check who *really* is source of bonus
-			std::string heroName = myHero->hasArt(artID) ? myHero->name : enemyHero().name;
-
-			//%s wields the %s, an ancient artifact which creates a p dead to all magic.
-			LOCPLINT->showInfoDialog(boost::str(boost::format(CGI->generaltexth->allTexts[683])
-										% heroName % CGI->artifacts()->getByIndex(artID)->getName()));
-		}
-	}
-}
-
-void CBattleInterface::bWaitf()
-{
-	if (spellDestSelectMode) //we are casting a spell
-		return;
-
-	if (activeStack != nullptr)
-		giveCommand(EActionType::WAIT);
-}
-
-void CBattleInterface::bDefencef()
-{
-	if (spellDestSelectMode) //we are casting a spell
-		return;
-
-	if (activeStack != nullptr)
-		giveCommand(EActionType::DEFEND);
-}
-
-void CBattleInterface::bConsoleUpf()
-{
-	if (spellDestSelectMode) //we are casting a spell
-		return;
-
-	console->scrollUp();
-}
-
-void CBattleInterface::bConsoleDownf()
-{
-	if (spellDestSelectMode) //we are casting a spell
-		return;
-
-	console->scrollDown();
-}
-
-void CBattleInterface::unitAdded(const CStack * stack)
-{
-	creDir[stack->ID] = stack->side == BattleSide::ATTACKER; // must be set before getting stack position
-
-	Point coords = CClickableHex::getXYUnitAnim(stack->getPosition(), stack, this);
-
-	if(stack->initialPosition < 0) //turret
-	{
-		const CCreature *turretCreature = CGI->creh->objects[siegeH->town->town->clientInfo.siegeShooter];
-
-		creAnims[stack->ID] = AnimationControls::getAnimation(turretCreature);
-
-		// Turret positions are read out of the config/wall_pos.txt
-		int posID = 0;
-		switch (stack->initialPosition)
-		{
-		case -2: // keep creature
-			posID = 18;
-			break;
-		case -3: // bottom creature
-			posID = 19;
-			break;
-		case -4: // upper creature
-			posID = 20;
-			break;
-		}
-
-		if (posID != 0)
-		{
-			coords.x = siegeH->town->town->clientInfo.siegePositions[posID].x + this->pos.x;
-			coords.y = siegeH->town->town->clientInfo.siegePositions[posID].y + this->pos.y;
-		}
-		creAnims[stack->ID]->pos.h = 225;
-	}
-	else
-	{
-		creAnims[stack->ID] = AnimationControls::getAnimation(stack->getCreature());
-		creAnims[stack->ID]->onAnimationReset += std::bind(&onAnimationFinished, stack, creAnims[stack->ID]);
-		creAnims[stack->ID]->pos.h = creAnims[stack->ID]->getHeight();
-	}
-	creAnims[stack->ID]->pos.x = coords.x;
-	creAnims[stack->ID]->pos.y = coords.y;
-	creAnims[stack->ID]->pos.w = creAnims[stack->ID]->getWidth();
-	creAnims[stack->ID]->setType(CCreatureAnim::HOLDING);
-
-	//loading projectiles for units
-	if(stack->isShooter())
-	{
-		initStackProjectile(stack);
-	}
-}
-
-void CBattleInterface::initStackProjectile(const CStack * stack)
-{
-	const CCreature * creature;//creature whose shots should be loaded
-	if(stack->getCreature()->idNumber == CreatureID::ARROW_TOWERS)
-		creature = CGI->creh->objects[siegeH->town->town->clientInfo.siegeShooter];
-	else
-		creature = stack->getCreature();
-
-	if (creature->animation.projectileRay.empty())
-	{
-		std::shared_ptr<CAnimation> projectile = std::make_shared<CAnimation>(creature->animation.projectileImageName);
-		projectile->preload();
-
-		if(projectile->size(1) != 0)
-			logAnim->error("Expected empty group 1 in stack projectile");
-		else
-			projectile->createFlippedGroup(0, 1);
-
-		idToProjectile[stack->getCreature()->idNumber] = projectile;
-	}
-	else
-	{
-		idToRay[stack->getCreature()->idNumber] = creature->animation.projectileRay;
-	}
-}
-
-void CBattleInterface::stackRemoved(uint32_t stackID)
-{
-	if (activeStack != nullptr)
-	{
-		if (activeStack->ID == stackID)
-		{
-			BattleAction *action = new BattleAction();
-			action->side = defendingHeroInstance ? (curInt->playerID == defendingHeroInstance->tempOwner) : false;
-			action->actionType = EActionType::CANCEL;
-			action->stackNumber = activeStack->ID;
-			givenCommand.setn(action);
-			setActiveStack(nullptr);
-		}
-	}
-
-	//todo: ensure that ghost stack animation has fadeout effect
-
-	redrawBackgroundWithHexes(activeStack);
-	queue->update();
-}
-
-void CBattleInterface::stackActivated(const CStack *stack) //TODO: check it all before game state is changed due to abilities
-{
-	stackToActivate = stack;
-	waitForAnims();
-	if (stackToActivate) //during waiting stack may have gotten activated through show
-		activateStack();
-}
-
-void CBattleInterface::stackMoved(const CStack *stack, std::vector<BattleHex> destHex, int distance)
-{
-	addNewAnim(new CMovementAnimation(this, stack, destHex, distance));
-	waitForAnims();
-}
-
-void CBattleInterface::stacksAreAttacked(std::vector<StackAttackedInfo> attackedInfos)
-{
-	for(auto & attackedInfo : attackedInfos)
-	{
-		//if (!attackedInfo.cloneKilled) //FIXME: play dead animation for cloned creature before it vanishes
-			addNewAnim(new CDefenceAnimation(attackedInfo, this));
-
-		if(attackedInfo.rebirth)
-		{
-			displayEffect(50, attackedInfo.defender->getPosition()); //TODO: play reverse death animation
-			CCS->soundh->playSound(soundBase::RESURECT);
-		}
-	}
-	waitForAnims();
-
-	std::array<int, 2> killedBySide = {0, 0};
-
-	int targets = 0;
-	for(const StackAttackedInfo & attackedInfo : attackedInfos)
-	{
-		++targets;
-
-		ui8 side = attackedInfo.defender->side;
-		killedBySide.at(side) += attackedInfo.amountKilled;
-	}
-
-	for(ui8 side = 0; side < 2; side++)
-	{
-		if(killedBySide.at(side) > killedBySide.at(1-side))
-			setHeroAnimation(side, 2);
-		else if(killedBySide.at(side) < killedBySide.at(1-side))
-			setHeroAnimation(side, 3);
-	}
-
-	for (auto & attackedInfo : attackedInfos)
-	{
-		if (attackedInfo.rebirth)
-			creAnims[attackedInfo.defender->ID]->setType(CCreatureAnim::HOLDING);
-		if (attackedInfo.cloneKilled)
-			stackRemoved(attackedInfo.defender->ID);
-	}
-}
-
-void CBattleInterface::stackAttacking( const CStack *attacker, BattleHex dest, const CStack *attacked, bool shooting )
-{
-	if (shooting)
-	{
-		addNewAnim(new CShootingAnimation(this, attacker, dest, attacked));
-	}
-	else
-	{
-		addNewAnim(new CMeleeAttackAnimation(this, attacker, dest, attacked));
-	}
-	//waitForAnims();
-}
-
-void CBattleInterface::newRoundFirst( int round )
-{
-	waitForAnims();
-}
-
-void CBattleInterface::newRound(int number)
-{
-	console->addText(CGI->generaltexth->allTexts[412]);
-}
-
-void CBattleInterface::giveCommand(EActionType action, BattleHex tile, si32 additional)
-{
-	const CStack * actor = nullptr;
-	if(action != EActionType::HERO_SPELL && action != EActionType::RETREAT && action != EActionType::SURRENDER)
-	{
-		actor = activeStack;
-	}
-
-	auto side = curInt->cb->playerToSide(curInt->playerID);
-	if(!side)
-	{
-		logGlobal->error("Player %s is not in battle", curInt->playerID.getStr());
-		return;
-	}
-
-	auto ba = new BattleAction(); //is deleted in CPlayerInterface::activeStack()
-	ba->side = side.get();
-	ba->actionType = action;
-	ba->aimToHex(tile);
-	ba->actionSubtype = additional;
-
-	sendCommand(ba, actor);
-}
-
-void CBattleInterface::sendCommand(BattleAction *& command, const CStack * actor)
-{
-	command->stackNumber = actor ? actor->unitId() : ((command->side == BattleSide::ATTACKER) ? -1 : -2);
-
-	if(!tacticsMode)
-	{
-		logGlobal->trace("Setting command for %s", (actor ? actor->nodeName() : "hero"));
-		myTurn = false;
-		setActiveStack(nullptr);
-		givenCommand.setn(command);
-	}
-	else
-	{
-		curInt->cb->battleMakeTacticAction(command);
-		vstd::clear_pointer(command);
-		setActiveStack(nullptr);
-		//next stack will be activated when action ends
-	}
-}
-
-bool CBattleInterface::isTileAttackable(const BattleHex & number) const
-{
-	for (auto & elem : occupyableHexes)
-	{
-		if (BattleHex::mutualPosition(elem, number) != -1 || elem == number)
-			return true;
-	}
-	return false;
-}
-
-bool CBattleInterface::isCatapultAttackable(BattleHex hex) const
-{
-	if (!siegeH || tacticsMode) return false;
-
-	auto wallPart = curInt->cb->battleHexToWallPart(hex);
-	if (!curInt->cb->isWallPartPotentiallyAttackable(wallPart)) return false;
-
-	auto state = curInt->cb->battleGetWallState(static_cast<int>(wallPart));
-	return state != EWallState::DESTROYED && state != EWallState::NONE;
-}
-
-const CGHeroInstance * CBattleInterface::getActiveHero()
-{
-	const CStack *attacker = activeStack;
-	if(!attacker)
-	{
-		return nullptr;
-	}
-
-	if(attacker->side == BattleSide::ATTACKER)
-	{
-		return attackingHeroInstance;
-	}
-
-	return defendingHeroInstance;
-}
-
-void CBattleInterface::hexLclicked(int whichOne)
-{
-	handleHex(whichOne, LCLICK);
-}
-
-void CBattleInterface::stackIsCatapulting(const CatapultAttack & ca)
-{
-	if (ca.attacker != -1)
-	{
-		const CStack *stack = curInt->cb->battleGetStackByID(ca.attacker);
-		for (auto attackInfo : ca.attackedParts)
-		{
-			addNewAnim(new CShootingAnimation(this, stack, attackInfo.destinationTile, nullptr, true, attackInfo.damageDealt));
-		}
-	}
-	else
-	{
-		//no attacker stack, assume spell-related (earthquake) - only hit animation
-		for (auto attackInfo : ca.attackedParts)
-		{
-			Point destPos = CClickableHex::getXYUnitAnim(attackInfo.destinationTile, nullptr, this) + Point(99, 120);
-
-			addNewAnim(new CEffectAnimation(this, "SGEXPL.DEF", destPos.x, destPos.y));
-		}
-	}
-
-	waitForAnims();
-
-	for (auto attackInfo : ca.attackedParts)
-	{
-		int wallId = attackInfo.attackedPart + 2;
-		//gate state changing handled separately
-		if (wallId == SiegeHelper::GATE)
-			continue;
-
-		SDL_FreeSurface(siegeH->walls[wallId]);
-		siegeH->walls[wallId] = BitmapHandler::loadBitmap(
-			siegeH->getSiegeName(wallId, curInt->cb->battleGetWallState(attackInfo.attackedPart)));
-	}
-}
-
-void CBattleInterface::battleFinished(const BattleResult& br)
-{
-	bresult = &br;
-	{
-		auto unlockPim = vstd::makeUnlockGuard(*CPlayerInterface::pim);
-		animsAreDisplayed.waitUntil(false);
-	}
-	setActiveStack(nullptr);
-	displayBattleFinished();
-}
-
-void CBattleInterface::displayBattleFinished()
-{
-	CCS->curh->changeGraphic(ECursor::ADVENTURE,0);
-	if(settings["session"]["spectate"].Bool() && settings["session"]["spectate-skip-battle-result"].Bool())
-	{
-		close();
-		return;
-	}
-
-	GH.pushInt(std::make_shared<CBattleResultWindow>(*bresult, *(this->curInt)));
-	curInt->waitWhileDialog(); // Avoid freeze when AI end turn after battle. Check bug #1897
-	CPlayerInterface::battleInt = nullptr;
-}
-
-void CBattleInterface::spellCast(const BattleSpellCast * sc)
-{
-	const SpellID spellID = sc->spellID;
-	const CSpell * spell = spellID.toSpell();
-
-	if(!spell)
-		return;
-
-	const std::string & castSoundPath = spell->getCastSound();
-
-	if (!castSoundPath.empty())
-		CCS->soundh->playSound(castSoundPath);
-
-	const auto casterStackID = sc->casterStack;
-	const CStack * casterStack = nullptr;
-	if(casterStackID >= 0)
-	{
-		casterStack = curInt->cb->battleGetStackByID(casterStackID);
-	}
-
-	Point srccoord = (sc->side ? Point(770, 60) : Point(30, 60)) + pos;	//hero position by default
-	{
-		if(casterStack != nullptr)
-		{
-			srccoord = CClickableHex::getXYUnitAnim(casterStack->getPosition(), casterStack, this);
-			srccoord.x += 250;
-			srccoord.y += 240;
-		}
-	}
-
-	if(casterStack != nullptr && sc->activeCast)
-	{
-		//todo: custom cast animation for hero
-		displaySpellCast(spellID, casterStack->getPosition());
-
-		addNewAnim(new CCastAnimation(this, casterStack, sc->tile, curInt->cb->battleGetStackByPos(sc->tile)));
-	}
-
-	waitForAnims(); //wait for cast animation
-
-	//playing projectile animation
-	if (sc->tile.isValid())
-	{
-		Point destcoord = CClickableHex::getXYUnitAnim(sc->tile, curInt->cb->battleGetStackByPos(sc->tile), this); //position attacked by projectile
-		destcoord.x += 250; destcoord.y += 240;
-
-		//animation angle
-		double angle = atan2(static_cast<double>(destcoord.x - srccoord.x), static_cast<double>(destcoord.y - srccoord.y));
-		bool Vflip = (angle < 0);
-		if (Vflip)
-			angle = -angle;
-
-		std::string animToDisplay = spell->animationInfo.selectProjectile(angle);
-
-		if(!animToDisplay.empty())
-		{
-			//TODO: calculate inside CEffectAnimation
-			std::shared_ptr<CAnimation> tmp = std::make_shared<CAnimation>(animToDisplay);
-			tmp->load(0, 0);
-			auto first = tmp->getImage(0, 0);
-
-			//displaying animation
-			double diffX = (destcoord.x - srccoord.x)*(destcoord.x - srccoord.x);
-			double diffY = (destcoord.y - srccoord.y)*(destcoord.y - srccoord.y);
-			double distance = sqrt(diffX + diffY);
-
-			int steps = static_cast<int>(distance / AnimationControls::getSpellEffectSpeed() + 1);
-			int dx = (destcoord.x - srccoord.x - first->width())/steps;
-			int dy = (destcoord.y - srccoord.y - first->height())/steps;
-
-			addNewAnim(new CEffectAnimation(this, animToDisplay, srccoord.x, srccoord.y, dx, dy, Vflip));
-		}
-	}
-
-	waitForAnims(); //wait for projectile animation
-
-	displaySpellHit(spellID, sc->tile);
-
-	//queuing affect animation
-	for(auto & elem : sc->affectedCres)
-	{
-		auto stack = curInt->cb->battleGetStackByID(elem, false);
-		if(stack)
-			displaySpellEffect(spellID, stack->getPosition());
-	}
-
-	//queuing additional animation
-	for(auto & elem : sc->customEffects)
-	{
-		auto stack = curInt->cb->battleGetStackByID(elem.stack, false);
-		if(stack)
-			displayEffect(elem.effect, stack->getPosition());
-	}
-
-	waitForAnims();
-	//mana absorption
-	if (sc->manaGained > 0)
-	{
-		Point leftHero = Point(15, 30) + pos;
-		Point rightHero = Point(755, 30) + pos;
-		addNewAnim(new CEffectAnimation(this, sc->side ? "SP07_A.DEF" : "SP07_B.DEF", leftHero.x, leftHero.y, 0, 0, false));
-		addNewAnim(new CEffectAnimation(this, sc->side ? "SP07_B.DEF" : "SP07_A.DEF", rightHero.x, rightHero.y, 0, 0, false));
-	}
-}
-
-void CBattleInterface::battleStacksEffectsSet(const SetStackEffect & sse)
-{
-	if(activeStack != nullptr)
-		redrawBackgroundWithHexes(activeStack);
-}
-
-void CBattleInterface::setHeroAnimation(ui8 side, int phase)
-{
-	if(side == BattleSide::ATTACKER)
-	{
-		if(attackingHero)
-			attackingHero->setPhase(phase);
-	}
-	else
-	{
-		if(defendingHero)
-			defendingHero->setPhase(phase);
-	}
-}
-
-void CBattleInterface::castThisSpell(SpellID spellID)
-{
-	spellToCast = std::make_shared<BattleAction>();
-	spellToCast->actionType = EActionType::HERO_SPELL;
-	spellToCast->actionSubtype = spellID; //spell number
-	spellToCast->stackNumber = (attackingHeroInstance->tempOwner == curInt->playerID) ? -1 : -2;
-	spellToCast->side = defendingHeroInstance ? (curInt->playerID == defendingHeroInstance->tempOwner) : false;
-	spellDestSelectMode = true;
-	creatureCasting = false;
-
-	//choosing possible targets
-	const CGHeroInstance *castingHero = (attackingHeroInstance->tempOwner == curInt->playerID) ? attackingHeroInstance : defendingHeroInstance;
-	assert(castingHero); // code below assumes non-null hero
-	sp = spellID.toSpell();
-	PossiblePlayerBattleAction spellSelMode = curInt->cb->getCasterAction(sp, castingHero, spells::Mode::HERO);
-
-	if (spellSelMode == PossiblePlayerBattleAction::NO_LOCATION) //user does not have to select location
-	{
-		spellToCast->aimToHex(BattleHex::INVALID);
-		curInt->cb->battleMakeAction(spellToCast.get());
-		endCastingSpell();
-	}
-	else
-	{
-		possibleActions.clear();
-		possibleActions.push_back (spellSelMode); //only this one action can be performed at the moment
-		GH.fakeMouseMove();//update cursor
-	}
-}
-
-void CBattleInterface::displayBattleLog(const std::vector<MetaString> & battleLog)
-{
-	for(const auto & line : battleLog)
-	{
-		std::string formatted = line.toString();
-		boost::algorithm::trim(formatted);
-		if(!console->addText(formatted))
-			logGlobal->warn("Too long battle log line");
-	}
-}
-
-void CBattleInterface::displayCustomEffects(const std::vector<CustomEffectInfo> & customEffects)
-{
-	for(const CustomEffectInfo & one : customEffects)
-	{
-		if(one.sound != 0)
-			CCS->soundh->playSound(soundBase::soundID(one.sound));
-		const CStack * s = curInt->cb->battleGetStackByID(one.stack, false);
-		if(s && one.effect != 0)
-			displayEffect(one.effect, s->getPosition());
-	}
-}
-
-void CBattleInterface::displayEffect(ui32 effect, BattleHex destTile)
-{
-	std::string customAnim = graphics->battleACToDef[effect][0];
-
-	addNewAnim(new CEffectAnimation(this, customAnim, destTile));
-}
-
-void CBattleInterface::displaySpellAnimationQueue(const CSpell::TAnimationQueue & q, BattleHex destinationTile)
-{
-	for(const CSpell::TAnimation & animation : q)
-	{
-		if(animation.pause > 0)
-			addNewAnim(new CDummyAnimation(this, animation.pause));
-		else
-			addNewAnim(new CEffectAnimation(this, animation.resourceName, destinationTile, false, animation.verticalPosition == VerticalPosition::BOTTOM));
-	}
-}
-
-void CBattleInterface::displaySpellCast(SpellID spellID, BattleHex destinationTile)
-{
-	const CSpell * spell = spellID.toSpell();
-
-	if(spell)
-		displaySpellAnimationQueue(spell->animationInfo.cast, destinationTile);
-}
-
-void CBattleInterface::displaySpellEffect(SpellID spellID, BattleHex destinationTile)
-{
-	const CSpell *spell = spellID.toSpell();
-
-	if(spell)
-		displaySpellAnimationQueue(spell->animationInfo.affect, destinationTile);
-}
-
-void CBattleInterface::displaySpellHit(SpellID spellID, BattleHex destinationTile)
-{
-	const CSpell * spell = spellID.toSpell();
-
-	if(spell)
-		displaySpellAnimationQueue(spell->animationInfo.hit, destinationTile);
-}
-
-void CBattleInterface::battleTriggerEffect(const BattleTriggerEffect & bte)
-{
-	const CStack * stack = curInt->cb->battleGetStackByID(bte.stackID);
-	if(!stack)
-	{
-		logGlobal->error("Invalid stack ID %d", bte.stackID);
-		return;
-	}
-	//don't show animation when no HP is regenerated
-	switch(bte.effect)
-	{
-		//TODO: move to bonus type handler
-		case Bonus::HP_REGENERATION:
-			displayEffect(74, stack->getPosition());
-			CCS->soundh->playSound(soundBase::REGENER);
-			break;
-		case Bonus::MANA_DRAIN:
-			displayEffect(77, stack->getPosition());
-			CCS->soundh->playSound(soundBase::MANADRAI);
-			break;
-		case Bonus::POISON:
-			displayEffect(67, stack->getPosition());
-			CCS->soundh->playSound(soundBase::POISON);
-			break;
-		case Bonus::FEAR:
-			displayEffect(15, stack->getPosition());
-			CCS->soundh->playSound(soundBase::FEAR);
-			break;
-		case Bonus::MORALE:
-		{
-			std::string hlp = CGI->generaltexth->allTexts[33];
-			boost::algorithm::replace_first(hlp,"%s",(stack->getName()));
-			displayEffect(20,stack->getPosition());
-			CCS->soundh->playSound(soundBase::GOODMRLE);
-			console->addText(hlp);
-			break;
-		}
-		default:
-			return;
-	}
-	//waitForAnims(); //fixme: freezes game :?
-}
-
-void CBattleInterface::setAnimSpeed(int set)
-{
-	Settings speed = settings.write["battle"]["animationSpeed"];
-	speed->Float() = float(set) / 100;
-}
-
-int CBattleInterface::getAnimSpeed() const
-{
-	if(settings["session"]["spectate"].Bool() && !settings["session"]["spectate-battle-speed"].isNull())
-		return static_cast<int>(vstd::round(settings["session"]["spectate-battle-speed"].Float() *100));
-
-	return static_cast<int>(vstd::round(settings["battle"]["animationSpeed"].Float() *100));
-}
-
-CPlayerInterface *CBattleInterface::getCurrentPlayerInterface() const
-{
-	return curInt.get();
-}
-
-bool CBattleInterface::shouldRotate(const CStack * stack, const BattleHex & oldPos, const BattleHex & nextHex)
-{
-	Point begPosition = CClickableHex::getXYUnitAnim(oldPos,stack, this);
-	Point endPosition = CClickableHex::getXYUnitAnim(nextHex, stack, this);
-
-	if((begPosition.x > endPosition.x) && creDir[stack->ID])
-		return true;
-	else if((begPosition.x < endPosition.x) && !creDir[stack->ID])
-		return true;
-
-	return false;
-}
-
-void CBattleInterface::setActiveStack(const CStack *stack)
-{
-	if (activeStack) // update UI
-		creAnims[activeStack->ID]->setBorderColor(AnimationControls::getNoBorder());
-
-	activeStack = stack;
-
-	if (activeStack) // update UI
-		creAnims[activeStack->ID]->setBorderColor(AnimationControls::getGoldBorder());
-
-	blockUI(activeStack == nullptr);
-}
-
-void CBattleInterface::setHoveredStack(const CStack *stack)
-{
-	if (mouseHoveredStack)
-		creAnims[mouseHoveredStack->ID]->setBorderColor(AnimationControls::getNoBorder());
-
-	// stack must be alive and not active (which uses gold border instead)
-	if (stack && stack->alive() && stack != activeStack)
-	{
-		mouseHoveredStack = stack;
-
-		if (mouseHoveredStack)
-		{
-			creAnims[mouseHoveredStack->ID]->setBorderColor(AnimationControls::getBlueBorder());
-			if (creAnims[mouseHoveredStack->ID]->framesInGroup(CCreatureAnim::MOUSEON) > 0)
-				creAnims[mouseHoveredStack->ID]->playOnce(CCreatureAnim::MOUSEON);
-		}
-	}
-	else
-		mouseHoveredStack = nullptr;
-}
-
-void CBattleInterface::activateStack()
-{
-	if(!battleActionsStarted)
-		return; //"show" function should re-call this function
-
-	myTurn = true;
-	if (!!attackerInt && defenderInt) //hotseat -> need to pick which interface "takes over" as active
-		curInt = attackerInt->playerID == stackToActivate->owner ? attackerInt : defenderInt;
-
-	setActiveStack(stackToActivate);
-	stackToActivate = nullptr;
-	const CStack * s = activeStack;
-	if(!s)
-		return;
-
-	queue->update();
-	redrawBackgroundWithHexes(activeStack);
-
-	//set casting flag to true if creature can use it to not check it every time
-	const auto spellcaster = s->getBonusLocalFirst(Selector::type()(Bonus::SPELLCASTER)),
-		randomSpellcaster = s->getBonusLocalFirst(Selector::type()(Bonus::RANDOM_SPELLCASTER));
-	if(s->canCast() && (spellcaster || randomSpellcaster))
-	{
-		stackCanCastSpell = true;
-		if(randomSpellcaster)
-			creatureSpellToCast = -1; //spell will be set later on cast
-		else
-			creatureSpellToCast = curInt->cb->battleGetRandomStackSpell(CRandomGenerator::getDefault(), s, CBattleInfoCallback::RANDOM_AIMED); //faerie dragon can cast only one spell until their next move
-		//TODO: what if creature can cast BOTH random genie spell and aimed spell?
-		//TODO: faerie dragon type spell should be selected by server
-	}
-	else
-	{
-		stackCanCastSpell = false;
-		creatureSpellToCast = -1;
-	}
-
-	possibleActions = getPossibleActionsForStack(s);
-
-	GH.fakeMouseMove();
-}
-
-void CBattleInterface::endCastingSpell()
-{
-	if(spellDestSelectMode)
-	{
-		spellToCast.reset();
-
-		sp = nullptr;
-		spellDestSelectMode = false;
-		CCS->curh->changeGraphic(ECursor::COMBAT, ECursor::COMBAT_POINTER);
-
-		if(activeStack)
-		{
-			possibleActions = getPossibleActionsForStack(activeStack); //restore actions after they were cleared
-			myTurn = true;
-		}
-	}
-	else
-	{
-		if(activeStack)
-		{
-			possibleActions = getPossibleActionsForStack(activeStack);
-			GH.fakeMouseMove();
-		}
-	}
-}
-
-void CBattleInterface::enterCreatureCastingMode()
-{
-	//silently check for possible errors
-	if (!myTurn)
-		return;
-
-	if (tacticsMode)
-		return;
-
-	//hero is casting a spell
-	if (spellDestSelectMode)
-		return;
-
-	if (!activeStack)
-		return;
-
-	if (!stackCanCastSpell)
-		return;
-
-	//random spellcaster
-	if (creatureSpellToCast == -1)
-		return;
-
-	if (vstd::contains(possibleActions, PossiblePlayerBattleAction::NO_LOCATION))
-	{
-		const spells::Caster * caster = activeStack;
-		const CSpell * spell = SpellID(creatureSpellToCast).toSpell();
-
-		spells::Target target;
-		target.emplace_back();
-
-		spells::BattleCast cast(curInt->cb.get(), caster, spells::Mode::CREATURE_ACTIVE, spell);
-
-		auto m = spell->battleMechanics(&cast);
-		spells::detail::ProblemImpl ignored;
-
-		const bool isCastingPossible = m->canBeCastAt(target, ignored);
-
-		if (isCastingPossible)
-		{
-			myTurn = false;
-			giveCommand(EActionType::MONSTER_SPELL, BattleHex::INVALID, creatureSpellToCast);
-			selectedStack = nullptr;
-
-			CCS->curh->changeGraphic(ECursor::COMBAT, ECursor::COMBAT_POINTER);
-		}
-	}
-	else
-	{
-		possibleActions = getPossibleActionsForStack(activeStack);
-
-		auto actionFilterPredicate = [](const PossiblePlayerBattleAction x)
-		{
-			return (x != PossiblePlayerBattleAction::ANY_LOCATION) && (x != PossiblePlayerBattleAction::NO_LOCATION) &&
-				(x != PossiblePlayerBattleAction::FREE_LOCATION) && (x != PossiblePlayerBattleAction::AIMED_SPELL_CREATURE) &&
-				(x != PossiblePlayerBattleAction::OBSTACLE);
-		};
-
-		vstd::erase_if(possibleActions, actionFilterPredicate);
-		GH.fakeMouseMove();
-	}
-}
-
-std::vector<PossiblePlayerBattleAction> CBattleInterface::getPossibleActionsForStack(const CStack *stack)
-{
-	BattleClientInterfaceData data; //hard to get rid of these things so for now they're required data to pass
-	data.creatureSpellToCast = creatureSpellToCast;
-	data.tacticsMode = tacticsMode;
-	auto allActions = curInt->cb->getClientActionsForStack(stack, data);
-
-	return std::vector<PossiblePlayerBattleAction>(allActions);
-}
-
-void CBattleInterface::reorderPossibleActionsPriority(const CStack * stack, MouseHoveredHexContext context)
-{
-	if(tacticsMode || possibleActions.empty()) return; //this function is not supposed to be called in tactics mode or before getPossibleActionsForStack
-
-	auto assignPriority = [&](PossiblePlayerBattleAction const & item) -> uint8_t //large lambda assigning priority which would have to be part of possibleActions without it
-	{
-		switch(item)
-		{
-		case PossiblePlayerBattleAction::AIMED_SPELL_CREATURE:
-		case PossiblePlayerBattleAction::ANY_LOCATION:
-		case PossiblePlayerBattleAction::NO_LOCATION:
-		case PossiblePlayerBattleAction::FREE_LOCATION:
-		case PossiblePlayerBattleAction::OBSTACLE:
-			if(!stack->hasBonusOfType(Bonus::NO_SPELLCAST_BY_DEFAULT) && context == MouseHoveredHexContext::OCCUPIED_HEX)
-				return 1;
-			else
-				return 100;//bottom priority
-			break;
-		case PossiblePlayerBattleAction::RANDOM_GENIE_SPELL:
-			return 2; break;
-		case PossiblePlayerBattleAction::RISE_DEMONS:
-			return 3; break;
-		case PossiblePlayerBattleAction::SHOOT:
-			return 4; break;
-		case PossiblePlayerBattleAction::ATTACK_AND_RETURN:
-			return 5; break;
-		case PossiblePlayerBattleAction::ATTACK:
-			return 6; break;
-		case PossiblePlayerBattleAction::WALK_AND_ATTACK:
-			return 7; break;
-		case PossiblePlayerBattleAction::MOVE_STACK:
-			return 8; break;
-		case PossiblePlayerBattleAction::CATAPULT:
-			return 9; break;
-		case PossiblePlayerBattleAction::HEAL:
-			return 10; break;
-		default:
-			return 200; break;
-		}
-	};
-
-	auto comparer = [&](PossiblePlayerBattleAction const & lhs, PossiblePlayerBattleAction const & rhs)
-	{
-		return assignPriority(lhs) > assignPriority(rhs);
-	};
-
-	std::make_heap(possibleActions.begin(), possibleActions.end(), comparer);
-}
-
-void CBattleInterface::endAction(const BattleAction* action)
-{
-	const CStack *stack = curInt->cb->battleGetStackByID(action->stackNumber);
-
-	if(action->actionType == EActionType::HERO_SPELL)
-		setHeroAnimation(action->side, 0);
-
-	//check if we should reverse stacks
-	//for some strange reason, it's not enough
-	TStacks stacks = curInt->cb->battleGetStacks(CBattleCallback::MINE_AND_ENEMY);
-
-	for (const CStack *s : stacks)
-	{
-		if (s && creDir[s->ID] != (s->side == BattleSide::ATTACKER) && s->alive()
-		   && creAnims[s->ID]->isIdle())
-		{
-			addNewAnim(new CReverseAnimation(this, s, s->getPosition(), false));
-		}
-	}
-
-	queue->update();
-
-	if (tacticsMode) //stack ended movement in tactics phase -> select the next one
-		bTacticNextStack(stack);
-
-	if(action->actionType == EActionType::HERO_SPELL) //we have activated next stack after sending request that has been just realized -> blockmap due to movement has changed
-		redrawBackgroundWithHexes(activeStack);
-
-	if (activeStack && !animsAreDisplayed.get() && pendingAnims.empty() && !active)
-	{
-		logGlobal->warn("Something wrong... interface was deactivated but there is no animation. Reactivating...");
-		blockUI(false);
-	}
-	else
-	{
-		// block UI if no active stack (e.g. enemy turn);
-		blockUI(activeStack == nullptr);
-	}
-}
-
-void CBattleInterface::hideQueue()
-{
-	Settings showQueue = settings.write["battle"]["showQueue"];
-	showQueue->Bool() = false;
-
-	queue->deactivate();
-
-	if (!queue->embedded)
-	{
-		moveBy(Point(0, -queue->pos.h / 2));
-		GH.totalRedraw();
-	}
-}
-
-void CBattleInterface::showQueue()
-{
-	Settings showQueue = settings.write["battle"]["showQueue"];
-	showQueue->Bool() = true;
-
-	queue->activate();
-
-	if (!queue->embedded)
-	{
-		moveBy(Point(0, +queue->pos.h / 2));
-		GH.totalRedraw();
-	}
-}
-
-void CBattleInterface::blockUI(bool on)
-{
-	bool canCastSpells = false;
-	auto hero = curInt->cb->battleGetMyHero();
-
-	if(hero)
-	{
-		ESpellCastProblem::ESpellCastProblem spellcastingProblem = curInt->cb->battleCanCastSpell(hero, spells::Mode::HERO);
-
-		//if magic is blocked, we leave button active, so the message can be displayed after button click
-		canCastSpells = spellcastingProblem == ESpellCastProblem::OK || spellcastingProblem == ESpellCastProblem::MAGIC_IS_BLOCKED;
-	}
-
-	bool canWait = activeStack ? !activeStack->waitedThisTurn : false;
-
-	bOptions->block(on);
-	bFlee->block(on || !curInt->cb->battleCanFlee());
-	bSurrender->block(on || curInt->cb->battleGetSurrenderCost() < 0);
-
-	// block only if during enemy turn and auto-fight is off
-	// otherwise - crash on accessing non-exisiting active stack
-	bAutofight->block(!curInt->isAutoFightOn && !activeStack);
-
-	if (tacticsMode && btactEnd && btactNext)
-	{
-		btactNext->block(on);
-		btactEnd->block(on);
-	}
-	else
-	{
-		bConsoleUp->block(on);
-		bConsoleDown->block(on);
-	}
-
-
-	bSpell->block(on || tacticsMode || !canCastSpells);
-	bWait->block(on || tacticsMode || !canWait);
-	bDefence->block(on || tacticsMode);
-}
-
-void CBattleInterface::startAction(const BattleAction* action)
-{
-	//setActiveStack(nullptr);
-	setHoveredStack(nullptr);
-	blockUI(true);
-
-	if(action->actionType == EActionType::END_TACTIC_PHASE)
-	{
-		SDL_FreeSurface(menu);
-		menu = BitmapHandler::loadBitmap("CBAR.bmp");
-
-		graphics->blueToPlayersAdv(menu, curInt->playerID);
-		return;
-	}
-
-	const CStack *stack = curInt->cb->battleGetStackByID(action->stackNumber);
-
-	if (stack)
-	{
-		queue->update();
-	}
-	else
-	{
-		assert(action->actionType == EActionType::HERO_SPELL); //only cast spell is valid action without acting stack number
-	}
-
-	auto actionTarget = action->getTarget(curInt->cb.get());
-
-	if(action->actionType == EActionType::WALK
-		|| (action->actionType == EActionType::WALK_AND_ATTACK && actionTarget.at(0).hexValue != stack->getPosition()))
-	{
-		assert(stack);
-		moveStarted = true;
-		if (creAnims[action->stackNumber]->framesInGroup(CCreatureAnim::MOVE_START))
-		{
-			pendingAnims.push_back(std::make_pair(new CMovementStartAnimation(this, stack), false));
-		}
-
-		if(shouldRotate(stack, stack->getPosition(), actionTarget.at(0).hexValue))
-			pendingAnims.push_back(std::make_pair(new CReverseAnimation(this, stack, stack->getPosition(), true), false));
-	}
-
-	redraw(); // redraw after deactivation, including proper handling of hovered hexes
-
-	if(action->actionType == EActionType::HERO_SPELL) //when hero casts spell
-	{
-		setHeroAnimation(action->side, 4);
-		return;
-	}
-
-	if (!stack)
-	{
-		logGlobal->error("Something wrong with stackNumber in actionStarted. Stack number: %d", action->stackNumber);
-		return;
-	}
-
-	int txtid = 0;
-	switch(action->actionType)
-	{
-	case EActionType::WAIT:
-		txtid = 136;
-		break;
-	case EActionType::BAD_MORALE:
-		txtid = -34; //negative -> no separate singular/plural form
-		displayEffect(30, stack->getPosition());
-		CCS->soundh->playSound(soundBase::BADMRLE);
-		break;
-	}
-
-	if(txtid != 0)
-		console->addText(stack->formatGeneralMessage(txtid));
-
-	//displaying special abilities
-	switch(action->actionType)
-	{
-		case EActionType::STACK_HEAL:
-			displayEffect(74, actionTarget.at(0).hexValue);
-			CCS->soundh->playSound(soundBase::REGENER);
-			break;
-	}
-}
-
-void CBattleInterface::waitForAnims()
-{
-	auto unlockPim = vstd::makeUnlockGuard(*CPlayerInterface::pim);
-	animsAreDisplayed.waitWhileTrue();
-}
-
-void CBattleInterface::bEndTacticPhase()
-{
-	setActiveStack(nullptr);
-	blockUI(true);
-	tacticsMode = false;
-}
-
-static bool immobile(const CStack *s)
-{
-	return !s->Speed(0, true); //should bound stacks be immobile?
-}
-
-void CBattleInterface::bTacticNextStack(const CStack * current)
-{
-	if (!current)
-		current = activeStack;
-
-	//no switching stacks when the current one is moving
-	waitForAnims();
-
-	TStacks stacksOfMine = tacticianInterface->cb->battleGetStacks(CBattleCallback::ONLY_MINE);
-	vstd::erase_if (stacksOfMine, &immobile);
-	if (stacksOfMine.empty())
-	{
-		bEndTacticPhase();
-		return;
-	}
-
-	auto it = vstd::find(stacksOfMine, current);
-	if (it != stacksOfMine.end() && ++it != stacksOfMine.end())
-		stackActivated(*it);
-	else
-		stackActivated(stacksOfMine.front());
-
-}
-
-std::string formatDmgRange(std::pair<ui32, ui32> dmgRange)
-{
-	if (dmgRange.first != dmgRange.second)
-		return (boost::format("%d - %d") % dmgRange.first % dmgRange.second).str();
-	else
-		return (boost::format("%d") % dmgRange.first).str();
-}
-
-bool CBattleInterface::canStackMoveHere(const CStack * activeStack, BattleHex myNumber)
-{
-	std::vector<BattleHex> acc = curInt->cb->battleGetAvailableHexes(activeStack);
-	BattleHex shiftedDest = myNumber.cloneInDirection(activeStack->destShiftDir(), false);
-
-	if (vstd::contains(acc, myNumber))
-		return true;
-	else if (activeStack->doubleWide() && vstd::contains(acc, shiftedDest))
-		return true;
-	else
-		return false;
-}
-
-void CBattleInterface::handleHex(BattleHex myNumber, int eventType)
-{
-	if (!myTurn || !battleActionsStarted) //we are not permit to do anything
-		return;
-
-	// This function handles mouse move over hexes and l-clicking on them.
-	// First we decide what happens if player clicks on this hex and set appropriately
-	// consoleMsg, cursorFrame/Type and prepare lambda realizeAction.
-	//
-	// Then, depending whether it was hover/click we either call the action or set tooltip/cursor.
-
-	//used when hovering -> tooltip message and cursor to be set
-	std::string consoleMsg;
-	bool setCursor = true; //if we want to suppress setting cursor
-	ECursor::ECursorTypes cursorType = ECursor::COMBAT;
-	int cursorFrame = ECursor::COMBAT_POINTER; //TODO: is this line used?
-
-	//used when l-clicking -> action to be called upon the click
-	std::function<void()> realizeAction;
-
-	//Get stack on the hex - first try to grab the alive one, if not found -> allow dead stacks.
-	const CStack * shere = curInt->cb->battleGetStackByPos(myNumber, true);
-	if(!shere)
-		shere = curInt->cb->battleGetStackByPos(myNumber, false);
-
-	if(!activeStack)
-		return;
-
-	bool ourStack = false;
-	if (shere)
-		ourStack = shere->owner == curInt->playerID;
-
-	//stack changed, update selection border
-	if (shere != mouseHoveredStack)
-	{
-		setHoveredStack(shere);
-	}
-
-	localActions.clear();
-	illegalActions.clear();
-
-	reorderPossibleActionsPriority(activeStack, shere ? MouseHoveredHexContext::OCCUPIED_HEX : MouseHoveredHexContext::UNOCCUPIED_HEX);
-	const bool forcedAction = possibleActions.size() == 1;
-
-	for (PossiblePlayerBattleAction action : possibleActions)
-	{
-		bool legalAction = false; //this action is legal and can be performed
-		bool notLegal = false; //this action is not legal and should display message
-
-		switch (action)
-		{
-			case PossiblePlayerBattleAction::CHOOSE_TACTICS_STACK:
-				if (shere && ourStack)
-					legalAction = true;
-				break;
-			case PossiblePlayerBattleAction::MOVE_TACTICS:
-			case PossiblePlayerBattleAction::MOVE_STACK:
-			{
-				if (!(shere && shere->alive())) //we can walk on dead stacks
-				{
-					if(canStackMoveHere(activeStack, myNumber))
-						legalAction = true;
-				}
-				break;
-			}
-			case PossiblePlayerBattleAction::ATTACK:
-			case PossiblePlayerBattleAction::WALK_AND_ATTACK:
-			case PossiblePlayerBattleAction::ATTACK_AND_RETURN:
-			{
-				if(curInt->cb->battleCanAttack(activeStack, shere, myNumber))
-				{
-					if (isTileAttackable(myNumber)) // move isTileAttackable to be part of battleCanAttack?
-					{
-						setBattleCursor(myNumber); // temporary - needed for following function :(
-						BattleHex attackFromHex = fromWhichHexAttack(myNumber);
-
-						if (attackFromHex >= 0) //we can be in this line when unreachable creature is L - clicked (as of revision 1308)
-							legalAction = true;
-					}
-				}
-			}
-				break;
-			case PossiblePlayerBattleAction::SHOOT:
-				if(curInt->cb->battleCanShoot(activeStack, myNumber))
-					legalAction = true;
-				break;
-			case PossiblePlayerBattleAction::ANY_LOCATION:
-				if (myNumber > -1) //TODO: this should be checked for all actions
-				{
-					if(isCastingPossibleHere(activeStack, shere, myNumber))
-						legalAction = true;
-				}
-				break;
-			case PossiblePlayerBattleAction::AIMED_SPELL_CREATURE:
-				if(shere && isCastingPossibleHere(activeStack, shere, myNumber))
-					legalAction = true;
-				break;
-			case PossiblePlayerBattleAction::RANDOM_GENIE_SPELL:
-			{
-				if(shere && ourStack && shere != activeStack && shere->alive()) //only positive spells for other allied creatures
-				{
-					int spellID = curInt->cb->battleGetRandomStackSpell(CRandomGenerator::getDefault(), shere, CBattleInfoCallback::RANDOM_GENIE);
-					if(spellID > -1)
-					{
-						legalAction = true;
-					}
-				}
-			}
-				break;
-			case PossiblePlayerBattleAction::OBSTACLE:
-				if(isCastingPossibleHere(activeStack, shere, myNumber))
-					legalAction = true;
-				break;
-			case PossiblePlayerBattleAction::TELEPORT:
-			{
-				//todo: move to mechanics
-				ui8 skill = 0;
-				if (creatureCasting)
-					skill = activeStack->getEffectLevel(SpellID(SpellID::TELEPORT).toSpell());
-				else
-					skill = getActiveHero()->getEffectLevel(SpellID(SpellID::TELEPORT).toSpell());
-				//TODO: explicitely save power, skill
-				if (curInt->cb->battleCanTeleportTo(selectedStack, myNumber, skill))
-					legalAction = true;
-				else
-					notLegal = true;
-			}
-				break;
-			case PossiblePlayerBattleAction::SACRIFICE: //choose our living stack to sacrifice
-				if (shere && shere != selectedStack && ourStack && shere->alive())
-					legalAction = true;
-				else
-					notLegal = true;
-				break;
-			case PossiblePlayerBattleAction::FREE_LOCATION:
-				legalAction = true;
-				if(!isCastingPossibleHere(activeStack, shere, myNumber))
-				{
-					legalAction = false;
-					notLegal = true;
-				}
-				break;
-			case PossiblePlayerBattleAction::CATAPULT:
-				if (isCatapultAttackable(myNumber))
-					legalAction = true;
-				break;
-			case PossiblePlayerBattleAction::HEAL:
-				if (shere && ourStack && shere->canBeHealed())
-					legalAction = true;
-				break;
-			case PossiblePlayerBattleAction::RISE_DEMONS:
-				if (shere && ourStack && !shere->alive())
-				{
-					if (!(shere->hasBonusOfType(Bonus::UNDEAD)
-						|| shere->hasBonusOfType(Bonus::NON_LIVING)
-						|| shere->hasBonusOfType(Bonus::GARGOYLE)
-						|| shere->summoned
-						|| shere->isClone()
-						|| shere->hasBonusOfType(Bonus::SIEGE_WEAPON)
-						))
-						legalAction = true;
-				}
-				break;
-		}
-		if (legalAction)
-			localActions.push_back (action);
-		else if (notLegal || forcedAction)
-			illegalActions.push_back (action);
-	}
-	illegalAction = PossiblePlayerBattleAction::INVALID; //clear it in first place
-
-	if (vstd::contains(localActions, selectedAction)) //try to use last selected action by default
-		currentAction = selectedAction;
-	else if (localActions.size()) //if not possible, select first available action (they are sorted by suggested priority)
-		currentAction = localActions.front();
-	else //no legal action possible
-	{
-		currentAction = PossiblePlayerBattleAction::INVALID; //don't allow to do anything
-
-		if (vstd::contains(illegalActions, selectedAction))
-			illegalAction = selectedAction;
-		else if (illegalActions.size())
-			illegalAction = illegalActions.front();
-		else if (shere && ourStack && shere->alive()) //last possibility - display info about our creature
-		{
-			currentAction = PossiblePlayerBattleAction::CREATURE_INFO;
-		}
-		else
-			illegalAction = PossiblePlayerBattleAction::INVALID; //we should never be here
-	}
-
-	bool isCastingPossible = false;
-	bool secondaryTarget = false;
-
-	if (currentAction > PossiblePlayerBattleAction::INVALID)
-	{
-		switch (currentAction) //display console message, realize selected action
-		{
-			case PossiblePlayerBattleAction::CHOOSE_TACTICS_STACK:
-				consoleMsg = (boost::format(CGI->generaltexth->allTexts[481]) % shere->getName()).str(); //Select %s
-				realizeAction = [=](){ stackActivated(shere); };
-				break;
-			case PossiblePlayerBattleAction::MOVE_TACTICS:
-			case PossiblePlayerBattleAction::MOVE_STACK:
-				if (activeStack->hasBonusOfType(Bonus::FLYING))
-				{
-					cursorFrame = ECursor::COMBAT_FLY;
-					consoleMsg = (boost::format(CGI->generaltexth->allTexts[295]) % activeStack->getName()).str(); //Fly %s here
-				}
-				else
-				{
-					cursorFrame = ECursor::COMBAT_MOVE;
-					consoleMsg = (boost::format(CGI->generaltexth->allTexts[294]) % activeStack->getName()).str(); //Move %s here
-				}
-
-				realizeAction = [=]()
-				{
-					if(activeStack->doubleWide())
-					{
-						std::vector<BattleHex> acc = curInt->cb->battleGetAvailableHexes(activeStack);
-						BattleHex shiftedDest = myNumber.cloneInDirection(activeStack->destShiftDir(), false);
-						if(vstd::contains(acc, myNumber))
-							giveCommand(EActionType::WALK, myNumber);
-						else if(vstd::contains(acc, shiftedDest))
-							giveCommand(EActionType::WALK, shiftedDest);
-					}
-					else
-					{
-						giveCommand(EActionType::WALK, myNumber);
-					}
-				};
-				break;
-			case PossiblePlayerBattleAction::ATTACK:
-			case PossiblePlayerBattleAction::WALK_AND_ATTACK:
-			case PossiblePlayerBattleAction::ATTACK_AND_RETURN: //TODO: allow to disable return
-				{
-					setBattleCursor(myNumber); //handle direction of cursor and attackable tile
-					setCursor = false; //don't overwrite settings from the call above //TODO: what does it mean?
-
-					bool returnAfterAttack = currentAction == PossiblePlayerBattleAction::ATTACK_AND_RETURN;
-
-					realizeAction = [=]()
-					{
-						BattleHex attackFromHex = fromWhichHexAttack(myNumber);
-						if(attackFromHex.isValid()) //we can be in this line when unreachable creature is L - clicked (as of revision 1308)
-						{
-							auto command = new BattleAction(BattleAction::makeMeleeAttack(activeStack, myNumber, attackFromHex, returnAfterAttack));
-							sendCommand(command, activeStack);
-						}
-					};
-
-					TDmgRange damage = curInt->cb->battleEstimateDamage(activeStack, shere);
-					std::string estDmgText = formatDmgRange(std::make_pair((ui32)damage.first, (ui32)damage.second)); //calculating estimated dmg
-					consoleMsg = (boost::format(CGI->generaltexth->allTexts[36]) % shere->getName() % estDmgText).str(); //Attack %s (%s damage)
-				}
-				break;
-			case PossiblePlayerBattleAction::SHOOT:
-			{
-				if (curInt->cb->battleHasShootingPenalty(activeStack, myNumber))
-					cursorFrame = ECursor::COMBAT_SHOOT_PENALTY;
-				else
-					cursorFrame = ECursor::COMBAT_SHOOT;
-
-				realizeAction = [=](){giveCommand(EActionType::SHOOT, myNumber);};
-				TDmgRange damage = curInt->cb->battleEstimateDamage(activeStack, shere);
-				std::string estDmgText = formatDmgRange(std::make_pair((ui32)damage.first, (ui32)damage.second)); //calculating estimated dmg
-				//printing - Shoot %s (%d shots left, %s damage)
-				consoleMsg = (boost::format(CGI->generaltexth->allTexts[296]) % shere->getName() % activeStack->shots.available() % estDmgText).str();
-			}
-				break;
-			case PossiblePlayerBattleAction::AIMED_SPELL_CREATURE:
-				sp = CGI->spellh->objects[creatureCasting ? creatureSpellToCast : spellToCast->actionSubtype]; //necessary if creature has random Genie spell at same time
-				consoleMsg = boost::str(boost::format(CGI->generaltexth->allTexts[27]) % sp->name % shere->getName()); //Cast %s on %s
-				switch (sp->id)
-				{
-					case SpellID::SACRIFICE:
-					case SpellID::TELEPORT:
-						selectedStack = shere; //remember first target
-						secondaryTarget = true;
-						break;
-				}
-				isCastingPossible = true;
-				break;
-			case PossiblePlayerBattleAction::ANY_LOCATION:
-				sp = CGI->spellh->objects[creatureCasting ? creatureSpellToCast : spellToCast->actionSubtype]; //necessary if creature has random Genie spell at same time
-				consoleMsg = boost::str(boost::format(CGI->generaltexth->allTexts[26]) % sp->name); //Cast %s
-				isCastingPossible = true;
-				break;
-			case PossiblePlayerBattleAction::RANDOM_GENIE_SPELL: //we assume that teleport / sacrifice will never be available as random spell
-				sp = nullptr;
-				consoleMsg = boost::str(boost::format(CGI->generaltexth->allTexts[301]) % shere->getName()); //Cast a spell on %
-				creatureCasting = true;
-				isCastingPossible = true;
-				break;
-			case PossiblePlayerBattleAction::TELEPORT:
-				consoleMsg = CGI->generaltexth->allTexts[25]; //Teleport Here
-				cursorFrame = ECursor::COMBAT_TELEPORT;
-				isCastingPossible = true;
-				break;
-			case PossiblePlayerBattleAction::OBSTACLE:
-				consoleMsg = CGI->generaltexth->allTexts[550];
-				//TODO: remove obstacle cursor
-				isCastingPossible = true;
-				break;
-			case PossiblePlayerBattleAction::SACRIFICE:
-				consoleMsg = (boost::format(CGI->generaltexth->allTexts[549]) % shere->getName()).str(); //sacrifice the %s
-				cursorFrame = ECursor::COMBAT_SACRIFICE;
-				isCastingPossible = true;
-				break;
-			case PossiblePlayerBattleAction::FREE_LOCATION:
-				consoleMsg = boost::str(boost::format(CGI->generaltexth->allTexts[26]) % sp->name); //Cast %s
-				isCastingPossible = true;
-				break;
-			case PossiblePlayerBattleAction::HEAL:
-				cursorFrame = ECursor::COMBAT_HEAL;
-				consoleMsg = (boost::format(CGI->generaltexth->allTexts[419]) % shere->getName()).str(); //Apply first aid to the %s
-				realizeAction = [=](){ giveCommand(EActionType::STACK_HEAL, myNumber); }; //command healing
-				break;
-			case PossiblePlayerBattleAction::RISE_DEMONS:
-				cursorType = ECursor::SPELLBOOK;
-				realizeAction = [=]()
-				{
-					giveCommand(EActionType::DAEMON_SUMMONING, myNumber);
-				};
-				break;
-			case PossiblePlayerBattleAction::CATAPULT:
-				cursorFrame = ECursor::COMBAT_SHOOT_CATAPULT;
-				realizeAction = [=](){ giveCommand(EActionType::CATAPULT, myNumber); };
-				break;
-			case PossiblePlayerBattleAction::CREATURE_INFO:
-			{
-				cursorFrame = ECursor::COMBAT_QUERY;
-				consoleMsg = (boost::format(CGI->generaltexth->allTexts[297]) % shere->getName()).str();
-				realizeAction = [=](){ GH.pushIntT<CStackWindow>(shere, false); };
-				break;
-			}
-		}
-	}
-	else //no possible valid action, display message
-	{
-		switch (illegalAction)
-		{
-			case PossiblePlayerBattleAction::AIMED_SPELL_CREATURE:
-			case PossiblePlayerBattleAction::RANDOM_GENIE_SPELL:
-				cursorFrame = ECursor::COMBAT_BLOCKED;
-				consoleMsg = CGI->generaltexth->allTexts[23];
-				break;
-			case PossiblePlayerBattleAction::TELEPORT:
-				cursorFrame = ECursor::COMBAT_BLOCKED;
-				consoleMsg = CGI->generaltexth->allTexts[24]; //Invalid Teleport Destination
-				break;
-			case PossiblePlayerBattleAction::SACRIFICE:
-				consoleMsg = CGI->generaltexth->allTexts[543]; //choose army to sacrifice
-				break;
-			case PossiblePlayerBattleAction::FREE_LOCATION:
-				cursorFrame = ECursor::COMBAT_BLOCKED;
-				consoleMsg = boost::str(boost::format(CGI->generaltexth->allTexts[181]) % sp->name); //No room to place %s here
-				break;
-			default:
-				if (myNumber == -1)
-					CCS->curh->changeGraphic(ECursor::COMBAT, ECursor::COMBAT_POINTER); //set neutral cursor over menu etc.
-				else
-					cursorFrame = ECursor::COMBAT_BLOCKED;
-				break;
-		}
-	}
-
-	if (isCastingPossible) //common part
-	{
-		switch (currentAction) //don't use that with teleport / sacrifice
-		{
-			case PossiblePlayerBattleAction::TELEPORT: //FIXME: more generic solution?
-			case PossiblePlayerBattleAction::SACRIFICE:
-				break;
-			default:
-				cursorType = ECursor::SPELLBOOK;
-				cursorFrame = 0;
-				if (consoleMsg.empty() && sp)
-					consoleMsg = boost::str(boost::format(CGI->generaltexth->allTexts[26]) % sp->name); //Cast %s
-				break;
-		}
-
-		realizeAction = [=]()
-		{
-			if(secondaryTarget) //select that target now
-			{
-
-				possibleActions.clear();
-				switch (sp->id.toEnum())
-				{
-					case SpellID::TELEPORT: //don't cast spell yet, only select target
-						spellToCast->aimToUnit(shere);
-						possibleActions.push_back(PossiblePlayerBattleAction::TELEPORT);
-						break;
-					case SpellID::SACRIFICE:
-						spellToCast->aimToHex(myNumber);
-						possibleActions.push_back(PossiblePlayerBattleAction::SACRIFICE);
-						break;
-				}
-			}
-			else
-			{
-				if (creatureCasting)
-				{
-					if (sp)
-					{
-						giveCommand(EActionType::MONSTER_SPELL, myNumber, creatureSpellToCast);
-					}
-					else //unknown random spell
-					{
-						giveCommand(EActionType::MONSTER_SPELL, myNumber);
-					}
-				}
-				else
-				{
-					assert(sp);
-					switch (sp->id.toEnum())
-					{
-					case SpellID::SACRIFICE:
-						spellToCast->aimToUnit(shere);//victim
-						break;
-					default:
-						spellToCast->aimToHex(myNumber);
-						break;
-					}
-					curInt->cb->battleMakeAction(spellToCast.get());
-					endCastingSpell();
-				}
-				selectedStack = nullptr;
-			}
-		};
-	}
-
-	{
-		if (eventType == MOVE)
-		{
-			if (setCursor)
-				CCS->curh->changeGraphic(cursorType, cursorFrame);
-			this->console->alterText(consoleMsg);
-			this->console->whoSetAlter = 0;
-		}
-		if (eventType == LCLICK && realizeAction)
-		{
-			//opening creature window shouldn't affect myTurn...
-			if ((currentAction != PossiblePlayerBattleAction::CREATURE_INFO) && !secondaryTarget)
-			{
-				myTurn = false; //tends to crash with empty calls
-			}
-			realizeAction();
-			if (!secondaryTarget) //do not replace teleport or sacrifice cursor
-				CCS->curh->changeGraphic(ECursor::COMBAT, ECursor::COMBAT_POINTER);
-			this->console->alterText("");
-		}
-	}
-}
-
-bool CBattleInterface::isCastingPossibleHere(const CStack *sactive, const CStack *shere, BattleHex myNumber)
-{
-	creatureCasting = stackCanCastSpell && !spellDestSelectMode; //TODO: allow creatures to cast aimed spells
-
-	bool isCastingPossible = true;
-
-	int spellID = -1;
-	if (creatureCasting)
-	{
-		if (creatureSpellToCast > -1 && (shere != sactive)) //can't cast on itself
-			spellID = creatureSpellToCast; //TODO: merge with SpellTocast?
-	}
-	else //hero casting
-	{
-		spellID = spellToCast->actionSubtype;
-	}
-
-
-	sp = nullptr;
-	if (spellID >= 0)
-		sp = CGI->spellh->objects[spellID];
-
-	if (sp)
-	{
-		const spells::Caster *caster = creatureCasting ? static_cast<const spells::Caster *>(sactive) : static_cast<const spells::Caster *>(curInt->cb->battleGetMyHero());
-		if (caster == nullptr)
-		{
-			isCastingPossible = false;//just in case
-		}
-		else
-		{
-			const spells::Mode mode = creatureCasting ? spells::Mode::CREATURE_ACTIVE : spells::Mode::HERO;
-
-			spells::Target target;
-			target.emplace_back(myNumber);
-
-			spells::BattleCast cast(curInt->cb.get(), caster, mode, sp);
-
-			auto m = sp->battleMechanics(&cast);
-			spells::detail::ProblemImpl problem; //todo: display problem in status bar
-
-			isCastingPossible = m->canBeCastAt(target, problem);
-		}
-	}
-	else
-		isCastingPossible = false;
-	if (!myNumber.isAvailable() && !shere) //empty tile outside battlefield (or in the unavailable border column)
-			isCastingPossible = false;
-
-	return isCastingPossible;
-}
-
-BattleHex CBattleInterface::fromWhichHexAttack(BattleHex myNumber)
-{
-	//TODO far too much repeating code
-	BattleHex destHex;
-	switch(CCS->curh->frame)
-	{
-	case 12: //from bottom right
-		{
-			bool doubleWide = activeStack->doubleWide();
-			destHex = myNumber + ( (myNumber/GameConstants::BFIELD_WIDTH)%2 ? GameConstants::BFIELD_WIDTH : GameConstants::BFIELD_WIDTH+1 ) +
-				(activeStack->side == BattleSide::ATTACKER && doubleWide ? 1 : 0);
-			if(vstd::contains(occupyableHexes, destHex))
-				return destHex;
-			else if(activeStack->side == BattleSide::ATTACKER)
-			{
-				if (vstd::contains(occupyableHexes, destHex+1))
-					return destHex+1;
-			}
-			else //if we are defender
-			{
-				if(vstd::contains(occupyableHexes, destHex-1))
-					return destHex-1;
-			}
-			break;
-		}
-	case 7: //from bottom left
-		{
-			destHex = myNumber + ( (myNumber/GameConstants::BFIELD_WIDTH)%2 ? GameConstants::BFIELD_WIDTH-1 : GameConstants::BFIELD_WIDTH );
-			if (vstd::contains(occupyableHexes, destHex))
-				return destHex;
-			else if(activeStack->side == BattleSide::ATTACKER)
-			{
-				if(vstd::contains(occupyableHexes, destHex+1))
-					return destHex+1;
-			}
-			else //we are defender
-			{
-				if(vstd::contains(occupyableHexes, destHex-1))
-					return destHex-1;
-			}
-			break;
-		}
-	case 8: //from left
-		{
-			if(activeStack->doubleWide() && activeStack->side == BattleSide::DEFENDER)
-			{
-				std::vector<BattleHex> acc = curInt->cb->battleGetAvailableHexes(activeStack);
-				if (vstd::contains(acc, myNumber))
-					return myNumber - 1;
-				else
-					return myNumber - 2;
-			}
-			else
-			{
-				return myNumber - 1;
-			}
-			break;
-		}
-	case 9: //from top left
-		{
-			destHex = myNumber - ((myNumber/GameConstants::BFIELD_WIDTH) % 2 ? GameConstants::BFIELD_WIDTH + 1 : GameConstants::BFIELD_WIDTH);
-			if(vstd::contains(occupyableHexes, destHex))
-				return destHex;
-			else if(activeStack->side == BattleSide::ATTACKER)
-			{
-				if(vstd::contains(occupyableHexes, destHex+1))
-					return destHex+1;
-			}
-			else //if we are defender
-			{
-				if(vstd::contains(occupyableHexes, destHex-1))
-					return destHex-1;
-			}
-			break;
-		}
-	case 10: //from top right
-		{
-			bool doubleWide = activeStack->doubleWide();
-			destHex = myNumber - ( (myNumber/GameConstants::BFIELD_WIDTH)%2 ? GameConstants::BFIELD_WIDTH : GameConstants::BFIELD_WIDTH-1 ) +
-				(activeStack->side == BattleSide::ATTACKER && doubleWide ? 1 : 0);
-			if(vstd::contains(occupyableHexes, destHex))
-				return destHex;
-			else if(activeStack->side == BattleSide::ATTACKER)
-			{
-				if(vstd::contains(occupyableHexes, destHex+1))
-					return destHex+1;
-			}
-			else //if we are defender
-			{
-				if(vstd::contains(occupyableHexes, destHex-1))
-					return destHex-1;
-			}
-			break;
-		}
-	case 11: //from right
-		{
-			if(activeStack->doubleWide() && activeStack->side == BattleSide::ATTACKER)
-			{
-				std::vector<BattleHex> acc = curInt->cb->battleGetAvailableHexes(activeStack);
-				if(vstd::contains(acc, myNumber))
-					return myNumber + 1;
-				else
-					return myNumber + 2;
-			}
-			else
-			{
-				return myNumber + 1;
-			}
-			break;
-		}
-	case 13: //from bottom
-		{
-			destHex = myNumber + ( (myNumber/GameConstants::BFIELD_WIDTH)%2 ? GameConstants::BFIELD_WIDTH : GameConstants::BFIELD_WIDTH+1 );
-			if(vstd::contains(occupyableHexes, destHex))
-				return destHex;
-			else if(activeStack->side == BattleSide::ATTACKER)
-			{
-				if(vstd::contains(occupyableHexes, destHex+1))
-					return destHex+1;
-			}
-			else //if we are defender
-			{
-				if(vstd::contains(occupyableHexes, destHex-1))
-					return destHex-1;
-			}
-			break;
-		}
-	case 14: //from top
-		{
-			destHex = myNumber - ( (myNumber/GameConstants::BFIELD_WIDTH)%2 ? GameConstants::BFIELD_WIDTH : GameConstants::BFIELD_WIDTH-1 );
-			if (vstd::contains(occupyableHexes, destHex))
-				return destHex;
-			else if(activeStack->side == BattleSide::ATTACKER)
-			{
-				if(vstd::contains(occupyableHexes, destHex+1))
-					return destHex+1;
-			}
-			else //if we are defender
-			{
-				if(vstd::contains(occupyableHexes, destHex-1))
-					return destHex-1;
-			}
-			break;
-		}
-	}
-	return -1;
-}
-
-Rect CBattleInterface::hexPosition(BattleHex hex) const
-{
-	int x = 14 + ((hex.getY())%2==0 ? 22 : 0) + 44*hex.getX() + pos.x;
-	int y = 86 + 42 *hex.getY() + pos.y;
-	int w = cellShade->w;
-	int h = cellShade->h;
-	return Rect(x, y, w, h);
-}
-
-void CBattleInterface::obstaclePlaced(const CObstacleInstance & oi)
-{
-	//so when multiple obstacles are added, they show up one after another
-	waitForAnims();
-
-	//soundBase::soundID sound; // FIXME(v.markovtsev): soundh->playSound() is commented in the end => warning
-
-	std::string defname;
-
-	switch(oi.obstacleType)
-	{
-	case CObstacleInstance::SPELL_CREATED:
-		{
-			auto &spellObstacle = dynamic_cast<const SpellCreatedObstacle&>(oi);
-			defname = spellObstacle.appearAnimation;
-			//TODO: sound
-			//soundBase::QUIKSAND
-			//soundBase::LANDMINE
-			//soundBase::FORCEFLD
-			//soundBase::fireWall
-		}
-		break;
-	default:
-		logGlobal->error("I don't know how to animate appearing obstacle of type %d", (int)oi.obstacleType);
-		return;
-	}
-
-	auto animation = std::make_shared<CAnimation>(defname);
-	animation->preload();
-
-	auto first = animation->getImage(0, 0);
-	if(!first)
-		return;
-
-	//we assume here that effect graphics have the same size as the usual obstacle image
-	// -> if we know how to blit obstacle, let's blit the effect in the same place
-	Point whereTo = getObstaclePosition(first, oi);
-	addNewAnim(new CEffectAnimation(this, animation, whereTo.x, whereTo.y));
-
-	//TODO we need to wait after playing sound till it's finished, otherwise it overlaps and sounds really bad
-	//CCS->soundh->playSound(sound);
-}
-
-void CBattleInterface::gateStateChanged(const EGateState state)
-{
-	auto oldState = curInt->cb->battleGetGateState();
-	bool playSound = false;
-	int stateId = EWallState::NONE;
-	switch(state)
-	{
-	case EGateState::CLOSED:
-		if (oldState != EGateState::BLOCKED)
-			playSound = true;
-		break;
-	case EGateState::BLOCKED:
-		if (oldState != EGateState::CLOSED)
-			playSound = true;
-		break;
-	case EGateState::OPENED:
-		playSound = true;
-		stateId = EWallState::DAMAGED;
-		break;
-	case EGateState::DESTROYED:
-		stateId = EWallState::DESTROYED;
-		break;
-	}
-
-	if (oldState != EGateState::NONE && oldState != EGateState::CLOSED && oldState != EGateState::BLOCKED)
-		SDL_FreeSurface(siegeH->walls[SiegeHelper::GATE]);
-
-	if (stateId != EWallState::NONE)
-		siegeH->walls[SiegeHelper::GATE] = BitmapHandler::loadBitmap(siegeH->getSiegeName(SiegeHelper::GATE, stateId));
-	if (playSound)
-		CCS->soundh->playSound(soundBase::DRAWBRG);
-}
-
-const CGHeroInstance *CBattleInterface::currentHero() const
-{
-	if (attackingHeroInstance->tempOwner == curInt->playerID)
-		return attackingHeroInstance;
-	else
-		return defendingHeroInstance;
-}
-
-InfoAboutHero CBattleInterface::enemyHero() const
-{
-	InfoAboutHero ret;
-	if (attackingHeroInstance->tempOwner == curInt->playerID)
-		curInt->cb->getHeroInfo(defendingHeroInstance, ret);
-	else
-		curInt->cb->getHeroInfo(attackingHeroInstance, ret);
-
-	return ret;
-}
-
-void CBattleInterface::requestAutofightingAIToTakeAction()
-{
-	assert(curInt->isAutoFightOn);
-
-	boost::thread aiThread([&]()
-	{
-		auto ba = make_unique<BattleAction>(curInt->autofightingAI->activeStack(activeStack));
-
-		if(curInt->cb->battleIsFinished())
-		{
-			return; // battle finished with spellcast
-		}
-
-		if (curInt->isAutoFightOn)
-		{
-			if (tacticsMode)
-			{
-				// Always end tactics mode. Player interface is blocked currently, so it's not possible that
-				// the AI can take any action except end tactics phase (AI actions won't be triggered)
-				//TODO implement the possibility that the AI will be triggered for further actions
-				//TODO any solution to merge tactics phase & normal phase in the way it is handled by the player and battle interface?
-				setActiveStack(nullptr);
-				blockUI(true);
-				tacticsMode = false;
-			}
-			else
-			{
-				givenCommand.setn(ba.release());
-			}
-		}
-		else
-		{
-			boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
-			activateStack();
-		}
-	});
-
-	aiThread.detach();
-}
-
-CBattleInterface::SiegeHelper::SiegeHelper(const CGTownInstance *siegeTown, const CBattleInterface *_owner)
-	: owner(_owner), town(siegeTown)
-{
-	for (int g = 0; g < ARRAY_COUNT(walls); ++g)
-	{
-		if (g != SiegeHelper::GATE)
-			walls[g] = BitmapHandler::loadBitmap(getSiegeName(g));
-	}
-}
-
-CBattleInterface::SiegeHelper::~SiegeHelper()
-{
-	auto gateState = owner->curInt->cb->battleGetGateState();
-	for (int g = 0; g < ARRAY_COUNT(walls); ++g)
-	{
-		if (g != SiegeHelper::GATE || (gateState != EGateState::NONE && gateState != EGateState::CLOSED && gateState != EGateState::BLOCKED))
-			SDL_FreeSurface(walls[g]);
-	}
-}
-
-std::string CBattleInterface::SiegeHelper::getSiegeName(ui16 what) const
-{
-	return getSiegeName(what, EWallState::INTACT);
-}
-
-std::string CBattleInterface::SiegeHelper::getSiegeName(ui16 what, int state) const
-{
-	auto getImageIndex = [&]() -> int
-	{
-		switch (state)
-		{
-		case EWallState::INTACT : return 1;
-		case EWallState::DAMAGED :
-			if(what == 2 || what == 3 || what == 8) // towers don't have separate image here - INTACT and DAMAGED is 1, DESTROYED is 2
-				return 1;
-			else
-				return 2;
-		case EWallState::DESTROYED :
-			if (what == 2 || what == 3 || what == 8)
-				return 2;
-			else
-				return 3;
-		}
-		return 1;
-	};
-
-	const std::string & prefix = town->town->clientInfo.siegePrefix;
-	std::string addit = boost::lexical_cast<std::string>(getImageIndex());
-
-	switch(what)
-	{
-	case SiegeHelper::BACKGROUND:
-		return prefix + "BACK.BMP";
-	case SiegeHelper::BACKGROUND_WALL:
-		{
-			switch(town->town->faction->index)
-			{
-			case ETownType::RAMPART:
-			case ETownType::NECROPOLIS:
-			case ETownType::DUNGEON:
-			case ETownType::STRONGHOLD:
-				return prefix + "TPW1.BMP";
-			default:
-				return prefix + "TPWL.BMP";
-			}
-		}
-	case SiegeHelper::KEEP:
-		return prefix + "MAN" + addit + ".BMP";
-	case SiegeHelper::BOTTOM_TOWER:
-		return prefix + "TW1" + addit + ".BMP";
-	case SiegeHelper::BOTTOM_WALL:
-		return prefix + "WA1" + addit + ".BMP";
-	case SiegeHelper::WALL_BELLOW_GATE:
-		return prefix + "WA3" + addit + ".BMP";
-	case SiegeHelper::WALL_OVER_GATE:
-		return prefix + "WA4" + addit + ".BMP";
-	case SiegeHelper::UPPER_WALL:
-		return prefix + "WA6" + addit + ".BMP";
-	case SiegeHelper::UPPER_TOWER:
-		return prefix + "TW2" + addit + ".BMP";
-	case SiegeHelper::GATE:
-		return prefix + "DRW" + addit + ".BMP";
-	case SiegeHelper::GATE_ARCH:
-		return prefix + "ARCH.BMP";
-	case SiegeHelper::BOTTOM_STATIC_WALL:
-		return prefix + "WA2.BMP";
-	case SiegeHelper::UPPER_STATIC_WALL:
-		return prefix + "WA5.BMP";
-	case SiegeHelper::MOAT:
-		return prefix + "MOAT.BMP";
-	case SiegeHelper::BACKGROUND_MOAT:
-		return prefix + "MLIP.BMP";
-	case SiegeHelper::KEEP_BATTLEMENT:
-		return prefix + "MANC.BMP";
-	case SiegeHelper::BOTTOM_BATTLEMENT:
-		return prefix + "TW1C.BMP";
-	case SiegeHelper::UPPER_BATTLEMENT:
-		return prefix + "TW2C.BMP";
-	default:
-		return "";
-	}
-}
-
-void CBattleInterface::SiegeHelper::printPartOfWall(SDL_Surface *to, int what)
-{
-	Point pos = Point(-1, -1);
-	auto & ci = town->town->clientInfo;
-
-	if (vstd::iswithin(what, 1, 17))
-	{
-		pos.x = ci.siegePositions[what].x + owner->pos.x;
-		pos.y = ci.siegePositions[what].y + owner->pos.y;
-	}
-
-	if (town->town->faction->index == ETownType::TOWER
-		&& (what == SiegeHelper::MOAT || what == SiegeHelper::BACKGROUND_MOAT))
-		return; // no moat in Tower. TODO: remove hardcode somehow?
-
-	if (pos.x != -1)
-	{
-		//gate have no displayed bitmap when drawbridge is raised
-		if (what == SiegeHelper::GATE)
-		{
-			auto gateState = owner->curInt->cb->battleGetGateState();
-			if (gateState != EGateState::OPENED && gateState != EGateState::DESTROYED)
-				return;
-		}
-
-		blitAt(walls[what], pos.x, pos.y, to);
-	}
-}
-
-CatapultProjectileInfo::CatapultProjectileInfo(Point from, Point dest)
-{
-	facA = 0.005; // seems to be constant
-
-	// system of 2 linear equations, solutions of which are missing coefficients
-	// for quadratic equation a*x*x + b*x + c
-	double eq[2][3] = {
-		{ static_cast<double>(from.x), 1.0, from.y - facA*from.x*from.x },
-		{ static_cast<double>(dest.x), 1.0, dest.y - facA*dest.x*dest.x }
-	};
-
-	// solve system via determinants
-	double det  = eq[0][0] *eq[1][1] - eq[1][0] *eq[0][1];
-	double detB = eq[0][2] *eq[1][1] - eq[1][2] *eq[0][1];
-	double detC = eq[0][0] *eq[1][2] - eq[1][0] *eq[0][2];
-
-	facB = detB / det;
-	facC = detC / det;
-
-	// make sure that parabola is correct e.g. passes through from and dest
-	assert(fabs(calculateY(from.x) - from.y) < 1.0);
-	assert(fabs(calculateY(dest.x) - dest.y) < 1.0);
-}
-
-double CatapultProjectileInfo::calculateY(double x)
-{
-	return facA *pow(x, 2.0) + facB *x + facC;
-}
-
-void CBattleInterface::showAll(SDL_Surface *to)
-{
-	show(to);
-}
-
-void CBattleInterface::show(SDL_Surface *to)
-{
-	assert(to);
-
-	SDL_Rect buf;
-	SDL_GetClipRect(to, &buf);
-	SDL_SetClipRect(to, &pos);
-
-	++animCount;
-
-	showBackground(to);
-	showBattlefieldObjects(to);
-	showProjectiles(to);
-
-	if(battleActionsStarted)
-		updateBattleAnimations();
-
-	SDL_SetClipRect(to, &buf); //restoring previous clip_rect
-
-	showInterface(to);
-
-	//activation of next stack
-	if (pendingAnims.empty() && stackToActivate != nullptr && battleActionsStarted) //FIXME: watch for recursive infinite loop here when working with this file, this needs rework anyway...
-	{
-		activateStack();
-
-		//we may have changed active interface (another side in hot-seat),
-		// so we can't continue drawing with old setting.
-		show(to);
-	}
-}
-
-void CBattleInterface::showBackground(SDL_Surface *to)
-{
-	if (activeStack != nullptr && creAnims[activeStack->ID]->isIdle()) //show everything with range
-	{
-		// FIXME: any *real* reason to keep this separate? Speed difference can't be that big
-		blitAt(backgroundWithHexes, pos.x, pos.y, to);
-	}
-	else
-	{
-		showBackgroundImage(to);
-		showAbsoluteObstacles(to);
-	}
-	showHighlightedHexes(to);
-}
-
-void CBattleInterface::showBackgroundImage(SDL_Surface *to)
-{
-	blitAt(background, pos.x, pos.y, to);
-	if (settings["battle"]["cellBorders"].Bool())
-	{
-		CSDL_Ext::blit8bppAlphaTo24bpp(cellBorders, nullptr, to, &pos);
-	}
-}
-
-void CBattleInterface::showAbsoluteObstacles(SDL_Surface * to)
-{
-	//Blit absolute obstacles
-	for(auto & oi : curInt->cb->battleGetAllObstacles())
-	{
-		if(oi->obstacleType == CObstacleInstance::ABSOLUTE_OBSTACLE)
-		{
-			auto img = getObstacleImage(*oi);
-			if(img)
-				img->draw(to, pos.x + oi->getInfo().width, pos.y + oi->getInfo().height);
-		}
-	}
-
-
-	if (siegeH && siegeH->town->hasBuilt(BuildingID::CITADEL))
-		siegeH->printPartOfWall(to, SiegeHelper::BACKGROUND_MOAT);
-}
-
-void CBattleInterface::showHighlightedHexes(SDL_Surface *to)
-{
-	bool delayedBlit = false; //workaround for blitting enemy stack hex without mouse shadow with stack range on
-	if(activeStack && settings["battle"]["stackRange"].Bool())
-	{
-		std::set<BattleHex> set = curInt->cb->battleGetAttackedHexes(activeStack, currentlyHoveredHex, attackingHex);
-		for(BattleHex hex : set)
-			if(hex != currentlyHoveredHex)
-				showHighlightedHex(to, hex);
-
-		// display the movement shadow of the stack at b (i.e. stack under mouse)
-		const CStack * const shere = curInt->cb->battleGetStackByPos(currentlyHoveredHex, false);
-		if(shere && shere != activeStack && shere->alive())
-		{
-			std::vector<BattleHex> v = curInt->cb->battleGetAvailableHexes(shere, true, nullptr);
-			for(BattleHex hex : v)
-			{
-				if(hex != currentlyHoveredHex)
-					showHighlightedHex(to, hex);
-				else if(!settings["battle"]["mouseShadow"].Bool())
-					delayedBlit = true; //blit at the end of method to avoid graphic artifacts
-				else
-					showHighlightedHex(to, hex, true); //blit now and blit 2nd time later for darker shadow - avoids graphic artifacts
-			}
-		}
-	}
-
-	for(int b=0; b<GameConstants::BFIELD_SIZE; ++b)
-	{
-		if(bfield[b]->strictHovered && bfield[b]->hovered)
-		{
-			if(previouslyHoveredHex == -1)
-				previouslyHoveredHex = b; //something to start with
-			if(currentlyHoveredHex == -1)
-				currentlyHoveredHex = b; //something to start with
-
-			if(currentlyHoveredHex != b) //repair hover info
-			{
-				previouslyHoveredHex = currentlyHoveredHex;
-				currentlyHoveredHex = b;
-			}
-			if(settings["battle"]["mouseShadow"].Bool() || delayedBlit)
-			{
-				const spells::Caster *caster = nullptr;
-				const CSpell *spell = nullptr;
-
-				spells::Mode mode = spells::Mode::HERO;
-
-				if(spellToCast)//hero casts spell
-				{
-					spell = SpellID(spellToCast->actionSubtype).toSpell();
-					caster = getActiveHero();
-				}
-				else if(creatureSpellToCast >= 0 && stackCanCastSpell && creatureCasting)//stack casts spell
-				{
-					spell = SpellID(creatureSpellToCast).toSpell();
-					caster = activeStack;
-					mode = spells::Mode::CREATURE_ACTIVE;
-				}
-
-				if(caster && spell) //when casting spell
-				{
-					// printing shaded hex(es)
-					spells::BattleCast event(curInt->cb.get(), caster, mode, spell);
-					auto shaded = spell->battleMechanics(&event)->rangeInHexes(currentlyHoveredHex);
-
-					for(BattleHex shadedHex : shaded)
-					{
-						if((shadedHex.getX() != 0) && (shadedHex.getX() != GameConstants::BFIELD_WIDTH - 1))
-							showHighlightedHex(to, shadedHex, true);
-					}
-				}
-				else if(active || delayedBlit) //always highlight pointed hex, keep this condition last in this method for correct behavior
-				{
-					if(currentlyHoveredHex.getX() != 0
-					 && currentlyHoveredHex.getX() != GameConstants::BFIELD_WIDTH - 1)
-						showHighlightedHex(to, currentlyHoveredHex, true); //keep true for OH3 behavior: hovered hex frame "thinner"
-				}
-			}
-		}
-	}
-}
-
-void CBattleInterface::showHighlightedHex(SDL_Surface *to, BattleHex hex, bool darkBorder)
-{
-	int x = 14 + (hex.getY() % 2 == 0 ? 22 : 0) + 44 *(hex.getX()) + pos.x;
-	int y = 86 + 42 *hex.getY() + pos.y;
-	SDL_Rect temp_rect = genRect (cellShade->h, cellShade->w, x, y);
-	CSDL_Ext::blit8bppAlphaTo24bpp (cellShade, nullptr, to, &temp_rect);
-	if(!darkBorder && settings["battle"]["cellBorders"].Bool())
-		CSDL_Ext::blit8bppAlphaTo24bpp(cellBorder, nullptr, to, &temp_rect); //redraw border to make it light green instead of shaded
-}
-
-void CBattleInterface::showProjectiles(SDL_Surface *to)
-{
-	assert(to);
-
-	std::list< std::list<ProjectileInfo>::iterator > toBeDeleted;
-	for (auto it = projectiles.begin(); it!=projectiles.end(); ++it)
-	{
-		// Check if projectile is already visible (shooter animation did the shot)
-		if (!it->shotDone)
-		{
-			// frame we're waiting for is reached OR animation has already finished
-			if (creAnims[it->stackID]->getCurrentFrame() >= it->animStartDelay ||
-				creAnims[it->stackID]->isShooting() == false)
-			{
-				//at this point projectile should become visible
-				creAnims[it->stackID]->pause(); // pause animation
-				it->shotDone = true;
-			}
-			else
-				continue; // wait...
-		}
-
-		if (idToProjectile.count(it->creID))
-		{
-			size_t group = it->reverse ? 1 : 0;
-			auto image = idToProjectile[it->creID]->getImage(it->frameNum, group, true);
-
-			if(image)
-			{
-				SDL_Rect dst;
-				dst.h = image->height();
-				dst.w = image->width();
-				dst.x = static_cast<int>(it->x - dst.w / 2);
-				dst.y = static_cast<int>(it->y - dst.h / 2);
-
-				image->draw(to, &dst, nullptr);
-			}
-		}
-		if (idToRay.count(it->creID))
-		{
-			auto const & ray = idToRay[it->creID];
-
-			if (std::abs(it->dx) > std::abs(it->dy)) // draw in horizontal axis
-			{
-				int y1 =  it->y0 - ray.size() / 2;
-				int y2 =  it->y - ray.size() / 2;
-
-				int x1 = it->x0;
-				int x2 = it->x;
-
-				for (size_t i = 0; i < ray.size(); ++i)
-				{
-					SDL_Color beginColor{ ray[i].r1, ray[i].g1, ray[i].b1, ray[i].a1};
-					SDL_Color endColor  { ray[i].r2, ray[i].g2, ray[i].b2, ray[i].a2};
-
-					CSDL_Ext::drawLine(to, x1, y1 + i, x2, y2 + i, beginColor, endColor);
-				}
-			}
-			else // draw in vertical axis
-			{
-				int x1 = it->x0 - ray.size() / 2;
-				int x2 = it->x - ray.size() / 2;
-
-				int y1 =  it->y0;
-				int y2 =  it->y;
-
-				for (size_t i = 0; i < ray.size(); ++i)
-				{
-					SDL_Color beginColor{ ray[i].r1, ray[i].g1, ray[i].b1, ray[i].a1};
-					SDL_Color endColor  { ray[i].r2, ray[i].g2, ray[i].b2, ray[i].a2};
-
-					CSDL_Ext::drawLine(to, x1 + i, y1, x2 + i, y2, beginColor, endColor);
-				}
-			}
-		}
-
-		// Update projectile
-		++it->step;
-		if (it->step > it->lastStep)
-		{
-			toBeDeleted.insert(toBeDeleted.end(), it);
-		}
-		else
-		{
-			if (it->catapultInfo)
-			{
-				// Parabolic shot of the trajectory, as follows: f(x) = ax^2 + bx + c
-				it->x += it->dx;
-				it->y = it->catapultInfo->calculateY(it->x);
-
-				++(it->frameNum);
-				it->frameNum %= idToProjectile[it->creID]->size(0);
-			}
-			else
-			{
-				// Normal projectile, just add the calculated "deltas" to the x and y positions.
-				it->x += it->dx;
-				it->y += it->dy;
-			}
-		}
-	}
-
-	for (auto & elem : toBeDeleted)
-	{
-		// resume animation
-		creAnims[elem->stackID]->play();
-		projectiles.erase(elem);
-	}
-}
-
-void CBattleInterface::showBattlefieldObjects(SDL_Surface *to)
-{
-	auto showHexEntry = [&](BattleObjectsByHex::HexData & hex)
-	{
-		showPiecesOfWall(to, hex.walls);
-		showObstacles(to, hex.obstacles);
-		showAliveStacks(to, hex.alive);
-		showBattleEffects(to, hex.effects);
-	};
-
-	BattleObjectsByHex objects = sortObjectsByHex();
-
-	// dead stacks should be blit first
-	showStacks(to, objects.beforeAll.dead);
-	for (auto & data : objects.hex)
-		showStacks(to, data.dead);
-	showStacks(to, objects.afterAll.dead);
-
-	// display objects that must be blit before anything else (e.g. topmost walls)
-	showHexEntry(objects.beforeAll);
-
-	// show heroes after "beforeAll" - e.g. topmost wall in siege
-	if (attackingHero)
-		attackingHero->show(to);
-	if (defendingHero)
-		defendingHero->show(to);
-
-	// actual blit of most of objects, hex by hex
-	// NOTE: row-by-row blitting may be a better approach
-	for (auto &data : objects.hex)
-		showHexEntry(data);
-
-	// objects that must be blit *after* everything else - e.g. bottom tower or some spell effects
-	showHexEntry(objects.afterAll);
-}
-
-void CBattleInterface::showAliveStacks(SDL_Surface *to, std::vector<const CStack *> stacks)
-{
-	BattleHex currentActionTarget;
-	if(curInt->curAction)
-	{
-		auto target = curInt->curAction->getTarget(curInt->cb.get());
-		if(!target.empty())
-			currentActionTarget = target.at(0).hexValue;
-	}
-
-	auto isAmountBoxVisible = [&](const CStack *stack) -> bool
-	{
-		if(stack->hasBonusOfType(Bonus::SIEGE_WEAPON) && stack->getCount() == 1) //do not show box for singular war machines, stacked war machines with box shown are supported as extension feature
-			return false;
-
-		if(stack->getCount() == 0) //hide box when target is going to die anyway - do not display "0 creatures"
-			return false;
-
-		for(auto anim : pendingAnims) //no matter what other conditions below are, hide box when creature is playing hit animation
-		{
-			auto hitAnimation = dynamic_cast<CDefenceAnimation*>(anim.first);
-			if(hitAnimation && (hitAnimation->stack->ID == stack->ID)) //we process only "current creature" as other creatures will be processed reliably on their own iteration
-				return false;
-		}
-
-		if(curInt->curAction)
-		{
-			if(curInt->curAction->stackNumber == stack->ID) //stack is currently taking action (is not a target of another creature's action etc)
-			{
-				if(curInt->curAction->actionType == EActionType::WALK || curInt->curAction->actionType == EActionType::SHOOT) //hide when stack walks or shoots
-					return false;
-
-				else if(curInt->curAction->actionType == EActionType::WALK_AND_ATTACK && currentActionTarget != stack->getPosition()) //when attacking, hide until walk phase finished
-					return false;
-			}
-
-			if(curInt->curAction->actionType == EActionType::SHOOT && currentActionTarget == stack->getPosition()) //hide if we are ranged attack target
-				return false;
-		}
-
-		return true;
-	};
-
-	auto getEffectsPositivness = [&](const std::vector<si32> & activeSpells) -> int
-	{
-		int pos = 0;
-		for (const auto & spellId : activeSpells)
-		{
-			pos += CGI->spellh->objects.at(spellId)->positiveness;
-		}
-		return pos;
-	};
-
-	auto getAmountBoxBackground = [&](int positivness) -> SDL_Surface *
-	{
-		if (positivness > 0)
-			return amountPositive;
-		if (positivness < 0)
-			return amountNegative;
-		return amountEffNeutral;
-	};
-
-	showStacks(to, stacks); // Actual display of all stacks
-
-	for (auto & stack : stacks)
-	{
-		assert(stack);
-		//printing amount
-		if (isAmountBoxVisible(stack))
-		{
-			const int sideShift = stack->side == BattleSide::ATTACKER ? 1 : -1;
-			const int reverseSideShift = stack->side == BattleSide::ATTACKER ? -1 : 1;
-			const BattleHex nextPos = stack->getPosition() + sideShift;
-			const bool edge = stack->getPosition() % GameConstants::BFIELD_WIDTH == (stack->side == BattleSide::ATTACKER ? GameConstants::BFIELD_WIDTH - 2 : 1);
-			const bool moveInside = !edge && !stackCountOutsideHexes[nextPos];
-			int xAdd = (stack->side == BattleSide::ATTACKER ? 220 : 202) +
-					   (stack->doubleWide() ? 44 : 0) * sideShift +
-					   (moveInside ? amountNormal->w + 10 : 0) * reverseSideShift;
-			int yAdd = 260 + ((stack->side == BattleSide::ATTACKER || moveInside) ? 0 : -15);
-
-			//blitting amount background box
-			SDL_Surface *amountBG = amountNormal;
-			std::vector<si32> activeSpells = stack->activeSpells();
-			if (!activeSpells.empty())
-				amountBG = getAmountBoxBackground(getEffectsPositivness(activeSpells));
-
-			SDL_Rect temp_rect = genRect(amountBG->h, amountBG->w, creAnims[stack->ID]->pos.x + xAdd, creAnims[stack->ID]->pos.y + yAdd);
-			SDL_BlitSurface(amountBG, nullptr, to, &temp_rect);
-
-			//blitting amount
-			Point textPos(creAnims[stack->ID]->pos.x + xAdd + amountNormal->w/2,
-						  creAnims[stack->ID]->pos.y + yAdd + amountNormal->h/2);
-			graphics->fonts[FONT_TINY]->renderTextCenter(to, makeNumberShort(stack->getCount()), Colors::WHITE, textPos);
-		}
-	}
-}
-
-void CBattleInterface::showStacks(SDL_Surface *to, std::vector<const CStack *> stacks)
-{
-	for (const CStack *stack : stacks)
-	{
-		creAnims[stack->ID]->nextFrame(to, creDir[stack->ID]); // do actual blit
-		creAnims[stack->ID]->incrementFrame(float(GH.mainFPSmng->getElapsedMilliseconds()) / 1000);
-	}
-}
-
-void CBattleInterface::showObstacles(SDL_Surface * to, std::vector<std::shared_ptr<const CObstacleInstance>> & obstacles)
-{
-	for(auto & obstacle : obstacles)
-	{
-		auto img = getObstacleImage(*obstacle);
-		if(img)
-		{
-			Point p = getObstaclePosition(img, *obstacle);
-			img->draw(to, p.x, p.y);
-		}
-	}
-}
-
-void CBattleInterface::showBattleEffects(SDL_Surface *to, const std::vector<const BattleEffect *> &battleEffects)
-{
-	for (auto & elem : battleEffects)
-	{
-		int currentFrame = static_cast<int>(floor(elem->currentFrame));
-		currentFrame %= elem->animation->size();
-
-		auto img = elem->animation->getImage(currentFrame);
-
-		SDL_Rect temp_rect = genRect(img->height(), img->width(), elem->x, elem->y);
-
-		img->draw(to, &temp_rect, nullptr);
-	}
-}
-
-void CBattleInterface::showInterface(SDL_Surface *to)
-{
-	blitAt(menu, pos.x, 556 + pos.y, to);
-
-	if (tacticsMode)
-	{
-		btactNext->showAll(to);
-		btactEnd->showAll(to);
-	}
-	else
-	{
-		console->showAll(to);
-		bConsoleUp->showAll(to);
-		bConsoleDown->showAll(to);
-	}
-
-	//showing buttons
-	bOptions->showAll(to);
-	bSurrender->showAll(to);
-	bFlee->showAll(to);
-	bAutofight->showAll(to);
-	bSpell->showAll(to);
-	bWait->showAll(to);
-	bDefence->showAll(to);
-
-	//showing in-game console
-	LOCPLINT->cingconsole->show(to);
-
-	Rect posWithQueue = Rect(pos.x, pos.y, 800, 600);
-
-	if (settings["battle"]["showQueue"].Bool())
-	{
-		if (!queue->embedded)
-		{
-			posWithQueue.y -= queue->pos.h;
-			posWithQueue.h += queue->pos.h;
-		}
-
-		queue->showAll(to);
-	}
-
-	//printing border around interface
-	if (screen->w != 800 || screen->h !=600)
-	{
-		CMessage::drawBorder(curInt->playerID,to,posWithQueue.w + 28, posWithQueue.h + 28, posWithQueue.x-14, posWithQueue.y-15);
-	}
-}
-
-BattleObjectsByHex CBattleInterface::sortObjectsByHex()
-{
-	auto getCurrentPosition = [&](const CStack *stack) -> BattleHex
-	{
-		for (auto & anim : pendingAnims)
-		{
-			// certainly ugly workaround but fixes quite annoying bug
-			// stack position will be updated only *after* movement is finished
-			// before this - stack is always at its initial position. Thus we need to find
-			// its current position. Which can be found only in this class
-			if (CMovementAnimation *move = dynamic_cast<CMovementAnimation*>(anim.first))
-			{
-				if (move->stack == stack)
-					return move->nextHex;
-			}
-		}
-		return stack->getPosition();
-	};
-
-	BattleObjectsByHex sorted;
-
-	auto stacks = curInt->cb->battleGetStacksIf([](const CStack *s)
-	{
-		return !s->isTurret();
-	});
-
-	// Sort creatures
-	for (auto & stack : stacks)
-	{
-		if (creAnims.find(stack->ID) == creAnims.end()) //e.g. for summoned but not yet handled stacks
-			continue;
-
-		if (stack->initialPosition < 0) // turret shooters are handled separately
-			continue;
-
-		//FIXME: hack to ignore ghost stacks
-		if ((creAnims[stack->ID]->getType() == CCreatureAnim::DEAD || creAnims[stack->ID]->getType() == CCreatureAnim::HOLDING) && stack->isGhost())
-			;//ignore
-		else if (!creAnims[stack->ID]->isDead())
-		{
-			if (!creAnims[stack->ID]->isMoving())
-				sorted.hex[stack->getPosition()].alive.push_back(stack);
-			else
-			{
-				// flying creature - just blit them over everyone else
-				if (stack->hasBonusOfType(Bonus::FLYING))
-					sorted.afterAll.alive.push_back(stack);
-				else//try to find current location
-					sorted.hex[getCurrentPosition(stack)].alive.push_back(stack);
-			}
-		}
-		else
-			sorted.hex[stack->getPosition()].dead.push_back(stack);
-	}
-
-	// Sort battle effects (spells)
-	for (auto & battleEffect : battleEffects)
-	{
-		if (battleEffect.position.isValid())
-			sorted.hex[battleEffect.position].effects.push_back(&battleEffect);
-		else
-			sorted.afterAll.effects.push_back(&battleEffect);
-	}
-
-	// Sort obstacles
-	{
-		std::map<BattleHex, std::shared_ptr<const CObstacleInstance>> backgroundObstacles;
-		for (auto &obstacle : curInt->cb->battleGetAllObstacles()) {
-			if (obstacle->obstacleType != CObstacleInstance::ABSOLUTE_OBSTACLE
-				&& obstacle->obstacleType != CObstacleInstance::MOAT) {
-				backgroundObstacles[obstacle->pos] = obstacle;
-			}
-		}
-		for (auto &op : backgroundObstacles)
-		{
-			sorted.beforeAll.obstacles.push_back(op.second);
-		}
-	}
-	// Sort wall parts
-	if (siegeH)
-	{
-		sorted.beforeAll.walls.push_back(SiegeHelper::BACKGROUND_WALL);
-		sorted.hex[135].walls.push_back(SiegeHelper::KEEP);
-		sorted.afterAll.walls.push_back(SiegeHelper::BOTTOM_TOWER);
-		sorted.hex[182].walls.push_back(SiegeHelper::BOTTOM_WALL);
-		sorted.hex[130].walls.push_back(SiegeHelper::WALL_BELLOW_GATE);
-		sorted.hex[78].walls.push_back(SiegeHelper::WALL_OVER_GATE);
-		sorted.hex[12].walls.push_back(SiegeHelper::UPPER_WALL);
-		sorted.beforeAll.walls.push_back(SiegeHelper::UPPER_TOWER);
-		sorted.hex[94].walls.push_back(SiegeHelper::GATE);
-		sorted.hex[112].walls.push_back(SiegeHelper::GATE_ARCH);
-		sorted.hex[165].walls.push_back(SiegeHelper::BOTTOM_STATIC_WALL);
-		sorted.hex[45].walls.push_back(SiegeHelper::UPPER_STATIC_WALL);
-
-		if (siegeH && siegeH->town->hasBuilt(BuildingID::CITADEL))
-		{
-			sorted.beforeAll.walls.push_back(SiegeHelper::MOAT);
-			//sorted.beforeAll.walls.push_back(SiegeHelper::BACKGROUND_MOAT); // blit as absolute obstacle
-			sorted.hex[135].walls.push_back(SiegeHelper::KEEP_BATTLEMENT);
-		}
-		if (siegeH && siegeH->town->hasBuilt(BuildingID::CASTLE))
-		{
-			sorted.afterAll.walls.push_back(SiegeHelper::BOTTOM_BATTLEMENT);
-			sorted.beforeAll.walls.push_back(SiegeHelper::UPPER_BATTLEMENT);
-		}
-	}
-	return sorted;
-}
-
-void CBattleInterface::updateBattleAnimations()
-{
-	//handle animations
-	for (auto & elem : pendingAnims)
-	{
-		if (!elem.first) //this animation should be deleted
-			continue;
-
-		if (!elem.second)
-		{
-			elem.second = elem.first->init();
-		}
-		if (elem.second && elem.first)
-			elem.first->nextFrame();
-	}
-
-	//delete anims
-	int preSize = static_cast<int>(pendingAnims.size());
-	for (auto it = pendingAnims.begin(); it != pendingAnims.end(); ++it)
-	{
-		if (it->first == nullptr)
-		{
-			pendingAnims.erase(it);
-			it = pendingAnims.begin();
-			break;
-		}
-	}
-
-	if (preSize > 0 && pendingAnims.empty())
-	{
-		//anims ended
-		blockUI(activeStack == nullptr);
-
-		animsAreDisplayed.setn(false);
-	}
-}
-
-std::shared_ptr<IImage> CBattleInterface::getObstacleImage(const CObstacleInstance & oi)
-{
-	int frameIndex = (animCount+1) *25 / getAnimSpeed();
-	std::shared_ptr<CAnimation> animation;
-
-	if(oi.obstacleType == CObstacleInstance::USUAL || oi.obstacleType == CObstacleInstance::ABSOLUTE_OBSTACLE)
-	{
-		animation = obstacleAnimations[oi.uniqueID];
-	}
-	else if(oi.obstacleType == CObstacleInstance::SPELL_CREATED)
-	{
-		const SpellCreatedObstacle * spellObstacle = dynamic_cast<const SpellCreatedObstacle *>(&oi);
-		if(!spellObstacle)
-			return std::shared_ptr<IImage>();
-
-		std::string animationName = spellObstacle->animation;
-
-		auto cacheIter = animationsCache.find(animationName);
-
-		if(cacheIter == animationsCache.end())
-		{
-			logAnim->trace("Creating obstacle animation %s", animationName);
-
-			animation = std::make_shared<CAnimation>(animationName);
-			animation->preload();
-			animationsCache[animationName] = animation;
-		}
-		else
-		{
-			animation = cacheIter->second;
-		}
-	}
-
-	if(animation)
-	{
-		frameIndex %= animation->size(0);
-		return animation->getImage(frameIndex, 0);
-	}
-
-	return nullptr;
-}
-
-Point CBattleInterface::getObstaclePosition(std::shared_ptr<IImage> image, const CObstacleInstance & obstacle)
-{
-	int offset = obstacle.getAnimationYOffset(image->height());
-
-	Rect r = hexPosition(obstacle.pos);
-	r.y += 42 - image->height() + offset;
-
-	return r.topLeft();
-}
-
-void CBattleInterface::redrawBackgroundWithHexes(const CStack *activeStack)
-{
-	attackableHexes.clear();
-	if (activeStack)
-		occupyableHexes = curInt->cb->battleGetAvailableHexes(activeStack, true, &attackableHexes);
-
-	auto fillStackCountOutsideHexes = [&]()
-	{
-		auto accessibility = curInt->cb->getAccesibility();
-
-		for(int i = 0; i < accessibility.size(); i++)
-			stackCountOutsideHexes.at(i) = (accessibility[i] == EAccessibility::ACCESSIBLE);
-	};
-
-	fillStackCountOutsideHexes();
-
-	//prepare background graphic with hexes and shaded hexes
-	blitAt(background, 0, 0, backgroundWithHexes);
-
-	//draw absolute obstacles (cliffs and so on)
-	for(auto & oi : curInt->cb->battleGetAllObstacles())
-	{
-		if(oi->obstacleType == CObstacleInstance::ABSOLUTE_OBSTACLE)
-		{
-			auto img = getObstacleImage(*oi);
-			if(img)
-				img->draw(backgroundWithHexes, oi->getInfo().width, oi->getInfo().height);
-		}
-	}
-
-	if (settings["battle"]["stackRange"].Bool())
-	{
-		std::vector<BattleHex> hexesToShade = occupyableHexes;
-		hexesToShade.insert(hexesToShade.end(), attackableHexes.begin(), attackableHexes.end());
-		for (BattleHex hex : hexesToShade)
-		{
-			int i = hex.getY(); //row
-			int j = hex.getX()-1; //column
-			int x = 58 + (i%2==0 ? 22 : 0) + 44*j;
-			int y = 86 + 42 *i;
-			SDL_Rect temp_rect = genRect(cellShade->h, cellShade->w, x, y);
-			CSDL_Ext::blit8bppAlphaTo24bpp(cellShade, nullptr, backgroundWithHexes, &temp_rect);
-		}
-	}
-
-	if(settings["battle"]["cellBorders"].Bool())
-		CSDL_Ext::blit8bppAlphaTo24bpp(cellBorders, nullptr, backgroundWithHexes, nullptr);
-}
-
-void CBattleInterface::showPiecesOfWall(SDL_Surface *to, std::vector<int> pieces)
-{
-	if (!siegeH)
-		return;
-	for (auto piece : pieces)
-	{
-		if (piece < 15) // not a tower - just print
-			siegeH->printPartOfWall(to, piece);
-		else // tower. find if tower is built and not destroyed - stack is present
-		{
-			// PieceID    StackID
-			// 15 = keep,  -2
-			// 16 = lower, -3
-			// 17 = upper, -4
-
-			// tower. check if tower is alive - stack is found
-			int stackPos = 13 - piece;
-
-			const CStack *turret = nullptr;
-
-			for (auto & stack : curInt->cb->battleGetAllStacks(true))
-			{
-				if(stack->initialPosition == stackPos)
-				{
-					turret = stack;
-					break;
-				}
-			}
-
-			if (turret)
-			{
-				std::vector<const CStack *> stackList(1, turret);
-				showStacks(to, stackList);
-				siegeH->printPartOfWall(to, piece);
-			}
-		}
-	}
-}

+ 0 - 414
client/battle/CBattleInterface.h

@@ -1,414 +0,0 @@
-/*
- * CBattleInterface.h, part of VCMI engine
- *
- * Authors: listed in file AUTHORS in main folder
- *
- * License: GNU General Public License v2.0 or later
- * Full text of license available in license.txt file, in main folder
- *
- */
-#pragma once
-
-#include <vcmi/spells/Magic.h>
-
-#include "../../lib/ConstTransitivePtr.h" //may be redundant
-#include "../../lib/GameConstants.h"
-
-#include "CBattleAnimations.h"
-
-#include "../../lib/spells/CSpellHandler.h" //CSpell::TAnimation
-#include "../../lib/CCreatureHandler.h"
-#include "../../lib/battle/CBattleInfoCallback.h"
-
-VCMI_LIB_NAMESPACE_BEGIN
-
-class CCreatureSet;
-class CGHeroInstance;
-class CStack;
-struct BattleResult;
-struct BattleSpellCast;
-struct CObstacleInstance;
-template <typename T> struct CondSh;
-struct SetStackEffect;
-class BattleAction;
-class CGTownInstance;
-struct CatapultAttack;
-struct BattleTriggerEffect;
-struct BattleHex;
-struct InfoAboutHero;
-class CBattleGameInterface;
-struct CustomEffectInfo;
-class CSpell;
-
-VCMI_LIB_NAMESPACE_END
-
-class CLabel;
-class CCallback;
-class CButton;
-class CToggleButton;
-class CToggleGroup;
-struct CatapultProjectileInfo;
-class CBattleAnimation;
-class CBattleHero;
-class CBattleConsole;
-class CBattleResultWindow;
-class CStackQueue;
-class CPlayerInterface;
-class CCreatureAnimation;
-struct ProjectileInfo;
-class CClickableHex;
-class CAnimation;
-class IImage;
-class CStackQueue;
-
-/// Small struct which contains information about the id of the attacked stack, the damage dealt,...
-struct StackAttackedInfo
-{
-	const CStack *defender; //attacked stack
-	int64_t dmg; //damage dealt
-	unsigned int amountKilled; //how many creatures in stack has been killed
-	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
-	bool cloneKilled;
-};
-
-/// Struct for battle effect animation e.g. morale, prayer, armageddon, bless,...
-struct BattleEffect
-{
-	int x, y; //position on the screen
-	float currentFrame;
-	std::shared_ptr<CAnimation> animation;
-	int effectID; //uniqueID equal ot ID of appropriate CSpellEffectAnim
-	BattleHex position; //Indicates if effect which hex the effect is drawn on
-};
-
-struct BattleObjectsByHex
-{
-	typedef std::vector<int> TWallList;
-	typedef std::vector<const CStack *> TStackList;
-	typedef std::vector<const BattleEffect *> TEffectList;
-	typedef std::vector<std::shared_ptr<const CObstacleInstance>> TObstacleList;
-
-	struct HexData
-	{
-		TWallList walls;
-		TStackList dead;
-		TStackList alive;
-		TEffectList effects;
-		TObstacleList obstacles;
-	};
-
-	HexData beforeAll;
-	HexData afterAll;
-	std::array<HexData, GameConstants::BFIELD_SIZE> hex;
-};
-
-/// Small struct which is needed for drawing the parabolic trajectory of the catapult cannon
-struct CatapultProjectileInfo
-{
-	CatapultProjectileInfo(Point from, Point dest);
-
-	double facA, facB, facC;
-
-	double calculateY(double x);
-};
-
-enum class MouseHoveredHexContext
-{
-	UNOCCUPIED_HEX,
-	OCCUPIED_HEX
-};
-
-/// Big class which handles the overall battle interface actions and it is also responsible for
-/// drawing everything correctly.
-class CBattleInterface : public WindowBase
-{
-private:
-	SDL_Surface *background, *menu, *amountNormal, *amountNegative, *amountPositive, *amountEffNeutral, *cellBorders, *backgroundWithHexes;
-
-	std::shared_ptr<CButton> bOptions;
-	std::shared_ptr<CButton> bSurrender;
-	std::shared_ptr<CButton> bFlee;
-	std::shared_ptr<CButton> bAutofight;
-	std::shared_ptr<CButton> bSpell;
-	std::shared_ptr<CButton> bWait;
-	std::shared_ptr<CButton> bDefence;
-	std::shared_ptr<CButton> bConsoleUp;
-	std::shared_ptr<CButton> bConsoleDown;
-	std::shared_ptr<CButton> btactNext;
-	std::shared_ptr<CButton> btactEnd;
-
-	std::shared_ptr<CBattleConsole> console;
-	std::shared_ptr<CBattleHero> attackingHero;
-	std::shared_ptr<CBattleHero> defendingHero;
-	std::shared_ptr<CStackQueue> queue;
-
-	const CCreatureSet *army1, *army2; //copy of initial armies (for result window)
-	const CGHeroInstance *attackingHeroInstance, *defendingHeroInstance;
-	std::map<int32_t, std::shared_ptr<CCreatureAnimation>> creAnims; //animations of creatures from fighting armies (order by BattleInfo's stacks' ID)
-
-	std::map<int, std::shared_ptr<CAnimation>> idToProjectile;
-	std::map<int, std::vector<CCreature::CreatureAnimation::RayColor>> idToRay;
-
-	std::map<std::string, std::shared_ptr<CAnimation>> animationsCache;
-	std::map<si32, std::shared_ptr<CAnimation>> obstacleAnimations;
-
-	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
-	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
-	std::array<bool, GameConstants::BFIELD_SIZE> stackCountOutsideHexes; // 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)
-	int attackingHex; //hex from which the stack would perform attack with current cursor
-
-	std::shared_ptr<CPlayerInterface> tacticianInterface; //used during tactics mode, points to the interface of player with higher tactics (can be either attacker or defender in hot-seat), valid onloy for human players
-	bool tacticsMode;
-	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
-	std::shared_ptr<BattleAction> spellToCast; //spell for which player is choosing destination
-	const CSpell *sp; //spell pointer for convenience
-	si32 creatureSpellToCast;
-	std::vector<PossiblePlayerBattleAction> possibleActions; //all actions possible to call at the moment by player
-	std::vector<PossiblePlayerBattleAction> localActions; //actions possible to take on hovered hex
-	std::vector<PossiblePlayerBattleAction> illegalActions; //these actions display message in case of illegal target
-	PossiblePlayerBattleAction currentAction; //action that will be performed on l-click
-	PossiblePlayerBattleAction selectedAction; //last action chosen (and saved) by player
-	PossiblePlayerBattleAction illegalAction; //most likely action that can't be performed here
-	bool battleActionsStarted; //used for delaying battle actions until intro sound stops
-	int battleIntroSoundChannel; //required as variable for disabling it via ESC key
-
-	void setActiveStack(const CStack *stack);
-	void setHoveredStack(const CStack *stack);
-
-	void requestAutofightingAIToTakeAction();
-
-	std::vector<PossiblePlayerBattleAction> getPossibleActionsForStack (const CStack *stack); //called when stack gets its turn
-	void endCastingSpell(); //ends casting spell (eg. when spell has been cast or canceled)
-	void reorderPossibleActionsPriority(const CStack * stack, MouseHoveredHexContext context);
-
-	//force active stack to cast a spell if possible
-	void enterCreatureCastingMode();
-
-	std::list<ProjectileInfo> projectiles; //projectiles flying on battlefield
-	void giveCommand(EActionType action, BattleHex tile = BattleHex(), si32 additional = -1);
-	void sendCommand(BattleAction *& command, const CStack * actor = nullptr);
-
-	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
-
-	std::list<BattleEffect> battleEffects; //different animations to display on the screen like spell effects
-
-	/// 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
-
-		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);
-
-		enum EWallVisual
-		{
-			BACKGROUND = 0,
-			BACKGROUND_WALL = 1,
-			KEEP,
-			BOTTOM_TOWER,
-			BOTTOM_WALL,
-			WALL_BELLOW_GATE,
-			WALL_OVER_GATE,
-			UPPER_WALL,
-			UPPER_TOWER,
-			GATE,
-			GATE_ARCH,
-			BOTTOM_STATIC_WALL,
-			UPPER_STATIC_WALL,
-			MOAT,
-			BACKGROUND_MOAT,
-			KEEP_BATTLEMENT,
-			BOTTOM_BATTLEMENT,
-			UPPER_BATTLEMENT
-		};
-
-		friend class CBattleInterface;
-	} *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
-
-	/** Methods for displaying battle screen */
-	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 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 showBattleEffects(SDL_Surface *to, const std::vector<const BattleEffect *> &battleEffects);
-	void showProjectiles(SDL_Surface *to);
-
-	BattleObjectsByHex sortObjectsByHex();
-	void updateBattleAnimations();
-
-	std::shared_ptr<IImage> getObstacleImage(const CObstacleInstance & oi);
-
-	Point getObstaclePosition(std::shared_ptr<IImage> image, const CObstacleInstance & obstacle);
-
-	void redrawBackgroundWithHexes(const CStack *activeStack);
-	/** End of battle screen blitting methods */
-
-	void setHeroAnimation(ui8 side, int phase);
-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
-	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);
-	virtual ~CBattleInterface();
-
-	//std::vector<TimeInterested*> timeinterested; //animation handling
-	void setPrintCellBorders(bool set); //if true, cell borders will be printed
-	void setPrintStackRange(bool set); //if true,range of active stack will be printed
-	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;
-	bool shouldRotate(const CStack * stack, const BattleHex & oldPos, const BattleHex & nextHex);
-
-	std::vector<std::shared_ptr<CClickableHex>> bfield; //11 lines, 17 hexes on each
-	SDL_Surface *cellBorder, *cellShade;
-
-	bool myTurn; //if true, interface is active (commands can be ordered)
-
-	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
-
-	// block all UI elements, e.g. during enemy turn
-	// unlike activate/deactivate this method will correctly grey-out all elements
-	void blockUI(bool on);
-
-	//button handle funcs:
-	void bOptionsf();
-	void bSurrenderf();
-	void bFleef();
-	void reallyFlee(); //performs fleeing without asking player
-	void reallySurrender(); //performs surrendering without asking player
-	void bAutofightf();
-	void bSpellf();
-	void bWaitf();
-	void bDefencef();
-	void bConsoleUpf();
-	void bConsoleDownf();
-	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 clickRight(tribool down, bool previousState) override;
-
-	void show(SDL_Surface *to) override;
-	void showAll(SDL_Surface *to) override;
-
-	//call-ins
-	void startAction(const BattleAction* action);
-	void unitAdded(const CStack * stack); //new stack appeared on battlefield
-	void stackRemoved(uint32_t 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 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 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 displayBattleFinished(); //displays battle result
-	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 displayBattleLog(const std::vector<MetaString> & battleLog);
-	void displayCustomEffects(const std::vector<CustomEffectInfo> & customEffects);
-
-	void displayEffect(ui32 effect, BattleHex destTile); //displays custom effect on the battlefield
-
-	void displaySpellAnimationQueue(const CSpell::TAnimationQueue & q, BattleHex destinationTile);
-	void displaySpellCast(SpellID spellID, BattleHex destinationTile); //displays spell`s cast animation
-	void displaySpellEffect(SpellID spellID, BattleHex destinationTile); //displays spell`s affected animation
-	void displaySpellHit(SpellID spellID, BattleHex destinationTile); //displays spell`s affected animation
-
-	void battleTriggerEffect(const BattleTriggerEffect & bte);
-	void setBattleCursor(const int myNumber); //really complex and messy, sets attackingHex
-	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
-
-	BattleHex fromWhichHexAttack(BattleHex myNumber);
-	void obstaclePlaced(const CObstacleInstance & oi);
-
-	void gateStateChanged(const EGateState state);
-
-	void initStackProjectile(const CStack * stack);
-
-	const CGHeroInstance *currentHero() const;
-	InfoAboutHero enemyHero() const;
-
-	friend class CPlayerInterface;
-	friend class CButton;
-	friend class CInGameConsole;
-	friend class CStackQueue;
-	friend class CBattleResultWindow;
-	friend class CBattleHero;
-	friend class CEffectAnimation;
-	friend class CBattleStackAnimation;
-	friend class CReverseAnimation;
-	friend class CDefenceAnimation;
-	friend class CMovementAnimation;
-	friend class CMovementStartAnimation;
-	friend class CAttackAnimation;
-	friend class CMeleeAttackAnimation;
-	friend class CShootingAnimation;
-	friend class CCastAnimation;
-	friend class CClickableHex;
-};

+ 50 - 31
client/battle/CCreatureAnimation.cpp → client/battle/CreatureAnimation.cpp

@@ -8,12 +8,12 @@
  *
  */
 #include "StdInc.h"
-#include "CCreatureAnimation.h"
+#include "CreatureAnimation.h"
 
 #include "../../lib/CConfigHandler.h"
 #include "../../lib/CCreatureHandler.h"
 
-#include "../gui/SDL_Extensions.h"
+#include "../gui/Canvas.h"
 
 static const SDL_Color creatureBlueBorder = { 0, 255, 255, 255 };
 static const SDL_Color creatureGoldBorder = { 255, 255, 0, 255 };
@@ -34,13 +34,13 @@ SDL_Color AnimationControls::getNoBorder()
 	return creatureNoBorder;
 }
 
-std::shared_ptr<CCreatureAnimation> AnimationControls::getAnimation(const CCreature * creature)
+std::shared_ptr<CreatureAnimation> AnimationControls::getAnimation(const CCreature * creature)
 {
 	auto func = std::bind(&AnimationControls::getCreatureAnimationSpeed, creature, _1, _2);
-	return std::make_shared<CCreatureAnimation>(creature->animDefName, func);
+	return std::make_shared<CreatureAnimation>(creature->animDefName, func);
 }
 
-float AnimationControls::getCreatureAnimationSpeed(const CCreature * creature, const CCreatureAnimation * anim, size_t group)
+float AnimationControls::getCreatureAnimationSpeed(const CCreature * creature, const CreatureAnimation * anim, size_t group)
 {
 	CCreatureAnim::EAnimType type = CCreatureAnim::EAnimType(group);
 
@@ -113,6 +113,11 @@ float AnimationControls::getProjectileSpeed()
 	return static_cast<float>(settings["battle"]["animationSpeed"].Float() * 100);
 }
 
+float AnimationControls::getCatapultSpeed()
+{
+	return static_cast<float>(settings["battle"]["animationSpeed"].Float() * 20);
+}
+
 float AnimationControls::getSpellEffectSpeed()
 {
 	return static_cast<float>(settings["battle"]["animationSpeed"].Float() * 30);
@@ -128,12 +133,12 @@ float AnimationControls::getFlightDistance(const CCreature * creature)
 	return static_cast<float>(creature->animation.flightAnimationDistance * 200);
 }
 
-CCreatureAnim::EAnimType CCreatureAnimation::getType() const
+CCreatureAnim::EAnimType CreatureAnimation::getType() const
 {
 	return type;
 }
 
-void CCreatureAnimation::setType(CCreatureAnim::EAnimType type)
+void CreatureAnimation::setType(CCreatureAnim::EAnimType type)
 {
 	this->type = type;
 	currentFrame = 0;
@@ -142,7 +147,7 @@ void CCreatureAnimation::setType(CCreatureAnim::EAnimType type)
 	play();
 }
 
-void CCreatureAnimation::shiftColor(const ColorShifter* shifter)
+void CreatureAnimation::shiftColor(const ColorShifter* shifter)
 {
 	if(forward)
 		forward->shiftColor(shifter);
@@ -151,7 +156,7 @@ void CCreatureAnimation::shiftColor(const ColorShifter* shifter)
 		reverse->shiftColor(shifter);
 }
 
-CCreatureAnimation::CCreatureAnimation(const std::string & name_, TSpeedController controller)
+CreatureAnimation::CreatureAnimation(const std::string & name_, TSpeedController controller)
 	: name(name_),
 	  speed(0.1f),
 	  currentFrame(0),
@@ -198,7 +203,7 @@ CCreatureAnimation::CCreatureAnimation(const std::string & name_, TSpeedControll
 	play();
 }
 
-void CCreatureAnimation::endAnimation()
+void CreatureAnimation::endAnimation()
 {
 	once = false;
 	auto copy = onAnimationReset;
@@ -206,7 +211,7 @@ void CCreatureAnimation::endAnimation()
 	copy();
 }
 
-bool CCreatureAnimation::incrementFrame(float timePassed)
+bool CreatureAnimation::incrementFrame(float timePassed)
 {
 	elapsedTime += timePassed;
 	currentFrame += timePassed * speed;
@@ -231,27 +236,27 @@ bool CCreatureAnimation::incrementFrame(float timePassed)
 	return false;
 }
 
-void CCreatureAnimation::setBorderColor(SDL_Color palette)
+void CreatureAnimation::setBorderColor(SDL_Color palette)
 {
 	border = palette;
 }
 
-int CCreatureAnimation::getWidth() const
+int CreatureAnimation::getWidth() const
 {
 	return fullWidth;
 }
 
-int CCreatureAnimation::getHeight() const
+int CreatureAnimation::getHeight() const
 {
 	return fullHeight;
 }
 
-float CCreatureAnimation::getCurrentFrame() const
+float CreatureAnimation::getCurrentFrame() const
 {
 	return currentFrame;
 }
 
-void CCreatureAnimation::playOnce( CCreatureAnim::EAnimType type )
+void CreatureAnimation::playOnce( CCreatureAnim::EAnimType type )
 {
 	setType(type);
 	once = true;
@@ -289,20 +294,20 @@ static SDL_Color addColors(const SDL_Color & base, const SDL_Color & over)
 			);
 }
 
-void CCreatureAnimation::genBorderPalette(IImage::BorderPallete & target)
+void CreatureAnimation::genBorderPalette(IImage::BorderPallete & target)
 {
 	target[0] = genBorderColor(getBorderStrength(elapsedTime), border);
 	target[1] = addColors(genShadow(128), genBorderColor(getBorderStrength(elapsedTime), border));
 	target[2] = addColors(genShadow(64),  genBorderColor(getBorderStrength(elapsedTime), border));
 }
 
-void CCreatureAnimation::nextFrame(SDL_Surface * dest, bool attacker)
+void CreatureAnimation::nextFrame(Canvas & canvas, bool facingRight)
 {
 	size_t frame = static_cast<size_t>(floor(currentFrame));
 
 	std::shared_ptr<IImage> image;
 
-	if(attacker)
+	if(facingRight)
 		image = forward->getImage(frame, type);
 	else
 		image = reverse->getImage(frame, type);
@@ -314,49 +319,63 @@ void CCreatureAnimation::nextFrame(SDL_Surface * dest, bool attacker)
 
 		image->setBorderPallete(borderPallete);
 
-		image->draw(dest, pos.x, pos.y);
+		canvas.draw(image, pos.topLeft(), Rect(0, 0, pos.w, pos.h));
 	}
 }
 
-int CCreatureAnimation::framesInGroup(CCreatureAnim::EAnimType group) const
+int CreatureAnimation::framesInGroup(CCreatureAnim::EAnimType group) const
 {
 	return static_cast<int>(forward->size(group));
 }
 
-bool CCreatureAnimation::isDead() const
+bool CreatureAnimation::isDead() const
+{
+	return getType() == CCreatureAnim::DEAD
+		|| getType() == CCreatureAnim::DEAD_RANGED;
+}
+
+bool CreatureAnimation::isDying() const
+{
+	return getType() == CCreatureAnim::DEATH
+		|| getType() == CCreatureAnim::DEATH_RANGED;
+}
+
+bool CreatureAnimation::isDeadOrDying() const
 {
 	return getType() == CCreatureAnim::DEAD
-	    || getType() == CCreatureAnim::DEATH
-	    || getType() == CCreatureAnim::DEAD_RANGED
-	    || getType() == CCreatureAnim::DEATH_RANGED;
+		|| getType() == CCreatureAnim::DEATH
+		|| getType() == CCreatureAnim::DEAD_RANGED
+		|| getType() == CCreatureAnim::DEATH_RANGED;
 }
 
-bool CCreatureAnimation::isIdle() const
+bool CreatureAnimation::isIdle() const
 {
 	return getType() == CCreatureAnim::HOLDING
 	    || getType() == CCreatureAnim::MOUSEON;
 }
 
-bool CCreatureAnimation::isMoving() const
+bool CreatureAnimation::isMoving() const
 {
 	return getType() == CCreatureAnim::MOVE_START
 	    || getType() == CCreatureAnim::MOVING
-	    || getType() == CCreatureAnim::MOVE_END;
+		|| getType() == CCreatureAnim::MOVE_END
+		|| getType() == CCreatureAnim::TURN_L
+		|| getType() == CCreatureAnim::TURN_R;
 }
 
-bool CCreatureAnimation::isShooting() const
+bool CreatureAnimation::isShooting() const
 {
 	return getType() == CCreatureAnim::SHOOT_UP
 	    || getType() == CCreatureAnim::SHOOT_FRONT
 	    || getType() == CCreatureAnim::SHOOT_DOWN;
 }
 
-void CCreatureAnimation::pause()
+void CreatureAnimation::pause()
 {
 	speed = 0;
 }
 
-void CCreatureAnimation::play()
+void CreatureAnimation::play()
 {
 	//logAnim->trace("Play %s group %d at %d:%d", name, static_cast<int>(getType()), pos.x, pos.y);
     speed = 0;

+ 45 - 25
client/battle/CCreatureAnimation.h → client/battle/CreatureAnimation.h

@@ -14,7 +14,8 @@
 #include "../gui/CAnimation.h"
 
 class CIntObject;
-class CCreatureAnimation;
+class CreatureAnimation;
+class Canvas;
 
 /// Namespace for some common controls of animations
 namespace AnimationControls
@@ -25,15 +26,18 @@ namespace AnimationControls
 	SDL_Color getNoBorder();
 
 	/// creates animation object with preset speed control
-	std::shared_ptr<CCreatureAnimation> getAnimation(const CCreature * creature);
+	std::shared_ptr<CreatureAnimation> 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);
+	float getCreatureAnimationSpeed(const CCreature * creature, const CreatureAnimation * anim, size_t groupID);
 
 	/// returns how far projectile should move each frame
 	/// TODO: make it time-based
 	float getProjectileSpeed();
 
+	/// returns speed of catapult projectile
+	float getCatapultSpeed();
+
 	/// returns speed of any spell effects, including any special effects like morale (in frames per second)
 	float getSpellEffectSpeed();
 
@@ -46,44 +50,51 @@ namespace AnimationControls
 
 /// Class which manages animations of creatures/units inside battles
 /// TODO: split into constant image container and class that does *control* of animation
-class CCreatureAnimation : public CIntObject
+class CreatureAnimation : public CIntObject
 {
 public:
-	typedef std::function<float(CCreatureAnimation *, size_t)> TSpeedController;
+	typedef std::function<float(CreatureAnimation *, size_t)> TSpeedController;
 
 private:
 	std::string name;
+
+	/// animation for rendering stack in default orientation - facing right
 	std::shared_ptr<CAnimation> forward;
+
+	/// animation that has all its frames flipped for rendering stack facing left
 	std::shared_ptr<CAnimation> reverse;
 
 	int fullWidth;
 	int fullHeight;
 
-	// speed of animation, measure in frames per second
+	/// speed of animation, measure in frames per second
 	float speed;
 
-	// currently displayed frame. Float to allow H3-style animations where frames
-	// don't display for integer number of frames
+	/// currently displayed frame. Float to allow H3-style animations where frames
+	/// don't display for integer number of frames
 	float currentFrame;
-	// cumulative, real-time duration of animation. Used for effects like selection border
+
+	/// cumulative, real-time duration of animation. Used for effects like selection border
 	float elapsedTime;
-	CCreatureAnim::EAnimType type; //type of animation being displayed
 
-	// border color, disabled if alpha = 0
+	///type of animation being displayed
+	CCreatureAnim::EAnimType type;
+
+	/// border color, disabled if alpha = 0
 	SDL_Color border;
 
 	TSpeedController speedController;
 
-	bool once; // animation will be played once and the reset to idling
+	/// animation will be played once and the reset to idling
+	bool once;
 
 	void endAnimation();
 
-
 	void genBorderPalette(IImage::BorderPallete & target);
 public:
 
-	// function(s) that will be called when animation ends, after reset to 1st frame
-	// NOTE that these function will be fired only once
+	/// function(s) that will be called when animation ends, after reset to 1st frame
+	/// NOTE that these functions will be fired only once
 	CFunctionList<void()> onAnimationReset;
 
 	int getWidth() const;
@@ -93,31 +104,40 @@ public:
 	/// name - path to .def file, relative to SPRITES/ directory
 	/// controller - function that will return for how long *each* frame
 	/// in specified group of animation should be played, measured in seconds
-	CCreatureAnimation(const std::string & name_, TSpeedController speedController);
+	CreatureAnimation(const std::string & name_, TSpeedController speedController);
 
-	void setType(CCreatureAnim::EAnimType type); //sets type of animation and cleares framecount
-	CCreatureAnim::EAnimType getType() const; //returns type of animation
+	/// sets type of animation and resets framecount
+	void setType(CCreatureAnim::EAnimType type);
 
-	void nextFrame(SDL_Surface * dest, bool attacker);
+	/// returns currently rendered type of animation
+	CCreatureAnim::EAnimType getType() const;
 
-	// should be called every frame, return true when animation was reset to beginning
+	void nextFrame(Canvas & canvas, bool facingRight);
+
+	/// should be called every frame, return true when animation was reset to beginning
 	bool incrementFrame(float timePassed);
+
 	void setBorderColor(SDL_Color palette);
 
-	// tint color effect
+	/// apply color tint effect
 	void shiftColor(const ColorShifter * shifter);
 
-	float getCurrentFrame() const; // Gets the current frame ID relative to frame group.
+	/// Gets the current frame ID within current group.
+	float getCurrentFrame() const;
 
-	void playOnce(CCreatureAnim::EAnimType type); //plays once given stage of animation, then resets to 2
+	/// plays once given type of animation, then resets to idle
+	void playOnce(CCreatureAnim::EAnimType type);
 
-	int framesInGroup(CCreatureAnim::EAnimType group) const;
+	/// returns number of frames in selected animation type
+	int framesInGroup(CCreatureAnim::EAnimType type) const;
 
 	void pause();
 	void play();
 
-	//helpers. TODO: move them somewhere else
+	/// helpers to classify current type of animation
 	bool isDead() const;
+	bool isDying() const;
+	bool isDeadOrDying() const;
 	bool isIdle() const;
 	bool isMoving() const;
 	bool isShooting() const;

+ 24 - 10
client/gui/CAnimation.cpp

@@ -92,14 +92,14 @@ public:
 	// Keep the original palette, in order to do color switching operation
 	void savePalette();
 
-	void draw(SDL_Surface * where, int posX=0, int posY=0, Rect *src=nullptr, ui8 alpha=255) const override;
-	void draw(SDL_Surface * where, SDL_Rect * dest, SDL_Rect * src, ui8 alpha=255) const override;
+	void draw(SDL_Surface * where, int posX=0, int posY=0, const Rect *src=nullptr, ui8 alpha=255) const override;
+	void draw(SDL_Surface * where, const SDL_Rect * dest, const SDL_Rect * src, ui8 alpha=255) const override;
 	std::shared_ptr<IImage> scaleFast(float scale) const override;
 	void exportBitmap(const boost::filesystem::path & path) const override;
 	void playerColored(PlayerColor player) override;
 	void setFlagColor(PlayerColor player) override;
-	int width() const override;
-	int height() const override;
+	bool isTransparent(const Point & coords) const override;
+	Point dimensions() const override;
 
 	void horizontalFlip() override;
 	void verticalFlip() override;
@@ -134,6 +134,11 @@ public:
 	~SDLImageLoader();
 };
 
+std::shared_ptr<IImage> IImage::createFromFile( const std::string & path )
+{
+	return std::shared_ptr<IImage>(new SDLImage(path));
+}
+
 // Extremely simple file cache. TODO: smarter, more general solution
 class CFileCache
 {
@@ -554,6 +559,15 @@ SDLImageLoader::~SDLImageLoader()
 IImage::IImage() = default;
 IImage::~IImage() = default;
 
+int IImage::width() const
+{
+	return dimensions().x;
+}
+
+int IImage::height() const
+{
+	return dimensions().y;
+}
 
 SDLImage::SDLImage(CDefFile * data, size_t frame, size_t group)
 	: surf(nullptr),
@@ -640,7 +654,7 @@ SDLImage::SDLImage(std::string filename)
 	}
 }
 
-void SDLImage::draw(SDL_Surface *where, int posX, int posY, Rect *src, ui8 alpha) const
+void SDLImage::draw(SDL_Surface *where, int posX, int posY, const Rect *src, ui8 alpha) const
 {
 	if(!surf)
 		return;
@@ -650,7 +664,7 @@ void SDLImage::draw(SDL_Surface *where, int posX, int posY, Rect *src, ui8 alpha
 	draw(where, &destRect, src);
 }
 
-void SDLImage::draw(SDL_Surface* where, SDL_Rect* dest, SDL_Rect* src, ui8 alpha) const
+void SDLImage::draw(SDL_Surface* where, const SDL_Rect* dest, const SDL_Rect* src, ui8 alpha) const
 {
 	if (!surf)
 		return;
@@ -730,14 +744,14 @@ void SDLImage::setFlagColor(PlayerColor player)
 		CSDL_Ext::setPlayerColor(surf, player);
 }
 
-int SDLImage::width() const
+bool SDLImage::isTransparent(const Point & coords) const
 {
-	return fullSize.x;
+	return CSDL_Ext::isTransparent(surf, coords.x, coords.y);
 }
 
-int SDLImage::height() const
+Point SDLImage::dimensions() const
 {
-	return fullSize.y;
+	return fullSize;
 }
 
 void SDLImage::horizontalFlip()

+ 11 - 4
client/gui/CAnimation.h

@@ -40,8 +40,8 @@ public:
 	using BorderPallete = std::array<SDL_Color, 3>;
 
 	//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, SDL_Rect * dest, SDL_Rect * src, ui8 alpha = 255) const = 0;
+	virtual void draw(SDL_Surface * where, int posX = 0, int posY = 0, const Rect * src = nullptr, ui8 alpha = 255) const=0;
+	virtual void draw(SDL_Surface * where, const SDL_Rect * dest, const SDL_Rect * src, ui8 alpha = 255) const = 0;
 
 	virtual std::shared_ptr<IImage> scaleFast(float scale) const = 0;
 
@@ -53,8 +53,12 @@ public:
 	//set special color for flag
 	virtual void setFlagColor(PlayerColor player)=0;
 
-	virtual int width() const=0;
-	virtual int height() const=0;
+	//test transparency of specific pixel
+	virtual bool isTransparent(const Point & coords) const = 0;
+
+	virtual Point dimensions() const = 0;
+	int width() const;
+	int height() const;
 
 	//only indexed bitmaps, 16 colors maximum
 	virtual void shiftPalette(int from, int howMany) = 0;
@@ -69,6 +73,9 @@ public:
 
 	IImage();
 	virtual ~IImage();
+
+	/// loads image from specified file. Returns 0-sized images on failure
+	static std::shared_ptr<IImage> createFromFile( const std::string & path );
 };
 
 /// Class for handling animation

+ 1 - 1
client/gui/CGuiHandler.cpp

@@ -21,7 +21,7 @@
 #include "../../lib/CConfigHandler.h"
 #include "../CMT.h"
 #include "../CPlayerInterface.h"
-#include "../battle/CBattleInterface.h"
+#include "../battle/BattleInterface.h"
 
 extern std::queue<SDL_Event> SDLEventsQueue;
 extern boost::mutex eventsM;

+ 2 - 2
client/gui/CGuiHandler.h

@@ -20,7 +20,7 @@ template <typename T> struct CondSh;
 VCMI_LIB_NAMESPACE_END
 
 class CFramerateManager;
-class CGStatusBar;
+class IStatusBar;
 class CIntObject;
 class IUpdateable;
 class IShowActivatable;
@@ -65,7 +65,7 @@ class CGuiHandler
 public:
 	CFramerateManager * mainFPSmng; //to keep const framerate
 	std::list<std::shared_ptr<IShowActivatable>> listInt; //list of interfaces - front=foreground; back = background (includes adventure map, window interfaces, all kind of active dialogs, and so on)
-	std::shared_ptr<CGStatusBar> statusbar;
+	std::shared_ptr<IStatusBar> statusbar;
 
 private:
 	std::vector<std::shared_ptr<IShowActivatable>> disposed;

+ 3 - 0
client/gui/CIntObject.cpp

@@ -373,3 +373,6 @@ void WindowBase::close()
 		logGlobal->error("Only top interface must be closed");
 	GH.popInts(1);
 }
+
+IStatusBar::~IStatusBar()
+{}

+ 22 - 2
client/gui/CIntObject.h

@@ -165,8 +165,6 @@ 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
@@ -217,3 +215,25 @@ public:
 protected:
 	void close();
 };
+
+class IStatusBar
+{
+public:
+	virtual ~IStatusBar();
+
+	/// set current text for the status bar
+	virtual void write(const std::string & text) = 0;
+
+	/// remove any current text from the status bar
+	virtual void clear() = 0;
+
+	/// remove text from status bar if current text matches tested text
+	virtual void clearIfMatching(const std::string & testedText) = 0;
+
+	/// enables mode for entering text instead of showing hover text
+	virtual void setEnteringMode(bool on) = 0;
+
+	/// overrides hover text from controls with text entered into in-game console (for chat/cheats)
+	virtual void setEnteredText(const std::string & text) = 0;
+
+};

+ 84 - 0
client/gui/Canvas.cpp

@@ -0,0 +1,84 @@
+/*
+ * Canvas.cpp, part of VCMI engine
+ *
+ * Authors: listed in file AUTHORS in main folder
+ *
+ * License: GNU General Public License v2.0 or later
+ * Full text of license available in license.txt file, in main folder
+ *
+ */
+#include "StdInc.h"
+#include "Canvas.h"
+
+#include "SDL_Extensions.h"
+#include "Geometries.h"
+#include "CAnimation.h"
+
+#include "../Graphics.h"
+
+Canvas::Canvas(SDL_Surface * surface):
+	surface(surface)
+{
+	surface->refcount++;
+}
+
+Canvas::Canvas(Canvas & other):
+	surface(other.surface)
+{
+	surface->refcount++;
+}
+
+Canvas::Canvas(const Point & size)
+{
+	surface = CSDL_Ext::newSurface(size.x, size.y);
+}
+
+Canvas::~Canvas()
+{
+	SDL_FreeSurface(surface);
+}
+
+void Canvas::draw(std::shared_ptr<IImage> image, const Point & pos)
+{
+	assert(image);
+	if (image)
+		image->draw(surface, pos.x, pos.y);
+}
+
+void Canvas::draw(std::shared_ptr<IImage> image, const Point & pos, const Rect & sourceRect)
+{
+	assert(image);
+	if (image)
+		image->draw(surface, pos.x, pos.y, &sourceRect);
+}
+
+void Canvas::draw(Canvas & image, const Point & pos)
+{
+	blitAt(image.surface, pos.x, pos.y, surface);
+}
+
+void Canvas::drawLine(const Point & from, const Point & dest, const SDL_Color & colorFrom, const SDL_Color & colorDest)
+{
+	CSDL_Ext::drawLine(surface, from.x, from.y, dest.x, dest.y, colorFrom, colorDest);
+}
+
+void Canvas::drawText(const Point & position, const EFonts & font, const SDL_Color & colorDest, ETextAlignment alignment, const std::string & text )
+{
+	switch (alignment)
+	{
+	case ETextAlignment::TOPLEFT:      return graphics->fonts[font]->renderTextLeft  (surface, text, colorDest, position);
+	case ETextAlignment::CENTER:       return graphics->fonts[font]->renderTextCenter(surface, text, colorDest, position);
+	case ETextAlignment::BOTTOMRIGHT:  return graphics->fonts[font]->renderTextRight (surface, text, colorDest, position);
+	}
+}
+
+void Canvas::drawText(const Point & position, const EFonts & font, const SDL_Color & colorDest, ETextAlignment alignment, const std::vector<std::string> & text )
+{
+	switch (alignment)
+	{
+	case ETextAlignment::TOPLEFT:      return graphics->fonts[font]->renderTextLinesLeft  (surface, text, colorDest, position);
+	case ETextAlignment::CENTER:       return graphics->fonts[font]->renderTextLinesCenter(surface, text, colorDest, position);
+	case ETextAlignment::BOTTOMRIGHT:  return graphics->fonts[font]->renderTextLinesRight (surface, text, colorDest, position);
+	}
+}
+

+ 55 - 0
client/gui/Canvas.h

@@ -0,0 +1,55 @@
+/*
+ * Canvas.h, part of VCMI engine
+ *
+ * Authors: listed in file AUTHORS in main folder
+ *
+ * License: GNU General Public License v2.0 or later
+ * Full text of license available in license.txt file, in main folder
+ *
+ */
+#pragma once
+
+#include "Geometries.h"
+
+struct SDL_Color;
+struct SDL_Surface;
+class IImage;
+enum EFonts : int;
+
+/// Class that represents surface for drawing on
+class Canvas
+{
+	SDL_Surface * surface;
+
+	Canvas & operator = (Canvas & other) = delete;
+public:
+
+	/// constructs canvas using existing surface. Caller maintains ownership on the surface
+	Canvas(SDL_Surface * surface);
+
+	/// copy contructor
+	Canvas(Canvas & other);
+
+	/// constructs canvas of specified size
+	Canvas(const Point & size);
+
+	~Canvas();
+
+	/// renders image onto this canvas at specified position
+	void draw(std::shared_ptr<IImage> image, const Point & pos);
+
+	/// renders section of image bounded by sourceRect at specified position
+	void draw(std::shared_ptr<IImage> image, const Point & pos, const Rect & sourceRect);
+
+	/// renders another canvas onto this canvas
+	void draw(Canvas & image, const Point & pos);
+
+	/// renders continuous, 1-pixel wide line with color gradient
+	void drawLine(const Point & from, const Point & dest, const SDL_Color & colorFrom, const SDL_Color & colorDest);
+
+	/// renders single line of text with specified parameters
+	void drawText(const Point & position, const EFonts & font, const SDL_Color & colorDest, ETextAlignment alignment, const std::string & text );
+
+	/// renders multiple lines of text with specified parameters
+	void drawText(const Point & position, const EFonts & font, const SDL_Color & colorDest, ETextAlignment alignment, const std::vector<std::string> & text );
+};

+ 2 - 0
client/gui/Geometries.h

@@ -12,6 +12,8 @@
 #include <SDL_video.h>
 #include "../../lib/int3.h"
 
+enum class ETextAlignment {TOPLEFT, CENTER, BOTTOMRIGHT};
+
 struct SDL_MouseMotionEvent;
 
 // A point with x/y coordinate, used mostly for graphic rendering

+ 10 - 34
client/gui/SDL_Extensions.cpp

@@ -188,24 +188,6 @@ Uint32 CSDL_Ext::SDL_GetPixel(SDL_Surface *surface, const int & x, const int & y
 	}
 }
 
-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}
-	};
-
-
-	for (size_t i=0; i< ARRAY_COUNT(colors); i++ )
-	{
-		SDL_Color & palColor = src->format->palette->colors[i];
-		palColor = colors[i];
-	}
-	SDL_SetColorKey(src, SDL_TRUE, 0);
-}
-
 template<int bpp>
 int CSDL_Ext::blit8bppAlphaTo24bppT(const SDL_Surface * src, const SDL_Rect * srcRect, SDL_Surface * dst, SDL_Rect * dstRect)
 {
@@ -362,23 +344,17 @@ void CSDL_Ext::update(SDL_Surface * what)
 		logGlobal->error("%s SDL_UpdateTexture %s", __FUNCTION__, SDL_GetError());
 }
 
-template<typename Int>
-Int lerp(Int a, Int b, float f)
-{
-	return a + std::round((b - a) * f);
-}
-
 static void drawLineX(SDL_Surface * sur, int x1, int y1, int x2, int y2, const SDL_Color & color1, const SDL_Color & color2)
 {
 	for(int x = x1; x <= x2; x++)
 	{
 		float f = float(x - x1) / float(x2 - x1);
-		int y = lerp(y1, y2, f);
+		int y = CSDL_Ext::lerp(y1, y2, f);
 
-		uint8_t r = lerp(color1.r, color2.r, f);
-		uint8_t g = lerp(color1.g, color2.g, f);
-		uint8_t b = lerp(color1.b, color2.b, f);
-		uint8_t a = lerp(color1.a, color2.a, f);
+		uint8_t r = CSDL_Ext::lerp(color1.r, color2.r, f);
+		uint8_t g = CSDL_Ext::lerp(color1.g, color2.g, f);
+		uint8_t b = CSDL_Ext::lerp(color1.b, color2.b, f);
+		uint8_t a = CSDL_Ext::lerp(color1.a, color2.a, f);
 
 		Uint8 *p = CSDL_Ext::getPxPtr(sur, x, y);
 		ColorPutter<4, 0>::PutColor(p, r,g,b,a);
@@ -390,12 +366,12 @@ static void drawLineY(SDL_Surface * sur, int x1, int y1, int x2, int y2, const S
 	for(int y = y1; y <= y2; y++)
 	{
 		float f = float(y - y1) / float(y2 - y1);
-		int x = lerp(x1, x2, f);
+		int x = CSDL_Ext::lerp(x1, x2, f);
 
-		uint8_t r = lerp(color1.r, color2.r, f);
-		uint8_t g = lerp(color1.g, color2.g, f);
-		uint8_t b = lerp(color1.b, color2.b, f);
-		uint8_t a = lerp(color1.a, color2.a, f);
+		uint8_t r = CSDL_Ext::lerp(color1.r, color2.r, f);
+		uint8_t g = CSDL_Ext::lerp(color1.g, color2.g, f);
+		uint8_t b = CSDL_Ext::lerp(color1.b, color2.b, f);
+		uint8_t a = CSDL_Ext::lerp(color1.a, color2.a, f);
 
 		Uint8 *p = CSDL_Ext::getPxPtr(sur, x, y);
 		ColorPutter<4, 0>::PutColor(p, r,g,b,a);

+ 39 - 20
client/gui/SDL_Extensions.h

@@ -49,6 +49,12 @@ inline bool isShiftKeyDown()
 }
 namespace CSDL_Ext
 {
+	template<typename Int>
+	Int lerp(Int a, Int b, float f)
+	{
+		return a + std::round((b - a) * f);
+	}
+
 	//todo: should this better be assignment operator?
 	STRONG_INLINE void colorAssign(SDL_Color & dest, const SDL_Color & source)
 	{
@@ -152,40 +158,54 @@ struct ColorPutter
 
 typedef void (*BlitterWithRotationVal)(SDL_Surface *src,SDL_Rect srcRect, SDL_Surface * dst, SDL_Rect dstRect, ui8 rotation);
 
+/// Base class for applying palette transformation on images
 class ColorShifter
 {
 public:
-	virtual ~ColorShifter() = default;
-	virtual SDL_Color shiftColor(SDL_Color clr) const = 0;
+	~ColorShifter() = default;
+	virtual SDL_Color shiftColor(SDL_Color input) const = 0;
 };
 
-class ColorShifterLightBlue : public ColorShifter
+/// Generic class for palette transformation
+/// formula:
+/// result = input * factor + added
+class ColorShifterMultiplyAndAdd : public ColorShifter
 {
-public:
-	SDL_Color shiftColor(SDL_Color clr) const override
-	{
-		clr.b = clr.b + (255 - clr.b) / 2;
-		return clr;
-	}
-};
+	SDL_Color added;
+	SDL_Color factor;
 
-class ColorShifterDeepBlue : public ColorShifter
-{
 public:
-	SDL_Color shiftColor(SDL_Color clr) const override
+	ColorShifterMultiplyAndAdd(SDL_Color factor, SDL_Color added) :
+		factor(factor),
+		added(added)
+	{}
+
+	SDL_Color shiftColor(SDL_Color input) const override
 	{
-		clr.b = 255;
-		return clr;
+		return {
+			uint8_t(std::min(255.f, std::round(input.r * float(factor.r) / 255.f + added.r))),
+			uint8_t(std::min(255.f, std::round(input.g * float(factor.g) / 255.f + added.g))),
+			uint8_t(std::min(255.f, std::round(input.b * float(factor.b) / 255.f + added.b))),
+			uint8_t(std::min(255.f, std::round(input.a * float(factor.a) / 255.f + added.a)))
+		};
 	}
 };
 
-class ColorShifterDeepRed : public ColorShifter
+/// Color shifter that allows to specify color to be excempt from changes
+class ColorShifterMultiplyAndAddExcept : public ColorShifterMultiplyAndAdd
 {
+	SDL_Color ignored;
 public:
-	SDL_Color shiftColor(SDL_Color clr) const override
+	ColorShifterMultiplyAndAddExcept(SDL_Color factor, SDL_Color added, SDL_Color ignored) :
+		ColorShifterMultiplyAndAdd(factor, added),
+		ignored(ignored)
+	{}
+
+	SDL_Color shiftColor(SDL_Color input) const override
 	{
-		clr.r = 255;
-		return clr;
+		if ( input.r == ignored.r && input.g == ignored.g && input.b == ignored.b && input.a == ignored.a)
+			return input;
+		return ColorShifterMultiplyAndAdd::shiftColor(input);
 	}
 };
 
@@ -222,7 +242,6 @@ namespace CSDL_Ext
 	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);

+ 8 - 9
client/lobby/CBonusSelection.cpp

@@ -18,7 +18,6 @@
 
 #include "../CGameInfo.h"
 #include "../CMessage.h"
-#include "../CBitmapHandler.h"
 #include "../CMusicHandler.h"
 #include "../CVideoHandler.h"
 #include "../CPlayerInterface.h"
@@ -76,25 +75,25 @@ CBonusSelection::CBonusSelection()
 	buttonRestart = std::make_shared<CButton>(Point(475, 536), "CBRESTB.DEF", CButton::tooltip(), std::bind(&CBonusSelection::restartMap, this), SDLK_RETURN);
 	buttonBack = std::make_shared<CButton>(Point(624, 536), "CBCANCB.DEF", CButton::tooltip(), std::bind(&CBonusSelection::goBack, this), SDLK_ESCAPE);
 
-	campaignName = std::make_shared<CLabel>(481, 28, FONT_BIG, EAlignment::TOPLEFT, Colors::YELLOW, CSH->si->getCampaignName());
+	campaignName = std::make_shared<CLabel>(481, 28, FONT_BIG, ETextAlignment::TOPLEFT, Colors::YELLOW, CSH->si->getCampaignName());
 
 	iconsMapSizes = std::make_shared<CAnimImage>("SCNRMPSZ", 4, 0, 735, 26);
 
-	labelCampaignDescription = std::make_shared<CLabel>(481, 63, FONT_SMALL, EAlignment::TOPLEFT, Colors::YELLOW, CGI->generaltexth->allTexts[38]);
+	labelCampaignDescription = std::make_shared<CLabel>(481, 63, FONT_SMALL, ETextAlignment::TOPLEFT, Colors::YELLOW, CGI->generaltexth->allTexts[38]);
 	campaignDescription = std::make_shared<CTextBox>(getCampaign()->camp->header.description, Rect(480, 86, 286, 117), 1);
 
-	mapName = std::make_shared<CLabel>(481, 219, FONT_BIG, EAlignment::TOPLEFT, Colors::YELLOW, CSH->mi->getName());
-	labelMapDescription = std::make_shared<CLabel>(481, 253, FONT_SMALL, EAlignment::TOPLEFT, Colors::YELLOW, CGI->generaltexth->allTexts[496]);
+	mapName = std::make_shared<CLabel>(481, 219, FONT_BIG, ETextAlignment::TOPLEFT, Colors::YELLOW, CSH->mi->getName());
+	labelMapDescription = std::make_shared<CLabel>(481, 253, FONT_SMALL, ETextAlignment::TOPLEFT, Colors::YELLOW, CGI->generaltexth->allTexts[496]);
 	mapDescription = std::make_shared<CTextBox>("", Rect(480, 280, 286, 117), 1);
 
-	labelChooseBonus = std::make_shared<CLabel>(511, 432, FONT_SMALL, EAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[71]);
+	labelChooseBonus = std::make_shared<CLabel>(511, 432, FONT_SMALL, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[71]);
 	groupBonuses = std::make_shared<CToggleGroup>(std::bind(&IServerAPI::setCampaignBonus, CSH, _1));
 
 	flagbox = std::make_shared<CFlagBox>(Rect(486, 407, 335, 23));
 
 	std::vector<std::string> difficulty;
 	boost::split(difficulty, CGI->generaltexth->allTexts[492], boost::is_any_of(" "));
-	labelDifficulty = std::make_shared<CLabel>(689, 432, FONT_MEDIUM, EAlignment::TOPLEFT, Colors::WHITE, difficulty.back());
+	labelDifficulty = std::make_shared<CLabel>(689, 432, FONT_MEDIUM, ETextAlignment::TOPLEFT, Colors::WHITE, difficulty.back());
 
 	for(size_t b = 0; b < difficultyIcons.size(); ++b)
 	{
@@ -529,7 +528,7 @@ void CBonusSelection::CRegion::clickLeft(tribool down, bool previousState)
 	if(indeterminate(down))
 		return;
 
-	if(!down && selectable && !CSDL_Ext::isTransparent(*graphicsNotSelected, GH.current->motion.x - pos.x, GH.current->motion.y - pos.y))
+	if(!down && selectable && !CSDL_Ext::isTransparent(graphicsNotSelected->getSurface(), GH.current->motion.x - pos.x, GH.current->motion.y - pos.y))
 	{
 		CSH->setCampaignMap(idOfMapAndRegion);
 	}
@@ -539,7 +538,7 @@ void CBonusSelection::CRegion::clickRight(tribool down, bool previousState)
 {
 	// FIXME: For some reason "down" is only ever contain indeterminate_value
 	auto text = CSH->si->campState->camp->scenarios[idOfMapAndRegion].regionText;
-	if(!CSDL_Ext::isTransparent(*graphicsNotSelected, GH.current->motion.x - pos.x, GH.current->motion.y - pos.y) && text.size())
+	if(!CSDL_Ext::isTransparent(graphicsNotSelected->getSurface(), GH.current->motion.x - pos.x, GH.current->motion.y - pos.y) && text.size())
 	{
 		CRClickPopup::createAndPush(text);
 	}

+ 22 - 23
client/lobby/CSelectionBase.cpp

@@ -21,7 +21,6 @@
 #include "../CGameInfo.h"
 #include "../CPlayerInterface.h"
 #include "../CMessage.h"
-#include "../CBitmapHandler.h"
 #include "../CMusicHandler.h"
 #include "../CVideoHandler.h"
 #include "../CPlayerInterface.h"
@@ -118,8 +117,8 @@ InfoCard::InfoCard()
 	pos.x += 393;
 	pos.y += 6;
 
-	labelSaveDate = std::make_shared<CLabel>(158, 19, FONT_SMALL, TOPLEFT, Colors::WHITE);
-	mapName = std::make_shared<CLabel>(26, 39, FONT_BIG, TOPLEFT, Colors::YELLOW);
+	labelSaveDate = std::make_shared<CLabel>(158, 19, FONT_SMALL, ETextAlignment::TOPLEFT, Colors::WHITE);
+	mapName = std::make_shared<CLabel>(26, 39, FONT_BIG, ETextAlignment::TOPLEFT, Colors::YELLOW);
 	Rect descriptionRect(26, 149, 320, 115);
 	mapDescription = std::make_shared<CTextBox>("", descriptionRect, 1);
 	playerListBg = std::make_shared<CPicture>("CHATPLUG.bmp", 16, 276);
@@ -127,7 +126,7 @@ InfoCard::InfoCard()
 
 	if(SEL->screenType == ESelectionScreen::campaignList)
 	{
-		labelCampaignDescription = std::make_shared<CLabel>(26, 132, FONT_SMALL, TOPLEFT, Colors::YELLOW, CGI->generaltexth->allTexts[38]);
+		labelCampaignDescription = std::make_shared<CLabel>(26, 132, FONT_SMALL, ETextAlignment::TOPLEFT, Colors::YELLOW, CGI->generaltexth->allTexts[38]);
 	}
 	else
 	{
@@ -155,24 +154,24 @@ InfoCard::InfoCard()
 		}
 
 		flagbox = std::make_shared<CFlagBox>(Rect(24, 400, 335, 23));
-		labelMapDiff = std::make_shared<CLabel>(33, 430, FONT_SMALL, TOPLEFT, Colors::YELLOW, CGI->generaltexth->allTexts[494]);
-		labelPlayerDifficulty = std::make_shared<CLabel>(133, 430, FONT_SMALL, TOPLEFT, Colors::YELLOW, CGI->generaltexth->allTexts[492] + ":");
-		labelRating = std::make_shared<CLabel>(290, 430, FONT_SMALL, TOPLEFT, Colors::YELLOW, CGI->generaltexth->allTexts[218] + ":");
-		labelScenarioName = std::make_shared<CLabel>(26, 22, FONT_SMALL, TOPLEFT, Colors::YELLOW, CGI->generaltexth->allTexts[495]);
-		labelScenarioDescription = std::make_shared<CLabel>(26, 132, FONT_SMALL, TOPLEFT, Colors::YELLOW, CGI->generaltexth->allTexts[496]);
-		labelVictoryCondition = std::make_shared<CLabel>(26, 283, FONT_SMALL, TOPLEFT, Colors::YELLOW, CGI->generaltexth->allTexts[497]);
-		labelLossCondition = std::make_shared<CLabel>(26, 339, FONT_SMALL, TOPLEFT, Colors::YELLOW, CGI->generaltexth->allTexts[498]);
+		labelMapDiff = std::make_shared<CLabel>(33, 430, FONT_SMALL, ETextAlignment::TOPLEFT, Colors::YELLOW, CGI->generaltexth->allTexts[494]);
+		labelPlayerDifficulty = std::make_shared<CLabel>(133, 430, FONT_SMALL, ETextAlignment::TOPLEFT, Colors::YELLOW, CGI->generaltexth->allTexts[492] + ":");
+		labelRating = std::make_shared<CLabel>(290, 430, FONT_SMALL, ETextAlignment::TOPLEFT, Colors::YELLOW, CGI->generaltexth->allTexts[218] + ":");
+		labelScenarioName = std::make_shared<CLabel>(26, 22, FONT_SMALL, ETextAlignment::TOPLEFT, Colors::YELLOW, CGI->generaltexth->allTexts[495]);
+		labelScenarioDescription = std::make_shared<CLabel>(26, 132, FONT_SMALL, ETextAlignment::TOPLEFT, Colors::YELLOW, CGI->generaltexth->allTexts[496]);
+		labelVictoryCondition = std::make_shared<CLabel>(26, 283, FONT_SMALL, ETextAlignment::TOPLEFT, Colors::YELLOW, CGI->generaltexth->allTexts[497]);
+		labelLossCondition = std::make_shared<CLabel>(26, 339, FONT_SMALL, ETextAlignment::TOPLEFT, Colors::YELLOW, CGI->generaltexth->allTexts[498]);
 		iconsVictoryCondition = std::make_shared<CAnimImage>("SCNRVICT", 0, 0, 24, 302);
 		iconsLossCondition = std::make_shared<CAnimImage>("SCNRLOSS", 0, 0, 24, 359);
 
-		labelVictoryConditionText = std::make_shared<CLabel>(60, 307, FONT_SMALL, TOPLEFT, Colors::WHITE);
-		labelLossConditionText = std::make_shared<CLabel>(60, 366, FONT_SMALL, TOPLEFT, Colors::WHITE);
+		labelVictoryConditionText = std::make_shared<CLabel>(60, 307, FONT_SMALL, ETextAlignment::TOPLEFT, Colors::WHITE);
+		labelLossConditionText = std::make_shared<CLabel>(60, 366, FONT_SMALL, ETextAlignment::TOPLEFT, Colors::WHITE);
 
-		labelDifficulty = std::make_shared<CLabel>(62, 472, FONT_SMALL, CENTER, Colors::WHITE);
-		labelDifficultyPercent = std::make_shared<CLabel>(311, 472, FONT_SMALL, CENTER, Colors::WHITE);
+		labelDifficulty = std::make_shared<CLabel>(62, 472, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
+		labelDifficultyPercent = std::make_shared<CLabel>(311, 472, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
 
-		labelGroupPlayersAssigned = std::make_shared<CLabelGroup>(FONT_SMALL, TOPLEFT, Colors::WHITE);
-		labelGroupPlayersUnassigned = std::make_shared<CLabelGroup>(FONT_SMALL, TOPLEFT, Colors::WHITE);
+		labelGroupPlayersAssigned = std::make_shared<CLabelGroup>(FONT_SMALL, ETextAlignment::TOPLEFT, Colors::WHITE);
+		labelGroupPlayersUnassigned = std::make_shared<CLabelGroup>(FONT_SMALL, ETextAlignment::TOPLEFT, Colors::WHITE);
 		disableLabelRedraws();
 	}
 	setChat(false);
@@ -220,8 +219,8 @@ void InfoCard::changeSelection()
 
 	OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
 	// FIXME: We recreate them each time because CLabelGroup don't use smart pointers
-	labelGroupPlayersAssigned = std::make_shared<CLabelGroup>(FONT_SMALL, TOPLEFT, Colors::WHITE);
-	labelGroupPlayersUnassigned = std::make_shared<CLabelGroup>(FONT_SMALL, TOPLEFT, Colors::WHITE);
+	labelGroupPlayersAssigned = std::make_shared<CLabelGroup>(FONT_SMALL, ETextAlignment::TOPLEFT, Colors::WHITE);
+	labelGroupPlayersUnassigned = std::make_shared<CLabelGroup>(FONT_SMALL, ETextAlignment::TOPLEFT, Colors::WHITE);
 	if(!showChat)
 	{
 		labelGroupPlayersAssigned->disable();
@@ -347,8 +346,8 @@ CFlagBox::CFlagBox(const Rect & rect)
 	pos.h = rect.h;
 	OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
 
-	labelAllies = std::make_shared<CLabel>(0, 0, FONT_SMALL, EAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[390] + ":");
-	labelEnemies = std::make_shared<CLabel>(133, 0, FONT_SMALL, EAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[391] + ":");
+	labelAllies = std::make_shared<CLabel>(0, 0, FONT_SMALL, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[390] + ":");
+	labelEnemies = std::make_shared<CLabel>(133, 0, FONT_SMALL, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[391] + ":");
 
 	iconsTeamFlags = std::make_shared<CAnimation>("ITGFLAGS.DEF");
 	iconsTeamFlags->preload();
@@ -390,8 +389,8 @@ CFlagBox::CFlagBoxTooltipBox::CFlagBoxTooltipBox(std::shared_ptr<CAnimation> ico
 	pos.w = 256;
 	pos.h = 90 + 50 * SEL->getMapInfo()->mapHeader->howManyTeams;
 
-	labelTeamAlignment = std::make_shared<CLabel>(128, 30, FONT_MEDIUM, CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[657]);
-	labelGroupTeams = std::make_shared<CLabelGroup>(FONT_SMALL, EAlignment::CENTER, Colors::WHITE);
+	labelTeamAlignment = std::make_shared<CLabel>(128, 30, FONT_MEDIUM, ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[657]);
+	labelGroupTeams = std::make_shared<CLabelGroup>(FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
 	for(int i = 0; i < SEL->getMapInfo()->mapHeader->howManyTeams; i++)
 	{
 		std::vector<ui8> flags;

+ 24 - 25
client/lobby/OptionsTab.cpp

@@ -12,7 +12,6 @@
 #include "CSelectionBase.h"
 #include "OptionsTab.h"
 
-#include "../CBitmapHandler.h"
 #include "../CGameInfo.h"
 #include "../CServerHandler.h"
 #include "../gui/CAnimation.h"
@@ -39,18 +38,18 @@ OptionsTab::OptionsTab() : humanPlayers(0)
 	OBJ_CONSTRUCTION;
 	background = std::make_shared<CPicture>("ADVOPTBK", 0, 6);
 	pos = background->pos;
-	labelTitle = std::make_shared<CLabel>(222, 30, FONT_BIG, CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[515]);
-	labelSubTitle = std::make_shared<CMultiLineLabel>(Rect(60, 44, 320, (int)graphics->fonts[EFonts::FONT_SMALL]->getLineHeight()*2), EFonts::FONT_SMALL, EAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[516]);
+	labelTitle = std::make_shared<CLabel>(222, 30, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[515]);
+	labelSubTitle = std::make_shared<CMultiLineLabel>(Rect(60, 44, 320, (int)graphics->fonts[EFonts::FONT_SMALL]->getLineHeight()*2), EFonts::FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[516]);
 
-	labelPlayerNameAndHandicap = std::make_shared<CMultiLineLabel>(Rect(58, 86, 100, (int)graphics->fonts[EFonts::FONT_SMALL]->getLineHeight()*2), EFonts::FONT_SMALL, EAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[517]);
-	labelStartingTown = std::make_shared<CMultiLineLabel>(Rect(163, 86, 70, (int)graphics->fonts[EFonts::FONT_SMALL]->getLineHeight()*2), EFonts::FONT_SMALL, EAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[518]);
-	labelStartingHero = std::make_shared<CMultiLineLabel>(Rect(239, 86, 70, (int)graphics->fonts[EFonts::FONT_SMALL]->getLineHeight()*2), EFonts::FONT_SMALL, EAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[519]);
-	labelStartingBonus = std::make_shared<CMultiLineLabel>(Rect(315, 86, 70, (int)graphics->fonts[EFonts::FONT_SMALL]->getLineHeight()*2), EFonts::FONT_SMALL, EAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[520]);
+	labelPlayerNameAndHandicap = std::make_shared<CMultiLineLabel>(Rect(58, 86, 100, (int)graphics->fonts[EFonts::FONT_SMALL]->getLineHeight()*2), EFonts::FONT_SMALL, ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[517]);
+	labelStartingTown = std::make_shared<CMultiLineLabel>(Rect(163, 86, 70, (int)graphics->fonts[EFonts::FONT_SMALL]->getLineHeight()*2), EFonts::FONT_SMALL, ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[518]);
+	labelStartingHero = std::make_shared<CMultiLineLabel>(Rect(239, 86, 70, (int)graphics->fonts[EFonts::FONT_SMALL]->getLineHeight()*2), EFonts::FONT_SMALL, ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[519]);
+	labelStartingBonus = std::make_shared<CMultiLineLabel>(Rect(315, 86, 70, (int)graphics->fonts[EFonts::FONT_SMALL]->getLineHeight()*2), EFonts::FONT_SMALL, ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[520]);
 	if(SEL->screenType == ESelectionScreen::newGame || SEL->screenType == ESelectionScreen::loadGame || SEL->screenType == ESelectionScreen::scenarioInfo)
 	{
 		sliderTurnDuration = std::make_shared<CSlider>(Point(55, 551), 194, std::bind(&IServerAPI::setTurnLength, CSH, _1), 1, (int)GameConstants::POSSIBLE_TURNTIME.size(), (int)GameConstants::POSSIBLE_TURNTIME.size(), true, CSlider::BLUE);
-		labelPlayerTurnDuration = std::make_shared<CLabel>(222, 538, FONT_SMALL, EAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[521]);
-		labelTurnDurationValue = std::make_shared<CLabel>(319, 559, FONT_SMALL, EAlignment::CENTER, Colors::WHITE);
+		labelPlayerTurnDuration = std::make_shared<CLabel>(222, 538, FONT_SMALL, ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[521]);
+		labelTurnDurationValue = std::make_shared<CLabel>(319, 559, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
 	}
 }
 
@@ -369,8 +368,8 @@ void OptionsTab::CPlayerOptionTooltipBox::genHeader()
 	backgroundTexture = std::make_shared<CFilledTexture>("DIBOXBCK", pos);
 	updateShadow();
 
-	labelTitle = std::make_shared<CLabel>(pos.w / 2 + 8, 21, FONT_MEDIUM, CENTER, Colors::YELLOW, getTitle());
-	labelSubTitle = std::make_shared<CLabel>(pos.w / 2, 88, FONT_SMALL, CENTER, Colors::WHITE, getSubtitle());
+	labelTitle = std::make_shared<CLabel>(pos.w / 2 + 8, 21, FONT_MEDIUM, ETextAlignment::CENTER, Colors::YELLOW, getTitle());
+	labelSubTitle = std::make_shared<CLabel>(pos.w / 2, 88, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, getSubtitle());
 	image = std::make_shared<CAnimImage>(getImageName(), getImageIndex(), 0, pos.w / 2 - 24, 45);
 }
 
@@ -378,7 +377,7 @@ void OptionsTab::CPlayerOptionTooltipBox::genTownWindow()
 {
 	pos = Rect(0, 0, 228, 290);
 	genHeader();
-	labelAssociatedCreatures = std::make_shared<CLabel>(pos.w / 2 + 8, 122, FONT_MEDIUM, CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[79]);
+	labelAssociatedCreatures = std::make_shared<CLabel>(pos.w / 2 + 8, 122, FONT_MEDIUM, ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[79]);
 	auto factionIndex = settings.castle >= CGI->townh->size() ? 0 : settings.castle;
 	std::vector<std::shared_ptr<CComponent>> components;
 	const CTown * town = (*CGI->townh)[factionIndex]->town;
@@ -395,11 +394,11 @@ void OptionsTab::CPlayerOptionTooltipBox::genHeroWindow()
 {
 	pos = Rect(0, 0, 292, 226);
 	genHeader();
-	labelHeroSpeciality = std::make_shared<CLabel>(pos.w / 2 + 4, 117, FONT_MEDIUM, CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[78]);
+	labelHeroSpeciality = std::make_shared<CLabel>(pos.w / 2 + 4, 117, FONT_MEDIUM, ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[78]);
 	auto heroIndex = settings.hero >= CGI->heroh->size() ? 0 : settings.hero;
 
 	imageSpeciality = std::make_shared<CAnimImage>("UN44", (*CGI->heroh)[heroIndex]->imageIndex, 0, pos.w / 2 - 22, 134);
-	labelSpecialityName = std::make_shared<CLabel>(pos.w / 2, 188, FONT_SMALL, CENTER, Colors::WHITE, (*CGI->heroh)[heroIndex]->specName);
+	labelSpecialityName = std::make_shared<CLabel>(pos.w / 2, 188, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, (*CGI->heroh)[heroIndex]->specName);
 }
 
 void OptionsTab::CPlayerOptionTooltipBox::genBonusWindow()
@@ -407,7 +406,7 @@ void OptionsTab::CPlayerOptionTooltipBox::genBonusWindow()
 	pos = Rect(0, 0, 228, 162);
 	genHeader();
 
-	textBonusDescription = std::make_shared<CTextBox>(getDescription(), Rect(10, 100, pos.w - 20, 70), 0, FONT_SMALL, CENTER, Colors::WHITE);
+	textBonusDescription = std::make_shared<CTextBox>(getDescription(), Rect(10, 100, pos.w - 20, 70), 0, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
 }
 
 OptionsTab::SelectedBox::SelectedBox(Point position, PlayerSettings & settings, SelType type)
@@ -416,7 +415,7 @@ OptionsTab::SelectedBox::SelectedBox(Point position, PlayerSettings & settings,
 	OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
 
 	image = std::make_shared<CAnimImage>(getImageName(), getImageIndex());
-	subtitle = std::make_shared<CLabel>(23, 39, FONT_TINY, CENTER, Colors::WHITE, getName());
+	subtitle = std::make_shared<CLabel>(23, 39, FONT_TINY, ETextAlignment::CENTER, Colors::WHITE, getName());
 
 	pos = image->pos;
 }
@@ -468,20 +467,20 @@ OptionsTab::PlayerOptionsEntry::PlayerOptionsEntry(const PlayerSettings & S, con
 	else
 		whoCanPlay = HUMAN;
 
-	static const char * flags[] =
-	{
+	static const std::array<std::string, PlayerColor::PLAYER_LIMIT_I> flags =
+	{{
 		"AOFLGBR.DEF", "AOFLGBB.DEF", "AOFLGBY.DEF", "AOFLGBG.DEF",
 		"AOFLGBO.DEF", "AOFLGBP.DEF", "AOFLGBT.DEF", "AOFLGBS.DEF"
-	};
-	static const char * bgs[] =
-	{
+	}};
+	static const std::array<std::string, PlayerColor::PLAYER_LIMIT_I> bgs =
+	{{
 		"ADOPRPNL.bmp", "ADOPBPNL.bmp", "ADOPYPNL.bmp", "ADOPGPNL.bmp",
 		"ADOPOPNL.bmp", "ADOPPPNL.bmp", "ADOPTPNL.bmp", "ADOPSPNL.bmp"
-	};
+	}};
 
-	background = std::make_shared<CPicture>(BitmapHandler::loadBitmap(bgs[s.color.getNum()]), 0, 0, true);
-	labelPlayerName = std::make_shared<CLabel>(55, 10, EFonts::FONT_SMALL, EAlignment::CENTER, Colors::WHITE, s.name);
-	labelWhoCanPlay = std::make_shared<CMultiLineLabel>(Rect(6, 23, 45, (int)graphics->fonts[EFonts::FONT_TINY]->getLineHeight()*2), EFonts::FONT_TINY, EAlignment::CENTER, Colors::WHITE, CGI->generaltexth->arraytxt[206 + whoCanPlay]);
+	background = std::make_shared<CPicture>(bgs[s.color.getNum()], 0, 0);
+	labelPlayerName = std::make_shared<CLabel>(55, 10, EFonts::FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, s.name);
+	labelWhoCanPlay = std::make_shared<CMultiLineLabel>(Rect(6, 23, 45, (int)graphics->fonts[EFonts::FONT_TINY]->getLineHeight()*2), EFonts::FONT_TINY, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->arraytxt[206 + whoCanPlay]);
 
 	if(SEL->screenType == ESelectionScreen::newGame)
 	{

+ 6 - 7
client/lobby/SelectionTab.cpp

@@ -15,7 +15,6 @@
 
 #include "../CGameInfo.h"
 #include "../CMessage.h"
-#include "../CBitmapHandler.h"
 #include "../CPlayerInterface.h"
 #include "../CServerHandler.h"
 #include "../gui/CAnimation.h"
@@ -142,7 +141,7 @@ SelectionTab::SelectionTab(ESelectionScreen Type)
 		pos = background->pos;
 		inputName = std::make_shared<CTextInput>(inputNameRect, Point(-32, -25), "GSSTRIP.bmp", 0);
 		inputName->filters += CTextInput::filenameFilter;
-		labelMapSizes = std::make_shared<CLabel>(87, 62, FONT_SMALL, EAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[510]);
+		labelMapSizes = std::make_shared<CLabel>(87, 62, FONT_SMALL, ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[510]);
 
 		int sizes[] = {36, 72, 108, 144, 0};
 		const char * filterIconNmes[] = {"SCSMBUT.DEF", "SCMDBUT.DEF", "SCLGBUT.DEF", "SCXLBUT.DEF", "SCALBUT.DEF"};
@@ -200,7 +199,7 @@ SelectionTab::SelectionTab(ESelectionScreen Type)
 	for(int i = 0; i < positionsToShow; i++)
 		listItems.push_back(std::make_shared<ListItem>(Point(30, 129 + i * 25), iconsMapFormats, iconsVictoryCondition, iconsLossCondition));
 
-	labelTabTitle = std::make_shared<CLabel>(205, 28, FONT_MEDIUM, EAlignment::CENTER, Colors::YELLOW, tabTitle);
+	labelTabTitle = std::make_shared<CLabel>(205, 28, FONT_MEDIUM, ETextAlignment::CENTER, Colors::YELLOW, tabTitle);
 	slider = std::make_shared<CSlider>(Point(372, 86), tabType != ESelectionScreen::saveGame ? 480 : 430, std::bind(&SelectionTab::sliderMove, this, _1), positionsToShow, (int)curItems.size(), 0, false, CSlider::BLUE);
 	filter(0);
 }
@@ -623,13 +622,13 @@ SelectionTab::ListItem::ListItem(Point position, std::shared_ptr<CAnimation> ico
 	: CIntObject(LCLICK, position)
 {
 	OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
-	labelName = std::make_shared<CLabel>(184, 0, FONT_SMALL, EAlignment::CENTER, Colors::WHITE);
+	labelName = std::make_shared<CLabel>(184, 0, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
 	labelName->setAutoRedraw(false);
-	labelAmountOfPlayers = std::make_shared<CLabel>(8, 0, FONT_SMALL, EAlignment::CENTER, Colors::WHITE);
+	labelAmountOfPlayers = std::make_shared<CLabel>(8, 0, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
 	labelAmountOfPlayers->setAutoRedraw(false);
-	labelNumberOfCampaignMaps = std::make_shared<CLabel>(8, 0, FONT_SMALL, EAlignment::CENTER, Colors::WHITE);
+	labelNumberOfCampaignMaps = std::make_shared<CLabel>(8, 0, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
 	labelNumberOfCampaignMaps->setAutoRedraw(false);
-	labelMapSizeLetter = std::make_shared<CLabel>(41, 0, FONT_SMALL, EAlignment::CENTER, Colors::WHITE);
+	labelMapSizeLetter = std::make_shared<CLabel>(41, 0, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
 	labelMapSizeLetter->setAutoRedraw(false);
 	// FIXME: This -12 should not be needed, but for some reason CAnimImage displaced otherwise
 	iconFormat = std::make_shared<CAnimImage>(iconsFormats, 0, 0, 59, -12);

+ 1 - 2
client/mainmenu/CCampaignScreen.cpp

@@ -15,7 +15,6 @@
 
 #include "../CGameInfo.h"
 #include "../CMessage.h"
-#include "../CBitmapHandler.h"
 #include "../CMusicHandler.h"
 #include "../CVideoHandler.h"
 #include "../CPlayerInterface.h"
@@ -105,7 +104,7 @@ CCampaignScreen::CCampaignButton::CCampaignButton(const JsonNode & config)
 		addUsedEvents(LCLICK | HOVER);
 		graphicsImage = std::make_shared<CPicture>(config["image"].String());
 
-		hoverLabel = std::make_shared<CLabel>(pos.w / 2, pos.h + 20, FONT_MEDIUM, CENTER, Colors::YELLOW, "");
+		hoverLabel = std::make_shared<CLabel>(pos.w / 2, pos.h + 20, FONT_MEDIUM, ETextAlignment::CENTER, Colors::YELLOW, "");
 		parent->addChild(hoverLabel.get());
 	}
 

+ 12 - 12
client/mainmenu/CMainMenu.cpp

@@ -37,7 +37,6 @@
 #include "../CPlayerInterface.h"
 #include "../../CCallback.h"
 #include "../CMessage.h"
-#include "../CBitmapHandler.h"
 #include "../Client.h"
 #include "../gui/CGuiHandler.h"
 #include "../gui/CAnimation.h"
@@ -370,13 +369,14 @@ CMultiMode::CMultiMode(ESelectionScreen ScreenType)
 	: screenType(ScreenType)
 {
 	OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
+
 	background = std::make_shared<CPicture>("MUPOPUP.bmp");
-	background->convertToScreenBPP(); //so we could draw without problems
-	blitAt(CPicture("MUMAP.bmp"), 16, 77, *background);
 	pos = background->center(); //center, window has size of bg graphic
 
-	statusBar = CGStatusBar::create(std::make_shared<CPicture>(Rect(7, 465, 440, 18), 0)); //226, 472
-	playerName = std::make_shared<CTextInput>(Rect(19, 436, 334, 16), *background);
+	picture = std::make_shared<CPicture>("MUMAP.bmp", 16, 77);
+
+	statusBar = CGStatusBar::create(std::make_shared<CPicture>(background->getSurface(), Rect(7, 465, 440, 18), 7, 465));
+	playerName = std::make_shared<CTextInput>(Rect(19, 436, 334, 16), background->getSurface());
 	playerName->setText(settings["general"]["playerName"].String());
 	playerName->cb += std::bind(&CMultiMode::onNameChange, this, _1);
 
@@ -415,17 +415,17 @@ CMultiPlayers::CMultiPlayers(const std::string & firstPlayer, ESelectionScreen S
 
 	std::string text = CGI->generaltexth->allTexts[446];
 	boost::replace_all(text, "\t", "\n");
-	textTitle = std::make_shared<CTextBox>(text, Rect(25, 20, 315, 50), 0, FONT_BIG, CENTER, Colors::WHITE); //HOTSEAT	Please enter names
+	textTitle = std::make_shared<CTextBox>(text, Rect(25, 20, 315, 50), 0, FONT_BIG, ETextAlignment::CENTER, Colors::WHITE); //HOTSEAT	Please enter names
 
 	for(int i = 0; i < inputNames.size(); i++)
 	{
-		inputNames[i] = std::make_shared<CTextInput>(Rect(60, 85 + i * 30, 280, 16), *background);
+		inputNames[i] = std::make_shared<CTextInput>(Rect(60, 85 + i * 30, 280, 16), background->getSurface());
 		inputNames[i]->cb += std::bind(&CMultiPlayers::onChange, this, _1);
 	}
 
 	buttonOk = std::make_shared<CButton>(Point(95, 338), "MUBCHCK.DEF", CGI->generaltexth->zelp[560], std::bind(&CMultiPlayers::enterSelectionScreen, this), SDLK_RETURN);
 	buttonCancel = std::make_shared<CButton>(Point(205, 338), "MUBCANC.DEF", CGI->generaltexth->zelp[561], [=](){ close();}, SDLK_ESCAPE);
-	statusBar = CGStatusBar::create(std::make_shared<CPicture>(Rect(7, 381, 348, 18), 0)); //226, 472
+	statusBar = CGStatusBar::create(std::make_shared<CPicture>(background->getSurface(), Rect(7, 381, 348, 18), 7, 381));
 
 	inputNames[0]->setText(firstPlayer, true);
 #ifndef VCMI_IOS
@@ -463,9 +463,9 @@ CSimpleJoinScreen::CSimpleJoinScreen(bool host)
 	background = std::make_shared<CPicture>("MUDIALOG.bmp"); // address background
 	pos = background->center(); //center, window has size of bg graphic (x,y = 396,278 w=232 h=212)
 
-	textTitle = std::make_shared<CTextBox>("", Rect(20, 20, 205, 50), 0, FONT_BIG, CENTER, Colors::WHITE);
-	inputAddress = std::make_shared<CTextInput>(Rect(25, 68, 175, 16), *background.get());
-	inputPort = std::make_shared<CTextInput>(Rect(25, 115, 175, 16), *background.get());
+	textTitle = std::make_shared<CTextBox>("", Rect(20, 20, 205, 50), 0, FONT_BIG, ETextAlignment::CENTER, Colors::WHITE);
+	inputAddress = std::make_shared<CTextInput>(Rect(25, 68, 175, 16), background->getSurface());
+	inputPort = std::make_shared<CTextInput>(Rect(25, 115, 175, 16), background->getSurface());
 	if(host && !settings["session"]["donotstartserver"].Bool())
 	{
 		textTitle->setText("Connecting...");
@@ -485,7 +485,7 @@ CSimpleJoinScreen::CSimpleJoinScreen(bool host)
 	inputPort->setText(boost::lexical_cast<std::string>(CSH->getHostPort()), true);
 
 	buttonCancel = std::make_shared<CButton>(Point(142, 142), "MUBCANC.DEF", CGI->generaltexth->zelp[561], std::bind(&CSimpleJoinScreen::leaveScreen, this), SDLK_ESCAPE);
-	statusBar = CGStatusBar::create(std::make_shared<CPicture>(Rect(7, 186, 218, 18), 0));
+	statusBar = CGStatusBar::create(std::make_shared<CPicture>(background->getSurface(), Rect(7, 186, 218, 18), 7, 186));
 }
 
 void CSimpleJoinScreen::connectToServer()

+ 1 - 0
client/mainmenu/CMainMenu.h

@@ -80,6 +80,7 @@ class CMultiMode : public WindowBase
 public:
 	ESelectionScreen screenType;
 	std::shared_ptr<CPicture> background;
+	std::shared_ptr<CPicture> picture;
 	std::shared_ptr<CTextInput> playerName;
 	std::shared_ptr<CButton> buttonHotseat;
 	std::shared_ptr<CButton> buttonHost;

+ 1 - 1
client/mainmenu/CPrologEpilogVideo.cpp

@@ -33,7 +33,7 @@ CPrologEpilogVideo::CPrologEpilogVideo(CCampaignScenario::SScenarioPrologEpilog
 	// MPTODO: Custom campaign crashing on this?
 //	voiceSoundHandle = CCS->soundh->playSound(CCampaignHandler::prologVoiceName(spe.prologVideo));
 
-	text = std::make_shared<CMultiLineLabel>(Rect(100, 500, 600, 100), EFonts::FONT_BIG, CENTER, Colors::METALLIC_GOLD, spe.prologText);
+	text = std::make_shared<CMultiLineLabel>(Rect(100, 500, 600, 100), EFonts::FONT_BIG, ETextAlignment::CENTER, Colors::METALLIC_GOLD, spe.prologText);
 	text->scrollTextTo(-100);
 }
 

+ 1 - 1
client/mainmenu/CreditsScreen.cpp

@@ -30,7 +30,7 @@ CreditsScreen::CreditsScreen(Rect rect)
 	std::string text((char *)textFile.first.get(), textFile.second);
 	size_t firstQuote = text.find('\"') + 1;
 	text = text.substr(firstQuote, text.find('\"', firstQuote) - firstQuote);
-	credits = std::make_shared<CMultiLineLabel>(Rect(pos.w - 350, 0, 350, 600), FONT_CREDITS, CENTER, Colors::WHITE, text);
+	credits = std::make_shared<CMultiLineLabel>(Rect(pos.w - 350, 0, 350, 600), FONT_CREDITS, ETextAlignment::CENTER, Colors::WHITE, text);
 	credits->scrollTextTo(-600); // move all text below the screen
 }
 

+ 15 - 49
client/widgets/AdventureMapClasses.cpp

@@ -31,8 +31,8 @@
 #include "../windows/CAdvmapInterface.h"
 #include "../windows/GUIClasses.h"
 
-#include "../battle/CBattleInterfaceClasses.h"
-#include "../battle/CBattleInterface.h"
+#include "../battle/BattleInterfaceClasses.h"
+#include "../battle/BattleInterface.h"
 
 #include "../../CCallback.h"
 #include "../../lib/StartInfo.h"
@@ -87,7 +87,7 @@ void CList::CListItem::clickLeft(tribool down, bool previousState)
 void CList::CListItem::hover(bool on)
 {
 	if (on)
-		GH.statusbar->setText(getHoverText());
+		GH.statusbar->write(getHoverText());
 	else
 		GH.statusbar->clear();
 }
@@ -572,7 +572,7 @@ void CMinimap::clickRight(tribool down, bool previousState)
 void CMinimap::hover(bool on)
 {
 	if(on)
-		GH.statusbar->setText(CGI->generaltexth->zelp[291].first);
+		GH.statusbar->write(CGI->generaltexth->zelp[291].first);
 	else
 		GH.statusbar->clear();
 }
@@ -705,7 +705,7 @@ CInfoBar::VisibleDateInfo::VisibleDateInfo()
 	else
 		labelText = CGI->generaltexth->allTexts[64] + " " + boost::lexical_cast<std::string>(LOCPLINT->cb->getDate(Date::DAY_OF_WEEK));
 
-	label = std::make_shared<CLabel>(95, 31, FONT_MEDIUM, CENTER, Colors::WHITE, labelText);
+	label = std::make_shared<CLabel>(95, 31, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, labelText);
 
 	forceRefresh.push_back(label);
 }
@@ -771,8 +771,8 @@ CInfoBar::VisibleGameStatusInfo::VisibleGameStatusInfo()
 
 	//generate widgets
 	background = std::make_shared<CPicture>("ADSTATIN");
-	allyLabel = std::make_shared<CLabel>(10, 106, FONT_SMALL, TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[390] + ":");
-	enemyLabel = std::make_shared<CLabel>(10, 136, FONT_SMALL, TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[391] + ":");
+	allyLabel = std::make_shared<CLabel>(10, 106, FONT_SMALL, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[390] + ":");
+	enemyLabel = std::make_shared<CLabel>(10, 136, FONT_SMALL, ETextAlignment::TOPLEFT, Colors::WHITE, CGI->generaltexth->allTexts[391] + ":");
 
 	int posx = allyLabel->pos.w + allyLabel->pos.x - pos.x + 4;
 	for(PlayerColor & player : allies)
@@ -794,7 +794,7 @@ CInfoBar::VisibleGameStatusInfo::VisibleGameStatusInfo()
 	{
 		hallIcons.push_back(std::make_shared<CAnimImage>("itmtl", i, 0, 6 + 42 * (int)i , 11));
 		if(halls[i])
-			hallLabels.push_back(std::make_shared<CLabel>( 26 + 42 * (int)i, 64, FONT_SMALL, CENTER, Colors::WHITE, boost::lexical_cast<std::string>(halls[i])));
+			hallLabels.push_back(std::make_shared<CLabel>( 26 + 42 * (int)i, 64, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, boost::lexical_cast<std::string>(halls[i])));
 	}
 }
 
@@ -807,7 +807,7 @@ CInfoBar::VisibleComponentInfo::VisibleComponentInfo(const Component & compToDis
 	comp = std::make_shared<CComponent>(compToDisplay);
 	comp->moveTo(Point(pos.x+47, pos.y+50));
 
-	text = std::make_shared<CTextBox>(message, Rect(10, 4, 160, 50), 0, FONT_SMALL, CENTER, Colors::WHITE);
+	text = std::make_shared<CTextBox>(message, Rect(10, 4, 160, 50), 0, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
 }
 
 void CInfoBar::playNewDaySound()
@@ -876,7 +876,7 @@ void CInfoBar::clickRight(tribool down, bool previousState)
 void CInfoBar::hover(bool on)
 {
 	if(on)
-		GH.statusbar->setText(CGI->generaltexth->zelp[292].first);
+		GH.statusbar->write(CGI->generaltexth->zelp[292].first);
 	else
 		GH.statusbar->clear();
 }
@@ -1126,65 +1126,31 @@ void CInGameConsole::textEdited(const SDL_TextEditingEvent & event)
 
 void CInGameConsole::startEnteringText()
 {
+	assert(GH.statusbar);
 	captureAllKeys = true;
-
-	CSDL_Ext::startTextInput(&GH.statusbar->pos);
-
 	enteredText = "_";
-	if(GH.topInt() == adventureInt)
-	{
-		GH.statusbar->alignment = TOPLEFT;
-		GH.statusbar->setText(enteredText);
 
-		//Prevent changes to the text from mouse interaction with the adventure map
-		GH.statusbar->lock(true);
-	}
-	else if(LOCPLINT->battleInt)
-	{
-		LOCPLINT->battleInt->console->ingcAlter = enteredText;
-	}
+	GH.statusbar->setEnteringMode(true);
+	GH.statusbar->setEnteredText(enteredText);
 }
 
 void CInGameConsole::endEnteringText(bool printEnteredText)
 {
 	captureAllKeys = false;
-
-	CSDL_Ext::stopTextInput();
-
 	prevEntDisp = -1;
 	if(printEnteredText)
 	{
 		std::string txt = enteredText.substr(0, enteredText.size()-1);
 		LOCPLINT->cb->sendMessage(txt, LOCPLINT->getSelection());
 		previouslyEntered.push_back(txt);
-		//print(txt);
 	}
 	enteredText.clear();
-	if(GH.topInt() == adventureInt)
-	{
-		GH.statusbar->alignment = CENTER;
-		GH.statusbar->lock(false);
-		GH.statusbar->clear();
-	}
-	else if(LOCPLINT->battleInt)
-	{
-		LOCPLINT->battleInt->console->ingcAlter = "";
-	}
+	GH.statusbar->setEnteringMode(false);
 }
 
 void CInGameConsole::refreshEnteredText()
 {
-	if(GH.topInt() == adventureInt)
-	{
-		GH.statusbar->lock(false);
-		GH.statusbar->clear();
-		GH.statusbar->setText(enteredText);
-		GH.statusbar->lock(true);
-	}
-	else if(LOCPLINT->battleInt)
-	{
-		LOCPLINT->battleInt->console->ingcAlter = enteredText;
-	}
+	GH.statusbar->setEnteredText(enteredText);
 }
 
 CAdvMapPanel::CAdvMapPanel(SDL_Surface * bg, Point position)

+ 8 - 24
client/widgets/Buttons.cpp

@@ -16,8 +16,8 @@
 #include "../CMusicHandler.h"
 #include "../CGameInfo.h"
 #include "../CPlayerInterface.h"
-#include "../battle/CBattleInterface.h"
-#include "../battle/CBattleInterfaceClasses.h"
+#include "../battle/BattleInterface.h"
+#include "../battle/BattleInterfaceClasses.h"
 #include "../gui/CAnimation.h"
 #include "../gui/CGuiHandler.h"
 #include "../windows/InfoWindows.h"
@@ -77,7 +77,7 @@ void CButton::addCallback(std::function<void()> callback)
 void CButton::addTextOverlay(const std::string & Text, EFonts font, SDL_Color color)
 {
 	OBJECT_CONSTRUCTION_CUSTOM_CAPTURING(255-DISPOSE);
-	addOverlay(std::make_shared<CLabel>(pos.w/2, pos.h/2, font, CENTER, color, Text));
+	addOverlay(std::make_shared<CLabel>(pos.w/2, pos.h/2, font, ETextAlignment::CENTER, color, Text));
 	update();
 }
 
@@ -207,26 +207,10 @@ void CButton::hover (bool on)
 
 	if(!name.empty() && !isBlocked()) //if there is no name, there is nothing to display also
 	{
-		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)
-			{
-				LOCPLINT->battleInt->console->alterTxt = "";
-				LOCPLINT->battleInt->console->whoSetAlter = 0;
-			}
-		}
-		else if(GH.statusbar) //for other buttons
-		{
-			if (on)
-				GH.statusbar->setText(name);
-			else if ( GH.statusbar->getText()==(name) )
-				GH.statusbar->clear();
-		}
+		if (on)
+			GH.statusbar->write(name);
+		else
+			GH.statusbar->clearIfMatching(name);
 	}
 }
 
@@ -530,7 +514,7 @@ void CVolumeSlider::clickRight(tribool down, bool previousState)
 		if(!helpBox.empty())
 			CRClickPopup::createAndPush(helpBox);
 		if(GH.statusbar)
-			GH.statusbar->setText(helpBox);
+			GH.statusbar->write(helpBox);
 	}
 }
 

+ 2 - 2
client/widgets/CComponent.cpp

@@ -74,7 +74,7 @@ void CComponent::init(Etype Type, int Subtype, int Val, ESize imageSize)
 	for(auto & line : textLines)
 	{
 		int height = static_cast<int>(graphics->fonts[font]->getLineHeight());
-		auto label = std::make_shared<CLabel>(pos.w/2, pos.h + height/2, font, CENTER, Colors::WHITE, line);
+		auto label = std::make_shared<CLabel>(pos.w/2, pos.h + height/2, font, ETextAlignment::CENTER, Colors::WHITE, line);
 
 		pos.h += height;
 		if(label->pos.w > pos.w)
@@ -424,7 +424,7 @@ void CComponentBox::placeComponents(bool selectable)
 				{
 					Point orPos = Point(currentX - freeSpace, currentY) + getOrTextPos(prevComp.get(), iter->get());
 
-					orLabels.push_back(std::make_shared<CLabel>(orPos.x, orPos.y, FONT_MEDIUM, CENTER, Colors::WHITE, CGI->generaltexth->allTexts[4]));
+					orLabels.push_back(std::make_shared<CLabel>(orPos.x, orPos.y, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[4]));
 				}
 				currentX += getDistance(prevComp.get(), iter->get());
 			}

+ 2 - 2
client/widgets/CGarrisonInt.cpp

@@ -118,7 +118,7 @@ void CGarrisonSlot::hover (bool on)
 				temp = CGI->generaltexth->tcommands[11]; //Empty
 			}
 		}
-		GH.statusbar->setText(temp);
+		GH.statusbar->write(temp);
 	}
 	else
 	{
@@ -418,7 +418,7 @@ CGarrisonSlot::CGarrisonSlot(CGarrisonInt * Owner, int x, int y, SlotID IID, CGa
 		pos.h = 64;
 	}
 
-	stackCount = std::make_shared<CLabel>(pos.w, pos.h, owner->smallIcons ? FONT_TINY : FONT_MEDIUM, BOTTOMRIGHT, Colors::WHITE);
+	stackCount = std::make_shared<CLabel>(pos.w, pos.h, owner->smallIcons ? FONT_TINY : FONT_MEDIUM, ETextAlignment::BOTTOMRIGHT, Colors::WHITE);
 
 	update();
 }

+ 2 - 2
client/widgets/Images.cpp

@@ -17,8 +17,8 @@
 #include "../gui/CGuiHandler.h"
 #include "../gui/CCursorHandler.h"
 
-#include "../battle/CBattleInterface.h"
-#include "../battle/CBattleInterfaceClasses.h"
+#include "../battle/BattleInterface.h"
+#include "../battle/BattleInterfaceClasses.h"
 
 #include "../CBitmapHandler.h"
 #include "../Graphics.h"

+ 2 - 1
client/widgets/Images.h

@@ -29,7 +29,8 @@ public:
 	bool freeSurf; //whether surface will be freed upon CPicture destruction
 	bool needRefresh;//Surface needs to be displayed each frame
 	bool visible;
-	operator SDL_Surface*()
+
+	SDL_Surface * getSurface()
 	{
 		return bg;
 	}

+ 10 - 11
client/widgets/MiscWidgets.cpp

@@ -15,7 +15,6 @@
 #include "../gui/CGuiHandler.h"
 #include "../gui/CCursorHandler.h"
 
-#include "../CBitmapHandler.h"
 #include "../CPlayerInterface.h"
 #include "../CMessage.h"
 #include "../CGameInfo.h"
@@ -34,9 +33,9 @@
 void CHoverableArea::hover (bool on)
 {
 	if (on)
-		GH.statusbar->setText(hoverText);
-	else if (GH.statusbar->getText()==hoverText)
-		GH.statusbar->clear();
+		GH.statusbar->write(hoverText);
+	else
+		GH.statusbar->clearIfMatching(hoverText);
 }
 
 CHoverableArea::CHoverableArea()
@@ -150,7 +149,7 @@ void CHeroArea::clickRight(tribool down, bool previousState)
 void CHeroArea::hover(bool on)
 {
 	if (on && hero)
-		GH.statusbar->setText(hero->getObjectName());
+		GH.statusbar->write(hero->getObjectName());
 	else
 		GH.statusbar->clear();
 }
@@ -224,7 +223,7 @@ void CArmyTooltip::init(const InfoAboutArmy &army)
 {
 	OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
 
-	title = std::make_shared<CLabel>(66, 2, FONT_SMALL, TOPLEFT, Colors::WHITE, army.name);
+	title = std::make_shared<CLabel>(66, 2, FONT_SMALL, ETextAlignment::TOPLEFT, Colors::WHITE, army.name);
 
 	std::vector<Point> slotsPos;
 	slotsPos.push_back(Point(36, 73));
@@ -257,7 +256,7 @@ void CArmyTooltip::init(const InfoAboutArmy &army)
 				subtitle = CGI->generaltexth->arraytxt[171 + 3*(slot.second.count)];
 		}
 
-		subtitles.push_back(std::make_shared<CLabel>(slotsPos[slot.first.getNum()].x + 17, slotsPos[slot.first.getNum()].y + 41, FONT_TINY, CENTER, Colors::WHITE, subtitle));
+		subtitles.push_back(std::make_shared<CLabel>(slotsPos[slot.first.getNum()].x + 17, slotsPos[slot.first.getNum()].y + 41, FONT_TINY, ETextAlignment::CENTER, Colors::WHITE, subtitle));
 	}
 
 }
@@ -282,10 +281,10 @@ void CHeroTooltip::init(const InfoAboutHero & hero)
 	if(hero.details)
 	{
 		for(size_t i = 0; i < hero.details->primskills.size(); i++)
-			labels.push_back(std::make_shared<CLabel>(75 + 28 * (int)i, 58, FONT_SMALL, CENTER, Colors::WHITE,
+			labels.push_back(std::make_shared<CLabel>(75 + 28 * (int)i, 58, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE,
 					   boost::lexical_cast<std::string>(hero.details->primskills[i])));
 
-		labels.push_back(std::make_shared<CLabel>(158, 98, FONT_TINY, CENTER, Colors::WHITE, boost::lexical_cast<std::string>(hero.details->mana)));
+		labels.push_back(std::make_shared<CLabel>(158, 98, FONT_TINY, ETextAlignment::CENTER, Colors::WHITE, boost::lexical_cast<std::string>(hero.details->mana)));
 
 		morale = std::make_shared<CAnimImage>("IMRL22", hero.details->morale + 3, 0, 5, 74);
 		luck = std::make_shared<CAnimImage>("ILCK22", hero.details->luck + 3, 0, 5, 91);
@@ -325,7 +324,7 @@ void CTownTooltip::init(const InfoAboutTown & town)
 
 		if(town.details->goldIncome)
 		{
-			income = std::make_shared<CLabel>(157, 58, FONT_TINY, CENTER, Colors::WHITE,
+			income = std::make_shared<CLabel>(157, 58, FONT_TINY, ETextAlignment::CENTER, Colors::WHITE,
 					   boost::lexical_cast<std::string>(town.details->goldIncome));
 		}
 		if(town.details->garrisonedHero) //garrisoned hero icon
@@ -453,7 +452,7 @@ CCreaturePic::CCreaturePic(int x, int y, const CCreature * cre, bool Big, bool A
 	anim->clipRect(cre->isDoubleWide()?170:150, 155, bg->pos.w, bg->pos.h);
 	anim->startPreview(cre->hasBonusOfType(Bonus::SIEGE_WEAPON));
 
-	amount = std::make_shared<CLabel>(bg->pos.w, bg->pos.h, FONT_MEDIUM, BOTTOMRIGHT, Colors::WHITE);
+	amount = std::make_shared<CLabel>(bg->pos.w, bg->pos.h, FONT_MEDIUM, ETextAlignment::BOTTOMRIGHT, Colors::WHITE);
 
 	pos.w = bg->pos.w;
 	pos.h = bg->pos.h;

+ 62 - 31
client/widgets/TextControls.cpp

@@ -36,7 +36,7 @@ void CLabel::showAll(SDL_Surface * to)
 
 }
 
-CLabel::CLabel(int x, int y, EFonts Font, EAlignment Align, const SDL_Color & Color, const std::string & Text)
+CLabel::CLabel(int x, int y, EFonts Font, ETextAlignment Align, const SDL_Color & Color, const std::string & Text)
 	: CTextContainer(Align, Font, Color), text(Text)
 {
 	type |= REDRAW_PARENT;
@@ -45,7 +45,7 @@ CLabel::CLabel(int x, int y, EFonts Font, EAlignment Align, const SDL_Color & Co
 	pos.y += y;
 	pos.w = pos.h = 0;
 
-	if(alignment == TOPLEFT) // causes issues for MIDDLE
+	if(alignment == ETextAlignment::TOPLEFT) // causes issues for MIDDLE
 	{
 		pos.w = (int)graphics->fonts[font]->getStringWidth(visibleText().c_str());
 		pos.h = (int)graphics->fonts[font]->getLineHeight();
@@ -96,7 +96,7 @@ size_t CLabel::getWidth()
 	return graphics->fonts[font]->getStringWidth(visibleText());;
 }
 
-CMultiLineLabel::CMultiLineLabel(Rect position, EFonts Font, EAlignment Align, const SDL_Color & Color, const std::string & Text) :
+CMultiLineLabel::CMultiLineLabel(Rect position, EFonts Font, ETextAlignment Align, const SDL_Color & Color, const std::string & Text) :
 	CLabel(position.x, position.y, Font, Align, Color, Text),
 	visibleSize(0, 0, position.w, position.h)
 {
@@ -137,19 +137,19 @@ void CTextContainer::blitLine(SDL_Surface * to, Rect destRect, std::string what)
 
 	// input is rect in which given text should be placed
 	// calculate proper position for top-left corner of the text
-	if(alignment == TOPLEFT)
+	if(alignment == ETextAlignment::TOPLEFT)
 	{
 		where.x += getBorderSize().x;
 		where.y += getBorderSize().y;
 	}
 
-	if(alignment == CENTER)
+	if(alignment == ETextAlignment::CENTER)
 	{
 		where.x += (int(destRect.w) - int(f->getStringWidth(what))) / 2;
 		where.y += (int(destRect.h) - int(f->getLineHeight())) / 2;
 	}
 
-	if(alignment == BOTTOMRIGHT)
+	if(alignment == ETextAlignment::BOTTOMRIGHT)
 	{
 		where.x += getBorderSize().x + destRect.w - (int)f->getStringWidth(what);
 		where.y += getBorderSize().y + destRect.h - (int)f->getLineHeight();
@@ -178,7 +178,7 @@ void CTextContainer::blitLine(SDL_Surface * to, Rect destRect, std::string what)
 	} while(begin++ != std::string::npos);
 }
 
-CTextContainer::CTextContainer(EAlignment alignment, EFonts font, SDL_Color color) :
+CTextContainer::CTextContainer(ETextAlignment alignment, EFonts font, SDL_Color color) :
 	alignment(alignment),
 	font(font),
 	color(color)
@@ -252,15 +252,15 @@ Rect CMultiLineLabel::getTextLocation()
 
 	switch(alignment)
 	{
-	case TOPLEFT:     return Rect(pos.topLeft(), textSize);
-	case CENTER:      return Rect(pos.topLeft() + textOffset / 2, textSize);
-	case BOTTOMRIGHT: return Rect(pos.topLeft() + textOffset, textSize);
+	case ETextAlignment::TOPLEFT:     return Rect(pos.topLeft(), textSize);
+	case ETextAlignment::CENTER:      return Rect(pos.topLeft() + textOffset / 2, textSize);
+	case ETextAlignment::BOTTOMRIGHT: return Rect(pos.topLeft() + textOffset, textSize);
 	}
 	assert(0);
 	return Rect();
 }
 
-CLabelGroup::CLabelGroup(EFonts Font, EAlignment Align, const SDL_Color & Color)
+CLabelGroup::CLabelGroup(EFonts Font, ETextAlignment Align, const SDL_Color & Color)
 	: font(Font), align(Align), color(Color)
 {
 	defActions = 255 - DISPOSE;
@@ -277,7 +277,7 @@ size_t CLabelGroup::currentSize() const
 	return labels.size();
 }
 
-CTextBox::CTextBox(std::string Text, const Rect & rect, int SliderStyle, EFonts Font, EAlignment Align, const SDL_Color & Color) :
+CTextBox::CTextBox(std::string Text, const Rect & rect, int SliderStyle, EFonts Font, ETextAlignment Align, const SDL_Color & Color) :
 	sliderStyle(SliderStyle),
 	slider(nullptr)
 {
@@ -339,30 +339,67 @@ void CTextBox::setText(const std::string & text)
 	}
 }
 
-void CGStatusBar::setText(const std::string & Text)
+void CGStatusBar::setEnteringMode(bool on)
 {
-	if(!textLock)
-		CLabel::setText(Text);
+	consoleText.clear();
+
+	if (on)
+	{
+		assert(enteringText == false);
+		alignment = ETextAlignment::TOPLEFT;
+		CSDL_Ext::startTextInput(&pos);
+		setText(consoleText);
+	}
+	else
+	{
+		assert(enteringText == true);
+		alignment = ETextAlignment::CENTER;
+		CSDL_Ext::stopTextInput();
+		setText(hoverText);
+	}
+	enteringText = on;
+}
+
+void CGStatusBar::setEnteredText(const std::string & text)
+{
+	assert(enteringText == true);
+	consoleText = text;
+	setText(text);
+}
+
+void CGStatusBar::write(const std::string & Text)
+{
+	hoverText = Text;
+
+	if (enteringText == false)
+		setText(hoverText);
+}
+
+void CGStatusBar::clearIfMatching(const std::string & Text)
+{
+	if (hoverText == Text)
+		clear();
 }
 
 void CGStatusBar::clear()
 {
-	setText("");
+	write({});
 }
 
-CGStatusBar::CGStatusBar(std::shared_ptr<CPicture> background_, EFonts Font, EAlignment Align, const SDL_Color & Color)
+CGStatusBar::CGStatusBar(std::shared_ptr<CPicture> background_, EFonts Font, ETextAlignment Align, const SDL_Color & Color)
 	: CLabel(background_->pos.x, background_->pos.y, Font, Align, Color, "")
+	, enteringText(false)
 {
 	background = background_;
 	addChild(background.get());
 	pos = background->pos;
 	getBorderSize();
-	textLock = false;
 	autoRedraw = false;
 }
 
 CGStatusBar::CGStatusBar(int x, int y, std::string name, int maxw)
-	: CLabel(x, y, FONT_SMALL, CENTER)
+	: CLabel(x, y, FONT_SMALL, ETextAlignment::CENTER)
+	, enteringText(false)
 {
 	OBJECT_CONSTRUCTION_CAPTURING(255 - DISPOSE);
 	background = std::make_shared<CPicture>(name);
@@ -374,7 +411,6 @@ CGStatusBar::CGStatusBar(int x, int y, std::string name, int maxw)
 		vstd::amin(pos.w, maxw);
 		background->srcRect = new Rect(0, 0, maxw, pos.h);
 	}
-	textLock = false;
 	autoRedraw = false;
 }
 
@@ -409,21 +445,16 @@ Point CGStatusBar::getBorderSize()
 
 	switch(alignment)
 	{
-	case TOPLEFT:     return Point(borderSize.x, borderSize.y);
-	case CENTER:      return Point(pos.w / 2, pos.h / 2);
-	case BOTTOMRIGHT: return Point(pos.w - borderSize.x, pos.h - borderSize.y);
+	case ETextAlignment::TOPLEFT:     return Point(borderSize.x, borderSize.y);
+	case ETextAlignment::CENTER:      return Point(pos.w / 2, pos.h / 2);
+	case ETextAlignment::BOTTOMRIGHT: return Point(pos.w - borderSize.x, pos.h - borderSize.y);
 	}
 	assert(0);
 	return Point();
 }
 
-void CGStatusBar::lock(bool shouldLock)
-{
-	textLock = shouldLock;
-}
-
 CTextInput::CTextInput(const Rect & Pos, EFonts font, const CFunctionList<void(const std::string &)> & CB)
-	: CLabel(Pos.x, Pos.y, font, CENTER),
+	: CLabel(Pos.x, Pos.y, font, ETextAlignment::CENTER),
 	cb(CB),
 	CFocusable(std::make_shared<CKeyboardFocusListener>(this))
 {
@@ -465,9 +496,9 @@ CTextInput::CTextInput(const Rect & Pos, SDL_Surface * srf)
 	background = std::make_shared<CPicture>(Pos, 0, true);
 	Rect hlp = Pos;
 	if(srf)
-		CSDL_Ext::blitSurface(srf, &hlp, *background.get(), nullptr);
+		CSDL_Ext::blitSurface(srf, &hlp, background->getSurface(), nullptr);
 	else
-		SDL_FillRect(*background.get(), nullptr, 0);
+		SDL_FillRect(background->getSurface(), nullptr, 0);
 	pos.w = background->pos.w;
 	pos.h = background->pos.h;
 	background->pos = pos;

+ 22 - 15
client/widgets/TextControls.h

@@ -25,10 +25,10 @@ protected:
 	/// do actual blitting of line. Text "what" will be placed at "where" and aligned according to alignment
 	void blitLine(SDL_Surface * to, Rect where, std::string what);
 
-	CTextContainer(EAlignment alignment, EFonts font, SDL_Color color);
+	CTextContainer(ETextAlignment alignment, EFonts font, SDL_Color color);
 
 public:
-	EAlignment alignment;
+	ETextAlignment alignment;
 	EFonts font;
 	SDL_Color color; // default font color. Can be overridden by placing "{}" into the string
 };
@@ -52,7 +52,7 @@ public:
 	virtual void setColor(const SDL_Color & Color);
 	size_t getWidth();
 
-	CLabel(int x = 0, int y = 0, EFonts Font = FONT_SMALL, EAlignment Align = TOPLEFT,
+	CLabel(int x = 0, int y = 0, EFonts Font = FONT_SMALL, ETextAlignment Align = ETextAlignment::TOPLEFT,
 		const SDL_Color & Color = Colors::WHITE, const std::string & Text = "");
 	void showAll(SDL_Surface * to) override; //shows statusbar (with current text)
 };
@@ -62,10 +62,10 @@ class CLabelGroup : public CIntObject
 {
 	std::vector<std::shared_ptr<CLabel>> labels;
 	EFonts font;
-	EAlignment align;
+	ETextAlignment align;
 	SDL_Color color;
 public:
-	CLabelGroup(EFonts Font = FONT_SMALL, EAlignment Align = TOPLEFT, const SDL_Color & Color = Colors::WHITE);
+	CLabelGroup(EFonts Font = FONT_SMALL, ETextAlignment Align = ETextAlignment::TOPLEFT, const SDL_Color & Color = Colors::WHITE);
 	void add(int x = 0, int y = 0, const std::string & text = "");
 	size_t currentSize() const;
 };
@@ -86,7 +86,7 @@ public:
 	// total size of text, x = longest line of text, y = total height of lines
 	Point textSize;
 
-	CMultiLineLabel(Rect position, EFonts Font = FONT_SMALL, EAlignment Align = TOPLEFT, const SDL_Color & Color = Colors::WHITE, const std::string & Text = "");
+	CMultiLineLabel(Rect position, EFonts Font = FONT_SMALL, ETextAlignment Align = ETextAlignment::TOPLEFT, const SDL_Color & Color = Colors::WHITE, const std::string & Text = "");
 
 	void setText(const std::string & Txt) override;
 	void showAll(SDL_Surface * to) override;
@@ -106,7 +106,7 @@ public:
 	std::shared_ptr<CMultiLineLabel> label;
 	std::shared_ptr<CSlider> slider;
 
-	CTextBox(std::string Text, const Rect & rect, int SliderStyle, EFonts Font = FONT_SMALL, EAlignment Align = TOPLEFT, const SDL_Color & Color = Colors::WHITE);
+	CTextBox(std::string Text, const Rect & rect, int SliderStyle, EFonts Font = FONT_SMALL, ETextAlignment Align = ETextAlignment::TOPLEFT, const SDL_Color & Color = Colors::WHITE);
 
 	void resize(Point newSize);
 	void setText(const std::string & Txt);
@@ -114,12 +114,15 @@ public:
 };
 
 /// Status bar which is shown at the bottom of the in-game screens
-class CGStatusBar : public CLabel, public std::enable_shared_from_this<CGStatusBar>
+class CGStatusBar : public CLabel, public std::enable_shared_from_this<CGStatusBar>, public IStatusBar
 {
-	bool textLock; //Used for blocking changes to the text
+	std::string hoverText;
+	std::string consoleText;
+	bool enteringText;
+
 	void init();
 
-	CGStatusBar(std::shared_ptr<CPicture> background_, EFonts Font = FONT_SMALL, EAlignment Align = CENTER, const SDL_Color & Color = Colors::WHITE);
+	CGStatusBar(std::shared_ptr<CPicture> background_, EFonts Font = FONT_SMALL, ETextAlignment Align = ETextAlignment::CENTER, const SDL_Color & Color = Colors::WHITE);
 	CGStatusBar(int x, int y, std::string name, int maxw = -1);
 protected:
 	Point getBorderSize() override;
@@ -137,14 +140,18 @@ public:
 		ret->init();
 		return ret;
 	}
-	void clear();//clears statusbar and refreshes
-	void setText(const std::string & Text) override; //prints text and refreshes statusbar
 
-	void show(SDL_Surface * to) override; //shows statusbar (with current text)
+	void setOnClick(std::function<void()> handler);
+
+	void show(SDL_Surface * to) override;
 
-	void lock(bool shouldLock); //If true, current text cannot be changed until lock(false) is called
+	// IStatusBar interface
+	void write(const std::string & Text) override;
+	void clearIfMatching(const std::string & Text) override;
+	void clear() override;
+	void setEnteringMode(bool on) override;
+	void setEnteredText(const std::string & text) override;
 
-	void setOnClick(std::function<void()> handler);
 };
 
 class CFocusable;

+ 5 - 5
client/windows/CAdvmapInterface.cpp

@@ -692,19 +692,19 @@ CAdvMapInt::CAdvMapInt():
 	for (int i = 0; i < 5; ++i)
 	{
 		panelWorldView->addChildIcon(std::pair<int, Point>(i, Point(5, 58 + i * 20)), iconColorMultiplier);
-		panelWorldView->addChildToPanel(std::make_shared<CLabel>(wvLeft + 45, 263 + i * 20, EFonts::FONT_SMALL, EAlignment::TOPLEFT,
+		panelWorldView->addChildToPanel(std::make_shared<CLabel>(wvLeft + 45, 263 + i * 20, EFonts::FONT_SMALL, ETextAlignment::TOPLEFT,
 												Colors::WHITE, CGI->generaltexth->allTexts[612 + i]));
 	}
 	for (int i = 0; i < 7; ++i)
 	{
 		panelWorldView->addChildIcon(std::pair<int, Point>(i +  5, Point(5, 182 + i * 20)), iconColorMultiplier);
 		panelWorldView->addChildIcon(std::pair<int, Point>(i + 12, Point(160, 182 + i * 20)), iconColorMultiplier);
-		panelWorldView->addChildToPanel(std::make_shared<CLabel>(wvLeft + 45, 387 + i * 20, EFonts::FONT_SMALL, EAlignment::TOPLEFT,
+		panelWorldView->addChildToPanel(std::make_shared<CLabel>(wvLeft + 45, 387 + i * 20, EFonts::FONT_SMALL, ETextAlignment::TOPLEFT,
 												Colors::WHITE, CGI->generaltexth->allTexts[619 + i]));
 	}
-	panelWorldView->addChildToPanel(std::make_shared<CLabel>(wvLeft +   5, 367, EFonts::FONT_SMALL, EAlignment::TOPLEFT,
+	panelWorldView->addChildToPanel(std::make_shared<CLabel>(wvLeft +   5, 367, EFonts::FONT_SMALL, ETextAlignment::TOPLEFT,
 											Colors::WHITE, CGI->generaltexth->allTexts[617]));
-	panelWorldView->addChildToPanel(std::make_shared<CLabel>(wvLeft + 45, 367, EFonts::FONT_SMALL, EAlignment::TOPLEFT,
+	panelWorldView->addChildToPanel(std::make_shared<CLabel>(wvLeft + 45, 367, EFonts::FONT_SMALL, ETextAlignment::TOPLEFT,
 											Colors::WHITE, CGI->generaltexth->allTexts[618]));
 
 	activeMapPanel = panelMain;
@@ -1810,7 +1810,7 @@ void CAdvMapInt::tileRClicked(const int3 &mapPos)
 		return;
 	}
 
-	CRClickPopup::createAndPush(obj, GH.current->motion, CENTER);
+	CRClickPopup::createAndPush(obj, GH.current->motion, ETextAlignment::CENTER);
 }
 
 void CAdvMapInt::enterCastingMode(const CSpell * sp)

+ 38 - 38
client/windows/CCastleInterface.cpp

@@ -261,7 +261,7 @@ void CBuildingRect::mouseMoved (const SDL_MouseMotionEvent & sEvent)
 			  || (*parent->selectedBuilding)<(*this)) //or we are on top
 			{
 				parent->selectedBuilding = this;
-				GH.statusbar->setText(getSubtitle());
+				GH.statusbar->write(getSubtitle());
 			}
 		}
 	}
@@ -275,19 +275,19 @@ CDwellingInfoBox::CDwellingInfoBox(int centerX, int centerY, const CGTownInstanc
 
 	const CCreature * creature = CGI->creh->objects.at(Town->creatures.at(level).second.back());
 
-	title = std::make_shared<CLabel>(80, 30, FONT_SMALL, CENTER, Colors::WHITE, creature->namePl);
+	title = std::make_shared<CLabel>(80, 30, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, creature->namePl);
 	animation = std::make_shared<CCreaturePic>(30, 44, creature, true, true);
 
 	std::string text = boost::lexical_cast<std::string>(Town->creatures.at(level).first);
-	available = std::make_shared<CLabel>(80,190, FONT_SMALL, CENTER, Colors::WHITE, CGI->generaltexth->allTexts[217] + text);
-	costPerTroop = std::make_shared<CLabel>(80, 227, FONT_SMALL, CENTER, Colors::WHITE, CGI->generaltexth->allTexts[346]);
+	available = std::make_shared<CLabel>(80,190, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[217] + text);
+	costPerTroop = std::make_shared<CLabel>(80, 227, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[346]);
 
 	for(int i = 0; i<GameConstants::RESOURCE_QUANTITY; i++)
 	{
 		if(creature->cost[i])
 		{
 			resPicture.push_back(std::make_shared<CAnimImage>("RESOURCE", i, 0, 0, 0));
-			resAmount.push_back(std::make_shared<CLabel>(0,0, FONT_SMALL, CENTER, Colors::WHITE, boost::lexical_cast<std::string>(creature->cost[i])));
+			resAmount.push_back(std::make_shared<CLabel>(0,0, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, boost::lexical_cast<std::string>(creature->cost[i])));
 		}
 	}
 
@@ -379,7 +379,7 @@ void CHeroGSlot::hover(bool on)
 		}
 	}
 	if(temp.size())
-		GH.statusbar->setText(temp);
+		GH.statusbar->write(temp);
 }
 
 void CHeroGSlot::clickLeft(tribool down, bool previousState)
@@ -996,14 +996,14 @@ CCreaInfo::CCreaInfo(Point position, const CGTownInstance * Town, int Level, boo
 
 	if(compact)
 	{
-		label = std::make_shared<CLabel>(40, 32, FONT_TINY, BOTTOMRIGHT, Colors::WHITE, value);
+		label = std::make_shared<CLabel>(40, 32, FONT_TINY, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, value);
 		pos.x += 8;
 		pos.w = 32;
 		pos.h = 32;
 	}
 	else
 	{
-		label = std::make_shared<CLabel>(24, 40, FONT_SMALL, CENTER, Colors::WHITE, value);
+		label = std::make_shared<CLabel>(24, 40, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, value);
 		pos.w = 48;
 		pos.h = 48;
 	}
@@ -1031,11 +1031,11 @@ void CCreaInfo::hover(bool on)
 
 	if(on)
 	{
-		GH.statusbar->setText(message);
+		GH.statusbar->write(message);
 	}
-	else if (message == GH.statusbar->getText())
+	else
 	{
-		GH.statusbar->clear();
+		GH.statusbar->clearIfMatching(message);
 	}
 }
 
@@ -1105,7 +1105,7 @@ void CTownInfo::hover(bool on)
 	if(on)
 	{
 		if(building )
-			GH.statusbar->setText(building->Name());
+			GH.statusbar->write(building->Name());
 	}
 	else
 	{
@@ -1143,8 +1143,8 @@ CCastleInterface::CCastleInterface(const CGTownInstance * Town, const CGTownInst
 	garr->type |= REDRAW_PARENT;
 
 	heroes = std::make_shared<HeroSlots>(town, Point(241, 387), Point(241, 483), garr, true);
-	title = std::make_shared<CLabel>(85, 387, FONT_MEDIUM, TOPLEFT, Colors::WHITE, town->name);
-	income = std::make_shared<CLabel>(195, 443, FONT_SMALL, CENTER);
+	title = std::make_shared<CLabel>(85, 387, FONT_MEDIUM, ETextAlignment::TOPLEFT, Colors::WHITE, town->name);
+	income = std::make_shared<CLabel>(195, 443, FONT_SMALL, ETextAlignment::CENTER);
 	icon = std::make_shared<CAnimImage>("ITPT", 0, 0, 15, 387);
 
 	exit = std::make_shared<CButton>(Point(744, 544), "TSBTNS", CButton::tooltip(CGI->generaltexth->tcommands[8]), [&](){close();}, SDLK_RETURN);
@@ -1159,7 +1159,7 @@ CCastleInterface::CCastleInterface(const CGTownInstance * Town, const CGTownInst
 	garr->addSplitBtn(split);
 
 	Rect barRect(9, 182, 732, 18);
-	auto statusbarBackground = std::make_shared<CPicture>(*(panel.get()), barRect, 9, 555, false);
+	auto statusbarBackground = std::make_shared<CPicture>(panel->getSurface(), barRect, 9, 555, false);
 	statusbar = CGStatusBar::create(statusbarBackground);
 	resdatabar = std::make_shared<CResDataBar>("ARESBAR", 3, 575, 32, 2, 85, 85);
 
@@ -1307,7 +1307,7 @@ CHallInterface::CBuildingBox::CBuildingBox(int x, int y, const CGTownInstance *
 	header = std::make_shared<CAnimImage>("TPTHBAR", panelIndex[state], 0, 1, 73);
 	if(iconIndex[state] >=0)
 		mark = std::make_shared<CAnimImage>("TPTHCHK", iconIndex[state], 0, 136, 56);
-	name = std::make_shared<CLabel>(75, 81, FONT_SMALL, CENTER, Colors::WHITE, building->Name());
+	name = std::make_shared<CLabel>(75, 81, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, building->Name());
 
 	//todo: add support for all possible states
 	if(state >= EBuildingState::BUILDING_ERROR)
@@ -1326,7 +1326,7 @@ void CHallInterface::CBuildingBox::hover(bool on)
 		else
 			toPrint = CGI->generaltexth->hcommands[state];
 		boost::algorithm::replace_first(toPrint,"%s",building->Name());
-		GH.statusbar->setText(toPrint);
+		GH.statusbar->write(toPrint);
 	}
 	else
 	{
@@ -1356,10 +1356,10 @@ CHallInterface::CHallInterface(const CGTownInstance * Town):
 	resdatabar->moveBy(pos.topLeft(), true);
 	Rect barRect(5, 556, 740, 18);
 
-	auto statusbarBackground = std::make_shared<CPicture>(*background, barRect, 5, 556, false);
+	auto statusbarBackground = std::make_shared<CPicture>(background->getSurface(), barRect, 5, 556, false);
 	statusbar = CGStatusBar::create(statusbarBackground);
 
-	title = std::make_shared<CLabel>(399, 12, FONT_MEDIUM, CENTER, Colors::WHITE, town->town->buildings.at(BuildingID(town->hallLevel()+BuildingID::VILLAGE_HALL))->Name());
+	title = std::make_shared<CLabel>(399, 12, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, town->town->buildings.at(BuildingID(town->hallLevel()+BuildingID::VILLAGE_HALL))->Name());
 	exit = std::make_shared<CButton>(Point(748, 556), "TPMAGE1.DEF", CButton::tooltip(CGI->generaltexth->hcommands[8]), [&](){close();}, SDLK_RETURN);
 	exit->assignedKeys.insert(SDLK_ESCAPE);
 
@@ -1403,12 +1403,12 @@ CBuildWindow::CBuildWindow(const CGTownInstance *Town, const CBuilding * Buildin
 	OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
 
 	icon = std::make_shared<CAnimImage>(town->town->clientInfo.buildingsIcons, building->bid, 0, 125, 50);
-	auto statusbarBackground = std::make_shared<CPicture>(*background, Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26);
+	auto statusbarBackground = std::make_shared<CPicture>(background->getSurface(), Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26);
 	statusbar = CGStatusBar::create(statusbarBackground);
 
-	name = std::make_shared<CLabel>(197, 30, FONT_MEDIUM, CENTER, Colors::WHITE, boost::str(boost::format(CGI->generaltexth->hcommands[7]) % building->Name()));
-	description = std::make_shared<CTextBox>(building->Description(), Rect(33, 135, 329, 67), 0, FONT_MEDIUM, CENTER);
-	stateText = std::make_shared<CTextBox>(getTextForState(state), Rect(33, 216, 329, 67), 0, FONT_SMALL, CENTER);
+	name = std::make_shared<CLabel>(197, 30, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, boost::str(boost::format(CGI->generaltexth->hcommands[7]) % building->Name()));
+	description = std::make_shared<CTextBox>(building->Description(), Rect(33, 135, 329, 67), 0, FONT_MEDIUM, ETextAlignment::CENTER);
+	stateText = std::make_shared<CTextBox>(getTextForState(state), Rect(33, 216, 329, 67), 0, FONT_SMALL, ETextAlignment::CENTER);
 
 	//Create components for all required resources
 	std::vector<std::shared_ptr<CComponent>> components;
@@ -1507,15 +1507,15 @@ void LabeledValue::init(std::string nameText, std::string descr, int min, int ma
 		if(min != max)
 			valueText += '-' + boost::lexical_cast<std::string>(max);
 	}
-	name = std::make_shared<CLabel>(3, 0, FONT_SMALL, TOPLEFT, Colors::WHITE, nameText);
-	value = std::make_shared<CLabel>(pos.w-3, pos.h-2, FONT_SMALL, BOTTOMRIGHT, Colors::WHITE, valueText);
+	name = std::make_shared<CLabel>(3, 0, FONT_SMALL, ETextAlignment::TOPLEFT, Colors::WHITE, nameText);
+	value = std::make_shared<CLabel>(pos.w-3, pos.h-2, FONT_SMALL, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, valueText);
 }
 
 void LabeledValue::hover(bool on)
 {
 	if(on)
 	{
-		GH.statusbar->setText(hoverText);
+		GH.statusbar->write(hoverText);
 	}
 	else
 	{
@@ -1533,7 +1533,7 @@ CFortScreen::CFortScreen(const CGTownInstance * town):
 		fortSize--;
 
 	const CBuilding * fortBuilding = town->town->buildings.at(BuildingID(town->fortLevel()+6));
-	title = std::make_shared<CLabel>(400, 12, FONT_BIG, CENTER, Colors::WHITE, fortBuilding->Name());
+	title = std::make_shared<CLabel>(400, 12, FONT_BIG, ETextAlignment::CENTER, Colors::WHITE, fortBuilding->Name());
 
 	std::string text = boost::str(boost::format(CGI->generaltexth->fcommands[6]) % fortBuilding->Name());
 	exit = std::make_shared<CButton>(Point(748, 556), "TPMAGE1", CButton::tooltip(text), [&](){ close(); }, SDLK_RETURN);
@@ -1579,7 +1579,7 @@ CFortScreen::CFortScreen(const CGTownInstance * town):
 
 	Rect barRect(4, 554, 740, 18);
 
-	auto statusbarBackground = std::make_shared<CPicture>(*background, barRect, 4, 554, false);
+	auto statusbarBackground = std::make_shared<CPicture>(background->getSurface(), barRect, 4, 554, false);
 	statusbar = CGStatusBar::create(statusbarBackground);
 }
 
@@ -1620,13 +1620,13 @@ CFortScreen::RecruitArea::RecruitArea(int posX, int posY, const CGTownInstance *
 	if(getMyBuilding() != nullptr)
 	{
 		buildingIcon = std::make_shared<CAnimImage>(town->town->clientInfo.buildingsIcons, getMyBuilding()->bid, 0, 4, 21);
-		buildingName = std::make_shared<CLabel>(78, 101, FONT_SMALL, CENTER, Colors::WHITE, getMyBuilding()->Name());
+		buildingName = std::make_shared<CLabel>(78, 101, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, getMyBuilding()->Name());
 
 		if(vstd::contains(town->builtBuildings, getMyBuilding()->bid))
 		{
 			ui32 available = town->creatures[level].first;
 			std::string availableText = CGI->generaltexth->allTexts[217]+ boost::lexical_cast<std::string>(available);
-			availableCount = std::make_shared<CLabel>(78, 119, FONT_SMALL, CENTER, Colors::WHITE, availableText);
+			availableCount = std::make_shared<CLabel>(78, 119, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, availableText);
 		}
 	}
 
@@ -1634,7 +1634,7 @@ CFortScreen::RecruitArea::RecruitArea(int posX, int posY, const CGTownInstance *
 	{
 		hoverText = boost::str(boost::format(CGI->generaltexth->tcommands[21]) % getMyCreature()->namePl);
 		new CCreaturePic(159, 4, getMyCreature(), false);
-		new CLabel(78,  11, FONT_SMALL, CENTER, Colors::WHITE, getMyCreature()->namePl);
+		new CLabel(78,  11, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, getMyCreature()->namePl);
 
 		Rect sizes(287, 4, 96, 18);
 		values.push_back(std::make_shared<LabeledValue>(sizes, CGI->generaltexth->allTexts[190], CGI->generaltexth->fcommands[0], getMyCreature()->getAttack(false)));
@@ -1683,7 +1683,7 @@ const CBuilding * CFortScreen::RecruitArea::getMyBuilding()
 void CFortScreen::RecruitArea::hover(bool on)
 {
 	if(on)
-		GH.statusbar->setText(hoverText);
+		GH.statusbar->write(hoverText);
 	else
 		GH.statusbar->clear();
 }
@@ -1720,7 +1720,7 @@ CMageGuildScreen::CMageGuildScreen(CCastleInterface * owner,std::string imagem)
 
 	Rect barRect(7, 556, 737, 18);
 
-	auto statusbarBackground = std::make_shared<CPicture>(*background, barRect, 7, 556, false);
+	auto statusbarBackground = std::make_shared<CPicture>(background->getSurface(), barRect, 7, 556, false);
 	statusbar = CGStatusBar::create(statusbarBackground);
 
 	exit = std::make_shared<CButton>(Point(748, 556), "TPMAGE1.DEF", CButton::tooltip(CGI->generaltexth->allTexts[593]), [&](){ close(); }, SDLK_RETURN);
@@ -1774,7 +1774,7 @@ void CMageGuildScreen::Scroll::clickRight(tribool down, bool previousState)
 void CMageGuildScreen::Scroll::hover(bool on)
 {
 	if(on)
-		GH.statusbar->setText(spell->name);
+		GH.statusbar->write(spell->name);
 	else
 		GH.statusbar->clear();
 
@@ -1787,7 +1787,7 @@ CBlacksmithDialog::CBlacksmithDialog(bool possible, CreatureID creMachineID, Art
 
 	Rect barRect(8, pos.h - 26, pos.w - 16, 19);
 
-	auto statusbarBackground = std::make_shared<CPicture>(*background, barRect, 8, pos.h - 26, false);
+	auto statusbarBackground = std::make_shared<CPicture>(background->getSurface(), barRect, 8, pos.h - 26, false);
 	statusbar = CGStatusBar::create(statusbarBackground);
 
 	animBG = std::make_shared<CPicture>("TPSMITBK", 64, 50);
@@ -1797,10 +1797,10 @@ CBlacksmithDialog::CBlacksmithDialog(bool possible, CreatureID creMachineID, Art
 	anim = std::make_shared<CCreatureAnim>(64, 50, creature->animDefName);
 	anim->clipRect(113,125,200,150);
 
-	title = std::make_shared<CLabel>(165, 28, FONT_BIG, CENTER, Colors::YELLOW,
+	title = std::make_shared<CLabel>(165, 28, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW,
 	            boost::str(boost::format(CGI->generaltexth->allTexts[274]) % creature->nameSing));
-	costText = std::make_shared<CLabel>(165, 218, FONT_MEDIUM, CENTER, Colors::WHITE, CGI->generaltexth->jktexts[43]);
-	costValue = std::make_shared<CLabel>(165, 290, FONT_MEDIUM, CENTER, Colors::WHITE,
+	costText = std::make_shared<CLabel>(165, 218, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->jktexts[43]);
+	costValue = std::make_shared<CLabel>(165, 290, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE,
 	                boost::lexical_cast<std::string>(aid.toArtifact(CGI->artifacts())->getPrice()));
 
 	std::string text = boost::str(boost::format(CGI->generaltexth->allTexts[595]) % creature->nameSing);

+ 6 - 6
client/windows/CCreatureWindow.cpp

@@ -239,8 +239,8 @@ CStackWindow::BonusLineSection::BonusLineSection(CStackWindow * owner, size_t li
 		{
 			BonusInfo & bi = parent->activeBonuses[bonusIndex];
 			icon[leftRight] = std::make_shared<CPicture>(bi.imagePath, position.x, position.y);
-			name[leftRight] = std::make_shared<CLabel>(position.x + 60, position.y + 2, FONT_SMALL, TOPLEFT, Colors::WHITE, bi.name);
-			description[leftRight] = std::make_shared<CMultiLineLabel>(Rect(position.x + 60, position.y + 17, 137, 30), FONT_SMALL, TOPLEFT, Colors::WHITE, bi.description);
+			name[leftRight] = std::make_shared<CLabel>(position.x + 60, position.y + 2, FONT_SMALL, ETextAlignment::TOPLEFT, Colors::WHITE, bi.name);
+			description[leftRight] = std::make_shared<CMultiLineLabel>(Rect(position.x + 60, position.y + 17, 137, 30), FONT_SMALL, ETextAlignment::TOPLEFT, Colors::WHITE, bi.description);
 		}
 	}
 }
@@ -511,7 +511,7 @@ CStackWindow::MainSection::MainSection(CStackWindow * owner, int yOffset, bool s
 		animation->setAmount(parent->info->creatureCount);
 	}
 
-	name = std::make_shared<CLabel>(215, 12, FONT_SMALL, CENTER, Colors::YELLOW, parent->info->getName());
+	name = std::make_shared<CLabel>(215, 12, FONT_SMALL, ETextAlignment::CENTER, Colors::YELLOW, parent->info->getName());
 
 	int dmgMultiply = 1;
 	if(parent->info->owner && parent->info->stackNode->hasBonusOfType(Bonus::SIEGE_WEAPON))
@@ -585,7 +585,7 @@ CStackWindow::MainSection::MainSection(CStackWindow * owner, int yOffset, bool s
 			expArea->text = parent->generateStackExpDescription();
 		}
 		expLabel = std::make_shared<CLabel>(
-				pos.x + 21, pos.y + 52, FONT_SMALL, CENTER, Colors::WHITE,
+				pos.x + 21, pos.y + 52, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE,
 				makeNumberShort<TExpType>(stack->experience, 6));
 	}
 
@@ -630,7 +630,7 @@ std::string CStackWindow::MainSection::getBackgroundName(bool showExp, bool show
 void CStackWindow::MainSection::addStatLabel(EStat index, int64_t value1, int64_t value2)
 {
 	const auto title = statNames.at(static_cast<size_t>(index));
-	stats.push_back(std::make_shared<CLabel>(145, 32 + (int)index*19, FONT_SMALL, TOPLEFT, Colors::WHITE, title));
+	stats.push_back(std::make_shared<CLabel>(145, 32 + (int)index*19, FONT_SMALL, ETextAlignment::TOPLEFT, Colors::WHITE, title));
 
 	const bool useRange = value1 != value2;
 	std::string formatStr = useRange ? statFormats.at(static_cast<size_t>(index)) : "%d";
@@ -640,7 +640,7 @@ void CStackWindow::MainSection::addStatLabel(EStat index, int64_t value1, int64_
 	if(useRange)
 		fmt % value2;
 
-	stats.push_back(std::make_shared<CLabel>(307, 48 + (int)index*19, FONT_SMALL, BOTTOMRIGHT, Colors::WHITE, fmt.str()));
+	stats.push_back(std::make_shared<CLabel>(307, 48 + (int)index*19, FONT_SMALL, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, fmt.str()));
 }
 
 void CStackWindow::MainSection::addStatLabel(EStat index, int64_t value)

+ 15 - 16
client/windows/CHeroWindow.cpp

@@ -15,7 +15,6 @@
 #include "CKingdomInterface.h"
 #include "GUIClasses.h"
 
-#include "../CBitmapHandler.h"
 #include "../CGameInfo.h"
 #include "../CMessage.h"
 #include "../CMT.h"
@@ -109,18 +108,18 @@ CHeroWindow::CHeroWindow(const CGHeroInstance * hero)
 	curHero = hero;
 
 	banner = std::make_shared<CAnimImage>("CREST58", LOCPLINT->playerID.getNum(), 0, 606, 8);
-	name = std::make_shared<CLabel>(190, 38, EFonts::FONT_BIG, EAlignment::CENTER, Colors::YELLOW);
-	title = std::make_shared<CLabel>(190, 65, EFonts::FONT_MEDIUM, EAlignment::CENTER, Colors::WHITE);
+	name = std::make_shared<CLabel>(190, 38, EFonts::FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW);
+	title = std::make_shared<CLabel>(190, 65, EFonts::FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE);
 
 	statusbar = CGStatusBar::create(7, 559, "ADROLLVR.bmp", 660);
 
 	quitButton = std::make_shared<CButton>(Point(609, 516), "hsbtns.def", CButton::tooltip(heroscrn[17]), [=](){ close(); }, SDLK_RETURN);
 	quitButton->assignedKeys.insert(SDLK_ESCAPE);
 
-	dismissLabel = std::make_shared<CTextBox>(CGI->generaltexth->jktexts[8], Rect(370, 430, 65, 35), 0, FONT_SMALL, TOPLEFT, Colors::WHITE);
+	dismissLabel = std::make_shared<CTextBox>(CGI->generaltexth->jktexts[8], Rect(370, 430, 65, 35), 0, FONT_SMALL, ETextAlignment::TOPLEFT, Colors::WHITE);
 	dismissButton = std::make_shared<CButton>(Point(454, 429), "hsbtns2.def", CButton::tooltip(heroscrn[28]), [=](){ dismissCurrent(); }, SDLK_d);
 
-	questlogLabel = std::make_shared<CTextBox>(CGI->generaltexth->jktexts[9], Rect(510, 430, 65, 35), 0, FONT_SMALL, TOPLEFT, Colors::WHITE);
+	questlogLabel = std::make_shared<CTextBox>(CGI->generaltexth->jktexts[9], Rect(510, 430, 65, 35), 0, FONT_SMALL, ETextAlignment::TOPLEFT, Colors::WHITE);
 	questlogButton = std::make_shared<CButton>(Point(314, 429), "hsbtns4.def", CButton::tooltip(heroscrn[0]), [=](){ LOCPLINT->showQuestLog(); }, SDLK_q);
 
 	formations = std::make_shared<CToggleGroup>(0);
@@ -149,7 +148,7 @@ CHeroWindow::CHeroWindow(const CGHeroInstance * hero)
 		area->hoverText = boost::str(boost::format(CGI->generaltexth->heroscrn[1]) % CGI->generaltexth->primarySkillNames[v]);
 		primSkillAreas.push_back(area);
 
-		auto value = std::make_shared<CLabel>(53 + 70 * v, 166, FONT_SMALL, CENTER);
+		auto value = std::make_shared<CLabel>(53 + 70 * v, 166, FONT_SMALL, ETextAlignment::CENTER);
 		primSkillValues.push_back(value);
 	}
 
@@ -184,19 +183,19 @@ CHeroWindow::CHeroWindow(const CGHeroInstance * hero)
 		int x = (i % 2) ? 212 : 68;
 		int y = 280 + 48 * (i/2);
 
-		secSkillValues.push_back(std::make_shared<CLabel>(x, y, FONT_SMALL, TOPLEFT));
-		secSkillNames.push_back(std::make_shared<CLabel>(x, y+20, FONT_SMALL, TOPLEFT));
+		secSkillValues.push_back(std::make_shared<CLabel>(x, y, FONT_SMALL, ETextAlignment::TOPLEFT));
+		secSkillNames.push_back(std::make_shared<CLabel>(x, y+20, FONT_SMALL, ETextAlignment::TOPLEFT));
 	}
 
 	// various texts
-	labels.push_back(std::make_shared<CLabel>(52, 99, FONT_SMALL, CENTER, Colors::YELLOW, CGI->generaltexth->jktexts[1]));
-	labels.push_back(std::make_shared<CLabel>(123, 99, FONT_SMALL, CENTER, Colors::YELLOW, CGI->generaltexth->jktexts[2]));
-	labels.push_back(std::make_shared<CLabel>(193, 99, FONT_SMALL, CENTER, Colors::YELLOW, CGI->generaltexth->jktexts[3]));
-	labels.push_back(std::make_shared<CLabel>(262, 99, FONT_SMALL, CENTER, Colors::YELLOW, CGI->generaltexth->jktexts[4]));
-
-	labels.push_back(std::make_shared<CLabel>(69, 183, FONT_SMALL, TOPLEFT, Colors::YELLOW, CGI->generaltexth->jktexts[5]));
-	labels.push_back(std::make_shared<CLabel>(69, 232, FONT_SMALL, TOPLEFT, Colors::YELLOW, CGI->generaltexth->jktexts[6]));
-	labels.push_back(std::make_shared<CLabel>(213, 232, FONT_SMALL, TOPLEFT, Colors::YELLOW, CGI->generaltexth->jktexts[7]));
+	labels.push_back(std::make_shared<CLabel>(52, 99, FONT_SMALL, ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->jktexts[1]));
+	labels.push_back(std::make_shared<CLabel>(123, 99, FONT_SMALL, ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->jktexts[2]));
+	labels.push_back(std::make_shared<CLabel>(193, 99, FONT_SMALL, ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->jktexts[3]));
+	labels.push_back(std::make_shared<CLabel>(262, 99, FONT_SMALL, ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->jktexts[4]));
+
+	labels.push_back(std::make_shared<CLabel>(69, 183, FONT_SMALL, ETextAlignment::TOPLEFT, Colors::YELLOW, CGI->generaltexth->jktexts[5]));
+	labels.push_back(std::make_shared<CLabel>(69, 232, FONT_SMALL, ETextAlignment::TOPLEFT, Colors::YELLOW, CGI->generaltexth->jktexts[6]));
+	labels.push_back(std::make_shared<CLabel>(213, 232, FONT_SMALL, ETextAlignment::TOPLEFT, Colors::YELLOW, CGI->generaltexth->jktexts[7]));
 
 	update(hero);
 }

+ 17 - 17
client/windows/CKingdomInterface.cpp

@@ -54,20 +54,20 @@ InfoBox::InfoBox(Point position, InfoPos Pos, InfoSize Size, std::shared_ptr<IIn
 	switch(infoPos)
 	{
 	case POS_CORNER:
-		value = std::make_shared<CLabel>(pos.w, pos.h, font, BOTTOMRIGHT, Colors::WHITE, data->getValueText());
+		value = std::make_shared<CLabel>(pos.w, pos.h, font, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, data->getValueText());
 		break;
 	case POS_INSIDE:
-		value = std::make_shared<CLabel>(pos.w/2, pos.h-6, font, CENTER, Colors::WHITE, data->getValueText());
+		value = std::make_shared<CLabel>(pos.w/2, pos.h-6, font, ETextAlignment::CENTER, Colors::WHITE, data->getValueText());
 		break;
 	case POS_UP_DOWN:
-		name = std::make_shared<CLabel>(pos.w/2, -12, font, CENTER, Colors::WHITE, data->getNameText());
+		name = std::make_shared<CLabel>(pos.w/2, -12, font, ETextAlignment::CENTER, Colors::WHITE, data->getNameText());
 		FALLTHROUGH;
 	case POS_DOWN:
-		value = std::make_shared<CLabel>(pos.w/2, pos.h+8, font, CENTER, Colors::WHITE, data->getValueText());
+		value = std::make_shared<CLabel>(pos.w/2, pos.h+8, font, ETextAlignment::CENTER, Colors::WHITE, data->getValueText());
 		break;
 	case POS_RIGHT:
-		name = std::make_shared<CLabel>(pos.w+6, 6, font, TOPLEFT, Colors::WHITE, data->getNameText());
-		value = std::make_shared<CLabel>(pos.w+6, pos.h-16, font, TOPLEFT, Colors::WHITE, data->getValueText());
+		name = std::make_shared<CLabel>(pos.w+6, 6, font, ETextAlignment::TOPLEFT, Colors::WHITE, data->getNameText());
+		value = std::make_shared<CLabel>(pos.w+6, pos.h-16, font, ETextAlignment::TOPLEFT, Colors::WHITE, data->getValueText());
 		break;
 	}
 
@@ -601,7 +601,7 @@ void CKingdomInterface::generateMinesList(const std::vector<const CGObjectInstan
 	incomeArea = std::make_shared<CHoverableArea>();
 	incomeArea->pos = Rect(pos.x+580, pos.y+31+footerPos, 136, 68);
 	incomeArea->hoverText = CGI->generaltexth->allTexts[255];
-	incomeAmount = std::make_shared<CLabel>(628, footerPos + 70, FONT_SMALL, TOPLEFT, Colors::WHITE, boost::lexical_cast<std::string>(totalIncome));
+	incomeAmount = std::make_shared<CLabel>(628, footerPos + 70, FONT_SMALL, ETextAlignment::TOPLEFT, Colors::WHITE, boost::lexical_cast<std::string>(totalIncome));
 }
 
 void CKingdomInterface::generateButtons()
@@ -682,8 +682,8 @@ CKingdHeroList::CKingdHeroList(size_t maxSize)
 	OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
 	title = std::make_shared<CPicture>("OVTITLE",16,0);
 	title->colorize(LOCPLINT->playerID);
-	heroLabel = std::make_shared<CLabel>(150, 10, FONT_MEDIUM, CENTER, Colors::WHITE, CGI->generaltexth->overview[0]);
-	skillsLabel = std::make_shared<CLabel>(500, 10, FONT_MEDIUM, CENTER, Colors::WHITE, CGI->generaltexth->overview[1]);
+	heroLabel = std::make_shared<CLabel>(150, 10, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->overview[0]);
+	skillsLabel = std::make_shared<CLabel>(500, 10, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->overview[1]);
 
 	ui32 townCount = LOCPLINT->cb->howManyHeroes(false);
 	ui32 size = conf.go()->ac.overviewSize*116 + 19;
@@ -722,9 +722,9 @@ CKingdTownList::CKingdTownList(size_t maxSize)
 	OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
 	title = std::make_shared<CPicture>("OVTITLE", 16, 0);
 	title->colorize(LOCPLINT->playerID);
-	townLabel = std::make_shared<CLabel>(146, 10,FONT_MEDIUM, CENTER, Colors::WHITE, CGI->generaltexth->overview[3]);
-	garrHeroLabel = std::make_shared<CLabel>(375, 10, FONT_MEDIUM, CENTER, Colors::WHITE, CGI->generaltexth->overview[4]);
-	visitHeroLabel = std::make_shared<CLabel>(608, 10, FONT_MEDIUM, CENTER, Colors::WHITE, CGI->generaltexth->overview[5]);
+	townLabel = std::make_shared<CLabel>(146, 10,FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->overview[3]);
+	garrHeroLabel = std::make_shared<CLabel>(375, 10, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->overview[4]);
+	visitHeroLabel = std::make_shared<CLabel>(608, 10, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->overview[5]);
 
 	ui32 townCount = LOCPLINT->cb->howManyTowns();
 	ui32 size = conf.go()->ac.overviewSize*116 + 19;
@@ -767,9 +767,9 @@ CTownItem::CTownItem(const CGTownInstance * Town)
 {
 	OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
 	background = std::make_shared<CAnimImage>("OVSLOT", 6);
-	name = std::make_shared<CLabel>(74, 8, FONT_SMALL, TOPLEFT, Colors::WHITE, town->name);
+	name = std::make_shared<CLabel>(74, 8, FONT_SMALL, ETextAlignment::TOPLEFT, Colors::WHITE, town->name);
 
-	income = std::make_shared<CLabel>( 190, 60, FONT_SMALL, CENTER, Colors::WHITE, boost::lexical_cast<std::string>(town->dailyIncome()[Res::GOLD]));
+	income = std::make_shared<CLabel>( 190, 60, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, boost::lexical_cast<std::string>(town->dailyIncome()[Res::GOLD]));
 	hall = std::make_shared<CTownInfo>( 69, 31, town, true);
 	fort = std::make_shared<CTownInfo>(111, 31, town, false);
 
@@ -863,7 +863,7 @@ CHeroItem::CHeroItem(const CGHeroInstance * Hero)
 	arts2->recActions = SHARE_POS;
 	backpack->recActions = SHARE_POS;
 
-	name = std::make_shared<CLabel>(75, 7, FONT_SMALL, TOPLEFT, Colors::WHITE, hero->name);
+	name = std::make_shared<CLabel>(75, 7, FONT_SMALL, ETextAlignment::TOPLEFT, Colors::WHITE, hero->name);
 
 	//layout is not trivial: MACH4 - catapult - excluded, MISC[x] rearranged
 	assert(arts1->arts.size() == 9);
@@ -919,8 +919,8 @@ CHeroItem::CHeroItem(const CGHeroInstance * Hero)
 	portrait = std::make_shared<CAnimImage>("PortraitsLarge", hero->portrait, 0, 5, 6);
 	heroArea = std::make_shared<CHeroArea>(5, 6, hero);
 
-	name = std::make_shared<CLabel>(73, 7, FONT_SMALL, TOPLEFT, Colors::WHITE, hero->name);
-	artsText = std::make_shared<CLabel>(320, 55, FONT_SMALL, CENTER, Colors::WHITE, CGI->generaltexth->overview[2]);
+	name = std::make_shared<CLabel>(73, 7, FONT_SMALL, ETextAlignment::TOPLEFT, Colors::WHITE, hero->name);
+	artsText = std::make_shared<CLabel>(320, 55, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->overview[2]);
 
 	for(size_t i=0; i<GameConstants::PRIMARY_SKILLS; i++)
 	{

+ 3 - 4
client/windows/CQuestLog.cpp

@@ -12,7 +12,6 @@
 
 #include "CAdvmapInterface.h"
 
-#include "../CBitmapHandler.h"
 #include "../CGameInfo.h"
 #include "../CPlayerInterface.h"
 #include "../Graphics.h"
@@ -131,11 +130,11 @@ CQuestLog::CQuestLog (const std::vector<QuestInfo> & Quests)
 
 	minimap = std::make_shared<CQuestMinimap>(Rect(12, 12, 169, 169));
 	// TextBox have it's own 4 pixel padding from top at least for English. To achieve 10px from both left and top only add 6px margin
-	description = std::make_shared<CTextBox>("", Rect(205, 18, 385, DESCRIPTION_HEIGHT_MAX), CSlider::BROWN, FONT_MEDIUM, TOPLEFT, Colors::WHITE);
+	description = std::make_shared<CTextBox>("", Rect(205, 18, 385, DESCRIPTION_HEIGHT_MAX), CSlider::BROWN, FONT_MEDIUM, ETextAlignment::TOPLEFT, Colors::WHITE);
 	ok = std::make_shared<CButton>(Point(539, 398), "IOKAY.DEF", CGI->generaltexth->zelp[445], std::bind(&CQuestLog::close, this), SDLK_RETURN);
 	// Both button and lable are shifted to -2px by x and y to not make them actually look like they're on same line with quests list and ok button
 	hideCompleteButton = std::make_shared<CToggleButton>(Point(10, 396), "sysopchk.def", CButton::tooltip(texts["hideComplete"]), std::bind(&CQuestLog::toggleComplete, this, _1));
-	hideCompleteLabel = std::make_shared<CLabel>(46, 398, FONT_MEDIUM, TOPLEFT, Colors::WHITE, texts["hideComplete"]["label"].String());
+	hideCompleteLabel = std::make_shared<CLabel>(46, 398, FONT_MEDIUM, ETextAlignment::TOPLEFT, Colors::WHITE, texts["hideComplete"]["label"].String());
 	slider = std::make_shared<CSlider>(Point(166, 195), 191, std::bind(&CQuestLog::sliderMoved, this, _1), QUEST_COUNT, 0, false, CSlider::BROWN);
 
 	recreateLabelList();
@@ -176,7 +175,7 @@ void CQuestLog::recreateLabelList()
 			else
 				text.addReplacement(quests[i].obj->getObjectName()); //get name of the object
 		}
-		auto label = std::make_shared<CQuestLabel>(Rect(13, 195, 149,31), FONT_SMALL, TOPLEFT, Colors::WHITE, text.toString());
+		auto label = std::make_shared<CQuestLabel>(Rect(13, 195, 149,31), FONT_SMALL, ETextAlignment::TOPLEFT, Colors::WHITE, text.toString());
 		label->disable();
 
 		label->callback = std::bind(&CQuestLog::selectQuest, this, i, currentLabel);

+ 2 - 2
client/windows/CQuestLog.h

@@ -43,8 +43,8 @@ class CQuestLabel : public LRClickableAreaWText, public CMultiLineLabel
 public:
 	std::function<void()> callback;
 
-	CQuestLabel(Rect position, EFonts Font = FONT_SMALL, EAlignment Align = TOPLEFT, const SDL_Color &Color = Colors::WHITE, const std::string &Text =  "")
-		: CMultiLineLabel (position, FONT_SMALL, TOPLEFT, Colors::WHITE, Text){};
+	CQuestLabel(Rect position, EFonts Font = FONT_SMALL, ETextAlignment Align = ETextAlignment::TOPLEFT, const SDL_Color &Color = Colors::WHITE, const std::string &Text =  "")
+		: CMultiLineLabel (position, FONT_SMALL, ETextAlignment::TOPLEFT, Colors::WHITE, Text){};
 	void clickLeft(tribool down, bool previousState) override;
 	void showAll(SDL_Surface * to) override;
 };

+ 5 - 5
client/windows/CSpellWindow.cpp

@@ -24,7 +24,7 @@
 #include "../CVideoHandler.h"
 #include "../Graphics.h"
 
-#include "../battle/CBattleInterface.h"
+#include "../battle/BattleInterface.h"
 #include "../gui/CAnimation.h"
 #include "../gui/CGuiHandler.h"
 #include "../gui/SDL_Extensions.h"
@@ -183,7 +183,7 @@ CSpellWindow::CSpellWindow(const CGHeroInstance * _myHero, CPlayerInterface * _m
 
 	for(auto item : schoolBorders)
 		item->preload();
-	mana = std::make_shared<CLabel>(435, 426, FONT_SMALL, CENTER, Colors::YELLOW, boost::lexical_cast<std::string>(myHero->mana));
+	mana = std::make_shared<CLabel>(435, 426, FONT_SMALL, ETextAlignment::CENTER, Colors::YELLOW, boost::lexical_cast<std::string>(myHero->mana));
 	statusBar = CGStatusBar::create(7, 569, "Spelroll.bmp");
 
 	SDL_Rect temp_rect = genRect(45, 35, 479 + pos.x, 405 + pos.y);
@@ -508,9 +508,9 @@ CSpellWindow::SpellArea::SpellArea(SDL_Rect pos, CSpellWindow * owner)
 	image = std::make_shared<CAnimImage>(owner->spellIcons, 0, 0);
 	image->visible = false;
 
-	name = std::make_shared<CLabel>(39, 70, FONT_TINY, CENTER);
-	level = std::make_shared<CLabel>(39, 82, FONT_TINY, CENTER);
-	cost = std::make_shared<CLabel>(39, 94, FONT_TINY, CENTER);
+	name = std::make_shared<CLabel>(39, 70, FONT_TINY, ETextAlignment::CENTER);
+	level = std::make_shared<CLabel>(39, 82, FONT_TINY, ETextAlignment::CENTER);
+	cost = std::make_shared<CLabel>(39, 94, FONT_TINY, ETextAlignment::CENTER);
 
 	for(auto l : {name, level, cost})
 		l->autoRedraw = false;

+ 21 - 21
client/windows/CTradeWindow.cpp

@@ -244,13 +244,13 @@ void CTradeWindow::CTradeableItem::hover(bool on)
 	{
 	case CREATURE:
 	case CREATURE_PLACEHOLDER:
-		GH.statusbar->setText(boost::str(boost::format(CGI->generaltexth->allTexts[481]) % CGI->creh->objects[id]->namePl));
+		GH.statusbar->write(boost::str(boost::format(CGI->generaltexth->allTexts[481]) % CGI->creh->objects[id]->namePl));
 		break;
 	case ARTIFACT_PLACEHOLDER:
 		if(id < 0)
-			GH.statusbar->setText(CGI->generaltexth->zelp[582].first);
+			GH.statusbar->write(CGI->generaltexth->zelp[582].first);
 		else
-			GH.statusbar->setText(CGI->artifacts()->getByIndex(id)->getName());
+			GH.statusbar->write(CGI->artifacts()->getByIndex(id)->getName());
 		break;
 	}
 }
@@ -659,7 +659,7 @@ CMarketplaceWindow::CMarketplaceWindow(const IMarket * Market, const CGHeroInsta
 	madeTransaction = false;
 	bool sliderNeeded = true;
 
-	statusBar = CGStatusBar::create(std::make_shared<CPicture>(*background, Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
+	statusBar = CGStatusBar::create(std::make_shared<CPicture>(background->getSurface(), Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
 
 	std::string title;
 
@@ -703,7 +703,7 @@ CMarketplaceWindow::CMarketplaceWindow(const IMarket * Market, const CGHeroInsta
 		}
 	}
 
-	titleLabel = std::make_shared<CLabel>(300, 27, FONT_BIG, CENTER, Colors::YELLOW, title);
+	titleLabel = std::make_shared<CLabel>(300, 27, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW, title);
 
 	initItems(false);
 	initItems(true);
@@ -730,15 +730,15 @@ CMarketplaceWindow::CMarketplaceWindow(const IMarket * Market, const CGHeroInsta
 	case EMarketMode::RESOURCE_RESOURCE:
 	case EMarketMode::RESOURCE_PLAYER:
 	case EMarketMode::RESOURCE_ARTIFACT:
-		labels.push_back(std::make_shared<CLabel>(154, 148, FONT_SMALL, CENTER, Colors::WHITE, CGI->generaltexth->allTexts[270]));
+		labels.push_back(std::make_shared<CLabel>(154, 148, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[270]));
 		break;
 	case EMarketMode::CREATURE_RESOURCE:
 		//%s's Creatures
-		labels.push_back(std::make_shared<CLabel>(152, 102, FONT_SMALL, CENTER, Colors::WHITE, boost::str(boost::format(CGI->generaltexth->allTexts[272]) % hero->name)));
+		labels.push_back(std::make_shared<CLabel>(152, 102, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, boost::str(boost::format(CGI->generaltexth->allTexts[272]) % hero->name)));
 		break;
 	case EMarketMode::ARTIFACT_RESOURCE:
 		//%s's Artifacts
-		labels.push_back(std::make_shared<CLabel>(152, 56, FONT_SMALL, CENTER, Colors::WHITE, boost::str(boost::format(CGI->generaltexth->allTexts[271]) % hero->name)));
+		labels.push_back(std::make_shared<CLabel>(152, 56, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, boost::str(boost::format(CGI->generaltexth->allTexts[271]) % hero->name)));
 		break;
 	}
 
@@ -751,16 +751,16 @@ CMarketplaceWindow::CMarketplaceWindow(const IMarket * Market, const CGHeroInsta
 	case EMarketMode::CREATURE_RESOURCE:
 	case EMarketMode::RESOURCE_ARTIFACT:
 	case EMarketMode::ARTIFACT_RESOURCE:
-		labels.push_back(std::make_shared<CLabel>(445, 148, FONT_SMALL, CENTER, Colors::WHITE, CGI->generaltexth->allTexts[168]));
+		labels.push_back(std::make_shared<CLabel>(445, 148, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[168]));
 		traderTextRect = Rect(316, 48, 260, 75);
 		break;
 	case EMarketMode::RESOURCE_PLAYER:
-		labels.push_back(std::make_shared<CLabel>(445, 55, FONT_SMALL, CENTER, Colors::WHITE, CGI->generaltexth->allTexts[169]));
+		labels.push_back(std::make_shared<CLabel>(445, 55, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[169]));
 		traderTextRect = Rect(28, 48, 260, 75);
 		break;
 	}
 
-	traderText = std::make_shared<CTextBox>("", traderTextRect, 0, FONT_SMALL, CENTER);
+	traderText = std::make_shared<CTextBox>("", traderTextRect, 0, FONT_SMALL, ETextAlignment::CENTER);
 	int specialOffset = mode == EMarketMode::ARTIFACT_RESOURCE ? 35 : 0; //in selling artifacts mode we need to move res-res and art-res buttons down
 
 	if(printButtonFor(EMarketMode::RESOURCE_PLAYER))
@@ -1094,14 +1094,14 @@ CAltarWindow::CAltarWindow(const IMarket * Market, const CGHeroInstance * Hero,
 	if(Mode == EMarketMode::CREATURE_EXP)
 	{
 		//%s's Creatures
-		labels.push_back(std::make_shared<CLabel>(155, 30, FONT_SMALL, CENTER, Colors::YELLOW,
+		labels.push_back(std::make_shared<CLabel>(155, 30, FONT_SMALL, ETextAlignment::CENTER, Colors::YELLOW,
 				   boost::str(boost::format(CGI->generaltexth->allTexts[272]) % hero->name)));
 
 		//Altar of Sacrifice
-		labels.push_back(std::make_shared<CLabel>(450, 30, FONT_SMALL, CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[479]));
+		labels.push_back(std::make_shared<CLabel>(450, 30, FONT_SMALL, ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[479]));
 
 		 //To sacrifice creatures, move them from your army on to the Altar and click Sacrifice
-		new CTextBox(CGI->generaltexth->allTexts[480], Rect(320, 56, 256, 40), 0, FONT_SMALL, CENTER, Colors::YELLOW);
+		new CTextBox(CGI->generaltexth->allTexts[480], Rect(320, 56, 256, 40), 0, FONT_SMALL, ETextAlignment::CENTER, Colors::YELLOW);
 
 		slider = std::make_shared<CSlider>(Point(231,481),137,std::bind(&CAltarWindow::sliderMoved,this,_1),0,0);
 		max = std::make_shared<CButton>(Point(147, 520), "IRCBTNS.DEF", CGI->generaltexth->zelp[578], std::bind(&CSlider::moveToMax, slider));
@@ -1115,9 +1115,9 @@ CAltarWindow::CAltarWindow(const IMarket * Market, const CGHeroInstance * Hero,
 	else
 	{
 		//Sacrifice artifacts for experience
-		labels.push_back(std::make_shared<CLabel>(450, 34, FONT_SMALL, CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[477]));
+		labels.push_back(std::make_shared<CLabel>(450, 34, FONT_SMALL, ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[477]));
 		//%s's Creatures
-		labels.push_back(std::make_shared<CLabel>(302, 423, FONT_SMALL, CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[478]));
+		labels.push_back(std::make_shared<CLabel>(302, 423, FONT_SMALL, ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[478]));
 
 		sacrificeAll = std::make_shared<CButton>(Point(393, 520), "ALTFILL.DEF", CGI->generaltexth->zelp[571], std::bind(&CAltarWindow::SacrificeAll,this));
 		sacrificeAll->block(hero->artifactsInBackpack.empty() && hero->artifactsWorn.empty());
@@ -1131,11 +1131,11 @@ CAltarWindow::CAltarWindow(const IMarket * Market, const CGHeroInstance * Hero,
 	}
 
 	//Experience needed to reach next level
-	texts.push_back(std::make_shared<CTextBox>(CGI->generaltexth->allTexts[475], Rect(15, 415, 125, 50), 0, FONT_SMALL, CENTER, Colors::YELLOW));
+	texts.push_back(std::make_shared<CTextBox>(CGI->generaltexth->allTexts[475], Rect(15, 415, 125, 50), 0, FONT_SMALL, ETextAlignment::CENTER, Colors::YELLOW));
 	//Total experience on the Altar
-	texts.push_back(std::make_shared<CTextBox>(CGI->generaltexth->allTexts[476], Rect(15, 495, 125, 40), 0, FONT_SMALL, CENTER, Colors::YELLOW));
+	texts.push_back(std::make_shared<CTextBox>(CGI->generaltexth->allTexts[476], Rect(15, 495, 125, 40), 0, FONT_SMALL, ETextAlignment::CENTER, Colors::YELLOW));
 
-	statusBar = CGStatusBar::create(std::make_shared<CPicture>(*background, Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
+	statusBar = CGStatusBar::create(std::make_shared<CPicture>(background->getSurface(), Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
 
 	ok = std::make_shared<CButton>(Point(516, 520), "IOK6432.DEF", CGI->generaltexth->zelp[568], [&](){ close();}, SDLK_RETURN);
 	ok->assignedKeys.insert(SDLK_ESCAPE);
@@ -1160,8 +1160,8 @@ CAltarWindow::CAltarWindow(const IMarket * Market, const CGHeroInstance * Hero,
 	expPerUnit.resize(GameConstants::ARMY_SIZE, 0);
 	getExpValues();
 
-	expToLevel = std::make_shared<CLabel>(73, 475, FONT_SMALL, CENTER);
-	expOnAltar = std::make_shared<CLabel>(73, 543, FONT_SMALL, CENTER);
+	expToLevel = std::make_shared<CLabel>(73, 475, FONT_SMALL, ETextAlignment::CENTER);
+	expOnAltar = std::make_shared<CLabel>(73, 543, FONT_SMALL, ETextAlignment::CENTER);
 
 	setExpToLevel();
 	calcTotalExp();

+ 3 - 3
client/windows/CWindowObject.cpp

@@ -13,16 +13,16 @@
 #include "CAdvmapInterface.h"
 
 #include "../widgets/MiscWidgets.h"
+#include "../widgets/Images.h"
 
 #include "../gui/SDL_Pixels.h"
 #include "../gui/SDL_Extensions.h"
 #include "../gui/CGuiHandler.h"
 #include "../gui/CCursorHandler.h"
 
-#include "../battle/CBattleInterface.h"
-#include "../battle/CBattleInterfaceClasses.h"
+#include "../battle/BattleInterface.h"
+#include "../battle/BattleInterfaceClasses.h"
 
-#include "../CBitmapHandler.h"
 #include "../Graphics.h"
 #include "../CGameInfo.h"
 #include "../CPlayerInterface.h"

+ 2 - 2
client/windows/CreaturePurchaseCard.cpp

@@ -55,8 +55,8 @@ void CreaturePurchaseCard::switchCreatureLevel()
 
 void CreaturePurchaseCard::initAmountInfo()
 {
-	availableAmount = std::make_shared<CLabel>(pos.x + 25, pos.y + 146, FONT_SMALL, CENTER, Colors::YELLOW);
-	purchaseAmount = std::make_shared<CLabel>(pos.x + 76, pos.y + 146, FONT_SMALL, CENTER, Colors::WHITE);
+	availableAmount = std::make_shared<CLabel>(pos.x + 25, pos.y + 146, FONT_SMALL, ETextAlignment::CENTER, Colors::YELLOW);
+	purchaseAmount = std::make_shared<CLabel>(pos.x + 76, pos.y + 146, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
 	updateAmountInfo(0);
 }
 

+ 64 - 65
client/windows/GUIClasses.cpp

@@ -17,7 +17,6 @@
 #include "CreatureCostBox.h"
 #include "InfoWindows.h"
 
-#include "../CBitmapHandler.h"
 #include "../CGameInfo.h"
 #include "../CMessage.h"
 #include "../CMusicHandler.h"
@@ -27,10 +26,10 @@
 #include "../mapHandler.h"
 #include "../CServerHandler.h"
 
-#include "../battle/CBattleInterfaceClasses.h"
-#include "../battle/CBattleInterface.h"
-#include "../battle/CCreatureAnimation.h"
+#include "../battle/BattleInterfaceClasses.h"
+#include "../battle/BattleInterface.h"
 
+#include "../gui/CAnimation.h"
 #include "../gui/CGuiHandler.h"
 #include "../gui/SDL_Extensions.h"
 #include "../gui/CCursorHandler.h"
@@ -205,7 +204,7 @@ CRecruitmentWindow::CRecruitmentWindow(const CGDwelling * Dwelling, int Level, c
 
 	OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
 
-	statusbar = CGStatusBar::create(std::make_shared<CPicture>(*background, Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
+	statusbar = CGStatusBar::create(std::make_shared<CPicture>(background->getSurface(), Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
 
 	slider = std::make_shared<CSlider>(Point(176,279),135,std::bind(&CRecruitmentWindow::sliderMoved,this, _1),0,0,0,true);
 
@@ -213,15 +212,15 @@ CRecruitmentWindow::CRecruitmentWindow(const CGDwelling * Dwelling, int Level, c
 	buyButton = std::make_shared<CButton>(Point(212, 313), "IBY6432.DEF", CGI->generaltexth->zelp[554], std::bind(&CRecruitmentWindow::buy, this), SDLK_RETURN);
 	cancelButton = std::make_shared<CButton>(Point(290, 313), "ICN6432.DEF", CGI->generaltexth->zelp[555], std::bind(&CRecruitmentWindow::close, this), SDLK_ESCAPE);
 
-	title = std::make_shared<CLabel>(243, 32, FONT_BIG, CENTER, Colors::YELLOW);
-	availableValue = std::make_shared<CLabel>(205, 253, FONT_SMALL, CENTER, Colors::WHITE);
-	toRecruitValue = std::make_shared<CLabel>(279, 253, FONT_SMALL, CENTER, Colors::WHITE);
+	title = std::make_shared<CLabel>(243, 32, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW);
+	availableValue = std::make_shared<CLabel>(205, 253, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
+	toRecruitValue = std::make_shared<CLabel>(279, 253, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
 
 	costPerTroopValue = std::make_shared<CreatureCostBox>(Rect(65, 222, 97, 74), CGI->generaltexth->allTexts[346]);
 	totalCostValue = std::make_shared<CreatureCostBox>(Rect(323, 222, 97, 74), CGI->generaltexth->allTexts[466]);
 
-	availableTitle = std::make_shared<CLabel>(205, 233, FONT_SMALL, CENTER, Colors::WHITE, CGI->generaltexth->allTexts[465]);
-	toRecruitTitle = std::make_shared<CLabel>(279, 233, FONT_SMALL, CENTER, Colors::WHITE, CGI->generaltexth->allTexts[16]);
+	availableTitle = std::make_shared<CLabel>(205, 233, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[465]);
+	toRecruitTitle = std::make_shared<CLabel>(279, 233, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[16]);
 
 	availableCreaturesChanged();
 }
@@ -334,7 +333,7 @@ CSplitWindow::CSplitWindow(const CCreature * creature, std::function<void(int, i
 
 	std::string titleStr = CGI->generaltexth->allTexts[256];
 	boost::algorithm::replace_first(titleStr,"%s", creature->namePl);
-	title = std::make_shared<CLabel>(150, 34, FONT_BIG, CENTER, Colors::YELLOW, titleStr);
+	title = std::make_shared<CLabel>(150, 34, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW, titleStr);
 }
 
 void CSplitWindow::setAmountText(std::string text, bool left)
@@ -405,15 +404,15 @@ CLevelWindow::CLevelWindow(const CGHeroInstance * hero, PrimarySkill::PrimarySki
 	ok = std::make_shared<CButton>(Point(297, 413), "IOKAY", CButton::tooltip(), std::bind(&CLevelWindow::close, this), SDLK_RETURN);
 
 	//%s has gained a level.
-	mainTitle = std::make_shared<CLabel>(192, 33, FONT_MEDIUM, CENTER, Colors::WHITE, boost::str(boost::format(CGI->generaltexth->allTexts[444]) % hero->name));
+	mainTitle = std::make_shared<CLabel>(192, 33, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, boost::str(boost::format(CGI->generaltexth->allTexts[444]) % hero->name));
 
 	//%s is now a level %d %s.
-	levelTitle = std::make_shared<CLabel>(192, 162, FONT_MEDIUM, CENTER, Colors::WHITE,
+	levelTitle = std::make_shared<CLabel>(192, 162, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE,
 		boost::str(boost::format(CGI->generaltexth->allTexts[445]) % hero->name % hero->level % hero->type->heroClass->name));
 
 	skillIcon = std::make_shared<CAnimImage>("PSKIL42", pskill, 0, 174, 190);
 
-	skillValue = std::make_shared<CLabel>(192, 253, FONT_MEDIUM, CENTER, Colors::WHITE, CGI->generaltexth->primarySkillNames[pskill] + " +1");
+	skillValue = std::make_shared<CLabel>(192, 253, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->primarySkillNames[pskill] + " +1");
 }
 
 
@@ -448,12 +447,12 @@ CSystemOptionsWindow::CSystemOptionsWindow()
 	onFullscreenChanged(settings.listen["video"]["fullscreen"])
 {
 	OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
-	title = std::make_shared<CLabel>(242, 32, FONT_BIG, CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[568]);
+	title = std::make_shared<CLabel>(242, 32, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[568]);
 
 	const JsonNode & texts = CGI->generaltexth->localizedTexts["systemOptions"];
 
 	//left window section
-	leftGroup = std::make_shared<CLabelGroup>(FONT_MEDIUM, CENTER, Colors::YELLOW);
+	leftGroup = std::make_shared<CLabelGroup>(FONT_MEDIUM, ETextAlignment::CENTER, Colors::YELLOW);
 	leftGroup->add(122,  64, CGI->generaltexth->allTexts[569]);
 	leftGroup->add(122, 130, CGI->generaltexth->allTexts[570]);
 	leftGroup->add(122, 196, CGI->generaltexth->allTexts[571]);
@@ -462,7 +461,7 @@ CSystemOptionsWindow::CSystemOptionsWindow()
 	leftGroup->add(122, 412, CGI->generaltexth->allTexts[395]);
 
 	//right section
-	rightGroup = std::make_shared<CLabelGroup>(FONT_MEDIUM, TOPLEFT, Colors::WHITE);
+	rightGroup = std::make_shared<CLabelGroup>(FONT_MEDIUM, ETextAlignment::TOPLEFT, Colors::WHITE);
 	rightGroup->add(282, 57,  CGI->generaltexth->allTexts[572]);
 	rightGroup->add(282, 89,  CGI->generaltexth->allTexts[573]);
 	rightGroup->add(282, 121, CGI->generaltexth->allTexts[574]);
@@ -556,7 +555,7 @@ CSystemOptionsWindow::CSystemOptionsWindow()
 	gameResButton = std::make_shared<CButton>(Point(28, 275),"buttons/resolution", CButton::tooltip(texts["resolutionButton"]), std::bind(&CSystemOptionsWindow::selectGameRes, this), SDLK_g);
 
 	const auto & screenRes = settings["video"]["screenRes"];
-	gameResLabel = std::make_shared<CLabel>(170, 292, FONT_MEDIUM, CENTER, Colors::YELLOW, resolutionToString(screenRes["width"].Integer(), screenRes["height"].Integer()));
+	gameResLabel = std::make_shared<CLabel>(170, 292, FONT_MEDIUM, ETextAlignment::CENTER, Colors::YELLOW, resolutionToString(screenRes["width"].Integer(), screenRes["height"].Integer()));
 }
 
 void CSystemOptionsWindow::selectGameRes()
@@ -667,13 +666,13 @@ CTavernWindow::CTavernWindow(const CGObjectInstance * TavernObj)
 	h1 = std::make_shared<HeroPortrait>(selected, 0, 72, 299, h[0]);
 	h2 = std::make_shared<HeroPortrait>(selected, 1, 162, 299, h[1]);
 
-	title = std::make_shared<CLabel>(200, 35, FONT_BIG, CENTER, Colors::YELLOW, CGI->generaltexth->jktexts[37]);
-	cost = std::make_shared<CLabel>(320, 328, FONT_SMALL, CENTER, Colors::WHITE, boost::lexical_cast<std::string>(GameConstants::HERO_GOLD_COST));
+	title = std::make_shared<CLabel>(200, 35, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->jktexts[37]);
+	cost = std::make_shared<CLabel>(320, 328, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, boost::lexical_cast<std::string>(GameConstants::HERO_GOLD_COST));
 
 	auto rumorText = boost::str(boost::format(CGI->generaltexth->allTexts[216]) % LOCPLINT->cb->getTavernRumor(tavernObj));
-	rumor = std::make_shared<CTextBox>(rumorText, Rect(32, 190, 330, 68), 0, FONT_SMALL, CENTER, Colors::WHITE);
+	rumor = std::make_shared<CTextBox>(rumorText, Rect(32, 190, 330, 68), 0, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
 
-	statusbar = CGStatusBar::create(std::make_shared<CPicture>(*background, Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
+	statusbar = CGStatusBar::create(std::make_shared<CPicture>(background->getSurface(), Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
 	cancel = std::make_shared<CButton>(Point(310, 428), "ICANCEL.DEF", CButton::tooltip(CGI->generaltexth->tavernInfo[7]), std::bind(&CTavernWindow::close, this), SDLK_ESCAPE);
 	recruit = std::make_shared<CButton>(Point(272, 355), "TPTAV01.DEF", CButton::tooltip(), std::bind(&CTavernWindow::recruitb, this), SDLK_RETURN);
 	thiefGuild = std::make_shared<CButton>(Point(22, 428), "TPTAV02.DEF", CButton::tooltip(CGI->generaltexth->tavernInfo[5]), std::bind(&CTavernWindow::thievesguildb, this), SDLK_t);
@@ -799,7 +798,7 @@ void CTavernWindow::HeroPortrait::hover(bool on)
 {
 	//Hoverable::hover(on);
 	if(on)
-		GH.statusbar->setText(hoverName);
+		GH.statusbar->write(hoverName);
 	else
 		GH.statusbar->clear();
 }
@@ -1083,8 +1082,8 @@ CExchangeWindow::CExchangeWindow(ObjectInstanceID hero1, ObjectInstanceID hero2,
 		return boost::str(fmt);
 	};
 
-	titles[0] = std::make_shared<CLabel>(147, 25, FONT_SMALL, CENTER, Colors::WHITE, genTitle(heroInst[0]));
-	titles[1] = std::make_shared<CLabel>(653, 25, FONT_SMALL, CENTER, Colors::WHITE, genTitle(heroInst[1]));
+	titles[0] = std::make_shared<CLabel>(147, 25, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, genTitle(heroInst[0]));
+	titles[1] = std::make_shared<CLabel>(653, 25, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, genTitle(heroInst[1]));
 
 	auto PSKIL32 = std::make_shared<CAnimation>("PSKIL32");
 	PSKIL32->preload();
@@ -1106,7 +1105,7 @@ CExchangeWindow::CExchangeWindow(ObjectInstanceID hero1, ObjectInstanceID hero2,
 		herosWArt[leftRight] = std::make_shared<CHeroWithMaybePickedArtifact>(this, hero);
 
 		for(int m=0; m<GameConstants::PRIMARY_SKILLS; ++m)
-			primSkillValues[leftRight].push_back(std::make_shared<CLabel>(352 + (qeLayout ? 96 : 93) * leftRight, (qeLayout ? 22 : 35) + (qeLayout ? 26 : 36) * m, FONT_SMALL, CENTER, Colors::WHITE));
+			primSkillValues[leftRight].push_back(std::make_shared<CLabel>(352 + (qeLayout ? 96 : 93) * leftRight, (qeLayout ? 22 : 35) + (qeLayout ? 26 : 36) * m, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE));
 
 
 		for(int m=0; m < hero->secSkills.size(); ++m)
@@ -1115,10 +1114,10 @@ CExchangeWindow::CExchangeWindow(ObjectInstanceID hero1, ObjectInstanceID hero2,
 		specImages[leftRight] = std::make_shared<CAnimImage>("UN32", hero->type->imageIndex, 0, 67 + 490 * leftRight, qeLayout ? 41 : 45);
 
 		expImages[leftRight] = std::make_shared<CAnimImage>(PSKIL32, 4, 0, 103 + 490 * leftRight, qeLayout ? 41 : 45);
-		expValues[leftRight] = std::make_shared<CLabel>(119 + 490 * leftRight, qeLayout ? 66 : 71, FONT_SMALL, CENTER, Colors::WHITE);
+		expValues[leftRight] = std::make_shared<CLabel>(119 + 490 * leftRight, qeLayout ? 66 : 71, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
 
 		manaImages[leftRight] = std::make_shared<CAnimImage>(PSKIL32, 5, 0, 139 + 490 * leftRight, qeLayout ? 41 : 45);
-		manaValues[leftRight] = std::make_shared<CLabel>(155 + 490 * leftRight, qeLayout ? 66 : 71, FONT_SMALL, CENTER, Colors::WHITE);
+		manaValues[leftRight] = std::make_shared<CLabel>(155 + 490 * leftRight, qeLayout ? 66 : 71, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
 	}
 
 	portraits[0] = std::make_shared<CAnimImage>("PortraitsLarge", heroInst[0]->portrait, 0, 257, 13);
@@ -1209,7 +1208,7 @@ CExchangeWindow::CExchangeWindow(ObjectInstanceID hero1, ObjectInstanceID hero2,
 	questlogButton[1] = std::make_shared<CButton>(Point(740, qeLayout ? 39 : 44), "hsbtns4.def", CButton::tooltip(CGI->generaltexth->heroscrn[0]), std::bind(&CExchangeWindow::questlog, this, 1));
 
 	Rect barRect(5, 578, 725, 18);
-	statusbar = CGStatusBar::create(std::make_shared<CPicture>(*background, barRect, 5, 578, false));
+	statusbar = CGStatusBar::create(std::make_shared<CPicture>(background->getSurface(), barRect, 5, 578, false));
 
 	//garrison interface
 
@@ -1317,8 +1316,8 @@ CShipyardWindow::CShipyardWindow(const std::vector<si32> & cost, int state, int
 	std::string goldValue = boost::lexical_cast<std::string>(cost[Res::GOLD]);
 	std::string woodValue = boost::lexical_cast<std::string>(cost[Res::WOOD]);
 
-	goldCost = std::make_shared<CLabel>(118, 294, FONT_SMALL, CENTER, Colors::WHITE, goldValue);
-	woodCost = std::make_shared<CLabel>(212, 294, FONT_SMALL, CENTER, Colors::WHITE, woodValue);
+	goldCost = std::make_shared<CLabel>(118, 294, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, goldValue);
+	woodCost = std::make_shared<CLabel>(212, 294, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, woodValue);
 
 	goldPic = std::make_shared<CAnimImage>("RESOURCE", Res::GOLD, 0, 100, 244);
 	woodPic = std::make_shared<CAnimImage>("RESOURCE", Res::WOOD, 0, 196, 244);
@@ -1336,10 +1335,10 @@ CShipyardWindow::CShipyardWindow(const std::vector<si32> & cost, int state, int
 		}
 	}
 
-	statusbar = CGStatusBar::create(std::make_shared<CPicture>(*background, Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
+	statusbar = CGStatusBar::create(std::make_shared<CPicture>(background->getSurface(), Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
 
-	title = std::make_shared<CLabel>(164, 27,  FONT_BIG, CENTER, Colors::YELLOW, CGI->generaltexth->jktexts[13]);
-	costLabel = std::make_shared<CLabel>(164, 220, FONT_MEDIUM, CENTER, Colors::WHITE, CGI->generaltexth->jktexts[14]);
+	title = std::make_shared<CLabel>(164, 27,  FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->jktexts[13]);
+	costLabel = std::make_shared<CLabel>(164, 220, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->jktexts[14]);
 }
 
 CPuzzleWindow::CPuzzleWindow(const int3 & GrailPos, double discoveredRatio)
@@ -1356,7 +1355,7 @@ CPuzzleWindow::CPuzzleWindow(const int3 & GrailPos, double discoveredRatio)
 	quitb->setBorderColor(Colors::METALLIC_GOLD);
 
 	logo = std::make_shared<CPicture>("PUZZLOGO", 607, 3);
-	title = std::make_shared<CLabel>(700, 95, FONT_BIG, CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[463]);
+	title = std::make_shared<CLabel>(700, 95, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[463]);
 	resDataBar = std::make_shared<CResDataBar>("ARESBAR.bmp", 3, 575, 32, 2, 85, 85);
 
 	int faction = LOCPLINT->cb->getStartInfo()->playerInfos.find(LOCPLINT->playerID)->second.castle;
@@ -1453,7 +1452,7 @@ CTransformerWindow::CItem::CItem(CTransformerWindow * parent_, int size_, int id
 	pos.x += 45  + (id%3)*83 + id/6*83;
 	pos.y += 109 + (id/3)*98;
 	icon = std::make_shared<CAnimImage>("TWCRPORT", parent->army->getCreature(SlotID(id))->idNumber + 2);
-	count = std::make_shared<CLabel>(28, 76,FONT_SMALL, CENTER, Colors::WHITE, boost::lexical_cast<std::string>(size));
+	count = std::make_shared<CLabel>(28, 76,FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, boost::lexical_cast<std::string>(size));
 }
 
 void CTransformerWindow::makeDeal()
@@ -1501,12 +1500,12 @@ CTransformerWindow::CTransformerWindow(const CGHeroInstance * _hero, const CGTow
 	all = std::make_shared<CButton>(Point(146, 416), "ALTARMY.DEF", CGI->generaltexth->zelp[590], [&](){ addAll(); }, SDLK_a);
 	convert = std::make_shared<CButton>(Point(269, 416), "ALTSACR.DEF", CGI->generaltexth->zelp[591], [&](){ makeDeal(); }, SDLK_RETURN);
 	cancel = std::make_shared<CButton>(Point(392, 416), "ICANCEL.DEF", CGI->generaltexth->zelp[592], [&](){ close(); },SDLK_ESCAPE);
-	statusbar = CGStatusBar::create(std::make_shared<CPicture>(*background, Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
+	statusbar = CGStatusBar::create(std::make_shared<CPicture>(background->getSurface(), Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
 
-	titleLeft = std::make_shared<CLabel>(153, 29,FONT_SMALL, CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[485]);//holding area
-	titleRight = std::make_shared<CLabel>(153+295, 29, FONT_SMALL, CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[486]);//transformer
-	helpLeft = std::make_shared<CTextBox>(CGI->generaltexth->allTexts[487], Rect(26,  56, 255, 40), 0, FONT_MEDIUM, CENTER, Colors::YELLOW);//move creatures to create skeletons
-	helpRight = std::make_shared<CTextBox>(CGI->generaltexth->allTexts[488], Rect(320, 56, 255, 40), 0, FONT_MEDIUM, CENTER, Colors::YELLOW);//creatures here will become skeletons
+	titleLeft = std::make_shared<CLabel>(153, 29,FONT_SMALL, ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[485]);//holding area
+	titleRight = std::make_shared<CLabel>(153+295, 29, FONT_SMALL, ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[486]);//transformer
+	helpLeft = std::make_shared<CTextBox>(CGI->generaltexth->allTexts[487], Rect(26,  56, 255, 40), 0, FONT_MEDIUM, ETextAlignment::CENTER, Colors::YELLOW);//move creatures to create skeletons
+	helpRight = std::make_shared<CTextBox>(CGI->generaltexth->allTexts[488], Rect(320, 56, 255, 40), 0, FONT_MEDIUM, ETextAlignment::CENTER, Colors::YELLOW);//creatures here will become skeletons
 }
 
 CUniversityWindow::CItem::CItem(CUniversityWindow * _parent, int _ID, int X, int Y)
@@ -1523,8 +1522,8 @@ CUniversityWindow::CItem::CItem(CUniversityWindow * _parent, int _ID, int X, int
 
 	icon = std::make_shared<CAnimImage>("SECSKILL", _ID * 3 + 3, 0);
 
-	name = std::make_shared<CLabel>(22, -13, FONT_SMALL, CENTER, Colors::WHITE, CGI->skillh->skillName(ID));
-	level = std::make_shared<CLabel>(22, 57, FONT_SMALL, CENTER, Colors::WHITE, CGI->generaltexth->levels[0]);
+	name = std::make_shared<CLabel>(22, -13, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->skillh->skillName(ID));
+	level = std::make_shared<CLabel>(22, 57, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->levels[0]);
 
 	pos.h = icon->pos.h;
 	pos.w = icon->pos.w;
@@ -1550,7 +1549,7 @@ void CUniversityWindow::CItem::clickRight(tribool down, bool previousState)
 void CUniversityWindow::CItem::hover(bool on)
 {
 	if(on)
-		GH.statusbar->setText(CGI->skillh->skillName(ID));
+		GH.statusbar->write(CGI->skillh->skillName(ID));
 	else
 		GH.statusbar->clear();
 }
@@ -1605,8 +1604,8 @@ CUniversityWindow::CUniversityWindow(const CGHeroInstance * _hero, const IMarket
 
 	titlePic->center(Point(232 + pos.x, 76 + pos.y));
 
-	clerkSpeech = std::make_shared<CTextBox>(CGI->generaltexth->allTexts[603], Rect(24, 129, 413, 70), 0, FONT_SMALL, CENTER, Colors::WHITE);
-	title = std::make_shared<CLabel>(231, 26, FONT_MEDIUM, CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[602]);
+	clerkSpeech = std::make_shared<CTextBox>(CGI->generaltexth->allTexts[603], Rect(24, 129, 413, 70), 0, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
+	title = std::make_shared<CLabel>(231, 26, FONT_MEDIUM, ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[602]);
 
 	std::vector<int> goods = market->availableItemsIds(EMarketMode::RESOURCE_SKILL);
 	assert(goods.size() == 4);
@@ -1615,7 +1614,7 @@ CUniversityWindow::CUniversityWindow(const CGHeroInstance * _hero, const IMarket
 		items.push_back(std::make_shared<CItem>(this, goods[i], 54+i*104, 234));
 
 	cancel = std::make_shared<CButton>(Point(200, 313), "IOKAY.DEF", CGI->generaltexth->zelp[632], [&](){ close(); }, SDLK_RETURN);
-	statusbar = CGStatusBar::create(std::make_shared<CPicture>(*background, Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
+	statusbar = CGStatusBar::create(std::make_shared<CPicture>(background->getSurface(), Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
 }
 
 void CUniversityWindow::makeDeal(int skill)
@@ -1635,14 +1634,14 @@ CUnivConfirmWindow::CUnivConfirmWindow(CUniversityWindow * owner_, int SKILL, bo
 	boost::replace_first(text, "%s", CGI->skillh->skillName(SKILL));
 	boost::replace_first(text, "%d", "2000");
 
-	clerkSpeech = std::make_shared<CTextBox>(text, Rect(24, 129, 413, 70), 0, FONT_SMALL, CENTER, Colors::WHITE);
+	clerkSpeech = std::make_shared<CTextBox>(text, Rect(24, 129, 413, 70), 0, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE);
 
-	name = std::make_shared<CLabel>(230, 37,  FONT_SMALL, CENTER, Colors::WHITE, CGI->skillh->skillName(SKILL));
+	name = std::make_shared<CLabel>(230, 37,  FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->skillh->skillName(SKILL));
 	icon = std::make_shared<CAnimImage>("SECSKILL", SKILL*3+3, 0, 211, 51);
-	level = std::make_shared<CLabel>(230, 107, FONT_SMALL, CENTER, Colors::WHITE, CGI->generaltexth->levels[1]);
+	level = std::make_shared<CLabel>(230, 107, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->levels[1]);
 
 	costIcon = std::make_shared<CAnimImage>("RESOURCE", Res::GOLD, 0, 210, 210);
-	cost = std::make_shared<CLabel>(230, 267, FONT_SMALL, CENTER, Colors::WHITE, "2000");
+	cost = std::make_shared<CLabel>(230, 267, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, "2000");
 
 	std::string hoverText = CGI->generaltexth->allTexts[609];
 	boost::replace_first(hoverText, "%s", CGI->generaltexth->levels[0]+ " " + CGI->skillh->skillName(SKILL));
@@ -1656,7 +1655,7 @@ CUnivConfirmWindow::CUnivConfirmWindow(CUniversityWindow * owner_, int SKILL, bo
 	confirm->block(!available);
 
 	cancel = std::make_shared<CButton>(Point(252,299), "ICANCEL.DEF", CGI->generaltexth->zelp[631], [&](){ close(); }, SDLK_ESCAPE);
-	statusbar = CGStatusBar::create(std::make_shared<CPicture>(*background, Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
+	statusbar = CGStatusBar::create(std::make_shared<CPicture>(background->getSurface(), Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
 }
 
 void CUnivConfirmWindow::makeDeal(int skill)
@@ -1695,7 +1694,7 @@ CGarrisonWindow::CGarrisonWindow(const CArmedInstance * up, const CGHeroInstance
 			logGlobal->error("Invalid armed instance for garrison window.");
 		}
 	}
-	title = std::make_shared<CLabel>(275, 30, FONT_BIG, CENTER, Colors::YELLOW, titleText);
+	title = std::make_shared<CLabel>(275, 30, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW, titleText);
 
 	banner = std::make_shared<CAnimImage>("CREST58", up->getOwner().getNum(), 0, 28, 124);
 	portrait = std::make_shared<CAnimImage>("PortraitsLarge", down->portrait, 0, 29, 222);
@@ -1713,14 +1712,14 @@ CHillFortWindow::CHillFortWindow(const CGHeroInstance * visitor, const CGObjectI
 {
 	OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
 
-	title = std::make_shared<CLabel>(325, 32, FONT_BIG, CENTER, Colors::YELLOW, fort->getObjectName());
+	title = std::make_shared<CLabel>(325, 32, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW, fort->getObjectName());
 
 	heroPic = std::make_shared<CHeroArea>(30, 60, hero);
 
 	for(int i=0; i < resCount; i++)
 	{
 		totalIcons[i] = std::make_shared<CAnimImage>("SMALRES", i, 0, 104 + 76 * i, 237);
-		totalLabels[i] = std::make_shared<CLabel>(166 + 76 * i, 253, FONT_SMALL, BOTTOMRIGHT);
+		totalLabels[i] = std::make_shared<CLabel>(166 + 76 * i, 253, FONT_SMALL, ETextAlignment::BOTTOMRIGHT);
 	}
 
 	for(int i = 0; i < slotsCount; i++)
@@ -1732,7 +1731,7 @@ CHillFortWindow::CHillFortWindow(const CGHeroInstance * visitor, const CGObjectI
 		for(int j : {0,1})
 		{
 			slotIcons[i][j] = std::make_shared<CAnimImage>("SMALRES", 0, 0, 104 + 76 * i, 128 + 20 * j);
-			slotLabels[i][j] = std::make_shared<CLabel>(168 + 76 * i, 144 + 20 * j, FONT_SMALL, BOTTOMRIGHT);
+			slotLabels[i][j] = std::make_shared<CLabel>(168 + 76 * i, 144 + 20 * j, FONT_SMALL, ETextAlignment::BOTTOMRIGHT);
 		}
 	}
 
@@ -1741,7 +1740,7 @@ CHillFortWindow::CHillFortWindow(const CGHeroInstance * visitor, const CGObjectI
 		upgradeAll->addImage(image);
 
 	quit = std::make_shared<CButton>(Point(294, 275), "IOKAY.DEF", CButton::tooltip(), std::bind(&CHillFortWindow::close, this), SDLK_RETURN);
-	statusbar = CGStatusBar::create(std::make_shared<CPicture>(*background, Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
+	statusbar = CGStatusBar::create(std::make_shared<CPicture>(background->getSurface(), Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
 
 	garr = std::make_shared<CGarrisonInt>(108, 60, 18, Point(), hero, nullptr);
 	updateGarrisons();
@@ -1945,7 +1944,7 @@ CThievesGuildWindow::CThievesGuildWindow(const CGObjectInstance * _owner):
 
 		std::string text = CGI->generaltexth->jktexts[24+g];
 		boost::algorithm::trim_if(text,boost::algorithm::is_any_of("\""));
-		rowHeaders.push_back(std::make_shared<CLabel>(135, y, FONT_MEDIUM, CENTER, Colors::YELLOW, text));
+		rowHeaders.push_back(std::make_shared<CLabel>(135, y, FONT_MEDIUM, ETextAlignment::CENTER, Colors::YELLOW, text));
 	}
 
 	auto PRSTRIPS = std::make_shared<CAnimation>("PRSTRIPS");
@@ -1955,7 +1954,7 @@ CThievesGuildWindow::CThievesGuildWindow(const CGObjectInstance * _owner):
 		columnBackgrounds.push_back(std::make_shared<CAnimImage>(PRSTRIPS, g-1, 0, 250 + 66*g, 7));
 
 	for(int g=0; g<tgi.playerColors.size(); ++g)
-		columnHeaders.push_back(std::make_shared<CLabel>(283 + 66*g, 24, FONT_BIG, CENTER, Colors::YELLOW, CGI->generaltexth->jktexts[16+g]));
+		columnHeaders.push_back(std::make_shared<CLabel>(283 + 66*g, 24, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW, CGI->generaltexth->jktexts[16+g]));
 
 	auto itgflags = std::make_shared<CAnimation>("itgflags");
 	itgflags->preload();
@@ -2004,11 +2003,11 @@ CThievesGuildWindow::CThievesGuildWindow(const CGObjectInstance * _owner):
 			if(iter.second.details)
 			{
 				primSkillHeaders.push_back(std::make_shared<CTextBox>(CGI->generaltexth->allTexts[184], Rect(260 + 66*counter, 396, 52, 64),
-					0, FONT_TINY, TOPLEFT, Colors::WHITE));
+					0, FONT_TINY, ETextAlignment::TOPLEFT, Colors::WHITE));
 
 				for(int i=0; i<iter.second.details->primskills.size(); ++i)
 				{
-					primSkillValues.push_back(std::make_shared<CLabel>(310 + 66 * counter, 407 + 11*i, FONT_TINY, BOTTOMRIGHT, Colors::WHITE,
+					primSkillValues.push_back(std::make_shared<CLabel>(310 + 66 * counter, 407 + 11*i, FONT_TINY, ETextAlignment::BOTTOMRIGHT, Colors::WHITE,
 							   boost::lexical_cast<std::string>(iter.second.details->primskills[i])));
 				}
 			}
@@ -2039,7 +2038,7 @@ CThievesGuildWindow::CThievesGuildWindow(const CGObjectInstance * _owner):
 			text = CGI->generaltexth->arraytxt[168 + it.second];
 		}
 
-		personalities.push_back(std::make_shared<CLabel>(283 + 66*counter, 459, FONT_SMALL, CENTER, Colors::WHITE, text));
+		personalities.push_back(std::make_shared<CLabel>(283 + 66*counter, 459, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, text));
 
 		counter++;
 	}
@@ -2056,7 +2055,7 @@ CObjectListWindow::CItem::CItem(CObjectListWindow * _parent, size_t _id, std::st
 
 	type |= REDRAW_PARENT;
 
-	text = std::make_shared<CLabel>(pos.w/2, pos.h/2, FONT_SMALL, CENTER, Colors::WHITE, _text);
+	text = std::make_shared<CLabel>(pos.w/2, pos.h/2, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, _text);
 	select(index == parent->selected);
 }
 
@@ -2109,8 +2108,8 @@ void CObjectListWindow::init(std::shared_ptr<CIntObject> titleWidget_, std::stri
 {
 	titleWidget = titleWidget_;
 
-	title = std::make_shared<CLabel>(152, 27, FONT_BIG, CENTER, Colors::YELLOW, _title);
-	descr = std::make_shared<CLabel>(145, 133, FONT_SMALL, CENTER, Colors::WHITE, _descr);
+	title = std::make_shared<CLabel>(152, 27, FONT_BIG, ETextAlignment::CENTER, Colors::YELLOW, _title);
+	descr = std::make_shared<CLabel>(145, 133, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE, _descr);
 	exit = std::make_shared<CButton>( Point(228, 402), "ICANCEL.DEF", CButton::tooltip(), std::bind(&CObjectListWindow::exitPressed, this), SDLK_ESCAPE);
 
 	if(titleWidget)

+ 9 - 10
client/windows/InfoWindows.cpp

@@ -12,7 +12,6 @@
 
 #include "CAdvmapInterface.h"
 
-#include "../CBitmapHandler.h"
 #include "../Graphics.h"
 #include "../CGameInfo.h"
 #include "../CPlayerInterface.h"
@@ -27,8 +26,8 @@
 #include "../gui/CGuiHandler.h"
 #include "../gui/CCursorHandler.h"
 
-#include "../battle/CBattleInterface.h"
-#include "../battle/CBattleInterfaceClasses.h"
+#include "../battle/BattleInterface.h"
+#include "../battle/BattleInterfaceClasses.h"
 
 #include "../../CCallback.h"
 
@@ -78,7 +77,7 @@ CSelWindow::CSelWindow(const std::string &Text, PlayerColor player, int charperl
 		buttons[i]->addCallback(std::bind(&CInfoWindow::close, this)); //each button will close the window apart from call-defined actions
 	}
 
-	text = std::make_shared<CTextBox>(Text, Rect(0, 0, 250, 100), 0, FONT_MEDIUM, CENTER, Colors::WHITE);
+	text = std::make_shared<CTextBox>(Text, Rect(0, 0, 250, 100), 0, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE);
 
 	buttons.front()->assignedKeys.insert(SDLK_RETURN); //first button - reacts on enter
 	buttons.back()->assignedKeys.insert(SDLK_ESCAPE); //last button - reacts on escape
@@ -132,7 +131,7 @@ CInfoWindow::CInfoWindow(std::string Text, PlayerColor player, const TCompsInfo
 		buttons.push_back(button);
 	}
 
-	text = std::make_shared<CTextBox>(Text, Rect(0, 0, 250, 100), 0, FONT_MEDIUM, CENTER, Colors::WHITE);
+	text = std::make_shared<CTextBox>(Text, Rect(0, 0, 250, 100), 0, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE);
 	if(!text->slider)
 	{
 		text->resize(text->label->textSize);
@@ -219,18 +218,18 @@ CInfoPopup::CInfoPopup(SDL_Surface * Bitmap, int x, int y, bool Free)
 }
 
 
-CInfoPopup::CInfoPopup(SDL_Surface * Bitmap, const Point &p, EAlignment alignment, bool Free)
+CInfoPopup::CInfoPopup(SDL_Surface * Bitmap, const Point &p, ETextAlignment alignment, bool Free)
  : free(Free),bitmap(Bitmap)
 {
 	switch(alignment)
 	{
-	case BOTTOMRIGHT:
+	case ETextAlignment::BOTTOMRIGHT:
 		init(p.x - Bitmap->w, p.y - Bitmap->h);
 		break;
-	case CENTER:
+	case ETextAlignment::CENTER:
 		init(p.x - Bitmap->w/2, p.y - Bitmap->h/2);
 		break;
-	case TOPLEFT:
+	case ETextAlignment::TOPLEFT:
 		init(p.x, p.y);
 		break;
 	default:
@@ -325,7 +324,7 @@ void CRClickPopup::createAndPush(const std::string & txt, std::shared_ptr<CCompo
 	createAndPush(txt, intComps);
 }
 
-void CRClickPopup::createAndPush(const CGObjectInstance * obj, const Point & p, EAlignment alignment)
+void CRClickPopup::createAndPush(const CGObjectInstance * obj, const Point & p, ETextAlignment alignment)
 {
 	auto iWin = createInfoWin(p, obj); //try get custom infowindow for this obj
 	if(iWin)

+ 2 - 2
client/windows/InfoWindows.h

@@ -83,7 +83,7 @@ public:
 	static std::shared_ptr<WindowBase> createInfoWin(Point position, const CGObjectInstance * specific);
 	static void createAndPush(const std::string & txt, const CInfoWindow::TCompsInfo &comps = CInfoWindow::TCompsInfo());
 	static void createAndPush(const std::string & txt, std::shared_ptr<CComponent> component);
-	static void createAndPush(const CGObjectInstance * obj, const Point & p, EAlignment alignment = BOTTOMRIGHT);
+	static void createAndPush(const CGObjectInstance * obj, const Point & p, ETextAlignment alignment = ETextAlignment::BOTTOMRIGHT);
 };
 
 /// popup displayed on R-click
@@ -103,7 +103,7 @@ public:
 	void close() override;
 	void show(SDL_Surface * to) override;
 	CInfoPopup(SDL_Surface * Bitmap, int x, int y, bool Free=false);
-	CInfoPopup(SDL_Surface * Bitmap, const Point &p, EAlignment alignment, bool Free=false);
+	CInfoPopup(SDL_Surface * Bitmap, const Point &p, ETextAlignment alignment, bool Free=false);
 	CInfoPopup(SDL_Surface * Bitmap = nullptr, bool Free = false);
 
 	void init(int x, int y);

+ 1 - 1
config/factions/necropolis.json

@@ -224,7 +224,7 @@
 				},
 				"moat" :
 				{
-					"bank" : { "x" : -1, "y" : -1 },
+					"bank" : { "x" : -1, "y" : -1 }, // Should not be present
 					"moat" : { "x" : 406, "y" : 77 }
 				},
 				"static" :

+ 1 - 1
config/spells/ability.json

@@ -168,7 +168,7 @@
 		"targetType": "NO_TARGET",
 
 		"animation":{
-			//missing
+			"affect":["SP10_"]
 		},
 		"sounds": {
 			"cast": "PARALYZE"

+ 2 - 2
config/spells/other.json

@@ -4,7 +4,7 @@
 		"targetType" : "NO_TARGET",
 
 		"sounds": {
-			"cast": "QUIKSAND"
+			"cast": "" // no casting sound, only obstacle placement sound
 		},
 		"levels" : {
 			"base":{
@@ -55,7 +55,7 @@
 		"targetType" : "NO_TARGET",
 
 		"sounds": {
-			"cast": ""
+			"cast": "" // no casting sound, only obstacle placement sound
 		},
 		"levels" : {
 			"base":{

+ 9 - 0
lib/battle/BattleHex.h

@@ -34,6 +34,15 @@ typedef boost::optional<ui8> BattleSideOpt;
 // for battle stacks' positions
 struct DLL_LINKAGE BattleHex //TODO: decide if this should be changed to class for better code design
 {
+	// helpers for siege
+	static const si16 CASTLE_CENTRAL_TOWER = -2;
+	static const si16 CASTLE_BOTTOM_TOWER = -3;
+	static const si16 CASTLE_UPPER_TOWER = -4;
+
+	// helpers for rendering
+	static const si16 HEX_BEFORE_ALL = std::numeric_limits<si16>::min();
+	static const si16 HEX_AFTER_ALL = std::numeric_limits<si16>::max();
+
 	si16 hex;
 	static const si16 INVALID = -1;
 	enum EDir

+ 3 - 3
lib/battle/BattleInfo.cpp

@@ -436,14 +436,14 @@ BattleInfo * BattleInfo::setupBattle(const int3 & tile, TerrainId terrain, const
 	if (curB->town && curB->town->fortLevel() >= CGTownInstance::CITADEL)
 	{
 		// keep tower
-		curB->generateNewStack(curB->nextUnitId(), CStackBasicDescriptor(CreatureID::ARROW_TOWERS, 1), 1, SlotID::ARROW_TOWERS_SLOT, -2);
+		curB->generateNewStack(curB->nextUnitId(), CStackBasicDescriptor(CreatureID::ARROW_TOWERS, 1), 1, SlotID::ARROW_TOWERS_SLOT, BattleHex::CASTLE_CENTRAL_TOWER);
 
 		if (curB->town->fortLevel() >= CGTownInstance::CASTLE)
 		{
 			// lower tower + upper tower
-			curB->generateNewStack(curB->nextUnitId(), CStackBasicDescriptor(CreatureID::ARROW_TOWERS, 1), 1, SlotID::ARROW_TOWERS_SLOT, -4);
+			curB->generateNewStack(curB->nextUnitId(), CStackBasicDescriptor(CreatureID::ARROW_TOWERS, 1), 1, SlotID::ARROW_TOWERS_SLOT, BattleHex::CASTLE_UPPER_TOWER);
 
-			curB->generateNewStack(curB->nextUnitId(), CStackBasicDescriptor(CreatureID::ARROW_TOWERS, 1), 1, SlotID::ARROW_TOWERS_SLOT, -3);
+			curB->generateNewStack(curB->nextUnitId(), CStackBasicDescriptor(CreatureID::ARROW_TOWERS, 1), 1, SlotID::ARROW_TOWERS_SLOT, BattleHex::CASTLE_BOTTOM_TOWER);
 		}
 
 		//moat

+ 2 - 0
lib/battle/CObstacleInstance.cpp

@@ -34,6 +34,8 @@ CObstacleInstance::~CObstacleInstance()
 
 const ObstacleInfo & CObstacleInstance::getInfo() const
 {
+	assert( obstacleType == USUAL || obstacleType == ABSOLUTE_OBSTACLE);
+
 	return *Obstacle(ID).getInfo();
 }
 

+ 6 - 6
lib/battle/CObstacleInstance.h

@@ -18,17 +18,17 @@ class JsonSerializeFormat;
 
 struct DLL_LINKAGE CObstacleInstance
 {
-	BattleHex pos; //position on battlefield, typically left bottom corner
-	ui8 obstacleType; //if true, then position is meaningless
-	si32 uniqueID;
-	si32 ID; //ID of obstacle (defines type of it)
-
-	enum EObstacleType
+	enum EObstacleType : ui8
 	{
 		//ABSOLUTE needs an underscore because it's a Win
 		USUAL, ABSOLUTE_OBSTACLE, SPELL_CREATED, MOAT
 	};
 
+	BattleHex pos; //position on battlefield, typically left bottom corner
+	EObstacleType obstacleType;
+	si32 uniqueID;
+	si32 ID; //ID of obstacle (defines type of it)
+
 	CObstacleInstance();
 	virtual ~CObstacleInstance();
 

+ 1 - 1
lib/spells/CSpellHandler.cpp

@@ -547,7 +547,7 @@ std::string CSpell::AnimationInfo::selectProjectile(const double angle) const
 
 	for(const auto & info : projectile)
 	{
-		if(info.minimumAngle < angle && info.minimumAngle > maximum)
+		if(info.minimumAngle < angle && info.minimumAngle >= maximum)
 		{
 			maximum = info.minimumAngle;
 			res = info.resourceName;

+ 5 - 1
lib/spells/effects/RemoveObstacle.cpp

@@ -43,7 +43,11 @@ RemoveObstacle::~RemoveObstacle() = default;
 
 bool RemoveObstacle::applicable(Problem & problem, const Mechanics * m) const
 {
-	return !getTargets(m, EffectTarget(), true).empty();
+	if (getTargets(m, EffectTarget(), true).empty())
+	{
+		return m->adaptProblem(ESpellCastProblem::NO_APPROPRIATE_TARGET, problem);
+	}
+	return true;
 }
 
 bool RemoveObstacle::applicable(Problem & problem, const Mechanics * m, const EffectTarget & target) const